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,199 @@
1
+ from sources.analysis.tokens import Token
2
+ from sources.analysis.unit import CUnit
3
+ from sources.enums import TokenKind
4
+
5
+
6
+ # Marker returned when a token is the first code of its line (only indentation before it).
7
+ LINE_START: str = "<line start>"
8
+
9
+ # Marker returned when a token is the last thing on its line (only trailing whitespace after it).
10
+ LINE_END: str = "<line end>"
11
+
12
+ # Marker returned when the neighbour of a token is a comment (separated by the given whitespace).
13
+ BEFORE_COMMENT: str = "<comment>"
14
+
15
+ # Token kinds that end a physical line.
16
+ LINE_BREAK_KINDS: frozenset[TokenKind] = frozenset({TokenKind.NEWLINE, TokenKind.LINE_SPLICE})
17
+
18
+
19
+ def gap_before(unit: CUnit, token: Token) -> str:
20
+ """
21
+ Whitespace between a token and the previous token on the same line.
22
+
23
+ Parameters
24
+ ----------
25
+ unit : CUnit
26
+ File of the token.
27
+ token : Token
28
+ The token.
29
+
30
+ Returns
31
+ ----------
32
+ str
33
+ The whitespace ("" when attached), or LINE_START when nothing but indentation precedes the token.
34
+ """
35
+ tokens: tuple[Token, ...] = unit.tokens
36
+ index: int = token.index - 1
37
+ if index < 0 or tokens[index].kind in LINE_BREAK_KINDS:
38
+ return LINE_START
39
+ if tokens[index].kind is TokenKind.WHITESPACE:
40
+ if index == 0 or tokens[index - 1].kind in LINE_BREAK_KINDS:
41
+ return LINE_START
42
+ return tokens[index].text
43
+ return ""
44
+
45
+
46
+ def gap_after(unit: CUnit, token: Token) -> str:
47
+ """
48
+ Whitespace between a token and the next token on the same line.
49
+
50
+ Parameters
51
+ ----------
52
+ unit : CUnit
53
+ File of the token.
54
+ token : Token
55
+ The token.
56
+
57
+ Returns
58
+ ----------
59
+ str
60
+ The whitespace ("" when attached), LINE_END when nothing but whitespace follows the token on its line,
61
+ or BEFORE_COMMENT when a comment follows (possibly after whitespace).
62
+ """
63
+ tokens: tuple[Token, ...] = unit.tokens
64
+ index: int = token.index + 1
65
+ if index >= len(tokens) or tokens[index].kind in LINE_BREAK_KINDS:
66
+ return LINE_END
67
+ if tokens[index].kind is TokenKind.COMMENT:
68
+ return BEFORE_COMMENT
69
+ if tokens[index].kind is TokenKind.WHITESPACE:
70
+ following: Token | None = tokens[index + 1] if index + 1 < len(tokens) else None
71
+ if following is None or following.kind in LINE_BREAK_KINDS:
72
+ return LINE_END
73
+ if following.kind is TokenKind.COMMENT:
74
+ return BEFORE_COMMENT
75
+ return tokens[index].text
76
+ return ""
77
+
78
+
79
+ def previous_code(unit: CUnit, token: Token) -> Token | None:
80
+ """
81
+ Previous token that is not whitespace, a newline or a line splice.
82
+
83
+ Parameters
84
+ ----------
85
+ unit : CUnit
86
+ File of the token.
87
+ token : Token
88
+ The token.
89
+
90
+ Returns
91
+ ----------
92
+ Token | None
93
+ The token, or None at the start of the file.
94
+ """
95
+ index: int = token.index - 1
96
+ while index >= 0 and unit.tokens[index].kind in (TokenKind.WHITESPACE, TokenKind.NEWLINE, TokenKind.LINE_SPLICE):
97
+ index -= 1
98
+ return unit.tokens[index] if index >= 0 else None
99
+
100
+
101
+ def next_code(unit: CUnit, token: Token) -> Token | None:
102
+ """
103
+ Next token that is not whitespace, a newline or a line splice.
104
+
105
+ Parameters
106
+ ----------
107
+ unit : CUnit
108
+ File of the token.
109
+ token : Token
110
+ The token.
111
+
112
+ Returns
113
+ ----------
114
+ Token | None
115
+ The token, or None at the end of the file.
116
+ """
117
+ index: int = token.index + 1
118
+ while index < len(unit.tokens) and unit.tokens[index].kind in (TokenKind.WHITESPACE, TokenKind.NEWLINE, TokenKind.LINE_SPLICE):
119
+ index += 1
120
+ return unit.tokens[index] if index < len(unit.tokens) else None
121
+
122
+
123
+ def first_code_of_line(unit: CUnit, line: int) -> Token | None:
124
+ """
125
+ First token of a line that is neither whitespace nor a newline.
126
+
127
+ Parameters
128
+ ----------
129
+ unit : CUnit
130
+ The file.
131
+ line : int
132
+ 1-based line.
133
+
134
+ Returns
135
+ ----------
136
+ Token | None
137
+ The token, or None for a blank line.
138
+ """
139
+ for token in line_tokens(unit, line):
140
+ if token.kind not in (TokenKind.WHITESPACE, TokenKind.NEWLINE, TokenKind.LINE_SPLICE):
141
+ return token
142
+ return None
143
+
144
+
145
+ def line_tokens(unit: CUnit, line: int) -> list[Token]:
146
+ """
147
+ Tokens that start on a line, in order.
148
+
149
+ Parameters
150
+ ----------
151
+ unit : CUnit
152
+ The file.
153
+ line : int
154
+ 1-based line.
155
+
156
+ Returns
157
+ ----------
158
+ list[Token]
159
+ The tokens.
160
+ """
161
+ return unit.tokens_on_line(line)
162
+
163
+
164
+ def starts_line(unit: CUnit, token: Token) -> bool:
165
+ """
166
+ Whether a token is the first code of its line.
167
+
168
+ Parameters
169
+ ----------
170
+ unit : CUnit
171
+ File of the token.
172
+ token : Token
173
+ The token.
174
+
175
+ Returns
176
+ ----------
177
+ bool
178
+ True when only indentation precedes it.
179
+ """
180
+ return gap_before(unit, token) == LINE_START
181
+
182
+
183
+ def ends_line(unit: CUnit, token: Token) -> bool:
184
+ """
185
+ Whether a token is the last code of its line (a trailing comment is allowed after it).
186
+
187
+ Parameters
188
+ ----------
189
+ unit : CUnit
190
+ File of the token.
191
+ token : Token
192
+ The token.
193
+
194
+ Returns
195
+ ----------
196
+ bool
197
+ True when only whitespace or a comment follows it on its line.
198
+ """
199
+ return gap_after(unit, token) in (LINE_END, BEFORE_COMMENT)
@@ -0,0 +1,277 @@
1
+ import re
2
+ from collections.abc import Iterator
3
+ from dataclasses import dataclass
4
+ from pathlib import PurePosixPath
5
+ from typing import Any
6
+
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, TokenKind
11
+ from sources.rules.arguments import ArgumentSpec
12
+ from sources.rules.primitives.base import CheckRun, Finding, Primitive
13
+
14
+
15
+ # Classes of names checked by `naming` (each has a `case.<class>` parameter).
16
+ NAME_CLASSES: tuple[str, ...] = (
17
+ "function", "variable", "constant", "parameter", "field", "tag", "typedef", "enumerator", "macro",
18
+ "macro_parameter", "label", "file", "directory",
19
+ )
20
+
21
+
22
+ # Boundaries between the words of a name: underscores, digits, and lower-to-upper case changes.
23
+ WORD_SPLIT_PATTERN: re.Pattern[str] = re.compile(r"_+|(?<=[a-z0-9])(?=[A-Z])|\d+")
24
+
25
+
26
+ def name_words(name: str) -> list[str]:
27
+ """
28
+ Lower-cased words of a name (`get_value`, `getValue` and `GET_VALUE` all give ["get", "value"]).
29
+
30
+ Parameters
31
+ ----------
32
+ name : str
33
+ The name.
34
+
35
+ Returns
36
+ ----------
37
+ list[str]
38
+ The words.
39
+ """
40
+ return [word.lower() for word in WORD_SPLIT_PATTERN.split(name) if word]
41
+
42
+
43
+ @dataclass(frozen=True, slots=True)
44
+ class NamedItem:
45
+ """
46
+ A declared name and where it is declared.
47
+ (dataclass)
48
+
49
+ Attributes
50
+ ----------
51
+ name : str
52
+ The name.
53
+ name_class : str
54
+ Its class (see NAME_CLASSES).
55
+ path : str
56
+ File of the declaration.
57
+ line : int
58
+ 1-based line.
59
+ column : int
60
+ 1-based column.
61
+ """
62
+
63
+ name: str
64
+ name_class: str
65
+ path: str
66
+ line: int
67
+ column: int
68
+
69
+
70
+ def _token_item(token: Token | None, name_class: str, path: str) -> NamedItem | None:
71
+ """
72
+ Named item located on a token.
73
+
74
+ Parameters
75
+ ----------
76
+ token : Token | None
77
+ Name token.
78
+ name_class : str
79
+ Class of the name.
80
+ path : str
81
+ File.
82
+
83
+ Returns
84
+ ----------
85
+ NamedItem | None
86
+ The item, or None without token.
87
+ """
88
+ if token is None:
89
+ return None
90
+ return NamedItem(token.text, name_class, path, token.line, token.column)
91
+
92
+
93
+ def _declarator(node: Node) -> Node:
94
+ """
95
+ Declarator of a declarator or INIT_DECLARATOR node.
96
+
97
+ Parameters
98
+ ----------
99
+ node : Node
100
+ The node.
101
+
102
+ Returns
103
+ ----------
104
+ Node
105
+ The declarator.
106
+ """
107
+ return node.fields["declarator"] if node.kind is NodeKind.INIT_DECLARATOR else node
108
+
109
+
110
+ def _identifiers(unit: CUnit) -> Iterator[NamedItem | None]:
111
+ """
112
+ Every name declared in a C/H file, with its class.
113
+
114
+ Parameters
115
+ ----------
116
+ unit : CUnit
117
+ The file.
118
+
119
+ Returns
120
+ ----------
121
+ Iterator[NamedItem | None]
122
+ The items (None entries are skipped by the caller).
123
+ """
124
+ path: str = unit.path
125
+ for function in unit.functions + unit.prototypes:
126
+ yield _token_item(function.declarator.fields.get("name_token"), "function", path)
127
+ constants: set[int] = {id(variable.node) for variable in unit.variables if variable.is_constant}
128
+ for declaration in unit.nodes(NodeKind.DECLARATION):
129
+ for item in declaration.fields.get("declarators", ()):
130
+ declarator: Node = _declarator(item)
131
+ if declarator.fields.get("declares_function"):
132
+ continue
133
+ yield _token_item(declarator.fields.get("name_token"), "constant" if id(item) in constants else "variable", path)
134
+ for definition in unit.nodes(NodeKind.TYPE_DEFINITION):
135
+ for item in definition.fields.get("declarators", ()):
136
+ yield _token_item(_declarator(item).fields.get("name_token"), "typedef", path)
137
+ for parameter in unit.nodes(NodeKind.PARAMETER):
138
+ yield _token_item(parameter.fields.get("name_token"), "parameter", path)
139
+ for field_declaration in unit.nodes(NodeKind.FIELD_DECLARATION):
140
+ for item in field_declaration.fields.get("declarators", ()):
141
+ yield _token_item(item.fields.get("name_token"), "field", path)
142
+ for record in unit.nodes(NodeKind.STRUCT_SPECIFIER, NodeKind.UNION_SPECIFIER, NodeKind.ENUM_SPECIFIER):
143
+ if record.fields.get("has_body"):
144
+ yield _token_item(record.fields.get("name_token"), "tag", path)
145
+ for enumerator in unit.nodes(NodeKind.ENUMERATOR):
146
+ yield _token_item(enumerator.fields.get("name_token"), "enumerator", path)
147
+ for label in unit.nodes(NodeKind.LABELED_STATEMENT):
148
+ yield _token_item(label.fields.get("name_token"), "label", path)
149
+ for macro in unit.macros:
150
+ yield _token_item(macro.name_token, "macro", path)
151
+ if macro.parameters:
152
+ seen_open: bool = False
153
+ for token in macro.directive.operand_tokens[1:]:
154
+ if token.text == ")":
155
+ break
156
+ if token.text == "(":
157
+ seen_open = True
158
+ elif seen_open and token.kind is TokenKind.IDENTIFIER:
159
+ yield _token_item(token, "macro_parameter", path)
160
+
161
+
162
+ def _paths(run: CheckRun) -> Iterator[NamedItem]:
163
+ """
164
+ File names (without extension) and the directories that contain them, each directory once.
165
+
166
+ Parameters
167
+ ----------
168
+ run : CheckRun
169
+ The check run.
170
+
171
+ Returns
172
+ ----------
173
+ Iterator[NamedItem]
174
+ The items (located at 1:1 of the file).
175
+ """
176
+ seen: set[str] = set()
177
+ for source in run.files:
178
+ path: PurePosixPath = PurePosixPath(source.path)
179
+ for index, part in enumerate(path.parts[:-1]):
180
+ directory: str = "/".join(path.parts[:index + 1])
181
+ if directory not in seen:
182
+ seen.add(directory)
183
+ yield NamedItem(part, "directory", source.path, 1, 1)
184
+ yield NamedItem(path.stem if path.suffix else path.name, "file", source.path, 1, 1)
185
+
186
+
187
+ class Naming(Primitive):
188
+ """
189
+ Names of identifiers or paths. Each class can be given a full-match regular expression
190
+ (`case.<class>`); a word list can be required in the names of some classes (any word of the name, split on `_` and case
191
+ changes, must be in `require_word`, e.g. a verb in function names) and a list of names can be forbidden
192
+ (`forbid_names`, e.g. vague file names).
193
+ (ABC -> Primitive)
194
+
195
+ Attributes
196
+ ----------
197
+ kind : str
198
+ "naming".
199
+ """
200
+
201
+ kind = "naming"
202
+ layer = Layer.SYNTAX
203
+ parameters = (
204
+ *(ArgumentSpec(f"case.{name_class}", ArgumentType.REGEX, description=f"Full-match pattern of {name_class} names.") for name_class in NAME_CLASSES),
205
+ ArgumentSpec("require_word", ArgumentType.WORD_SET, description="Words; a name must contain one of them as an `_`-separated part."),
206
+ ArgumentSpec("require_word_in", ArgumentType.LIST, default=(), item_type=ArgumentType.ENUM, choices=NAME_CLASSES, description="Classes where require_word applies."),
207
+ ArgumentSpec("forbid_names", ArgumentType.WORD_SET, description="Forbidden whole names."),
208
+ ArgumentSpec("forbid_names_in", ArgumentType.LIST, default=(), item_type=ArgumentType.ENUM, choices=NAME_CLASSES, description="Classes where forbid_names applies."),
209
+ ArgumentSpec("exempt", ArgumentType.LIST, default=(), description="Names never checked."),
210
+ )
211
+ targets = ("identifier", "path_component")
212
+ where_keys = frozenset({"name"})
213
+ data_keys = frozenset({"class", "expected"})
214
+ default_message = "{code}: invalid {class} name '{name}'"
215
+
216
+ def _problem(self, item: NamedItem, parameters: dict[str, Any]) -> str | None:
217
+ """
218
+ What is wrong with a name.
219
+
220
+ Parameters
221
+ ----------
222
+ item : NamedItem
223
+ The name.
224
+ parameters : dict[str, Any]
225
+ Bound parameters.
226
+
227
+ Returns
228
+ ----------
229
+ str | None
230
+ Description of the expected form, or None when the name is fine.
231
+ """
232
+ pattern: re.Pattern[str] | None = parameters.get(f"case.{item.name_class}")
233
+ if pattern is not None and pattern.fullmatch(item.name) is None:
234
+ return f"matching {pattern.pattern}"
235
+ words: frozenset[str] | None = parameters.get("require_word")
236
+ if words and item.name_class in parameters["require_word_in"]:
237
+ if not any(part in words for part in name_words(item.name)):
238
+ return "containing a word of the list"
239
+ forbidden: frozenset[str] | None = parameters.get("forbid_names")
240
+ if forbidden and item.name_class in parameters["forbid_names_in"] and item.name.lower() in forbidden:
241
+ return "more explicit"
242
+ return None
243
+
244
+ def run(self, run: CheckRun) -> Iterator[Finding]:
245
+ """
246
+ Run the check (see class description).
247
+
248
+ Parameters
249
+ ----------
250
+ run : CheckRun
251
+ Project context, files and parameters.
252
+
253
+ Returns
254
+ ----------
255
+ Iterator[Finding]
256
+ The problems found.
257
+ """
258
+ parameters: dict[str, Any] = dict(run.parameters)
259
+ exempt: frozenset[str] = frozenset(parameters["exempt"])
260
+ items: list[NamedItem] = []
261
+ if (run.selection.target or self.targets[0]) == "path_component":
262
+ items.extend(_paths(run))
263
+ else:
264
+ for unit in run.units():
265
+ items.extend(item for item in _identifiers(unit) if item is not None)
266
+ seen: set[tuple[str, int, int, str]] = set()
267
+ for item in sorted(items, key=lambda entry: (entry.path, entry.line, entry.column)):
268
+ key: tuple[str, int, int, str] = (item.path, item.line, item.column, item.name_class)
269
+ if key in seen or item.name in exempt or not run.selection.name_matches(item.name):
270
+ continue
271
+ seen.add(key)
272
+ problem: str | None = self._problem(item, parameters)
273
+ if problem is not None:
274
+ yield Finding(
275
+ item.path, item.line, item.column, item.line, item.column + len(item.name),
276
+ name=item.name, value=item.name, node_key=key, data={"class": item.name_class.replace("_", " "), "expected": problem},
277
+ )
@@ -0,0 +1,62 @@
1
+ from collections.abc import Iterator
2
+
3
+ from sources.analysis.tokens import Token
4
+ from sources.enums import ArgumentType, FileKind, Layer
5
+ from sources.rules.arguments import ArgumentSpec
6
+ from sources.rules.primitives.base import CheckRun, Finding, Primitive
7
+
8
+
9
+ class SymbolLinkage(Primitive):
10
+ """
11
+ Report non-`static` functions and file-scope variables defined in a `.c` file and used by no other file
12
+ of the project (they could be `static`). Uses the project context (cross-file references).
13
+ (ABC -> Primitive)
14
+
15
+ Attributes
16
+ ----------
17
+ kind : str
18
+ "symbol_linkage".
19
+ """
20
+
21
+ kind = "symbol_linkage"
22
+ layer = Layer.PROJECT
23
+ parameters = (
24
+ ArgumentSpec("symbol_kinds", ArgumentType.LIST, default=("function", "variable"), item_type=ArgumentType.ENUM, choices=("function", "variable"), description="Kinds of symbols checked."),
25
+ ArgumentSpec("exempt", ArgumentType.LIST, default=(), description="Names that never need to be static."),
26
+ )
27
+ where_keys = frozenset({"name"})
28
+ default_message = "{code}: '{name}' is not used outside {path}; make it static"
29
+
30
+ def run(self, run: CheckRun) -> Iterator[Finding]:
31
+ """
32
+ Run the check (see class description).
33
+
34
+ Parameters
35
+ ----------
36
+ run : CheckRun
37
+ Project context, files and parameters.
38
+
39
+ Returns
40
+ ----------
41
+ Iterator[Finding]
42
+ The problems found.
43
+ """
44
+ kinds: tuple[str, ...] = run.parameters["symbol_kinds"]
45
+ exempt: frozenset[str] = frozenset(run.parameters["exempt"])
46
+ for unit in run.units():
47
+ if unit.source.kind is not FileKind.C:
48
+ continue
49
+ candidates: list[tuple[str, Token | None]] = []
50
+ if "function" in kinds:
51
+ candidates.extend((function.name, function.declarator.fields.get("name_token")) for function in unit.functions if not function.is_static)
52
+ if "variable" in kinds:
53
+ candidates.extend(
54
+ (variable.name, variable.node.fields.get("name_token") or variable.node.fields["declarator"].fields.get("name_token"))
55
+ for variable in unit.variables
56
+ if not variable.local and variable.is_definition and "static" not in variable.storage
57
+ )
58
+ for name, token in candidates:
59
+ if name in exempt or token is None or not run.selection.name_matches(name):
60
+ continue
61
+ if not run.project.is_used_outside(name, unit.path):
62
+ yield Finding(unit.path, token.line, token.column, token.end_line, token.end_column, name=name, value=name)
@@ -0,0 +1,49 @@
1
+ from types import MappingProxyType
2
+
3
+ from sources.rules.primitives.base import Primitive
4
+ from sources.rules.primitives.braces import BracePlacement
5
+ from sources.rules.primitives.directives import DirectiveCheck, IncludeGuard
6
+ from sources.rules.primitives.indentation import Indentation
7
+ from sources.rules.primitives.naming import Naming
8
+ from sources.rules.primitives.project import SymbolLinkage
9
+ from sources.rules.primitives.repository import ContentSniff, PathPattern
10
+ from sources.rules.primitives.review import ManualReview
11
+ from sources.rules.primitives.semantic import ConstCorrectness, LiteralUsage, TypeAccuracy
12
+ from sources.rules.primitives.spacing import Spacing
13
+ from sources.rules.primitives.structure import GlobalMutability, NestingDepth, NodeForbid, TopLevelItems
14
+ from sources.rules.primitives.syntax import NodeMetric
15
+ from sources.rules.primitives.text import BlankLines, LineMetric, TextRegex
16
+ from sources.rules.primitives.tokens import TokenForbid
17
+
18
+
19
+ # Check kinds reserved for Python code (plan 03, section 7.3); not supported yet.
20
+ RESERVED_KINDS: frozenset[str] = frozenset({"python", "plugin"})
21
+
22
+ # Every available primitive, by `kind` (one stateless instance each).
23
+ PRIMITIVES: MappingProxyType[str, Primitive] = MappingProxyType({
24
+ primitive.kind: primitive
25
+ for primitive in (
26
+ TextRegex(),
27
+ LineMetric(),
28
+ BlankLines(),
29
+ TokenForbid(),
30
+ NodeMetric(),
31
+ ManualReview(),
32
+ SymbolLinkage(),
33
+ PathPattern(),
34
+ ContentSniff(),
35
+ DirectiveCheck(),
36
+ IncludeGuard(),
37
+ NodeForbid(),
38
+ NestingDepth(),
39
+ TopLevelItems(),
40
+ GlobalMutability(),
41
+ Spacing(),
42
+ BracePlacement(),
43
+ Indentation(),
44
+ Naming(),
45
+ LiteralUsage(),
46
+ ConstCorrectness(),
47
+ TypeAccuracy(),
48
+ )
49
+ })