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
File without changes
@@ -0,0 +1,258 @@
1
+ from dataclasses import dataclass
2
+
3
+ from sources.analysis.tokens import Token
4
+ from sources.enums import TokenKind
5
+
6
+
7
+ # Directives that open a conditional block.
8
+ CONDITIONAL_OPENERS: frozenset[str] = frozenset({"if", "ifdef", "ifndef"})
9
+
10
+ # Directives that continue a conditional block at the level of its opener.
11
+ CONDITIONAL_BRANCHES: frozenset[str] = frozenset({"else", "elif", "elifdef", "elifndef"})
12
+
13
+
14
+ @dataclass(frozen=True, slots=True)
15
+ class Directive:
16
+ """
17
+ One preprocessor directive, continuation lines included.
18
+ (dataclass)
19
+
20
+ Attributes
21
+ ----------
22
+ name : str
23
+ Directive name (`include`, `define`, `ifndef`...), or "" for a null directive (`#` alone).
24
+ tokens : tuple[Token, ...]
25
+ Tokens of the directive, from the `#` to the last token before the end of line.
26
+ operand : str
27
+ Text after the directive name, with line splices removed and spaces trimmed.
28
+ depth : int
29
+ Conditional nesting depth: number of enclosing `#if*` blocks (`#else`/`#elif`/`#endif` are at the
30
+ depth of their opener).
31
+ continued : bool
32
+ Whether the directive spans several physical lines (line splices).
33
+ """
34
+
35
+ name: str
36
+ tokens: tuple[Token, ...]
37
+ operand: str
38
+ depth: int
39
+ continued: bool
40
+
41
+ @property
42
+ def line(self) -> int:
43
+ """
44
+ 1-based line of the `#`.
45
+
46
+ Returns
47
+ ----------
48
+ int
49
+ The line.
50
+ """
51
+ return self.tokens[0].line
52
+
53
+ @property
54
+ def column(self) -> int:
55
+ """
56
+ 1-based column of the `#`.
57
+
58
+ Returns
59
+ ----------
60
+ int
61
+ The column.
62
+ """
63
+ return self.tokens[0].column
64
+
65
+ @property
66
+ def end_line(self) -> int:
67
+ """
68
+ 1-based line of the last token of the directive.
69
+
70
+ Returns
71
+ ----------
72
+ int
73
+ The line.
74
+ """
75
+ return self.tokens[-1].end_line
76
+
77
+ @property
78
+ def operand_tokens(self) -> tuple[Token, ...]:
79
+ """
80
+ Non-trivia tokens after the directive name.
81
+
82
+ Returns
83
+ ----------
84
+ tuple[Token, ...]
85
+ The operand tokens.
86
+ """
87
+ return tuple(token for token in self.tokens[1:] if not token.is_trivia)
88
+
89
+
90
+ @dataclass(frozen=True, slots=True)
91
+ class MacroDefinition:
92
+ """
93
+ A `#define` directive, split into its parts.
94
+ (dataclass)
95
+
96
+ Attributes
97
+ ----------
98
+ name : str
99
+ Macro name.
100
+ name_token : Token
101
+ Token of the macro name.
102
+ parameters : tuple[str, ...] | None
103
+ Parameter names of a function-like macro (`...` kept as is), or None for an object-like macro.
104
+ body : tuple[Token, ...]
105
+ Tokens of the replacement list (trivia included).
106
+ directive : Directive
107
+ The directive itself.
108
+ """
109
+
110
+ name: str
111
+ name_token: Token
112
+ parameters: tuple[str, ...] | None
113
+ body: tuple[Token, ...]
114
+ directive: Directive
115
+
116
+
117
+ @dataclass(frozen=True, slots=True)
118
+ class Include:
119
+ """
120
+ An `#include` directive.
121
+ (dataclass)
122
+
123
+ Attributes
124
+ ----------
125
+ target : str
126
+ Included path, without its delimiters (empty when the operand is a macro).
127
+ system : bool
128
+ True for `<...>`, False for `"..."`.
129
+ directive : Directive
130
+ The directive itself.
131
+ """
132
+
133
+ target: str
134
+ system: bool
135
+ directive: Directive
136
+
137
+
138
+ def _operand_text(tokens: tuple[Token, ...]) -> str:
139
+ """
140
+ Text of the operand tokens of a directive, without line splices.
141
+
142
+ Parameters
143
+ ----------
144
+ tokens : tuple[Token, ...]
145
+ Tokens after the directive name.
146
+
147
+ Returns
148
+ ----------
149
+ str
150
+ The trimmed operand text.
151
+ """
152
+ return "".join(" " if token.kind is TokenKind.LINE_SPLICE else token.text for token in tokens).strip()
153
+
154
+
155
+ def collect_directives(tokens: tuple[Token, ...]) -> tuple[Directive, ...]:
156
+ """
157
+ Group the tokens of a file into preprocessor directives.
158
+
159
+ Parameters
160
+ ----------
161
+ tokens : tuple[Token, ...]
162
+ Every token of the file.
163
+
164
+ Returns
165
+ ----------
166
+ tuple[Directive, ...]
167
+ The directives, in order.
168
+ """
169
+ directives: list[Directive] = []
170
+ depth: int = 0
171
+ index: int = 0
172
+ while index < len(tokens):
173
+ token: Token = tokens[index]
174
+ if token.kind is not TokenKind.DIRECTIVE:
175
+ index += 1
176
+ continue
177
+ end: int = index + 1
178
+ while end < len(tokens) and tokens[end].in_directive:
179
+ end += 1
180
+ group: tuple[Token, ...] = tokens[index:end]
181
+ name: str = token.text.lstrip("#%:").strip()
182
+ if name in CONDITIONAL_BRANCHES or name == "endif":
183
+ depth = max(depth - 1, 0)
184
+ directives.append(Directive(
185
+ name=name,
186
+ tokens=group,
187
+ operand=_operand_text(group[1:]),
188
+ depth=depth,
189
+ continued=any(part.kind is TokenKind.LINE_SPLICE for part in group),
190
+ ))
191
+ if name in CONDITIONAL_OPENERS or name in CONDITIONAL_BRANCHES:
192
+ depth += 1
193
+ index = end
194
+ return tuple(directives)
195
+
196
+
197
+ def collect_macros(directives: tuple[Directive, ...]) -> tuple[MacroDefinition, ...]:
198
+ """
199
+ Extract the `#define` directives.
200
+
201
+ Parameters
202
+ ----------
203
+ directives : tuple[Directive, ...]
204
+ Directives of a file.
205
+
206
+ Returns
207
+ ----------
208
+ tuple[MacroDefinition, ...]
209
+ The macro definitions, in order.
210
+ """
211
+ macros: list[MacroDefinition] = []
212
+ for directive in directives:
213
+ if directive.name != "define":
214
+ continue
215
+ significant: tuple[Token, ...] = directive.operand_tokens
216
+ if not significant or significant[0].kind not in (TokenKind.IDENTIFIER, TokenKind.KEYWORD):
217
+ continue
218
+ name_token: Token = significant[0]
219
+ parameters: tuple[str, ...] | None = None
220
+ if len(significant) > 1 and significant[1].text == "(" and significant[1].offset == name_token.end_offset:
221
+ names: list[str] = []
222
+ for part in significant[2:]:
223
+ if part.text == ")":
224
+ break
225
+ if part.text != ",":
226
+ names.append(part.text)
227
+ parameters = tuple(names)
228
+ body: tuple[Token, ...] = tuple(part for part in directive.tokens if part.in_macro_body)
229
+ macros.append(MacroDefinition(name_token.text, name_token, parameters, body, directive))
230
+ return tuple(macros)
231
+
232
+
233
+ def collect_includes(directives: tuple[Directive, ...]) -> tuple[Include, ...]:
234
+ """
235
+ Extract the `#include` directives.
236
+
237
+ Parameters
238
+ ----------
239
+ directives : tuple[Directive, ...]
240
+ Directives of a file.
241
+
242
+ Returns
243
+ ----------
244
+ tuple[Include, ...]
245
+ The includes, in order.
246
+ """
247
+ includes: list[Include] = []
248
+ for directive in directives:
249
+ if directive.name != "include":
250
+ continue
251
+ operand: tuple[Token, ...] = directive.operand_tokens
252
+ if operand and operand[0].kind is TokenKind.HEADER_NAME:
253
+ includes.append(Include(operand[0].text[1:-1], True, directive))
254
+ elif operand and operand[0].kind is TokenKind.STRING:
255
+ includes.append(Include(operand[0].text.strip('"'), False, directive))
256
+ else:
257
+ includes.append(Include("", False, directive))
258
+ return tuple(includes)
@@ -0,0 +1,288 @@
1
+ import re
2
+
3
+ from sources.analysis.source import EOL_PATTERN
4
+ from sources.analysis.tokens import KEYWORDS, Token
5
+ from sources.enums import TokenKind
6
+
7
+
8
+ # Encoding prefix of string and character literals.
9
+ _LITERAL_PREFIX: str = r"(?:u8|[uUL])?"
10
+
11
+ # Body character of a string/char literal: anything but the quote, a backslash or an end of line,
12
+ # or an escape sequence (a backslash followed by any character, including an end of line).
13
+ _LITERAL_BODY: str = r"(?:[^{quote}\\\r\n]|\\(?:\r\n|[\s\S]))*"
14
+
15
+ # Ordered alternatives of the master pattern; the first one that matches wins.
16
+ _TOKEN_ALTERNATIVES: tuple[tuple[str, str], ...] = (
17
+ ("splice", r"\\(?:\r\n|\n|\r)"),
18
+ ("newline", r"\r\n|\n|\r"),
19
+ ("whitespace", r"[ \t\f\v]+"),
20
+ ("block_comment", r"/\*(?:[^*]|\*(?!/))*(?:\*/)?"),
21
+ ("line_comment", r"//[^\r\n]*"),
22
+ ("string", _LITERAL_PREFIX + '"' + _LITERAL_BODY.format(quote='"') + '"?'),
23
+ ("char", _LITERAL_PREFIX + "'" + _LITERAL_BODY.format(quote="'") + "'?"),
24
+ ("number", r"\.?[0-9](?:[eEpP][+-]|[\w.])*"),
25
+ ("identifier", r"[^\W\d]\w*"),
26
+ (
27
+ "punctuator",
28
+ r"%:%:|\.\.\.|<<=|>>=|->|\+\+|--|<<|>>|<=|>=|==|!=|&&|\|\||\*=|/=|%=|\+=|-=|&=|\^=|\|="
29
+ r"|##|<:|:>|<%|%>|%:|[\[\](){}.&*+\-~!/%<>^|?:;=,#]",
30
+ ),
31
+ ("unknown", r"[\s\S]"),
32
+ )
33
+
34
+ # Master pattern of the lexer: one named group per alternative.
35
+ TOKEN_PATTERN: re.Pattern[str] = re.compile("|".join(f"(?P<{name}>{pattern})" for name, pattern in _TOKEN_ALTERNATIVES))
36
+
37
+ # Optional spaces then a directive name, right after a `#` that starts a directive.
38
+ DIRECTIVE_NAME_PATTERN: re.Pattern[str] = re.compile(r"[ \t]*([A-Za-z_]\w*)?")
39
+
40
+ # `<...>` operand of an `#include` directive.
41
+ HEADER_NAME_PATTERN: re.Pattern[str] = re.compile(r"<[^>\r\n]*>")
42
+
43
+ # Mapping from the master pattern group names to token kinds.
44
+ GROUP_KINDS: dict[str, TokenKind] = {
45
+ "splice": TokenKind.LINE_SPLICE,
46
+ "newline": TokenKind.NEWLINE,
47
+ "whitespace": TokenKind.WHITESPACE,
48
+ "block_comment": TokenKind.COMMENT,
49
+ "line_comment": TokenKind.COMMENT,
50
+ "string": TokenKind.STRING,
51
+ "char": TokenKind.CHAR,
52
+ "number": TokenKind.NUMBER,
53
+ "identifier": TokenKind.IDENTIFIER,
54
+ "punctuator": TokenKind.PUNCTUATOR,
55
+ "unknown": TokenKind.UNKNOWN,
56
+ }
57
+
58
+ # `#define` parsing state: not inside a `#define`.
59
+ DEFINE_NONE: int = 0
60
+
61
+ # `#define` parsing state: waiting for the macro name.
62
+ DEFINE_NAME: int = 1
63
+
64
+ # `#define` parsing state: inside the parameter list of a function-like macro.
65
+ DEFINE_PARAMETERS: int = 2
66
+
67
+ # `#define` parsing state: inside the replacement list.
68
+ DEFINE_BODY: int = 3
69
+
70
+ # Directive names whose operand may be a `<...>` header name.
71
+ INCLUDE_DIRECTIVES: frozenset[str] = frozenset({"include", "include_next", "import"})
72
+
73
+
74
+ def _literal_terminated(text: str, quote: str) -> bool:
75
+ """
76
+ Whether a string or character literal matched by the master pattern has its closing quote.
77
+
78
+ Parameters
79
+ ----------
80
+ text : str
81
+ Text of the literal, with its optional prefix.
82
+ quote : str
83
+ The quote character (`"` or `'`).
84
+
85
+ Returns
86
+ ----------
87
+ bool
88
+ True when the literal is closed.
89
+ """
90
+ body: str = text[text.index(quote) + 1:]
91
+ index: int = 0
92
+ while index < len(body):
93
+ if body[index] == "\\":
94
+ index += 2
95
+ continue
96
+ if body[index] == quote:
97
+ return index == len(body) - 1
98
+ index += 1
99
+ return False
100
+
101
+
102
+ class Lexer:
103
+ """
104
+ Lossless lexer for C and H files. It never raises: unterminated literals and comments, and stray
105
+ characters, become tokens flagged as such.
106
+
107
+ Attributes
108
+ ----------
109
+ text : str
110
+ Decoded content of the file.
111
+ """
112
+
113
+ def __init__(self, text: str) -> None:
114
+ """
115
+ Prepare the lexer.
116
+
117
+ Parameters
118
+ ----------
119
+ text : str
120
+ Decoded content of the file.
121
+
122
+ Returns
123
+ ----------
124
+ None
125
+ Nothing.
126
+ """
127
+ self.text: str = text
128
+ self._tokens: list[Token] = []
129
+ self._line: int = 1
130
+ self._line_start: int = 0
131
+ self._at_line_start: bool = True
132
+ self._directive: str | None = None
133
+ self._define_state: int = DEFINE_NONE
134
+
135
+ def _emit(self, kind: TokenKind, start: int, end: int, *, terminated: bool = True) -> Token:
136
+ """
137
+ Create a token from a slice of the text and advance the line counters.
138
+
139
+ Parameters
140
+ ----------
141
+ kind : TokenKind
142
+ Kind of the token.
143
+ start : int
144
+ Offset of the first character.
145
+ end : int
146
+ Offset just after the last character.
147
+ terminated : bool
148
+ False for unterminated literals and comments.
149
+
150
+ Returns
151
+ ----------
152
+ Token
153
+ The created token.
154
+ """
155
+ text: str = self.text[start:end]
156
+ line: int = self._line
157
+ column: int = start - self._line_start + 1
158
+ for match in EOL_PATTERN.finditer(text):
159
+ self._line += 1
160
+ self._line_start = start + match.end()
161
+ in_directive: bool = self._directive is not None and kind is not TokenKind.NEWLINE
162
+ token: Token = Token(
163
+ kind=kind,
164
+ text=text,
165
+ index=len(self._tokens),
166
+ offset=start,
167
+ line=line,
168
+ column=column,
169
+ end_line=self._line,
170
+ end_column=end - self._line_start + 1,
171
+ in_directive=in_directive or kind is TokenKind.DIRECTIVE,
172
+ in_macro_body=self._define_state == DEFINE_BODY and in_directive,
173
+ terminated=terminated,
174
+ )
175
+ self._tokens.append(token)
176
+ return token
177
+
178
+ def _update_define_state(self, token: Token, next_char: str) -> None:
179
+ """
180
+ Track the parts of a `#define` (name, parameters, body) after each token of the directive.
181
+
182
+ Parameters
183
+ ----------
184
+ token : Token
185
+ Token just emitted.
186
+ next_char : str
187
+ Character right after the token ("" at the end of the text).
188
+
189
+ Returns
190
+ ----------
191
+ None
192
+ Nothing.
193
+ """
194
+ if token.is_trivia:
195
+ return
196
+ if self._define_state == DEFINE_NAME and token.kind in (TokenKind.IDENTIFIER, TokenKind.KEYWORD):
197
+ self._define_state = DEFINE_PARAMETERS if next_char == "(" else DEFINE_BODY
198
+ elif self._define_state == DEFINE_PARAMETERS and token.text == ")":
199
+ self._define_state = DEFINE_BODY
200
+
201
+ def _lex_directive_start(self, hash_start: int, hash_end: int) -> int:
202
+ """
203
+ Emit the DIRECTIVE token for a `#` found at the start of a line.
204
+
205
+ Parameters
206
+ ----------
207
+ hash_start : int
208
+ Offset of the `#` (or `%:`).
209
+ hash_end : int
210
+ Offset just after it.
211
+
212
+ Returns
213
+ ----------
214
+ int
215
+ Offset where lexing continues.
216
+ """
217
+ match: re.Match[str] = DIRECTIVE_NAME_PATTERN.match(self.text, hash_end) # type: ignore[assignment]
218
+ name: str = match.group(1) or ""
219
+ end: int = match.end() if name else hash_end
220
+ self._directive = name
221
+ self._emit(TokenKind.DIRECTIVE, hash_start, end)
222
+ self._define_state = DEFINE_NAME if name == "define" else DEFINE_NONE
223
+ return end
224
+
225
+ def tokenize(self) -> tuple[Token, ...]:
226
+ """
227
+ Split the whole text into tokens.
228
+
229
+ Returns
230
+ ----------
231
+ tuple[Token, ...]
232
+ Every token of the file, in order.
233
+ """
234
+ position: int = 0
235
+ length: int = len(self.text)
236
+ while position < length:
237
+ if self._directive in INCLUDE_DIRECTIVES and self.text[position] == "<":
238
+ header: re.Match[str] | None = HEADER_NAME_PATTERN.match(self.text, position)
239
+ if header is not None:
240
+ self._emit(TokenKind.HEADER_NAME, position, header.end())
241
+ position = header.end()
242
+ continue
243
+ match: re.Match[str] = TOKEN_PATTERN.match(self.text, position) # type: ignore[assignment]
244
+ group: str = match.lastgroup or "unknown"
245
+ start, end = match.span()
246
+ text: str = match.group()
247
+ if group == "punctuator" and text in ("#", "%:") and self._at_line_start and self._directive is None:
248
+ position = self._lex_directive_start(start, end)
249
+ self._at_line_start = False
250
+ continue
251
+ kind: TokenKind = GROUP_KINDS[group]
252
+ if kind is TokenKind.IDENTIFIER and text in KEYWORDS:
253
+ kind = TokenKind.KEYWORD
254
+ terminated: bool = True
255
+ if group == "block_comment":
256
+ terminated = len(text) >= 4 and text.endswith("*/")
257
+ elif group == "string":
258
+ terminated = _literal_terminated(text, '"')
259
+ elif group == "char":
260
+ terminated = _literal_terminated(text, "'")
261
+ token: Token = self._emit(kind, start, end, terminated=terminated)
262
+ if kind is TokenKind.NEWLINE:
263
+ self._directive = None
264
+ self._define_state = DEFINE_NONE
265
+ self._at_line_start = True
266
+ elif self._directive is not None:
267
+ self._update_define_state(token, self.text[end:end + 1])
268
+ elif not token.is_trivia:
269
+ self._at_line_start = False
270
+ position = end
271
+ return tuple(self._tokens)
272
+
273
+
274
+ def tokenize(text: str) -> tuple[Token, ...]:
275
+ """
276
+ Split a C or H file into tokens (see Lexer).
277
+
278
+ Parameters
279
+ ----------
280
+ text : str
281
+ Decoded content of the file.
282
+
283
+ Returns
284
+ ----------
285
+ tuple[Token, ...]
286
+ Every token of the file, in order.
287
+ """
288
+ return Lexer(text).tokenize()