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,129 @@
1
+ import re
2
+ from collections.abc import Iterator
3
+
4
+ from sources.analysis.source import SourceFile
5
+ from sources.enums import ArgumentType, Layer
6
+ from sources.rules.arguments import ArgumentSpec
7
+ from sources.rules.primitives.base import CheckRun, Finding, Primitive
8
+ from sources.utils.globs import match_glob
9
+
10
+
11
+ # Magic numbers of compiled binaries, by format name.
12
+ BINARY_MAGICS: dict[str, tuple[bytes, ...]] = {
13
+ "elf": (b"\x7fELF",),
14
+ "mach_o": (b"\xfe\xed\xfa\xce", b"\xfe\xed\xfa\xcf", b"\xce\xfa\xed\xfe", b"\xcf\xfa\xed\xfe", b"\xca\xfe\xba\xbe"),
15
+ "pe": (b"MZ",),
16
+ "archive": (b"!<arch>\n",),
17
+ }
18
+
19
+ # Lines that only C code contains (preprocessor include, or a function definition header followed by a brace).
20
+ C_SOURCE_PATTERN: re.Pattern[str] = re.compile(
21
+ r"^[ \t]*#[ \t]*include[ \t]*[<\"]|^[A-Za-z_][\w \t\*]*\b[A-Za-z_]\w*[ \t]*\([^;{}]*\)[ \t]*\n?\{",
22
+ re.MULTILINE,
23
+ )
24
+
25
+
26
+ class PathPattern(Primitive):
27
+ """
28
+ Forbid repository files whose path matches one of a list of globs (a glob without `/` matches the file
29
+ name anywhere in the tree).
30
+ (ABC -> Primitive)
31
+
32
+ Attributes
33
+ ----------
34
+ kind : str
35
+ "path_pattern".
36
+ """
37
+
38
+ kind = "path_pattern"
39
+ layer = Layer.REPOSITORY
40
+ parameters = (
41
+ ArgumentSpec("patterns", ArgumentType.LIST, required=True, item_type=ArgumentType.GLOB, description="Forbidden path globs."),
42
+ )
43
+ where_keys = frozenset({"name"})
44
+ default_message = "{code}: '{path}' must not be in the repository"
45
+
46
+ def run(self, run: CheckRun) -> Iterator[Finding]:
47
+ """
48
+ Run the check (see class description).
49
+
50
+ Parameters
51
+ ----------
52
+ run : CheckRun
53
+ Project context, files and parameters.
54
+
55
+ Returns
56
+ ----------
57
+ Iterator[Finding]
58
+ The problems found.
59
+ """
60
+ for source in run.files:
61
+ matched: list[str] = [pattern for pattern in run.parameters["patterns"] if match_glob(source.path, pattern)]
62
+ if matched and run.selection.name_matches(source.path):
63
+ yield Finding(source.path, 1, 1, name=source.path, value=matched[0], node_key=source.path)
64
+
65
+
66
+ def sniff_format(source: SourceFile) -> str | None:
67
+ """
68
+ Recognise the content of a file: compiled binary formats, or C source code.
69
+
70
+ Parameters
71
+ ----------
72
+ source : SourceFile
73
+ The file.
74
+
75
+ Returns
76
+ ----------
77
+ str | None
78
+ "elf", "mach_o", "pe", "archive", "c_source", or None.
79
+ """
80
+ for name, magics in BINARY_MAGICS.items():
81
+ if source.raw.startswith(magics):
82
+ if name != "pe" or source.binary:
83
+ return name
84
+ if not source.binary and source.text and C_SOURCE_PATTERN.search(source.text):
85
+ return "c_source"
86
+ return None
87
+
88
+
89
+ class ContentSniff(Primitive):
90
+ """
91
+ Forbid files whose content has one of the given formats (compiled binaries, or C code in a file that
92
+ does not have a C extension).
93
+ (ABC -> Primitive)
94
+
95
+ Attributes
96
+ ----------
97
+ kind : str
98
+ "content_sniff".
99
+ """
100
+
101
+ kind = "content_sniff"
102
+ layer = Layer.REPOSITORY
103
+ parameters = (
104
+ ArgumentSpec("formats", ArgumentType.LIST, required=True, item_type=ArgumentType.ENUM, choices=("elf", "mach_o", "pe", "archive", "c_source"), description="Forbidden content formats."),
105
+ )
106
+ where_keys = frozenset({"name"})
107
+ default_message = "{code}: '{path}' contains {value} content"
108
+
109
+ def run(self, run: CheckRun) -> Iterator[Finding]:
110
+ """
111
+ Run the check (see class description).
112
+
113
+ Parameters
114
+ ----------
115
+ run : CheckRun
116
+ Project context, files and parameters.
117
+
118
+ Returns
119
+ ----------
120
+ Iterator[Finding]
121
+ The problems found.
122
+ """
123
+ formats: frozenset[str] = frozenset(run.parameters["formats"])
124
+ for source in run.files:
125
+ if source.skipped is not None or not run.selection.name_matches(source.path):
126
+ continue
127
+ found: str | None = sniff_format(source)
128
+ if found in formats:
129
+ yield Finding(source.path, 1, 1, name=source.path, value=found, node_key=source.path)
@@ -0,0 +1,87 @@
1
+ from collections.abc import Iterator
2
+
3
+ from sources.analysis.syntax import Node
4
+ from sources.enums import ArgumentType, Layer, NodeKind
5
+ from sources.rules.arguments import ArgumentSpec
6
+ from sources.rules.primitives.base import CheckRun, Finding, Primitive, node_finding
7
+
8
+
9
+ def _typedef_name(node: Node) -> str:
10
+ """
11
+ Name of an anonymous struct/union: the first name declared with it (`typedef struct {...} point_t;`).
12
+
13
+ Parameters
14
+ ----------
15
+ node : Node
16
+ A struct or union specifier.
17
+
18
+ Returns
19
+ ----------
20
+ str
21
+ The name, or "<anonymous>".
22
+ """
23
+ parent: Node | None = node.parent
24
+ if parent is not None and parent.kind in (NodeKind.TYPE_DEFINITION, NodeKind.DECLARATION, NodeKind.FIELD_DECLARATION):
25
+ for item in parent.fields.get("declarators", ()):
26
+ if item.name:
27
+ return item.name
28
+ return "<anonymous>"
29
+
30
+
31
+ class ManualReview(Primitive):
32
+ """
33
+ Emit one review item per target, carrying a question for the human reviewer. Review items never count
34
+ toward failure (plan 03, RULE-13).
35
+ (ABC -> Primitive)
36
+
37
+ Attributes
38
+ ----------
39
+ kind : str
40
+ "manual_review".
41
+ """
42
+
43
+ kind = "manual_review"
44
+ layer = Layer.SYNTAX
45
+ parameters = (
46
+ ArgumentSpec("question", ArgumentType.STR, default="Does this follow the rule?", description="Question shown to the reviewer; {name} is replaced by the item name."),
47
+ ArgumentSpec("variadic_only", ArgumentType.BOOL, default=False, description="Only variadic functions (function targets)."),
48
+ )
49
+ targets = ("file", "function_definition", "function_declarator", "struct_definition")
50
+ where_keys = frozenset({"name", "storage", "context", "not_context"})
51
+ data_keys = frozenset({"question"})
52
+ default_message = "{code}: {question}"
53
+
54
+ def run(self, run: CheckRun) -> Iterator[Finding]:
55
+ """
56
+ Run the check (see class description).
57
+
58
+ Parameters
59
+ ----------
60
+ run : CheckRun
61
+ Project context, files and parameters.
62
+
63
+ Returns
64
+ ----------
65
+ Iterator[Finding]
66
+ The review items.
67
+ """
68
+ target: str = run.selection.target or self.targets[0]
69
+ question: str = run.parameters["question"]
70
+ if target == "file":
71
+ for source in run.files:
72
+ if run.selection.name_matches(source.path):
73
+ yield Finding(source.path, 1, 1, name=source.path, review=True, node_key=source.path, data={"question": question.replace("{name}", source.path)})
74
+ return
75
+ for unit in run.units():
76
+ items: list[tuple[Node, frozenset[str]]]
77
+ variadic_only: bool = run.parameters["variadic_only"]
78
+ if target == "function_definition":
79
+ items = [(function.node, function.storage) for function in unit.functions if function.variadic or not variadic_only]
80
+ elif target == "function_declarator":
81
+ items = [(function.declarator, function.storage) for function in unit.functions + unit.prototypes if function.variadic or not variadic_only]
82
+ else:
83
+ items = [(node, frozenset()) for node in unit.nodes(NodeKind.STRUCT_SPECIFIER, NodeKind.UNION_SPECIFIER) if node.fields["has_body"]]
84
+ for node, storage in sorted(items, key=lambda pair: pair[0].start_offset):
85
+ if run.node_selected(unit, node, storage):
86
+ name: str = node.name or _typedef_name(node)
87
+ yield node_finding(unit.path, node, review=True, data={"question": question.replace("{name}", name)})
@@ -0,0 +1,319 @@
1
+ import re
2
+ from collections.abc import Iterator
3
+
4
+ from sources.analysis.project import ProjectContext
5
+ from sources.analysis.syntax import Node
6
+ from sources.analysis.tokens import Token
7
+ from sources.analysis.unit import CUnit, FunctionInfo, ParameterInfo
8
+ from sources.enums import ArgumentType, Layer, NodeKind
9
+ from sources.rules.arguments import ArgumentSpec
10
+ from sources.rules.primitives.base import CheckRun, Finding, Primitive, node_finding
11
+
12
+
13
+ # Assignment-like parents: the node is written when it is their left operand.
14
+ WRITE_PARENTS: frozenset[NodeKind] = frozenset({NodeKind.ASSIGNMENT_EXPRESSION})
15
+
16
+ # Nodes that keep designating the same object as their first child (`p->f`, `p[i]`, `(p)`).
17
+ ACCESS_KINDS: frozenset[NodeKind] = frozenset({NodeKind.MEMBER_EXPRESSION, NodeKind.SUBSCRIPT_EXPRESSION, NodeKind.PARENTHESIZED_EXPRESSION})
18
+
19
+ # Comparison operators: reading a pointer to compare it never modifies the data.
20
+ COMPARISONS: frozenset[str] = frozenset({"==", "!=", "<", ">", "<=", ">=", "&&", "||"})
21
+
22
+ # Basic integer types that a more accurate type usually replaces (C-A2 hints).
23
+ PLAIN_INTEGER_TYPES: frozenset[str] = frozenset({"int", "unsigned int", "unsigned", "long", "unsigned long", "short"})
24
+
25
+ # Names that hold a size or a length (C-A2 hint: size_t).
26
+ SIZE_NAME_PATTERN: re.Pattern[str] = re.compile(r"(?:^|_)(?:size|len|length)(?:$|_)")
27
+
28
+ # Calls returning a size (C-A2 hint: size_t).
29
+ SIZE_CALLS: frozenset[str] = frozenset({"strlen", "my_strlen", "sizeof"})
30
+
31
+
32
+ def _number_value(node: Node) -> str:
33
+ """
34
+ Text of a number literal, with a leading minus when it is negated.
35
+
36
+ Parameters
37
+ ----------
38
+ node : Node
39
+ A NUMBER_LITERAL node.
40
+
41
+ Returns
42
+ ----------
43
+ str
44
+ The value as written, e.g. "-1".
45
+ """
46
+ parent: Node | None = node.parent
47
+ if parent is not None and parent.kind is NodeKind.UNARY_EXPRESSION and parent.fields["operator"] == "-":
48
+ return "-" + node.fields["value"]
49
+ return node.fields["value"]
50
+
51
+
52
+ class LiteralUsage(Primitive):
53
+ """
54
+ Number literals written inside function bodies that are not in an allowlist of trivial values (they
55
+ should be named constants or macros).
56
+ (ABC -> Primitive)
57
+
58
+ Attributes
59
+ ----------
60
+ kind : str
61
+ "literal_usage".
62
+ """
63
+
64
+ kind = "literal_usage"
65
+ layer = Layer.SYNTAX
66
+ parameters = (
67
+ ArgumentSpec("allowed", ArgumentType.LIST, default=("0", "1"), description="Trivial values allowed anywhere."),
68
+ )
69
+ default_message = "{code}: '{value}' should be a named constant"
70
+
71
+ def run(self, run: CheckRun) -> Iterator[Finding]:
72
+ """
73
+ Run the check (see class description).
74
+
75
+ Parameters
76
+ ----------
77
+ run : CheckRun
78
+ Project context, files and parameters.
79
+
80
+ Returns
81
+ ----------
82
+ Iterator[Finding]
83
+ The problems found.
84
+ """
85
+ allowed: frozenset[str] = frozenset(run.parameters["allowed"])
86
+ for unit in run.units():
87
+ for literal in unit.nodes(NodeKind.NUMBER_LITERAL):
88
+ if literal.nearest(NodeKind.FUNCTION_DEFINITION) is None:
89
+ continue
90
+ value: str = _number_value(literal)
91
+ if value not in allowed and value.lower().rstrip("ul") not in allowed:
92
+ yield node_finding(unit.path, literal, name=value, value=value)
93
+
94
+
95
+ def _is_written(reference: Node) -> bool:
96
+ """
97
+ Whether the data a pointer points to is modified through this use (`*p = `, `p[i]++`, `p->f = `...).
98
+
99
+ Parameters
100
+ ----------
101
+ reference : Node
102
+ IDENTIFIER node naming the pointer.
103
+
104
+ Returns
105
+ ----------
106
+ bool
107
+ True when the pointed data may be written.
108
+ """
109
+ node: Node = reference
110
+ dereferenced: bool = False
111
+ while node.parent is not None:
112
+ parent: Node = node.parent
113
+ if parent.kind in ACCESS_KINDS and parent.children[0] is node:
114
+ dereferenced = dereferenced or parent.kind is not NodeKind.PARENTHESIZED_EXPRESSION
115
+ node = parent
116
+ continue
117
+ if parent.kind is NodeKind.UNARY_EXPRESSION and parent.fields["operator"] == "*":
118
+ dereferenced = True
119
+ node = parent
120
+ continue
121
+ break
122
+ parent = node.parent # type: ignore[assignment]
123
+ if parent is None:
124
+ return False
125
+ if not dereferenced:
126
+ return False
127
+ if parent.kind in WRITE_PARENTS and parent.fields["left"] is node:
128
+ return True
129
+ if parent.kind is NodeKind.UPDATE_EXPRESSION:
130
+ return True
131
+ return parent.kind is NodeKind.UNARY_EXPRESSION and parent.fields["operator"] == "&"
132
+
133
+
134
+ def _escapes(reference: Node, project: ProjectContext) -> bool:
135
+ """
136
+ Whether the pointer itself leaves the function in a way that may modify its data: passed to a function
137
+ that does not take a const pointer at that position, returned, stored, or used in arithmetic.
138
+
139
+ Parameters
140
+ ----------
141
+ reference : Node
142
+ IDENTIFIER node naming the pointer.
143
+ project : ProjectContext
144
+ Project context (prototypes of project functions).
145
+
146
+ Returns
147
+ ----------
148
+ bool
149
+ True when the pointer escapes.
150
+ """
151
+ node: Node = reference
152
+ while node.parent is not None and node.parent.kind in (NodeKind.PARENTHESIZED_EXPRESSION, NodeKind.CAST_EXPRESSION):
153
+ node = node.parent
154
+ parent: Node | None = node.parent
155
+ if parent is None:
156
+ return False
157
+ if parent.kind is NodeKind.CALL_EXPRESSION and parent.fields["function"] is not node:
158
+ callee: str | None = parent.name
159
+ position: int = list(parent.fields["arguments"]).index(node)
160
+ candidates: tuple[FunctionInfo, ...] = project.function_prototypes.get(callee or "", ()) + project.function_definitions.get(callee or "", ())
161
+ for function in candidates:
162
+ if position < len(function.parameters):
163
+ parameter: ParameterInfo = function.parameters[position]
164
+ if parameter.pointer_depth == 1 and "const" in parameter.node.fields["qualifiers"]:
165
+ return False
166
+ return True
167
+ if parent.kind in (NodeKind.RETURN_STATEMENT, NodeKind.INIT_DECLARATOR, NodeKind.INITIALIZER_LIST):
168
+ return True
169
+ if parent.kind is NodeKind.ASSIGNMENT_EXPRESSION:
170
+ return parent.fields["right"] is node
171
+ if parent.kind is NodeKind.BINARY_EXPRESSION:
172
+ return parent.fields["operator"] not in COMPARISONS
173
+ if parent.kind is NodeKind.CONDITIONAL_EXPRESSION:
174
+ return parent.fields["condition"] is not node
175
+ return False
176
+
177
+
178
+ class ConstCorrectness(Primitive):
179
+ """
180
+ Pointer parameters of function definitions whose pointed data is never modified by the function (nor
181
+ handed to code that may modify it) but is not declared `const`.
182
+ (ABC -> Primitive)
183
+
184
+ Attributes
185
+ ----------
186
+ kind : str
187
+ "const_correctness".
188
+ """
189
+
190
+ kind = "const_correctness"
191
+ layer = Layer.PROJECT
192
+ where_keys = frozenset({"name"})
193
+ default_message = "{code}: the data pointed by '{name}' is never modified; make it const"
194
+
195
+ def run(self, run: CheckRun) -> Iterator[Finding]:
196
+ """
197
+ Run the check (see class description).
198
+
199
+ Parameters
200
+ ----------
201
+ run : CheckRun
202
+ Project context, files and parameters.
203
+
204
+ Returns
205
+ ----------
206
+ Iterator[Finding]
207
+ The problems found.
208
+ """
209
+ for unit in run.units():
210
+ for function in unit.functions:
211
+ body: Node | None = function.body
212
+ if body is None:
213
+ continue
214
+ for parameter in function.parameters:
215
+ if parameter.name is None or parameter.pointer_depth != 1 or "const" in parameter.node.fields["qualifiers"]:
216
+ continue
217
+ if not run.selection.name_matches(parameter.name):
218
+ continue
219
+ uses: list[Node] = [node for node in body.descendants(NodeKind.IDENTIFIER) if node.name == parameter.name]
220
+ if not uses or any(_is_written(use) or _escapes(use, run.project) for use in uses):
221
+ continue
222
+ token: Token | None = parameter.node.fields.get("name_token")
223
+ if token is not None:
224
+ yield Finding(unit.path, token.line, token.column, token.end_line, token.end_column, name=parameter.name, node_key=id(parameter.node))
225
+
226
+
227
+ def _type_text(specifiers: object) -> str:
228
+ """
229
+ Basic type of declaration specifiers, e.g. "unsigned int".
230
+
231
+ Parameters
232
+ ----------
233
+ specifiers : object
234
+ Specifiers of a declaration (parser Specifiers).
235
+
236
+ Returns
237
+ ----------
238
+ str
239
+ The type words joined by spaces.
240
+ """
241
+ return " ".join(getattr(specifiers, "type_words", ()))
242
+
243
+
244
+ class TypeAccuracy(Primitive):
245
+ """
246
+ Hints that a more accurate type fits: plain integer types used for names that hold a size or a length,
247
+ or initialised from a size (strlen, sizeof).
248
+ (ABC -> Primitive)
249
+
250
+ Attributes
251
+ ----------
252
+ kind : str
253
+ "type_accuracy".
254
+ """
255
+
256
+ kind = "type_accuracy"
257
+ layer = Layer.SYNTAX
258
+ where_keys = frozenset({"name"})
259
+ data_keys = frozenset({"type"})
260
+ default_message = "{code}: '{name}' ({type}) could use a more accurate type such as size_t"
261
+
262
+ def _hints(self, unit: CUnit) -> Iterator[tuple[Token, str]]:
263
+ """
264
+ Names declared with a plain integer type that hold a size.
265
+
266
+ Parameters
267
+ ----------
268
+ unit : CUnit
269
+ The file.
270
+
271
+ Returns
272
+ ----------
273
+ Iterator[tuple[Token, str]]
274
+ (name token, declared type) pairs.
275
+ """
276
+ for function in unit.functions:
277
+ words: str = _type_text(function.node.fields["specifiers"])
278
+ token: Token | None = function.declarator.fields.get("name_token")
279
+ if token is not None and words in PLAIN_INTEGER_TYPES and SIZE_NAME_PATTERN.search(token.text) and not function.declarator.fields["pointer_depth"]:
280
+ yield token, words
281
+ for declaration in unit.nodes(NodeKind.DECLARATION):
282
+ words = _type_text(declaration.fields["specifiers"]) if "specifiers" in declaration.fields else ""
283
+ if words not in PLAIN_INTEGER_TYPES:
284
+ continue
285
+ for item in declaration.fields.get("declarators", ()):
286
+ declarator: Node = item.fields["declarator"] if item.kind is NodeKind.INIT_DECLARATOR else item
287
+ token = declarator.fields.get("name_token")
288
+ if token is None or declarator.fields.get("declares_function") or declarator.fields.get("pointer_depth"):
289
+ continue
290
+ value: Node | None = item.fields.get("value") if item.kind is NodeKind.INIT_DECLARATOR else None
291
+ from_size: bool = value is not None and (
292
+ value.kind is NodeKind.SIZEOF_EXPRESSION or (value.kind is NodeKind.CALL_EXPRESSION and value.name in SIZE_CALLS)
293
+ )
294
+ if SIZE_NAME_PATTERN.search(token.text) or from_size:
295
+ yield token, words
296
+ for parameter in unit.nodes(NodeKind.PARAMETER):
297
+ words = _type_text(parameter.fields["specifiers"])
298
+ token = parameter.fields.get("name_token")
299
+ if token is not None and words in PLAIN_INTEGER_TYPES and not parameter.fields["pointer_depth"] and SIZE_NAME_PATTERN.search(token.text):
300
+ yield token, words
301
+
302
+ def run(self, run: CheckRun) -> Iterator[Finding]:
303
+ """
304
+ Run the check (see class description).
305
+
306
+ Parameters
307
+ ----------
308
+ run : CheckRun
309
+ Project context, files and parameters.
310
+
311
+ Returns
312
+ ----------
313
+ Iterator[Finding]
314
+ The problems found.
315
+ """
316
+ for unit in run.units():
317
+ for token, words in self._hints(unit):
318
+ if run.selection.name_matches(token.text):
319
+ yield Finding(unit.path, token.line, token.column, token.end_line, token.end_column, name=token.text, node_key=token.index, data={"type": words})