1
0

glibcpp.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. #! /usr/bin/python3
  2. # Approximation to C preprocessing.
  3. # Copyright (C) 2019-2026 Free Software Foundation, Inc.
  4. # This file is part of the GNU C Library.
  5. #
  6. # The GNU C Library is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU Lesser General Public
  8. # License as published by the Free Software Foundation; either
  9. # version 2.1 of the License, or (at your option) any later version.
  10. #
  11. # The GNU C Library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. # Lesser General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Lesser General Public
  17. # License along with the GNU C Library; if not, see
  18. # <https://www.gnu.org/licenses/>.
  19. """
  20. Simplified lexical analyzer for C preprocessing tokens.
  21. Does not implement trigraphs.
  22. Does not implement backslash-newline in the middle of any lexical
  23. item other than a string literal.
  24. Does not implement universal-character-names in identifiers.
  25. Treats prefixed strings (e.g. L"...") as two tokens (L and "...").
  26. Accepts non-ASCII characters only within comments and strings.
  27. """
  28. import collections
  29. import operator
  30. import re
  31. import sys
  32. # Caution: The order of the outermost alternation matters.
  33. # STRING must be before BAD_STRING, CHARCONST before BAD_CHARCONST,
  34. # BLOCK_COMMENT before BAD_BLOCK_COM before PUNCTUATOR, and OTHER must
  35. # be last.
  36. # Caution: There should be no capturing groups other than the named
  37. # captures in the outermost alternation.
  38. # For reference, these are all of the C punctuators as of C11:
  39. # [ ] ( ) { } , ; ? ~
  40. # ! != * *= / /= ^ ^= = ==
  41. # # ##
  42. # % %= %> %: %:%:
  43. # & &= &&
  44. # | |= ||
  45. # + += ++
  46. # - -= -- ->
  47. # . ...
  48. # : :>
  49. # < <% <: << <<= <=
  50. # > >= >> >>=
  51. # The BAD_* tokens are not part of the official definition of pp-tokens;
  52. # they match unclosed strings, character constants, and block comments,
  53. # so that the regex engine doesn't have to backtrack all the way to the
  54. # beginning of a broken construct and then emit dozens of junk tokens.
  55. PP_TOKEN_RE_ = re.compile(r"""
  56. (?P<STRING> \"(?:[^\"\\\r\n]|\\(?:[\r\n -~]|\r\n))*\")
  57. |(?P<BAD_STRING> \"(?:[^\"\\\r\n]|\\[ -~])*)
  58. |(?P<CHARCONST> \'(?:[^\'\\\r\n]|\\(?:[\r\n -~]|\r\n))*\')
  59. |(?P<BAD_CHARCONST> \'(?:[^\'\\\r\n]|\\[ -~])*)
  60. |(?P<BLOCK_COMMENT> /\*(?:\*(?!/)|[^*])*\*/)
  61. |(?P<BAD_BLOCK_COM> /\*(?:\*(?!/)|[^*])*\*?)
  62. |(?P<LINE_COMMENT> //[^\r\n]*)
  63. |(?P<IDENT> [_a-zA-Z][_a-zA-Z0-9]*)
  64. |(?P<PP_NUMBER> \.?[0-9](?:[0-9a-df-oq-zA-DF-OQ-Z_.]|[eEpP][+-]?)*)
  65. |(?P<PUNCTUATOR>
  66. [,;?~(){}\[\]]
  67. | [!*/^=]=?
  68. | \#\#?
  69. | %(?:[=>]|:(?:%:)?)?
  70. | &[=&]?
  71. |\|[=|]?
  72. |\+[=+]?
  73. | -[=->]?
  74. |\.(?:\.\.)?
  75. | :>?
  76. | <(?:[%:]|<(?:=|<=?)?)?
  77. | >(?:=|>=?)?)
  78. |(?P<ESCNL> \\(?:\r|\n|\r\n))
  79. |(?P<WHITESPACE> [ \t\n\r\v\f]+)
  80. |(?P<OTHER> .)
  81. """, re.DOTALL | re.VERBOSE)
  82. HEADER_NAME_RE_ = re.compile(r"""
  83. < [^>\r\n]+ >
  84. | " [^"\r\n]+ "
  85. """, re.DOTALL | re.VERBOSE)
  86. ENDLINE_RE_ = re.compile(r"""\r|\n|\r\n""")
  87. # based on the sample code in the Python re documentation
  88. Token_ = collections.namedtuple("Token", (
  89. "kind", "text", "line", "column", "context"))
  90. Token_.__doc__ = """
  91. One C preprocessing token, comment, or chunk of whitespace.
  92. 'kind' identifies the token type, which will be one of:
  93. STRING, CHARCONST, BLOCK_COMMENT, LINE_COMMENT, IDENT,
  94. PP_NUMBER, PUNCTUATOR, ESCNL, WHITESPACE, HEADER_NAME,
  95. or OTHER. The BAD_* alternatives in PP_TOKEN_RE_ are
  96. handled within tokenize_c, below.
  97. 'text' is the sequence of source characters making up the token;
  98. no decoding whatsoever is performed.
  99. 'line' and 'column' give the position of the first character of the
  100. token within the source file. They are both 1-based.
  101. 'context' indicates whether or not this token occurred within a
  102. preprocessing directive; it will be None for running text,
  103. '<null>' for the leading '#' of a directive line (because '#'
  104. all by itself on a line is a "null directive"), or the name of
  105. the directive for tokens within a directive line, starting with
  106. the IDENT for the name itself.
  107. """
  108. def tokenize_c(file_contents, reporter):
  109. """Yield a series of Token objects, one for each preprocessing
  110. token, comment, or chunk of whitespace within FILE_CONTENTS.
  111. The REPORTER object is expected to have one method,
  112. reporter.error(token, message), which will be called to
  113. indicate a lexical error at the position of TOKEN.
  114. If MESSAGE contains the four-character sequence '{!r}', that
  115. is expected to be replaced by repr(token.text).
  116. """
  117. Token = Token_
  118. PP_TOKEN_RE = PP_TOKEN_RE_
  119. ENDLINE_RE = ENDLINE_RE_
  120. HEADER_NAME_RE = HEADER_NAME_RE_
  121. line_num = 1
  122. line_start = 0
  123. pos = 0
  124. limit = len(file_contents)
  125. directive = None
  126. at_bol = True
  127. while pos < limit:
  128. if directive == "include":
  129. mo = HEADER_NAME_RE.match(file_contents, pos)
  130. if mo:
  131. kind = "HEADER_NAME"
  132. directive = "after_include"
  133. else:
  134. mo = PP_TOKEN_RE.match(file_contents, pos)
  135. kind = mo.lastgroup
  136. if kind != "WHITESPACE":
  137. directive = "after_include"
  138. else:
  139. mo = PP_TOKEN_RE.match(file_contents, pos)
  140. kind = mo.lastgroup
  141. text = mo.group()
  142. line = line_num
  143. column = mo.start() - line_start
  144. adj_line_start = 0
  145. # only these kinds can contain a newline
  146. if kind in ("WHITESPACE", "BLOCK_COMMENT", "LINE_COMMENT",
  147. "STRING", "CHARCONST", "BAD_BLOCK_COM", "ESCNL"):
  148. for tmo in ENDLINE_RE.finditer(text):
  149. line_num += 1
  150. adj_line_start = tmo.end()
  151. if adj_line_start:
  152. line_start = mo.start() + adj_line_start
  153. # Track whether or not we are scanning a preprocessing directive.
  154. if kind == "LINE_COMMENT" or (kind == "WHITESPACE" and adj_line_start):
  155. at_bol = True
  156. directive = None
  157. else:
  158. if kind == "PUNCTUATOR" and text == "#" and at_bol:
  159. directive = "<null>"
  160. elif kind == "IDENT" and directive == "<null>":
  161. directive = text
  162. at_bol = False
  163. # Report ill-formed tokens and rewrite them as their well-formed
  164. # equivalents, so downstream processing doesn't have to know about them.
  165. # (Rewriting instead of discarding provides better error recovery.)
  166. if kind == "BAD_BLOCK_COM":
  167. reporter.error(Token("BAD_BLOCK_COM", "", line, column+1, ""),
  168. "unclosed block comment")
  169. text += "*/"
  170. kind = "BLOCK_COMMENT"
  171. elif kind == "BAD_STRING":
  172. reporter.error(Token("BAD_STRING", "", line, column+1, ""),
  173. "unclosed string")
  174. text += "\""
  175. kind = "STRING"
  176. elif kind == "BAD_CHARCONST":
  177. reporter.error(Token("BAD_CHARCONST", "", line, column+1, ""),
  178. "unclosed char constant")
  179. text += "'"
  180. kind = "CHARCONST"
  181. tok = Token(kind, text, line, column+1,
  182. "include" if directive == "after_include" else directive)
  183. # Do not complain about OTHER tokens inside macro definitions.
  184. # $ and @ appear in macros defined by headers intended to be
  185. # included from assembly language, e.g. sysdeps/mips/sys/asm.h.
  186. if kind == "OTHER" and directive != "define":
  187. self.error(tok, "stray {!r} in program")
  188. yield tok
  189. pos = mo.end()
  190. class MacroDefinition(collections.namedtuple('MacroDefinition',
  191. 'name_token args body error')):
  192. """A preprocessor macro definition.
  193. name_token is the Token_ for the name.
  194. args is None for a macro that is not function-like. Otherwise, it
  195. is a tuple that contains the macro argument name tokens.
  196. body is a tuple that contains the tokens that constitute the body
  197. of the macro definition (excluding whitespace).
  198. error is None if no error was detected, or otherwise a problem
  199. description associated with this macro definition.
  200. """
  201. @property
  202. def function(self):
  203. """Return true if the macro is function-like."""
  204. return self.args is not None
  205. @property
  206. def name(self):
  207. """Return the name of the macro being defined."""
  208. return self.name_token.text
  209. @property
  210. def line(self):
  211. """Return the line number of the macro definition."""
  212. return self.name_token.line
  213. @property
  214. def args_lowered(self):
  215. """Return the macro argument list as a list of strings"""
  216. if self.function:
  217. return [token.text for token in self.args]
  218. else:
  219. return None
  220. @property
  221. def body_lowered(self):
  222. """Return the macro body as a list of strings."""
  223. return [token.text for token in self.body]
  224. def macro_definitions(tokens):
  225. """A generator for C macro definitions among tokens.
  226. The generator yields MacroDefinition objects.
  227. tokens must be iterable, yielding Token_ objects.
  228. """
  229. macro_name = None
  230. macro_start = False # Set to false after macro name and one otken.
  231. macro_args = None # Set to a list during the macro argument sequence.
  232. in_macro_args = False # True while processing macro identifier-list.
  233. error = None
  234. body = []
  235. for token in tokens:
  236. if token.context == 'define' and macro_name is None \
  237. and token.kind == 'IDENT':
  238. # Starting up macro processing.
  239. if macro_start:
  240. # First identifier is the macro name.
  241. macro_name = token
  242. else:
  243. # Next token is the name.
  244. macro_start = True
  245. continue
  246. if macro_name is None:
  247. # Drop tokens not in macro definitions.
  248. continue
  249. if token.context != 'define':
  250. # End of the macro definition.
  251. if in_macro_args and error is None:
  252. error = 'macro definition ends in macro argument list'
  253. yield MacroDefinition(macro_name, macro_args, tuple(body), error)
  254. # No longer in a macro definition.
  255. macro_name = None
  256. macro_start = False
  257. macro_args = None
  258. in_macro_args = False
  259. error = None
  260. body.clear()
  261. continue
  262. if macro_start:
  263. # First token after the macro name.
  264. macro_start = False
  265. if token.kind == 'PUNCTUATOR' and token.text == '(':
  266. macro_args = []
  267. in_macro_args = True
  268. continue
  269. if in_macro_args:
  270. if token.kind == 'IDENT' \
  271. or (token.kind == 'PUNCTUATOR' and token.text == '...'):
  272. # Macro argument or ... placeholder.
  273. macro_args.append(token)
  274. if token.kind == 'PUNCTUATOR':
  275. if token.text == ')':
  276. macro_args = tuple(macro_args)
  277. in_macro_args = False
  278. elif token.text == ',':
  279. pass # Skip. Not a full syntax check.
  280. elif error is None:
  281. error = 'invalid punctuator in macro argument list: ' \
  282. + repr(token.text)
  283. elif error is None:
  284. error = 'invalid {} token in macro argument list'.format(
  285. token.kind)
  286. continue
  287. if token.kind not in ('WHITESPACE', 'BLOCK_COMMENT'):
  288. body.append(token)
  289. # Emit the macro in case the last line does not end with a newline.
  290. if macro_name is not None:
  291. if in_macro_args and error is None:
  292. error = 'macro definition ends in macro argument list'
  293. yield MacroDefinition(macro_name, macro_args, tuple(body), error)
  294. # Used to split UL etc. suffixes from numbers such as 123UL.
  295. RE_SPLIT_INTEGER_SUFFIX = re.compile(r'([^ullULL]+)([ullULL]*)')
  296. BINARY_OPERATORS = {
  297. '+': operator.add,
  298. '<<': operator.lshift,
  299. '|': operator.or_,
  300. }
  301. # Use the general-purpose dict type if it is order-preserving.
  302. if (sys.version_info[0], sys.version_info[1]) <= (3, 6):
  303. OrderedDict = collections.OrderedDict
  304. else:
  305. OrderedDict = dict
  306. def macro_eval(macro_defs, reporter):
  307. """Compute macro values
  308. macro_defs is the output from macro_definitions. reporter is an
  309. object that accepts reporter.error(line_number, message) and
  310. reporter.note(line_number, message) calls to report errors
  311. and error context invocations.
  312. The returned dict contains the values of macros which are not
  313. function-like, pairing their names with their computed values.
  314. The current implementation is incomplete. It is deliberately not
  315. entirely faithful to C, even in the implemented parts. It checks
  316. that macro replacements follow certain syntactic rules even if
  317. they are never evaluated.
  318. """
  319. # Unevaluated macro definitions by name.
  320. definitions = OrderedDict()
  321. for md in macro_defs:
  322. if md.name in definitions:
  323. reporter.error(md.line, 'macro {} redefined'.format(md.name))
  324. reporter.note(definitions[md.name].line,
  325. 'location of previous definition')
  326. else:
  327. definitions[md.name] = md
  328. # String to value mappings for fully evaluated macros.
  329. evaluated = OrderedDict()
  330. # String to macro definitions during evaluation. Nice error
  331. # reporting relies on deterministic iteration order.
  332. stack = OrderedDict()
  333. def eval_token(current, token):
  334. """Evaluate one macro token.
  335. Integers and strings are returned as such (the latter still
  336. quoted). Identifiers are expanded.
  337. None indicates an empty expansion or an error.
  338. """
  339. if token.kind == 'PP_NUMBER':
  340. value = None
  341. m = RE_SPLIT_INTEGER_SUFFIX.match(token.text)
  342. if m:
  343. try:
  344. value = int(m.group(1), 0)
  345. except ValueError:
  346. pass
  347. if value is None:
  348. reporter.error(token.line,
  349. 'invalid number {!r} in definition of {}'.format(
  350. token.text, current.name))
  351. return value
  352. if token.kind == 'STRING':
  353. return token.text
  354. if token.kind == 'CHARCONST' and len(token.text) == 3:
  355. return ord(token.text[1])
  356. if token.kind == 'IDENT':
  357. name = token.text
  358. result = eval1(current, name)
  359. if name not in evaluated:
  360. evaluated[name] = result
  361. return result
  362. reporter.error(token.line,
  363. 'unrecognized {!r} in definition of {}'.format(
  364. token.text, current.name))
  365. return None
  366. def eval1(current, name):
  367. """Evaluate one name.
  368. The name is looked up and the macro definition evaluated
  369. recursively if necessary. The current argument is the macro
  370. definition being evaluated.
  371. None as a return value indicates an error.
  372. """
  373. # Fast path if the value has already been evaluated.
  374. if name in evaluated:
  375. return evaluated[name]
  376. try:
  377. md = definitions[name]
  378. except KeyError:
  379. reporter.error(current.line,
  380. 'reference to undefined identifier {} in definition of {}'
  381. .format(name, current.name))
  382. return None
  383. if md.name in stack:
  384. # Recursive macro definition.
  385. md = stack[name]
  386. reporter.error(md.line,
  387. 'macro definition {} refers to itself'.format(md.name))
  388. for md1 in reversed(list(stack.values())):
  389. if md1 is md:
  390. break
  391. reporter.note(md1.line,
  392. 'evaluated from {}'.format(md1.name))
  393. return None
  394. stack[md.name] = md
  395. if md.function:
  396. reporter.error(current.line,
  397. 'attempt to evaluate function-like macro {}'.format(name))
  398. reporter.note(md.line, 'definition of {}'.format(md.name))
  399. return None
  400. try:
  401. body = md.body
  402. if len(body) == 0:
  403. # Empty expansion.
  404. return None
  405. # Remove surrounding ().
  406. if body[0].text == '(' and body[-1].text == ')':
  407. body = body[1:-1]
  408. had_parens = True
  409. else:
  410. had_parens = False
  411. if len(body) == 1:
  412. return eval_token(md, body[0])
  413. # Minimal expression evaluator for binary operators.
  414. op = body[1].text
  415. if len(body) == 3 and op in BINARY_OPERATORS:
  416. if not had_parens:
  417. reporter.error(body[1].line,
  418. 'missing parentheses around {} expression'.format(op))
  419. reporter.note(md.line,
  420. 'in definition of macro {}'.format(md.name))
  421. left = eval_token(md, body[0])
  422. right = eval_token(md, body[2])
  423. if type(left) != type(1):
  424. reporter.error(left.line,
  425. 'left operand of {} is not an integer'.format(op))
  426. reporter.note(md.line,
  427. 'in definition of macro {}'.format(md.name))
  428. if type(right) != type(1):
  429. reporter.error(left.line,
  430. 'right operand of {} is not an integer'.format(op))
  431. reporter.note(md.line,
  432. 'in definition of macro {}'.format(md.name))
  433. return BINARY_OPERATORS[op](left, right)
  434. reporter.error(md.line,
  435. 'uninterpretable macro token sequence: {}'.format(
  436. ' '.join(md.body_lowered)))
  437. return None
  438. finally:
  439. del stack[md.name]
  440. # Start of main body of macro_eval.
  441. for md in definitions.values():
  442. name = md.name
  443. if name not in evaluated and not md.function:
  444. evaluated[name] = eval1(md, name)
  445. return evaluated