c_cpp.py 16 KB

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