c_cpp.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. """
  2. pygments.lexers.c_cpp
  3. ~~~~~~~~~~~~~~~~~~~~~
  4. Lexers for C/C++ languages.
  5. :copyright: Copyright 2006-2023 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'), suffix=r'\b'), Keyword.Type)
  96. ],
  97. 'keywords': [
  98. (r'(struct|union)(\s+)', bygroups(Keyword, Whitespace), 'classname'),
  99. (r'case\b', Keyword, 'case-value'),
  100. (words(('asm', 'auto', 'break', 'const', 'continue', 'default',
  101. 'do', 'else', 'enum', 'extern', 'for', 'goto', 'if',
  102. 'register', 'restricted', 'return', 'sizeof', 'struct',
  103. 'static', 'switch', 'typedef', 'volatile', 'while', 'union',
  104. 'thread_local', 'alignas', 'alignof', 'static_assert', '_Pragma'),
  105. suffix=r'\b'), Keyword),
  106. (words(('inline', '_inline', '__inline', 'naked', 'restrict',
  107. 'thread'), suffix=r'\b'), Keyword.Reserved),
  108. # Vector intrinsics
  109. (r'(__m(128i|128d|128|64))\b', Keyword.Reserved),
  110. # Microsoft-isms
  111. (words((
  112. 'asm', 'based', 'except', 'stdcall', 'cdecl',
  113. 'fastcall', 'declspec', 'finally', 'try',
  114. 'leave', 'w64', 'unaligned', 'raise', 'noop',
  115. 'identifier', 'forceinline', 'assume'),
  116. prefix=r'__', suffix=r'\b'), Keyword.Reserved)
  117. ],
  118. 'root': [
  119. include('whitespace'),
  120. include('keywords'),
  121. # functions
  122. (r'(' + _namespaced_ident + r'(?:[&*\s])+)' # return arguments
  123. r'(' + _possible_comments + r')'
  124. r'(' + _namespaced_ident + r')' # method name
  125. r'(' + _possible_comments + r')'
  126. r'(\([^;"\')]*?\))' # signature
  127. r'(' + _possible_comments + r')'
  128. r'([^;{/"\']*)(\{)',
  129. bygroups(using(this), using(this, state='whitespace'),
  130. Name.Function, using(this, state='whitespace'),
  131. using(this), using(this, state='whitespace'),
  132. using(this), Punctuation),
  133. 'function'),
  134. # function declarations
  135. (r'(' + _namespaced_ident + r'(?:[&*\s])+)' # return arguments
  136. r'(' + _possible_comments + r')'
  137. r'(' + _namespaced_ident + r')' # method name
  138. r'(' + _possible_comments + r')'
  139. r'(\([^;"\')]*?\))' # signature
  140. r'(' + _possible_comments + r')'
  141. r'([^;/"\']*)(;)',
  142. bygroups(using(this), using(this, state='whitespace'),
  143. Name.Function, using(this, state='whitespace'),
  144. using(this), using(this, state='whitespace'),
  145. using(this), Punctuation)),
  146. include('types'),
  147. default('statement'),
  148. ],
  149. 'statement': [
  150. include('whitespace'),
  151. include('statements'),
  152. (r'\}', Punctuation),
  153. (r'[{;]', Punctuation, '#pop'),
  154. ],
  155. 'function': [
  156. include('whitespace'),
  157. include('statements'),
  158. (';', Punctuation),
  159. (r'\{', Punctuation, '#push'),
  160. (r'\}', Punctuation, '#pop'),
  161. ],
  162. 'string': [
  163. (r'"', String, '#pop'),
  164. (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|'
  165. r'u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8}|[0-7]{1,3})', String.Escape),
  166. (r'[^\\"\n]+', String), # all other characters
  167. (r'\\\n', String), # line continuation
  168. (r'\\', String), # stray backslash
  169. ],
  170. 'macro': [
  171. (r'('+_ws1+r')(include)('+_ws1+r')("[^"]+")([^\n]*)',
  172. bygroups(using(this), Comment.Preproc, using(this),
  173. Comment.PreprocFile, Comment.Single)),
  174. (r'('+_ws1+r')(include)('+_ws1+r')(<[^>]+>)([^\n]*)',
  175. bygroups(using(this), Comment.Preproc, using(this),
  176. Comment.PreprocFile, Comment.Single)),
  177. (r'[^/\n]+', Comment.Preproc),
  178. (r'/[*](.|\n)*?[*]/', Comment.Multiline),
  179. (r'//.*?\n', Comment.Single, '#pop'),
  180. (r'/', Comment.Preproc),
  181. (r'(?<=\\)\n', Comment.Preproc),
  182. (r'\n', Comment.Preproc, '#pop'),
  183. ],
  184. 'if0': [
  185. (r'^\s*#if.*?(?<!\\)\n', Comment.Preproc, '#push'),
  186. (r'^\s*#el(?:se|if).*\n', Comment.Preproc, '#pop'),
  187. (r'^\s*#endif.*?(?<!\\)\n', Comment.Preproc, '#pop'),
  188. (r'.*?\n', Comment),
  189. ],
  190. 'classname': [
  191. (_ident, Name.Class, '#pop'),
  192. # template specification
  193. (r'\s*(?=>)', Text, '#pop'),
  194. default('#pop')
  195. ],
  196. # Mark identifiers preceded by `case` keyword as constants.
  197. 'case-value': [
  198. (r'(?<!:)(:)(?!:)', Punctuation, '#pop'),
  199. (_ident, Name.Constant),
  200. include('whitespace'),
  201. include('statements'),
  202. ]
  203. }
  204. stdlib_types = {
  205. 'size_t', 'ssize_t', 'off_t', 'wchar_t', 'ptrdiff_t', 'sig_atomic_t', 'fpos_t',
  206. 'clock_t', 'time_t', 'va_list', 'jmp_buf', 'FILE', 'DIR', 'div_t', 'ldiv_t',
  207. 'mbstate_t', 'wctrans_t', 'wint_t', 'wctype_t'}
  208. c99_types = {
  209. 'int8_t', 'int16_t', 'int32_t', 'int64_t', 'uint8_t',
  210. 'uint16_t', 'uint32_t', 'uint64_t', 'int_least8_t', 'int_least16_t',
  211. 'int_least32_t', 'int_least64_t', 'uint_least8_t', 'uint_least16_t',
  212. 'uint_least32_t', 'uint_least64_t', 'int_fast8_t', 'int_fast16_t', 'int_fast32_t',
  213. 'int_fast64_t', 'uint_fast8_t', 'uint_fast16_t', 'uint_fast32_t', 'uint_fast64_t',
  214. 'intptr_t', 'uintptr_t', 'intmax_t', 'uintmax_t'}
  215. linux_types = {
  216. 'clockid_t', 'cpu_set_t', 'cpumask_t', 'dev_t', 'gid_t', 'id_t', 'ino_t', 'key_t',
  217. 'mode_t', 'nfds_t', 'pid_t', 'rlim_t', 'sig_t', 'sighandler_t', 'siginfo_t',
  218. 'sigset_t', 'sigval_t', 'socklen_t', 'timer_t', 'uid_t'}
  219. c11_atomic_types = {
  220. 'atomic_bool', 'atomic_char', 'atomic_schar', 'atomic_uchar', 'atomic_short',
  221. 'atomic_ushort', 'atomic_int', 'atomic_uint', 'atomic_long', 'atomic_ulong',
  222. 'atomic_llong', 'atomic_ullong', 'atomic_char16_t', 'atomic_char32_t', 'atomic_wchar_t',
  223. 'atomic_int_least8_t', 'atomic_uint_least8_t', 'atomic_int_least16_t',
  224. 'atomic_uint_least16_t', 'atomic_int_least32_t', 'atomic_uint_least32_t',
  225. 'atomic_int_least64_t', 'atomic_uint_least64_t', 'atomic_int_fast8_t',
  226. 'atomic_uint_fast8_t', 'atomic_int_fast16_t', 'atomic_uint_fast16_t',
  227. 'atomic_int_fast32_t', 'atomic_uint_fast32_t', 'atomic_int_fast64_t',
  228. 'atomic_uint_fast64_t', 'atomic_intptr_t', 'atomic_uintptr_t', 'atomic_size_t',
  229. 'atomic_ptrdiff_t', 'atomic_intmax_t', 'atomic_uintmax_t'}
  230. def __init__(self, **options):
  231. self.stdlibhighlighting = get_bool_opt(options, 'stdlibhighlighting', True)
  232. self.c99highlighting = get_bool_opt(options, 'c99highlighting', True)
  233. self.c11highlighting = get_bool_opt(options, 'c11highlighting', True)
  234. self.platformhighlighting = get_bool_opt(options, 'platformhighlighting', True)
  235. RegexLexer.__init__(self, **options)
  236. def get_tokens_unprocessed(self, text, stack=('root',)):
  237. for index, token, value in \
  238. RegexLexer.get_tokens_unprocessed(self, text, stack):
  239. if token is Name:
  240. if self.stdlibhighlighting and value in self.stdlib_types:
  241. token = Keyword.Type
  242. elif self.c99highlighting and value in self.c99_types:
  243. token = Keyword.Type
  244. elif self.c11highlighting and value in self.c11_atomic_types:
  245. token = Keyword.Type
  246. elif self.platformhighlighting and value in self.linux_types:
  247. token = Keyword.Type
  248. yield index, token, value
  249. class CLexer(CFamilyLexer):
  250. """
  251. For C source code with preprocessor directives.
  252. Additional options accepted:
  253. `stdlibhighlighting`
  254. Highlight common types found in the C/C++ standard library (e.g. `size_t`).
  255. (default: ``True``).
  256. `c99highlighting`
  257. Highlight common types found in the C99 standard library (e.g. `int8_t`).
  258. Actually, this includes all fixed-width integer types.
  259. (default: ``True``).
  260. `c11highlighting`
  261. Highlight atomic types found in the C11 standard library (e.g. `atomic_bool`).
  262. (default: ``True``).
  263. `platformhighlighting`
  264. Highlight common types found in the platform SDK headers (e.g. `clockid_t` on Linux).
  265. (default: ``True``).
  266. """
  267. name = 'C'
  268. aliases = ['c']
  269. filenames = ['*.c', '*.h', '*.idc', '*.x[bp]m']
  270. mimetypes = ['text/x-chdr', 'text/x-csrc', 'image/x-xbitmap', 'image/x-xpixmap']
  271. priority = 0.1
  272. tokens = {
  273. 'keywords': [
  274. (words((
  275. '_Alignas', '_Alignof', '_Noreturn', '_Generic', '_Thread_local',
  276. '_Static_assert', '_Imaginary', 'noreturn', 'imaginary', 'complex'),
  277. suffix=r'\b'), Keyword),
  278. inherit
  279. ],
  280. 'types': [
  281. (words(('_Bool', '_Complex', '_Atomic'), suffix=r'\b'), Keyword.Type),
  282. inherit
  283. ]
  284. }
  285. def analyse_text(text):
  286. if re.search(r'^\s*#include [<"]', text, re.MULTILINE):
  287. return 0.1
  288. if re.search(r'^\s*#ifn?def ', text, re.MULTILINE):
  289. return 0.1
  290. class CppLexer(CFamilyLexer):
  291. """
  292. For C++ source code with preprocessor directives.
  293. Additional options accepted:
  294. `stdlibhighlighting`
  295. Highlight common types found in the C/C++ standard library (e.g. `size_t`).
  296. (default: ``True``).
  297. `c99highlighting`
  298. Highlight common types found in the C99 standard library (e.g. `int8_t`).
  299. Actually, this includes all fixed-width integer types.
  300. (default: ``True``).
  301. `c11highlighting`
  302. Highlight atomic types found in the C11 standard library (e.g. `atomic_bool`).
  303. (default: ``True``).
  304. `platformhighlighting`
  305. Highlight common types found in the platform SDK headers (e.g. `clockid_t` on Linux).
  306. (default: ``True``).
  307. """
  308. name = 'C++'
  309. url = 'https://isocpp.org/'
  310. aliases = ['cpp', 'c++']
  311. filenames = ['*.cpp', '*.hpp', '*.c++', '*.h++',
  312. '*.cc', '*.hh', '*.cxx', '*.hxx',
  313. '*.C', '*.H', '*.cp', '*.CPP', '*.tpp']
  314. mimetypes = ['text/x-c++hdr', 'text/x-c++src']
  315. priority = 0.1
  316. tokens = {
  317. 'statements': [
  318. # C++11 raw strings
  319. (r'((?:[LuU]|u8)?R)(")([^\\()\s]{,16})(\()((?:.|\n)*?)(\)\3)(")',
  320. bygroups(String.Affix, String, String.Delimiter, String.Delimiter,
  321. String, String.Delimiter, String)),
  322. inherit,
  323. ],
  324. 'root': [
  325. inherit,
  326. # C++ Microsoft-isms
  327. (words(('virtual_inheritance', 'uuidof', 'super', 'single_inheritance',
  328. 'multiple_inheritance', 'interface', 'event'),
  329. prefix=r'__', suffix=r'\b'), Keyword.Reserved),
  330. # Offload C++ extensions, http://offload.codeplay.com/
  331. (r'__(offload|blockingoffload|outer)\b', Keyword.Pseudo),
  332. ],
  333. 'enumname': [
  334. include('whitespace'),
  335. # 'enum class' and 'enum struct' C++11 support
  336. (words(('class', 'struct'), suffix=r'\b'), Keyword),
  337. (CFamilyLexer._ident, Name.Class, '#pop'),
  338. # template specification
  339. (r'\s*(?=>)', Text, '#pop'),
  340. default('#pop')
  341. ],
  342. 'keywords': [
  343. (r'(class|concept|typename)(\s+)', bygroups(Keyword, Whitespace), 'classname'),
  344. (words((
  345. 'catch', 'const_cast', 'delete', 'dynamic_cast', 'explicit',
  346. 'export', 'friend', 'mutable', 'new', 'operator',
  347. 'private', 'protected', 'public', 'reinterpret_cast', 'class',
  348. 'restrict', 'static_cast', 'template', 'this', 'throw', 'throws',
  349. 'try', 'typeid', 'using', 'virtual', 'constexpr', 'nullptr', 'concept',
  350. 'decltype', 'noexcept', 'override', 'final', 'constinit', 'consteval',
  351. 'co_await', 'co_return', 'co_yield', 'requires', 'import', 'module',
  352. 'typename'),
  353. suffix=r'\b'), Keyword),
  354. (r'namespace\b', Keyword, 'namespace'),
  355. (r'(enum)(\s+)', bygroups(Keyword, Whitespace), 'enumname'),
  356. inherit
  357. ],
  358. 'types': [
  359. (r'char(16_t|32_t|8_t)\b', Keyword.Type),
  360. inherit
  361. ],
  362. 'namespace': [
  363. (r'[;{]', Punctuation, ('#pop', 'root')),
  364. (r'inline\b', Keyword.Reserved),
  365. (CFamilyLexer._ident, Name.Namespace),
  366. include('statement')
  367. ]
  368. }
  369. def analyse_text(text):
  370. if re.search('#include <[a-z_]+>', text):
  371. return 0.2
  372. if re.search('using namespace ', text):
  373. return 0.4