c_cpp.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. """
  2. pygments.lexers.c_cpp
  3. ~~~~~~~~~~~~~~~~~~~~~
  4. Lexers for C/C++ languages.
  5. :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
  6. :license: BSD, see LICENSE for details.
  7. """
  8. import re
  9. from pygments.lexer import RegexLexer, include, bygroups, using, \
  10. this, inherit, default, words
  11. from pygments.util import get_bool_opt
  12. from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
  13. Number, Punctuation, Whitespace
  14. __all__ = ['CLexer', 'CppLexer']
  15. class CFamilyLexer(RegexLexer):
  16. """
  17. For C family source code. This is used as a base class to avoid repetitious
  18. definitions.
  19. """
  20. # The trailing ?, rather than *, avoids a geometric performance drop here.
  21. #: only one /* */ style comment
  22. _ws1 = r'\s*(?:/[*].*?[*]/\s*)?'
  23. # Hexadecimal part in an hexadecimal integer/floating-point literal.
  24. # This includes decimal separators matching.
  25. _hexpart = r'[0-9a-fA-F](\'?[0-9a-fA-F])*'
  26. # Decimal part in an decimal integer/floating-point literal.
  27. # This includes decimal separators matching.
  28. _decpart = r'\d(\'?\d)*'
  29. # Integer literal suffix (e.g. 'ull' or 'll').
  30. _intsuffix = r'(([uU][lL]{0,2})|[lL]{1,2}[uU]?)?'
  31. # Identifier regex with C and C++ Universal Character Name (UCN) support.
  32. _ident = r'(?!\d)(?:[\w$]|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8})+'
  33. _namespaced_ident = r'(?!\d)(?:[\w$]|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|::)+'
  34. # Single and multiline comment regexes
  35. # Beware not to use *? for the inner content! When these regexes
  36. # are embedded in larger regexes, that can cause the stuff*? to
  37. # match more than it would have if the regex had been used in
  38. # a standalone way ...
  39. _comment_single = r'//(?:.|(?<=\\)\n)*\n'
  40. _comment_multiline = r'/(?:\\\n)?[*](?:[^*]|[*](?!(?:\\\n)?/))*[*](?:\\\n)?/'
  41. # Regex to match optional comments
  42. _possible_comments = rf'\s*(?:(?:(?:{_comment_single})|(?:{_comment_multiline}))\s*)*'
  43. tokens = {
  44. 'whitespace': [
  45. # preprocessor directives: without whitespace
  46. (r'^#if\s+0', Comment.Preproc, 'if0'),
  47. ('^#', Comment.Preproc, 'macro'),
  48. # or with whitespace
  49. ('^(' + _ws1 + r')(#if\s+0)',
  50. bygroups(using(this), Comment.Preproc), 'if0'),
  51. ('^(' + _ws1 + ')(#)',
  52. bygroups(using(this), Comment.Preproc), 'macro'),
  53. # Labels:
  54. # Line start and possible indentation.
  55. (r'(^[ \t]*)'
  56. # Not followed by keywords which can be mistaken as labels.
  57. r'(?!(?:public|private|protected|default)\b)'
  58. # Actual label, followed by a single colon.
  59. r'(' + _ident + r')(\s*)(:)(?!:)',
  60. bygroups(Whitespace, Name.Label, Whitespace, Punctuation)),
  61. (r'\n', Whitespace),
  62. (r'[^\S\n]+', Whitespace),
  63. (r'\\\n', Text), # line continuation
  64. (_comment_single, Comment.Single),
  65. (_comment_multiline, Comment.Multiline),
  66. # Open until EOF, so no ending delimiter
  67. (r'/(\\\n)?[*][\w\W]*', Comment.Multiline),
  68. ],
  69. 'statements': [
  70. include('keywords'),
  71. include('types'),
  72. (r'([LuU]|u8)?(")', bygroups(String.Affix, String), 'string'),
  73. (r"([LuU]|u8)?(')(\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\\'\n])(')",
  74. bygroups(String.Affix, String.Char, String.Char, String.Char)),
  75. # Hexadecimal floating-point literals (C11, C++17)
  76. (r'0[xX](' + _hexpart + r'\.' + _hexpart + r'|\.' + _hexpart +
  77. r'|' + _hexpart + r')[pP][+-]?' + _hexpart + r'[lL]?', Number.Float),
  78. (r'(-)?(' + _decpart + r'\.' + _decpart + r'|\.' + _decpart + r'|' +
  79. _decpart + r')[eE][+-]?' + _decpart + r'[fFlL]?', Number.Float),
  80. (r'(-)?((' + _decpart + r'\.(' + _decpart + r')?|\.' +
  81. _decpart + r')[fFlL]?)|(' + _decpart + r'[fFlL])', Number.Float),
  82. (r'(-)?0[xX]' + _hexpart + _intsuffix, Number.Hex),
  83. (r'(-)?0[bB][01](\'?[01])*' + _intsuffix, Number.Bin),
  84. (r'(-)?0(\'?[0-7])+' + _intsuffix, Number.Oct),
  85. (r'(-)?' + _decpart + _intsuffix, Number.Integer),
  86. (r'[~!%^&*+=|?:<>/-]', Operator),
  87. (r'[()\[\],.]', Punctuation),
  88. (r'(true|false|NULL)\b', Name.Builtin),
  89. (_ident, Name)
  90. ],
  91. 'types': [
  92. (words(('int8', 'int16', 'int32', 'int64', 'wchar_t'), prefix=r'__',
  93. suffix=r'\b'), Keyword.Reserved),
  94. (words(('bool', 'int', 'long', 'float', 'short', 'double', 'char',
  95. 'unsigned', 'signed', 'void', '_BitInt',
  96. '__int128'), suffix=r'\b'), Keyword.Type)
  97. ],
  98. 'keywords': [
  99. (r'(struct|union)(\s+)', bygroups(Keyword, Whitespace), 'classname'),
  100. (r'case\b', Keyword, 'case-value'),
  101. (words(('asm', 'auto', 'break', 'const', 'continue', 'default',
  102. 'do', 'else', 'enum', 'extern', 'for', 'goto', 'if',
  103. 'register', 'restricted', 'return', 'sizeof', 'struct',
  104. 'static', 'switch', 'typedef', 'volatile', 'while', 'union',
  105. 'thread_local', 'alignas', 'alignof', 'static_assert', '_Pragma'),
  106. suffix=r'\b'), Keyword),
  107. (words(('inline', '_inline', '__inline', 'naked', 'restrict',
  108. 'thread'), suffix=r'\b'), Keyword.Reserved),
  109. # Vector intrinsics
  110. (r'(__m(128i|128d|128|64))\b', Keyword.Reserved),
  111. # Microsoft-isms
  112. (words((
  113. 'asm', 'based', 'except', 'stdcall', 'cdecl',
  114. 'fastcall', 'declspec', 'finally', 'try',
  115. 'leave', 'w64', 'unaligned', 'raise', 'noop',
  116. 'identifier', 'forceinline', 'assume'),
  117. prefix=r'__', suffix=r'\b'), Keyword.Reserved)
  118. ],
  119. 'root': [
  120. include('whitespace'),
  121. include('keywords'),
  122. # functions
  123. (r'(' + _namespaced_ident + r'(?:[&*\s])+)' # return arguments
  124. r'(' + _possible_comments + r')'
  125. r'(' + _namespaced_ident + r')' # method name
  126. r'(' + _possible_comments + r')'
  127. r'(\([^;"\')]*?\))' # signature
  128. r'(' + _possible_comments + r')'
  129. r'([^;{/"\']*)(\{)',
  130. bygroups(using(this), using(this, state='whitespace'),
  131. Name.Function, using(this, state='whitespace'),
  132. using(this), using(this, state='whitespace'),
  133. using(this), Punctuation),
  134. 'function'),
  135. # function declarations
  136. (r'(' + _namespaced_ident + r'(?:[&*\s])+)' # return arguments
  137. r'(' + _possible_comments + r')'
  138. r'(' + _namespaced_ident + r')' # method name
  139. r'(' + _possible_comments + r')'
  140. r'(\([^;"\')]*?\))' # signature
  141. r'(' + _possible_comments + r')'
  142. r'([^;/"\']*)(;)',
  143. bygroups(using(this), using(this, state='whitespace'),
  144. Name.Function, using(this, state='whitespace'),
  145. using(this), using(this, state='whitespace'),
  146. using(this), Punctuation)),
  147. include('types'),
  148. default('statement'),
  149. ],
  150. 'statement': [
  151. include('whitespace'),
  152. include('statements'),
  153. (r'\}', Punctuation),
  154. (r'[{;]', Punctuation, '#pop'),
  155. ],
  156. 'function': [
  157. include('whitespace'),
  158. include('statements'),
  159. (';', Punctuation),
  160. (r'\{', Punctuation, '#push'),
  161. (r'\}', Punctuation, '#pop'),
  162. ],
  163. 'string': [
  164. (r'"', String, '#pop'),
  165. (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|'
  166. r'u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8}|[0-7]{1,3})', String.Escape),
  167. (r'[^\\"\n]+', String), # all other characters
  168. (r'\\\n', String), # line continuation
  169. (r'\\', String), # stray backslash
  170. ],
  171. 'macro': [
  172. (r'('+_ws1+r')(include)('+_ws1+r')("[^"]+")([^\n]*)',
  173. bygroups(using(this), Comment.Preproc, using(this),
  174. Comment.PreprocFile, Comment.Single)),
  175. (r'('+_ws1+r')(include)('+_ws1+r')(<[^>]+>)([^\n]*)',
  176. bygroups(using(this), Comment.Preproc, using(this),
  177. Comment.PreprocFile, Comment.Single)),
  178. (r'[^/\n]+', Comment.Preproc),
  179. (r'/[*](.|\n)*?[*]/', Comment.Multiline),
  180. (r'//.*?\n', Comment.Single, '#pop'),
  181. (r'/', Comment.Preproc),
  182. (r'(?<=\\)\n', Comment.Preproc),
  183. (r'\n', Comment.Preproc, '#pop'),
  184. ],
  185. 'if0': [
  186. (r'^\s*#if.*?(?<!\\)\n', Comment.Preproc, '#push'),
  187. (r'^\s*#el(?:se|if).*\n', Comment.Preproc, '#pop'),
  188. (r'^\s*#endif.*?(?<!\\)\n', Comment.Preproc, '#pop'),
  189. (r'.*?\n', Comment),
  190. ],
  191. 'classname': [
  192. (_ident, Name.Class, '#pop'),
  193. # template specification
  194. (r'\s*(?=>)', Text, '#pop'),
  195. default('#pop')
  196. ],
  197. # Mark identifiers preceded by `case` keyword as constants.
  198. 'case-value': [
  199. (r'(?<!:)(:)(?!:)', Punctuation, '#pop'),
  200. (_ident, Name.Constant),
  201. include('whitespace'),
  202. include('statements'),
  203. ]
  204. }
  205. stdlib_types = {
  206. 'size_t', 'ssize_t', 'off_t', 'wchar_t', 'ptrdiff_t', 'sig_atomic_t', 'fpos_t',
  207. 'clock_t', 'time_t', 'va_list', 'jmp_buf', 'FILE', 'DIR', 'div_t', 'ldiv_t',
  208. 'mbstate_t', 'wctrans_t', 'wint_t', 'wctype_t'}
  209. c99_types = {
  210. 'int8_t', 'int16_t', 'int32_t', 'int64_t', 'uint8_t',
  211. 'uint16_t', 'uint32_t', 'uint64_t', 'int_least8_t', 'int_least16_t',
  212. 'int_least32_t', 'int_least64_t', 'uint_least8_t', 'uint_least16_t',
  213. 'uint_least32_t', 'uint_least64_t', 'int_fast8_t', 'int_fast16_t', 'int_fast32_t',
  214. 'int_fast64_t', 'uint_fast8_t', 'uint_fast16_t', 'uint_fast32_t', 'uint_fast64_t',
  215. 'intptr_t', 'uintptr_t', 'intmax_t', 'uintmax_t'}
  216. linux_types = {
  217. 'clockid_t', 'cpu_set_t', 'cpumask_t', 'dev_t', 'gid_t', 'id_t', 'ino_t', 'key_t',
  218. 'mode_t', 'nfds_t', 'pid_t', 'rlim_t', 'sig_t', 'sighandler_t', 'siginfo_t',
  219. 'sigset_t', 'sigval_t', 'socklen_t', 'timer_t', 'uid_t'}
  220. c11_atomic_types = {
  221. 'atomic_bool', 'atomic_char', 'atomic_schar', 'atomic_uchar', 'atomic_short',
  222. 'atomic_ushort', 'atomic_int', 'atomic_uint', 'atomic_long', 'atomic_ulong',
  223. 'atomic_llong', 'atomic_ullong', 'atomic_char16_t', 'atomic_char32_t', 'atomic_wchar_t',
  224. 'atomic_int_least8_t', 'atomic_uint_least8_t', 'atomic_int_least16_t',
  225. 'atomic_uint_least16_t', 'atomic_int_least32_t', 'atomic_uint_least32_t',
  226. 'atomic_int_least64_t', 'atomic_uint_least64_t', 'atomic_int_fast8_t',
  227. 'atomic_uint_fast8_t', 'atomic_int_fast16_t', 'atomic_uint_fast16_t',
  228. 'atomic_int_fast32_t', 'atomic_uint_fast32_t', 'atomic_int_fast64_t',
  229. 'atomic_uint_fast64_t', 'atomic_intptr_t', 'atomic_uintptr_t', 'atomic_size_t',
  230. 'atomic_ptrdiff_t', 'atomic_intmax_t', 'atomic_uintmax_t'}
  231. def __init__(self, **options):
  232. self.stdlibhighlighting = get_bool_opt(options, 'stdlibhighlighting', True)
  233. self.c99highlighting = get_bool_opt(options, 'c99highlighting', True)
  234. self.c11highlighting = get_bool_opt(options, 'c11highlighting', True)
  235. self.platformhighlighting = get_bool_opt(options, 'platformhighlighting', True)
  236. RegexLexer.__init__(self, **options)
  237. def get_tokens_unprocessed(self, text, stack=('root',)):
  238. for index, token, value in \
  239. RegexLexer.get_tokens_unprocessed(self, text, stack):
  240. if token is Name:
  241. if self.stdlibhighlighting and value in self.stdlib_types:
  242. token = Keyword.Type
  243. elif self.c99highlighting and value in self.c99_types:
  244. token = Keyword.Type
  245. elif self.c11highlighting and value in self.c11_atomic_types:
  246. token = Keyword.Type
  247. elif self.platformhighlighting and value in self.linux_types:
  248. token = Keyword.Type
  249. yield index, token, value
  250. class CLexer(CFamilyLexer):
  251. """
  252. For C source code with preprocessor directives.
  253. Additional options accepted:
  254. `stdlibhighlighting`
  255. Highlight common types found in the C/C++ standard library (e.g. `size_t`).
  256. (default: ``True``).
  257. `c99highlighting`
  258. Highlight common types found in the C99 standard library (e.g. `int8_t`).
  259. Actually, this includes all fixed-width integer types.
  260. (default: ``True``).
  261. `c11highlighting`
  262. Highlight atomic types found in the C11 standard library (e.g. `atomic_bool`).
  263. (default: ``True``).
  264. `platformhighlighting`
  265. Highlight common types found in the platform SDK headers (e.g. `clockid_t` on Linux).
  266. (default: ``True``).
  267. """
  268. name = 'C'
  269. aliases = ['c']
  270. filenames = ['*.c', '*.h', '*.idc', '*.x[bp]m']
  271. mimetypes = ['text/x-chdr', 'text/x-csrc', 'image/x-xbitmap', 'image/x-xpixmap']
  272. url = 'https://en.wikipedia.org/wiki/C_(programming_language)'
  273. version_added = ''
  274. priority = 0.1
  275. tokens = {
  276. 'keywords': [
  277. (words((
  278. '_Alignas', '_Alignof', '_Noreturn', '_Generic', '_Thread_local',
  279. '_Static_assert', '_Imaginary', 'noreturn', 'imaginary', 'complex'),
  280. suffix=r'\b'), Keyword),
  281. inherit
  282. ],
  283. 'types': [
  284. (words(('_Bool', '_Complex', '_Atomic'), suffix=r'\b'), Keyword.Type),
  285. inherit
  286. ]
  287. }
  288. def analyse_text(text):
  289. if re.search(r'^\s*#include [<"]', text, re.MULTILINE):
  290. return 0.1
  291. if re.search(r'^\s*#ifn?def ', text, re.MULTILINE):
  292. return 0.1
  293. class CppLexer(CFamilyLexer):
  294. """
  295. For C++ source code with preprocessor directives.
  296. Additional options accepted:
  297. `stdlibhighlighting`
  298. Highlight common types found in the C/C++ standard library (e.g. `size_t`).
  299. (default: ``True``).
  300. `c99highlighting`
  301. Highlight common types found in the C99 standard library (e.g. `int8_t`).
  302. Actually, this includes all fixed-width integer types.
  303. (default: ``True``).
  304. `c11highlighting`
  305. Highlight atomic types found in the C11 standard library (e.g. `atomic_bool`).
  306. (default: ``True``).
  307. `platformhighlighting`
  308. Highlight common types found in the platform SDK headers (e.g. `clockid_t` on Linux).
  309. (default: ``True``).
  310. """
  311. name = 'C++'
  312. url = 'https://isocpp.org/'
  313. aliases = ['cpp', 'c++']
  314. filenames = ['*.cpp', '*.hpp', '*.c++', '*.h++',
  315. '*.cc', '*.hh', '*.cxx', '*.hxx',
  316. '*.C', '*.H', '*.cp', '*.CPP', '*.tpp']
  317. mimetypes = ['text/x-c++hdr', 'text/x-c++src']
  318. version_added = ''
  319. priority = 0.1
  320. tokens = {
  321. 'statements': [
  322. # C++11 raw strings
  323. (r'((?:[LuU]|u8)?R)(")([^\\()\s]{,16})(\()((?:.|\n)*?)(\)\3)(")',
  324. bygroups(String.Affix, String, String.Delimiter, String.Delimiter,
  325. String, String.Delimiter, String)),
  326. inherit,
  327. ],
  328. 'root': [
  329. inherit,
  330. # C++ Microsoft-isms
  331. (words(('virtual_inheritance', 'uuidof', 'super', 'single_inheritance',
  332. 'multiple_inheritance', 'interface', 'event'),
  333. prefix=r'__', suffix=r'\b'), Keyword.Reserved),
  334. # Offload C++ extensions, http://offload.codeplay.com/
  335. (r'__(offload|blockingoffload|outer)\b', Keyword.Pseudo),
  336. ],
  337. 'enumname': [
  338. include('whitespace'),
  339. # 'enum class' and 'enum struct' C++11 support
  340. (words(('class', 'struct'), suffix=r'\b'), Keyword),
  341. (CFamilyLexer._ident, Name.Class, '#pop'),
  342. # template specification
  343. (r'\s*(?=>)', Text, '#pop'),
  344. default('#pop')
  345. ],
  346. 'keywords': [
  347. (r'(class|concept|typename)(\s+)', bygroups(Keyword, Whitespace), 'classname'),
  348. (words((
  349. 'catch', 'const_cast', 'delete', 'dynamic_cast', 'explicit',
  350. 'export', 'friend', 'mutable', 'new', 'operator',
  351. 'private', 'protected', 'public', 'reinterpret_cast', 'class',
  352. '__restrict', 'static_cast', 'template', 'this', 'throw', 'throws',
  353. 'try', 'typeid', 'using', 'virtual', 'constexpr', 'nullptr', 'concept',
  354. 'decltype', 'noexcept', 'override', 'final', 'constinit', 'consteval',
  355. 'co_await', 'co_return', 'co_yield', 'requires', 'import', 'module',
  356. 'typename', 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
  357. 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'),
  358. suffix=r'\b'), Keyword),
  359. (r'namespace\b', Keyword, 'namespace'),
  360. (r'(enum)(\s+)', bygroups(Keyword, Whitespace), 'enumname'),
  361. inherit
  362. ],
  363. 'types': [
  364. (r'char(16_t|32_t|8_t)\b', Keyword.Type),
  365. inherit
  366. ],
  367. 'namespace': [
  368. (r'[;{]', Punctuation, ('#pop', 'root')),
  369. (r'inline\b', Keyword.Reserved),
  370. (CFamilyLexer._ident, Name.Namespace),
  371. include('statement')
  372. ]
  373. }
  374. def analyse_text(text):
  375. if re.search('#include <[a-z_]+>', text):
  376. return 0.2
  377. if re.search('using namespace ', text):
  378. return 0.4