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,586 @@
1
+ import re
2
+ from collections.abc import Callable, Iterator, Mapping
3
+ from dataclasses import dataclass
4
+ from typing import Any
5
+
6
+ from sources.analysis.project import ProjectContext
7
+ from sources.analysis.syntax import Node
8
+ from sources.analysis.tokens import Token
9
+ from sources.analysis.unit import CUnit
10
+ from sources.enums import ArgumentType, Layer, NodeKind
11
+ from sources.rules.arguments import ArgumentSpec
12
+ from sources.rules.definition import CheckDefinition
13
+ from sources.rules.primitives.base import CheckRun, Finding, Primitive, node_finding
14
+
15
+
16
+ # One `pattern.fields` condition: `<field><operator><value>`.
17
+ FIELD_CONDITION_PATTERN: re.Pattern[str] = re.compile(r"([a-z_]+)\s*(>=|<=|!=|=|>|<)\s*(.+)")
18
+
19
+ # Control statements whose header is followed by a body.
20
+ CONTROL_KINDS: frozenset[NodeKind] = frozenset({
21
+ NodeKind.IF_STATEMENT, NodeKind.WHILE_STATEMENT, NodeKind.FOR_STATEMENT, NodeKind.SWITCH_STATEMENT,
22
+ })
23
+
24
+ # Node kinds through which an expression value is passed unchanged to the parent.
25
+ TRANSPARENT_KINDS: frozenset[NodeKind] = frozenset({NodeKind.PARENTHESIZED_EXPRESSION})
26
+
27
+
28
+ @dataclass(frozen=True, slots=True)
29
+ class FieldCondition:
30
+ """
31
+ One parsed `pattern.fields` condition.
32
+ (dataclass)
33
+
34
+ Attributes
35
+ ----------
36
+ field : str
37
+ Field name (real node field or virtual field).
38
+ operator : str
39
+ Comparison operator.
40
+ value : str
41
+ Expected value, as written.
42
+ """
43
+
44
+ field: str
45
+ operator: str
46
+ value: str
47
+
48
+
49
+ def _value_used(node: Node) -> bool:
50
+ """
51
+ Whether the value of an expression is used (not discarded by an expression statement, a `for` init or
52
+ update part, a non-last comma operand or a `(void)` cast).
53
+
54
+ Parameters
55
+ ----------
56
+ node : Node
57
+ An expression node.
58
+
59
+ Returns
60
+ ----------
61
+ bool
62
+ True when the value is used.
63
+ """
64
+ parent: Node | None = node.parent
65
+ if parent is None:
66
+ return False
67
+ if parent.kind in (NodeKind.EXPRESSION_STATEMENT, NodeKind.FOR_INIT, NodeKind.FOR_UPDATE):
68
+ return False
69
+ if parent.kind is NodeKind.COMMA_EXPRESSION:
70
+ return parent.children[-1] is node and _value_used(parent)
71
+ if parent.kind in TRANSPARENT_KINDS:
72
+ return _value_used(parent)
73
+ if parent.kind is NodeKind.CAST_EXPRESSION:
74
+ type_name: Node = parent.fields["type"]
75
+ if type_name.fields["specifiers"].type_words == ["void"] and type_name.fields["declarator"] is None:
76
+ return False
77
+ return True
78
+
79
+
80
+ def _shares_line_with_previous(node: Node) -> bool:
81
+ """
82
+ Whether a block item starts on the line where the previous item of the same block ends.
83
+
84
+ Parameters
85
+ ----------
86
+ node : Node
87
+ A node.
88
+
89
+ Returns
90
+ ----------
91
+ bool
92
+ True for a second statement on the same line.
93
+ """
94
+ parent: Node | None = node.parent
95
+ if parent is None or parent.kind is not NodeKind.COMPOUND_STATEMENT:
96
+ return False
97
+ index: int = next(position for position, child in enumerate(parent.children) if child is node)
98
+ return index > 0 and parent.children[index - 1].end_line == node.line
99
+
100
+
101
+ def _close_paren(node: Node) -> Token | None:
102
+ """
103
+ Closing parenthesis of the header of a control statement.
104
+
105
+ Parameters
106
+ ----------
107
+ node : Node
108
+ A control statement.
109
+
110
+ Returns
111
+ ----------
112
+ Token | None
113
+ The token, or None.
114
+ """
115
+ if node.kind is NodeKind.FOR_STATEMENT:
116
+ return node.fields.get("close_paren")
117
+ condition: Node | None = node.fields.get("condition")
118
+ return condition.fields.get("close_paren") if condition is not None else None
119
+
120
+
121
+ def _body_on_header_line(node: Node) -> bool:
122
+ """
123
+ Whether the first statement of a control structure body is on the line of its condition
124
+ (`if (c) return;`, `if (c) {return;}`), or an `else` statement on the `else` line.
125
+
126
+ Parameters
127
+ ----------
128
+ node : Node
129
+ A control statement.
130
+
131
+ Returns
132
+ ----------
133
+ bool
134
+ True when a condition and a statement share a line.
135
+ """
136
+ if node.kind not in CONTROL_KINDS:
137
+ return False
138
+ closing: Token | None = _close_paren(node)
139
+ body: Node | None = node.fields.get("consequence") if node.kind is NodeKind.IF_STATEMENT else node.fields.get("body")
140
+ if closing is None or body is None:
141
+ return False
142
+ first: Node | None = body.children[0] if body.kind is NodeKind.COMPOUND_STATEMENT and body.children else body
143
+ if first is not None and first.kind is not NodeKind.COMPOUND_STATEMENT and first.line == closing.end_line:
144
+ return True
145
+ if node.kind is NodeKind.IF_STATEMENT:
146
+ alternative: Node | None = node.fields.get("alternative")
147
+ else_token: Token | None = node.fields.get("else_token")
148
+ if alternative is not None and else_token is not None and alternative.kind is not NodeKind.IF_STATEMENT:
149
+ inner: Node | None = alternative.children[0] if alternative.kind is NodeKind.COMPOUND_STATEMENT and alternative.children else alternative
150
+ if inner is not None and inner.kind is not NodeKind.COMPOUND_STATEMENT and inner.line == else_token.line:
151
+ return True
152
+ return False
153
+
154
+
155
+ def _misplaced_declaration(node: Node) -> bool:
156
+ """
157
+ Whether a declaration inside a function is not at the beginning of the function: it is in a nested block,
158
+ or a statement precedes it in the function body (`for` init declarations are allowed).
159
+
160
+ Parameters
161
+ ----------
162
+ node : Node
163
+ A DECLARATION or TYPE_DEFINITION node.
164
+
165
+ Returns
166
+ ----------
167
+ bool
168
+ True for a misplaced declaration.
169
+ """
170
+ parent: Node | None = node.parent
171
+ if parent is None or parent.kind is NodeKind.FOR_INIT or node.nearest(NodeKind.FUNCTION_DEFINITION) is None:
172
+ return False
173
+ if parent.kind is not NodeKind.COMPOUND_STATEMENT or parent.parent is None or parent.parent.kind is not NodeKind.FUNCTION_DEFINITION:
174
+ return True
175
+ for sibling in parent.children:
176
+ if sibling is node:
177
+ return False
178
+ if sibling.kind not in (NodeKind.DECLARATION, NodeKind.TYPE_DEFINITION):
179
+ return True
180
+ return False
181
+
182
+
183
+ def _record_by_copy(node: Node, project: ProjectContext) -> bool:
184
+ """
185
+ Whether a parameter is a structure or union passed by copy (its type, or the typedef it uses, is a
186
+ struct/union, without pointer or array).
187
+
188
+ Parameters
189
+ ----------
190
+ node : Node
191
+ A PARAMETER node.
192
+ project : ProjectContext
193
+ Project context (typedef map).
194
+
195
+ Returns
196
+ ----------
197
+ bool
198
+ True for a struct/union passed by copy.
199
+ """
200
+ if node.kind is not NodeKind.PARAMETER:
201
+ return False
202
+ declarator: Node | None = node.fields.get("declarator")
203
+ if node.fields["pointer_depth"] or (declarator is not None and declarator.fields.get("suffixes")):
204
+ return False
205
+ specifiers = node.fields["specifiers"]
206
+ if specifiers.type_node is not None:
207
+ return specifiers.type_node.kind in (NodeKind.STRUCT_SPECIFIER, NodeKind.UNION_SPECIFIER)
208
+ for word in specifiers.type_words:
209
+ for typedef in project.typedefs.get(word, ()):
210
+ if typedef.record_kind in ("struct", "union"):
211
+ return True
212
+ return False
213
+
214
+
215
+ # Virtual fields usable in `pattern.fields`, computed from the node and the project.
216
+ VIRTUAL_FIELDS: dict[str, Callable[[Node, ProjectContext], Any]] = {
217
+ "value_used": lambda node, project: _value_used(node),
218
+ "declarator_count": lambda node, project: len(node.fields.get("declarators", ())),
219
+ "shares_line_with_previous": lambda node, project: _shares_line_with_previous(node),
220
+ "body_on_header_line": lambda node, project: _body_on_header_line(node),
221
+ "misplaced_declaration": lambda node, project: _misplaced_declaration(node),
222
+ "record_by_copy": lambda node, project: _record_by_copy(node, project),
223
+ "in_function": lambda node, project: node.nearest(NodeKind.FUNCTION_DEFINITION) is not None,
224
+ }
225
+
226
+
227
+ def _compare(actual: Any, operator: str, expected: str) -> bool:
228
+ """
229
+ Compare a field value with a condition value (numbers numerically, booleans as true/false, else text).
230
+
231
+ Parameters
232
+ ----------
233
+ actual : Any
234
+ Field value.
235
+ operator : str
236
+ Comparison operator.
237
+ expected : str
238
+ Expected value, as written.
239
+
240
+ Returns
241
+ ----------
242
+ bool
243
+ True when the condition holds.
244
+ """
245
+ if isinstance(actual, bool):
246
+ text: str = "true" if actual else "false"
247
+ return (text == expected) == (operator == "=") if operator in ("=", "!=") else False
248
+ if isinstance(actual, int) and re.fullmatch(r"-?\d+", expected):
249
+ number: int = int(expected)
250
+ return {
251
+ "=": actual == number, "!=": actual != number, ">": actual > number,
252
+ "<": actual < number, ">=": actual >= number, "<=": actual <= number,
253
+ }[operator]
254
+ text = "" if actual is None else str(actual)
255
+ if operator == "=":
256
+ return text == expected
257
+ if operator == "!=":
258
+ return text != expected
259
+ return False
260
+
261
+
262
+ def parse_field_conditions(items: tuple[str, ...]) -> tuple[FieldCondition, ...]:
263
+ """
264
+ Parse `pattern.fields` items.
265
+
266
+ Parameters
267
+ ----------
268
+ items : tuple[str, ...]
269
+ Items such as "empty=true", "declarator_count>1", "operator=&&".
270
+
271
+ Returns
272
+ ----------
273
+ tuple[FieldCondition, ...]
274
+ The conditions.
275
+
276
+ Raises
277
+ ----------
278
+ ValueError
279
+ An item is malformed.
280
+ """
281
+ conditions: list[FieldCondition] = []
282
+ for item in items:
283
+ match: re.Match[str] | None = FIELD_CONDITION_PATTERN.fullmatch(item.strip())
284
+ if match is None:
285
+ raise ValueError(f"invalid field condition '{item}' (expected <field><op><value>)")
286
+ conditions.append(FieldCondition(match.group(1), match.group(2), match.group(3).strip()))
287
+ return tuple(conditions)
288
+
289
+
290
+ class NodeForbid(Primitive):
291
+ """
292
+ Forbid syntax nodes that match a structural pattern: node kind, parent / ancestor constraints, and
293
+ conditions on node fields (real ones such as `operator` or `empty`, or virtual ones such as
294
+ `value_used`, `declarator_count`, `body_on_header_line`, `misplaced_declaration`, `record_by_copy`).
295
+ (ABC -> Primitive)
296
+
297
+ Attributes
298
+ ----------
299
+ kind : str
300
+ "node_forbid".
301
+ """
302
+
303
+ kind = "node_forbid"
304
+ layer = Layer.PROJECT
305
+ parameters = (
306
+ ArgumentSpec("node", ArgumentType.LIST, required=True, item_type=ArgumentType.ENUM, choices=tuple(kind.value for kind in NodeKind), description="Forbidden node kinds."),
307
+ ArgumentSpec("pattern.parent", ArgumentType.LIST, default=(), item_type=ArgumentType.ENUM, choices=tuple(kind.value for kind in NodeKind), description="The direct parent must be one of these kinds."),
308
+ ArgumentSpec("pattern.not_parent", ArgumentType.LIST, default=(), item_type=ArgumentType.ENUM, choices=tuple(kind.value for kind in NodeKind), description="The direct parent must not be one of these kinds."),
309
+ ArgumentSpec("pattern.ancestor", ArgumentType.LIST, default=(), item_type=ArgumentType.ENUM, choices=tuple(kind.value for kind in NodeKind), description="Some ancestor must be one of these kinds."),
310
+ ArgumentSpec("pattern.not_ancestor", ArgumentType.LIST, default=(), item_type=ArgumentType.ENUM, choices=tuple(kind.value for kind in NodeKind), description="No ancestor may be one of these kinds."),
311
+ ArgumentSpec("pattern.fields", ArgumentType.LIST, default=(), description="Conditions on fields, e.g. empty=true, declarator_count>1, operator=&&."),
312
+ ArgumentSpec("location", ArgumentType.ENUM, default="node", choices=("node", "operator", "name"), description="Where the finding is reported."),
313
+ )
314
+ where_keys = frozenset({"name", "storage", "context", "not_context"})
315
+ default_message = "{code}: forbidden construct"
316
+
317
+ def validate(self, parameters: Mapping[str, Any], check: CheckDefinition) -> None:
318
+ """
319
+ Check the field conditions.
320
+
321
+ Parameters
322
+ ----------
323
+ parameters : Mapping[str, Any]
324
+ Bound parameter values.
325
+ check : CheckDefinition
326
+ The check definition.
327
+
328
+ Returns
329
+ ----------
330
+ None
331
+ Nothing.
332
+
333
+ Raises
334
+ ----------
335
+ ValueError
336
+ A field condition is malformed.
337
+ """
338
+ parse_field_conditions(parameters["pattern.fields"])
339
+
340
+ def _matches(self, node: Node, parameters: Mapping[str, Any], conditions: tuple[FieldCondition, ...], project: ProjectContext) -> bool:
341
+ """
342
+ Whether a node matches the pattern.
343
+
344
+ Parameters
345
+ ----------
346
+ node : Node
347
+ The node.
348
+ parameters : Mapping[str, Any]
349
+ Bound parameters.
350
+ conditions : tuple[FieldCondition, ...]
351
+ Field conditions.
352
+ project : ProjectContext
353
+ Project context.
354
+
355
+ Returns
356
+ ----------
357
+ bool
358
+ True on a match.
359
+ """
360
+ parent_kind: str | None = node.parent.kind.value if node.parent is not None else None
361
+ if parameters["pattern.parent"] and parent_kind not in parameters["pattern.parent"]:
362
+ return False
363
+ if parameters["pattern.not_parent"] and parent_kind in parameters["pattern.not_parent"]:
364
+ return False
365
+ ancestors: set[str] = {ancestor.kind.value for ancestor in node.ancestors()}
366
+ if parameters["pattern.ancestor"] and not ancestors & set(parameters["pattern.ancestor"]):
367
+ return False
368
+ if ancestors & set(parameters["pattern.not_ancestor"]):
369
+ return False
370
+ for condition in conditions:
371
+ getter: Callable[[Node, ProjectContext], Any] | None = VIRTUAL_FIELDS.get(condition.field)
372
+ actual: Any = getter(node, project) if getter is not None else node.fields.get(condition.field)
373
+ if not _compare(actual, condition.operator, condition.value):
374
+ return False
375
+ return True
376
+
377
+ def run(self, run: CheckRun) -> Iterator[Finding]:
378
+ """
379
+ Run the check (see class description).
380
+
381
+ Parameters
382
+ ----------
383
+ run : CheckRun
384
+ Project context, files and parameters.
385
+
386
+ Returns
387
+ ----------
388
+ Iterator[Finding]
389
+ The problems found.
390
+ """
391
+ kinds: list[NodeKind] = [NodeKind(kind) for kind in run.parameters["node"]]
392
+ conditions: tuple[FieldCondition, ...] = parse_field_conditions(run.parameters["pattern.fields"])
393
+ location: str = run.parameters["location"]
394
+ for unit in run.units():
395
+ for node in unit.nodes(*kinds):
396
+ if not self._matches(node, run.parameters, conditions, run.project) or not run.node_selected(unit, node):
397
+ continue
398
+ token: Token | None = node.fields.get("operator_token") if location == "operator" else node.fields.get("name_token") if location == "name" else None
399
+ if token is not None:
400
+ yield Finding(unit.path, token.line, token.column, token.end_line, token.end_column, name=node.name or token.text, value=node.fields.get("operator"), node_key=id(node))
401
+ else:
402
+ yield node_finding(unit.path, node, value=node.fields.get("operator"))
403
+
404
+
405
+ class NestingDepth(Primitive):
406
+ """
407
+ Depth of nested node kinds: a node of a counted kind is at depth 1 + the number of its ancestors of a
408
+ counted kind (inside the same function). The first node deeper than `max` on each branch is reported.
409
+ An `else if` is an `if` inside the `else`, so it is one level deeper than its `if`.
410
+ (ABC -> Primitive)
411
+
412
+ Attributes
413
+ ----------
414
+ kind : str
415
+ "nesting_depth".
416
+ """
417
+
418
+ kind = "nesting_depth"
419
+ layer = Layer.SYNTAX
420
+ parameters = (
421
+ ArgumentSpec("counted", ArgumentType.LIST, required=True, item_type=ArgumentType.ENUM, choices=tuple(kind.value for kind in NodeKind), description="Node kinds that count as one level."),
422
+ ArgumentSpec("max", ArgumentType.INT, required=True, minimum=0, description="Deepest allowed level."),
423
+ )
424
+ default_message = "{code}: nesting depth {value} (max {limit})"
425
+
426
+ def run(self, run: CheckRun) -> Iterator[Finding]:
427
+ """
428
+ Run the check (see class description).
429
+
430
+ Parameters
431
+ ----------
432
+ run : CheckRun
433
+ Project context, files and parameters.
434
+
435
+ Returns
436
+ ----------
437
+ Iterator[Finding]
438
+ The problems found.
439
+ """
440
+ counted: frozenset[NodeKind] = frozenset(NodeKind(kind) for kind in run.parameters["counted"])
441
+ limit: int = run.parameters["max"]
442
+ for unit in run.units():
443
+ for node in unit.nodes(*counted):
444
+ depth: int = 1
445
+ for ancestor in node.ancestors():
446
+ if ancestor.kind is NodeKind.FUNCTION_DEFINITION:
447
+ break
448
+ if ancestor.kind in counted:
449
+ depth += 1
450
+ if depth == limit + 1:
451
+ yield node_finding(unit.path, node, value=depth, limit=limit)
452
+
453
+
454
+ def _item_categories(node: Node) -> list[tuple[str, Node]]:
455
+ """
456
+ Categories of a top-level item (plan 03, C-H1).
457
+
458
+ Parameters
459
+ ----------
460
+ node : Node
461
+ A child of the translation unit.
462
+
463
+ Returns
464
+ ----------
465
+ list[tuple[str, Node]]
466
+ (category, node to report on) pairs.
467
+ """
468
+ if node.kind is NodeKind.FUNCTION_DEFINITION:
469
+ storage: frozenset[str] = node.fields["storage"]
470
+ return [("static_inline_function" if {"static", "inline"} <= storage else "function_definition", node)]
471
+ if node.kind is NodeKind.TYPE_DEFINITION:
472
+ return [("typedef", node)]
473
+ if node.kind is not NodeKind.DECLARATION:
474
+ return []
475
+ categories: list[tuple[str, Node]] = []
476
+ type_node: Node | None = node.fields.get("type_node")
477
+ declarators: tuple[Node, ...] = node.fields.get("declarators", ())
478
+ if type_node is not None and type_node.kind in (NodeKind.STRUCT_SPECIFIER, NodeKind.UNION_SPECIFIER, NodeKind.ENUM_SPECIFIER):
479
+ if type_node.fields.get("has_body") or not declarators:
480
+ categories.append(("record_declaration", type_node))
481
+ for item in declarators:
482
+ declarator: Node = item.fields["declarator"] if item.kind is NodeKind.INIT_DECLARATOR else item
483
+ if declarator.fields.get("declares_function"):
484
+ categories.append(("prototype", item))
485
+ elif "extern" in node.fields["storage"] and item.kind is not NodeKind.INIT_DECLARATOR:
486
+ categories.append(("extern_variable", item))
487
+ else:
488
+ categories.append(("variable_definition", item))
489
+ return categories
490
+
491
+
492
+ class TopLevelItems(Primitive):
493
+ """
494
+ Kinds of top-level items allowed or forbidden in a file: function_definition, static_inline_function,
495
+ prototype, typedef, record_declaration, extern_variable, variable_definition, macro, conditional_directive.
496
+ (ABC -> Primitive)
497
+
498
+ Attributes
499
+ ----------
500
+ kind : str
501
+ "top_level_items".
502
+ """
503
+
504
+ kind = "top_level_items"
505
+ layer = Layer.SYNTAX
506
+ parameters = (
507
+ ArgumentSpec("forbidden", ArgumentType.LIST, required=True, item_type=ArgumentType.ENUM, choices=(
508
+ "function_definition", "static_inline_function", "prototype", "typedef", "record_declaration",
509
+ "extern_variable", "variable_definition", "macro", "conditional_directive",
510
+ ), description="Forbidden item categories."),
511
+ )
512
+ default_message = "{code}: {value} not allowed in this file"
513
+
514
+ def run(self, run: CheckRun) -> Iterator[Finding]:
515
+ """
516
+ Run the check (see class description).
517
+
518
+ Parameters
519
+ ----------
520
+ run : CheckRun
521
+ Project context, files and parameters.
522
+
523
+ Returns
524
+ ----------
525
+ Iterator[Finding]
526
+ The problems found.
527
+ """
528
+ forbidden: frozenset[str] = frozenset(run.parameters["forbidden"])
529
+ for unit in run.units():
530
+ found: list[Finding] = []
531
+ for item in unit.tree.children:
532
+ for category, node in _item_categories(item):
533
+ if category in forbidden:
534
+ found.append(node_finding(unit.path, node, value=category))
535
+ for directive in unit.directives:
536
+ category = "macro" if directive.name == "define" else "conditional_directive" if directive.name in ("if", "ifdef", "ifndef", "elif", "else", "endif", "elifdef", "elifndef") else ""
537
+ if category in forbidden:
538
+ found.append(Finding(unit.path, directive.line, directive.column, name=directive.name, value=category, node_key=id(directive)))
539
+ yield from sorted(found, key=lambda finding: (finding.line, finding.column))
540
+
541
+
542
+ class GlobalMutability(Primitive):
543
+ """
544
+ Report global variables that are not constant: file-scope variables and (optionally) `static` local
545
+ variables whose own top-level declarator is not `const` (`char *const p` is constant, `const char *p`
546
+ is not).
547
+ (ABC -> Primitive)
548
+
549
+ Attributes
550
+ ----------
551
+ kind : str
552
+ "global_mutability".
553
+ """
554
+
555
+ kind = "global_mutability"
556
+ layer = Layer.SYNTAX
557
+ parameters = (
558
+ ArgumentSpec("include_static_locals", ArgumentType.BOOL, default=True, description="Also report static local variables."),
559
+ )
560
+ where_keys = frozenset({"name"})
561
+ default_message = "{code}: '{name}' is a global variable"
562
+
563
+ def run(self, run: CheckRun) -> Iterator[Finding]:
564
+ """
565
+ Run the check (see class description).
566
+
567
+ Parameters
568
+ ----------
569
+ run : CheckRun
570
+ Project context, files and parameters.
571
+
572
+ Returns
573
+ ----------
574
+ Iterator[Finding]
575
+ The problems found.
576
+ """
577
+ for unit in run.units():
578
+ for variable in unit.variables:
579
+ if variable.is_constant or (variable.local and not run.parameters["include_static_locals"]):
580
+ continue
581
+ if not run.selection.name_matches(variable.name):
582
+ continue
583
+ declarator: Node = variable.node.fields["declarator"] if variable.node.kind is NodeKind.INIT_DECLARATOR else variable.node
584
+ token: Token | None = declarator.fields.get("name_token")
585
+ if token is not None:
586
+ yield Finding(unit.path, token.line, token.column, token.end_line, token.end_column, name=variable.name, node_key=id(variable.node))