jarbin-c-coding-style 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. jarbin_c_coding_style-2.0.0.dist-info/METADATA +150 -0
  2. jarbin_c_coding_style-2.0.0.dist-info/RECORD +186 -0
  3. jarbin_c_coding_style-2.0.0.dist-info/WHEEL +4 -0
  4. jarbin_c_coding_style-2.0.0.dist-info/entry_points.txt +2 -0
  5. jarbin_c_coding_style-2.0.0.dist-info/licenses/LICENSE +674 -0
  6. sources/__init__.py +0 -0
  7. sources/__main__.py +6 -0
  8. sources/analysis/__init__.py +0 -0
  9. sources/analysis/directives.py +258 -0
  10. sources/analysis/lexer.py +288 -0
  11. sources/analysis/parser.py +1754 -0
  12. sources/analysis/project.py +286 -0
  13. sources/analysis/source.py +326 -0
  14. sources/analysis/syntax.py +238 -0
  15. sources/analysis/tokens.py +116 -0
  16. sources/analysis/unit.py +700 -0
  17. sources/application.py +118 -0
  18. sources/build_info.json +6 -0
  19. sources/cli/__init__.py +0 -0
  20. sources/cli/arguments.py +507 -0
  21. sources/cli/completion.py +610 -0
  22. sources/cli/context.py +258 -0
  23. sources/cli/converters.py +204 -0
  24. sources/cli/help.py +162 -0
  25. sources/cli/parser.py +659 -0
  26. sources/configs/__init__.py +0 -0
  27. sources/configs/editor.py +207 -0
  28. sources/configs/ini.py +327 -0
  29. sources/configs/project.py +735 -0
  30. sources/configs/schema/__init__.py +0 -0
  31. sources/configs/schema/project.py +68 -0
  32. sources/constants.py +801 -0
  33. sources/diagnostics/__init__.py +0 -0
  34. sources/diagnostics/fingerprint.py +82 -0
  35. sources/diagnostics/model.py +146 -0
  36. sources/engine/__init__.py +0 -0
  37. sources/engine/api.py +355 -0
  38. sources/engine/examples.py +157 -0
  39. sources/engine/outcome.py +114 -0
  40. sources/engine/plan.py +440 -0
  41. sources/engine/runner.py +345 -0
  42. sources/engine/scanner.py +179 -0
  43. sources/enums.py +838 -0
  44. sources/errors/__init__.py +0 -0
  45. sources/errors/exceptions.py +727 -0
  46. sources/fixers/__init__.py +0 -0
  47. sources/fixers/base.py +209 -0
  48. sources/fixers/conflicts.py +129 -0
  49. sources/fixers/diff.py +73 -0
  50. sources/fixers/engine.py +434 -0
  51. sources/fixers/journal.py +290 -0
  52. sources/fixers/kinds.py +30 -0
  53. sources/fixers/layout.py +411 -0
  54. sources/fixers/model.py +151 -0
  55. sources/fixers/registry.py +54 -0
  56. sources/fixers/text.py +353 -0
  57. sources/fixers/verify.py +123 -0
  58. sources/fixers/writer.py +88 -0
  59. sources/integrations/__init__.py +0 -0
  60. sources/integrations/ci/__init__.py +0 -0
  61. sources/integrations/ci/github.py +183 -0
  62. sources/integrations/editors/__init__.py +0 -0
  63. sources/integrations/git/__init__.py +0 -0
  64. sources/integrations/git/repository.py +176 -0
  65. sources/integrations/update/__init__.py +0 -0
  66. sources/integrations/update/installers.py +529 -0
  67. sources/integrations/update/releases.py +397 -0
  68. sources/integrations/update/state.py +143 -0
  69. sources/outputs/__init__.py +0 -0
  70. sources/outputs/github/__init__.py +0 -0
  71. sources/outputs/github/renderer.py +135 -0
  72. sources/outputs/html/__init__.py +0 -0
  73. sources/outputs/html/renderer.py +694 -0
  74. sources/outputs/json/__init__.py +0 -0
  75. sources/outputs/json/renderer.py +154 -0
  76. sources/outputs/json/report.schema.json +121 -0
  77. sources/outputs/junit/__init__.py +0 -0
  78. sources/outputs/junit/renderer.py +151 -0
  79. sources/outputs/registry.py +135 -0
  80. sources/outputs/report.py +224 -0
  81. sources/outputs/sarif/__init__.py +0 -0
  82. sources/outputs/sarif/renderer.py +182 -0
  83. sources/outputs/terminal/__init__.py +0 -0
  84. sources/outputs/terminal/renderer.py +184 -0
  85. sources/outputs/terminal/style.py +159 -0
  86. sources/rules/__init__.py +0 -0
  87. sources/rules/arguments.py +362 -0
  88. sources/rules/catalog.py +227 -0
  89. sources/rules/categories/advanced/constant_pointers.ini +46 -0
  90. sources/rules/categories/advanced/line_break_at_end_of_file.ini +44 -0
  91. sources/rules/categories/advanced/static.ini +65 -0
  92. sources/rules/categories/advanced/typing.ini +47 -0
  93. sources/rules/categories/control_structures/conditional_branching.ini +89 -0
  94. sources/rules/categories/control_structures/goto.ini +45 -0
  95. sources/rules/categories/control_structures/ternary_operators.ini +57 -0
  96. sources/rules/categories/extensions/language_extensions.ini +71 -0
  97. sources/rules/categories/files_organization/contents_of_the_repository.ini +85 -0
  98. sources/rules/categories/files_organization/file_coherence.ini +166 -0
  99. sources/rules/categories/files_organization/file_extension.ini +68 -0
  100. sources/rules/categories/files_organization/fixtures/program +0 -0
  101. sources/rules/categories/files_organization/naming_files_and_folders.ini +74 -0
  102. sources/rules/categories/functions/coherence_of_functions.ini +45 -0
  103. sources/rules/categories/functions/comments_inside_a_function.ini +45 -0
  104. sources/rules/categories/functions/functions_without_parameters.ini +39 -0
  105. sources/rules/categories/functions/naming_functions.ini +79 -0
  106. sources/rules/categories/functions/number_of_columns.ini +61 -0
  107. sources/rules/categories/functions/number_of_lines.ini +70 -0
  108. sources/rules/categories/functions/number_of_parameters.ini +64 -0
  109. sources/rules/categories/functions/structures_as_parameters.ini +44 -0
  110. sources/rules/categories/global_scope/constant_values.ini +49 -0
  111. sources/rules/categories/global_scope/file_header.ini +92 -0
  112. sources/rules/categories/global_scope/global_variables.ini +53 -0
  113. sources/rules/categories/global_scope/include.ini +39 -0
  114. sources/rules/categories/global_scope/indentation_of_preprocessor.ini +62 -0
  115. sources/rules/categories/global_scope/inline_assembly.ini +43 -0
  116. sources/rules/categories/global_scope/leading_trailing_lines.ini +58 -0
  117. sources/rules/categories/global_scope/line_endings.ini +53 -0
  118. sources/rules/categories/global_scope/separation_of_functions.ini +61 -0
  119. sources/rules/categories/global_scope/trailing_spaces.ini +45 -0
  120. sources/rules/categories/header_files/content.ini +104 -0
  121. sources/rules/categories/header_files/include_guard.ini +47 -0
  122. sources/rules/categories/header_files/macros.ini +57 -0
  123. sources/rules/categories/layout_inside_a_function_scope/blank_lines.ini +71 -0
  124. sources/rules/categories/layout_inside_a_function_scope/code_line_content.ini +112 -0
  125. sources/rules/categories/layout_inside_a_function_scope/curly_brackets.ini +94 -0
  126. sources/rules/categories/layout_inside_a_function_scope/indentation.ini +96 -0
  127. sources/rules/categories/layout_inside_a_function_scope/spaces.ini +113 -0
  128. sources/rules/categories/layout_inside_a_function_scope/variable_declarations.ini +65 -0
  129. sources/rules/categories/variables_and_types/naming_identifiers.ini +74 -0
  130. sources/rules/categories/variables_and_types/pointers.ini +67 -0
  131. sources/rules/categories/variables_and_types/structures.ini +47 -0
  132. sources/rules/data/verbs.txt +182 -0
  133. sources/rules/definition.py +430 -0
  134. sources/rules/loader.py +925 -0
  135. sources/rules/paths.py +6 -0
  136. sources/rules/primitives/__init__.py +0 -0
  137. sources/rules/primitives/base.py +297 -0
  138. sources/rules/primitives/braces.py +211 -0
  139. sources/rules/primitives/directives.py +203 -0
  140. sources/rules/primitives/indentation.py +376 -0
  141. sources/rules/primitives/layout.py +199 -0
  142. sources/rules/primitives/naming.py +277 -0
  143. sources/rules/primitives/project.py +62 -0
  144. sources/rules/primitives/registry.py +49 -0
  145. sources/rules/primitives/repository.py +129 -0
  146. sources/rules/primitives/review.py +87 -0
  147. sources/rules/primitives/semantic.py +319 -0
  148. sources/rules/primitives/spacing.py +210 -0
  149. sources/rules/primitives/structure.py +586 -0
  150. sources/rules/primitives/syntax.py +200 -0
  151. sources/rules/primitives/text.py +408 -0
  152. sources/rules/primitives/tokens.py +84 -0
  153. sources/rules/template.py +138 -0
  154. sources/selftest/__init__.py +0 -0
  155. sources/selftest/cases.py +292 -0
  156. sources/services.py +90 -0
  157. sources/subcommands/__init__.py +0 -0
  158. sources/subcommands/base.py +45 -0
  159. sources/subcommands/check/__init__.py +0 -0
  160. sources/subcommands/check/command.py +45 -0
  161. sources/subcommands/check/fixing.py +224 -0
  162. sources/subcommands/check/handler.py +757 -0
  163. sources/subcommands/info/__init__.py +0 -0
  164. sources/subcommands/info/command.py +45 -0
  165. sources/subcommands/info/handler.py +527 -0
  166. sources/subcommands/registry.py +37 -0
  167. sources/subcommands/rule/__init__.py +0 -0
  168. sources/subcommands/rule/command.py +45 -0
  169. sources/subcommands/rule/handler.py +1067 -0
  170. sources/subcommands/rule/render.py +273 -0
  171. sources/subcommands/runner.py +124 -0
  172. sources/subcommands/test/__init__.py +0 -0
  173. sources/subcommands/test/command.py +45 -0
  174. sources/subcommands/test/handler.py +166 -0
  175. sources/subcommands/test/render.py +219 -0
  176. sources/subcommands/test/runner.py +430 -0
  177. sources/subcommands/update/__init__.py +0 -0
  178. sources/subcommands/update/command.py +45 -0
  179. sources/subcommands/update/handler.py +408 -0
  180. sources/utils/__init__.py +0 -0
  181. sources/utils/build_info.py +188 -0
  182. sources/utils/git.py +73 -0
  183. sources/utils/globs.py +98 -0
  184. sources/utils/logging.py +154 -0
  185. sources/utils/schema.py +77 -0
  186. sources/utils/versions.py +87 -0
@@ -0,0 +1,1754 @@
1
+ import re
2
+ from collections.abc import Iterable
3
+ from dataclasses import dataclass, field
4
+
5
+ from sources.analysis.syntax import Node
6
+ from sources.analysis.tokens import Token
7
+ from sources.enums import NodeKind, TokenKind
8
+
9
+
10
+ # Type names defined by the C standard library and POSIX headers, known without reading the headers.
11
+ STANDARD_TYPE_NAMES: frozenset[str] = frozenset({
12
+ "size_t", "ssize_t", "ptrdiff_t", "wchar_t", "wint_t", "intptr_t", "uintptr_t", "intmax_t", "uintmax_t",
13
+ "int8_t", "int16_t", "int32_t", "int64_t", "uint8_t", "uint16_t", "uint32_t", "uint64_t",
14
+ "FILE", "DIR", "va_list", "off_t", "pid_t", "uid_t", "gid_t", "mode_t", "time_t", "clock_t",
15
+ "socklen_t", "sig_atomic_t", "pthread_t", "pthread_mutex_t", "pthread_cond_t", "jmp_buf", "fpos_t",
16
+ "div_t", "ldiv_t", "regex_t", "regmatch_t", "locale_t", "dev_t", "ino_t", "nlink_t", "blksize_t",
17
+ "blkcnt_t", "suseconds_t", "useconds_t", "sigset_t", "mbstate_t", "char16_t", "char32_t",
18
+ "max_align_t", "timer_t", "key_t", "nfds_t", "in_addr_t", "in_port_t", "sa_family_t",
19
+ })
20
+
21
+ # Identifiers ending with `_t` are treated as type names (Epitech requires this suffix for typedefs).
22
+ TYPE_SUFFIX_PATTERN: re.Pattern[str] = re.compile(r"[A-Za-z_]\w*_t")
23
+
24
+ # Keywords naming a basic type.
25
+ TYPE_KEYWORDS: frozenset[str] = frozenset({
26
+ "void", "char", "short", "int", "long", "float", "double", "signed", "unsigned", "_Bool", "_Complex",
27
+ "_Imaginary", "bool",
28
+ })
29
+
30
+ # Keywords qualifying a type.
31
+ QUALIFIER_KEYWORDS: frozenset[str] = frozenset({"const", "volatile", "restrict", "_Atomic"})
32
+
33
+ # Storage class keywords.
34
+ STORAGE_KEYWORDS: frozenset[str] = frozenset({"typedef", "extern", "static", "auto", "register", "_Thread_local", "thread_local"})
35
+
36
+ # Function specifier keywords.
37
+ FUNCTION_SPECIFIER_KEYWORDS: frozenset[str] = frozenset({"inline", "_Noreturn"})
38
+
39
+ # Compiler-specific words that behave like qualifiers and are skipped.
40
+ QUALIFIER_IDENTIFIERS: frozenset[str] = frozenset({
41
+ "__extension__", "__inline", "__inline__", "__restrict", "__restrict__", "__volatile__", "__const",
42
+ "__signed__", "__unused",
43
+ })
44
+
45
+ # Compiler-specific words followed by a parenthesised argument that is skipped.
46
+ ATTRIBUTE_IDENTIFIERS: frozenset[str] = frozenset({"__attribute__", "__attribute", "__declspec"})
47
+
48
+ # Spellings of inline assembly.
49
+ ASM_IDENTIFIERS: frozenset[str] = frozenset({"asm", "__asm__", "__asm"})
50
+
51
+ # Keywords followed by a parenthesised argument that is skipped in declaration specifiers.
52
+ PARENTHESIZED_SPECIFIERS: frozenset[str] = frozenset({"typeof", "typeof_unqual", "_Alignas", "alignas"})
53
+
54
+ # Keywords that start a declaration inside a block.
55
+ DECLARATION_KEYWORDS: frozenset[str] = (
56
+ TYPE_KEYWORDS | QUALIFIER_KEYWORDS | STORAGE_KEYWORDS | FUNCTION_SPECIFIER_KEYWORDS | PARENTHESIZED_SPECIFIERS
57
+ | {"struct", "union", "enum", "_Static_assert", "static_assert"}
58
+ )
59
+
60
+ # Assignment operators.
61
+ ASSIGNMENT_OPERATORS: frozenset[str] = frozenset({"=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", "&=", "^=", "|="})
62
+
63
+ # Binary operators and their precedence (higher binds tighter).
64
+ BINARY_PRECEDENCE: dict[str, int] = {
65
+ "||": 1, "&&": 2, "|": 3, "^": 4, "&": 5, "==": 6, "!=": 6, "<": 7, ">": 7, "<=": 7, ">=": 7,
66
+ "<<": 8, ">>": 8, "+": 9, "-": 9, "*": 10, "/": 10, "%": 10,
67
+ }
68
+
69
+ # Prefix unary operators (besides `++`, `--` and `sizeof`).
70
+ UNARY_OPERATORS: frozenset[str] = frozenset({"&", "*", "+", "-", "~", "!"})
71
+
72
+ # Keywords used as constant values.
73
+ CONSTANT_KEYWORDS: frozenset[str] = frozenset({"true", "false", "nullptr"})
74
+
75
+ # Tokens that may follow the declarator name of a declaration in a block (`int a;`, `t_x a = ...`).
76
+ DECLARATOR_FOLLOWERS: frozenset[str] = frozenset({";", "=", ",", "[", ")", "("})
77
+
78
+
79
+ class ParseError(Exception):
80
+ """
81
+ Raised inside the parser when the tokens do not match the grammar. It never leaves the parser: the
82
+ region is turned into an ERROR node.
83
+ (Exception)
84
+
85
+ Attributes
86
+ ----------
87
+ token : Token | None
88
+ Token where the problem was found (None at the end of the file).
89
+ """
90
+
91
+ def __init__(self, message: str, token: Token | None) -> None:
92
+ """
93
+ Create the error.
94
+
95
+ Parameters
96
+ ----------
97
+ message : str
98
+ Description of the problem.
99
+ token : Token | None
100
+ Token where the problem was found.
101
+
102
+ Returns
103
+ ----------
104
+ None
105
+ Nothing.
106
+ """
107
+ super().__init__(message)
108
+ self.token: Token | None = token
109
+
110
+
111
+ @dataclass(slots=True)
112
+ class Specifiers:
113
+ """
114
+ Declaration specifiers read before a declarator (storage, qualifiers, type).
115
+ (dataclass)
116
+
117
+ Attributes
118
+ ----------
119
+ storage : set[str]
120
+ Storage class and function specifiers (`static`, `extern`, `typedef`, `inline`...).
121
+ qualifiers : set[str]
122
+ Type qualifiers (`const`, `volatile`...).
123
+ type_words : list[str]
124
+ Basic type keywords and typedef name, in order.
125
+ type_node : Node | None
126
+ struct/union/enum specifier node, if any.
127
+ tokens : list[Token]
128
+ Every token read.
129
+ """
130
+
131
+ storage: set[str] = field(default_factory=set)
132
+ qualifiers: set[str] = field(default_factory=set)
133
+ type_words: list[str] = field(default_factory=list)
134
+ type_node: Node | None = None
135
+ tokens: list[Token] = field(default_factory=list)
136
+
137
+ @property
138
+ def has_type(self) -> bool:
139
+ """
140
+ Whether a type was read.
141
+
142
+ Returns
143
+ ----------
144
+ bool
145
+ True when a basic type, a typedef name or a struct/union/enum was read.
146
+ """
147
+ return bool(self.type_words) or self.type_node is not None
148
+
149
+ @property
150
+ def text(self) -> str:
151
+ """
152
+ Specifiers as written, tokens separated by one space.
153
+
154
+ Returns
155
+ ----------
156
+ str
157
+ The text.
158
+ """
159
+ return " ".join(token.text for token in self.tokens)
160
+
161
+
162
+ def is_type_name(name: str, known: set[str] | frozenset[str]) -> bool:
163
+ """
164
+ Whether an identifier names a type (known typedef, standard type or `_t` suffix).
165
+
166
+ Parameters
167
+ ----------
168
+ name : str
169
+ The identifier.
170
+ known : set[str] | frozenset[str]
171
+ Typedef names known so far.
172
+
173
+ Returns
174
+ ----------
175
+ bool
176
+ True for a type name.
177
+ """
178
+ return name in known or name in STANDARD_TYPE_NAMES or TYPE_SUFFIX_PATTERN.fullmatch(name) is not None
179
+
180
+
181
+ def collect_typedef_names(tokens: Iterable[Token]) -> set[str]:
182
+ """
183
+ Find the names declared by `typedef` in a token stream without parsing it. Used before parsing so
184
+ that a file can use types defined in another file of the project.
185
+
186
+ Parameters
187
+ ----------
188
+ tokens : Iterable[Token]
189
+ Tokens of a file.
190
+
191
+ Returns
192
+ ----------
193
+ set[str]
194
+ The typedef names.
195
+ """
196
+ significant: list[Token] = [token for token in tokens if token.is_significant]
197
+ names: set[str] = set()
198
+ index: int = 0
199
+ while index < len(significant):
200
+ if significant[index].text != "typedef":
201
+ index += 1
202
+ continue
203
+ braces: int = 0
204
+ parens: int = 0
205
+ index += 1
206
+ while index < len(significant):
207
+ token: Token = significant[index]
208
+ following: str = significant[index + 1].text if index + 1 < len(significant) else ""
209
+ previous: str = significant[index - 1].text
210
+ if token.text == "{":
211
+ braces += 1
212
+ elif token.text == "}":
213
+ braces -= 1
214
+ elif token.text == "(":
215
+ parens += 1
216
+ elif token.text == ")":
217
+ parens -= 1
218
+ elif token.text == ";" and braces <= 0:
219
+ break
220
+ elif token.kind is TokenKind.IDENTIFIER and braces == 0:
221
+ if parens == 0 and following in (";", ",", "["):
222
+ names.add(token.text)
223
+ elif parens == 1 and previous == "*" and following == ")":
224
+ names.add(token.text)
225
+ index += 1
226
+ index += 1
227
+ return names
228
+
229
+
230
+ class Parser:
231
+ """
232
+ Hand-written, error-tolerant recursive-descent parser for C (as written, without preprocessing).
233
+ Regions it cannot understand become ERROR nodes and parsing resumes after them.
234
+
235
+ Attributes
236
+ ----------
237
+ tokens : list[Token]
238
+ Significant tokens of the file (no trivia, no directive lines).
239
+ type_names : set[str]
240
+ Typedef names known so far (project names, then this file's as they are parsed).
241
+ errors : list[Node]
242
+ ERROR nodes created while parsing.
243
+ """
244
+
245
+ def __init__(self, tokens: Iterable[Token], type_names: Iterable[str] = ()) -> None:
246
+ """
247
+ Prepare the parser.
248
+
249
+ Parameters
250
+ ----------
251
+ tokens : Iterable[Token]
252
+ Every token of the file (trivia and directives are filtered out).
253
+ type_names : Iterable[str]
254
+ Typedef names known before parsing (e.g. from the rest of the project).
255
+
256
+ Returns
257
+ ----------
258
+ None
259
+ Nothing.
260
+ """
261
+ self.tokens: list[Token] = [token for token in tokens if token.is_significant]
262
+ self.type_names: set[str] = set(type_names)
263
+ self.errors: list[Node] = []
264
+ self._error_marks: list[int] = []
265
+ self._position: int = 0
266
+
267
+ # ------------------------------------------------------------------
268
+ # Token helpers
269
+ # ------------------------------------------------------------------
270
+
271
+ def _peek(self, ahead: int = 0) -> Token | None:
272
+ """
273
+ Look at a token without consuming it.
274
+
275
+ Parameters
276
+ ----------
277
+ ahead : int
278
+ Distance from the current token.
279
+
280
+ Returns
281
+ ----------
282
+ Token | None
283
+ The token, or None past the end.
284
+ """
285
+ index: int = self._position + ahead
286
+ return self.tokens[index] if index < len(self.tokens) else None
287
+
288
+ def _at(self, *texts: str, ahead: int = 0) -> bool:
289
+ """
290
+ Whether a token has one of the given texts.
291
+
292
+ Parameters
293
+ ----------
294
+ *texts : str
295
+ Accepted texts.
296
+ ahead : int
297
+ Distance from the current token.
298
+
299
+ Returns
300
+ ----------
301
+ bool
302
+ True on a match.
303
+ """
304
+ token: Token | None = self._peek(ahead)
305
+ return token is not None and token.text in texts and token.kind not in (TokenKind.STRING, TokenKind.CHAR)
306
+
307
+ def _advance(self) -> Token:
308
+ """
309
+ Consume the current token.
310
+
311
+ Returns
312
+ ----------
313
+ Token
314
+ The consumed token.
315
+
316
+ Raises
317
+ ----------
318
+ ParseError
319
+ The end of the file was reached.
320
+ """
321
+ token: Token | None = self._peek()
322
+ if token is None:
323
+ raise ParseError("unexpected end of file", self.tokens[-1] if self.tokens else None)
324
+ self._position += 1
325
+ return token
326
+
327
+ def _accept(self, text: str) -> Token | None:
328
+ """
329
+ Consume the current token when it has the given text.
330
+
331
+ Parameters
332
+ ----------
333
+ text : str
334
+ Expected text.
335
+
336
+ Returns
337
+ ----------
338
+ Token | None
339
+ The consumed token, or None.
340
+ """
341
+ if self._at(text):
342
+ return self._advance()
343
+ return None
344
+
345
+ def _expect(self, text: str) -> Token:
346
+ """
347
+ Consume the current token, which must have the given text.
348
+
349
+ Parameters
350
+ ----------
351
+ text : str
352
+ Expected text.
353
+
354
+ Returns
355
+ ----------
356
+ Token
357
+ The consumed token.
358
+
359
+ Raises
360
+ ----------
361
+ ParseError
362
+ The current token has another text.
363
+ """
364
+ if not self._at(text):
365
+ raise ParseError(f"expected '{text}'", self._peek())
366
+ return self._advance()
367
+
368
+ def _expect_identifier(self) -> Token:
369
+ """
370
+ Consume an identifier.
371
+
372
+ Returns
373
+ ----------
374
+ Token
375
+ The identifier token.
376
+
377
+ Raises
378
+ ----------
379
+ ParseError
380
+ The current token is not an identifier.
381
+ """
382
+ token: Token | None = self._peek()
383
+ if token is None or token.kind is not TokenKind.IDENTIFIER:
384
+ raise ParseError("expected an identifier", token)
385
+ return self._advance()
386
+
387
+ @property
388
+ def _previous(self) -> Token:
389
+ """
390
+ Last consumed token.
391
+
392
+ Returns
393
+ ----------
394
+ Token
395
+ The token.
396
+ """
397
+ return self.tokens[self._position - 1]
398
+
399
+ def _skip_parenthesized(self) -> None:
400
+ """
401
+ Consume a balanced `( ... )` group.
402
+
403
+ Returns
404
+ ----------
405
+ None
406
+ Nothing.
407
+
408
+ Raises
409
+ ----------
410
+ ParseError
411
+ The current token is not `(` or the group is not closed.
412
+ """
413
+ self._expect("(")
414
+ depth: int = 1
415
+ while depth:
416
+ token: Token = self._advance()
417
+ if token.text == "(":
418
+ depth += 1
419
+ elif token.text == ")":
420
+ depth -= 1
421
+
422
+ def _skip_braces(self) -> None:
423
+ """
424
+ Consume a balanced `{ ... }` group (until the end of the file when it is not closed).
425
+
426
+ Returns
427
+ ----------
428
+ None
429
+ Nothing.
430
+ """
431
+ depth: int = 0
432
+ while (token := self._peek()) is not None:
433
+ self._position += 1
434
+ if token.text == "{":
435
+ depth += 1
436
+ elif token.text == "}":
437
+ depth -= 1
438
+ if depth <= 0:
439
+ return
440
+
441
+ def _skip_attributes(self) -> None:
442
+ """
443
+ Consume GNU attributes, `__declspec(...)`, asm labels and qualifier-like compiler words.
444
+
445
+ Returns
446
+ ----------
447
+ None
448
+ Nothing.
449
+ """
450
+ while (token := self._peek()) is not None and token.kind is TokenKind.IDENTIFIER:
451
+ if token.text in ATTRIBUTE_IDENTIFIERS or (token.text in ASM_IDENTIFIERS and self._at("(", ahead=1)):
452
+ self._advance()
453
+ self._skip_parenthesized()
454
+ elif token.text in QUALIFIER_IDENTIFIERS:
455
+ self._advance()
456
+ else:
457
+ return
458
+
459
+ # ------------------------------------------------------------------
460
+ # Recovery
461
+ # ------------------------------------------------------------------
462
+
463
+ def _recover(self, start: int, top_level: bool) -> Node:
464
+ """
465
+ Turn the region starting at `start` into an ERROR node. The region ends after a balanced `{...}`
466
+ (and an optional `;`), after a `;` outside parentheses (any `;` at top level), or before a `}`
467
+ that closes the enclosing block.
468
+
469
+ Parameters
470
+ ----------
471
+ start : int
472
+ Index of the first token of the region.
473
+ top_level : bool
474
+ True outside any block (a stray `}` is then part of the error).
475
+
476
+ Returns
477
+ ----------
478
+ Node
479
+ The ERROR node.
480
+ """
481
+ self._position = start
482
+ del self.errors[self._error_marks.pop() if self._error_marks else len(self.errors):]
483
+ first: Token | None = self._peek()
484
+ depth: int = 0
485
+ while (token := self._peek()) is not None:
486
+ text: str = token.text
487
+ if text in ("(", "["):
488
+ depth += 1
489
+ elif text in (")", "]"):
490
+ depth = max(depth - 1, 0)
491
+ elif text == "{":
492
+ self._skip_braces()
493
+ self._accept(";")
494
+ break
495
+ elif text == "}":
496
+ if not top_level and self._position > start:
497
+ break
498
+ self._position += 1
499
+ if depth == 0:
500
+ break
501
+ continue
502
+ elif text == ";" and (depth == 0 or top_level):
503
+ self._position += 1
504
+ break
505
+ self._position += 1
506
+ if self._position == start and self._peek() is not None:
507
+ self._position += 1
508
+ node: Node = Node(NodeKind.ERROR, first, self._previous if self._position else first)
509
+ self.errors.append(node)
510
+ return node
511
+
512
+ # ------------------------------------------------------------------
513
+ # Translation unit and declarations
514
+ # ------------------------------------------------------------------
515
+
516
+ def parse(self) -> Node:
517
+ """
518
+ Parse the whole file.
519
+
520
+ Returns
521
+ ----------
522
+ Node
523
+ The TRANSLATION_UNIT node.
524
+ """
525
+ items: list[Node | None] = []
526
+ while self._peek() is not None:
527
+ start: int = self._position
528
+ self._error_marks.append(len(self.errors))
529
+ try:
530
+ items.append(self._parse_external())
531
+ self._error_marks.pop()
532
+ except ParseError:
533
+ items.append(self._recover(start, top_level=True))
534
+ first: Token | None = self.tokens[0] if self.tokens else None
535
+ last: Token | None = self.tokens[-1] if self.tokens else None
536
+ return Node(NodeKind.TRANSLATION_UNIT, first, last, items)
537
+
538
+ def _identifier_starts_type(self, context: str) -> bool:
539
+ """
540
+ Whether the current identifier is a type name in declaration specifiers. Unknown names are accepted
541
+ when what follows can only be a declaration.
542
+
543
+ Parameters
544
+ ----------
545
+ context : str
546
+ "declaration", "parameter" or "type_name".
547
+
548
+ Returns
549
+ ----------
550
+ bool
551
+ True when the identifier is read as a type.
552
+ """
553
+ token: Token = self._peek() # type: ignore[assignment]
554
+ if is_type_name(token.text, self.type_names):
555
+ return True
556
+ following: Token | None = self._peek(1)
557
+ if following is None:
558
+ return False
559
+ if following.kind is TokenKind.IDENTIFIER and following.text not in ATTRIBUTE_IDENTIFIERS | ASM_IDENTIFIERS:
560
+ return True
561
+ if context in ("parameter", "type_name"):
562
+ return following.text in ("*", ")", ",", "[")
563
+ ahead: int = 1
564
+ while self._at("*", ahead=ahead) or self._at("const", "volatile", "restrict", ahead=ahead):
565
+ ahead += 1
566
+ if ahead == 1:
567
+ return False
568
+ after: Token | None = self._peek(ahead)
569
+ return after is not None and (after.kind is TokenKind.IDENTIFIER or after.text == "(")
570
+
571
+ def _parse_specifiers(self, context: str = "declaration") -> Specifiers:
572
+ """
573
+ Read declaration specifiers (storage, qualifiers, type).
574
+
575
+ Parameters
576
+ ----------
577
+ context : str
578
+ "declaration", "parameter" or "type_name" (changes how unknown type names are guessed).
579
+
580
+ Returns
581
+ ----------
582
+ Specifiers
583
+ What was read (possibly nothing).
584
+ """
585
+ specifiers: Specifiers = Specifiers()
586
+ while (token := self._peek()) is not None:
587
+ text: str = token.text
588
+ start: int = self._position
589
+ if token.kind is TokenKind.KEYWORD:
590
+ if text in STORAGE_KEYWORDS or text in FUNCTION_SPECIFIER_KEYWORDS:
591
+ specifiers.storage.add(text)
592
+ self._advance()
593
+ elif text == "_Atomic" and self._at("(", ahead=1):
594
+ self._advance()
595
+ self._skip_parenthesized()
596
+ specifiers.type_words.append(text)
597
+ elif text in QUALIFIER_KEYWORDS:
598
+ specifiers.qualifiers.add(text)
599
+ self._advance()
600
+ elif text in TYPE_KEYWORDS:
601
+ specifiers.type_words.append(text)
602
+ self._advance()
603
+ elif text in ("struct", "union"):
604
+ specifiers.type_node = self._parse_record()
605
+ elif text == "enum":
606
+ specifiers.type_node = self._parse_enum()
607
+ elif text in PARENTHESIZED_SPECIFIERS:
608
+ self._advance()
609
+ self._skip_parenthesized()
610
+ if text.startswith("typeof"):
611
+ specifiers.type_words.append(text)
612
+ else:
613
+ break
614
+ elif token.kind is TokenKind.IDENTIFIER:
615
+ if text in ATTRIBUTE_IDENTIFIERS or text in QUALIFIER_IDENTIFIERS:
616
+ self._skip_attributes()
617
+ elif not specifiers.has_type and self._identifier_starts_type(context):
618
+ specifiers.type_words.append(text)
619
+ self._advance()
620
+ else:
621
+ break
622
+ else:
623
+ break
624
+ specifiers.tokens.extend(self.tokens[start:self._position])
625
+ return specifiers
626
+
627
+ def _parse_external(self) -> Node | None:
628
+ """
629
+ Parse one top-level item: function definition or declaration.
630
+
631
+ Returns
632
+ ----------
633
+ Node | None
634
+ The item, or None for a stray `;`.
635
+
636
+ Raises
637
+ ----------
638
+ ParseError
639
+ The item is not valid.
640
+ """
641
+ if self._accept(";"):
642
+ return None
643
+ first: Token = self._peek() # type: ignore[assignment]
644
+ if self._at("_Static_assert", "static_assert"):
645
+ self._advance()
646
+ self._skip_parenthesized()
647
+ return Node(NodeKind.DECLARATION, first, self._expect(";"), static_assert=True, storage=frozenset(), declarators=())
648
+ specifiers: Specifiers = self._parse_specifiers()
649
+ if not specifiers.tokens and not (self._peek() is not None and self._peek().kind is TokenKind.IDENTIFIER and self._at("(", ahead=1)):
650
+ raise ParseError("expected a declaration", first)
651
+ if self._at(";"):
652
+ return self._declaration_node(first, specifiers, [], self._advance())
653
+ declarator: Node = self._parse_declarator(abstract=False) # type: ignore[assignment]
654
+ if declarator.fields["declares_function"] and self._at("{"):
655
+ body: Node = self._parse_compound()
656
+ return Node(
657
+ NodeKind.FUNCTION_DEFINITION, first, body.last, [specifiers.type_node, declarator, body],
658
+ name=declarator.name,
659
+ storage=frozenset(specifiers.storage),
660
+ specifiers=specifiers,
661
+ return_type=" ".join(token.text for token in specifiers.tokens if token.text not in STORAGE_KEYWORDS | FUNCTION_SPECIFIER_KEYWORDS),
662
+ declarator=declarator,
663
+ body=body,
664
+ )
665
+ return self._finish_declaration(first, specifiers, declarator)
666
+
667
+ def _finish_declaration(self, first: Token, specifiers: Specifiers, declarator: Node) -> Node:
668
+ """
669
+ Parse the rest of a declaration after its first declarator (initialiser, other declarators, `;`).
670
+
671
+ Parameters
672
+ ----------
673
+ first : Token
674
+ First token of the declaration.
675
+ specifiers : Specifiers
676
+ Specifiers already read.
677
+ declarator : Node
678
+ First declarator, already read.
679
+
680
+ Returns
681
+ ----------
682
+ Node
683
+ The DECLARATION or TYPE_DEFINITION node.
684
+
685
+ Raises
686
+ ----------
687
+ ParseError
688
+ The declaration is not valid.
689
+ """
690
+ declarators: list[Node] = [self._parse_initializer_part(declarator)]
691
+ while self._accept(","):
692
+ following: Node = self._parse_declarator(abstract=False) # type: ignore[assignment]
693
+ declarators.append(self._parse_initializer_part(following))
694
+ return self._declaration_node(first, specifiers, declarators, self._expect(";"))
695
+
696
+ def _parse_initializer_part(self, declarator: Node) -> Node:
697
+ """
698
+ Read the optional `= initializer` after a declarator.
699
+
700
+ Parameters
701
+ ----------
702
+ declarator : Node
703
+ The declarator.
704
+
705
+ Returns
706
+ ----------
707
+ Node
708
+ The declarator itself, or an INIT_DECLARATOR wrapping it.
709
+
710
+ Raises
711
+ ----------
712
+ ParseError
713
+ The initialiser is not valid.
714
+ """
715
+ if not self._accept("="):
716
+ return declarator
717
+ value: Node = self._parse_initializer()
718
+ return Node(NodeKind.INIT_DECLARATOR, declarator.first, value.last, [declarator, value], name=declarator.name, declarator=declarator, value=value)
719
+
720
+ def _declaration_node(self, first: Token, specifiers: Specifiers, declarators: list[Node], end: Token) -> Node:
721
+ """
722
+ Build a DECLARATION (or TYPE_DEFINITION) node and record new typedef names.
723
+
724
+ Parameters
725
+ ----------
726
+ first : Token
727
+ First token of the declaration.
728
+ specifiers : Specifiers
729
+ Its specifiers.
730
+ declarators : list[Node]
731
+ Its declarators (possibly with initialisers).
732
+ end : Token
733
+ The closing `;`.
734
+
735
+ Returns
736
+ ----------
737
+ Node
738
+ The node.
739
+ """
740
+ is_typedef: bool = "typedef" in specifiers.storage
741
+ if is_typedef:
742
+ self.type_names.update(declarator.name for declarator in declarators if declarator.name)
743
+ return Node(
744
+ NodeKind.TYPE_DEFINITION if is_typedef else NodeKind.DECLARATION, first, end,
745
+ [specifiers.type_node, *declarators],
746
+ storage=frozenset(specifiers.storage),
747
+ qualifiers=frozenset(specifiers.qualifiers),
748
+ specifiers=specifiers,
749
+ type_node=specifiers.type_node,
750
+ declarators=tuple(declarators),
751
+ )
752
+
753
+ def _parse_record(self) -> Node:
754
+ """
755
+ Parse a struct or union specifier, with or without body.
756
+
757
+ Returns
758
+ ----------
759
+ Node
760
+ The STRUCT_SPECIFIER or UNION_SPECIFIER node.
761
+
762
+ Raises
763
+ ----------
764
+ ParseError
765
+ The specifier is not valid.
766
+ """
767
+ keyword: Token = self._advance()
768
+ self._skip_attributes()
769
+ tag: Token | None = self._peek() if self._peek() is not None and self._peek().kind is TokenKind.IDENTIFIER else None
770
+ if tag is not None:
771
+ self._advance()
772
+ self._skip_attributes()
773
+ members: list[Node] = []
774
+ body_open: Token | None = None
775
+ body_close: Token | None = None
776
+ if self._at("{"):
777
+ body_open = self._advance()
778
+ while not self._at("}"):
779
+ if self._peek() is None:
780
+ raise ParseError("unterminated structure body", body_open)
781
+ start: int = self._position
782
+ self._error_marks.append(len(self.errors))
783
+ try:
784
+ members.append(self._parse_field_declaration())
785
+ self._error_marks.pop()
786
+ except ParseError:
787
+ members.append(self._recover(start, top_level=False))
788
+ body_close = self._advance()
789
+ self._skip_attributes()
790
+ kind: NodeKind = NodeKind.STRUCT_SPECIFIER if keyword.text == "struct" else NodeKind.UNION_SPECIFIER
791
+ return Node(
792
+ kind, keyword, self._previous, members,
793
+ name=tag.text if tag is not None else None,
794
+ name_token=tag,
795
+ has_body=body_open is not None,
796
+ body_open=body_open,
797
+ body_close=body_close,
798
+ fields=tuple(members),
799
+ )
800
+
801
+ def _parse_field_declaration(self) -> Node:
802
+ """
803
+ Parse one declaration inside a struct or union body.
804
+
805
+ Returns
806
+ ----------
807
+ Node
808
+ The FIELD_DECLARATION node.
809
+
810
+ Raises
811
+ ----------
812
+ ParseError
813
+ The declaration is not valid.
814
+ """
815
+ first: Token = self._peek() # type: ignore[assignment]
816
+ specifiers: Specifiers = self._parse_specifiers()
817
+ if not specifiers.has_type:
818
+ raise ParseError("expected a field type", first)
819
+ declarators: list[Node] = []
820
+ while not self._at(";"):
821
+ declarator: Node | None = None
822
+ if not self._at(":"):
823
+ declarator = self._parse_declarator(abstract=False)
824
+ if self._accept(":"):
825
+ width: Node = self._parse_conditional()
826
+ if declarator is None:
827
+ declarator = Node(
828
+ NodeKind.DECLARATOR, width.first, width.last,
829
+ name=None, name_token=None, pointers=(), star_tokens=(), pointer_depth=0, suffixes=(), nested=None,
830
+ declares_function=False, parameters=None, own_parameters=None,
831
+ )
832
+ declarator.children.append(width)
833
+ width.parent = declarator
834
+ declarator.last = width.last
835
+ declarator.fields["bit_width"] = width
836
+ if declarator is not None:
837
+ declarators.append(declarator)
838
+ if not self._accept(","):
839
+ break
840
+ end: Token = self._expect(";")
841
+ return Node(
842
+ NodeKind.FIELD_DECLARATION, first, end, [specifiers.type_node, *declarators],
843
+ specifiers=specifiers,
844
+ qualifiers=frozenset(specifiers.qualifiers),
845
+ type_node=specifiers.type_node,
846
+ declarators=tuple(declarators),
847
+ )
848
+
849
+ def _parse_enum(self) -> Node:
850
+ """
851
+ Parse an enum specifier, with or without body.
852
+
853
+ Returns
854
+ ----------
855
+ Node
856
+ The ENUM_SPECIFIER node.
857
+
858
+ Raises
859
+ ----------
860
+ ParseError
861
+ The specifier is not valid.
862
+ """
863
+ keyword: Token = self._advance()
864
+ self._skip_attributes()
865
+ tag: Token | None = self._peek() if self._peek() is not None and self._peek().kind is TokenKind.IDENTIFIER else None
866
+ if tag is not None:
867
+ self._advance()
868
+ if self._accept(":"):
869
+ self._parse_specifiers("type_name")
870
+ enumerators: list[Node] = []
871
+ has_body: bool = False
872
+ body_open: Token | None = None
873
+ if self._at("{"):
874
+ has_body = True
875
+ body_open = self._advance()
876
+ while not self._at("}"):
877
+ name: Token = self._expect_identifier()
878
+ self._skip_attributes()
879
+ value: Node | None = None
880
+ if self._accept("="):
881
+ value = self._parse_conditional()
882
+ enumerators.append(Node(NodeKind.ENUMERATOR, name, self._previous, [value], name=name.text, name_token=name, value=value))
883
+ if not self._accept(","):
884
+ break
885
+ body_close: Token | None = self._expect("}") if has_body else None
886
+ return Node(
887
+ NodeKind.ENUM_SPECIFIER, keyword, self._previous, enumerators,
888
+ name=tag.text if tag is not None else None,
889
+ name_token=tag,
890
+ has_body=has_body,
891
+ body_open=body_open,
892
+ body_close=body_close,
893
+ enumerators=tuple(enumerators),
894
+ )
895
+
896
+ # ------------------------------------------------------------------
897
+ # Declarators
898
+ # ------------------------------------------------------------------
899
+
900
+ def _starts_nested_declarator(self, abstract: bool) -> bool:
901
+ """
902
+ Whether the current `(` opens a nested declarator rather than a parameter list.
903
+
904
+ Parameters
905
+ ----------
906
+ abstract : bool
907
+ True when the declarator may have no name (parameters, type names).
908
+
909
+ Returns
910
+ ----------
911
+ bool
912
+ True for a nested declarator.
913
+ """
914
+ if not abstract:
915
+ return True
916
+ following: Token | None = self._peek(1)
917
+ if following is None:
918
+ return False
919
+ if following.text in ("*", "[", "^"):
920
+ return True
921
+ return following.kind is TokenKind.IDENTIFIER and not is_type_name(following.text, self.type_names) and self._at(")", ahead=2)
922
+
923
+ def _parse_declarator(self, abstract: bool) -> Node | None:
924
+ """
925
+ Parse a declarator: pointers, then a name or a nested declarator, then array and function suffixes.
926
+
927
+ Parameters
928
+ ----------
929
+ abstract : bool
930
+ True when the name is optional (parameters, type names).
931
+
932
+ Returns
933
+ ----------
934
+ Node | None
935
+ DECLARATOR or FUNCTION_DECLARATOR node, or None for an empty abstract declarator.
936
+
937
+ Raises
938
+ ----------
939
+ ParseError
940
+ The declarator is not valid.
941
+ """
942
+ start: int = self._position
943
+ pointers: list[tuple[str, ...]] = []
944
+ stars: list[Token] = []
945
+ while self._at("*"):
946
+ stars.append(self._advance())
947
+ qualifiers: list[str] = []
948
+ while (token := self._peek()) is not None and (token.text in QUALIFIER_KEYWORDS or token.text in QUALIFIER_IDENTIFIERS or token.text in ATTRIBUTE_IDENTIFIERS):
949
+ if token.text in ATTRIBUTE_IDENTIFIERS:
950
+ self._skip_attributes()
951
+ else:
952
+ qualifiers.append(self._advance().text)
953
+ pointers.append(tuple(qualifiers))
954
+ self._skip_attributes()
955
+ name_token: Token | None = None
956
+ nested: Node | None = None
957
+ token: Token | None = self._peek()
958
+ if token is not None and token.kind is TokenKind.IDENTIFIER and token.text not in ASM_IDENTIFIERS:
959
+ name_token = self._advance()
960
+ elif self._at("(") and self._starts_nested_declarator(abstract):
961
+ self._advance()
962
+ nested = self._parse_declarator(abstract)
963
+ self._expect(")")
964
+ elif not abstract:
965
+ raise ParseError("expected a declarator", token)
966
+ children: list[Node | None] = [nested]
967
+ suffixes: list[str] = []
968
+ parameter_lists: list[Node] = []
969
+ while True:
970
+ if self._at("["):
971
+ self._advance()
972
+ while self._at("static", "const", "volatile", "restrict"):
973
+ self._advance()
974
+ size: Node | None = None
975
+ if self._at("*") and self._at("]", ahead=1):
976
+ self._advance()
977
+ elif not self._at("]"):
978
+ size = self._parse_assignment()
979
+ self._expect("]")
980
+ suffixes.append("array")
981
+ children.append(size)
982
+ elif self._at("("):
983
+ parameters: Node = self._parse_parameter_list()
984
+ suffixes.append("function")
985
+ parameter_lists.append(parameters)
986
+ children.append(parameters)
987
+ else:
988
+ break
989
+ self._skip_attributes()
990
+ if self._position == start:
991
+ return None
992
+ name: str | None = name_token.text if name_token is not None else (nested.name if nested is not None else None)
993
+ declares_function: bool
994
+ own_parameters: Node | None = parameter_lists[0] if suffixes and suffixes[0] == "function" else None
995
+ if nested is not None and nested.fields["suffixes"]:
996
+ declares_function = nested.fields["declares_function"]
997
+ function_parameters: Node | None = nested.fields["parameters"]
998
+ elif nested is not None and nested.fields["pointers"]:
999
+ declares_function = False
1000
+ function_parameters = None
1001
+ else:
1002
+ declares_function = own_parameters is not None
1003
+ function_parameters = own_parameters
1004
+ pointer_depth: int = len(pointers) + (nested.fields["pointer_depth"] if nested is not None else 0)
1005
+ return Node(
1006
+ NodeKind.FUNCTION_DECLARATOR if "function" in suffixes else NodeKind.DECLARATOR,
1007
+ self.tokens[start], self._previous, children,
1008
+ name=name,
1009
+ name_token=name_token if name_token is not None else (nested.fields["name_token"] if nested is not None else None),
1010
+ pointers=tuple(pointers),
1011
+ star_tokens=tuple(stars),
1012
+ pointer_depth=pointer_depth,
1013
+ suffixes=tuple(suffixes),
1014
+ nested=nested,
1015
+ declares_function=declares_function,
1016
+ parameters=function_parameters,
1017
+ own_parameters=own_parameters,
1018
+ )
1019
+
1020
+ def _parse_parameter_list(self) -> Node:
1021
+ """
1022
+ Parse a parenthesised parameter list.
1023
+
1024
+ Returns
1025
+ ----------
1026
+ Node
1027
+ The PARAMETER_LIST node; fields `empty` (no parameter at all), `void` (`(void)`) and `variadic`.
1028
+
1029
+ Raises
1030
+ ----------
1031
+ ParseError
1032
+ The list is not valid.
1033
+ """
1034
+ opening: Token = self._expect("(")
1035
+ parameters: list[Node] = []
1036
+ variadic: bool = False
1037
+ if not self._at(")"):
1038
+ while True:
1039
+ if self._accept("..."):
1040
+ variadic = True
1041
+ break
1042
+ parameters.append(self._parse_parameter())
1043
+ if not self._accept(","):
1044
+ break
1045
+ closing: Token = self._expect(")")
1046
+ void: bool = (
1047
+ len(parameters) == 1 and parameters[0].fields["declarator"] is None
1048
+ and parameters[0].fields["specifiers"].type_words == ["void"]
1049
+ )
1050
+ return Node(
1051
+ NodeKind.PARAMETER_LIST, opening, closing, parameters,
1052
+ parameters=() if void else tuple(parameters),
1053
+ empty=not parameters and not variadic,
1054
+ void=void,
1055
+ variadic=variadic,
1056
+ )
1057
+
1058
+ def _parse_parameter(self) -> Node:
1059
+ """
1060
+ Parse one parameter declaration.
1061
+
1062
+ Returns
1063
+ ----------
1064
+ Node
1065
+ The PARAMETER node.
1066
+
1067
+ Raises
1068
+ ----------
1069
+ ParseError
1070
+ The parameter is not valid.
1071
+ """
1072
+ start: int = self._position
1073
+ specifiers: Specifiers = self._parse_specifiers("parameter")
1074
+ if not specifiers.tokens:
1075
+ raise ParseError("expected a parameter type", self._peek())
1076
+ declarator: Node | None = self._parse_declarator(abstract=True)
1077
+ name_token: Token | None = declarator.fields["name_token"] if declarator is not None else None
1078
+ type_text: str = " ".join(token.text for token in self.tokens[start:self._position] if token is not name_token)
1079
+ return Node(
1080
+ NodeKind.PARAMETER, self.tokens[start], self._previous, [specifiers.type_node, declarator],
1081
+ name=declarator.name if declarator is not None else None,
1082
+ name_token=name_token,
1083
+ specifiers=specifiers,
1084
+ qualifiers=frozenset(specifiers.qualifiers),
1085
+ declarator=declarator,
1086
+ pointer_depth=declarator.fields["pointer_depth"] if declarator is not None else 0,
1087
+ type_text=type_text,
1088
+ )
1089
+
1090
+ def _parse_type_name(self) -> Node:
1091
+ """
1092
+ Parse an abstract type (casts, `sizeof`, compound literals).
1093
+
1094
+ Returns
1095
+ ----------
1096
+ Node
1097
+ The TYPE_NAME node.
1098
+
1099
+ Raises
1100
+ ----------
1101
+ ParseError
1102
+ The type is not valid.
1103
+ """
1104
+ start: int = self._position
1105
+ specifiers: Specifiers = self._parse_specifiers("type_name")
1106
+ if not specifiers.has_type and not specifiers.qualifiers:
1107
+ raise ParseError("expected a type", self._peek())
1108
+ declarator: Node | None = self._parse_declarator(abstract=True)
1109
+ return Node(
1110
+ NodeKind.TYPE_NAME, self.tokens[start], self._previous, [specifiers.type_node, declarator],
1111
+ specifiers=specifiers,
1112
+ declarator=declarator,
1113
+ pointer_depth=declarator.fields["pointer_depth"] if declarator is not None else 0,
1114
+ )
1115
+
1116
+ def _parse_initializer(self) -> Node:
1117
+ """
1118
+ Parse an initialiser: braced list or expression.
1119
+
1120
+ Returns
1121
+ ----------
1122
+ Node
1123
+ The INITIALIZER_LIST node or the expression.
1124
+
1125
+ Raises
1126
+ ----------
1127
+ ParseError
1128
+ The initialiser is not valid.
1129
+ """
1130
+ if not self._at("{"):
1131
+ return self._parse_assignment()
1132
+ opening: Token = self._advance()
1133
+ items: list[Node] = []
1134
+ while not self._at("}"):
1135
+ while self._at(".", "["):
1136
+ if self._advance().text == ".":
1137
+ self._expect_identifier()
1138
+ else:
1139
+ self._parse_conditional()
1140
+ if self._accept("..."):
1141
+ self._parse_conditional()
1142
+ self._expect("]")
1143
+ self._accept("=")
1144
+ items.append(self._parse_initializer())
1145
+ if not self._accept(","):
1146
+ break
1147
+ closing: Token = self._expect("}")
1148
+ return Node(NodeKind.INITIALIZER_LIST, opening, closing, items)
1149
+
1150
+ # ------------------------------------------------------------------
1151
+ # Statements
1152
+ # ------------------------------------------------------------------
1153
+
1154
+ def _looks_like_declaration(self) -> bool:
1155
+ """
1156
+ Whether the block item at the current token is a declaration rather than a statement.
1157
+
1158
+ Returns
1159
+ ----------
1160
+ bool
1161
+ True for a declaration.
1162
+ """
1163
+ token: Token | None = self._peek()
1164
+ if token is None:
1165
+ return False
1166
+ if token.kind is TokenKind.KEYWORD:
1167
+ return token.text in DECLARATION_KEYWORDS
1168
+ if token.kind is not TokenKind.IDENTIFIER:
1169
+ return False
1170
+ if token.text in ATTRIBUTE_IDENTIFIERS or token.text == "__extension__":
1171
+ return True
1172
+ following: Token | None = self._peek(1)
1173
+ if following is None:
1174
+ return False
1175
+ if is_type_name(token.text, self.type_names):
1176
+ return following.kind is TokenKind.IDENTIFIER or following.text in ("*", "(") or following.text in QUALIFIER_KEYWORDS
1177
+ if following.kind is TokenKind.IDENTIFIER:
1178
+ return following.text not in ASM_IDENTIFIERS
1179
+ ahead: int = 1
1180
+ while self._at("*", ahead=ahead):
1181
+ ahead += 1
1182
+ name: Token | None = self._peek(ahead)
1183
+ return ahead > 1 and name is not None and name.kind is TokenKind.IDENTIFIER and self._at(*DECLARATOR_FOLLOWERS, ahead=ahead + 1)
1184
+
1185
+ def _parse_compound(self) -> Node:
1186
+ """
1187
+ Parse a block `{ ... }`; invalid items become ERROR nodes.
1188
+
1189
+ Returns
1190
+ ----------
1191
+ Node
1192
+ The COMPOUND_STATEMENT node.
1193
+
1194
+ Raises
1195
+ ----------
1196
+ ParseError
1197
+ The block is not closed before the end of the file.
1198
+ """
1199
+ opening: Token = self._expect("{")
1200
+ items: list[Node] = []
1201
+ while not self._at("}"):
1202
+ if self._peek() is None:
1203
+ raise ParseError("unterminated block", opening)
1204
+ start: int = self._position
1205
+ self._error_marks.append(len(self.errors))
1206
+ try:
1207
+ items.append(self._parse_block_item())
1208
+ self._error_marks.pop()
1209
+ except ParseError:
1210
+ items.append(self._recover(start, top_level=False))
1211
+ closing: Token = self._advance()
1212
+ return Node(NodeKind.COMPOUND_STATEMENT, opening, closing, items)
1213
+
1214
+ def _parse_block_item(self) -> Node:
1215
+ """
1216
+ Parse one item of a block: declaration or statement.
1217
+
1218
+ Returns
1219
+ ----------
1220
+ Node
1221
+ The item.
1222
+
1223
+ Raises
1224
+ ----------
1225
+ ParseError
1226
+ The item is not valid.
1227
+ """
1228
+ if self._looks_like_declaration():
1229
+ return self._parse_local_declaration()
1230
+ return self._parse_statement()
1231
+
1232
+ def _parse_local_declaration(self) -> Node:
1233
+ """
1234
+ Parse a declaration inside a block or a `for` header.
1235
+
1236
+ Returns
1237
+ ----------
1238
+ Node
1239
+ The DECLARATION or TYPE_DEFINITION node.
1240
+
1241
+ Raises
1242
+ ----------
1243
+ ParseError
1244
+ The declaration is not valid.
1245
+ """
1246
+ first: Token = self._peek() # type: ignore[assignment]
1247
+ if self._at("_Static_assert", "static_assert"):
1248
+ self._advance()
1249
+ self._skip_parenthesized()
1250
+ return Node(NodeKind.DECLARATION, first, self._expect(";"), static_assert=True, storage=frozenset(), declarators=())
1251
+ specifiers: Specifiers = self._parse_specifiers()
1252
+ if not specifiers.tokens:
1253
+ raise ParseError("expected a declaration", first)
1254
+ if self._at(";"):
1255
+ return self._declaration_node(first, specifiers, [], self._advance())
1256
+ declarator: Node = self._parse_declarator(abstract=False) # type: ignore[assignment]
1257
+ return self._finish_declaration(first, specifiers, declarator)
1258
+
1259
+ def _parse_condition(self) -> Node:
1260
+ """
1261
+ Parse a parenthesised controlling expression.
1262
+
1263
+ Returns
1264
+ ----------
1265
+ Node
1266
+ The CONDITION node (its span is the expression; the parentheses are in `open_paren` / `close_paren`).
1267
+
1268
+ Raises
1269
+ ----------
1270
+ ParseError
1271
+ The condition is not valid.
1272
+ """
1273
+ opening: Token = self._expect("(")
1274
+ expression: Node = self._parse_expression()
1275
+ closing: Token = self._expect(")")
1276
+ return Node(NodeKind.CONDITION, expression.first, expression.last, [expression], expression=expression, open_paren=opening, close_paren=closing)
1277
+
1278
+ def _parse_statement(self) -> Node:
1279
+ """
1280
+ Parse one statement.
1281
+
1282
+ Returns
1283
+ ----------
1284
+ Node
1285
+ The statement node.
1286
+
1287
+ Raises
1288
+ ----------
1289
+ ParseError
1290
+ The statement is not valid.
1291
+ """
1292
+ token: Token | None = self._peek()
1293
+ if token is None:
1294
+ raise ParseError("expected a statement", self.tokens[-1] if self.tokens else None)
1295
+ text: str = token.text
1296
+ if text == "{" and token.kind is TokenKind.PUNCTUATOR:
1297
+ return self._parse_compound()
1298
+ if token.kind is TokenKind.KEYWORD:
1299
+ if text == "if":
1300
+ return self._parse_if()
1301
+ if text == "while":
1302
+ keyword: Token = self._advance()
1303
+ condition: Node = self._parse_condition()
1304
+ body: Node = self._parse_statement()
1305
+ return Node(NodeKind.WHILE_STATEMENT, keyword, body.last, [condition, body], condition=condition, body=body)
1306
+ if text == "do":
1307
+ keyword = self._advance()
1308
+ body = self._parse_statement()
1309
+ while_token: Token = self._expect("while")
1310
+ condition = self._parse_condition()
1311
+ end: Token = self._expect(";")
1312
+ return Node(NodeKind.DO_STATEMENT, keyword, end, [body, condition], condition=condition, body=body, while_token=while_token)
1313
+ if text == "for":
1314
+ return self._parse_for()
1315
+ if text == "switch":
1316
+ keyword = self._advance()
1317
+ condition = self._parse_condition()
1318
+ body = self._parse_statement()
1319
+ return Node(NodeKind.SWITCH_STATEMENT, keyword, body.last, [condition, body], condition=condition, body=body)
1320
+ if text in ("case", "default"):
1321
+ keyword = self._advance()
1322
+ value: Node | None = None
1323
+ if text == "case":
1324
+ value = self._parse_conditional()
1325
+ if self._accept("..."):
1326
+ self._parse_conditional()
1327
+ colon: Token = self._expect(":")
1328
+ statement: Node | None = None if self._at("}") else self._parse_statement()
1329
+ return Node(NodeKind.CASE_STATEMENT, keyword, statement.last if statement else colon, [value, statement], value=value, statement=statement, default=text == "default")
1330
+ if text == "return":
1331
+ keyword = self._advance()
1332
+ value = None if self._at(";") else self._parse_expression()
1333
+ end = self._expect(";")
1334
+ return Node(NodeKind.RETURN_STATEMENT, keyword, end, [value], value=value)
1335
+ if text in ("break", "continue"):
1336
+ keyword = self._advance()
1337
+ end = self._expect(";")
1338
+ return Node(NodeKind.BREAK_STATEMENT if text == "break" else NodeKind.CONTINUE_STATEMENT, keyword, end)
1339
+ if text == "goto":
1340
+ keyword = self._advance()
1341
+ label: Token = self._expect_identifier()
1342
+ end = self._expect(";")
1343
+ return Node(NodeKind.GOTO_STATEMENT, keyword, end, name=label.text, name_token=label)
1344
+ if token.kind is TokenKind.IDENTIFIER and self._at(":", ahead=1):
1345
+ label = self._advance()
1346
+ colon = self._advance()
1347
+ statement = None if self._at("}") else self._parse_statement()
1348
+ return Node(NodeKind.LABELED_STATEMENT, label, statement.last if statement else colon, [statement], name=label.text, name_token=label, statement=statement)
1349
+ if text == ";" and token.kind is TokenKind.PUNCTUATOR:
1350
+ end = self._advance()
1351
+ return Node(NodeKind.EXPRESSION_STATEMENT, end, end, expression=None)
1352
+ expression: Node = self._parse_expression()
1353
+ end = self._expect(";")
1354
+ return Node(NodeKind.EXPRESSION_STATEMENT, expression.first, end, [expression], expression=expression)
1355
+
1356
+ def _parse_if(self) -> Node:
1357
+ """
1358
+ Parse an `if` statement with its optional `else` branch.
1359
+
1360
+ Returns
1361
+ ----------
1362
+ Node
1363
+ The IF_STATEMENT node.
1364
+
1365
+ Raises
1366
+ ----------
1367
+ ParseError
1368
+ The statement is not valid.
1369
+ """
1370
+ keyword: Token = self._advance()
1371
+ condition: Node = self._parse_condition()
1372
+ consequence: Node = self._parse_statement()
1373
+ alternative: Node | None = None
1374
+ else_token: Token | None = self._accept("else")
1375
+ if else_token is not None:
1376
+ alternative = self._parse_statement()
1377
+ last: Token = alternative.last if alternative is not None else consequence.last # type: ignore[assignment]
1378
+ return Node(
1379
+ NodeKind.IF_STATEMENT, keyword, last, [condition, consequence, alternative],
1380
+ condition=condition, consequence=consequence, alternative=alternative, else_token=else_token,
1381
+ )
1382
+
1383
+ def _parse_for(self) -> Node:
1384
+ """
1385
+ Parse a `for` loop. Its three header parts are wrapped in FOR_INIT, CONDITION and FOR_UPDATE nodes.
1386
+
1387
+ Returns
1388
+ ----------
1389
+ Node
1390
+ The FOR_STATEMENT node.
1391
+
1392
+ Raises
1393
+ ----------
1394
+ ParseError
1395
+ The loop is not valid.
1396
+ """
1397
+ keyword: Token = self._advance()
1398
+ opening: Token = self._expect("(")
1399
+ init: Node | None = None
1400
+ if self._at(";"):
1401
+ self._advance()
1402
+ elif self._looks_like_declaration():
1403
+ declaration: Node = self._parse_local_declaration()
1404
+ init = Node(NodeKind.FOR_INIT, declaration.first, declaration.last, [declaration], declaration=declaration)
1405
+ else:
1406
+ expression: Node = self._parse_expression()
1407
+ init = Node(NodeKind.FOR_INIT, expression.first, expression.last, [expression], expression=expression)
1408
+ self._expect(";")
1409
+ condition: Node | None = None
1410
+ if not self._at(";"):
1411
+ expression = self._parse_expression()
1412
+ condition = Node(NodeKind.CONDITION, expression.first, expression.last, [expression], expression=expression)
1413
+ self._expect(";")
1414
+ update: Node | None = None
1415
+ if not self._at(")"):
1416
+ expression = self._parse_expression()
1417
+ update = Node(NodeKind.FOR_UPDATE, expression.first, expression.last, [expression], expression=expression)
1418
+ closing: Token = self._expect(")")
1419
+ body: Node = self._parse_statement()
1420
+ return Node(
1421
+ NodeKind.FOR_STATEMENT, keyword, body.last, [init, condition, update, body],
1422
+ init=init, condition=condition, update=update, body=body, open_paren=opening, close_paren=closing,
1423
+ )
1424
+
1425
+ # ------------------------------------------------------------------
1426
+ # Expressions
1427
+ # ------------------------------------------------------------------
1428
+
1429
+ def _parse_expression(self) -> Node:
1430
+ """
1431
+ Parse an expression, comma operator included.
1432
+
1433
+ Returns
1434
+ ----------
1435
+ Node
1436
+ The expression node.
1437
+
1438
+ Raises
1439
+ ----------
1440
+ ParseError
1441
+ The expression is not valid.
1442
+ """
1443
+ first: Node = self._parse_assignment()
1444
+ if not self._at(","):
1445
+ return first
1446
+ items: list[Node] = [first]
1447
+ while self._accept(","):
1448
+ items.append(self._parse_assignment())
1449
+ return Node(NodeKind.COMMA_EXPRESSION, first.first, items[-1].last, items, operands=tuple(items))
1450
+
1451
+ def _parse_assignment(self) -> Node:
1452
+ """
1453
+ Parse an assignment expression (right-associative).
1454
+
1455
+ Returns
1456
+ ----------
1457
+ Node
1458
+ The expression node.
1459
+
1460
+ Raises
1461
+ ----------
1462
+ ParseError
1463
+ The expression is not valid.
1464
+ """
1465
+ left: Node = self._parse_conditional()
1466
+ token: Token | None = self._peek()
1467
+ if token is not None and token.kind is TokenKind.PUNCTUATOR and token.text in ASSIGNMENT_OPERATORS:
1468
+ operator: Token = self._advance()
1469
+ right: Node = self._parse_assignment()
1470
+ return Node(NodeKind.ASSIGNMENT_EXPRESSION, left.first, right.last, [left, right], operator=operator.text, operator_token=operator, left=left, right=right)
1471
+ return left
1472
+
1473
+ def _parse_conditional(self) -> Node:
1474
+ """
1475
+ Parse a conditional (ternary) expression.
1476
+
1477
+ Returns
1478
+ ----------
1479
+ Node
1480
+ The expression node.
1481
+
1482
+ Raises
1483
+ ----------
1484
+ ParseError
1485
+ The expression is not valid.
1486
+ """
1487
+ condition: Node = self._parse_binary(1)
1488
+ if not self._at("?"):
1489
+ return condition
1490
+ question: Token = self._advance()
1491
+ consequence: Node = self._parse_expression()
1492
+ colon: Token = self._expect(":")
1493
+ alternative: Node = self._parse_conditional()
1494
+ return Node(
1495
+ NodeKind.CONDITIONAL_EXPRESSION, condition.first, alternative.last, [condition, consequence, alternative],
1496
+ condition=condition, consequence=consequence, alternative=alternative, question_token=question, colon_token=colon,
1497
+ )
1498
+
1499
+ def _parse_binary(self, minimum: int) -> Node:
1500
+ """
1501
+ Parse binary operators by precedence climbing.
1502
+
1503
+ Parameters
1504
+ ----------
1505
+ minimum : int
1506
+ Lowest precedence accepted at this level.
1507
+
1508
+ Returns
1509
+ ----------
1510
+ Node
1511
+ The expression node.
1512
+
1513
+ Raises
1514
+ ----------
1515
+ ParseError
1516
+ The expression is not valid.
1517
+ """
1518
+ left: Node = self._parse_cast()
1519
+ while (token := self._peek()) is not None and token.kind is TokenKind.PUNCTUATOR and BINARY_PRECEDENCE.get(token.text, 0) >= minimum:
1520
+ precedence: int = BINARY_PRECEDENCE[token.text]
1521
+ operator: Token = self._advance()
1522
+ right: Node = self._parse_binary(precedence + 1)
1523
+ kind: NodeKind = NodeKind.LOGICAL_EXPRESSION if operator.text in ("&&", "||") else NodeKind.BINARY_EXPRESSION
1524
+ left = Node(kind, left.first, right.last, [left, right], operator=operator.text, operator_token=operator, left=left, right=right)
1525
+ return left
1526
+
1527
+ def _starts_type_name(self, ahead: int) -> bool:
1528
+ """
1529
+ Whether the token at `ahead` starts a type name (to tell a cast from a parenthesised expression).
1530
+
1531
+ Parameters
1532
+ ----------
1533
+ ahead : int
1534
+ Distance from the current token.
1535
+
1536
+ Returns
1537
+ ----------
1538
+ bool
1539
+ True when a type name starts there.
1540
+ """
1541
+ token: Token | None = self._peek(ahead)
1542
+ if token is None:
1543
+ return False
1544
+ if token.kind is TokenKind.KEYWORD:
1545
+ return token.text in TYPE_KEYWORDS | QUALIFIER_KEYWORDS | PARENTHESIZED_SPECIFIERS | {"struct", "union", "enum"}
1546
+ if token.kind is not TokenKind.IDENTIFIER:
1547
+ return False
1548
+ if is_type_name(token.text, self.type_names):
1549
+ return True
1550
+ stars: int = 1
1551
+ while self._at("*", ahead=ahead + stars):
1552
+ stars += 1
1553
+ return stars > 1 and self._at(")", ahead=ahead + stars)
1554
+
1555
+ def _parse_cast(self) -> Node:
1556
+ """
1557
+ Parse a cast or compound literal, or fall back to a unary expression.
1558
+
1559
+ Returns
1560
+ ----------
1561
+ Node
1562
+ The expression node.
1563
+
1564
+ Raises
1565
+ ----------
1566
+ ParseError
1567
+ The expression is not valid.
1568
+ """
1569
+ if self._at("(") and self._starts_type_name(1):
1570
+ opening: Token = self._advance()
1571
+ type_name: Node = self._parse_type_name()
1572
+ self._expect(")")
1573
+ if self._at("{"):
1574
+ initializer: Node = self._parse_initializer()
1575
+ literal: Node = Node(NodeKind.COMPOUND_LITERAL, opening, initializer.last, [type_name, initializer], type=type_name, value=initializer)
1576
+ return self._parse_postfix_operators(literal)
1577
+ operand: Node = self._parse_cast()
1578
+ return Node(NodeKind.CAST_EXPRESSION, opening, operand.last, [type_name, operand], type=type_name, value=operand)
1579
+ return self._parse_unary()
1580
+
1581
+ def _parse_unary(self) -> Node:
1582
+ """
1583
+ Parse prefix operators, `sizeof` and `_Alignof`.
1584
+
1585
+ Returns
1586
+ ----------
1587
+ Node
1588
+ The expression node.
1589
+
1590
+ Raises
1591
+ ----------
1592
+ ParseError
1593
+ The expression is not valid.
1594
+ """
1595
+ token: Token | None = self._peek()
1596
+ if token is None:
1597
+ raise ParseError("expected an expression", self.tokens[-1] if self.tokens else None)
1598
+ if token.kind is TokenKind.PUNCTUATOR and token.text in ("++", "--"):
1599
+ operator: Token = self._advance()
1600
+ operand: Node = self._parse_unary()
1601
+ return Node(NodeKind.UPDATE_EXPRESSION, operator, operand.last, [operand], operator=operator.text, operator_token=operator, prefix=True, operand=operand)
1602
+ if token.kind is TokenKind.PUNCTUATOR and token.text in UNARY_OPERATORS:
1603
+ operator = self._advance()
1604
+ operand = self._parse_cast()
1605
+ return Node(NodeKind.UNARY_EXPRESSION, operator, operand.last, [operand], operator=operator.text, operator_token=operator, operand=operand)
1606
+ if token.text in ("sizeof", "_Alignof", "alignof") and token.kind is TokenKind.KEYWORD:
1607
+ keyword: Token = self._advance()
1608
+ if self._at("(") and self._starts_type_name(1):
1609
+ self._advance()
1610
+ type_name: Node = self._parse_type_name()
1611
+ closing: Token = self._expect(")")
1612
+ return Node(NodeKind.SIZEOF_EXPRESSION, keyword, closing, [type_name], operator=keyword.text, type=type_name, value=None)
1613
+ operand = self._parse_unary()
1614
+ return Node(NodeKind.SIZEOF_EXPRESSION, keyword, operand.last, [operand], operator=keyword.text, type=None, value=operand)
1615
+ return self._parse_postfix_operators(self._parse_primary())
1616
+
1617
+ def _parse_postfix_operators(self, expression: Node) -> Node:
1618
+ """
1619
+ Parse calls, subscripts, member accesses and postfix `++` / `--` after an expression.
1620
+
1621
+ Parameters
1622
+ ----------
1623
+ expression : Node
1624
+ The operand already parsed.
1625
+
1626
+ Returns
1627
+ ----------
1628
+ Node
1629
+ The expression node.
1630
+
1631
+ Raises
1632
+ ----------
1633
+ ParseError
1634
+ The expression is not valid.
1635
+ """
1636
+ while (token := self._peek()) is not None and token.kind is TokenKind.PUNCTUATOR:
1637
+ if token.text == "[":
1638
+ self._advance()
1639
+ index: Node = self._parse_expression()
1640
+ closing: Token = self._expect("]")
1641
+ expression = Node(NodeKind.SUBSCRIPT_EXPRESSION, expression.first, closing, [expression, index], value=expression, index=index)
1642
+ elif token.text == "(":
1643
+ opening: Token = self._advance()
1644
+ arguments: list[Node] = []
1645
+ if not self._at(")"):
1646
+ arguments.append(self._parse_assignment())
1647
+ while self._accept(","):
1648
+ arguments.append(self._parse_assignment())
1649
+ closing = self._expect(")")
1650
+ callee_name: str | None = expression.name if expression.kind is NodeKind.IDENTIFIER else None
1651
+ expression = Node(
1652
+ NodeKind.CALL_EXPRESSION, expression.first, closing, [expression, *arguments],
1653
+ name=callee_name, function=expression, arguments=tuple(arguments), open_paren=opening, close_paren=closing,
1654
+ )
1655
+ elif token.text in (".", "->"):
1656
+ operator: Token = self._advance()
1657
+ member: Token = self._expect_identifier()
1658
+ expression = Node(NodeKind.MEMBER_EXPRESSION, expression.first, member, [expression], operator=operator.text, operator_token=operator, value=expression, field=member.text)
1659
+ elif token.text in ("++", "--"):
1660
+ operator = self._advance()
1661
+ expression = Node(NodeKind.UPDATE_EXPRESSION, expression.first, operator, [expression], operator=operator.text, operator_token=operator, prefix=False, operand=expression)
1662
+ else:
1663
+ break
1664
+ return expression
1665
+
1666
+ def _parse_primary(self) -> Node:
1667
+ """
1668
+ Parse a primary expression: name, constant, string, parenthesised expression or GNU statement
1669
+ expression.
1670
+
1671
+ Returns
1672
+ ----------
1673
+ Node
1674
+ The expression node.
1675
+
1676
+ Raises
1677
+ ----------
1678
+ ParseError
1679
+ No primary expression starts here.
1680
+ """
1681
+ token: Token = self._advance()
1682
+ if token.kind is TokenKind.IDENTIFIER or (token.kind is TokenKind.KEYWORD and token.text in CONSTANT_KEYWORDS):
1683
+ if token.text in ASM_IDENTIFIERS and self._at("(", "volatile", "__volatile__", "goto", "inline"):
1684
+ self._position -= 1
1685
+ return self._parse_opaque_call()
1686
+ return Node(NodeKind.IDENTIFIER, token, token, name=token.text, constant=token.kind is TokenKind.KEYWORD)
1687
+ if token.kind is TokenKind.KEYWORD and token.text == "_Generic":
1688
+ self._position -= 1
1689
+ return self._parse_opaque_call()
1690
+ if token.kind is TokenKind.NUMBER:
1691
+ return Node(NodeKind.NUMBER_LITERAL, token, token, value=token.text)
1692
+ if token.kind is TokenKind.CHAR:
1693
+ return Node(NodeKind.CHAR_LITERAL, token, token, value=token.text)
1694
+ if token.kind is TokenKind.STRING:
1695
+ start: int = self._position - 1
1696
+ while (following := self._peek()) is not None and following.kind is TokenKind.STRING:
1697
+ self._advance()
1698
+ parts: list[Token] = self.tokens[start:self._position]
1699
+ return Node(NodeKind.STRING_LITERAL, token, parts[-1], value=" ".join(part.text for part in parts))
1700
+ if token.text == "(" and token.kind is TokenKind.PUNCTUATOR:
1701
+ if self._at("{"):
1702
+ block: Node = self._parse_compound()
1703
+ closing: Token = self._expect(")")
1704
+ return Node(NodeKind.PARENTHESIZED_EXPRESSION, token, closing, [block], expression=block, statement_expression=True)
1705
+ expression: Node = self._parse_expression()
1706
+ closing = self._expect(")")
1707
+ return Node(NodeKind.PARENTHESIZED_EXPRESSION, token, closing, [expression], expression=expression, statement_expression=False)
1708
+ raise ParseError("expected an expression", token)
1709
+
1710
+ def _parse_opaque_call(self) -> Node:
1711
+ """
1712
+ Parse `_Generic(...)` or `asm(...)` as a call whose arguments are skipped.
1713
+
1714
+ Returns
1715
+ ----------
1716
+ Node
1717
+ The CALL_EXPRESSION node (no argument nodes).
1718
+
1719
+ Raises
1720
+ ----------
1721
+ ParseError
1722
+ The parentheses are not balanced.
1723
+ """
1724
+ name: Token = self._advance()
1725
+ while self._at("volatile", "__volatile__", "goto", "inline"):
1726
+ self._advance()
1727
+ opening: Token | None = self._peek()
1728
+ self._skip_parenthesized()
1729
+ callee: Node = Node(NodeKind.IDENTIFIER, name, name, name=name.text, constant=False)
1730
+ return Node(
1731
+ NodeKind.CALL_EXPRESSION, name, self._previous, [callee],
1732
+ name=name.text, function=callee, arguments=(), open_paren=opening, close_paren=self._previous, opaque=True,
1733
+ )
1734
+
1735
+
1736
+ def parse_tokens(tokens: Iterable[Token], type_names: Iterable[str] = ()) -> tuple[Node, tuple[Node, ...]]:
1737
+ """
1738
+ Parse the tokens of a C or H file.
1739
+
1740
+ Parameters
1741
+ ----------
1742
+ tokens : Iterable[Token]
1743
+ Every token of the file.
1744
+ type_names : Iterable[str]
1745
+ Typedef names known before parsing.
1746
+
1747
+ Returns
1748
+ ----------
1749
+ tuple[Node, tuple[Node, ...]]
1750
+ The TRANSLATION_UNIT node and the ERROR nodes.
1751
+ """
1752
+ parser: Parser = Parser(tokens, type_names)
1753
+ tree: Node = parser.parse()
1754
+ return tree, tuple(parser.errors)