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,203 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from collections.abc import Iterator
|
|
3
|
+
|
|
4
|
+
from sources.analysis.directives import Directive, MacroDefinition
|
|
5
|
+
from sources.analysis.tokens import Token
|
|
6
|
+
from sources.analysis.unit import CUnit
|
|
7
|
+
from sources.enums import ArgumentType, Layer, TokenKind
|
|
8
|
+
from sources.rules.arguments import ArgumentSpec
|
|
9
|
+
from sources.rules.primitives.base import CheckRun, Finding, Primitive
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
# Token kinds accepted as the whole body of a "literal" macro.
|
|
13
|
+
LITERAL_KINDS: frozenset[TokenKind] = frozenset({TokenKind.NUMBER, TokenKind.STRING, TokenKind.CHAR})
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _directive_finding(unit: CUnit, directive: Directive, **values: object) -> Finding:
|
|
17
|
+
"""
|
|
18
|
+
Finding located on a directive (from its `#` to the end of its last line).
|
|
19
|
+
|
|
20
|
+
Parameters
|
|
21
|
+
----------
|
|
22
|
+
unit : CUnit
|
|
23
|
+
The file.
|
|
24
|
+
directive : Directive
|
|
25
|
+
The directive.
|
|
26
|
+
**values : object
|
|
27
|
+
Other Finding fields.
|
|
28
|
+
|
|
29
|
+
Returns
|
|
30
|
+
----------
|
|
31
|
+
Finding
|
|
32
|
+
The finding.
|
|
33
|
+
"""
|
|
34
|
+
last: Token = directive.tokens[-1]
|
|
35
|
+
values.setdefault("name", directive.name)
|
|
36
|
+
return Finding(unit.path, directive.line, directive.column, last.end_line, last.end_column, node_key=id(directive), **values) # type: ignore[arg-type]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _is_literal_body(macro: MacroDefinition) -> bool:
|
|
40
|
+
"""
|
|
41
|
+
Whether a macro body is a single literal, possibly signed and parenthesised (`42`, `(-1)`, `"text"`).
|
|
42
|
+
|
|
43
|
+
Parameters
|
|
44
|
+
----------
|
|
45
|
+
macro : MacroDefinition
|
|
46
|
+
The macro.
|
|
47
|
+
|
|
48
|
+
Returns
|
|
49
|
+
----------
|
|
50
|
+
bool
|
|
51
|
+
True for a literal body.
|
|
52
|
+
"""
|
|
53
|
+
significant: list[Token] = [token for token in macro.body if not token.is_trivia]
|
|
54
|
+
while len(significant) >= 2 and significant[0].text == "(" and significant[-1].text == ")":
|
|
55
|
+
significant = significant[1:-1]
|
|
56
|
+
if significant and significant[0].text in ("-", "+"):
|
|
57
|
+
significant = significant[1:]
|
|
58
|
+
if significant and all(token.kind is TokenKind.STRING for token in significant):
|
|
59
|
+
return True
|
|
60
|
+
return len(significant) == 1 and significant[0].kind in LITERAL_KINDS
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class DirectiveCheck(Primitive):
|
|
64
|
+
"""
|
|
65
|
+
Constraints on preprocessor directives: required or forbidden operand, no line continuation, forbidden
|
|
66
|
+
tokens in macro bodies, literal-only bodies for object-like macros.
|
|
67
|
+
(ABC -> Primitive)
|
|
68
|
+
|
|
69
|
+
Attributes
|
|
70
|
+
----------
|
|
71
|
+
kind : str
|
|
72
|
+
"directive".
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
kind = "directive"
|
|
76
|
+
layer = Layer.TOKENS
|
|
77
|
+
parameters = (
|
|
78
|
+
ArgumentSpec("names", ArgumentType.LIST, required=True, description="Directive names checked (include, define, pragma...)."),
|
|
79
|
+
ArgumentSpec("operand_pattern", ArgumentType.REGEX, description="The operand must match (search) this pattern."),
|
|
80
|
+
ArgumentSpec("operand_forbid", ArgumentType.REGEX, description="The operand must not match (search) this pattern."),
|
|
81
|
+
ArgumentSpec("forbid_continuation", ArgumentType.BOOL, default=False, description="Forbid line continuations (backslash-newline)."),
|
|
82
|
+
ArgumentSpec("body_forbid", ArgumentType.LIST, default=(), description="Token texts forbidden in macro bodies."),
|
|
83
|
+
ArgumentSpec("require_literal_body", ArgumentType.BOOL, default=False, description="Object-like macros with a body must expand to a single literal."),
|
|
84
|
+
ArgumentSpec("any_directive", ArgumentType.BOOL, default=False, description="Report every directive of the given names (no other condition)."),
|
|
85
|
+
)
|
|
86
|
+
default_message = "{code}: invalid #{name} directive"
|
|
87
|
+
|
|
88
|
+
def run(self, run: CheckRun) -> Iterator[Finding]:
|
|
89
|
+
"""
|
|
90
|
+
Run the check (see class description).
|
|
91
|
+
|
|
92
|
+
Parameters
|
|
93
|
+
----------
|
|
94
|
+
run : CheckRun
|
|
95
|
+
Project context, files and parameters.
|
|
96
|
+
|
|
97
|
+
Returns
|
|
98
|
+
----------
|
|
99
|
+
Iterator[Finding]
|
|
100
|
+
The problems found.
|
|
101
|
+
"""
|
|
102
|
+
names: frozenset[str] = frozenset(run.parameters["names"])
|
|
103
|
+
required: re.Pattern[str] | None = run.parameters["operand_pattern"]
|
|
104
|
+
forbidden: re.Pattern[str] | None = run.parameters["operand_forbid"]
|
|
105
|
+
body_forbid: frozenset[str] = frozenset(run.parameters["body_forbid"])
|
|
106
|
+
for unit in run.units():
|
|
107
|
+
macros: dict[int, MacroDefinition] = {id(macro.directive): macro for macro in unit.macros}
|
|
108
|
+
for directive in unit.directives:
|
|
109
|
+
if directive.name not in names:
|
|
110
|
+
continue
|
|
111
|
+
if run.parameters["any_directive"]:
|
|
112
|
+
yield _directive_finding(unit, directive, value=directive.operand)
|
|
113
|
+
continue
|
|
114
|
+
if required is not None and not required.search(directive.operand):
|
|
115
|
+
yield _directive_finding(unit, directive, value=directive.operand)
|
|
116
|
+
continue
|
|
117
|
+
if forbidden is not None and forbidden.search(directive.operand):
|
|
118
|
+
yield _directive_finding(unit, directive, value=directive.operand)
|
|
119
|
+
continue
|
|
120
|
+
if run.parameters["forbid_continuation"] and directive.continued:
|
|
121
|
+
yield _directive_finding(unit, directive, value=directive.operand)
|
|
122
|
+
continue
|
|
123
|
+
macro: MacroDefinition | None = macros.get(id(directive))
|
|
124
|
+
if macro is None:
|
|
125
|
+
continue
|
|
126
|
+
bad: list[Token] = [token for token in macro.body if token.text in body_forbid and token.kind is TokenKind.PUNCTUATOR]
|
|
127
|
+
if bad:
|
|
128
|
+
yield _directive_finding(unit, directive, value=bad[0].text, name=macro.name)
|
|
129
|
+
continue
|
|
130
|
+
has_body: bool = any(not token.is_trivia for token in macro.body)
|
|
131
|
+
if run.parameters["require_literal_body"] and macro.parameters is None and has_body and not _is_literal_body(macro):
|
|
132
|
+
yield _directive_finding(unit, directive, value=directive.operand, name=macro.name)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class IncludeGuard(Primitive):
|
|
136
|
+
"""
|
|
137
|
+
Headers are wrapped in `#ifndef X` / `#define X` / ... / `#endif`: the guard is the first directive, its
|
|
138
|
+
`#endif` is the last one, and only comments and blank lines are outside it (`#pragma once` does not count).
|
|
139
|
+
(ABC -> Primitive)
|
|
140
|
+
|
|
141
|
+
Attributes
|
|
142
|
+
----------
|
|
143
|
+
kind : str
|
|
144
|
+
"include_guard".
|
|
145
|
+
"""
|
|
146
|
+
|
|
147
|
+
kind = "include_guard"
|
|
148
|
+
layer = Layer.TOKENS
|
|
149
|
+
default_message = "{code}: header is not protected by an include guard ({value})"
|
|
150
|
+
|
|
151
|
+
def _problem(self, unit: CUnit) -> tuple[int, int, str] | None:
|
|
152
|
+
"""
|
|
153
|
+
First problem of the include guard of a header.
|
|
154
|
+
|
|
155
|
+
Parameters
|
|
156
|
+
----------
|
|
157
|
+
unit : CUnit
|
|
158
|
+
The header.
|
|
159
|
+
|
|
160
|
+
Returns
|
|
161
|
+
----------
|
|
162
|
+
tuple[int, int, str] | None
|
|
163
|
+
(line, column, reason), or None when the guard is correct.
|
|
164
|
+
"""
|
|
165
|
+
directives: tuple[Directive, ...] = unit.directives
|
|
166
|
+
code: list[Token] = [token for token in unit.tokens if token.is_significant]
|
|
167
|
+
if not directives or directives[0].name != "ifndef":
|
|
168
|
+
return 1, 1, "missing #ifndef"
|
|
169
|
+
opening: Directive = directives[0]
|
|
170
|
+
guard: str = opening.operand.split()[0] if opening.operand.split() else ""
|
|
171
|
+
if code and code[0].offset < opening.tokens[0].offset:
|
|
172
|
+
return code[0].line, code[0].column, "code before #ifndef"
|
|
173
|
+
if len(directives) < 3 or directives[1].name != "define" or (directives[1].operand.split() or [""])[0] != guard:
|
|
174
|
+
return opening.line, opening.column, f"#ifndef {guard} is not followed by #define {guard}"
|
|
175
|
+
closing: Directive = directives[-1]
|
|
176
|
+
if closing.name != "endif" or closing.depth != 0:
|
|
177
|
+
return closing.line, closing.column, "the last directive is not the closing #endif"
|
|
178
|
+
for directive in directives[1:-1]:
|
|
179
|
+
if directive.depth == 0:
|
|
180
|
+
return directive.line, directive.column, "directive outside the include guard"
|
|
181
|
+
after: list[Token] = [token for token in code if token.offset > closing.tokens[0].offset]
|
|
182
|
+
if after:
|
|
183
|
+
return after[0].line, after[0].column, "code after #endif"
|
|
184
|
+
return None
|
|
185
|
+
|
|
186
|
+
def run(self, run: CheckRun) -> Iterator[Finding]:
|
|
187
|
+
"""
|
|
188
|
+
Run the check (see class description).
|
|
189
|
+
|
|
190
|
+
Parameters
|
|
191
|
+
----------
|
|
192
|
+
run : CheckRun
|
|
193
|
+
Project context, files and parameters.
|
|
194
|
+
|
|
195
|
+
Returns
|
|
196
|
+
----------
|
|
197
|
+
Iterator[Finding]
|
|
198
|
+
The problems found.
|
|
199
|
+
"""
|
|
200
|
+
for unit in run.units():
|
|
201
|
+
problem: tuple[int, int, str] | None = self._problem(unit)
|
|
202
|
+
if problem is not None:
|
|
203
|
+
yield Finding(unit.path, problem[0], problem[1], value=problem[2], node_key=unit.path)
|
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
from collections.abc import Iterator
|
|
2
|
+
|
|
3
|
+
from sources.analysis.source import Line
|
|
4
|
+
from sources.analysis.syntax import Node
|
|
5
|
+
from sources.analysis.tokens import Token
|
|
6
|
+
from sources.analysis.unit import CUnit
|
|
7
|
+
from sources.enums import ArgumentType, Layer, NodeKind, TokenKind
|
|
8
|
+
from sources.rules.arguments import ArgumentSpec
|
|
9
|
+
from sources.rules.primitives.base import CheckRun, Finding, Primitive
|
|
10
|
+
from sources.rules.primitives.layout import first_code_of_line, starts_line
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
# Control statements whose body is indented one level deeper when it is not a block.
|
|
14
|
+
BODY_OWNERS: frozenset[NodeKind] = frozenset({NodeKind.WHILE_STATEMENT, NodeKind.FOR_STATEMENT, NodeKind.DO_STATEMENT, NodeKind.SWITCH_STATEMENT})
|
|
15
|
+
|
|
16
|
+
# Tokens that may close a construct at the indentation of the statement that opened it.
|
|
17
|
+
CLOSING_TEXTS: frozenset[str] = frozenset({"}", ")", "]"})
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _leading(line: Line) -> str:
|
|
21
|
+
"""
|
|
22
|
+
Leading whitespace of a line.
|
|
23
|
+
|
|
24
|
+
Parameters
|
|
25
|
+
----------
|
|
26
|
+
line : Line
|
|
27
|
+
The line.
|
|
28
|
+
|
|
29
|
+
Returns
|
|
30
|
+
----------
|
|
31
|
+
str
|
|
32
|
+
The whitespace.
|
|
33
|
+
"""
|
|
34
|
+
return line.text[:len(line.text) - len(line.text.lstrip(" \t"))]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class _Layout:
|
|
38
|
+
"""
|
|
39
|
+
Expected indentation of the lines of a file, computed from its syntax tree: exact levels for lines
|
|
40
|
+
that start a block item, minimum levels for continuation lines.
|
|
41
|
+
|
|
42
|
+
Attributes
|
|
43
|
+
----------
|
|
44
|
+
unit : CUnit
|
|
45
|
+
The file.
|
|
46
|
+
width : int
|
|
47
|
+
Spaces per level.
|
|
48
|
+
exact : dict[int, tuple[int, int]]
|
|
49
|
+
Accepted level range of lines that start an item, by line.
|
|
50
|
+
spans : list[tuple[int, int, int]]
|
|
51
|
+
(start offset, end offset, level) of every item, for continuation lines.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
def __init__(self, unit: CUnit, width: int) -> None:
|
|
55
|
+
"""
|
|
56
|
+
Compute the layout.
|
|
57
|
+
|
|
58
|
+
Parameters
|
|
59
|
+
----------
|
|
60
|
+
unit : CUnit
|
|
61
|
+
The file.
|
|
62
|
+
width : int
|
|
63
|
+
Spaces per level.
|
|
64
|
+
|
|
65
|
+
Returns
|
|
66
|
+
----------
|
|
67
|
+
None
|
|
68
|
+
Nothing.
|
|
69
|
+
"""
|
|
70
|
+
self.unit: CUnit = unit
|
|
71
|
+
self.width: int = width
|
|
72
|
+
self.exact: dict[int, tuple[int, int]] = {}
|
|
73
|
+
self.spans: list[tuple[int, int, int]] = []
|
|
74
|
+
for child in unit.tree.children:
|
|
75
|
+
self._item(child, 0)
|
|
76
|
+
|
|
77
|
+
def _actual(self, line: int) -> int | None:
|
|
78
|
+
"""
|
|
79
|
+
Indentation level actually used on a line.
|
|
80
|
+
|
|
81
|
+
Parameters
|
|
82
|
+
----------
|
|
83
|
+
line : int
|
|
84
|
+
1-based line.
|
|
85
|
+
|
|
86
|
+
Returns
|
|
87
|
+
----------
|
|
88
|
+
int | None
|
|
89
|
+
The level, or None when the indentation is not a whole number of levels.
|
|
90
|
+
"""
|
|
91
|
+
leading: str = _leading(self.unit.source.line(line))
|
|
92
|
+
if "\t" in leading or len(leading) % self.width:
|
|
93
|
+
return None
|
|
94
|
+
return len(leading) // self.width
|
|
95
|
+
|
|
96
|
+
def _expect(self, token: Token | None, low: int, high: int | None = None) -> None:
|
|
97
|
+
"""
|
|
98
|
+
Record the accepted levels of the line of a token, when the token starts its line.
|
|
99
|
+
|
|
100
|
+
Parameters
|
|
101
|
+
----------
|
|
102
|
+
token : Token | None
|
|
103
|
+
The token.
|
|
104
|
+
low : int
|
|
105
|
+
Lowest accepted level.
|
|
106
|
+
high : int | None
|
|
107
|
+
Highest accepted level (default: low).
|
|
108
|
+
|
|
109
|
+
Returns
|
|
110
|
+
----------
|
|
111
|
+
None
|
|
112
|
+
Nothing.
|
|
113
|
+
"""
|
|
114
|
+
if token is not None and starts_line(self.unit, token):
|
|
115
|
+
self.exact.setdefault(token.line, (low, low if high is None else high))
|
|
116
|
+
|
|
117
|
+
def _item(self, node: Node, depth: int, high: int | None = None) -> None:
|
|
118
|
+
"""
|
|
119
|
+
Record a block item and its content.
|
|
120
|
+
|
|
121
|
+
Parameters
|
|
122
|
+
----------
|
|
123
|
+
node : Node
|
|
124
|
+
The item.
|
|
125
|
+
depth : int
|
|
126
|
+
Expected level of its first line.
|
|
127
|
+
high : int | None
|
|
128
|
+
Highest accepted level when several are accepted (the actual one is then used for the content).
|
|
129
|
+
|
|
130
|
+
Returns
|
|
131
|
+
----------
|
|
132
|
+
None
|
|
133
|
+
Nothing.
|
|
134
|
+
"""
|
|
135
|
+
if node.kind is NodeKind.ERROR:
|
|
136
|
+
return
|
|
137
|
+
if high is not None and node.first is not None and starts_line(self.unit, node.first):
|
|
138
|
+
actual: int | None = self._actual(node.first.line)
|
|
139
|
+
if actual is not None and depth <= actual <= high:
|
|
140
|
+
depth, high = actual, None
|
|
141
|
+
if node.kind is not NodeKind.LABELED_STATEMENT:
|
|
142
|
+
self._expect(node.first, depth, high)
|
|
143
|
+
self.spans.append((node.start_offset, node.end_offset, depth))
|
|
144
|
+
self._content(node, depth)
|
|
145
|
+
|
|
146
|
+
def _compound(self, compound: Node, depth: int, children: int | None = None, children_high: int | None = None) -> None:
|
|
147
|
+
"""
|
|
148
|
+
Record a block whose brackets are at `depth`.
|
|
149
|
+
|
|
150
|
+
Parameters
|
|
151
|
+
----------
|
|
152
|
+
compound : Node
|
|
153
|
+
The COMPOUND_STATEMENT.
|
|
154
|
+
depth : int
|
|
155
|
+
Level of its brackets.
|
|
156
|
+
children : int | None
|
|
157
|
+
Level of its items (default: depth + 1).
|
|
158
|
+
children_high : int | None
|
|
159
|
+
Highest accepted level of its items.
|
|
160
|
+
|
|
161
|
+
Returns
|
|
162
|
+
----------
|
|
163
|
+
None
|
|
164
|
+
Nothing.
|
|
165
|
+
"""
|
|
166
|
+
self._expect(compound.first, depth)
|
|
167
|
+
self._expect(compound.last, depth)
|
|
168
|
+
for child in compound.children:
|
|
169
|
+
self._item(child, depth + 1 if children is None else children, children_high)
|
|
170
|
+
|
|
171
|
+
def _body(self, body: Node | None, depth: int) -> None:
|
|
172
|
+
"""
|
|
173
|
+
Record the body of a control statement at `depth`.
|
|
174
|
+
|
|
175
|
+
Parameters
|
|
176
|
+
----------
|
|
177
|
+
body : Node | None
|
|
178
|
+
The body.
|
|
179
|
+
depth : int
|
|
180
|
+
Level of the control statement.
|
|
181
|
+
|
|
182
|
+
Returns
|
|
183
|
+
----------
|
|
184
|
+
None
|
|
185
|
+
Nothing.
|
|
186
|
+
"""
|
|
187
|
+
if body is None:
|
|
188
|
+
return
|
|
189
|
+
if body.kind is NodeKind.COMPOUND_STATEMENT:
|
|
190
|
+
self._compound(body, depth)
|
|
191
|
+
else:
|
|
192
|
+
self._item(body, depth + 1)
|
|
193
|
+
|
|
194
|
+
def _record(self, record: Node | None, depth: int) -> None:
|
|
195
|
+
"""
|
|
196
|
+
Record a struct, union or enum body declared at `depth`.
|
|
197
|
+
|
|
198
|
+
Parameters
|
|
199
|
+
----------
|
|
200
|
+
record : Node | None
|
|
201
|
+
The specifier.
|
|
202
|
+
depth : int
|
|
203
|
+
Level of the declaration.
|
|
204
|
+
|
|
205
|
+
Returns
|
|
206
|
+
----------
|
|
207
|
+
None
|
|
208
|
+
Nothing.
|
|
209
|
+
"""
|
|
210
|
+
if record is None or not record.fields.get("has_body"):
|
|
211
|
+
return
|
|
212
|
+
self._expect(record.fields.get("body_close"), depth)
|
|
213
|
+
for member in record.children:
|
|
214
|
+
self._item(member, depth + 1)
|
|
215
|
+
|
|
216
|
+
def _content(self, node: Node, depth: int) -> None:
|
|
217
|
+
"""
|
|
218
|
+
Record the nested items of a node.
|
|
219
|
+
|
|
220
|
+
Parameters
|
|
221
|
+
----------
|
|
222
|
+
node : Node
|
|
223
|
+
The node.
|
|
224
|
+
depth : int
|
|
225
|
+
Its level.
|
|
226
|
+
|
|
227
|
+
Returns
|
|
228
|
+
----------
|
|
229
|
+
None
|
|
230
|
+
Nothing.
|
|
231
|
+
"""
|
|
232
|
+
kind: NodeKind = node.kind
|
|
233
|
+
if kind is NodeKind.FUNCTION_DEFINITION:
|
|
234
|
+
self._compound(node.fields["body"], depth)
|
|
235
|
+
elif kind is NodeKind.COMPOUND_STATEMENT:
|
|
236
|
+
self._compound(node, depth)
|
|
237
|
+
elif kind is NodeKind.IF_STATEMENT:
|
|
238
|
+
self._body(node.fields["consequence"], depth)
|
|
239
|
+
self._expect(node.fields.get("else_token"), depth)
|
|
240
|
+
alternative: Node | None = node.fields.get("alternative")
|
|
241
|
+
if alternative is not None and alternative.kind is NodeKind.IF_STATEMENT:
|
|
242
|
+
self.spans.append((alternative.start_offset, alternative.end_offset, depth))
|
|
243
|
+
self._content(alternative, depth)
|
|
244
|
+
else:
|
|
245
|
+
self._body(alternative, depth)
|
|
246
|
+
elif kind is NodeKind.SWITCH_STATEMENT:
|
|
247
|
+
body: Node = node.fields["body"]
|
|
248
|
+
if body.kind is NodeKind.COMPOUND_STATEMENT:
|
|
249
|
+
self._compound(body, depth, depth, depth + 1)
|
|
250
|
+
else:
|
|
251
|
+
self._item(body, depth + 1)
|
|
252
|
+
elif kind in BODY_OWNERS:
|
|
253
|
+
self._body(node.fields.get("body"), depth)
|
|
254
|
+
self._expect(node.fields.get("while_token"), depth)
|
|
255
|
+
elif kind is NodeKind.CASE_STATEMENT:
|
|
256
|
+
statement: Node | None = node.fields.get("statement")
|
|
257
|
+
if statement is not None:
|
|
258
|
+
self._item(statement, depth + 1)
|
|
259
|
+
elif kind is NodeKind.LABELED_STATEMENT:
|
|
260
|
+
statement = node.fields.get("statement")
|
|
261
|
+
if statement is not None:
|
|
262
|
+
self._item(statement, depth)
|
|
263
|
+
elif kind in (NodeKind.DECLARATION, NodeKind.TYPE_DEFINITION, NodeKind.FIELD_DECLARATION):
|
|
264
|
+
self._record(node.fields.get("type_node"), depth)
|
|
265
|
+
|
|
266
|
+
def expected(self, token: Token) -> tuple[int, int | None, bool]:
|
|
267
|
+
"""
|
|
268
|
+
Accepted levels of the line starting with a token.
|
|
269
|
+
|
|
270
|
+
Parameters
|
|
271
|
+
----------
|
|
272
|
+
token : Token
|
|
273
|
+
First code token of the line.
|
|
274
|
+
|
|
275
|
+
Returns
|
|
276
|
+
----------
|
|
277
|
+
tuple[int, int | None, bool]
|
|
278
|
+
(lowest level, highest level or None for "at least", whether the line starts an item).
|
|
279
|
+
"""
|
|
280
|
+
if token.line in self.exact:
|
|
281
|
+
low, high = self.exact[token.line]
|
|
282
|
+
return low, high, True
|
|
283
|
+
depth: int = 0
|
|
284
|
+
for start, end, level in self.spans:
|
|
285
|
+
if start < token.offset < end:
|
|
286
|
+
depth = level
|
|
287
|
+
if token.text in CLOSING_TEXTS:
|
|
288
|
+
return depth, None, False
|
|
289
|
+
return depth + 1, None, False
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
class Indentation(Primitive):
|
|
293
|
+
"""
|
|
294
|
+
Leading whitespace of lines. Modes: `tabs` (no tab in the indentation), `multiple_of` (whole number of
|
|
295
|
+
`unit` spaces), `block` (level of each line from the syntax tree; continuation lines one level deeper at
|
|
296
|
+
least), `preprocessor` (directives indented by their conditional nesting depth, independently of the code).
|
|
297
|
+
Block comment bodies and string continuations are never checked.
|
|
298
|
+
(ABC -> Primitive)
|
|
299
|
+
|
|
300
|
+
Attributes
|
|
301
|
+
----------
|
|
302
|
+
kind : str
|
|
303
|
+
"indentation".
|
|
304
|
+
"""
|
|
305
|
+
|
|
306
|
+
kind = "indentation"
|
|
307
|
+
layer = Layer.SYNTAX
|
|
308
|
+
parameters = (
|
|
309
|
+
ArgumentSpec("mode", ArgumentType.ENUM, required=True, choices=("tabs", "multiple_of", "block", "preprocessor"), description="What is checked."),
|
|
310
|
+
ArgumentSpec("unit", ArgumentType.INT, default=4, minimum=1, description="Spaces per indentation level."),
|
|
311
|
+
)
|
|
312
|
+
default_message = "{code}: bad indentation"
|
|
313
|
+
|
|
314
|
+
def _code_lines(self, unit: CUnit) -> Iterator[tuple[Line, Token]]:
|
|
315
|
+
"""
|
|
316
|
+
Lines whose first token is code (not a comment, not a directive, not inside a comment or string).
|
|
317
|
+
|
|
318
|
+
Parameters
|
|
319
|
+
----------
|
|
320
|
+
unit : CUnit
|
|
321
|
+
The file.
|
|
322
|
+
|
|
323
|
+
Returns
|
|
324
|
+
----------
|
|
325
|
+
Iterator[tuple[Line, Token]]
|
|
326
|
+
(line, first token) pairs.
|
|
327
|
+
"""
|
|
328
|
+
for line in unit.source.lines:
|
|
329
|
+
token: Token | None = first_code_of_line(unit, line.number)
|
|
330
|
+
if token is None or token.kind is TokenKind.COMMENT or token.in_directive or unit.in_error(token.offset):
|
|
331
|
+
continue
|
|
332
|
+
yield line, token
|
|
333
|
+
|
|
334
|
+
def run(self, run: CheckRun) -> Iterator[Finding]:
|
|
335
|
+
"""
|
|
336
|
+
Run the check (see class description).
|
|
337
|
+
|
|
338
|
+
Parameters
|
|
339
|
+
----------
|
|
340
|
+
run : CheckRun
|
|
341
|
+
Project context, files and parameters.
|
|
342
|
+
|
|
343
|
+
Returns
|
|
344
|
+
----------
|
|
345
|
+
Iterator[Finding]
|
|
346
|
+
The problems found.
|
|
347
|
+
"""
|
|
348
|
+
mode: str = run.parameters["mode"]
|
|
349
|
+
width: int = run.parameters["unit"]
|
|
350
|
+
for unit in run.units():
|
|
351
|
+
if mode == "tabs":
|
|
352
|
+
for line in unit.source.lines:
|
|
353
|
+
leading: str = _leading(line)
|
|
354
|
+
if "\t" in leading:
|
|
355
|
+
yield Finding(unit.path, line.number, leading.index("\t") + 1, value="tab", node_key=line.number)
|
|
356
|
+
elif mode == "multiple_of":
|
|
357
|
+
for line, token in self._code_lines(unit):
|
|
358
|
+
leading = _leading(line)
|
|
359
|
+
if "\t" not in leading and len(leading) % width:
|
|
360
|
+
yield Finding(unit.path, line.number, 1, value=len(leading), limit=width, node_key=line.number)
|
|
361
|
+
elif mode == "preprocessor":
|
|
362
|
+
for directive in unit.directives:
|
|
363
|
+
leading = _leading(unit.source.line(directive.line))
|
|
364
|
+
expected: int = directive.depth * width
|
|
365
|
+
if leading != " " * expected:
|
|
366
|
+
yield Finding(unit.path, directive.line, 1, name=directive.name, value=len(leading), limit=expected, node_key=directive.line)
|
|
367
|
+
else:
|
|
368
|
+
layout: _Layout = _Layout(unit, width)
|
|
369
|
+
for line, token in self._code_lines(unit):
|
|
370
|
+
leading = _leading(line)
|
|
371
|
+
if "\t" in leading:
|
|
372
|
+
continue
|
|
373
|
+
low, high, exact = layout.expected(token)
|
|
374
|
+
level: float = len(leading) / width
|
|
375
|
+
if (exact and high is not None and not low <= level <= high) or (high is None and level < low) or (exact and high is not None and level != int(level)):
|
|
376
|
+
yield Finding(unit.path, line.number, 1, value=len(leading), limit=low * width, node_key=line.number)
|