c_cpp.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. # -*- coding: utf-8 -*-
  2. """
  3. pygments.lexers.c_cpp
  4. ~~~~~~~~~~~~~~~~~~~~~
  5. Lexers for C/C++ languages.
  6. :copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.
  7. :license: BSD, see LICENSE for details.
  8. """
  9. import re
  10. from pygments.lexer import RegexLexer, include, bygroups, using, \
  11. this, inherit, default, words
  12. from pygments.util import get_bool_opt
  13. from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
  14. Number, Punctuation, Error
  15. __all__ = ['CLexer', 'CppLexer']
  16. class CFamilyLexer(RegexLexer):
  17. """
  18. For C family source code. This is used as a base class to avoid repetitious
  19. definitions.
  20. """
  21. #: optional Comment or Whitespace
  22. _ws = r'(?:\s|//.*?\n|/[*].*?[*]/)+'
  23. # The trailing ?, rather than *, avoids a geometric performance drop here.
  24. #: only one /* */ style comment
  25. _ws1 = r'\s*(?:/[*].*?[*]/\s*)?'
  26. tokens = {
  27. 'whitespace': [
  28. # preprocessor directives: without whitespace
  29. (r'^#if\s+0', Comment.Preproc, 'if0'),
  30. ('^#', Comment.Preproc, 'macro'),
  31. # or with whitespace
  32. ('^(' + _ws1 + r')(#if\s+0)',
  33. bygroups(using(this), Comment.Preproc), 'if0'),
  34. ('^(' + _ws1 + ')(#)',
  35. bygroups(using(this), Comment.Preproc), 'macro'),
  36. (r'\n', Text),
  37. (r'\s+', Text),
  38. (r'\\\n', Text), # line continuation
  39. (r'//(\n|[\w\W]*?[^\\]\n)', Comment.Single),
  40. (r'/(\\\n)?[*][\w\W]*?[*](\\\n)?/', Comment.Multiline),
  41. # Open until EOF, so no ending delimeter
  42. (r'/(\\\n)?[*][\w\W]*', Comment.Multiline),
  43. ],
  44. 'statements': [
  45. (r'(L?)(")', bygroups(String.Affix, String), 'string'),
  46. (r"(L?)(')(\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\\'\n])(')",
  47. bygroups(String.Affix, String.Char, String.Char, String.Char)),
  48. (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+[LlUu]*', Number.Float),
  49. (r'(\d+\.\d*|\.\d+|\d+[fF])[fF]?', Number.Float),
  50. (r'0x[0-9a-fA-F]+[LlUu]*', Number.Hex),
  51. (r'0[0-7]+[LlUu]*', Number.Oct),
  52. (r'\d+[LlUu]*', Number.Integer),
  53. (r'\*/', Error),
  54. (r'[~!%^&*+=|?:<>/-]', Operator),
  55. (r'[()\[\],.]', Punctuation),
  56. (words(('asm', 'auto', 'break', 'case', 'const', 'continue',
  57. 'default', 'do', 'else', 'enum', 'extern', 'for', 'goto',
  58. 'if', 'register', 'restricted', 'return', 'sizeof',
  59. 'static', 'struct', 'switch', 'typedef', 'union',
  60. 'volatile', 'while'),
  61. suffix=r'\b'), Keyword),
  62. (r'(bool|int|long|float|short|double|char|unsigned|signed|void)\b',
  63. Keyword.Type),
  64. (words(('inline', '_inline', '__inline', 'naked', 'restrict',
  65. 'thread', 'typename'), suffix=r'\b'), Keyword.Reserved),
  66. # Vector intrinsics
  67. (r'(__m(128i|128d|128|64))\b', Keyword.Reserved),
  68. # Microsoft-isms
  69. (words((
  70. 'asm', 'int8', 'based', 'except', 'int16', 'stdcall', 'cdecl',
  71. 'fastcall', 'int32', 'declspec', 'finally', 'int64', 'try',
  72. 'leave', 'wchar_t', 'w64', 'unaligned', 'raise', 'noop',
  73. 'identifier', 'forceinline', 'assume'),
  74. prefix=r'__', suffix=r'\b'), Keyword.Reserved),
  75. (r'(true|false|NULL)\b', Name.Builtin),
  76. (r'([a-zA-Z_]\w*)(\s*)(:)(?!:)', bygroups(Name.Label, Text, Punctuation)),
  77. (r'[a-zA-Z_]\w*', Name),
  78. ],
  79. 'root': [
  80. include('whitespace'),
  81. # functions
  82. (r'((?:[\w*\s])+?(?:\s|[*]))' # return arguments
  83. r'([a-zA-Z_]\w*)' # method name
  84. r'(\s*\([^;]*?\))' # signature
  85. r'([^;{]*)(\{)',
  86. bygroups(using(this), Name.Function, using(this), using(this),
  87. Punctuation),
  88. 'function'),
  89. # function declarations
  90. (r'((?:[\w*\s])+?(?:\s|[*]))' # return arguments
  91. r'([a-zA-Z_]\w*)' # method name
  92. r'(\s*\([^;]*?\))' # signature
  93. r'([^;]*)(;)',
  94. bygroups(using(this), Name.Function, using(this), using(this),
  95. Punctuation)),
  96. default('statement'),
  97. ],
  98. 'statement': [
  99. include('whitespace'),
  100. include('statements'),
  101. ('[{}]', Punctuation),
  102. (';', Punctuation, '#pop'),
  103. ],
  104. 'function': [
  105. include('whitespace'),
  106. include('statements'),
  107. (';', Punctuation),
  108. (r'\{', Punctuation, '#push'),
  109. (r'\}', Punctuation, '#pop'),
  110. ],
  111. 'string': [
  112. (r'"', String, '#pop'),
  113. (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|'
  114. r'u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8}|[0-7]{1,3})', String.Escape),
  115. (r'[^\\"\n]+', String), # all other characters
  116. (r'\\\n', String), # line continuation
  117. (r'\\', String), # stray backslash
  118. ],
  119. 'macro': [
  120. (r'(include)(' + _ws1 + r')([^\n]+)',
  121. bygroups(Comment.Preproc, Text, Comment.PreprocFile)),
  122. (r'[^/\n]+', Comment.Preproc),
  123. (r'/[*](.|\n)*?[*]/', Comment.Multiline),
  124. (r'//.*?\n', Comment.Single, '#pop'),
  125. (r'/', Comment.Preproc),
  126. (r'(?<=\\)\n', Comment.Preproc),
  127. (r'\n', Comment.Preproc, '#pop'),
  128. ],
  129. 'if0': [
  130. (r'^\s*#if.*?(?<!\\)\n', Comment.Preproc, '#push'),
  131. (r'^\s*#el(?:se|if).*\n', Comment.Preproc, '#pop'),
  132. (r'^\s*#endif.*?(?<!\\)\n', Comment.Preproc, '#pop'),
  133. (r'.*?\n', Comment),
  134. ]
  135. }
  136. stdlib_types = {
  137. 'size_t', 'ssize_t', 'off_t', 'wchar_t', 'ptrdiff_t', 'sig_atomic_t', 'fpos_t',
  138. 'clock_t', 'time_t', 'va_list', 'jmp_buf', 'FILE', 'DIR', 'div_t', 'ldiv_t',
  139. 'mbstate_t', 'wctrans_t', 'wint_t', 'wctype_t'}
  140. c99_types = {
  141. '_Bool', '_Complex', 'int8_t', 'int16_t', 'int32_t', 'int64_t', 'uint8_t',
  142. 'uint16_t', 'uint32_t', 'uint64_t', 'int_least8_t', 'int_least16_t',
  143. 'int_least32_t', 'int_least64_t', 'uint_least8_t', 'uint_least16_t',
  144. 'uint_least32_t', 'uint_least64_t', 'int_fast8_t', 'int_fast16_t', 'int_fast32_t',
  145. 'int_fast64_t', 'uint_fast8_t', 'uint_fast16_t', 'uint_fast32_t', 'uint_fast64_t',
  146. 'intptr_t', 'uintptr_t', 'intmax_t', 'uintmax_t'}
  147. linux_types = {
  148. 'clockid_t', 'cpu_set_t', 'cpumask_t', 'dev_t', 'gid_t', 'id_t', 'ino_t', 'key_t',
  149. 'mode_t', 'nfds_t', 'pid_t', 'rlim_t', 'sig_t', 'sighandler_t', 'siginfo_t',
  150. 'sigset_t', 'sigval_t', 'socklen_t', 'timer_t', 'uid_t'}
  151. def __init__(self, **options):
  152. self.stdlibhighlighting = get_bool_opt(options, 'stdlibhighlighting', True)
  153. self.c99highlighting = get_bool_opt(options, 'c99highlighting', True)
  154. self.platformhighlighting = get_bool_opt(options, 'platformhighlighting', True)
  155. RegexLexer.__init__(self, **options)
  156. def get_tokens_unprocessed(self, text):
  157. for index, token, value in \
  158. RegexLexer.get_tokens_unprocessed(self, text):
  159. if token is Name:
  160. if self.stdlibhighlighting and value in self.stdlib_types:
  161. token = Keyword.Type
  162. elif self.c99highlighting and value in self.c99_types:
  163. token = Keyword.Type
  164. elif self.platformhighlighting and value in self.linux_types:
  165. token = Keyword.Type
  166. yield index, token, value
  167. class CLexer(CFamilyLexer):
  168. """
  169. For C source code with preprocessor directives.
  170. """
  171. name = 'C'
  172. aliases = ['c']
  173. filenames = ['*.c', '*.h', '*.idc']
  174. mimetypes = ['text/x-chdr', 'text/x-csrc']
  175. priority = 0.1
  176. def analyse_text(text):
  177. if re.search(r'^\s*#include [<"]', text, re.MULTILINE):
  178. return 0.1
  179. if re.search(r'^\s*#ifn?def ', text, re.MULTILINE):
  180. return 0.1
  181. class CppLexer(CFamilyLexer):
  182. """
  183. For C++ source code with preprocessor directives.
  184. """
  185. name = 'C++'
  186. aliases = ['cpp', 'c++']
  187. filenames = ['*.cpp', '*.hpp', '*.c++', '*.h++',
  188. '*.cc', '*.hh', '*.cxx', '*.hxx',
  189. '*.C', '*.H', '*.cp', '*.CPP']
  190. mimetypes = ['text/x-c++hdr', 'text/x-c++src']
  191. priority = 0.1
  192. tokens = {
  193. 'statements': [
  194. (words((
  195. 'catch', 'const_cast', 'delete', 'dynamic_cast', 'explicit',
  196. 'export', 'friend', 'mutable', 'namespace', 'new', 'operator',
  197. 'private', 'protected', 'public', 'reinterpret_cast',
  198. 'restrict', 'static_cast', 'template', 'this', 'throw', 'throws',
  199. 'try', 'typeid', 'typename', 'using', 'virtual',
  200. 'constexpr', 'nullptr', 'decltype', 'thread_local',
  201. 'alignas', 'alignof', 'static_assert', 'noexcept', 'override',
  202. 'final'), suffix=r'\b'), Keyword),
  203. (r'char(16_t|32_t)\b', Keyword.Type),
  204. (r'(class)(\s+)', bygroups(Keyword, Text), 'classname'),
  205. # C++11 raw strings
  206. (r'(R)(")([^\\()\s]{,16})(\()((?:.|\n)*?)(\)\3)(")',
  207. bygroups(String.Affix, String, String.Delimiter, String.Delimiter,
  208. String, String.Delimiter, String)),
  209. # C++11 UTF-8/16/32 strings
  210. (r'(u8|u|U)(")', bygroups(String.Affix, String), 'string'),
  211. inherit,
  212. ],
  213. 'root': [
  214. inherit,
  215. # C++ Microsoft-isms
  216. (words(('virtual_inheritance', 'uuidof', 'super', 'single_inheritance',
  217. 'multiple_inheritance', 'interface', 'event'),
  218. prefix=r'__', suffix=r'\b'), Keyword.Reserved),
  219. # Offload C++ extensions, http://offload.codeplay.com/
  220. (r'__(offload|blockingoffload|outer)\b', Keyword.Pseudo),
  221. ],
  222. 'classname': [
  223. (r'[a-zA-Z_]\w*', Name.Class, '#pop'),
  224. # template specification
  225. (r'\s*(?=>)', Text, '#pop'),
  226. ],
  227. }
  228. def analyse_text(text):
  229. if re.search('#include <[a-z_]+>', text):
  230. return 0.2
  231. if re.search('using namespace ', text):
  232. return 0.4