c_parser.py 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464
  1. # ------------------------------------------------------------------------------
  2. # pycparser: c_parser.py
  3. #
  4. # Recursive-descent parser for the C language.
  5. #
  6. # Eli Bendersky [https://eli.thegreenplace.net/]
  7. # License: BSD
  8. # ------------------------------------------------------------------------------
  9. from dataclasses import dataclass
  10. from typing import (
  11. Any,
  12. Literal,
  13. NoReturn,
  14. Optional,
  15. TypedDict,
  16. cast,
  17. )
  18. from . import c_ast
  19. from .ast_transforms import fix_atomic_specifiers, fix_switch_cases
  20. from .c_lexer import CLexer, Token
  21. @dataclass
  22. class Coord:
  23. """Coordinates of a syntactic element. Consists of:
  24. - File name
  25. - Line number
  26. - Column number
  27. """
  28. file: str
  29. line: int
  30. column: int | None = None
  31. def __str__(self) -> str:
  32. text = f"{self.file}:{self.line}"
  33. if self.column is not None:
  34. text += f":{self.column}"
  35. return text
  36. class ParseError(Exception):
  37. pass
  38. class CParser:
  39. """Recursive-descent C parser.
  40. Usage:
  41. parser = CParser()
  42. ast = parser.parse(text, filename)
  43. The `lexer` parameter lets you inject a lexer class (defaults to CLexer).
  44. The parameters after `lexer` are accepted for backward compatibility with
  45. the old PLY-based parser and are otherwise unused.
  46. """
  47. def __init__(
  48. self,
  49. lex_optimize: bool = True,
  50. lexer: type[CLexer] = CLexer,
  51. lextab: str = "pycparser.lextab",
  52. yacc_optimize: bool = True,
  53. yacctab: str = "pycparser.yacctab",
  54. yacc_debug: bool = False,
  55. taboutputdir: str = "",
  56. ) -> None:
  57. self.clex: CLexer = lexer(
  58. error_func=self._lex_error_func,
  59. on_lbrace_func=self._lex_on_lbrace_func,
  60. on_rbrace_func=self._lex_on_rbrace_func,
  61. type_lookup_func=self._lex_type_lookup_func,
  62. )
  63. # Stack of scopes for keeping track of symbols. _scope_stack[-1] is
  64. # the current (topmost) scope. Each scope is a dictionary that
  65. # specifies whether a name is a type. If _scope_stack[n][name] is
  66. # True, 'name' is currently a type in the scope. If it's False,
  67. # 'name' is defined in the scope but not as a type (for instance, if we
  68. # saw: int name;)
  69. # If 'name' is not a key in _scope_stack[n] then 'name' was not defined
  70. # in this scope at all.
  71. self._scope_stack: list[dict[str, bool]] = [{}]
  72. self._tokens: _TokenStream = _TokenStream(self.clex)
  73. def parse(
  74. self, text: str, filename: str = "", debug: bool = False
  75. ) -> c_ast.FileAST:
  76. """Parses C code and returns an AST.
  77. text:
  78. A string containing the C source code
  79. filename:
  80. Name of the file being parsed (for meaningful error messages)
  81. debug:
  82. Deprecated debug flag (unused); for backwards compatibility.
  83. """
  84. self._scope_stack = [{}]
  85. self.clex.input(text, filename)
  86. self._tokens = _TokenStream(self.clex)
  87. ast = self._parse_translation_unit_or_empty()
  88. tok = self._peek()
  89. if tok is not None:
  90. self._parse_error(f"before: {tok.value}", self._tok_coord(tok))
  91. return ast
  92. # ------------------------------------------------------------------
  93. # Scope and declaration helpers
  94. # ------------------------------------------------------------------
  95. def _coord(self, lineno: int, column: int | None = None) -> Coord:
  96. return Coord(file=self.clex.filename, line=lineno, column=column)
  97. def _parse_error(self, msg: str, coord: Coord | str | None) -> NoReturn:
  98. raise ParseError(f"{coord}: {msg}")
  99. def _push_scope(self) -> None:
  100. self._scope_stack.append({})
  101. def _pop_scope(self) -> None:
  102. if len(self._scope_stack) <= 1:
  103. raise ParseError("Unmatched '}'")
  104. self._scope_stack.pop()
  105. def _add_typedef_name(self, name: str, coord: Coord | None) -> None:
  106. """Add a new typedef name (ie a TYPEID) to the current scope"""
  107. if not self._scope_stack[-1].get(name, True):
  108. self._parse_error(
  109. f"Typedef {name!r} previously declared as non-typedef in this scope",
  110. coord,
  111. )
  112. self._scope_stack[-1][name] = True
  113. def _add_identifier(self, name: str, coord: Coord | None) -> None:
  114. """Add a new object, function, or enum member name (ie an ID) to the
  115. current scope
  116. """
  117. if self._scope_stack[-1].get(name, False):
  118. self._parse_error(
  119. f"Non-typedef {name!r} previously declared as typedef in this scope",
  120. coord,
  121. )
  122. self._scope_stack[-1][name] = False
  123. def _is_type_in_scope(self, name: str) -> bool:
  124. """Is *name* a typedef-name in the current scope?"""
  125. for scope in reversed(self._scope_stack):
  126. # If name is an identifier in this scope it shadows typedefs in
  127. # higher scopes.
  128. if name in scope:
  129. return scope[name]
  130. return False
  131. def _lex_error_func(self, msg: str, line: int, column: int) -> None:
  132. self._parse_error(msg, self._coord(line, column))
  133. def _lex_on_lbrace_func(self) -> None:
  134. self._push_scope()
  135. def _lex_on_rbrace_func(self) -> None:
  136. self._pop_scope()
  137. def _lex_type_lookup_func(self, name: str) -> bool:
  138. """Looks up types that were previously defined with typedef.
  139. Passed to the lexer for recognizing identifiers that are types.
  140. """
  141. return self._is_type_in_scope(name)
  142. # To understand what's going on here, read sections A.8.5 and
  143. # A.8.6 of K&R2 very carefully.
  144. #
  145. # A C type consists of a basic type declaration, with a list
  146. # of modifiers. For example:
  147. #
  148. # int *c[5];
  149. #
  150. # The basic declaration here is 'int c', and the pointer and
  151. # the array are the modifiers.
  152. #
  153. # Basic declarations are represented by TypeDecl (from module c_ast) and the
  154. # modifiers are FuncDecl, PtrDecl and ArrayDecl.
  155. #
  156. # The standard states that whenever a new modifier is parsed, it should be
  157. # added to the end of the list of modifiers. For example:
  158. #
  159. # K&R2 A.8.6.2: Array Declarators
  160. #
  161. # In a declaration T D where D has the form
  162. # D1 [constant-expression-opt]
  163. # and the type of the identifier in the declaration T D1 is
  164. # "type-modifier T", the type of the
  165. # identifier of D is "type-modifier array of T"
  166. #
  167. # This is what this method does. The declarator it receives
  168. # can be a list of declarators ending with TypeDecl. It
  169. # tacks the modifier to the end of this list, just before
  170. # the TypeDecl.
  171. #
  172. # Additionally, the modifier may be a list itself. This is
  173. # useful for pointers, that can come as a chain from the rule
  174. # p_pointer. In this case, the whole modifier list is spliced
  175. # into the new location.
  176. def _type_modify_decl(self, decl: Any, modifier: Any) -> c_ast.Node:
  177. """Tacks a type modifier on a declarator, and returns
  178. the modified declarator.
  179. Note: the declarator and modifier may be modified
  180. """
  181. modifier_head = modifier
  182. modifier_tail = modifier
  183. # The modifier may be a nested list. Reach its tail.
  184. while modifier_tail.type:
  185. modifier_tail = modifier_tail.type
  186. # If the decl is a basic type, just tack the modifier onto it.
  187. if isinstance(decl, c_ast.TypeDecl):
  188. modifier_tail.type = decl
  189. return modifier
  190. else:
  191. # Otherwise, the decl is a list of modifiers. Reach
  192. # its tail and splice the modifier onto the tail,
  193. # pointing to the underlying basic type.
  194. decl_tail = decl
  195. while not isinstance(decl_tail.type, c_ast.TypeDecl):
  196. decl_tail = decl_tail.type
  197. modifier_tail.type = decl_tail.type
  198. decl_tail.type = modifier_head
  199. return decl
  200. # Due to the order in which declarators are constructed,
  201. # they have to be fixed in order to look like a normal AST.
  202. #
  203. # When a declaration arrives from syntax construction, it has
  204. # these problems:
  205. # * The innermost TypeDecl has no type (because the basic
  206. # type is only known at the uppermost declaration level)
  207. # * The declaration has no variable name, since that is saved
  208. # in the innermost TypeDecl
  209. # * The typename of the declaration is a list of type
  210. # specifiers, and not a node. Here, basic identifier types
  211. # should be separated from more complex types like enums
  212. # and structs.
  213. #
  214. # This method fixes these problems.
  215. def _fix_decl_name_type(
  216. self,
  217. decl: c_ast.Decl | c_ast.Typedef | c_ast.Typename,
  218. typename: list[Any],
  219. ) -> c_ast.Decl | c_ast.Typedef | c_ast.Typename:
  220. """Fixes a declaration. Modifies decl."""
  221. # Reach the underlying basic type
  222. typ = decl
  223. while not isinstance(typ, c_ast.TypeDecl):
  224. typ = typ.type
  225. decl.name = typ.declname
  226. typ.quals = decl.quals[:]
  227. # The typename is a list of types. If any type in this
  228. # list isn't an IdentifierType, it must be the only
  229. # type in the list (it's illegal to declare "int enum ..")
  230. # If all the types are basic, they're collected in the
  231. # IdentifierType holder.
  232. for tn in typename:
  233. if not isinstance(tn, c_ast.IdentifierType):
  234. if len(typename) > 1:
  235. self._parse_error("Invalid multiple types specified", tn.coord)
  236. else:
  237. typ.type = tn
  238. # Normalize atomic specifiers for declarations and type
  239. # names alike (casts, sizeof, unnamed parameters, etc.).
  240. return fix_atomic_specifiers(decl)
  241. if not typename:
  242. # Functions default to returning int
  243. if not isinstance(decl.type, c_ast.FuncDecl):
  244. self._parse_error("Missing type in declaration", decl.coord)
  245. typ.type = c_ast.IdentifierType(["int"], coord=decl.coord)
  246. else:
  247. # At this point, we know that typename is a list of IdentifierType
  248. # nodes. Concatenate all the names into a single list.
  249. typ.type = c_ast.IdentifierType(
  250. [name for id in typename for name in id.names], coord=typename[0].coord
  251. )
  252. return decl
  253. def _add_declaration_specifier(
  254. self,
  255. declspec: Optional["_DeclSpec"],
  256. newspec: Any,
  257. kind: "_DeclSpecKind",
  258. append: bool = False,
  259. ) -> "_DeclSpec":
  260. """See _DeclSpec for the specifier dictionary layout."""
  261. if declspec is None:
  262. spec: _DeclSpec = {
  263. "qual": [],
  264. "storage": [],
  265. "type": [],
  266. "function": [],
  267. "alignment": [],
  268. }
  269. else:
  270. spec = declspec
  271. if append:
  272. spec[kind].append(newspec)
  273. else:
  274. spec[kind].insert(0, newspec)
  275. return spec
  276. def _build_declarations(
  277. self,
  278. spec: "_DeclSpec",
  279. decls: list["_DeclInfo"],
  280. typedef_namespace: bool = False,
  281. ) -> list[c_ast.Node]:
  282. """Builds a list of declarations all sharing the given specifiers.
  283. If typedef_namespace is true, each declared name is added
  284. to the "typedef namespace", which also includes objects,
  285. functions, and enum constants.
  286. """
  287. is_typedef = "typedef" in spec["storage"]
  288. declarations = []
  289. # Bit-fields are allowed to be unnamed.
  290. if decls[0].get("bitsize") is None:
  291. # When redeclaring typedef names as identifiers in inner scopes, a
  292. # problem can occur where the identifier gets grouped into
  293. # spec['type'], leaving decl as None. This can only occur for the
  294. # first declarator.
  295. if decls[0]["decl"] is None:
  296. if (
  297. len(spec["type"]) < 2
  298. or len(spec["type"][-1].names) != 1
  299. or not self._is_type_in_scope(spec["type"][-1].names[0])
  300. ):
  301. coord = "?"
  302. for t in spec["type"]:
  303. if hasattr(t, "coord"):
  304. coord = t.coord
  305. break
  306. self._parse_error("Invalid declaration", coord)
  307. # Make this look as if it came from "direct_declarator:ID"
  308. decls[0]["decl"] = c_ast.TypeDecl(
  309. declname=spec["type"][-1].names[0],
  310. type=None,
  311. quals=None,
  312. align=spec["alignment"],
  313. coord=spec["type"][-1].coord,
  314. )
  315. # Remove the "new" type's name from the end of spec['type']
  316. del spec["type"][-1]
  317. # A similar problem can occur where the declaration ends up
  318. # looking like an abstract declarator. Give it a name if this is
  319. # the case.
  320. elif not isinstance(
  321. decls[0]["decl"],
  322. (c_ast.Enum, c_ast.Struct, c_ast.Union, c_ast.IdentifierType),
  323. ):
  324. decls_0_tail = cast(Any, decls[0]["decl"])
  325. while not isinstance(decls_0_tail, c_ast.TypeDecl):
  326. decls_0_tail = decls_0_tail.type
  327. if decls_0_tail.declname is None:
  328. decls_0_tail.declname = spec["type"][-1].names[0]
  329. del spec["type"][-1]
  330. for decl in decls:
  331. assert decl["decl"] is not None
  332. if is_typedef:
  333. declaration = c_ast.Typedef(
  334. name=None,
  335. quals=spec["qual"],
  336. storage=spec["storage"],
  337. type=decl["decl"],
  338. coord=decl["decl"].coord,
  339. )
  340. else:
  341. declaration = c_ast.Decl(
  342. name=None,
  343. quals=spec["qual"],
  344. align=spec["alignment"],
  345. storage=spec["storage"],
  346. funcspec=spec["function"],
  347. type=decl["decl"],
  348. init=decl.get("init"),
  349. bitsize=decl.get("bitsize"),
  350. coord=decl["decl"].coord,
  351. )
  352. if isinstance(
  353. declaration.type,
  354. (c_ast.Enum, c_ast.Struct, c_ast.Union, c_ast.IdentifierType),
  355. ):
  356. fixed_decl = declaration
  357. else:
  358. fixed_decl = self._fix_decl_name_type(declaration, spec["type"])
  359. # Add the type name defined by typedef to a
  360. # symbol table (for usage in the lexer)
  361. if typedef_namespace:
  362. if is_typedef:
  363. self._add_typedef_name(fixed_decl.name, fixed_decl.coord)
  364. else:
  365. self._add_identifier(fixed_decl.name, fixed_decl.coord)
  366. declarations.append(fixed_decl)
  367. return declarations
  368. def _build_function_definition(
  369. self,
  370. spec: "_DeclSpec",
  371. decl: c_ast.Node,
  372. param_decls: list[c_ast.Node] | None,
  373. body: c_ast.Node,
  374. ) -> c_ast.Node:
  375. """Builds a function definition."""
  376. if "typedef" in spec["storage"]:
  377. self._parse_error("Invalid typedef", decl.coord)
  378. declaration = self._build_declarations(
  379. spec=spec,
  380. decls=[{"decl": decl, "init": None, "bitsize": None}],
  381. typedef_namespace=True,
  382. )[0]
  383. return c_ast.FuncDef(
  384. decl=declaration, param_decls=param_decls, body=body, coord=decl.coord
  385. )
  386. def _select_struct_union_class(self, token: str) -> type:
  387. """Given a token (either STRUCT or UNION), selects the
  388. appropriate AST class.
  389. """
  390. if token == "struct":
  391. return c_ast.Struct
  392. else:
  393. return c_ast.Union
  394. # ------------------------------------------------------------------
  395. # Token helpers
  396. # ------------------------------------------------------------------
  397. def _peek(self, k: int = 1) -> Token | None:
  398. """Return the k-th next token without consuming it (1-based)."""
  399. return self._tokens.peek(k)
  400. def _peek_type(self, k: int = 1) -> str | None:
  401. """Return the type of the k-th next token, or None if absent (1-based)."""
  402. tok = self._peek(k)
  403. return tok.type if tok is not None else None
  404. def _advance(self) -> Token:
  405. tok = self._tokens.next()
  406. if tok is None:
  407. self._parse_error("At end of input", self.clex.filename)
  408. else:
  409. return tok
  410. def _accept(self, token_type: str) -> Token | None:
  411. """Conditionally consume next token, only if it's of token_type.
  412. If it is of the expected type, consume and return it.
  413. Otherwise, leaves the token intact and returns None.
  414. """
  415. tok = self._peek()
  416. if tok is not None and tok.type == token_type:
  417. return self._advance()
  418. return None
  419. def _expect(self, token_type: str) -> Token:
  420. tok = self._advance()
  421. if tok.type != token_type:
  422. self._parse_error(f"before: {tok.value}", self._tok_coord(tok))
  423. return tok
  424. def _mark(self) -> int:
  425. return self._tokens.mark()
  426. def _reset(self, mark: int) -> None:
  427. self._tokens.reset(mark)
  428. def _tok_coord(self, tok: Token) -> Coord:
  429. return self._coord(tok.lineno, tok.column)
  430. def _starts_declaration(self, tok: Token | None = None) -> bool:
  431. tok = tok or self._peek()
  432. if tok is None:
  433. return False
  434. return tok.type in _DECL_START
  435. def _starts_expression(self, tok: Token | None = None) -> bool:
  436. tok = tok or self._peek()
  437. if tok is None:
  438. return False
  439. return tok.type in _STARTS_EXPRESSION
  440. def _starts_statement(self) -> bool:
  441. tok_type = self._peek_type()
  442. if tok_type is None:
  443. return False
  444. if tok_type in _STARTS_STATEMENT:
  445. return True
  446. return self._starts_expression()
  447. def _starts_declarator(self, id_only: bool = False) -> bool:
  448. tok_type = self._peek_type()
  449. if tok_type is None:
  450. return False
  451. if tok_type in {"TIMES", "LPAREN"}:
  452. return True
  453. if id_only:
  454. return tok_type == "ID"
  455. return tok_type in {"ID", "TYPEID"}
  456. def _peek_declarator_name_info(self) -> tuple[str | None, bool]:
  457. mark = self._mark()
  458. tok_type, saw_paren = self._scan_declarator_name_info()
  459. self._reset(mark)
  460. return tok_type, saw_paren
  461. def _parse_any_declarator(
  462. self, allow_abstract: bool = False, typeid_paren_as_abstract: bool = False
  463. ) -> tuple[c_ast.Node | None, bool]:
  464. # C declarators are ambiguous without lookahead. For example:
  465. # int foo(int (aa)); -> aa is a name (ID)
  466. # typedef char TT;
  467. # int bar(int (TT)); -> TT is a type (TYPEID) in parens
  468. name_type, saw_paren = self._peek_declarator_name_info()
  469. if name_type is None or (
  470. typeid_paren_as_abstract and name_type == "TYPEID" and saw_paren
  471. ):
  472. if not allow_abstract:
  473. tok = self._peek()
  474. coord = self._tok_coord(tok) if tok is not None else self.clex.filename
  475. self._parse_error("Invalid declarator", coord)
  476. decl = self._parse_abstract_declarator_opt()
  477. return decl, False
  478. if name_type == "TYPEID":
  479. if typeid_paren_as_abstract:
  480. decl = self._parse_typeid_noparen_declarator()
  481. else:
  482. decl = self._parse_typeid_declarator()
  483. else:
  484. decl = self._parse_id_declarator()
  485. return decl, True
  486. def _scan_declarator_name_info(self) -> tuple[str | None, bool]:
  487. saw_paren = False
  488. while self._accept("TIMES"):
  489. while self._peek_type() in _TYPE_QUALIFIER:
  490. self._advance()
  491. tok = self._peek()
  492. if tok is None:
  493. return None, saw_paren
  494. if tok.type in {"ID", "TYPEID"}:
  495. self._advance()
  496. return tok.type, saw_paren
  497. if tok.type == "LPAREN":
  498. saw_paren = True
  499. self._advance()
  500. tok_type, nested_paren = self._scan_declarator_name_info()
  501. if nested_paren:
  502. saw_paren = True
  503. depth = 1
  504. while True:
  505. tok = self._peek()
  506. if tok is None:
  507. return None, saw_paren
  508. if tok.type == "LPAREN":
  509. depth += 1
  510. elif tok.type == "RPAREN":
  511. depth -= 1
  512. self._advance()
  513. if depth == 0:
  514. break
  515. continue
  516. self._advance()
  517. return tok_type, saw_paren
  518. return None, saw_paren
  519. def _starts_direct_abstract_declarator(self) -> bool:
  520. return self._peek_type() in {"LPAREN", "LBRACKET"}
  521. def _is_assignment_op(self) -> bool:
  522. tok = self._peek()
  523. return tok is not None and tok.type in _ASSIGNMENT_OPS
  524. def _try_parse_paren_type_name(
  525. self,
  526. ) -> tuple[c_ast.Typename, int, Token] | None:
  527. """Parse and return a parenthesized type name if present.
  528. Returns (typ, mark, lparen_tok) when the next tokens look like
  529. '(' type_name ')', where typ is the parsed type name, mark is the
  530. token-stream position before parsing, and lparen_tok is the LPAREN
  531. token. Returns None if no parenthesized type name is present.
  532. """
  533. mark = self._mark()
  534. lparen_tok = self._accept("LPAREN")
  535. if lparen_tok is None:
  536. return None
  537. if not self._starts_declaration():
  538. self._reset(mark)
  539. return None
  540. typ = self._parse_type_name()
  541. if self._accept("RPAREN") is None:
  542. self._reset(mark)
  543. return None
  544. return typ, mark, lparen_tok
  545. # ------------------------------------------------------------------
  546. # Top-level
  547. # ------------------------------------------------------------------
  548. # BNF: translation_unit_or_empty : translation_unit | empty
  549. def _parse_translation_unit_or_empty(self) -> c_ast.FileAST:
  550. if self._peek() is None:
  551. return c_ast.FileAST([])
  552. return c_ast.FileAST(self._parse_translation_unit())
  553. # BNF: translation_unit : external_declaration+
  554. def _parse_translation_unit(self) -> list[c_ast.Node]:
  555. ext = []
  556. while self._peek() is not None:
  557. ext.extend(self._parse_external_declaration())
  558. return ext
  559. # BNF: external_declaration : function_definition
  560. # | declaration
  561. # | pp_directive
  562. # | pppragma_directive
  563. # | static_assert
  564. # | ';'
  565. def _parse_external_declaration(self) -> list[c_ast.Node]:
  566. tok = self._peek()
  567. if tok is None:
  568. return []
  569. if tok.type == "PPHASH":
  570. self._parse_pp_directive()
  571. return []
  572. if tok.type in {"PPPRAGMA", "_PRAGMA"}:
  573. return [self._parse_pppragma_directive()]
  574. if self._accept("SEMI"):
  575. return []
  576. if tok.type == "_STATIC_ASSERT":
  577. return [self._parse_static_assert()]
  578. if not self._starts_declaration(tok):
  579. # Special handling for old-style function definitions that have an
  580. # implicit return type, e.g.
  581. #
  582. # foo() {
  583. # return 5;
  584. # }
  585. #
  586. # These get an implicit 'int' return type.
  587. decl = self._parse_id_declarator()
  588. param_decls = None
  589. if self._peek_type() != "LBRACE":
  590. self._parse_error("Invalid function definition", decl.coord)
  591. spec: _DeclSpec = {
  592. "qual": [],
  593. "alignment": [],
  594. "storage": [],
  595. "type": [c_ast.IdentifierType(["int"], coord=decl.coord)],
  596. "function": [],
  597. }
  598. func = self._build_function_definition(
  599. spec=spec,
  600. decl=decl,
  601. param_decls=param_decls,
  602. body=self._parse_compound_statement(),
  603. )
  604. return [func]
  605. # From here on, parsing a standard declatation/definition.
  606. spec, saw_type, spec_coord = self._parse_declaration_specifiers(
  607. allow_no_type=True
  608. )
  609. name_type, _ = self._peek_declarator_name_info()
  610. if name_type != "ID":
  611. decls = self._parse_decl_body_with_spec(spec, saw_type)
  612. self._expect("SEMI")
  613. return decls
  614. decl = self._parse_id_declarator()
  615. if self._peek_type() == "LBRACE" or self._starts_declaration():
  616. param_decls = None
  617. if self._starts_declaration():
  618. param_decls = self._parse_declaration_list()
  619. if self._peek_type() != "LBRACE":
  620. self._parse_error("Invalid function definition", decl.coord)
  621. if not spec["type"]:
  622. spec["type"] = [c_ast.IdentifierType(["int"], coord=spec_coord)]
  623. func = self._build_function_definition(
  624. spec=spec,
  625. decl=decl,
  626. param_decls=param_decls,
  627. body=self._parse_compound_statement(),
  628. )
  629. return [func]
  630. decl_dict: _DeclInfo = {"decl": decl, "init": None, "bitsize": None}
  631. if self._accept("EQUALS"):
  632. decl_dict["init"] = self._parse_initializer()
  633. decls = self._parse_init_declarator_list(first=decl_dict)
  634. decls = self._build_declarations(spec=spec, decls=decls, typedef_namespace=True)
  635. self._expect("SEMI")
  636. return decls
  637. # ------------------------------------------------------------------
  638. # Declarations
  639. #
  640. # Declarations always come as lists (because they can be several in one
  641. # line). When returning parsed declarations, a list is always returned -
  642. # even if it contains a single element.
  643. # ------------------------------------------------------------------
  644. # BNF: declaration : decl_body ';' | static_assert
  645. def _parse_declaration(self) -> list[c_ast.Node]:
  646. if self._peek_type() == "_STATIC_ASSERT":
  647. return [self._parse_static_assert()]
  648. decls = self._parse_decl_body()
  649. self._expect("SEMI")
  650. return decls
  651. # BNF: decl_body : declaration_specifiers decl_body_with_spec
  652. def _parse_decl_body(self) -> list[c_ast.Node]:
  653. spec, saw_type, _ = self._parse_declaration_specifiers(allow_no_type=True)
  654. return self._parse_decl_body_with_spec(spec, saw_type)
  655. # BNF: decl_body_with_spec : init_declarator_list
  656. # | struct_or_union_or_enum_only
  657. def _parse_decl_body_with_spec(
  658. self, spec: "_DeclSpec", saw_type: bool
  659. ) -> list[c_ast.Node]:
  660. # saw_type is True if the specifiers included an actual type (as
  661. # opposed to only storage/function/qualifiers).
  662. decl_infos: list[_DeclInfo] | None = None
  663. if saw_type:
  664. if self._starts_declarator():
  665. decl_infos = self._parse_init_declarator_list()
  666. else:
  667. if self._starts_declarator(id_only=True):
  668. decl_infos = self._parse_init_declarator_list(id_only=True)
  669. decls: list[c_ast.Node]
  670. if decl_infos is None:
  671. ty = spec["type"]
  672. s_u_or_e = (c_ast.Struct, c_ast.Union, c_ast.Enum)
  673. if len(ty) == 1 and isinstance(ty[0], s_u_or_e):
  674. decls = [
  675. c_ast.Decl(
  676. name=None,
  677. quals=spec["qual"],
  678. align=spec["alignment"],
  679. storage=spec["storage"],
  680. funcspec=spec["function"],
  681. type=ty[0],
  682. init=None,
  683. bitsize=None,
  684. coord=ty[0].coord,
  685. )
  686. ]
  687. else:
  688. decls = self._build_declarations(
  689. spec=spec,
  690. decls=[{"decl": None, "init": None, "bitsize": None}],
  691. typedef_namespace=True,
  692. )
  693. else:
  694. decls = self._build_declarations(
  695. spec=spec, decls=decl_infos, typedef_namespace=True
  696. )
  697. return decls
  698. # BNF: declaration_list : declaration+
  699. def _parse_declaration_list(self) -> list[c_ast.Node]:
  700. decls = []
  701. while self._starts_declaration():
  702. decls.extend(self._parse_declaration())
  703. return decls
  704. # BNF: declaration_specifiers : (storage_class_specifier
  705. # | type_specifier
  706. # | type_qualifier
  707. # | function_specifier
  708. # | alignment_specifier)+
  709. def _parse_declaration_specifiers(
  710. self, allow_no_type: bool = False
  711. ) -> tuple["_DeclSpec", bool, Coord | None]:
  712. """Parse declaration-specifier sequence.
  713. allow_no_type:
  714. If True, allow a missing type specifier without error.
  715. Returns:
  716. (spec, saw_type, first_coord) where spec is a dict with
  717. qual/storage/type/function/alignment entries, saw_type is True
  718. if a type specifier was consumed, and first_coord is the coord
  719. of the first specifier token (used for diagnostics).
  720. """
  721. spec = None
  722. saw_type = False
  723. first_coord = None
  724. while True:
  725. tok = self._peek()
  726. if tok is None:
  727. break
  728. if tok.type == "_ALIGNAS":
  729. if first_coord is None:
  730. first_coord = self._tok_coord(tok)
  731. spec = self._add_declaration_specifier(
  732. spec, self._parse_alignment_specifier(), "alignment", append=True
  733. )
  734. continue
  735. if tok.type == "_ATOMIC" and self._peek_type(2) == "LPAREN":
  736. if first_coord is None:
  737. first_coord = self._tok_coord(tok)
  738. spec = self._add_declaration_specifier(
  739. spec, self._parse_atomic_specifier(), "type", append=True
  740. )
  741. saw_type = True
  742. continue
  743. if tok.type in _TYPE_QUALIFIER:
  744. if first_coord is None:
  745. first_coord = self._tok_coord(tok)
  746. spec = self._add_declaration_specifier(
  747. spec, self._advance().value, "qual", append=True
  748. )
  749. continue
  750. if tok.type in _STORAGE_CLASS:
  751. if first_coord is None:
  752. first_coord = self._tok_coord(tok)
  753. spec = self._add_declaration_specifier(
  754. spec, self._advance().value, "storage", append=True
  755. )
  756. continue
  757. if tok.type in _FUNCTION_SPEC:
  758. if first_coord is None:
  759. first_coord = self._tok_coord(tok)
  760. spec = self._add_declaration_specifier(
  761. spec, self._advance().value, "function", append=True
  762. )
  763. continue
  764. if tok.type in _TYPE_SPEC_SIMPLE:
  765. if first_coord is None:
  766. first_coord = self._tok_coord(tok)
  767. tok = self._advance()
  768. spec = self._add_declaration_specifier(
  769. spec,
  770. c_ast.IdentifierType([tok.value], coord=self._tok_coord(tok)),
  771. "type",
  772. append=True,
  773. )
  774. saw_type = True
  775. continue
  776. if tok.type == "TYPEID":
  777. if saw_type:
  778. break
  779. if first_coord is None:
  780. first_coord = self._tok_coord(tok)
  781. tok = self._advance()
  782. spec = self._add_declaration_specifier(
  783. spec,
  784. c_ast.IdentifierType([tok.value], coord=self._tok_coord(tok)),
  785. "type",
  786. append=True,
  787. )
  788. saw_type = True
  789. continue
  790. if tok.type in {"STRUCT", "UNION"}:
  791. if first_coord is None:
  792. first_coord = self._tok_coord(tok)
  793. spec = self._add_declaration_specifier(
  794. spec, self._parse_struct_or_union_specifier(), "type", append=True
  795. )
  796. saw_type = True
  797. continue
  798. if tok.type == "ENUM":
  799. if first_coord is None:
  800. first_coord = self._tok_coord(tok)
  801. spec = self._add_declaration_specifier(
  802. spec, self._parse_enum_specifier(), "type", append=True
  803. )
  804. saw_type = True
  805. continue
  806. break
  807. if spec is None:
  808. self._parse_error("Invalid declaration", self.clex.filename)
  809. if not saw_type and not allow_no_type:
  810. self._parse_error("Missing type in declaration", first_coord)
  811. return spec, saw_type, first_coord
  812. # BNF: specifier_qualifier_list : (type_specifier
  813. # | type_qualifier
  814. # | alignment_specifier)+
  815. def _parse_specifier_qualifier_list(self) -> "_DeclSpec":
  816. spec = None
  817. saw_type = False
  818. saw_alignment = False
  819. first_coord = None
  820. while True:
  821. tok = self._peek()
  822. if tok is None:
  823. break
  824. if tok.type == "_ALIGNAS":
  825. if first_coord is None:
  826. first_coord = self._tok_coord(tok)
  827. spec = self._add_declaration_specifier(
  828. spec, self._parse_alignment_specifier(), "alignment", append=True
  829. )
  830. saw_alignment = True
  831. continue
  832. if tok.type == "_ATOMIC" and self._peek_type(2) == "LPAREN":
  833. if first_coord is None:
  834. first_coord = self._tok_coord(tok)
  835. spec = self._add_declaration_specifier(
  836. spec, self._parse_atomic_specifier(), "type", append=True
  837. )
  838. saw_type = True
  839. continue
  840. if tok.type in _TYPE_QUALIFIER:
  841. if first_coord is None:
  842. first_coord = self._tok_coord(tok)
  843. spec = self._add_declaration_specifier(
  844. spec, self._advance().value, "qual", append=True
  845. )
  846. continue
  847. if tok.type in _TYPE_SPEC_SIMPLE:
  848. if first_coord is None:
  849. first_coord = self._tok_coord(tok)
  850. tok = self._advance()
  851. spec = self._add_declaration_specifier(
  852. spec,
  853. c_ast.IdentifierType([tok.value], coord=self._tok_coord(tok)),
  854. "type",
  855. append=True,
  856. )
  857. saw_type = True
  858. continue
  859. if tok.type == "TYPEID":
  860. if saw_type:
  861. break
  862. if first_coord is None:
  863. first_coord = self._tok_coord(tok)
  864. tok = self._advance()
  865. spec = self._add_declaration_specifier(
  866. spec,
  867. c_ast.IdentifierType([tok.value], coord=self._tok_coord(tok)),
  868. "type",
  869. append=True,
  870. )
  871. saw_type = True
  872. continue
  873. if tok.type in {"STRUCT", "UNION"}:
  874. if first_coord is None:
  875. first_coord = self._tok_coord(tok)
  876. spec = self._add_declaration_specifier(
  877. spec, self._parse_struct_or_union_specifier(), "type", append=True
  878. )
  879. saw_type = True
  880. continue
  881. if tok.type == "ENUM":
  882. if first_coord is None:
  883. first_coord = self._tok_coord(tok)
  884. spec = self._add_declaration_specifier(
  885. spec, self._parse_enum_specifier(), "type", append=True
  886. )
  887. saw_type = True
  888. continue
  889. break
  890. if spec is None:
  891. self._parse_error("Invalid specifier list", self.clex.filename)
  892. if not saw_type and not saw_alignment:
  893. self._parse_error("Missing type in declaration", first_coord)
  894. if spec.get("storage") is None:
  895. spec["storage"] = []
  896. if spec.get("function") is None:
  897. spec["function"] = []
  898. return spec
  899. # BNF: type_qualifier_list : type_qualifier+
  900. def _parse_type_qualifier_list(self) -> list[str]:
  901. quals = []
  902. while self._peek_type() in _TYPE_QUALIFIER:
  903. quals.append(self._advance().value)
  904. return quals
  905. # BNF: alignment_specifier : _ALIGNAS '(' type_name | constant_expression ')'
  906. def _parse_alignment_specifier(self) -> c_ast.Node:
  907. tok = self._expect("_ALIGNAS")
  908. self._expect("LPAREN")
  909. if self._starts_declaration():
  910. typ = self._parse_type_name()
  911. self._expect("RPAREN")
  912. return c_ast.Alignas(typ, self._tok_coord(tok))
  913. expr = self._parse_constant_expression()
  914. self._expect("RPAREN")
  915. return c_ast.Alignas(expr, self._tok_coord(tok))
  916. # BNF: atomic_specifier : _ATOMIC '(' type_name ')'
  917. def _parse_atomic_specifier(self) -> c_ast.Node:
  918. self._expect("_ATOMIC")
  919. self._expect("LPAREN")
  920. typ = self._parse_type_name()
  921. self._expect("RPAREN")
  922. typ.quals.append("_Atomic")
  923. return typ
  924. # BNF: init_declarator_list : init_declarator (',' init_declarator)*
  925. def _parse_init_declarator_list(
  926. self, first: Optional["_DeclInfo"] = None, id_only: bool = False
  927. ) -> list["_DeclInfo"]:
  928. decls = (
  929. [first]
  930. if first is not None
  931. else [self._parse_init_declarator(id_only=id_only)]
  932. )
  933. while self._accept("COMMA"):
  934. decls.append(self._parse_init_declarator(id_only=id_only))
  935. return decls
  936. # BNF: init_declarator : declarator ('=' initializer)?
  937. def _parse_init_declarator(self, id_only: bool = False) -> "_DeclInfo":
  938. decl = self._parse_id_declarator() if id_only else self._parse_declarator()
  939. init = None
  940. if self._accept("EQUALS"):
  941. init = self._parse_initializer()
  942. return {"decl": decl, "init": init, "bitsize": None}
  943. # ------------------------------------------------------------------
  944. # Structs/unions/enums
  945. # ------------------------------------------------------------------
  946. # BNF: struct_or_union_specifier : struct_or_union ID? '{' struct_declaration_list? '}'
  947. # | struct_or_union ID
  948. def _parse_struct_or_union_specifier(self) -> c_ast.Node:
  949. tok = self._advance()
  950. klass = self._select_struct_union_class(tok.value)
  951. if self._peek_type() in {"ID", "TYPEID"}:
  952. name_tok = self._advance()
  953. if self._peek_type() == "LBRACE":
  954. self._advance()
  955. if self._accept("RBRACE"):
  956. return klass(
  957. name=name_tok.value, decls=[], coord=self._tok_coord(name_tok)
  958. )
  959. decls = self._parse_struct_declaration_list()
  960. self._expect("RBRACE")
  961. return klass(
  962. name=name_tok.value, decls=decls, coord=self._tok_coord(name_tok)
  963. )
  964. return klass(
  965. name=name_tok.value, decls=None, coord=self._tok_coord(name_tok)
  966. )
  967. if self._peek_type() == "LBRACE":
  968. brace_tok = self._advance()
  969. if self._accept("RBRACE"):
  970. return klass(name=None, decls=[], coord=self._tok_coord(brace_tok))
  971. decls = self._parse_struct_declaration_list()
  972. self._expect("RBRACE")
  973. return klass(name=None, decls=decls, coord=self._tok_coord(brace_tok))
  974. self._parse_error("Invalid struct/union declaration", self._tok_coord(tok))
  975. # BNF: struct_declaration_list : struct_declaration+
  976. def _parse_struct_declaration_list(self) -> list[c_ast.Node]:
  977. decls = []
  978. while self._peek_type() not in {None, "RBRACE"}:
  979. items = self._parse_struct_declaration()
  980. if items is None:
  981. continue
  982. decls.extend(items)
  983. return decls
  984. # BNF: struct_declaration : specifier_qualifier_list struct_declarator_list? ';'
  985. # | static_assert
  986. # | pppragma_directive
  987. def _parse_struct_declaration(self) -> list[c_ast.Node] | None:
  988. if self._peek_type() == "_STATIC_ASSERT":
  989. return [self._parse_static_assert()]
  990. if self._peek_type() == "SEMI":
  991. self._advance()
  992. return None
  993. if self._peek_type() in {"PPPRAGMA", "_PRAGMA"}:
  994. return [self._parse_pppragma_directive()]
  995. spec = self._parse_specifier_qualifier_list()
  996. assert "typedef" not in spec.get("storage", [])
  997. decls = None
  998. if self._starts_declarator() or self._peek_type() == "COLON":
  999. decls = self._parse_struct_declarator_list()
  1000. if decls is not None:
  1001. self._expect("SEMI")
  1002. return self._build_declarations(spec=spec, decls=decls)
  1003. if len(spec["type"]) == 1:
  1004. node = spec["type"][0]
  1005. if isinstance(node, c_ast.Node):
  1006. decl_type = node
  1007. else:
  1008. decl_type = c_ast.IdentifierType(node)
  1009. self._expect("SEMI")
  1010. return self._build_declarations(
  1011. spec=spec,
  1012. decls=[{"decl": decl_type, "init": None, "bitsize": None}],
  1013. )
  1014. self._expect("SEMI")
  1015. return self._build_declarations(
  1016. spec=spec, decls=[{"decl": None, "init": None, "bitsize": None}]
  1017. )
  1018. # BNF: struct_declarator_list : struct_declarator (',' struct_declarator)*
  1019. def _parse_struct_declarator_list(self) -> list["_DeclInfo"]:
  1020. decls = [self._parse_struct_declarator()]
  1021. while self._accept("COMMA"):
  1022. decls.append(self._parse_struct_declarator())
  1023. return decls
  1024. # BNF: struct_declarator : declarator? ':' constant_expression
  1025. # | declarator (':' constant_expression)?
  1026. def _parse_struct_declarator(self) -> "_DeclInfo":
  1027. if self._accept("COLON"):
  1028. bitsize = self._parse_constant_expression()
  1029. return {
  1030. "decl": c_ast.TypeDecl(None, None, None, None),
  1031. "init": None,
  1032. "bitsize": bitsize,
  1033. }
  1034. decl = self._parse_declarator()
  1035. if self._accept("COLON"):
  1036. bitsize = self._parse_constant_expression()
  1037. return {"decl": decl, "init": None, "bitsize": bitsize}
  1038. return {"decl": decl, "init": None, "bitsize": None}
  1039. # BNF: enum_specifier : ENUM ID? '{' enumerator_list? '}'
  1040. # | ENUM ID
  1041. def _parse_enum_specifier(self) -> c_ast.Node:
  1042. tok = self._expect("ENUM")
  1043. if self._peek_type() in {"ID", "TYPEID"}:
  1044. name_tok = self._advance()
  1045. if self._peek_type() == "LBRACE":
  1046. self._advance()
  1047. enums = self._parse_enumerator_list()
  1048. self._expect("RBRACE")
  1049. return c_ast.Enum(name_tok.value, enums, self._tok_coord(tok))
  1050. return c_ast.Enum(name_tok.value, None, self._tok_coord(tok))
  1051. self._expect("LBRACE")
  1052. enums = self._parse_enumerator_list()
  1053. self._expect("RBRACE")
  1054. return c_ast.Enum(None, enums, self._tok_coord(tok))
  1055. # BNF: enumerator_list : enumerator (',' enumerator)* ','?
  1056. def _parse_enumerator_list(self) -> c_ast.Node:
  1057. enum = self._parse_enumerator()
  1058. enum_list = c_ast.EnumeratorList([enum], enum.coord)
  1059. while self._accept("COMMA"):
  1060. if self._peek_type() == "RBRACE":
  1061. break
  1062. enum = self._parse_enumerator()
  1063. enum_list.enumerators.append(enum)
  1064. return enum_list
  1065. # BNF: enumerator : ID ('=' constant_expression)?
  1066. def _parse_enumerator(self) -> c_ast.Node:
  1067. name_tok = self._expect("ID")
  1068. if self._accept("EQUALS"):
  1069. value = self._parse_constant_expression()
  1070. else:
  1071. value = None
  1072. enum = c_ast.Enumerator(name_tok.value, value, self._tok_coord(name_tok))
  1073. self._add_identifier(enum.name, enum.coord)
  1074. return enum
  1075. # ------------------------------------------------------------------
  1076. # Declarators
  1077. # ------------------------------------------------------------------
  1078. # BNF: declarator : pointer? direct_declarator
  1079. def _parse_declarator(self) -> c_ast.Node:
  1080. decl, _ = self._parse_any_declarator(
  1081. allow_abstract=False, typeid_paren_as_abstract=False
  1082. )
  1083. assert decl is not None
  1084. return decl
  1085. # BNF: id_declarator : declarator with ID name
  1086. def _parse_id_declarator(self) -> c_ast.Node:
  1087. return self._parse_declarator_kind(kind="id", allow_paren=True)
  1088. # BNF: typeid_declarator : declarator with TYPEID name
  1089. def _parse_typeid_declarator(self) -> c_ast.Node:
  1090. return self._parse_declarator_kind(kind="typeid", allow_paren=True)
  1091. # BNF: typeid_noparen_declarator : declarator without parenthesized name
  1092. def _parse_typeid_noparen_declarator(self) -> c_ast.Node:
  1093. return self._parse_declarator_kind(kind="typeid", allow_paren=False)
  1094. # BNF: declarator_kind : pointer? direct_declarator(kind)
  1095. def _parse_declarator_kind(self, kind: str, allow_paren: bool) -> c_ast.Node:
  1096. ptr = None
  1097. if self._peek_type() == "TIMES":
  1098. ptr = self._parse_pointer()
  1099. direct = self._parse_direct_declarator(kind, allow_paren=allow_paren)
  1100. if ptr is not None:
  1101. return self._type_modify_decl(direct, ptr)
  1102. return direct
  1103. # BNF: direct_declarator : ID | TYPEID | '(' declarator ')'
  1104. # | direct_declarator '[' ... ']'
  1105. # | direct_declarator '(' ... ')'
  1106. def _parse_direct_declarator(
  1107. self, kind: str, allow_paren: bool = True
  1108. ) -> c_ast.Node:
  1109. if allow_paren and self._accept("LPAREN"):
  1110. decl = self._parse_declarator_kind(kind, allow_paren=True)
  1111. self._expect("RPAREN")
  1112. else:
  1113. if kind == "id":
  1114. name_tok = self._expect("ID")
  1115. else:
  1116. name_tok = self._expect("TYPEID")
  1117. decl = c_ast.TypeDecl(
  1118. declname=name_tok.value,
  1119. type=None,
  1120. quals=None,
  1121. align=None,
  1122. coord=self._tok_coord(name_tok),
  1123. )
  1124. return self._parse_decl_suffixes(decl)
  1125. def _parse_decl_suffixes(self, decl: c_ast.Node) -> c_ast.Node:
  1126. """Parse a chain of array/function suffixes and attach them to decl."""
  1127. while True:
  1128. if self._peek_type() == "LBRACKET":
  1129. decl = self._type_modify_decl(decl, self._parse_array_decl(decl))
  1130. continue
  1131. if self._peek_type() == "LPAREN":
  1132. func = self._parse_function_decl(decl)
  1133. decl = self._type_modify_decl(decl, func)
  1134. continue
  1135. break
  1136. return decl
  1137. # BNF: array_decl : '[' array_specifiers? assignment_expression? ']'
  1138. def _parse_array_decl(self, base_decl: c_ast.Node) -> c_ast.Node:
  1139. return self._parse_array_decl_common(base_type=None, coord=base_decl.coord)
  1140. def _parse_array_decl_common(
  1141. self, base_type: c_ast.Node | None, coord: Coord | None = None
  1142. ) -> c_ast.Node:
  1143. """Parse an array declarator suffix and return an ArrayDecl node.
  1144. base_type:
  1145. Base declarator node to attach (None for direct-declarator parsing,
  1146. TypeDecl for abstract declarators).
  1147. coord:
  1148. Coordinate to use for the ArrayDecl. If None, uses the '[' token.
  1149. """
  1150. lbrack_tok = self._expect("LBRACKET")
  1151. if coord is None:
  1152. coord = self._tok_coord(lbrack_tok)
  1153. def make_array_decl(dim, dim_quals):
  1154. return c_ast.ArrayDecl(
  1155. type=base_type, dim=dim, dim_quals=dim_quals, coord=coord
  1156. )
  1157. if self._accept("STATIC"):
  1158. dim_quals = ["static"] + (self._parse_type_qualifier_list() or [])
  1159. dim = self._parse_assignment_expression()
  1160. self._expect("RBRACKET")
  1161. return make_array_decl(dim, dim_quals)
  1162. if self._peek_type() in _TYPE_QUALIFIER:
  1163. dim_quals = self._parse_type_qualifier_list() or []
  1164. if self._accept("STATIC"):
  1165. dim_quals = dim_quals + ["static"]
  1166. dim = self._parse_assignment_expression()
  1167. self._expect("RBRACKET")
  1168. return make_array_decl(dim, dim_quals)
  1169. times_tok = self._accept("TIMES")
  1170. if times_tok:
  1171. self._expect("RBRACKET")
  1172. dim = c_ast.ID(times_tok.value, self._tok_coord(times_tok))
  1173. return make_array_decl(dim, dim_quals)
  1174. dim = None
  1175. if self._starts_expression():
  1176. dim = self._parse_assignment_expression()
  1177. self._expect("RBRACKET")
  1178. return make_array_decl(dim, dim_quals)
  1179. times_tok = self._accept("TIMES")
  1180. if times_tok:
  1181. self._expect("RBRACKET")
  1182. dim = c_ast.ID(times_tok.value, self._tok_coord(times_tok))
  1183. return make_array_decl(dim, [])
  1184. dim = None
  1185. if self._starts_expression():
  1186. dim = self._parse_assignment_expression()
  1187. self._expect("RBRACKET")
  1188. return make_array_decl(dim, [])
  1189. # BNF: function_decl : '(' parameter_type_list_opt | identifier_list_opt ')'
  1190. def _parse_function_decl(self, base_decl: c_ast.Node) -> c_ast.Node:
  1191. self._expect("LPAREN")
  1192. if self._accept("RPAREN"):
  1193. args = None
  1194. else:
  1195. args = (
  1196. self._parse_parameter_type_list()
  1197. if self._starts_declaration()
  1198. else self._parse_identifier_list_opt()
  1199. )
  1200. self._expect("RPAREN")
  1201. func = c_ast.FuncDecl(args=args, type=None, coord=base_decl.coord)
  1202. if self._peek_type() == "LBRACE" and func.args is not None:
  1203. for param in func.args.params:
  1204. if isinstance(param, c_ast.EllipsisParam):
  1205. break
  1206. name = getattr(param, "name", None)
  1207. if name:
  1208. self._add_identifier(name, param.coord)
  1209. return func
  1210. # BNF: pointer : '*' type_qualifier_list? pointer?
  1211. def _parse_pointer(self) -> c_ast.Node | None:
  1212. stars = []
  1213. times_tok = self._accept("TIMES")
  1214. while times_tok:
  1215. quals = self._parse_type_qualifier_list() or []
  1216. stars.append((quals, self._tok_coord(times_tok)))
  1217. times_tok = self._accept("TIMES")
  1218. if not stars:
  1219. return None
  1220. ptr = None
  1221. for quals, coord in stars:
  1222. ptr = c_ast.PtrDecl(quals=quals, type=ptr, coord=coord)
  1223. return ptr
  1224. # BNF: parameter_type_list : parameter_list (',' ELLIPSIS)?
  1225. def _parse_parameter_type_list(self) -> c_ast.ParamList:
  1226. params = self._parse_parameter_list()
  1227. if self._peek_type() == "COMMA" and self._peek_type(2) == "ELLIPSIS":
  1228. self._advance()
  1229. ell_tok = self._advance()
  1230. params.params.append(c_ast.EllipsisParam(self._tok_coord(ell_tok)))
  1231. return params
  1232. # BNF: parameter_list : parameter_declaration (',' parameter_declaration)*
  1233. def _parse_parameter_list(self) -> c_ast.ParamList:
  1234. first = self._parse_parameter_declaration()
  1235. params = c_ast.ParamList([first], first.coord)
  1236. while self._peek_type() == "COMMA" and self._peek_type(2) != "ELLIPSIS":
  1237. self._advance()
  1238. params.params.append(self._parse_parameter_declaration())
  1239. return params
  1240. # BNF: parameter_declaration : declaration_specifiers declarator?
  1241. # | declaration_specifiers abstract_declarator_opt
  1242. def _parse_parameter_declaration(self) -> c_ast.Node:
  1243. spec, _, spec_coord = self._parse_declaration_specifiers(allow_no_type=True)
  1244. if not spec["type"]:
  1245. spec["type"] = [c_ast.IdentifierType(["int"], coord=spec_coord)]
  1246. if self._starts_declarator():
  1247. decl, is_named = self._parse_any_declarator(
  1248. allow_abstract=True, typeid_paren_as_abstract=True
  1249. )
  1250. if is_named:
  1251. return self._build_declarations(
  1252. spec=spec,
  1253. decls=[{"decl": decl, "init": None, "bitsize": None}],
  1254. )[0]
  1255. return self._build_parameter_declaration(spec, decl, spec_coord)
  1256. decl = self._parse_abstract_declarator_opt()
  1257. return self._build_parameter_declaration(spec, decl, spec_coord)
  1258. def _build_parameter_declaration(
  1259. self, spec: "_DeclSpec", decl: c_ast.Node | None, spec_coord: Coord | None
  1260. ) -> c_ast.Node:
  1261. if (
  1262. len(spec["type"]) > 1
  1263. and len(spec["type"][-1].names) == 1
  1264. and self._is_type_in_scope(spec["type"][-1].names[0])
  1265. ):
  1266. return self._build_declarations(
  1267. spec=spec, decls=[{"decl": decl, "init": None, "bitsize": None}]
  1268. )[0]
  1269. decl = c_ast.Typename(
  1270. name="",
  1271. quals=spec["qual"],
  1272. align=None,
  1273. type=decl or c_ast.TypeDecl(None, None, None, None),
  1274. coord=spec_coord,
  1275. )
  1276. return self._fix_decl_name_type(decl, spec["type"])
  1277. # BNF: identifier_list_opt : identifier_list | empty
  1278. def _parse_identifier_list_opt(self) -> c_ast.Node | None:
  1279. if self._peek_type() == "RPAREN":
  1280. return None
  1281. return self._parse_identifier_list()
  1282. # BNF: identifier_list : identifier (',' identifier)*
  1283. def _parse_identifier_list(self) -> c_ast.Node:
  1284. first = self._parse_identifier()
  1285. params = c_ast.ParamList([first], first.coord)
  1286. while self._accept("COMMA"):
  1287. params.params.append(self._parse_identifier())
  1288. return params
  1289. # ------------------------------------------------------------------
  1290. # Abstract declarators
  1291. # ------------------------------------------------------------------
  1292. # BNF: type_name : specifier_qualifier_list abstract_declarator_opt
  1293. def _parse_type_name(self) -> c_ast.Typename:
  1294. spec = self._parse_specifier_qualifier_list()
  1295. decl = self._parse_abstract_declarator_opt()
  1296. coord = None
  1297. if decl is not None:
  1298. coord = decl.coord
  1299. elif spec["type"]:
  1300. coord = spec["type"][0].coord
  1301. typename = c_ast.Typename(
  1302. name="",
  1303. quals=spec["qual"][:],
  1304. align=None,
  1305. type=decl or c_ast.TypeDecl(None, None, None, None),
  1306. coord=coord,
  1307. )
  1308. return cast(c_ast.Typename, self._fix_decl_name_type(typename, spec["type"]))
  1309. # BNF: abstract_declarator_opt : pointer? direct_abstract_declarator?
  1310. def _parse_abstract_declarator_opt(self) -> c_ast.Node | None:
  1311. if self._peek_type() == "TIMES":
  1312. ptr = self._parse_pointer()
  1313. if self._starts_direct_abstract_declarator():
  1314. decl = self._parse_direct_abstract_declarator()
  1315. else:
  1316. decl = c_ast.TypeDecl(None, None, None, None)
  1317. assert ptr is not None
  1318. return self._type_modify_decl(decl, ptr)
  1319. if self._starts_direct_abstract_declarator():
  1320. return self._parse_direct_abstract_declarator()
  1321. return None
  1322. # BNF: direct_abstract_declarator : '(' parameter_type_list_opt ')'
  1323. # | '(' abstract_declarator ')'
  1324. # | '[' ... ']'
  1325. def _parse_direct_abstract_declarator(self) -> c_ast.Node:
  1326. lparen_tok = self._accept("LPAREN")
  1327. if lparen_tok:
  1328. if self._starts_declaration() or self._peek_type() == "RPAREN":
  1329. params = self._parse_parameter_type_list_opt()
  1330. self._expect("RPAREN")
  1331. decl = c_ast.FuncDecl(
  1332. args=params,
  1333. type=c_ast.TypeDecl(None, None, None, None),
  1334. coord=self._tok_coord(lparen_tok),
  1335. )
  1336. else:
  1337. decl = self._parse_abstract_declarator_opt()
  1338. self._expect("RPAREN")
  1339. assert decl is not None
  1340. elif self._peek_type() == "LBRACKET":
  1341. decl = self._parse_abstract_array_base()
  1342. else:
  1343. self._parse_error("Invalid abstract declarator", self.clex.filename)
  1344. return self._parse_decl_suffixes(decl)
  1345. # BNF: parameter_type_list_opt : parameter_type_list | empty
  1346. def _parse_parameter_type_list_opt(self) -> c_ast.ParamList | None:
  1347. if self._peek_type() == "RPAREN":
  1348. return None
  1349. return self._parse_parameter_type_list()
  1350. # BNF: abstract_array_base : '[' array_specifiers? assignment_expression? ']'
  1351. def _parse_abstract_array_base(self) -> c_ast.Node:
  1352. return self._parse_array_decl_common(
  1353. base_type=c_ast.TypeDecl(None, None, None, None), coord=None
  1354. )
  1355. # ------------------------------------------------------------------
  1356. # Statements
  1357. # ------------------------------------------------------------------
  1358. # BNF: statement : labeled_statement | compound_statement
  1359. # | selection_statement | iteration_statement
  1360. # | jump_statement | expression_statement
  1361. # | pppragma_directive
  1362. def _parse_statement(self) -> c_ast.Node:
  1363. tok_type = self._peek_type()
  1364. match tok_type:
  1365. case "CASE" | "DEFAULT":
  1366. return self._parse_labeled_statement()
  1367. case "ID" if self._peek_type(2) == "COLON":
  1368. return self._parse_labeled_statement()
  1369. case "LBRACE":
  1370. return self._parse_compound_statement()
  1371. case "IF" | "SWITCH":
  1372. return self._parse_selection_statement()
  1373. case "WHILE" | "DO" | "FOR":
  1374. return self._parse_iteration_statement()
  1375. case "GOTO" | "BREAK" | "CONTINUE" | "RETURN":
  1376. return self._parse_jump_statement()
  1377. case "PPPRAGMA" | "_PRAGMA":
  1378. return self._parse_pppragma_directive()
  1379. case _:
  1380. return self._parse_expression_statement()
  1381. # BNF: pragmacomp_or_statement : pppragma_directive* statement
  1382. def _parse_pragmacomp_or_statement(self) -> c_ast.Node:
  1383. if self._peek_type() in {"PPPRAGMA", "_PRAGMA"}:
  1384. pragmas = self._parse_pppragma_directive_list()
  1385. stmt = self._parse_statement()
  1386. return c_ast.Compound(block_items=pragmas + [stmt], coord=pragmas[0].coord)
  1387. return self._parse_statement()
  1388. # BNF: block_item : declaration | statement
  1389. def _parse_block_item(self) -> c_ast.Node | list[c_ast.Node]:
  1390. if self._peek_type() == "_STATIC_ASSERT":
  1391. return self._parse_static_assert()
  1392. if self._starts_declaration():
  1393. return self._parse_declaration()
  1394. return self._parse_statement()
  1395. # BNF: block_item_list : block_item+
  1396. def _parse_block_item_list(self) -> list[c_ast.Node]:
  1397. items: list[c_ast.Node] = []
  1398. while self._peek_type() not in {"RBRACE", None}:
  1399. item = self._parse_block_item()
  1400. if isinstance(item, c_ast.Node):
  1401. items.append(item)
  1402. elif item != [None]:
  1403. items.extend(item)
  1404. return items
  1405. # BNF: compound_statement : '{' block_item_list? '}'
  1406. def _parse_compound_statement(self) -> c_ast.Node:
  1407. lbrace_tok = self._expect("LBRACE")
  1408. if self._accept("RBRACE"):
  1409. return c_ast.Compound(block_items=None, coord=self._tok_coord(lbrace_tok))
  1410. block_items = self._parse_block_item_list()
  1411. self._expect("RBRACE")
  1412. return c_ast.Compound(
  1413. block_items=block_items, coord=self._tok_coord(lbrace_tok)
  1414. )
  1415. # BNF: labeled_statement : ID ':' statement
  1416. # | CASE constant_expression ':' statement
  1417. # | DEFAULT ':' statement
  1418. def _parse_labeled_statement(self) -> c_ast.Node:
  1419. tok_type = self._peek_type()
  1420. match tok_type:
  1421. case "ID":
  1422. name_tok = self._advance()
  1423. self._expect("COLON")
  1424. if self._starts_statement():
  1425. stmt = self._parse_pragmacomp_or_statement()
  1426. else:
  1427. stmt = c_ast.EmptyStatement(self._tok_coord(name_tok))
  1428. return c_ast.Label(name_tok.value, stmt, self._tok_coord(name_tok))
  1429. case "CASE":
  1430. case_tok = self._advance()
  1431. expr = self._parse_constant_expression()
  1432. self._expect("COLON")
  1433. if self._starts_statement():
  1434. stmt = self._parse_pragmacomp_or_statement()
  1435. else:
  1436. stmt = c_ast.EmptyStatement(self._tok_coord(case_tok))
  1437. return c_ast.Case(expr, [stmt], self._tok_coord(case_tok))
  1438. case "DEFAULT":
  1439. def_tok = self._advance()
  1440. self._expect("COLON")
  1441. if self._starts_statement():
  1442. stmt = self._parse_pragmacomp_or_statement()
  1443. else:
  1444. stmt = c_ast.EmptyStatement(self._tok_coord(def_tok))
  1445. return c_ast.Default([stmt], self._tok_coord(def_tok))
  1446. case _:
  1447. self._parse_error("Invalid labeled statement", self.clex.filename)
  1448. # BNF: selection_statement : IF '(' expression ')' statement (ELSE statement)?
  1449. # | SWITCH '(' expression ')' statement
  1450. def _parse_selection_statement(self) -> c_ast.Node:
  1451. tok = self._advance()
  1452. match tok.type:
  1453. case "IF":
  1454. self._expect("LPAREN")
  1455. cond = self._parse_expression()
  1456. self._expect("RPAREN")
  1457. then_stmt = self._parse_pragmacomp_or_statement()
  1458. if self._accept("ELSE"):
  1459. else_stmt = self._parse_pragmacomp_or_statement()
  1460. return c_ast.If(cond, then_stmt, else_stmt, self._tok_coord(tok))
  1461. return c_ast.If(cond, then_stmt, None, self._tok_coord(tok))
  1462. case "SWITCH":
  1463. self._expect("LPAREN")
  1464. expr = self._parse_expression()
  1465. self._expect("RPAREN")
  1466. stmt = self._parse_pragmacomp_or_statement()
  1467. return fix_switch_cases(c_ast.Switch(expr, stmt, self._tok_coord(tok)))
  1468. case _:
  1469. self._parse_error("Invalid selection statement", self._tok_coord(tok))
  1470. # BNF: iteration_statement : WHILE '(' expression ')' statement
  1471. # | DO statement WHILE '(' expression ')' ';'
  1472. # | FOR '(' (declaration | expression_opt) ';'
  1473. # expression_opt ';' expression_opt ')' statement
  1474. def _parse_iteration_statement(self) -> c_ast.Node:
  1475. tok = self._advance()
  1476. match tok.type:
  1477. case "WHILE":
  1478. self._expect("LPAREN")
  1479. cond = self._parse_expression()
  1480. self._expect("RPAREN")
  1481. stmt = self._parse_pragmacomp_or_statement()
  1482. return c_ast.While(cond, stmt, self._tok_coord(tok))
  1483. case "DO":
  1484. stmt = self._parse_pragmacomp_or_statement()
  1485. self._expect("WHILE")
  1486. self._expect("LPAREN")
  1487. cond = self._parse_expression()
  1488. self._expect("RPAREN")
  1489. self._expect("SEMI")
  1490. return c_ast.DoWhile(cond, stmt, self._tok_coord(tok))
  1491. case "FOR":
  1492. self._expect("LPAREN")
  1493. if self._peek_type() == "_STATIC_ASSERT" or self._starts_declaration():
  1494. decls = self._parse_declaration()
  1495. init = c_ast.DeclList(decls, self._tok_coord(tok))
  1496. cond = self._parse_expression_opt()
  1497. self._expect("SEMI")
  1498. next_expr = self._parse_expression_opt()
  1499. self._expect("RPAREN")
  1500. stmt = self._parse_pragmacomp_or_statement()
  1501. return c_ast.For(init, cond, next_expr, stmt, self._tok_coord(tok))
  1502. init = self._parse_expression_opt()
  1503. self._expect("SEMI")
  1504. cond = self._parse_expression_opt()
  1505. self._expect("SEMI")
  1506. next_expr = self._parse_expression_opt()
  1507. self._expect("RPAREN")
  1508. stmt = self._parse_pragmacomp_or_statement()
  1509. return c_ast.For(init, cond, next_expr, stmt, self._tok_coord(tok))
  1510. case _:
  1511. self._parse_error("Invalid iteration statement", self._tok_coord(tok))
  1512. # BNF: jump_statement : GOTO ID ';' | BREAK ';' | CONTINUE ';'
  1513. # | RETURN expression? ';'
  1514. def _parse_jump_statement(self) -> c_ast.Node:
  1515. tok = self._advance()
  1516. match tok.type:
  1517. case "GOTO":
  1518. name_tok = self._expect("ID")
  1519. self._expect("SEMI")
  1520. return c_ast.Goto(name_tok.value, self._tok_coord(tok))
  1521. case "BREAK":
  1522. self._expect("SEMI")
  1523. return c_ast.Break(self._tok_coord(tok))
  1524. case "CONTINUE":
  1525. self._expect("SEMI")
  1526. return c_ast.Continue(self._tok_coord(tok))
  1527. case "RETURN":
  1528. if self._accept("SEMI"):
  1529. return c_ast.Return(None, self._tok_coord(tok))
  1530. expr = self._parse_expression()
  1531. self._expect("SEMI")
  1532. return c_ast.Return(expr, self._tok_coord(tok))
  1533. case _:
  1534. self._parse_error("Invalid jump statement", self._tok_coord(tok))
  1535. # BNF: expression_statement : expression_opt ';'
  1536. def _parse_expression_statement(self) -> c_ast.Node:
  1537. expr = self._parse_expression_opt()
  1538. semi_tok = self._expect("SEMI")
  1539. if expr is None:
  1540. return c_ast.EmptyStatement(self._tok_coord(semi_tok))
  1541. return expr
  1542. # ------------------------------------------------------------------
  1543. # Expressions
  1544. # ------------------------------------------------------------------
  1545. # BNF: expression_opt : expression | empty
  1546. def _parse_expression_opt(self) -> c_ast.Node | None:
  1547. if self._starts_expression():
  1548. return self._parse_expression()
  1549. return None
  1550. # BNF: expression : assignment_expression (',' assignment_expression)*
  1551. def _parse_expression(self) -> c_ast.Node:
  1552. expr = self._parse_assignment_expression()
  1553. if not self._accept("COMMA"):
  1554. return expr
  1555. exprs = [expr, self._parse_assignment_expression()]
  1556. while self._accept("COMMA"):
  1557. exprs.append(self._parse_assignment_expression())
  1558. return c_ast.ExprList(exprs, expr.coord)
  1559. # BNF: assignment_expression : conditional_expression
  1560. # | unary_expression assignment_op assignment_expression
  1561. def _parse_assignment_expression(self) -> c_ast.Node:
  1562. if self._peek_type() == "LPAREN" and self._peek_type(2) == "LBRACE":
  1563. self._advance()
  1564. comp = self._parse_compound_statement()
  1565. self._expect("RPAREN")
  1566. return comp
  1567. expr = self._parse_conditional_expression()
  1568. if self._is_assignment_op():
  1569. op = self._advance().value
  1570. rhs = self._parse_assignment_expression()
  1571. return c_ast.Assignment(op, expr, rhs, expr.coord)
  1572. return expr
  1573. # BNF: conditional_expression : binary_expression
  1574. # | binary_expression '?' expression ':' conditional_expression
  1575. def _parse_conditional_expression(self) -> c_ast.Node:
  1576. expr = self._parse_binary_expression()
  1577. if self._accept("CONDOP"):
  1578. iftrue = self._parse_expression()
  1579. self._expect("COLON")
  1580. iffalse = self._parse_conditional_expression()
  1581. return c_ast.TernaryOp(expr, iftrue, iffalse, expr.coord)
  1582. return expr
  1583. # BNF: binary_expression : cast_expression (binary_op cast_expression)*
  1584. def _parse_binary_expression(
  1585. self, min_prec: int = 0, lhs: c_ast.Node | None = None
  1586. ) -> c_ast.Node:
  1587. if lhs is None:
  1588. lhs = self._parse_cast_expression()
  1589. while True:
  1590. tok = self._peek()
  1591. if tok is None or tok.type not in _BINARY_PRECEDENCE:
  1592. break
  1593. prec = _BINARY_PRECEDENCE[tok.type]
  1594. if prec < min_prec:
  1595. break
  1596. op = tok.value
  1597. self._advance()
  1598. rhs = self._parse_cast_expression()
  1599. while True:
  1600. next_tok = self._peek()
  1601. if next_tok is None or next_tok.type not in _BINARY_PRECEDENCE:
  1602. break
  1603. next_prec = _BINARY_PRECEDENCE[next_tok.type]
  1604. if next_prec > prec:
  1605. rhs = self._parse_binary_expression(next_prec, rhs)
  1606. else:
  1607. break
  1608. lhs = c_ast.BinaryOp(op, lhs, rhs, lhs.coord)
  1609. return lhs
  1610. # BNF: cast_expression : '(' type_name ')' cast_expression
  1611. # | unary_expression
  1612. def _parse_cast_expression(self) -> c_ast.Node:
  1613. result = self._try_parse_paren_type_name()
  1614. if result is not None:
  1615. typ, mark, lparen_tok = result
  1616. if self._peek_type() == "LBRACE":
  1617. # (type){...} is a compound literal, not a cast. Examples:
  1618. # (int){1} -> compound literal, handled in postfix
  1619. # (int) x -> cast, handled below
  1620. self._reset(mark)
  1621. else:
  1622. expr = self._parse_cast_expression()
  1623. return c_ast.Cast(typ, expr, self._tok_coord(lparen_tok))
  1624. return self._parse_unary_expression()
  1625. # BNF: unary_expression : postfix_expression
  1626. # | '++' unary_expression
  1627. # | '--' unary_expression
  1628. # | unary_op cast_expression
  1629. # | 'sizeof' unary_expression
  1630. # | 'sizeof' '(' type_name ')'
  1631. # | '_Alignof' '(' type_name ')'
  1632. def _parse_unary_expression(self) -> c_ast.Node:
  1633. tok_type = self._peek_type()
  1634. if tok_type in {"PLUSPLUS", "MINUSMINUS"}:
  1635. tok = self._advance()
  1636. expr = self._parse_unary_expression()
  1637. return c_ast.UnaryOp(tok.value, expr, expr.coord)
  1638. if tok_type in {"AND", "TIMES", "PLUS", "MINUS", "NOT", "LNOT"}:
  1639. tok = self._advance()
  1640. expr = self._parse_cast_expression()
  1641. return c_ast.UnaryOp(tok.value, expr, expr.coord)
  1642. if tok_type == "SIZEOF":
  1643. tok = self._advance()
  1644. result = self._try_parse_paren_type_name()
  1645. if result is not None:
  1646. typ, _, _ = result
  1647. return c_ast.UnaryOp(tok.value, typ, self._tok_coord(tok))
  1648. expr = self._parse_unary_expression()
  1649. return c_ast.UnaryOp(tok.value, expr, self._tok_coord(tok))
  1650. if tok_type == "_ALIGNOF":
  1651. tok = self._advance()
  1652. self._expect("LPAREN")
  1653. typ = self._parse_type_name()
  1654. self._expect("RPAREN")
  1655. return c_ast.UnaryOp(tok.value, typ, self._tok_coord(tok))
  1656. return self._parse_postfix_expression()
  1657. # BNF: postfix_expression : primary_expression postfix_suffix*
  1658. # | '(' type_name ')' '{' initializer_list ','? '}'
  1659. def _parse_postfix_expression(self) -> c_ast.Node:
  1660. result = self._try_parse_paren_type_name()
  1661. if result is not None:
  1662. typ, mark, _ = result
  1663. # Disambiguate between casts and compound literals:
  1664. # (int) x -> cast
  1665. # (int) {1} -> compound literal
  1666. lbrace_tok = self._accept("LBRACE")
  1667. if lbrace_tok is not None:
  1668. if self._accept("RBRACE"):
  1669. # Empty compound literal, e.g. (int){} (C99 empty braces).
  1670. return c_ast.CompoundLiteral(
  1671. typ, c_ast.InitList([], self._tok_coord(lbrace_tok))
  1672. )
  1673. init = self._parse_initializer_list()
  1674. self._accept("COMMA")
  1675. self._expect("RBRACE")
  1676. return c_ast.CompoundLiteral(typ, init)
  1677. else:
  1678. self._reset(mark)
  1679. expr = self._parse_primary_expression()
  1680. while True:
  1681. if self._accept("LBRACKET"):
  1682. sub = self._parse_expression()
  1683. self._expect("RBRACKET")
  1684. expr = c_ast.ArrayRef(expr, sub, expr.coord)
  1685. continue
  1686. if self._accept("LPAREN"):
  1687. if self._peek_type() == "RPAREN":
  1688. self._advance()
  1689. args = None
  1690. else:
  1691. args = self._parse_argument_expression_list()
  1692. self._expect("RPAREN")
  1693. expr = c_ast.FuncCall(expr, args, expr.coord)
  1694. continue
  1695. if self._peek_type() in {"PERIOD", "ARROW"}:
  1696. op_tok = self._advance()
  1697. name_tok = self._advance()
  1698. if name_tok.type not in {"ID", "TYPEID"}:
  1699. self._parse_error(
  1700. "Invalid struct reference", self._tok_coord(name_tok)
  1701. )
  1702. field = c_ast.ID(name_tok.value, self._tok_coord(name_tok))
  1703. expr = c_ast.StructRef(expr, op_tok.value, field, expr.coord)
  1704. continue
  1705. if self._peek_type() in {"PLUSPLUS", "MINUSMINUS"}:
  1706. tok = self._advance()
  1707. expr = c_ast.UnaryOp("p" + tok.value, expr, expr.coord)
  1708. continue
  1709. break
  1710. return expr
  1711. # BNF: primary_expression : ID | constant | string_literal
  1712. # | '(' expression ')' | generic_selection | offsetof
  1713. def _parse_primary_expression(self) -> c_ast.Node:
  1714. tok_type = self._peek_type()
  1715. if tok_type == "ID":
  1716. return self._parse_identifier()
  1717. if (
  1718. tok_type in _INT_CONST
  1719. or tok_type in _FLOAT_CONST
  1720. or tok_type in _CHAR_CONST
  1721. ):
  1722. return self._parse_constant()
  1723. if tok_type in _STRING_LITERAL:
  1724. return self._parse_unified_string_literal()
  1725. if tok_type == "LPAREN":
  1726. self._advance()
  1727. expr = self._parse_expression()
  1728. self._expect("RPAREN")
  1729. return expr
  1730. if tok_type == "_GENERIC":
  1731. return self._parse_generic_selection()
  1732. if tok_type == "OFFSETOF":
  1733. off_tok = self._advance()
  1734. self._expect("LPAREN")
  1735. typ = self._parse_type_name()
  1736. self._expect("COMMA")
  1737. designator = self._parse_offsetof_member_designator()
  1738. self._expect("RPAREN")
  1739. coord = self._tok_coord(off_tok)
  1740. return c_ast.FuncCall(
  1741. c_ast.ID(off_tok.value, coord),
  1742. c_ast.ExprList([typ, designator], coord),
  1743. coord,
  1744. )
  1745. self._parse_error("Invalid expression", self.clex.filename)
  1746. # BNF: generic_selection : _GENERIC '(' assignment_expression ','
  1747. # generic_association (',' generic_association)* ')'
  1748. def _parse_generic_selection(self) -> c_ast.GenericSelection:
  1749. tok = self._expect("_GENERIC")
  1750. self._expect("LPAREN")
  1751. expr = self._parse_assignment_expression()
  1752. self._expect("COMMA")
  1753. associations = [self._parse_generic_association()]
  1754. while self._accept("COMMA"):
  1755. associations.append(self._parse_generic_association())
  1756. self._expect("RPAREN")
  1757. return c_ast.GenericSelection(expr, associations, self._tok_coord(tok))
  1758. # BNF: generic_association : type_name ':' assignment_expression
  1759. # | DEFAULT ':' assignment_expression
  1760. def _parse_generic_association(self) -> c_ast.GenericAssociation:
  1761. tok = self._peek()
  1762. if tok is None:
  1763. self._parse_error("At end of input", self.clex.filename)
  1764. typ = None if self._accept("DEFAULT") else self._parse_type_name()
  1765. self._expect("COLON")
  1766. expr = self._parse_assignment_expression()
  1767. return c_ast.GenericAssociation(typ, expr, self._tok_coord(tok))
  1768. # BNF: offsetof_member_designator : identifier_or_typeid
  1769. # ('.' identifier_or_typeid | '[' expression ']')*
  1770. def _parse_offsetof_member_designator(self) -> c_ast.Node:
  1771. node = self._parse_identifier_or_typeid()
  1772. while True:
  1773. if self._accept("PERIOD"):
  1774. field = self._parse_identifier_or_typeid()
  1775. node = c_ast.StructRef(node, ".", field, node.coord)
  1776. continue
  1777. if self._accept("LBRACKET"):
  1778. expr = self._parse_expression()
  1779. self._expect("RBRACKET")
  1780. node = c_ast.ArrayRef(node, expr, node.coord)
  1781. continue
  1782. break
  1783. return node
  1784. # BNF: argument_expression_list : assignment_expression (',' assignment_expression)*
  1785. def _parse_argument_expression_list(self) -> c_ast.Node:
  1786. expr = self._parse_assignment_expression()
  1787. exprs = [expr]
  1788. while self._accept("COMMA"):
  1789. exprs.append(self._parse_assignment_expression())
  1790. return c_ast.ExprList(exprs, expr.coord)
  1791. # BNF: constant_expression : conditional_expression
  1792. def _parse_constant_expression(self) -> c_ast.Node:
  1793. return self._parse_conditional_expression()
  1794. # ------------------------------------------------------------------
  1795. # Terminals
  1796. # ------------------------------------------------------------------
  1797. # BNF: identifier : ID
  1798. def _parse_identifier(self) -> c_ast.Node:
  1799. tok = self._expect("ID")
  1800. return c_ast.ID(tok.value, self._tok_coord(tok))
  1801. # BNF: identifier_or_typeid : ID | TYPEID
  1802. def _parse_identifier_or_typeid(self) -> c_ast.Node:
  1803. tok = self._advance()
  1804. if tok.type not in {"ID", "TYPEID"}:
  1805. self._parse_error("Expected identifier", self._tok_coord(tok))
  1806. return c_ast.ID(tok.value, self._tok_coord(tok))
  1807. # BNF: constant : INT_CONST | FLOAT_CONST | CHAR_CONST
  1808. def _parse_constant(self) -> c_ast.Node:
  1809. tok = self._advance()
  1810. if tok.type in _INT_CONST:
  1811. u_count = 0
  1812. l_count = 0
  1813. for ch in tok.value[-3:]:
  1814. if ch in ("l", "L"):
  1815. l_count += 1
  1816. elif ch in ("u", "U"):
  1817. u_count += 1
  1818. if u_count > 1:
  1819. raise ValueError("Constant cannot have more than one u/U suffix.")
  1820. if l_count > 2:
  1821. raise ValueError("Constant cannot have more than two l/L suffix.")
  1822. prefix = "unsigned " * u_count + "long " * l_count
  1823. return c_ast.Constant(prefix + "int", tok.value, self._tok_coord(tok))
  1824. if tok.type in _FLOAT_CONST:
  1825. if tok.value[-1] in ("f", "F"):
  1826. t = "float"
  1827. elif tok.value[-1] in ("l", "L"):
  1828. t = "long double"
  1829. else:
  1830. t = "double"
  1831. return c_ast.Constant(t, tok.value, self._tok_coord(tok))
  1832. if tok.type in _CHAR_CONST:
  1833. return c_ast.Constant("char", tok.value, self._tok_coord(tok))
  1834. self._parse_error("Invalid constant", self._tok_coord(tok))
  1835. # BNF: unified_string_literal : (STRING_LITERAL | WSTRING_LITERAL
  1836. # | U8STRING_LITERAL | U16STRING_LITERAL
  1837. # | U32STRING_LITERAL)+
  1838. def _parse_unified_string_literal(self) -> c_ast.Constant:
  1839. # Represent the whole run of adjacent literals with one Constant.
  1840. # C interprets escapes before concatenating the character sequences,
  1841. # whereas Constant.value holds source spelling. Simply removing the
  1842. # quotes between "\1" "23" would produce "\123", changing three
  1843. # characters into one (issue #392).
  1844. tok = self._advance()
  1845. if tok.type not in _STRING_LITERAL:
  1846. self._parse_error("Invalid string literal", self._tok_coord(tok))
  1847. # Split off the optional encoding prefix and remove the closing quote.
  1848. # Each part holds unquoted source text that can safely share one literal.
  1849. prefix, contents = tok.value.split('"', 1)
  1850. parts = [contents[:-1]]
  1851. while self._peek_type() in _STRING_LITERAL:
  1852. tok2 = self._advance()
  1853. next_prefix, next_contents = tok2.value.split('"', 1)
  1854. # The first nonempty prefix applies to the whole run, even if it
  1855. # occurs after ordinary literals. Conflicting prefixes retain the
  1856. # parser's existing permissive behavior: the first one wins.
  1857. prefix = prefix or next_prefix
  1858. next_contents = next_contents[:-1]
  1859. # Extend the current part when safe; otherwise start a new one so
  1860. # a quote boundary survives. Empty literals can merge, but do not
  1861. # end a trailing escape: "\1" "" "23" still needs a boundary.
  1862. if self._string_literal_needs_separator(parts[-1], next_contents):
  1863. parts.append(next_contents)
  1864. else:
  1865. parts[-1] += next_contents
  1866. # Re-quote each part, keeping only the necessary literal boundaries.
  1867. # The prefix on the first literal applies to the adjacent sequence.
  1868. # The generator can emit this value directly without decoding escapes.
  1869. value = prefix + '"' + '" "'.join(parts) + '"'
  1870. return c_ast.Constant("string", value, self._tok_coord(tok))
  1871. @staticmethod
  1872. def _string_literal_needs_separator(left: str, right: str) -> bool:
  1873. """Whether joining two literal bodies would change their C spelling."""
  1874. if not left or not right:
  1875. return False
  1876. # A generated trigraph would be replaced before C string processing;
  1877. # for example, merging "?" "?=" would create the trigraph for '#'.
  1878. boundary = left[-2:] + right[:2]
  1879. if any("??" + ch in boundary for ch in "=/'()!<>-"):
  1880. return True
  1881. # Only an escape reaching the end of left can absorb characters from
  1882. # right. The last backslash is the only possible start of that escape.
  1883. escape_start = left.rfind("\\")
  1884. if escape_start == -1:
  1885. return False
  1886. # An even run of backslashes represents escaped backslashes, not the
  1887. # start of the numeric escape that the following digits might suggest.
  1888. run_start = escape_start
  1889. while run_start > 0 and left[run_start - 1] == "\\":
  1890. run_start -= 1
  1891. if (escape_start - run_start + 1) % 2 == 0:
  1892. return False
  1893. escape = left[escape_start + 1 :]
  1894. if escape.startswith("x"):
  1895. # Hex escapes have no digit limit: "\x1" "a" must stay separated.
  1896. hex_digits = "0123456789abcdefABCDEF"
  1897. return right[0] in hex_digits and all(ch in hex_digits for ch in escape[1:])
  1898. # Octal escapes consume at most three digits: "\12" "3" needs a
  1899. # boundary, but "\123" "4" can become "\1234". Universal character names
  1900. # have fixed widths and cannot absorb characters from the next literal.
  1901. return (
  1902. 1 <= len(escape) < 3
  1903. and all(ch in "01234567" for ch in escape)
  1904. and right[0] in "01234567"
  1905. )
  1906. # ------------------------------------------------------------------
  1907. # Initializers
  1908. # ------------------------------------------------------------------
  1909. # BNF: initializer : assignment_expression
  1910. # | '{' initializer_list ','? '}'
  1911. # | '{' '}'
  1912. def _parse_initializer(self) -> c_ast.Node:
  1913. lbrace_tok = self._accept("LBRACE")
  1914. if lbrace_tok:
  1915. if self._accept("RBRACE"):
  1916. return c_ast.InitList([], self._tok_coord(lbrace_tok))
  1917. init_list = self._parse_initializer_list()
  1918. self._accept("COMMA")
  1919. self._expect("RBRACE")
  1920. return init_list
  1921. return self._parse_assignment_expression()
  1922. # BNF: initializer_list : initializer_item (',' initializer_item)* ','?
  1923. def _parse_initializer_list(self) -> c_ast.Node:
  1924. items = [self._parse_initializer_item()]
  1925. while self._accept("COMMA"):
  1926. if self._peek_type() == "RBRACE":
  1927. break
  1928. items.append(self._parse_initializer_item())
  1929. return c_ast.InitList(items, items[0].coord)
  1930. # BNF: initializer_item : designation? initializer
  1931. def _parse_initializer_item(self) -> c_ast.Node:
  1932. designation = None
  1933. if self._peek_type() in {"LBRACKET", "PERIOD"}:
  1934. designation = self._parse_designation()
  1935. init = self._parse_initializer()
  1936. if designation is not None:
  1937. return c_ast.NamedInitializer(designation, init)
  1938. return init
  1939. # BNF: designation : designator_list '='
  1940. def _parse_designation(self) -> list[c_ast.Node]:
  1941. designators = self._parse_designator_list()
  1942. self._expect("EQUALS")
  1943. return designators
  1944. # BNF: designator_list : designator+
  1945. def _parse_designator_list(self) -> list[c_ast.Node]:
  1946. designators = []
  1947. while self._peek_type() in {"LBRACKET", "PERIOD"}:
  1948. designators.append(self._parse_designator())
  1949. return designators
  1950. # BNF: designator : '[' constant_expression ']'
  1951. # | '.' identifier_or_typeid
  1952. def _parse_designator(self) -> c_ast.Node:
  1953. if self._accept("LBRACKET"):
  1954. expr = self._parse_constant_expression()
  1955. self._expect("RBRACKET")
  1956. return expr
  1957. if self._accept("PERIOD"):
  1958. return self._parse_identifier_or_typeid()
  1959. self._parse_error("Invalid designator", self.clex.filename)
  1960. # ------------------------------------------------------------------
  1961. # Preprocessor-like directives
  1962. # ------------------------------------------------------------------
  1963. # BNF: pp_directive : '#' ... (unsupported)
  1964. def _parse_pp_directive(self) -> NoReturn:
  1965. tok = self._expect("PPHASH")
  1966. self._parse_error("Directives not supported yet", self._tok_coord(tok))
  1967. # BNF: pppragma_directive : PPPRAGMA PPPRAGMASTR?
  1968. # | _PRAGMA '(' string_literal ')'
  1969. def _parse_pppragma_directive(self) -> c_ast.Node:
  1970. if self._peek_type() == "PPPRAGMA":
  1971. tok = self._advance()
  1972. if self._peek_type() == "PPPRAGMASTR":
  1973. str_tok = self._advance()
  1974. return c_ast.Pragma(str_tok.value, self._tok_coord(str_tok))
  1975. return c_ast.Pragma("", self._tok_coord(tok))
  1976. if self._peek_type() == "_PRAGMA":
  1977. tok = self._advance()
  1978. lparen = self._expect("LPAREN")
  1979. literal = self._parse_unified_string_literal()
  1980. self._expect("RPAREN")
  1981. return c_ast.Pragma(literal, self._tok_coord(lparen))
  1982. self._parse_error("Invalid pragma", self.clex.filename)
  1983. # BNF: pppragma_directive_list : pppragma_directive+
  1984. def _parse_pppragma_directive_list(self) -> list[c_ast.Node]:
  1985. pragmas = []
  1986. while self._peek_type() in {"PPPRAGMA", "_PRAGMA"}:
  1987. pragmas.append(self._parse_pppragma_directive())
  1988. return pragmas
  1989. # BNF: static_assert : _STATIC_ASSERT '(' constant_expression
  1990. # (',' unified_string_literal)? ')' ';'
  1991. # C11 requires a message; omission is supported as an extension.
  1992. def _parse_static_assert(self) -> c_ast.StaticAssert:
  1993. tok = self._expect("_STATIC_ASSERT")
  1994. self._expect("LPAREN")
  1995. cond = self._parse_constant_expression()
  1996. msg = None
  1997. if self._accept("COMMA"):
  1998. msg = self._parse_unified_string_literal()
  1999. self._expect("RPAREN")
  2000. self._expect("SEMI")
  2001. return c_ast.StaticAssert(cond, msg, self._tok_coord(tok))
  2002. _ASSIGNMENT_OPS = {
  2003. "EQUALS",
  2004. "XOREQUAL",
  2005. "TIMESEQUAL",
  2006. "DIVEQUAL",
  2007. "MODEQUAL",
  2008. "PLUSEQUAL",
  2009. "MINUSEQUAL",
  2010. "LSHIFTEQUAL",
  2011. "RSHIFTEQUAL",
  2012. "ANDEQUAL",
  2013. "OREQUAL",
  2014. }
  2015. # Precedence of operators (lower number = weather binding)
  2016. # If this changes, c_generator.CGenerator.precedence_map needs to change as
  2017. # well
  2018. _BINARY_PRECEDENCE = {
  2019. "LOR": 0,
  2020. "LAND": 1,
  2021. "OR": 2,
  2022. "XOR": 3,
  2023. "AND": 4,
  2024. "EQ": 5,
  2025. "NE": 5,
  2026. "GT": 6,
  2027. "GE": 6,
  2028. "LT": 6,
  2029. "LE": 6,
  2030. "RSHIFT": 7,
  2031. "LSHIFT": 7,
  2032. "PLUS": 8,
  2033. "MINUS": 8,
  2034. "TIMES": 9,
  2035. "DIVIDE": 9,
  2036. "MOD": 9,
  2037. }
  2038. _STORAGE_CLASS = {"AUTO", "REGISTER", "STATIC", "EXTERN", "TYPEDEF", "_THREAD_LOCAL"}
  2039. _FUNCTION_SPEC = {"INLINE", "_NORETURN"}
  2040. _TYPE_QUALIFIER = {"CONST", "RESTRICT", "VOLATILE", "_ATOMIC"}
  2041. _TYPE_SPEC_SIMPLE = {
  2042. "VOID",
  2043. "_BOOL",
  2044. "CHAR",
  2045. "SHORT",
  2046. "INT",
  2047. "LONG",
  2048. "FLOAT",
  2049. "DOUBLE",
  2050. "_COMPLEX",
  2051. "SIGNED",
  2052. "UNSIGNED",
  2053. "__INT128",
  2054. }
  2055. _DECL_START = (
  2056. _STORAGE_CLASS
  2057. | _FUNCTION_SPEC
  2058. | _TYPE_QUALIFIER
  2059. | _TYPE_SPEC_SIMPLE
  2060. | {"TYPEID", "STRUCT", "UNION", "ENUM", "_ALIGNAS", "_ATOMIC"}
  2061. )
  2062. _EXPR_START = {
  2063. "ID",
  2064. "LPAREN",
  2065. "PLUSPLUS",
  2066. "MINUSMINUS",
  2067. "PLUS",
  2068. "MINUS",
  2069. "TIMES",
  2070. "AND",
  2071. "NOT",
  2072. "LNOT",
  2073. "SIZEOF",
  2074. "_ALIGNOF",
  2075. "_GENERIC",
  2076. "OFFSETOF",
  2077. }
  2078. _INT_CONST = {
  2079. "INT_CONST_DEC",
  2080. "INT_CONST_OCT",
  2081. "INT_CONST_HEX",
  2082. "INT_CONST_BIN",
  2083. "INT_CONST_CHAR",
  2084. }
  2085. _FLOAT_CONST = {"FLOAT_CONST", "HEX_FLOAT_CONST"}
  2086. _CHAR_CONST = {
  2087. "CHAR_CONST",
  2088. "WCHAR_CONST",
  2089. "U8CHAR_CONST",
  2090. "U16CHAR_CONST",
  2091. "U32CHAR_CONST",
  2092. }
  2093. _STRING_LITERAL = {
  2094. "STRING_LITERAL",
  2095. "WSTRING_LITERAL",
  2096. "U8STRING_LITERAL",
  2097. "U16STRING_LITERAL",
  2098. "U32STRING_LITERAL",
  2099. }
  2100. _STARTS_EXPRESSION = (
  2101. _EXPR_START | _INT_CONST | _FLOAT_CONST | _CHAR_CONST | _STRING_LITERAL
  2102. )
  2103. _STARTS_STATEMENT = {
  2104. "LBRACE",
  2105. "IF",
  2106. "SWITCH",
  2107. "WHILE",
  2108. "DO",
  2109. "FOR",
  2110. "GOTO",
  2111. "BREAK",
  2112. "CONTINUE",
  2113. "RETURN",
  2114. "CASE",
  2115. "DEFAULT",
  2116. "PPPRAGMA",
  2117. "_PRAGMA",
  2118. "SEMI",
  2119. }
  2120. class _TokenStream:
  2121. """Wraps a lexer to provide convenient, buffered access to the underlying
  2122. token stream. The lexer is expected to be initialized with the input
  2123. string already.
  2124. """
  2125. def __init__(self, lexer: CLexer) -> None:
  2126. self._lexer = lexer
  2127. self._buffer: list[Token | None] = []
  2128. self._index = 0
  2129. def peek(self, k: int = 1) -> Token | None:
  2130. """Peek at the k-th next token in the stream, without consuming it.
  2131. Examples:
  2132. k=1 returns the immediate next token.
  2133. k=2 returns the token after that.
  2134. """
  2135. if k <= 0:
  2136. return None
  2137. self._fill(k)
  2138. return self._buffer[self._index + k - 1]
  2139. def next(self) -> Token | None:
  2140. """Consume a single token and return it."""
  2141. self._fill(1)
  2142. tok = self._buffer[self._index]
  2143. self._index += 1
  2144. return tok
  2145. # The 'mark' and 'reset' methods are useful for speculative parsing with
  2146. # backtracking; when the parser needs to examine a sequence of tokens
  2147. # and potentially decide to try a different path on the same sequence, it
  2148. # can call 'mark' to obtain the current token position, and if the first
  2149. # path fails restore the position with `reset(pos)`.
  2150. def mark(self) -> int:
  2151. return self._index
  2152. def reset(self, mark: int) -> None:
  2153. self._index = mark
  2154. def _fill(self, n: int) -> None:
  2155. while len(self._buffer) < self._index + n:
  2156. tok = self._lexer.token()
  2157. self._buffer.append(tok)
  2158. if tok is None:
  2159. break
  2160. # Declaration specifiers are represented by a dictionary with entries:
  2161. # - qual: a list of type qualifiers
  2162. # - storage: a list of storage class specifiers
  2163. # - type: a list of type specifiers
  2164. # - function: a list of function specifiers
  2165. # - alignment: a list of alignment specifiers
  2166. class _DeclSpec(TypedDict):
  2167. qual: list[Any]
  2168. storage: list[Any]
  2169. type: list[Any]
  2170. function: list[Any]
  2171. alignment: list[Any]
  2172. _DeclSpecKind = Literal["qual", "storage", "type", "function", "alignment"]
  2173. class _DeclInfo(TypedDict):
  2174. # Declarator payloads used by declaration/initializer parsing:
  2175. # - decl: the declarator node (may be None for abstract/implicit cases)
  2176. # - init: optional initializer expression
  2177. # - bitsize: optional bit-field width expression (for struct declarators)
  2178. decl: c_ast.Node | None
  2179. init: c_ast.Node | None
  2180. bitsize: c_ast.Node | None