c_lexer.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. #------------------------------------------------------------------------------
  2. # pycparser: c_lexer.py
  3. #
  4. # CLexer class: lexer for the C language
  5. #
  6. # Eli Bendersky [https://eli.thegreenplace.net/]
  7. # License: BSD
  8. #------------------------------------------------------------------------------
  9. import re
  10. import sys
  11. from .ply import lex
  12. from .ply.lex import TOKEN
  13. class CLexer(object):
  14. """ A lexer for the C language. After building it, set the
  15. input text with input(), and call token() to get new
  16. tokens.
  17. The public attribute filename can be set to an initial
  18. filename, but the lexer will update it upon #line
  19. directives.
  20. """
  21. def __init__(self, error_func, on_lbrace_func, on_rbrace_func,
  22. type_lookup_func):
  23. """ Create a new Lexer.
  24. error_func:
  25. An error function. Will be called with an error
  26. message, line and column as arguments, in case of
  27. an error during lexing.
  28. on_lbrace_func, on_rbrace_func:
  29. Called when an LBRACE or RBRACE is encountered
  30. (likely to push/pop type_lookup_func's scope)
  31. type_lookup_func:
  32. A type lookup function. Given a string, it must
  33. return True IFF this string is a name of a type
  34. that was defined with a typedef earlier.
  35. """
  36. self.error_func = error_func
  37. self.on_lbrace_func = on_lbrace_func
  38. self.on_rbrace_func = on_rbrace_func
  39. self.type_lookup_func = type_lookup_func
  40. self.filename = ''
  41. # Keeps track of the last token returned from self.token()
  42. self.last_token = None
  43. # Allow either "# line" or "# <num>" to support GCC's
  44. # cpp output
  45. #
  46. self.line_pattern = re.compile(r'([ \t]*line\W)|([ \t]*\d+)')
  47. self.pragma_pattern = re.compile(r'[ \t]*pragma\W')
  48. def build(self, **kwargs):
  49. """ Builds the lexer from the specification. Must be
  50. called after the lexer object is created.
  51. This method exists separately, because the PLY
  52. manual warns against calling lex.lex inside
  53. __init__
  54. """
  55. self.lexer = lex.lex(object=self, **kwargs)
  56. def reset_lineno(self):
  57. """ Resets the internal line number counter of the lexer.
  58. """
  59. self.lexer.lineno = 1
  60. def input(self, text):
  61. self.lexer.input(text)
  62. def token(self):
  63. self.last_token = self.lexer.token()
  64. return self.last_token
  65. def find_tok_column(self, token):
  66. """ Find the column of the token in its line.
  67. """
  68. last_cr = self.lexer.lexdata.rfind('\n', 0, token.lexpos)
  69. return token.lexpos - last_cr
  70. ######################-- PRIVATE --######################
  71. ##
  72. ## Internal auxiliary methods
  73. ##
  74. def _error(self, msg, token):
  75. location = self._make_tok_location(token)
  76. self.error_func(msg, location[0], location[1])
  77. self.lexer.skip(1)
  78. def _make_tok_location(self, token):
  79. return (token.lineno, self.find_tok_column(token))
  80. ##
  81. ## Reserved keywords
  82. ##
  83. keywords = (
  84. '_BOOL', '_COMPLEX', 'AUTO', 'BREAK', 'CASE', 'CHAR', 'CONST',
  85. 'CONTINUE', 'DEFAULT', 'DO', 'DOUBLE', 'ELSE', 'ENUM', 'EXTERN',
  86. 'FLOAT', 'FOR', 'GOTO', 'IF', 'INLINE', 'INT', 'LONG',
  87. 'REGISTER', 'OFFSETOF',
  88. 'RESTRICT', 'RETURN', 'SHORT', 'SIGNED', 'SIZEOF', 'STATIC', 'STRUCT',
  89. 'SWITCH', 'TYPEDEF', 'UNION', 'UNSIGNED', 'VOID',
  90. 'VOLATILE', 'WHILE', '__INT128',
  91. )
  92. keyword_map = {}
  93. for keyword in keywords:
  94. if keyword == '_BOOL':
  95. keyword_map['_Bool'] = keyword
  96. elif keyword == '_COMPLEX':
  97. keyword_map['_Complex'] = keyword
  98. else:
  99. keyword_map[keyword.lower()] = keyword
  100. ##
  101. ## All the tokens recognized by the lexer
  102. ##
  103. tokens = keywords + (
  104. # Identifiers
  105. 'ID',
  106. # Type identifiers (identifiers previously defined as
  107. # types with typedef)
  108. 'TYPEID',
  109. # constants
  110. 'INT_CONST_DEC', 'INT_CONST_OCT', 'INT_CONST_HEX', 'INT_CONST_BIN', 'INT_CONST_CHAR',
  111. 'FLOAT_CONST', 'HEX_FLOAT_CONST',
  112. 'CHAR_CONST',
  113. 'WCHAR_CONST',
  114. # String literals
  115. 'STRING_LITERAL',
  116. 'WSTRING_LITERAL',
  117. # Operators
  118. 'PLUS', 'MINUS', 'TIMES', 'DIVIDE', 'MOD',
  119. 'OR', 'AND', 'NOT', 'XOR', 'LSHIFT', 'RSHIFT',
  120. 'LOR', 'LAND', 'LNOT',
  121. 'LT', 'LE', 'GT', 'GE', 'EQ', 'NE',
  122. # Assignment
  123. 'EQUALS', 'TIMESEQUAL', 'DIVEQUAL', 'MODEQUAL',
  124. 'PLUSEQUAL', 'MINUSEQUAL',
  125. 'LSHIFTEQUAL','RSHIFTEQUAL', 'ANDEQUAL', 'XOREQUAL',
  126. 'OREQUAL',
  127. # Increment/decrement
  128. 'PLUSPLUS', 'MINUSMINUS',
  129. # Structure dereference (->)
  130. 'ARROW',
  131. # Conditional operator (?)
  132. 'CONDOP',
  133. # Delimeters
  134. 'LPAREN', 'RPAREN', # ( )
  135. 'LBRACKET', 'RBRACKET', # [ ]
  136. 'LBRACE', 'RBRACE', # { }
  137. 'COMMA', 'PERIOD', # . ,
  138. 'SEMI', 'COLON', # ; :
  139. # Ellipsis (...)
  140. 'ELLIPSIS',
  141. # pre-processor
  142. 'PPHASH', # '#'
  143. 'PPPRAGMA', # 'pragma'
  144. 'PPPRAGMASTR',
  145. )
  146. ##
  147. ## Regexes for use in tokens
  148. ##
  149. ##
  150. # valid C identifiers (K&R2: A.2.3), plus '$' (supported by some compilers)
  151. identifier = r'[a-zA-Z_$][0-9a-zA-Z_$]*'
  152. hex_prefix = '0[xX]'
  153. hex_digits = '[0-9a-fA-F]+'
  154. bin_prefix = '0[bB]'
  155. bin_digits = '[01]+'
  156. # integer constants (K&R2: A.2.5.1)
  157. integer_suffix_opt = r'(([uU]ll)|([uU]LL)|(ll[uU]?)|(LL[uU]?)|([uU][lL])|([lL][uU]?)|[uU])?'
  158. decimal_constant = '(0'+integer_suffix_opt+')|([1-9][0-9]*'+integer_suffix_opt+')'
  159. octal_constant = '0[0-7]*'+integer_suffix_opt
  160. hex_constant = hex_prefix+hex_digits+integer_suffix_opt
  161. bin_constant = bin_prefix+bin_digits+integer_suffix_opt
  162. bad_octal_constant = '0[0-7]*[89]'
  163. # character constants (K&R2: A.2.5.2)
  164. # Note: a-zA-Z and '.-~^_!=&;,' are allowed as escape chars to support #line
  165. # directives with Windows paths as filenames (..\..\dir\file)
  166. # For the same reason, decimal_escape allows all digit sequences. We want to
  167. # parse all correct code, even if it means to sometimes parse incorrect
  168. # code.
  169. #
  170. # The original regexes were taken verbatim from the C syntax definition,
  171. # and were later modified to avoid worst-case exponential running time.
  172. #
  173. # simple_escape = r"""([a-zA-Z._~!=&\^\-\\?'"])"""
  174. # decimal_escape = r"""(\d+)"""
  175. # hex_escape = r"""(x[0-9a-fA-F]+)"""
  176. # bad_escape = r"""([\\][^a-zA-Z._~^!=&\^\-\\?'"x0-7])"""
  177. #
  178. # The following modifications were made to avoid the ambiguity that allowed backtracking:
  179. # (https://github.com/eliben/pycparser/issues/61)
  180. #
  181. # - \x was removed from simple_escape, unless it was not followed by a hex digit, to avoid ambiguity with hex_escape.
  182. # - hex_escape allows one or more hex characters, but requires that the next character(if any) is not hex
  183. # - decimal_escape allows one or more decimal characters, but requires that the next character(if any) is not a decimal
  184. # - bad_escape does not allow any decimals (8-9), to avoid conflicting with the permissive decimal_escape.
  185. #
  186. # Without this change, python's `re` module would recursively try parsing each ambiguous escape sequence in multiple ways.
  187. # e.g. `\123` could be parsed as `\1`+`23`, `\12`+`3`, and `\123`.
  188. simple_escape = r"""([a-wyzA-Z._~!=&\^\-\\?'"]|x(?![0-9a-fA-F]))"""
  189. decimal_escape = r"""(\d+)(?!\d)"""
  190. hex_escape = r"""(x[0-9a-fA-F]+)(?![0-9a-fA-F])"""
  191. bad_escape = r"""([\\][^a-zA-Z._~^!=&\^\-\\?'"x0-9])"""
  192. escape_sequence = r"""(\\("""+simple_escape+'|'+decimal_escape+'|'+hex_escape+'))'
  193. # This complicated regex with lookahead might be slow for strings, so because all of the valid escapes (including \x) allowed
  194. # 0 or more non-escaped characters after the first character, simple_escape+decimal_escape+hex_escape got simplified to
  195. escape_sequence_start_in_string = r"""(\\[0-9a-zA-Z._~!=&\^\-\\?'"])"""
  196. cconst_char = r"""([^'\\\n]|"""+escape_sequence+')'
  197. char_const = "'"+cconst_char+"'"
  198. wchar_const = 'L'+char_const
  199. multicharacter_constant = "'"+cconst_char+"{2,4}'"
  200. unmatched_quote = "('"+cconst_char+"*\\n)|('"+cconst_char+"*$)"
  201. bad_char_const = r"""('"""+cconst_char+"""[^'\n]+')|('')|('"""+bad_escape+r"""[^'\n]*')"""
  202. # string literals (K&R2: A.2.6)
  203. string_char = r"""([^"\\\n]|"""+escape_sequence_start_in_string+')'
  204. string_literal = '"'+string_char+'*"'
  205. wstring_literal = 'L'+string_literal
  206. bad_string_literal = '"'+string_char+'*'+bad_escape+string_char+'*"'
  207. # floating constants (K&R2: A.2.5.3)
  208. exponent_part = r"""([eE][-+]?[0-9]+)"""
  209. fractional_constant = r"""([0-9]*\.[0-9]+)|([0-9]+\.)"""
  210. floating_constant = '(((('+fractional_constant+')'+exponent_part+'?)|([0-9]+'+exponent_part+'))[FfLl]?)'
  211. binary_exponent_part = r'''([pP][+-]?[0-9]+)'''
  212. hex_fractional_constant = '((('+hex_digits+r""")?\."""+hex_digits+')|('+hex_digits+r"""\.))"""
  213. hex_floating_constant = '('+hex_prefix+'('+hex_digits+'|'+hex_fractional_constant+')'+binary_exponent_part+'[FfLl]?)'
  214. ##
  215. ## Lexer states: used for preprocessor \n-terminated directives
  216. ##
  217. states = (
  218. # ppline: preprocessor line directives
  219. #
  220. ('ppline', 'exclusive'),
  221. # pppragma: pragma
  222. #
  223. ('pppragma', 'exclusive'),
  224. )
  225. def t_PPHASH(self, t):
  226. r'[ \t]*\#'
  227. if self.line_pattern.match(t.lexer.lexdata, pos=t.lexer.lexpos):
  228. t.lexer.begin('ppline')
  229. self.pp_line = self.pp_filename = None
  230. elif self.pragma_pattern.match(t.lexer.lexdata, pos=t.lexer.lexpos):
  231. t.lexer.begin('pppragma')
  232. else:
  233. t.type = 'PPHASH'
  234. return t
  235. ##
  236. ## Rules for the ppline state
  237. ##
  238. @TOKEN(string_literal)
  239. def t_ppline_FILENAME(self, t):
  240. if self.pp_line is None:
  241. self._error('filename before line number in #line', t)
  242. else:
  243. self.pp_filename = t.value.lstrip('"').rstrip('"')
  244. @TOKEN(decimal_constant)
  245. def t_ppline_LINE_NUMBER(self, t):
  246. if self.pp_line is None:
  247. self.pp_line = t.value
  248. else:
  249. # Ignore: GCC's cpp sometimes inserts a numeric flag
  250. # after the file name
  251. pass
  252. def t_ppline_NEWLINE(self, t):
  253. r'\n'
  254. if self.pp_line is None:
  255. self._error('line number missing in #line', t)
  256. else:
  257. self.lexer.lineno = int(self.pp_line)
  258. if self.pp_filename is not None:
  259. self.filename = self.pp_filename
  260. t.lexer.begin('INITIAL')
  261. def t_ppline_PPLINE(self, t):
  262. r'line'
  263. pass
  264. t_ppline_ignore = ' \t'
  265. def t_ppline_error(self, t):
  266. self._error('invalid #line directive', t)
  267. ##
  268. ## Rules for the pppragma state
  269. ##
  270. def t_pppragma_NEWLINE(self, t):
  271. r'\n'
  272. t.lexer.lineno += 1
  273. t.lexer.begin('INITIAL')
  274. def t_pppragma_PPPRAGMA(self, t):
  275. r'pragma'
  276. return t
  277. t_pppragma_ignore = ' \t'
  278. def t_pppragma_STR(self, t):
  279. '.+'
  280. t.type = 'PPPRAGMASTR'
  281. return t
  282. def t_pppragma_error(self, t):
  283. self._error('invalid #pragma directive', t)
  284. ##
  285. ## Rules for the normal state
  286. ##
  287. t_ignore = ' \t'
  288. # Newlines
  289. def t_NEWLINE(self, t):
  290. r'\n+'
  291. t.lexer.lineno += t.value.count("\n")
  292. # Operators
  293. t_PLUS = r'\+'
  294. t_MINUS = r'-'
  295. t_TIMES = r'\*'
  296. t_DIVIDE = r'/'
  297. t_MOD = r'%'
  298. t_OR = r'\|'
  299. t_AND = r'&'
  300. t_NOT = r'~'
  301. t_XOR = r'\^'
  302. t_LSHIFT = r'<<'
  303. t_RSHIFT = r'>>'
  304. t_LOR = r'\|\|'
  305. t_LAND = r'&&'
  306. t_LNOT = r'!'
  307. t_LT = r'<'
  308. t_GT = r'>'
  309. t_LE = r'<='
  310. t_GE = r'>='
  311. t_EQ = r'=='
  312. t_NE = r'!='
  313. # Assignment operators
  314. t_EQUALS = r'='
  315. t_TIMESEQUAL = r'\*='
  316. t_DIVEQUAL = r'/='
  317. t_MODEQUAL = r'%='
  318. t_PLUSEQUAL = r'\+='
  319. t_MINUSEQUAL = r'-='
  320. t_LSHIFTEQUAL = r'<<='
  321. t_RSHIFTEQUAL = r'>>='
  322. t_ANDEQUAL = r'&='
  323. t_OREQUAL = r'\|='
  324. t_XOREQUAL = r'\^='
  325. # Increment/decrement
  326. t_PLUSPLUS = r'\+\+'
  327. t_MINUSMINUS = r'--'
  328. # ->
  329. t_ARROW = r'->'
  330. # ?
  331. t_CONDOP = r'\?'
  332. # Delimeters
  333. t_LPAREN = r'\('
  334. t_RPAREN = r'\)'
  335. t_LBRACKET = r'\['
  336. t_RBRACKET = r'\]'
  337. t_COMMA = r','
  338. t_PERIOD = r'\.'
  339. t_SEMI = r';'
  340. t_COLON = r':'
  341. t_ELLIPSIS = r'\.\.\.'
  342. # Scope delimiters
  343. # To see why on_lbrace_func is needed, consider:
  344. # typedef char TT;
  345. # void foo(int TT) { TT = 10; }
  346. # TT x = 5;
  347. # Outside the function, TT is a typedef, but inside (starting and ending
  348. # with the braces) it's a parameter. The trouble begins with yacc's
  349. # lookahead token. If we open a new scope in brace_open, then TT has
  350. # already been read and incorrectly interpreted as TYPEID. So, we need
  351. # to open and close scopes from within the lexer.
  352. # Similar for the TT immediately outside the end of the function.
  353. #
  354. @TOKEN(r'\{')
  355. def t_LBRACE(self, t):
  356. self.on_lbrace_func()
  357. return t
  358. @TOKEN(r'\}')
  359. def t_RBRACE(self, t):
  360. self.on_rbrace_func()
  361. return t
  362. t_STRING_LITERAL = string_literal
  363. # The following floating and integer constants are defined as
  364. # functions to impose a strict order (otherwise, decimal
  365. # is placed before the others because its regex is longer,
  366. # and this is bad)
  367. #
  368. @TOKEN(floating_constant)
  369. def t_FLOAT_CONST(self, t):
  370. return t
  371. @TOKEN(hex_floating_constant)
  372. def t_HEX_FLOAT_CONST(self, t):
  373. return t
  374. @TOKEN(hex_constant)
  375. def t_INT_CONST_HEX(self, t):
  376. return t
  377. @TOKEN(bin_constant)
  378. def t_INT_CONST_BIN(self, t):
  379. return t
  380. @TOKEN(bad_octal_constant)
  381. def t_BAD_CONST_OCT(self, t):
  382. msg = "Invalid octal constant"
  383. self._error(msg, t)
  384. @TOKEN(octal_constant)
  385. def t_INT_CONST_OCT(self, t):
  386. return t
  387. @TOKEN(decimal_constant)
  388. def t_INT_CONST_DEC(self, t):
  389. return t
  390. # Must come before bad_char_const, to prevent it from
  391. # catching valid char constants as invalid
  392. #
  393. @TOKEN(multicharacter_constant)
  394. def t_INT_CONST_CHAR(self, t):
  395. return t
  396. @TOKEN(char_const)
  397. def t_CHAR_CONST(self, t):
  398. return t
  399. @TOKEN(wchar_const)
  400. def t_WCHAR_CONST(self, t):
  401. return t
  402. @TOKEN(unmatched_quote)
  403. def t_UNMATCHED_QUOTE(self, t):
  404. msg = "Unmatched '"
  405. self._error(msg, t)
  406. @TOKEN(bad_char_const)
  407. def t_BAD_CHAR_CONST(self, t):
  408. msg = "Invalid char constant %s" % t.value
  409. self._error(msg, t)
  410. @TOKEN(wstring_literal)
  411. def t_WSTRING_LITERAL(self, t):
  412. return t
  413. # unmatched string literals are caught by the preprocessor
  414. @TOKEN(bad_string_literal)
  415. def t_BAD_STRING_LITERAL(self, t):
  416. msg = "String contains invalid escape code"
  417. self._error(msg, t)
  418. @TOKEN(identifier)
  419. def t_ID(self, t):
  420. t.type = self.keyword_map.get(t.value, "ID")
  421. if t.type == 'ID' and self.type_lookup_func(t.value):
  422. t.type = "TYPEID"
  423. return t
  424. def t_error(self, t):
  425. msg = 'Illegal character %s' % repr(t.value[0])
  426. self._error(msg, t)