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.
- jarbin_c_coding_style-2.0.0.dist-info/METADATA +150 -0
- jarbin_c_coding_style-2.0.0.dist-info/RECORD +186 -0
- jarbin_c_coding_style-2.0.0.dist-info/WHEEL +4 -0
- jarbin_c_coding_style-2.0.0.dist-info/entry_points.txt +2 -0
- jarbin_c_coding_style-2.0.0.dist-info/licenses/LICENSE +674 -0
- sources/__init__.py +0 -0
- sources/__main__.py +6 -0
- sources/analysis/__init__.py +0 -0
- sources/analysis/directives.py +258 -0
- sources/analysis/lexer.py +288 -0
- sources/analysis/parser.py +1754 -0
- sources/analysis/project.py +286 -0
- sources/analysis/source.py +326 -0
- sources/analysis/syntax.py +238 -0
- sources/analysis/tokens.py +116 -0
- sources/analysis/unit.py +700 -0
- sources/application.py +118 -0
- sources/build_info.json +6 -0
- sources/cli/__init__.py +0 -0
- sources/cli/arguments.py +507 -0
- sources/cli/completion.py +610 -0
- sources/cli/context.py +258 -0
- sources/cli/converters.py +204 -0
- sources/cli/help.py +162 -0
- sources/cli/parser.py +659 -0
- sources/configs/__init__.py +0 -0
- sources/configs/editor.py +207 -0
- sources/configs/ini.py +327 -0
- sources/configs/project.py +735 -0
- sources/configs/schema/__init__.py +0 -0
- sources/configs/schema/project.py +68 -0
- sources/constants.py +801 -0
- sources/diagnostics/__init__.py +0 -0
- sources/diagnostics/fingerprint.py +82 -0
- sources/diagnostics/model.py +146 -0
- sources/engine/__init__.py +0 -0
- sources/engine/api.py +355 -0
- sources/engine/examples.py +157 -0
- sources/engine/outcome.py +114 -0
- sources/engine/plan.py +440 -0
- sources/engine/runner.py +345 -0
- sources/engine/scanner.py +179 -0
- sources/enums.py +838 -0
- sources/errors/__init__.py +0 -0
- sources/errors/exceptions.py +727 -0
- sources/fixers/__init__.py +0 -0
- sources/fixers/base.py +209 -0
- sources/fixers/conflicts.py +129 -0
- sources/fixers/diff.py +73 -0
- sources/fixers/engine.py +434 -0
- sources/fixers/journal.py +290 -0
- sources/fixers/kinds.py +30 -0
- sources/fixers/layout.py +411 -0
- sources/fixers/model.py +151 -0
- sources/fixers/registry.py +54 -0
- sources/fixers/text.py +353 -0
- sources/fixers/verify.py +123 -0
- sources/fixers/writer.py +88 -0
- sources/integrations/__init__.py +0 -0
- sources/integrations/ci/__init__.py +0 -0
- sources/integrations/ci/github.py +183 -0
- sources/integrations/editors/__init__.py +0 -0
- sources/integrations/git/__init__.py +0 -0
- sources/integrations/git/repository.py +176 -0
- sources/integrations/update/__init__.py +0 -0
- sources/integrations/update/installers.py +529 -0
- sources/integrations/update/releases.py +397 -0
- sources/integrations/update/state.py +143 -0
- sources/outputs/__init__.py +0 -0
- sources/outputs/github/__init__.py +0 -0
- sources/outputs/github/renderer.py +135 -0
- sources/outputs/html/__init__.py +0 -0
- sources/outputs/html/renderer.py +694 -0
- sources/outputs/json/__init__.py +0 -0
- sources/outputs/json/renderer.py +154 -0
- sources/outputs/json/report.schema.json +121 -0
- sources/outputs/junit/__init__.py +0 -0
- sources/outputs/junit/renderer.py +151 -0
- sources/outputs/registry.py +135 -0
- sources/outputs/report.py +224 -0
- sources/outputs/sarif/__init__.py +0 -0
- sources/outputs/sarif/renderer.py +182 -0
- sources/outputs/terminal/__init__.py +0 -0
- sources/outputs/terminal/renderer.py +184 -0
- sources/outputs/terminal/style.py +159 -0
- sources/rules/__init__.py +0 -0
- sources/rules/arguments.py +362 -0
- sources/rules/catalog.py +227 -0
- sources/rules/categories/advanced/constant_pointers.ini +46 -0
- sources/rules/categories/advanced/line_break_at_end_of_file.ini +44 -0
- sources/rules/categories/advanced/static.ini +65 -0
- sources/rules/categories/advanced/typing.ini +47 -0
- sources/rules/categories/control_structures/conditional_branching.ini +89 -0
- sources/rules/categories/control_structures/goto.ini +45 -0
- sources/rules/categories/control_structures/ternary_operators.ini +57 -0
- sources/rules/categories/extensions/language_extensions.ini +71 -0
- sources/rules/categories/files_organization/contents_of_the_repository.ini +85 -0
- sources/rules/categories/files_organization/file_coherence.ini +166 -0
- sources/rules/categories/files_organization/file_extension.ini +68 -0
- sources/rules/categories/files_organization/fixtures/program +0 -0
- sources/rules/categories/files_organization/naming_files_and_folders.ini +74 -0
- sources/rules/categories/functions/coherence_of_functions.ini +45 -0
- sources/rules/categories/functions/comments_inside_a_function.ini +45 -0
- sources/rules/categories/functions/functions_without_parameters.ini +39 -0
- sources/rules/categories/functions/naming_functions.ini +79 -0
- sources/rules/categories/functions/number_of_columns.ini +61 -0
- sources/rules/categories/functions/number_of_lines.ini +70 -0
- sources/rules/categories/functions/number_of_parameters.ini +64 -0
- sources/rules/categories/functions/structures_as_parameters.ini +44 -0
- sources/rules/categories/global_scope/constant_values.ini +49 -0
- sources/rules/categories/global_scope/file_header.ini +92 -0
- sources/rules/categories/global_scope/global_variables.ini +53 -0
- sources/rules/categories/global_scope/include.ini +39 -0
- sources/rules/categories/global_scope/indentation_of_preprocessor.ini +62 -0
- sources/rules/categories/global_scope/inline_assembly.ini +43 -0
- sources/rules/categories/global_scope/leading_trailing_lines.ini +58 -0
- sources/rules/categories/global_scope/line_endings.ini +53 -0
- sources/rules/categories/global_scope/separation_of_functions.ini +61 -0
- sources/rules/categories/global_scope/trailing_spaces.ini +45 -0
- sources/rules/categories/header_files/content.ini +104 -0
- sources/rules/categories/header_files/include_guard.ini +47 -0
- sources/rules/categories/header_files/macros.ini +57 -0
- sources/rules/categories/layout_inside_a_function_scope/blank_lines.ini +71 -0
- sources/rules/categories/layout_inside_a_function_scope/code_line_content.ini +112 -0
- sources/rules/categories/layout_inside_a_function_scope/curly_brackets.ini +94 -0
- sources/rules/categories/layout_inside_a_function_scope/indentation.ini +96 -0
- sources/rules/categories/layout_inside_a_function_scope/spaces.ini +113 -0
- sources/rules/categories/layout_inside_a_function_scope/variable_declarations.ini +65 -0
- sources/rules/categories/variables_and_types/naming_identifiers.ini +74 -0
- sources/rules/categories/variables_and_types/pointers.ini +67 -0
- sources/rules/categories/variables_and_types/structures.ini +47 -0
- sources/rules/data/verbs.txt +182 -0
- sources/rules/definition.py +430 -0
- sources/rules/loader.py +925 -0
- sources/rules/paths.py +6 -0
- sources/rules/primitives/__init__.py +0 -0
- sources/rules/primitives/base.py +297 -0
- sources/rules/primitives/braces.py +211 -0
- sources/rules/primitives/directives.py +203 -0
- sources/rules/primitives/indentation.py +376 -0
- sources/rules/primitives/layout.py +199 -0
- sources/rules/primitives/naming.py +277 -0
- sources/rules/primitives/project.py +62 -0
- sources/rules/primitives/registry.py +49 -0
- sources/rules/primitives/repository.py +129 -0
- sources/rules/primitives/review.py +87 -0
- sources/rules/primitives/semantic.py +319 -0
- sources/rules/primitives/spacing.py +210 -0
- sources/rules/primitives/structure.py +586 -0
- sources/rules/primitives/syntax.py +200 -0
- sources/rules/primitives/text.py +408 -0
- sources/rules/primitives/tokens.py +84 -0
- sources/rules/template.py +138 -0
- sources/selftest/__init__.py +0 -0
- sources/selftest/cases.py +292 -0
- sources/services.py +90 -0
- sources/subcommands/__init__.py +0 -0
- sources/subcommands/base.py +45 -0
- sources/subcommands/check/__init__.py +0 -0
- sources/subcommands/check/command.py +45 -0
- sources/subcommands/check/fixing.py +224 -0
- sources/subcommands/check/handler.py +757 -0
- sources/subcommands/info/__init__.py +0 -0
- sources/subcommands/info/command.py +45 -0
- sources/subcommands/info/handler.py +527 -0
- sources/subcommands/registry.py +37 -0
- sources/subcommands/rule/__init__.py +0 -0
- sources/subcommands/rule/command.py +45 -0
- sources/subcommands/rule/handler.py +1067 -0
- sources/subcommands/rule/render.py +273 -0
- sources/subcommands/runner.py +124 -0
- sources/subcommands/test/__init__.py +0 -0
- sources/subcommands/test/command.py +45 -0
- sources/subcommands/test/handler.py +166 -0
- sources/subcommands/test/render.py +219 -0
- sources/subcommands/test/runner.py +430 -0
- sources/subcommands/update/__init__.py +0 -0
- sources/subcommands/update/command.py +45 -0
- sources/subcommands/update/handler.py +408 -0
- sources/utils/__init__.py +0 -0
- sources/utils/build_info.py +188 -0
- sources/utils/git.py +73 -0
- sources/utils/globs.py +98 -0
- sources/utils/logging.py +154 -0
- sources/utils/schema.py +77 -0
- sources/utils/versions.py +87 -0
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
from collections.abc import Iterator, Mapping
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from sources.analysis.syntax import Node
|
|
5
|
+
from sources.analysis.unit import CUnit, FunctionInfo
|
|
6
|
+
from sources.enums import ArgumentType, Layer, NodeKind
|
|
7
|
+
from sources.rules.arguments import ArgumentSpec
|
|
8
|
+
from sources.rules.definition import CheckDefinition
|
|
9
|
+
from sources.rules.primitives.base import CheckRun, Finding, Primitive, node_finding
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
# Prefix of a `measure` that counts descendant nodes of a kind, e.g. "count:function_definition".
|
|
13
|
+
COUNT_MEASURE_PREFIX: str = "count:"
|
|
14
|
+
|
|
15
|
+
# Measures of `node_metric` that are not node counts, with the targets they apply to.
|
|
16
|
+
NODE_MEASURES: dict[str, frozenset[str]] = {
|
|
17
|
+
"body_lines": frozenset({"function_definition"}),
|
|
18
|
+
"named_parameters": frozenset({"function_definition", "function_declarator"}),
|
|
19
|
+
"fields": frozenset({"struct_definition"}),
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _over_limit(value: int, parameters: Mapping[str, Any]) -> int | None:
|
|
24
|
+
"""
|
|
25
|
+
Compare a measure with the `max` and `min` parameters.
|
|
26
|
+
|
|
27
|
+
Parameters
|
|
28
|
+
----------
|
|
29
|
+
value : int
|
|
30
|
+
The measure.
|
|
31
|
+
parameters : Mapping[str, Any]
|
|
32
|
+
Bound parameters.
|
|
33
|
+
|
|
34
|
+
Returns
|
|
35
|
+
----------
|
|
36
|
+
int | None
|
|
37
|
+
The broken limit, or None.
|
|
38
|
+
"""
|
|
39
|
+
if parameters.get("max") is not None and value > parameters["max"]:
|
|
40
|
+
return parameters["max"]
|
|
41
|
+
if parameters.get("min") is not None and value < parameters["min"]:
|
|
42
|
+
return parameters["min"]
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class NodeMetric(Primitive):
|
|
47
|
+
"""
|
|
48
|
+
Measure syntax items (function body lines, parameter count, struct fields, number of descendant nodes
|
|
49
|
+
of a kind) and compare the measure with `max` / `min`. For `count:<node>` measures, `where.*` filters
|
|
50
|
+
the counted nodes; otherwise it filters the measured items.
|
|
51
|
+
(ABC -> Primitive)
|
|
52
|
+
|
|
53
|
+
Attributes
|
|
54
|
+
----------
|
|
55
|
+
kind : str
|
|
56
|
+
"node_metric".
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
kind = "node_metric"
|
|
60
|
+
layer = Layer.SYNTAX
|
|
61
|
+
parameters = (
|
|
62
|
+
ArgumentSpec("measure", ArgumentType.STR, required=True, description="body_lines, named_parameters, fields or count:<node kind>."),
|
|
63
|
+
ArgumentSpec("max", ArgumentType.INT, minimum=0, description="Largest accepted measure."),
|
|
64
|
+
ArgumentSpec("min", ArgumentType.INT, minimum=0, description="Smallest accepted measure."),
|
|
65
|
+
)
|
|
66
|
+
targets = ("function_definition", "function_declarator", "struct_definition", "file")
|
|
67
|
+
where_keys = frozenset({"name", "storage", "node", "context", "not_context"})
|
|
68
|
+
default_message = "{code}: {value} is over the limit of {limit}"
|
|
69
|
+
|
|
70
|
+
def validate(self, parameters: Mapping[str, Any], check: CheckDefinition) -> None:
|
|
71
|
+
"""
|
|
72
|
+
Check the measure name and that a limit is given.
|
|
73
|
+
|
|
74
|
+
Parameters
|
|
75
|
+
----------
|
|
76
|
+
parameters : Mapping[str, Any]
|
|
77
|
+
Bound parameter values.
|
|
78
|
+
check : CheckDefinition
|
|
79
|
+
The check definition.
|
|
80
|
+
|
|
81
|
+
Returns
|
|
82
|
+
----------
|
|
83
|
+
None
|
|
84
|
+
Nothing.
|
|
85
|
+
|
|
86
|
+
Raises
|
|
87
|
+
----------
|
|
88
|
+
ValueError
|
|
89
|
+
Unknown measure, measure not available for the target, or no limit.
|
|
90
|
+
"""
|
|
91
|
+
measure: str = parameters["measure"]
|
|
92
|
+
target: str = check.selection.target or self.targets[0]
|
|
93
|
+
if measure.startswith(COUNT_MEASURE_PREFIX):
|
|
94
|
+
kind: str = measure[len(COUNT_MEASURE_PREFIX):]
|
|
95
|
+
if kind not in {node_kind.value for node_kind in NodeKind}:
|
|
96
|
+
raise ValueError(f"unknown node kind '{kind}' in measure '{measure}'")
|
|
97
|
+
elif measure not in NODE_MEASURES:
|
|
98
|
+
raise ValueError(f"unknown measure '{measure}' (expected {', '.join(NODE_MEASURES)} or count:<node>)")
|
|
99
|
+
elif target not in NODE_MEASURES[measure]:
|
|
100
|
+
raise ValueError(f"measure '{measure}' does not apply to target '{target}'")
|
|
101
|
+
if parameters.get("max") is None and parameters.get("min") is None:
|
|
102
|
+
raise ValueError("node_metric needs 'max', 'min' or both")
|
|
103
|
+
|
|
104
|
+
def _items(self, run: CheckRun, unit: CUnit, target: str, filtered: bool) -> Iterator[tuple[Node, Node, FunctionInfo | None]]:
|
|
105
|
+
"""
|
|
106
|
+
Items measured in a file.
|
|
107
|
+
|
|
108
|
+
Parameters
|
|
109
|
+
----------
|
|
110
|
+
run : CheckRun
|
|
111
|
+
The check run.
|
|
112
|
+
unit : CUnit
|
|
113
|
+
The file.
|
|
114
|
+
target : str
|
|
115
|
+
The target.
|
|
116
|
+
filtered : bool
|
|
117
|
+
Whether `where.*` filters the items (False for count measures).
|
|
118
|
+
|
|
119
|
+
Returns
|
|
120
|
+
----------
|
|
121
|
+
Iterator[tuple[Node, Node, FunctionInfo | None]]
|
|
122
|
+
(item node, node to report on, function information when relevant).
|
|
123
|
+
"""
|
|
124
|
+
if target == "file":
|
|
125
|
+
yield unit.tree, unit.tree, None
|
|
126
|
+
return
|
|
127
|
+
if target in ("function_definition", "function_declarator"):
|
|
128
|
+
functions: tuple[FunctionInfo, ...] = unit.functions if target == "function_definition" else unit.functions + unit.prototypes
|
|
129
|
+
for function in sorted(functions, key=lambda info: info.declarator.start_offset):
|
|
130
|
+
item: Node = function.node if target == "function_definition" else function.declarator
|
|
131
|
+
if not filtered or run.node_selected(unit, item, function.storage):
|
|
132
|
+
yield item, item, function
|
|
133
|
+
return
|
|
134
|
+
for record in unit.nodes(NodeKind.STRUCT_SPECIFIER, NodeKind.UNION_SPECIFIER):
|
|
135
|
+
if record.fields["has_body"] and (not filtered or run.node_selected(unit, record)):
|
|
136
|
+
yield record, record, None
|
|
137
|
+
|
|
138
|
+
def _measure(self, run: CheckRun, unit: CUnit, item: Node, function: FunctionInfo | None, measure: str) -> int:
|
|
139
|
+
"""
|
|
140
|
+
Measure one item.
|
|
141
|
+
|
|
142
|
+
Parameters
|
|
143
|
+
----------
|
|
144
|
+
run : CheckRun
|
|
145
|
+
The check run.
|
|
146
|
+
unit : CUnit
|
|
147
|
+
The file.
|
|
148
|
+
item : Node
|
|
149
|
+
The item.
|
|
150
|
+
function : FunctionInfo | None
|
|
151
|
+
Function information of the item, if any.
|
|
152
|
+
measure : str
|
|
153
|
+
The measure.
|
|
154
|
+
|
|
155
|
+
Returns
|
|
156
|
+
----------
|
|
157
|
+
int
|
|
158
|
+
The measure.
|
|
159
|
+
"""
|
|
160
|
+
if measure == "body_lines":
|
|
161
|
+
body: Node = item.fields["body"]
|
|
162
|
+
return max(body.end_line - body.line - 1, 0)
|
|
163
|
+
if measure == "named_parameters":
|
|
164
|
+
return len(function.parameters) if function is not None else 0
|
|
165
|
+
if measure == "fields":
|
|
166
|
+
return sum(max(len(member.fields.get("declarators", ())), 1) for member in item.children if member.kind is NodeKind.FIELD_DECLARATION)
|
|
167
|
+
kind: NodeKind = NodeKind(measure[len(COUNT_MEASURE_PREFIX):])
|
|
168
|
+
nodes: list[Node] = unit.nodes(kind) if item.kind is NodeKind.TRANSLATION_UNIT else list(item.descendants(kind))
|
|
169
|
+
return sum(1 for node in nodes if run.node_selected(unit, node))
|
|
170
|
+
|
|
171
|
+
def run(self, run: CheckRun) -> Iterator[Finding]:
|
|
172
|
+
"""
|
|
173
|
+
Run the check (see class description).
|
|
174
|
+
|
|
175
|
+
Parameters
|
|
176
|
+
----------
|
|
177
|
+
run : CheckRun
|
|
178
|
+
Project context, files and parameters.
|
|
179
|
+
|
|
180
|
+
Returns
|
|
181
|
+
----------
|
|
182
|
+
Iterator[Finding]
|
|
183
|
+
The problems found.
|
|
184
|
+
"""
|
|
185
|
+
target: str = run.selection.target or self.targets[0]
|
|
186
|
+
measure: str = run.parameters["measure"]
|
|
187
|
+
counting: bool = measure.startswith(COUNT_MEASURE_PREFIX)
|
|
188
|
+
for unit in run.units():
|
|
189
|
+
for item, located, function in self._items(run, unit, target, not counting):
|
|
190
|
+
value: int = self._measure(run, unit, item, function, measure)
|
|
191
|
+
limit: int | None = _over_limit(value, run.parameters)
|
|
192
|
+
if limit is None:
|
|
193
|
+
continue
|
|
194
|
+
if target == "file":
|
|
195
|
+
yield Finding(unit.path, 1, 1, value=value, limit=limit, node_key=unit.path)
|
|
196
|
+
elif target == "function_declarator" and located.fields.get("name_token") is not None:
|
|
197
|
+
name_token = located.fields["name_token"]
|
|
198
|
+
yield Finding(unit.path, name_token.line, name_token.column, name_token.end_line, name_token.end_column, name=located.name, value=value, limit=limit, node_key=id(located))
|
|
199
|
+
else:
|
|
200
|
+
yield node_finding(unit.path, located, value=value, limit=limit)
|
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from collections.abc import Iterator, Mapping
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from sources.analysis.source import Line, SourceFile, visual_overflow_index, visual_width
|
|
6
|
+
from sources.analysis.syntax import Node
|
|
7
|
+
from sources.analysis.unit import CUnit
|
|
8
|
+
from sources.enums import ArgumentType, Layer, NodeKind, TokenKind
|
|
9
|
+
from sources.rules.arguments import ArgumentSpec
|
|
10
|
+
from sources.rules.definition import CheckDefinition
|
|
11
|
+
from sources.rules.primitives.base import CheckRun, Finding, Primitive
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
# Region value of `blank_lines` for the gap between two consecutive function definitions.
|
|
15
|
+
BETWEEN_FUNCTIONS_REGION: str = "between:function_definition"
|
|
16
|
+
|
|
17
|
+
# Region value of `blank_lines` for the gap between the leading declarations of a function and its statements.
|
|
18
|
+
AFTER_DECLARATIONS_REGION: str = "after:declarations"
|
|
19
|
+
|
|
20
|
+
# Region value of `blank_lines` for every other line of a function body (one finding per blank line).
|
|
21
|
+
FUNCTION_BODY_REGION: str = "function_body"
|
|
22
|
+
|
|
23
|
+
# Node kinds that are declarations inside a function body.
|
|
24
|
+
DECLARATION_KINDS: tuple[NodeKind, ...] = (NodeKind.DECLARATION, NodeKind.TYPE_DEFINITION)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _text_files(run: CheckRun) -> Iterator[SourceFile]:
|
|
28
|
+
"""
|
|
29
|
+
Files to analyse that have text (not binary, not skipped).
|
|
30
|
+
|
|
31
|
+
Parameters
|
|
32
|
+
----------
|
|
33
|
+
run : CheckRun
|
|
34
|
+
The check run.
|
|
35
|
+
|
|
36
|
+
Returns
|
|
37
|
+
----------
|
|
38
|
+
Iterator[SourceFile]
|
|
39
|
+
The files.
|
|
40
|
+
"""
|
|
41
|
+
for source in run.files:
|
|
42
|
+
if not source.binary and source.skipped is None:
|
|
43
|
+
yield source
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _limit_violation(value: int, parameters: Mapping[str, Any]) -> int | None:
|
|
47
|
+
"""
|
|
48
|
+
Compare a count with the `exact`, `min` and `max` parameters.
|
|
49
|
+
|
|
50
|
+
Parameters
|
|
51
|
+
----------
|
|
52
|
+
value : int
|
|
53
|
+
The measured count.
|
|
54
|
+
parameters : Mapping[str, Any]
|
|
55
|
+
Bound parameters (`exact`, `min`, `max`, any of them None).
|
|
56
|
+
|
|
57
|
+
Returns
|
|
58
|
+
----------
|
|
59
|
+
int | None
|
|
60
|
+
The limit that is broken, or None when the count is accepted.
|
|
61
|
+
"""
|
|
62
|
+
if parameters.get("exact") is not None and value != parameters["exact"]:
|
|
63
|
+
return parameters["exact"]
|
|
64
|
+
if parameters.get("max") is not None and value > parameters["max"]:
|
|
65
|
+
return parameters["max"]
|
|
66
|
+
if parameters.get("min") is not None and value < parameters["min"]:
|
|
67
|
+
return parameters["min"]
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class TextRegex(Primitive):
|
|
72
|
+
"""
|
|
73
|
+
Search a regular expression in the raw bytes, the decoded text or each line of a file, and forbid or
|
|
74
|
+
require it.
|
|
75
|
+
(ABC -> Primitive)
|
|
76
|
+
|
|
77
|
+
Attributes
|
|
78
|
+
----------
|
|
79
|
+
kind : str
|
|
80
|
+
"text_regex".
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
kind = "text_regex"
|
|
84
|
+
layer = Layer.TEXT
|
|
85
|
+
parameters = (
|
|
86
|
+
ArgumentSpec("on", ArgumentType.ENUM, default="line", choices=("bytes", "text", "line"), description="What the pattern is applied to."),
|
|
87
|
+
ArgumentSpec("pattern", ArgumentType.REGEX, required=True, description="Regular expression."),
|
|
88
|
+
ArgumentSpec("mode", ArgumentType.ENUM, default="forbid", choices=("forbid", "require"), description="Forbid every match, or require one."),
|
|
89
|
+
ArgumentSpec("anchor", ArgumentType.ENUM, default="any", choices=("any", "file_start", "file_end"), description="Where a match counts (and where a missing match is reported)."),
|
|
90
|
+
ArgumentSpec("skip_empty_files", ArgumentType.BOOL, default=True, description="Ignore empty files."),
|
|
91
|
+
)
|
|
92
|
+
default_message = "{code}: '{value}' is not allowed here"
|
|
93
|
+
|
|
94
|
+
def _matches(self, source: SourceFile, pattern: re.Pattern[str], on: str, anchor: str) -> Iterator[tuple[int, int, int, int, str]]:
|
|
95
|
+
"""
|
|
96
|
+
Every accepted match, as positions.
|
|
97
|
+
|
|
98
|
+
Parameters
|
|
99
|
+
----------
|
|
100
|
+
source : SourceFile
|
|
101
|
+
The file.
|
|
102
|
+
pattern : re.Pattern[str]
|
|
103
|
+
The pattern.
|
|
104
|
+
on : str
|
|
105
|
+
"bytes", "text" or "line".
|
|
106
|
+
anchor : str
|
|
107
|
+
"any", "file_start" or "file_end".
|
|
108
|
+
|
|
109
|
+
Returns
|
|
110
|
+
----------
|
|
111
|
+
Iterator[tuple[int, int, int, int, str]]
|
|
112
|
+
(line, column, end_line, end_column, matched text) of each match.
|
|
113
|
+
"""
|
|
114
|
+
if on == "line":
|
|
115
|
+
for line in source.lines:
|
|
116
|
+
for match in pattern.finditer(line.text):
|
|
117
|
+
yield line.number, match.start() + 1, line.number, match.end() + 1, match.group()
|
|
118
|
+
return
|
|
119
|
+
if on == "bytes":
|
|
120
|
+
raw_pattern: re.Pattern[bytes] = re.compile(pattern.pattern.encode("utf-8", "surrogateescape"), pattern.flags & ~re.UNICODE)
|
|
121
|
+
for match in raw_pattern.finditer(source.raw):
|
|
122
|
+
if (anchor == "file_start" and match.start() != 0) or (anchor == "file_end" and match.end() != len(source.raw)):
|
|
123
|
+
continue
|
|
124
|
+
line, column = source.position(source.char_offset_of_byte(match.start()))
|
|
125
|
+
end_line, end_column = source.position(source.char_offset_of_byte(match.end()))
|
|
126
|
+
yield line, column, end_line, end_column, match.group().decode("utf-8", "surrogateescape")
|
|
127
|
+
return
|
|
128
|
+
for match in pattern.finditer(source.text):
|
|
129
|
+
if (anchor == "file_start" and match.start() != 0) or (anchor == "file_end" and match.end() != len(source.text)):
|
|
130
|
+
continue
|
|
131
|
+
line, column = source.position(match.start())
|
|
132
|
+
end_line, end_column = source.position(match.end())
|
|
133
|
+
yield line, column, end_line, end_column, match.group()
|
|
134
|
+
|
|
135
|
+
def run(self, run: CheckRun) -> Iterator[Finding]:
|
|
136
|
+
"""
|
|
137
|
+
Run the check (see class description).
|
|
138
|
+
|
|
139
|
+
Parameters
|
|
140
|
+
----------
|
|
141
|
+
run : CheckRun
|
|
142
|
+
Project context, files and parameters.
|
|
143
|
+
|
|
144
|
+
Returns
|
|
145
|
+
----------
|
|
146
|
+
Iterator[Finding]
|
|
147
|
+
The problems found.
|
|
148
|
+
"""
|
|
149
|
+
pattern: re.Pattern[str] = run.parameters["pattern"]
|
|
150
|
+
on: str = run.parameters["on"]
|
|
151
|
+
anchor: str = run.parameters["anchor"]
|
|
152
|
+
for source in run.files:
|
|
153
|
+
if source.skipped is not None or (source.binary and on != "bytes"):
|
|
154
|
+
continue
|
|
155
|
+
if run.parameters["skip_empty_files"] and not source.raw:
|
|
156
|
+
continue
|
|
157
|
+
matches: Iterator[tuple[int, int, int, int, str]] = self._matches(source, pattern, on, anchor)
|
|
158
|
+
if run.parameters["mode"] == "forbid":
|
|
159
|
+
for line, column, end_line, end_column, text in matches:
|
|
160
|
+
yield Finding(source.path, line, column, end_line, end_column, value=text)
|
|
161
|
+
continue
|
|
162
|
+
if next(matches, None) is None:
|
|
163
|
+
if anchor == "file_start" or not source.lines:
|
|
164
|
+
yield Finding(source.path, 1, 1)
|
|
165
|
+
else:
|
|
166
|
+
last: Line = source.lines[-1]
|
|
167
|
+
yield Finding(source.path, last.number, len(last.text) + 1)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class LineMetric(Primitive):
|
|
171
|
+
"""
|
|
172
|
+
Measure every line of a file and compare the measure with a maximum.
|
|
173
|
+
(ABC -> Primitive)
|
|
174
|
+
|
|
175
|
+
Attributes
|
|
176
|
+
----------
|
|
177
|
+
kind : str
|
|
178
|
+
"line_metric".
|
|
179
|
+
"""
|
|
180
|
+
|
|
181
|
+
kind = "line_metric"
|
|
182
|
+
layer = Layer.TEXT
|
|
183
|
+
parameters = (
|
|
184
|
+
ArgumentSpec("measure", ArgumentType.ENUM, default="visual_columns", choices=("visual_columns", "characters", "bytes"), description="What is measured."),
|
|
185
|
+
ArgumentSpec("tab_width", ArgumentType.INT, default=8, minimum=1, description="Columns between two tab stops (visual_columns only)."),
|
|
186
|
+
ArgumentSpec("max", ArgumentType.INT, required=True, minimum=0, description="Largest accepted measure."),
|
|
187
|
+
)
|
|
188
|
+
default_message = "{code}: line is {value} columns long (max {limit})"
|
|
189
|
+
|
|
190
|
+
def run(self, run: CheckRun) -> Iterator[Finding]:
|
|
191
|
+
"""
|
|
192
|
+
Run the check (see class description).
|
|
193
|
+
|
|
194
|
+
Parameters
|
|
195
|
+
----------
|
|
196
|
+
run : CheckRun
|
|
197
|
+
Project context, files and parameters.
|
|
198
|
+
|
|
199
|
+
Returns
|
|
200
|
+
----------
|
|
201
|
+
Iterator[Finding]
|
|
202
|
+
The problems found.
|
|
203
|
+
"""
|
|
204
|
+
measure: str = run.parameters["measure"]
|
|
205
|
+
tab_width: int = run.parameters["tab_width"]
|
|
206
|
+
limit: int = run.parameters["max"]
|
|
207
|
+
for source in _text_files(run):
|
|
208
|
+
for line in source.lines:
|
|
209
|
+
overflow: int | None
|
|
210
|
+
if measure == "visual_columns":
|
|
211
|
+
value: int = visual_width(line.text, tab_width)
|
|
212
|
+
overflow = visual_overflow_index(line.text, tab_width, limit)
|
|
213
|
+
elif measure == "characters":
|
|
214
|
+
value = len(line.text)
|
|
215
|
+
overflow = limit if value > limit else None
|
|
216
|
+
else:
|
|
217
|
+
value = len(line.text.encode("utf-8", "surrogateescape"))
|
|
218
|
+
overflow = None
|
|
219
|
+
if value > limit:
|
|
220
|
+
overflow = len(line.text.encode("utf-8", "surrogateescape")[:limit].decode("utf-8", "ignore"))
|
|
221
|
+
if value > limit:
|
|
222
|
+
yield Finding(source.path, line.number, (overflow or 0) + 1, line.number, len(line.text) + 1, value=value, limit=limit)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
class BlankLines(Primitive):
|
|
226
|
+
"""
|
|
227
|
+
Count blank lines in a region (start of file, end of file, between two function definitions) and
|
|
228
|
+
compare the count with `exact`, `min` and `max`.
|
|
229
|
+
(ABC -> Primitive)
|
|
230
|
+
|
|
231
|
+
Attributes
|
|
232
|
+
----------
|
|
233
|
+
kind : str
|
|
234
|
+
"blank_lines".
|
|
235
|
+
"""
|
|
236
|
+
|
|
237
|
+
kind = "blank_lines"
|
|
238
|
+
layer = Layer.SYNTAX
|
|
239
|
+
parameters = (
|
|
240
|
+
ArgumentSpec("region", ArgumentType.ENUM, required=True, choices=("file_start", "file_end", BETWEEN_FUNCTIONS_REGION, AFTER_DECLARATIONS_REGION, FUNCTION_BODY_REGION), description="Region whose blank lines are counted."),
|
|
241
|
+
ArgumentSpec("exact", ArgumentType.INT, minimum=0, description="Required number of blank lines."),
|
|
242
|
+
ArgumentSpec("min", ArgumentType.INT, minimum=0, description="Smallest accepted number of blank lines."),
|
|
243
|
+
ArgumentSpec("max", ArgumentType.INT, minimum=0, description="Largest accepted number of blank lines."),
|
|
244
|
+
)
|
|
245
|
+
default_message = "{code}: {value} blank line(s) (expected {limit})"
|
|
246
|
+
|
|
247
|
+
def validate(self, parameters: Mapping[str, Any], check: CheckDefinition) -> None:
|
|
248
|
+
"""
|
|
249
|
+
Require at least one of `exact`, `min` and `max`.
|
|
250
|
+
|
|
251
|
+
Parameters
|
|
252
|
+
----------
|
|
253
|
+
parameters : Mapping[str, Any]
|
|
254
|
+
Bound parameter values.
|
|
255
|
+
check : CheckDefinition
|
|
256
|
+
The check definition.
|
|
257
|
+
|
|
258
|
+
Returns
|
|
259
|
+
----------
|
|
260
|
+
None
|
|
261
|
+
Nothing.
|
|
262
|
+
|
|
263
|
+
Raises
|
|
264
|
+
----------
|
|
265
|
+
ValueError
|
|
266
|
+
No limit is given.
|
|
267
|
+
"""
|
|
268
|
+
if parameters["region"] != FUNCTION_BODY_REGION and all(parameters.get(key) is None for key in ("exact", "min", "max")):
|
|
269
|
+
raise ValueError("blank_lines needs at least one of 'exact', 'min' or 'max'")
|
|
270
|
+
|
|
271
|
+
def _between_functions(self, run: CheckRun, unit: CUnit) -> Iterator[Finding]:
|
|
272
|
+
"""
|
|
273
|
+
Check the gaps between consecutive top-level function definitions. Gaps holding anything but blank
|
|
274
|
+
lines and comments (declarations, directives) are ignored.
|
|
275
|
+
|
|
276
|
+
Parameters
|
|
277
|
+
----------
|
|
278
|
+
run : CheckRun
|
|
279
|
+
The check run.
|
|
280
|
+
unit : CUnit
|
|
281
|
+
The file.
|
|
282
|
+
|
|
283
|
+
Returns
|
|
284
|
+
----------
|
|
285
|
+
Iterator[Finding]
|
|
286
|
+
The problems found.
|
|
287
|
+
"""
|
|
288
|
+
code_lines: set[int] = set()
|
|
289
|
+
comment_lines: set[int] = set()
|
|
290
|
+
for token in unit.tokens:
|
|
291
|
+
if token.kind is TokenKind.COMMENT:
|
|
292
|
+
comment_lines.update(range(token.line, token.end_line + 1))
|
|
293
|
+
elif not token.is_trivia:
|
|
294
|
+
code_lines.update(range(token.line, token.end_line + 1))
|
|
295
|
+
items: list[Node] = unit.tree.children
|
|
296
|
+
for previous, current in zip(items, items[1:]):
|
|
297
|
+
if previous.kind is not NodeKind.FUNCTION_DEFINITION or current.kind is not NodeKind.FUNCTION_DEFINITION:
|
|
298
|
+
continue
|
|
299
|
+
gap: range = range(previous.end_line + 1, current.line)
|
|
300
|
+
if any(number in code_lines for number in gap):
|
|
301
|
+
continue
|
|
302
|
+
blank: int = sum(1 for number in gap if number not in comment_lines and unit.source.line(number).is_blank)
|
|
303
|
+
limit: int | None = _limit_violation(blank, run.parameters)
|
|
304
|
+
if limit is not None:
|
|
305
|
+
yield Finding(unit.path, current.line, current.column, value=blank, limit=limit, name=current.name, node_key=id(current))
|
|
306
|
+
|
|
307
|
+
def _declaration_gap(self, unit: CUnit, body: Node) -> tuple[Node | None, range]:
|
|
308
|
+
"""
|
|
309
|
+
Gap between the leading declarations of a function body and its first statement.
|
|
310
|
+
|
|
311
|
+
Parameters
|
|
312
|
+
----------
|
|
313
|
+
unit : CUnit
|
|
314
|
+
The file.
|
|
315
|
+
body : Node
|
|
316
|
+
The function body.
|
|
317
|
+
|
|
318
|
+
Returns
|
|
319
|
+
----------
|
|
320
|
+
tuple[Node | None, range]
|
|
321
|
+
The first statement after the declarations (None when there is none or no declaration), and the
|
|
322
|
+
lines of the gap.
|
|
323
|
+
"""
|
|
324
|
+
items: list[Node] = body.children
|
|
325
|
+
count: int = 0
|
|
326
|
+
while count < len(items) and items[count].kind in DECLARATION_KINDS:
|
|
327
|
+
count += 1
|
|
328
|
+
if count == 0 or count == len(items):
|
|
329
|
+
return None, range(0)
|
|
330
|
+
return items[count], range(items[count - 1].end_line + 1, items[count].line)
|
|
331
|
+
|
|
332
|
+
def _function_bodies(self, run: CheckRun, region: str) -> Iterator[Finding]:
|
|
333
|
+
"""
|
|
334
|
+
Blank lines inside function bodies: the declaration gap (`after:declarations`), or every other blank
|
|
335
|
+
line (`function_body`, reported one by one).
|
|
336
|
+
|
|
337
|
+
Parameters
|
|
338
|
+
----------
|
|
339
|
+
run : CheckRun
|
|
340
|
+
The check run.
|
|
341
|
+
region : str
|
|
342
|
+
The region.
|
|
343
|
+
|
|
344
|
+
Returns
|
|
345
|
+
----------
|
|
346
|
+
Iterator[Finding]
|
|
347
|
+
The problems found.
|
|
348
|
+
"""
|
|
349
|
+
for unit in run.units():
|
|
350
|
+
comment_lines: set[int] = set()
|
|
351
|
+
for token in unit.comments:
|
|
352
|
+
comment_lines.update(range(token.line, token.end_line + 1))
|
|
353
|
+
for function in unit.functions:
|
|
354
|
+
body: Node = function.node.fields["body"]
|
|
355
|
+
statement, gap = self._declaration_gap(unit, body)
|
|
356
|
+
if region == AFTER_DECLARATIONS_REGION:
|
|
357
|
+
if statement is None:
|
|
358
|
+
continue
|
|
359
|
+
blank: int = sum(1 for number in gap if unit.source.line(number).is_blank)
|
|
360
|
+
limit: int | None = _limit_violation(blank, run.parameters)
|
|
361
|
+
if limit is not None:
|
|
362
|
+
yield Finding(unit.path, statement.line, statement.column, value=blank, limit=limit, name=function.name, node_key=id(body))
|
|
363
|
+
continue
|
|
364
|
+
for number in range(body.line + 1, body.end_line):
|
|
365
|
+
if number in gap or number in comment_lines or not unit.source.line(number).is_blank:
|
|
366
|
+
continue
|
|
367
|
+
yield Finding(unit.path, number, 1, value=1, limit=0, name=function.name, node_key=(id(body), number))
|
|
368
|
+
|
|
369
|
+
def run(self, run: CheckRun) -> Iterator[Finding]:
|
|
370
|
+
"""
|
|
371
|
+
Run the check (see class description).
|
|
372
|
+
|
|
373
|
+
Parameters
|
|
374
|
+
----------
|
|
375
|
+
run : CheckRun
|
|
376
|
+
Project context, files and parameters.
|
|
377
|
+
|
|
378
|
+
Returns
|
|
379
|
+
----------
|
|
380
|
+
Iterator[Finding]
|
|
381
|
+
The problems found.
|
|
382
|
+
"""
|
|
383
|
+
region: str = run.parameters["region"]
|
|
384
|
+
if region == BETWEEN_FUNCTIONS_REGION:
|
|
385
|
+
for unit in run.units():
|
|
386
|
+
yield from self._between_functions(run, unit)
|
|
387
|
+
return
|
|
388
|
+
if region in (AFTER_DECLARATIONS_REGION, FUNCTION_BODY_REGION):
|
|
389
|
+
yield from self._function_bodies(run, region)
|
|
390
|
+
return
|
|
391
|
+
for source in _text_files(run):
|
|
392
|
+
lines: tuple[Line, ...] = source.lines
|
|
393
|
+
if region == "file_start":
|
|
394
|
+
count: int = 0
|
|
395
|
+
while count < len(lines) and lines[count].is_blank:
|
|
396
|
+
count += 1
|
|
397
|
+
limit: int | None = _limit_violation(count, run.parameters)
|
|
398
|
+
if limit is not None:
|
|
399
|
+
yield Finding(source.path, 1, 1, value=count, limit=limit)
|
|
400
|
+
continue
|
|
401
|
+
last_content: int = len(lines)
|
|
402
|
+
while last_content > 0 and lines[last_content - 1].is_blank:
|
|
403
|
+
last_content -= 1
|
|
404
|
+
count = len(lines) - last_content
|
|
405
|
+
limit = _limit_violation(count, run.parameters)
|
|
406
|
+
if limit is not None:
|
|
407
|
+
line: int = min(last_content + limit + 1, len(lines)) if count > limit else max(len(lines), 1)
|
|
408
|
+
yield Finding(source.path, line, 1, value=count, limit=limit)
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
from collections.abc import Iterator, Mapping
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from sources.enums import ArgumentType, CodeContext, Layer, TokenKind
|
|
5
|
+
from sources.rules.arguments import ArgumentSpec
|
|
6
|
+
from sources.rules.definition import CheckDefinition
|
|
7
|
+
from sources.rules.primitives.base import DEFAULT_TOKEN_EXCLUDED_CONTEXTS, CheckRun, Finding, Primitive, token_finding
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class TokenForbid(Primitive):
|
|
11
|
+
"""
|
|
12
|
+
Forbid tokens by kind and/or exact text, in the selected contexts. Comments and strings are skipped by
|
|
13
|
+
default, unless the forbidden kinds are comments or strings themselves.
|
|
14
|
+
(ABC -> Primitive)
|
|
15
|
+
|
|
16
|
+
Attributes
|
|
17
|
+
----------
|
|
18
|
+
kind : str
|
|
19
|
+
"token_forbid".
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
kind = "token_forbid"
|
|
23
|
+
layer = Layer.TOKENS
|
|
24
|
+
parameters = (
|
|
25
|
+
ArgumentSpec("kinds", ArgumentType.LIST, default=(), item_type=ArgumentType.ENUM, choices=tuple(kind.value for kind in TokenKind), description="Forbidden token kinds (empty: any kind)."),
|
|
26
|
+
ArgumentSpec("values", ArgumentType.LIST, default=(), description="Forbidden token texts (empty: any text)."),
|
|
27
|
+
)
|
|
28
|
+
where_keys = frozenset({"context", "not_context", "name"})
|
|
29
|
+
default_message = "{code}: '{name}' is forbidden"
|
|
30
|
+
|
|
31
|
+
def validate(self, parameters: Mapping[str, Any], check: CheckDefinition) -> None:
|
|
32
|
+
"""
|
|
33
|
+
Require `kinds` or `values`.
|
|
34
|
+
|
|
35
|
+
Parameters
|
|
36
|
+
----------
|
|
37
|
+
parameters : Mapping[str, Any]
|
|
38
|
+
Bound parameter values.
|
|
39
|
+
check : CheckDefinition
|
|
40
|
+
The check definition.
|
|
41
|
+
|
|
42
|
+
Returns
|
|
43
|
+
----------
|
|
44
|
+
None
|
|
45
|
+
Nothing.
|
|
46
|
+
|
|
47
|
+
Raises
|
|
48
|
+
----------
|
|
49
|
+
ValueError
|
|
50
|
+
Neither `kinds` nor `values` is given.
|
|
51
|
+
"""
|
|
52
|
+
if not parameters["kinds"] and not parameters["values"]:
|
|
53
|
+
raise ValueError("token_forbid needs 'kinds', 'values' or both")
|
|
54
|
+
|
|
55
|
+
def run(self, run: CheckRun) -> Iterator[Finding]:
|
|
56
|
+
"""
|
|
57
|
+
Run the check (see class description).
|
|
58
|
+
|
|
59
|
+
Parameters
|
|
60
|
+
----------
|
|
61
|
+
run : CheckRun
|
|
62
|
+
Project context, files and parameters.
|
|
63
|
+
|
|
64
|
+
Returns
|
|
65
|
+
----------
|
|
66
|
+
Iterator[Finding]
|
|
67
|
+
The problems found.
|
|
68
|
+
"""
|
|
69
|
+
kinds: frozenset[TokenKind] = frozenset(TokenKind(kind) for kind in run.parameters["kinds"])
|
|
70
|
+
values: frozenset[str] = frozenset(run.parameters["values"])
|
|
71
|
+
excluded: set[CodeContext] = set(DEFAULT_TOKEN_EXCLUDED_CONTEXTS)
|
|
72
|
+
if TokenKind.COMMENT in kinds:
|
|
73
|
+
excluded.discard(CodeContext.COMMENT)
|
|
74
|
+
if kinds & {TokenKind.STRING, TokenKind.CHAR, TokenKind.HEADER_NAME}:
|
|
75
|
+
excluded.discard(CodeContext.STRING)
|
|
76
|
+
default_excluded: frozenset[CodeContext] = frozenset(excluded)
|
|
77
|
+
for unit in run.units():
|
|
78
|
+
for token in unit.tokens:
|
|
79
|
+
if kinds and token.kind not in kinds:
|
|
80
|
+
continue
|
|
81
|
+
if values and token.text not in values:
|
|
82
|
+
continue
|
|
83
|
+
if run.token_selected(unit, token, default_excluded):
|
|
84
|
+
yield token_finding(unit.path, token, value=token.text)
|