c_lexer.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  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. from collections.abc import Callable
  11. from dataclasses import dataclass
  12. from enum import Enum
  13. @dataclass(slots=True)
  14. class Token:
  15. type: str
  16. value: str
  17. lineno: int
  18. column: int
  19. class CLexer:
  20. """A standalone lexer for C.
  21. The lexer takes the following callback functions as parameters during
  22. construction:
  23. error_func:
  24. Called with (msg, line, column) on lexing errors.
  25. on_lbrace_func:
  26. Called when an LBRACE token is produced (used for scope tracking).
  27. on_rbrace_func:
  28. Called when an RBRACE token is produced (used for scope tracking).
  29. type_lookup_func:
  30. Called with an identifier name; expected to return True if it is
  31. a typedef name and should be tokenized as TYPEID.
  32. Call input(text) to initialize lexing, and then keep calling token() to
  33. get the next token, until it returns None (at end of input).
  34. """
  35. def __init__(
  36. self,
  37. error_func: Callable[[str, int, int], None],
  38. on_lbrace_func: Callable[[], None],
  39. on_rbrace_func: Callable[[], None],
  40. type_lookup_func: Callable[[str], bool],
  41. ) -> None:
  42. self.error_func = error_func
  43. self.on_lbrace_func = on_lbrace_func
  44. self.on_rbrace_func = on_rbrace_func
  45. self.type_lookup_func = type_lookup_func
  46. self._init_state()
  47. def input(self, text: str, filename: str = "") -> None:
  48. """Initialize the lexer to the given input text.
  49. filename is an optional name identifying the initial file from which the
  50. input comes. The lexer may modify it if #line directives are
  51. encountered.
  52. """
  53. self._init_state()
  54. self._lexdata = text
  55. self._filename = filename
  56. def _init_state(self) -> None:
  57. self._lexdata = ""
  58. self._filename = ""
  59. self._pos = 0
  60. self._line_start = 0
  61. self._pending_tok: Token | None = None
  62. self._lineno = 1
  63. @property
  64. def filename(self) -> str:
  65. return self._filename
  66. def token(self) -> Token | None:
  67. # Lexing strategy overview:
  68. #
  69. # - We maintain a current position (self._pos), line number, and the
  70. # byte offset of the current line start. The lexer is a simple loop
  71. # that skips whitespace/newlines and emits one token per call.
  72. #
  73. # - A small amount of logic is handled manually before regex matching:
  74. #
  75. # * Preprocessor-style directives: if we see '#', we check whether
  76. # it's a #line or #pragma directive and consume it inline. #line
  77. # updates lineno/filename and produces no tokens. #pragma can yield
  78. # both PPPRAGMA and PPPRAGMASTR, but token() returns a single token,
  79. # so we stash the PPPRAGMASTR as _pending_tok to return on the next
  80. # token() call. Otherwise we return PPHASH.
  81. # * Newlines update lineno/line-start tracking so tokens can record
  82. # accurate columns.
  83. #
  84. # - The bulk of tokens are recognized in _match_token:
  85. #
  86. # * _regex_rules: regex patterns for identifiers, literals, and other
  87. # complex tokens (including error-producing patterns). The lexer
  88. # uses a combined _regex_master to scan options at the same time.
  89. # * _fixed_tokens: exact string matches for operators and punctuation,
  90. # resolved by longest match.
  91. #
  92. # - Error patterns call the error callback and advance minimally, which
  93. # keeps lexing resilient while reporting useful diagnostics.
  94. text = self._lexdata
  95. n = len(text)
  96. if self._pending_tok is not None:
  97. tok = self._pending_tok
  98. self._pending_tok = None
  99. return tok
  100. while self._pos < n:
  101. match text[self._pos]:
  102. case " " | "\t":
  103. self._pos += 1
  104. case "\n":
  105. self._lineno += 1
  106. self._pos += 1
  107. self._line_start = self._pos
  108. case "#":
  109. if _line_pattern.match(text, self._pos + 1):
  110. self._pos += 1
  111. self._handle_ppline()
  112. continue
  113. if _pragma_pattern.match(text, self._pos + 1):
  114. self._pos += 1
  115. toks = self._handle_pppragma()
  116. if len(toks) > 1:
  117. self._pending_tok = toks[1]
  118. if len(toks) > 0:
  119. return toks[0]
  120. continue
  121. tok = self._make_token("PPHASH", "#", self._pos)
  122. self._pos += 1
  123. return tok
  124. case _:
  125. if tok := self._match_token():
  126. return tok
  127. else:
  128. continue
  129. def _match_token(self) -> Token | None:
  130. """Match one token at the current position.
  131. Returns a Token on success, or None if no token could be matched and
  132. an error was reported. This method always advances _pos by the matched
  133. length, or by 1 on error/no-match.
  134. """
  135. text = self._lexdata
  136. pos = self._pos
  137. # We pick the longest match between:
  138. # - the master regex (identifiers, literals, error patterns, etc.)
  139. # - fixed operator/punctuator literals from the bucket for text[pos]
  140. #
  141. # The longest match is required to ensure we properly lex something
  142. # like ".123" (a floating-point constant) as a single entity (with
  143. # FLOAT_CONST), rather than a PERIOD followed by a number.
  144. #
  145. # The fixed-literal buckets are already length-sorted, so within that
  146. # bucket we can take the first match. However, we still compare its
  147. # length to the regex match because the regex may have matched a longer
  148. # token that should take precedence.
  149. best = None
  150. if m := _regex_master.match(text, pos):
  151. tok_type = m.lastgroup
  152. # All master-regex alternatives are named; lastgroup shouldn't be None.
  153. assert tok_type is not None
  154. value = m.group(tok_type)
  155. length = len(value)
  156. action, msg = _regex_actions[tok_type]
  157. best = (length, tok_type, value, action, msg)
  158. if bucket := _fixed_tokens_by_first.get(text[pos]):
  159. for entry in bucket:
  160. if text.startswith(entry.literal, pos):
  161. length = len(entry.literal)
  162. if best is None or length > best[0]:
  163. best = (
  164. length,
  165. entry.tok_type,
  166. entry.literal,
  167. _RegexAction.TOKEN,
  168. None,
  169. )
  170. break
  171. if best is None:
  172. self._error(f"Illegal character {text[pos]!r}", pos)
  173. self._pos += 1
  174. return None
  175. length, tok_type, value, action, msg = best
  176. match action:
  177. case _RegexAction.TOKEN:
  178. pass
  179. case _RegexAction.ERROR:
  180. if tok_type == "BAD_CHAR_CONST":
  181. msg = f"Invalid char constant {value}"
  182. # All other ERROR rules provide a message.
  183. assert msg is not None
  184. self._error(msg, pos)
  185. self._pos += max(1, length)
  186. return None
  187. case _RegexAction.ID:
  188. tok_type = _keyword_map.get(value, "ID")
  189. if tok_type == "ID" and self.type_lookup_func(value):
  190. tok_type = "TYPEID"
  191. case _:
  192. raise RuntimeError("unreachable")
  193. tok = self._make_token(tok_type, value, pos)
  194. self._pos += length
  195. if tok.type == "LBRACE":
  196. self.on_lbrace_func()
  197. elif tok.type == "RBRACE":
  198. self.on_rbrace_func()
  199. return tok
  200. def _make_token(self, tok_type: str, value: str, pos: int) -> Token:
  201. """Create a Token at an absolute input position.
  202. Expects tok_type/value and the absolute byte offset pos in the current
  203. input. Does not advance lexer state; callers manage _pos themselves.
  204. Returns a Token with lineno/column computed from current line tracking.
  205. """
  206. column = pos - self._line_start + 1
  207. tok = Token(tok_type, value, self._lineno, column)
  208. return tok
  209. def _error(self, msg: str, pos: int) -> None:
  210. column = pos - self._line_start + 1
  211. self.error_func(msg, self._lineno, column)
  212. def _handle_ppline(self) -> None:
  213. # Since #line directives aren't supposed to return tokens but should
  214. # only affect the lexer's state (update line/filename for coords), this
  215. # method does a bit of parsing on its own. It doesn't return anything,
  216. # but its side effect is to update self._pos past the directive, and
  217. # potentially update self._lineno and self._filename, based on the
  218. # directive's contents.
  219. #
  220. # Accepted #line forms from preprocessors:
  221. # - "#line 66 \"kwas\\df.h\""
  222. # - "# 9"
  223. # - "#line 10 \"include/me.h\" 1 2 3" (extra numeric flags)
  224. # - "# 1 \"file.h\" 3"
  225. # Errors we must report:
  226. # - "#line \"file.h\"" (filename before line number)
  227. # - "#line df" (garbage instead of number/string)
  228. #
  229. # We scan the directive line once (after an optional 'line' keyword),
  230. # validating the order: NUMBER, optional STRING, then any NUMBERs.
  231. # The NUMBERs tail is only accepted if a filename STRING was present.
  232. text = self._lexdata
  233. n = len(text)
  234. line_end = text.find("\n", self._pos)
  235. if line_end == -1:
  236. line_end = n
  237. line = text[self._pos : line_end]
  238. pos = 0
  239. line_len = len(line)
  240. def skip_ws() -> None:
  241. nonlocal pos
  242. while pos < line_len and line[pos] in " \t":
  243. pos += 1
  244. skip_ws()
  245. if line.startswith("line", pos):
  246. pos += 4
  247. def success(pp_line: str | None, pp_filename: str | None) -> None:
  248. if pp_line is None:
  249. self._error("line number missing in #line", self._pos + line_len)
  250. else:
  251. try:
  252. self._lineno = int(pp_line)
  253. except ValueError:
  254. self._error("invalid #line directive", self._pos + line_len)
  255. return
  256. if pp_filename is not None:
  257. self._filename = pp_filename
  258. self._pos = line_end + 1
  259. self._line_start = self._pos
  260. def fail(msg: str, offset: int) -> None:
  261. self._error(msg, self._pos + offset)
  262. self._pos = line_end + 1
  263. self._line_start = self._pos
  264. skip_ws()
  265. if pos >= line_len:
  266. success(None, None)
  267. return
  268. if line[pos] == '"':
  269. fail("filename before line number in #line", pos)
  270. return
  271. m = re.match(_decimal_constant, line[pos:])
  272. if not m:
  273. fail("invalid #line directive", pos)
  274. return
  275. pp_line = m.group(0)
  276. pos += len(pp_line)
  277. skip_ws()
  278. if pos >= line_len:
  279. success(pp_line, None)
  280. return
  281. if line[pos] != '"':
  282. fail("invalid #line directive", pos)
  283. return
  284. m = re.match(_string_literal, line[pos:])
  285. if not m:
  286. fail("invalid #line directive", pos)
  287. return
  288. pp_filename = m.group(0).lstrip('"').rstrip('"')
  289. pos += len(m.group(0))
  290. # Consume arbitrary sequence of numeric flags after the directive
  291. while True:
  292. skip_ws()
  293. if pos >= line_len:
  294. break
  295. m = re.match(_decimal_constant, line[pos:])
  296. if not m:
  297. fail("invalid #line directive", pos)
  298. return
  299. pos += len(m.group(0))
  300. success(pp_line, pp_filename)
  301. def _handle_pppragma(self) -> list[Token]:
  302. # Parse a full #pragma line; returns a list of tokens with 1 or 2
  303. # tokens - PPPRAGMA and an optional PPPRAGMASTR. If an empty list is
  304. # returned, it means an error occurred, or we're at the end of input.
  305. #
  306. # Examples:
  307. # - "#pragma" -> PPPRAGMA only
  308. # - "#pragma once" -> PPPRAGMA, PPPRAGMASTR("once")
  309. # - "# pragma omp parallel private(th_id)" -> PPPRAGMA, PPPRAGMASTR("omp parallel private(th_id)")
  310. # - "#\tpragma {pack: 2, smack: 3}" -> PPPRAGMA, PPPRAGMASTR("{pack: 2, smack: 3}")
  311. text = self._lexdata
  312. n = len(text)
  313. pos = self._pos
  314. while pos < n and text[pos] in " \t":
  315. pos += 1
  316. if pos >= n:
  317. self._pos = pos
  318. return []
  319. if not text.startswith("pragma", pos):
  320. self._error("invalid #pragma directive", pos)
  321. self._pos = pos + 1
  322. return []
  323. pragma_pos = pos
  324. pos += len("pragma")
  325. toks = [self._make_token("PPPRAGMA", "pragma", pragma_pos)]
  326. while pos < n and text[pos] in " \t":
  327. pos += 1
  328. start = pos
  329. while pos < n and text[pos] != "\n":
  330. pos += 1
  331. if pos > start:
  332. toks.append(self._make_token("PPPRAGMASTR", text[start:pos], start))
  333. if pos < n and text[pos] == "\n":
  334. self._lineno += 1
  335. pos += 1
  336. self._line_start = pos
  337. self._pos = pos
  338. return toks
  339. ##
  340. ## Reserved keywords
  341. ##
  342. _keywords: tuple[str, ...] = (
  343. "AUTO",
  344. "BREAK",
  345. "CASE",
  346. "CHAR",
  347. "CONST",
  348. "CONTINUE",
  349. "DEFAULT",
  350. "DO",
  351. "DOUBLE",
  352. "ELSE",
  353. "ENUM",
  354. "EXTERN",
  355. "FLOAT",
  356. "FOR",
  357. "GOTO",
  358. "IF",
  359. "INLINE",
  360. "INT",
  361. "LONG",
  362. "REGISTER",
  363. "OFFSETOF",
  364. "RESTRICT",
  365. "RETURN",
  366. "SHORT",
  367. "SIGNED",
  368. "SIZEOF",
  369. "STATIC",
  370. "STRUCT",
  371. "SWITCH",
  372. "TYPEDEF",
  373. "UNION",
  374. "UNSIGNED",
  375. "VOID",
  376. "VOLATILE",
  377. "WHILE",
  378. "__INT128",
  379. "_BOOL",
  380. "_COMPLEX",
  381. "_GENERIC",
  382. "_NORETURN",
  383. "_THREAD_LOCAL",
  384. "_STATIC_ASSERT",
  385. "_ATOMIC",
  386. "_ALIGNOF",
  387. "_ALIGNAS",
  388. "_PRAGMA",
  389. )
  390. _keyword_map: dict[str, str] = {}
  391. for keyword in _keywords:
  392. # Keywords from new C standard are mixed-case, like _Bool, _Alignas, etc.
  393. if keyword.startswith("_") and len(keyword) > 1 and keyword[1].isalpha():
  394. _keyword_map[keyword[:2].upper() + keyword[2:].lower()] = keyword
  395. else:
  396. _keyword_map[keyword.lower()] = keyword
  397. ##
  398. ## Regexes for use in tokens
  399. ##
  400. # valid C identifiers (K&R2: A.2.3), plus '$' (supported by some compilers)
  401. _identifier = r"[a-zA-Z_$][0-9a-zA-Z_$]*"
  402. _hex_prefix = "0[xX]"
  403. _hex_digits = "[0-9a-fA-F]+"
  404. _bin_prefix = "0[bB]"
  405. _bin_digits = "[01]+"
  406. # integer constants (K&R2: A.2.5.1)
  407. _integer_suffix_opt = (
  408. r"(([uU]ll)|([uU]LL)|(ll[uU]?)|(LL[uU]?)|([uU][lL])|([lL][uU]?)|[uU])?"
  409. )
  410. _decimal_constant = (
  411. "(0" + _integer_suffix_opt + ")|([1-9][0-9]*" + _integer_suffix_opt + ")"
  412. )
  413. _octal_constant = "0[0-7]*" + _integer_suffix_opt
  414. _hex_constant = _hex_prefix + _hex_digits + _integer_suffix_opt
  415. _bin_constant = _bin_prefix + _bin_digits + _integer_suffix_opt
  416. _bad_octal_constant = "0[0-7]*[89]"
  417. # comments are not supported
  418. _unsupported_c_style_comment = r"\/\*"
  419. _unsupported_cxx_style_comment = r"\/\/"
  420. # Character constants and escape sequences.
  421. #
  422. # Tokens preserve their source spelling; the lexer does not decode escapes or
  423. # validate Unicode code points. Each complete escape must match as one character
  424. # in _cconst_char, which is used for both single and multicharacter constants.
  425. # Matching is deliberately permissive: simple escapes accept extra letters and
  426. # punctuation, and numeric escapes accept decimal digits, not just octal digits.
  427. #
  428. # _cconst_char is also repeated in the error patterns. If an escape can match in
  429. # several ways, long malformed constants can cause exponential backtracking
  430. # (https://github.com/eliben/pycparser/issues/61). The lookaheads prevent this:
  431. # - Decimal and hexadecimal escapes consume the whole run of digits. For
  432. # example, \123 cannot be split into \1 followed by the characters 2 and 3.
  433. # - A simple \x escape is allowed only when no hexadecimal digit follows it.
  434. # - A complete Unicode escape cannot fall back to a simple \u or \U escape.
  435. # _bad_escape also excludes all decimal digits to agree with this permissiveness.
  436. # Universal character names consume exactly four hex digits after u or eight
  437. # after U. A following hex digit is a separate character, unlike with \x.
  438. _unicode_escape = r"(u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8})"
  439. # This lookahead runs immediately after the backslash. If a complete Unicode
  440. # escape follows, only _unicode_escape may match it: \u00e9 cannot be read as
  441. # \u followed by 0, 0, e, 9. Incomplete forms retain the permissive behavior
  442. # of simple escapes.
  443. _simple_escape = (
  444. rf"(?!{_unicode_escape})"
  445. r"""([a-wyzA-Z._~!=&\^\-\\?'"]|x(?![0-9a-fA-F]))"""
  446. )
  447. _decimal_escape = r"""(\d+)(?!\d)"""
  448. _hex_escape = r"""(x[0-9a-fA-F]+)(?![0-9a-fA-F])"""
  449. _bad_escape = r"""([\\][^a-zA-Z._~^!=&\^\-\\?'"x0-9])"""
  450. _escape_sequence = (
  451. r"""(\\("""
  452. + _simple_escape
  453. + "|"
  454. + _decimal_escape
  455. + "|"
  456. + _hex_escape
  457. + "|"
  458. + _unicode_escape
  459. + "))"
  460. )
  461. # Strings do not need to count the characters represented by escapes. Match
  462. # just the backslash and a permitted following character; _string_char consumes
  463. # any remaining numeric or Unicode digits as ordinary text. This avoids matching
  464. # complete escape sequences repeatedly. The permissive spellings also support
  465. # Windows paths in #line filenames, which are matched with _string_literal.
  466. _escape_sequence_start_in_string = r"""(\\[0-9a-zA-Z._~!=&\^\-\\?'"])"""
  467. _cconst_char = r"""([^'\\\n]|""" + _escape_sequence + ")"
  468. _char_const = "'" + _cconst_char + "'"
  469. _wchar_const = "L" + _char_const
  470. _u8char_const = "u8" + _char_const
  471. _u16char_const = "u" + _char_const
  472. _u32char_const = "U" + _char_const
  473. _multicharacter_constant = "'" + _cconst_char + "{2,4}'"
  474. _unmatched_quote = "('" + _cconst_char + "*\\n)|('" + _cconst_char + "*$)"
  475. _bad_char_const = (
  476. r"""('""" + _cconst_char + """[^'\n]+')|('')|('""" + _bad_escape + r"""[^'\n]*')"""
  477. )
  478. # String literals, including wide and Unicode prefixes.
  479. _string_char = r"""([^"\\\n]|""" + _escape_sequence_start_in_string + ")"
  480. _string_literal = '"' + _string_char + '*"'
  481. _wstring_literal = "L" + _string_literal
  482. _u8string_literal = "u8" + _string_literal
  483. _u16string_literal = "u" + _string_literal
  484. _u32string_literal = "U" + _string_literal
  485. _bad_string_literal = '"' + _string_char + "*" + _bad_escape + _string_char + '*"'
  486. # floating constants (K&R2: A.2.5.3)
  487. _exponent_part = r"""([eE][-+]?[0-9]+)"""
  488. _fractional_constant = r"""([0-9]*\.[0-9]+)|([0-9]+\.)"""
  489. _floating_constant = (
  490. "(((("
  491. + _fractional_constant
  492. + ")"
  493. + _exponent_part
  494. + "?)|([0-9]+"
  495. + _exponent_part
  496. + "))[FfLl]?)"
  497. )
  498. _binary_exponent_part = r"""([pP][+-]?[0-9]+)"""
  499. _hex_fractional_constant = (
  500. "(((" + _hex_digits + r""")?\.""" + _hex_digits + ")|(" + _hex_digits + r"""\.))"""
  501. )
  502. _hex_floating_constant = (
  503. "("
  504. + _hex_prefix
  505. + "("
  506. + _hex_digits
  507. + "|"
  508. + _hex_fractional_constant
  509. + ")"
  510. + _binary_exponent_part
  511. + "[FfLl]?)"
  512. )
  513. class _RegexAction(Enum):
  514. TOKEN = 0
  515. ID = 1
  516. ERROR = 2
  517. @dataclass(frozen=True)
  518. class _RegexRule:
  519. # tok_type: name of the token emitted for a match
  520. # regex_pattern: the raw regex (no anchors) to match at the current position
  521. # action: TOKEN for normal tokens, ID for identifiers, ERROR to report
  522. # error_message: message used for ERROR entries
  523. tok_type: str
  524. regex_pattern: str
  525. action: _RegexAction
  526. error_message: str | None
  527. _regex_rules: list[_RegexRule] = [
  528. _RegexRule(
  529. "UNSUPPORTED_C_STYLE_COMMENT",
  530. _unsupported_c_style_comment,
  531. _RegexAction.ERROR,
  532. "Comments are not supported, see https://github.com/eliben/pycparser#3using.",
  533. ),
  534. _RegexRule(
  535. "UNSUPPORTED_CXX_STYLE_COMMENT",
  536. _unsupported_cxx_style_comment,
  537. _RegexAction.ERROR,
  538. "Comments are not supported, see https://github.com/eliben/pycparser#3using.",
  539. ),
  540. _RegexRule(
  541. "BAD_STRING_LITERAL",
  542. _bad_string_literal,
  543. _RegexAction.ERROR,
  544. "String contains invalid escape code",
  545. ),
  546. _RegexRule("WSTRING_LITERAL", _wstring_literal, _RegexAction.TOKEN, None),
  547. _RegexRule("U8STRING_LITERAL", _u8string_literal, _RegexAction.TOKEN, None),
  548. _RegexRule("U16STRING_LITERAL", _u16string_literal, _RegexAction.TOKEN, None),
  549. _RegexRule("U32STRING_LITERAL", _u32string_literal, _RegexAction.TOKEN, None),
  550. _RegexRule("STRING_LITERAL", _string_literal, _RegexAction.TOKEN, None),
  551. _RegexRule("HEX_FLOAT_CONST", _hex_floating_constant, _RegexAction.TOKEN, None),
  552. _RegexRule("FLOAT_CONST", _floating_constant, _RegexAction.TOKEN, None),
  553. _RegexRule("INT_CONST_HEX", _hex_constant, _RegexAction.TOKEN, None),
  554. _RegexRule("INT_CONST_BIN", _bin_constant, _RegexAction.TOKEN, None),
  555. _RegexRule(
  556. "BAD_CONST_OCT",
  557. _bad_octal_constant,
  558. _RegexAction.ERROR,
  559. "Invalid octal constant",
  560. ),
  561. _RegexRule("INT_CONST_OCT", _octal_constant, _RegexAction.TOKEN, None),
  562. _RegexRule("INT_CONST_DEC", _decimal_constant, _RegexAction.TOKEN, None),
  563. _RegexRule("INT_CONST_CHAR", _multicharacter_constant, _RegexAction.TOKEN, None),
  564. _RegexRule("CHAR_CONST", _char_const, _RegexAction.TOKEN, None),
  565. _RegexRule("WCHAR_CONST", _wchar_const, _RegexAction.TOKEN, None),
  566. _RegexRule("U8CHAR_CONST", _u8char_const, _RegexAction.TOKEN, None),
  567. _RegexRule("U16CHAR_CONST", _u16char_const, _RegexAction.TOKEN, None),
  568. _RegexRule("U32CHAR_CONST", _u32char_const, _RegexAction.TOKEN, None),
  569. _RegexRule("UNMATCHED_QUOTE", _unmatched_quote, _RegexAction.ERROR, "Unmatched '"),
  570. _RegexRule("BAD_CHAR_CONST", _bad_char_const, _RegexAction.ERROR, None),
  571. _RegexRule("ID", _identifier, _RegexAction.ID, None),
  572. ]
  573. _regex_actions: dict[str, tuple[_RegexAction, str | None]] = {}
  574. _regex_pattern_parts: list[str] = []
  575. for _rule in _regex_rules:
  576. _regex_actions[_rule.tok_type] = (_rule.action, _rule.error_message)
  577. _regex_pattern_parts.append(f"(?P<{_rule.tok_type}>{_rule.regex_pattern})")
  578. # The master regex is a single alternation of all token patterns, each wrapped
  579. # in a named group. We match once at the current position and then use
  580. # `lastgroup` to recover which token kind fired; this avoids iterating over all
  581. # regexes on every character while keeping the same token-level semantics.
  582. _regex_master: re.Pattern[str] = re.compile("|".join(_regex_pattern_parts))
  583. @dataclass(frozen=True)
  584. class _FixedToken:
  585. tok_type: str
  586. literal: str
  587. _fixed_tokens: list[_FixedToken] = [
  588. _FixedToken("ELLIPSIS", "..."),
  589. _FixedToken("LSHIFTEQUAL", "<<="),
  590. _FixedToken("RSHIFTEQUAL", ">>="),
  591. _FixedToken("PLUSPLUS", "++"),
  592. _FixedToken("MINUSMINUS", "--"),
  593. _FixedToken("ARROW", "->"),
  594. _FixedToken("LAND", "&&"),
  595. _FixedToken("LOR", "||"),
  596. _FixedToken("LSHIFT", "<<"),
  597. _FixedToken("RSHIFT", ">>"),
  598. _FixedToken("LE", "<="),
  599. _FixedToken("GE", ">="),
  600. _FixedToken("EQ", "=="),
  601. _FixedToken("NE", "!="),
  602. _FixedToken("TIMESEQUAL", "*="),
  603. _FixedToken("DIVEQUAL", "/="),
  604. _FixedToken("MODEQUAL", "%="),
  605. _FixedToken("PLUSEQUAL", "+="),
  606. _FixedToken("MINUSEQUAL", "-="),
  607. _FixedToken("ANDEQUAL", "&="),
  608. _FixedToken("OREQUAL", "|="),
  609. _FixedToken("XOREQUAL", "^="),
  610. _FixedToken("EQUALS", "="),
  611. _FixedToken("PLUS", "+"),
  612. _FixedToken("MINUS", "-"),
  613. _FixedToken("TIMES", "*"),
  614. _FixedToken("DIVIDE", "/"),
  615. _FixedToken("MOD", "%"),
  616. _FixedToken("OR", "|"),
  617. _FixedToken("AND", "&"),
  618. _FixedToken("NOT", "~"),
  619. _FixedToken("XOR", "^"),
  620. _FixedToken("LNOT", "!"),
  621. _FixedToken("LT", "<"),
  622. _FixedToken("GT", ">"),
  623. _FixedToken("CONDOP", "?"),
  624. _FixedToken("LPAREN", "("),
  625. _FixedToken("RPAREN", ")"),
  626. _FixedToken("LBRACKET", "["),
  627. _FixedToken("RBRACKET", "]"),
  628. _FixedToken("LBRACE", "{"),
  629. _FixedToken("RBRACE", "}"),
  630. _FixedToken("COMMA", ","),
  631. _FixedToken("PERIOD", "."),
  632. _FixedToken("SEMI", ";"),
  633. _FixedToken("COLON", ":"),
  634. ]
  635. # To avoid scanning all fixed tokens on every character, we bucket them by the
  636. # first character. When matching at position i, we only look at the bucket for
  637. # text[i], and we pre-sort that bucket by token length so the first match is
  638. # also the longest. This preserves longest-match semantics (e.g. '>>=' before
  639. # '>>' before '>') while reducing the number of comparisons.
  640. _fixed_tokens_by_first: dict[str, list[_FixedToken]] = {}
  641. for _entry in _fixed_tokens:
  642. _fixed_tokens_by_first.setdefault(_entry.literal[0], []).append(_entry)
  643. for _bucket in _fixed_tokens_by_first.values():
  644. _bucket.sort(key=lambda item: len(item.literal), reverse=True)
  645. _line_pattern: re.Pattern[str] = re.compile(r"([ \t]*line\W)|([ \t]*\d+)")
  646. _pragma_pattern: re.Pattern[str] = re.compile(r"[ \t]*pragma\W")