ai-editor-tree-engine-dev 1.0.176__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.
- ai_editor_tree_engine_dev-1.0.176.dist-info/METADATA +35 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/RECORD +121 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/WHEEL +5 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/licenses/LICENSE +21 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/top_level.txt +1 -0
- tree_engine/PUBLIC_API.md +161 -0
- tree_engine/__init__.py +327 -0
- tree_engine/checks/__init__.py +60 -0
- tree_engine/checks/builtin/__init__.py +5 -0
- tree_engine/checks/builtin/compile_check.py +53 -0
- tree_engine/checks/builtin/csv_syntax.py +51 -0
- tree_engine/checks/builtin/docstrings.py +211 -0
- tree_engine/checks/builtin/encoding.py +55 -0
- tree_engine/checks/builtin/fleet_rules.py +227 -0
- tree_engine/checks/builtin/format_syntax.py +82 -0
- tree_engine/checks/builtin/jsonl_syntax.py +49 -0
- tree_engine/checks/builtin/shipped.py +52 -0
- tree_engine/checks/builtin/syntax.py +118 -0
- tree_engine/checks/builtin/xml_wellformed.py +51 -0
- tree_engine/checks/chain.py +332 -0
- tree_engine/checks/external/__init__.py +5 -0
- tree_engine/checks/external/_base.py +61 -0
- tree_engine/checks/external/bandit.py +53 -0
- tree_engine/checks/external/black.py +48 -0
- tree_engine/checks/external/flake8.py +38 -0
- tree_engine/checks/external/isort.py +38 -0
- tree_engine/checks/external/mypy.py +45 -0
- tree_engine/checks/external/ruff.py +45 -0
- tree_engine/checks/external/runner.py +197 -0
- tree_engine/checks/model.py +110 -0
- tree_engine/checks/options.py +73 -0
- tree_engine/checks/plugin.py +171 -0
- tree_engine/checks/registry.py +349 -0
- tree_engine/core/address.py +376 -0
- tree_engine/core/identifier_map.py +266 -0
- tree_engine/core/identity.py +226 -0
- tree_engine/core/instrumentation.py +399 -0
- tree_engine/core/integrity.py +341 -0
- tree_engine/core/integrity_full.py +382 -0
- tree_engine/core/journal.py +260 -0
- tree_engine/core/journal_compose.py +571 -0
- tree_engine/core/live_tree.py +785 -0
- tree_engine/core/locking.py +188 -0
- tree_engine/core/move.py +585 -0
- tree_engine/core/move_references.py +323 -0
- tree_engine/core/node_types.py +408 -0
- tree_engine/core/nodes.py +348 -0
- tree_engine/core/offsets.py +24 -0
- tree_engine/core/operations.py +825 -0
- tree_engine/core/plugin_boundary.py +160 -0
- tree_engine/core/position_map.py +263 -0
- tree_engine/core/position_transfer.py +512 -0
- tree_engine/core/range_refresh.py +366 -0
- tree_engine/core/reference_cache.py +360 -0
- tree_engine/core/references.py +223 -0
- tree_engine/core/reparse.py +378 -0
- tree_engine/core/short_id.py +296 -0
- tree_engine/core/subtree_apply.py +397 -0
- tree_engine/core/subtree_copy.py +399 -0
- tree_engine/core/transactions.py +397 -0
- tree_engine/core/trivia.py +396 -0
- tree_engine/core/updates.py +398 -0
- tree_engine/core/validation.py +377 -0
- tree_engine/errors.py +104 -0
- tree_engine/exceptions.py +376 -0
- tree_engine/facade.py +4524 -0
- tree_engine/plugins/_statements.py +369 -0
- tree_engine/plugins/bsl/block_edit.py +449 -0
- tree_engine/plugins/bsl/blocks.py +127 -0
- tree_engine/plugins/bsl/checker.py +297 -0
- tree_engine/plugins/bsl/dialects.py +303 -0
- tree_engine/plugins/bsl/generator.py +481 -0
- tree_engine/plugins/bsl/import_map.py +995 -0
- tree_engine/plugins/bsl/plugin.py +452 -0
- tree_engine/plugins/contract.py +355 -0
- tree_engine/plugins/cpp/import_map.py +505 -0
- tree_engine/plugins/cpp/languages.py +99 -0
- tree_engine/plugins/cpp/plugin.py +501 -0
- tree_engine/plugins/csv_format.py +676 -0
- tree_engine/plugins/detachable.py +156 -0
- tree_engine/plugins/fallback.py +421 -0
- tree_engine/plugins/ini_format.py +330 -0
- tree_engine/plugins/json_format.py +813 -0
- tree_engine/plugins/json_pointer.py +203 -0
- tree_engine/plugins/jsonl_format.py +392 -0
- tree_engine/plugins/markdown_format.py +748 -0
- tree_engine/plugins/onec_query_format.py +61 -0
- tree_engine/plugins/parse_position.py +54 -0
- tree_engine/plugins/plain_text.py +1543 -0
- tree_engine/plugins/python/export_map.py +306 -0
- tree_engine/plugins/python/import_map.py +429 -0
- tree_engine/plugins/python/plugin.py +1710 -0
- tree_engine/plugins/registry.py +497 -0
- tree_engine/plugins/scan.py +87 -0
- tree_engine/plugins/selection.py +228 -0
- tree_engine/plugins/sql_format.py +61 -0
- tree_engine/plugins/toml_format.py +1072 -0
- tree_engine/plugins/xml_format.py +911 -0
- tree_engine/plugins/yaml/builder.py +49 -0
- tree_engine/plugins/yaml/emitter.py +225 -0
- tree_engine/plugins/yaml/flow.py +227 -0
- tree_engine/plugins/yaml/plugin.py +458 -0
- tree_engine/plugins/yaml/ranges.py +52 -0
- tree_engine/plugins/yaml/reader.py +359 -0
- tree_engine/plugins/yaml/scanner.py +298 -0
- tree_engine/query/adapter.py +283 -0
- tree_engine/query/engine.py +853 -0
- tree_engine/query/inspection.py +498 -0
- tree_engine/query/outline.py +288 -0
- tree_engine/query/predicates.py +263 -0
- tree_engine/query/rendered_lines.py +46 -0
- tree_engine/query/results.py +206 -0
- tree_engine/query/selector.py +400 -0
- tree_engine/query/xml_query.py +747 -0
- tree_engine/storage/codec.py +400 -0
- tree_engine/storage/document_bridge.py +579 -0
- tree_engine/storage/file_txn.py +459 -0
- tree_engine/storage/history.py +106 -0
- tree_engine/storage/lifecycle.py +622 -0
- tree_engine/storage/schema.py +403 -0
- tree_engine/storage/session_guard.py +398 -0
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
"""The ``docstrings`` builtin checker: docstring policy B (TODO 15a86bcb, group G5, decision D-BQ).
|
|
2
|
+
|
|
3
|
+
Author: Vasiliy Zdanovskiy
|
|
4
|
+
email: vasilyvz@gmail.com
|
|
5
|
+
|
|
6
|
+
Codes: DOC000 syntax error (the only finding when the module does not parse), DOC001 module docstring
|
|
7
|
+
missing or empty, DOC010 function docstring missing, DOC011 class docstring missing (its methods are then
|
|
8
|
+
not checked), DOC020 parameter not described, DOC021 return annotation without a return description,
|
|
9
|
+
DOC030 parameter without annotation, DOC031 missing return annotation, DOC040 class attribute not
|
|
10
|
+
described. Every kind of parameter is checked (positional-only, regular, ``*args``, keyword-only,
|
|
11
|
+
``**kwargs``). Findings are sorted by ``(line, column, code)`` and have severity ``error``.
|
|
12
|
+
|
|
13
|
+
Differences from the Code Analysis Server rule set this was ported from: a bare ``Args:`` header does not
|
|
14
|
+
document a parameter named ``args`` (the header word is not a description); ``-> None`` needs no return
|
|
15
|
+
description; ``exempt_properties=true`` (default off) lets ``@property`` accessors go without a
|
|
16
|
+
docstring.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import ast
|
|
22
|
+
import re
|
|
23
|
+
from typing import List, Optional, Tuple, Union
|
|
24
|
+
|
|
25
|
+
from tree_engine.checks.model import Diagnostic, Severity
|
|
26
|
+
from tree_engine.checks.options import as_bool, parse_options
|
|
27
|
+
from tree_engine.checks.plugin import CheckerMetadata, CheckerPlugin, CheckRequest, KIND_BUILTIN
|
|
28
|
+
|
|
29
|
+
__all__ = ["DocstringsChecker", "check_docstrings"]
|
|
30
|
+
|
|
31
|
+
TOOL = "docstrings"
|
|
32
|
+
_PARAM_PATTERNS = (
|
|
33
|
+
r":param\s+{name}",
|
|
34
|
+
r":parameter\s+{name}",
|
|
35
|
+
r"Args:.*?{name}",
|
|
36
|
+
r"Parameters:.*?{name}",
|
|
37
|
+
r"\b{name}\s*:",
|
|
38
|
+
r"\b{name}\s*\(",
|
|
39
|
+
)
|
|
40
|
+
_ATTR_PATTERNS = (
|
|
41
|
+
r":attr\s+{name}",
|
|
42
|
+
r":attribute\s+{name}",
|
|
43
|
+
r"Attributes:.*?{name}",
|
|
44
|
+
r"Properties:.*?{name}",
|
|
45
|
+
r"\b{name}\s*:",
|
|
46
|
+
r"\b{name}\s*\(",
|
|
47
|
+
)
|
|
48
|
+
_RETURN_PATTERNS = (r":return", r":returns", r"Returns:", r"Return:")
|
|
49
|
+
#: Patterns that anchor on a section header: they run on the original text.
|
|
50
|
+
_HEADER_ANCHORED = ("Args:", "Parameters:", "Attributes:", "Properties:")
|
|
51
|
+
_BARE_HEADER = re.compile(
|
|
52
|
+
r"^[ \t]*(?:Args|Arguments|Parameters|Params|Attributes|Properties|Returns?|Raises|Yields?)[ \t]*:[ \t]*$",
|
|
53
|
+
re.IGNORECASE | re.MULTILINE,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
_Finding = Tuple[int, int, str, str]
|
|
57
|
+
_Function = Union[ast.FunctionDef, ast.AsyncFunctionDef]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _usable(docstring: Optional[str]) -> Optional[str]:
|
|
61
|
+
if not docstring or not docstring.strip():
|
|
62
|
+
return None
|
|
63
|
+
return docstring
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _documented(name: str, docstring: str, patterns: Tuple[str, ...]) -> bool:
|
|
67
|
+
"""True when a pattern mentions ``name``; a bare section header is not a mention of ``args``."""
|
|
68
|
+
escaped = re.escape(name)
|
|
69
|
+
bare_removed = _BARE_HEADER.sub("", docstring)
|
|
70
|
+
for pattern in patterns:
|
|
71
|
+
text = docstring if pattern.startswith(_HEADER_ANCHORED) else bare_removed
|
|
72
|
+
if re.search(pattern.format(name=escaped), text, re.IGNORECASE | re.DOTALL):
|
|
73
|
+
return True
|
|
74
|
+
return False
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _init_attributes(init_node: _Function, names: set) -> None:
|
|
78
|
+
for stmt in init_node.body:
|
|
79
|
+
targets: List[ast.expr] = []
|
|
80
|
+
if isinstance(stmt, ast.Assign):
|
|
81
|
+
targets = list(stmt.targets)
|
|
82
|
+
elif isinstance(stmt, ast.AnnAssign):
|
|
83
|
+
targets = [stmt.target]
|
|
84
|
+
for target in targets:
|
|
85
|
+
if isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name) and target.value.id == "self":
|
|
86
|
+
names.add(target.attr)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _class_attributes(class_node: ast.ClassDef) -> List[str]:
|
|
90
|
+
names: set = set()
|
|
91
|
+
for item in class_node.body:
|
|
92
|
+
if isinstance(item, ast.Assign):
|
|
93
|
+
for target in item.targets:
|
|
94
|
+
if isinstance(target, ast.Name):
|
|
95
|
+
names.add(target.id)
|
|
96
|
+
elif isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name):
|
|
97
|
+
names.add(target.attr)
|
|
98
|
+
elif isinstance(item, ast.AnnAssign):
|
|
99
|
+
if isinstance(item.target, ast.Name):
|
|
100
|
+
names.add(item.target.id)
|
|
101
|
+
elif isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
102
|
+
if item.name == "__init__":
|
|
103
|
+
_init_attributes(item, names)
|
|
104
|
+
for decorator in item.decorator_list:
|
|
105
|
+
if isinstance(decorator, ast.Name) and decorator.id == "property":
|
|
106
|
+
names.add(item.name)
|
|
107
|
+
return sorted(names)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _is_property(node: _Function) -> bool:
|
|
111
|
+
for decorator in node.decorator_list:
|
|
112
|
+
if isinstance(decorator, ast.Name) and decorator.id == "property":
|
|
113
|
+
return True
|
|
114
|
+
if isinstance(decorator, ast.Attribute) and decorator.attr in ("setter", "getter", "deleter"):
|
|
115
|
+
return True
|
|
116
|
+
return False
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _returns_none(node: _Function) -> bool:
|
|
120
|
+
returns = node.returns
|
|
121
|
+
return isinstance(returns, ast.Constant) and returns.value is None
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _check_function(node: _Function, owner: Optional[str], findings: List[_Finding], exempt_properties: bool) -> None:
|
|
125
|
+
context = f"{owner}.{node.name}" if owner else node.name
|
|
126
|
+
line, column = node.lineno, node.col_offset + 1
|
|
127
|
+
docstring = _usable(ast.get_docstring(node))
|
|
128
|
+
if docstring is None:
|
|
129
|
+
if not (exempt_properties and _is_property(node)):
|
|
130
|
+
findings.append((line, column, "DOC010", f"{context} is missing a docstring"))
|
|
131
|
+
return
|
|
132
|
+
params = [*node.args.posonlyargs, *node.args.args, *node.args.kwonlyargs]
|
|
133
|
+
if node.args.vararg is not None:
|
|
134
|
+
params.append(node.args.vararg)
|
|
135
|
+
if node.args.kwarg is not None:
|
|
136
|
+
params.append(node.args.kwarg)
|
|
137
|
+
params = [p for p in params if p.arg not in ("self", "cls")]
|
|
138
|
+
for param in params:
|
|
139
|
+
if param.annotation is None:
|
|
140
|
+
findings.append((line, column, "DOC030", f"{context} parameter {param.arg!r} has no type annotation"))
|
|
141
|
+
if node.returns is None:
|
|
142
|
+
findings.append((line, column, "DOC031", f"{context} has no return type annotation"))
|
|
143
|
+
for param in params:
|
|
144
|
+
if not _documented(param.arg, docstring, _PARAM_PATTERNS):
|
|
145
|
+
findings.append((line, column, "DOC020", f"{context} docstring does not describe parameter {param.arg!r}"))
|
|
146
|
+
if node.returns is not None and node.name != "__init__" and not _returns_none(node):
|
|
147
|
+
if not any(re.search(p, docstring, re.IGNORECASE) for p in _RETURN_PATTERNS):
|
|
148
|
+
findings.append((line, column, "DOC021", f"{context} docstring has no return value description"))
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _check_class(node: ast.ClassDef, findings: List[_Finding], exempt_properties: bool) -> None:
|
|
152
|
+
line, column = node.lineno, node.col_offset + 1
|
|
153
|
+
docstring = _usable(ast.get_docstring(node))
|
|
154
|
+
if docstring is None:
|
|
155
|
+
findings.append((line, column, "DOC011", f"class {node.name} is missing a docstring"))
|
|
156
|
+
return
|
|
157
|
+
for attribute in _class_attributes(node):
|
|
158
|
+
if not _documented(attribute, docstring, _ATTR_PATTERNS):
|
|
159
|
+
findings.append((line, column, "DOC040", f"class {node.name} docstring does not describe attribute {attribute!r}"))
|
|
160
|
+
for item in node.body:
|
|
161
|
+
if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
162
|
+
_check_function(item, node.name, findings, exempt_properties)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def check_docstrings(source: str, path: str, exempt_properties: bool = False) -> List[Diagnostic]:
|
|
166
|
+
"""Docstring diagnostics of one Python module (policy B); ``[]`` when it is fully documented."""
|
|
167
|
+
parse_text = source[1:] if source.startswith("") else source
|
|
168
|
+
try:
|
|
169
|
+
tree = ast.parse(parse_text, filename=path or "<string>")
|
|
170
|
+
except SyntaxError as exc:
|
|
171
|
+
return [
|
|
172
|
+
Diagnostic(
|
|
173
|
+
tool=TOOL,
|
|
174
|
+
code="DOC000",
|
|
175
|
+
severity=Severity.ERROR,
|
|
176
|
+
message=f"syntax error: {exc.msg}",
|
|
177
|
+
path=path,
|
|
178
|
+
line=max(exc.lineno or 1, 1),
|
|
179
|
+
column=max(exc.offset or 1, 1),
|
|
180
|
+
)
|
|
181
|
+
]
|
|
182
|
+
findings: List[_Finding] = []
|
|
183
|
+
if _usable(ast.get_docstring(tree)) is None:
|
|
184
|
+
findings.append((1, 1, "DOC001", "module docstring is missing or empty"))
|
|
185
|
+
for node in ast.walk(tree):
|
|
186
|
+
if isinstance(node, ast.ClassDef):
|
|
187
|
+
_check_class(node, findings, exempt_properties)
|
|
188
|
+
for node in tree.body:
|
|
189
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
190
|
+
_check_function(node, None, findings, exempt_properties)
|
|
191
|
+
return [
|
|
192
|
+
Diagnostic(tool=TOOL, code=code, severity=Severity.ERROR, message=message, path=path, line=line, column=column)
|
|
193
|
+
for line, column, code, message in sorted(findings, key=lambda f: (f[0], f[1], f[2]))
|
|
194
|
+
]
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class DocstringsChecker(CheckerPlugin):
|
|
198
|
+
"""Builtin ``docstrings`` checker; option ``exempt_properties=true`` (default off)."""
|
|
199
|
+
|
|
200
|
+
_METADATA = CheckerMetadata(
|
|
201
|
+
check_id=TOOL, kind=KIND_BUILTIN, contract_version="1", file_extensions=(".py",), format_ids=("python",)
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
@property
|
|
205
|
+
def metadata(self) -> CheckerMetadata:
|
|
206
|
+
return self._METADATA
|
|
207
|
+
|
|
208
|
+
def check(self, request: CheckRequest) -> List[Diagnostic]:
|
|
209
|
+
options = parse_options(TOOL, request.args, {"exempt_properties": as_bool})
|
|
210
|
+
source = request.source if isinstance(request.source, str) else request.source.decode("utf-8", errors="replace")
|
|
211
|
+
return check_docstrings(source, request.path, exempt_properties=options.get("exempt_properties", False))
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""The ``encoding`` builtin checker: bytes that are not valid UTF-8 (TODO 15a86bcb, group G6, Q11 b).
|
|
2
|
+
|
|
3
|
+
Author: Vasiliy Zdanovskiy
|
|
4
|
+
email: vasilyvz@gmail.com
|
|
5
|
+
|
|
6
|
+
Only invalid UTF-8 is reported, as one ``ENC-UTF8`` error at the line and column of the first invalid
|
|
7
|
+
byte. A BOM, CRLF line ends and a missing final newline are not findings. A ``str`` source is already
|
|
8
|
+
decoded and always gives ``[]``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from typing import List
|
|
14
|
+
|
|
15
|
+
from tree_engine.checks.model import Diagnostic, Severity
|
|
16
|
+
from tree_engine.checks.plugin import CheckerMetadata, CheckerPlugin, CheckRequest, KIND_BUILTIN
|
|
17
|
+
|
|
18
|
+
__all__ = ["EncodingChecker"]
|
|
19
|
+
|
|
20
|
+
TOOL = "encoding"
|
|
21
|
+
ALL_FORMATS = ("python", "json", "yaml", "toml", "ini", "xml", "markdown", "jsonl", "plain_text", "csv", "sql", "onec_query", "bsl")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class EncodingChecker(CheckerPlugin):
|
|
25
|
+
"""Builtin ``encoding`` checker."""
|
|
26
|
+
|
|
27
|
+
_METADATA = CheckerMetadata(check_id=TOOL, kind=KIND_BUILTIN, contract_version="1", format_ids=ALL_FORMATS)
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def metadata(self) -> CheckerMetadata:
|
|
31
|
+
return self._METADATA
|
|
32
|
+
|
|
33
|
+
def check(self, request: CheckRequest) -> List[Diagnostic]:
|
|
34
|
+
data = request.source
|
|
35
|
+
if isinstance(data, str):
|
|
36
|
+
return []
|
|
37
|
+
try:
|
|
38
|
+
data.decode("utf-8")
|
|
39
|
+
except UnicodeDecodeError as exc:
|
|
40
|
+
before = data[: exc.start]
|
|
41
|
+
line = before.count(b"\n") + 1
|
|
42
|
+
line_start = before.rfind(b"\n") + 1
|
|
43
|
+
column = len(before[line_start:].decode("utf-8", errors="replace")) + 1
|
|
44
|
+
return [
|
|
45
|
+
Diagnostic(
|
|
46
|
+
tool=TOOL,
|
|
47
|
+
code="ENC-UTF8",
|
|
48
|
+
severity=Severity.ERROR,
|
|
49
|
+
message=f"invalid UTF-8 byte 0x{data[exc.start]:02x} at offset {exc.start}: {exc.reason}",
|
|
50
|
+
path=request.path,
|
|
51
|
+
line=line,
|
|
52
|
+
column=column,
|
|
53
|
+
)
|
|
54
|
+
]
|
|
55
|
+
return []
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""The fleet-rule builtin checkers: ``placeholders``, ``stubs``, ``empty_implementations``, ``file_length``.
|
|
2
|
+
|
|
3
|
+
Author: Vasiliy Zdanovskiy
|
|
4
|
+
email: vasilyvz@gmail.com
|
|
5
|
+
|
|
6
|
+
TODO 15a86bcb group G6, decision D-BU: the definitions are those of the Code Analysis Server's
|
|
7
|
+
comprehensive analyzer word for word (placeholder words, stub bodies, empty-method bodies, the default
|
|
8
|
+
limit of 400 lines). Imports-not-at-top and duplicates are not part of this release. Findings have
|
|
9
|
+
severity ``warning`` and are sorted by ``(line, column, code)``. A module that does not parse gives no
|
|
10
|
+
stub or empty-implementation finding; placeholders still report comments.
|
|
11
|
+
|
|
12
|
+
Options (``name=value`` tokens in ``CheckRequest.args``): ``placeholders``: ``patterns=A,B``;
|
|
13
|
+
``empty_implementations``: ``ignore_abstract=false``; ``file_length``: ``max_lines=N``.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import ast
|
|
19
|
+
import io
|
|
20
|
+
import re
|
|
21
|
+
import tokenize
|
|
22
|
+
from typing import Dict, List, Optional, Tuple
|
|
23
|
+
|
|
24
|
+
from tree_engine.checks.model import Diagnostic, Severity
|
|
25
|
+
from tree_engine.checks.options import as_bool, as_positive_int, as_str_list, parse_options
|
|
26
|
+
from tree_engine.checks.plugin import CheckerMetadata, CheckerPlugin, CheckRequest, KIND_BUILTIN
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"PlaceholdersChecker",
|
|
30
|
+
"StubsChecker",
|
|
31
|
+
"EmptyImplementationsChecker",
|
|
32
|
+
"FileLengthChecker",
|
|
33
|
+
"PLACEHOLDER_PATTERNS",
|
|
34
|
+
"DEFAULT_MAX_FILE_LINES",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
PLACEHOLDER_PATTERNS: Tuple[str, ...] = (
|
|
38
|
+
"TODO", "FIXME", "XXX", "HACK", "NOTE", "BUG", "OPTIMIZE", "PLACEHOLDER", "STUB", "NOT IMPLEMENTED",
|
|
39
|
+
)
|
|
40
|
+
DEFAULT_MAX_FILE_LINES = 400
|
|
41
|
+
_FINDING = Tuple[int, int, str, str]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _text(request: CheckRequest) -> str:
|
|
45
|
+
source = request.source
|
|
46
|
+
text = source if isinstance(source, str) else source.decode("utf-8", errors="replace")
|
|
47
|
+
return text[1:] if text.startswith("") else text
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _tree(text: str, path: str) -> Optional[ast.Module]:
|
|
51
|
+
try:
|
|
52
|
+
return ast.parse(text, filename=path or "<string>")
|
|
53
|
+
except (SyntaxError, ValueError):
|
|
54
|
+
return None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _diagnostics(tool: str, path: str, findings: List[_FINDING]) -> List[Diagnostic]:
|
|
58
|
+
return [
|
|
59
|
+
Diagnostic(tool=tool, code=code, severity=Severity.WARNING, message=message, path=path, line=line, column=column)
|
|
60
|
+
for line, column, code, message in sorted(findings, key=lambda f: (f[0], f[1], f[2]))
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _python_metadata(check_id: str) -> CheckerMetadata:
|
|
65
|
+
return CheckerMetadata(
|
|
66
|
+
check_id=check_id, kind=KIND_BUILTIN, contract_version="1", file_extensions=(".py",), format_ids=("python",)
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class PlaceholdersChecker(CheckerPlugin):
|
|
71
|
+
"""Placeholder words in comments, docstrings and string literals."""
|
|
72
|
+
|
|
73
|
+
_METADATA = _python_metadata("placeholders")
|
|
74
|
+
|
|
75
|
+
@property
|
|
76
|
+
def metadata(self) -> CheckerMetadata:
|
|
77
|
+
return self._METADATA
|
|
78
|
+
|
|
79
|
+
def check(self, request: CheckRequest) -> List[Diagnostic]:
|
|
80
|
+
options = parse_options("placeholders", request.args, {"patterns": as_str_list})
|
|
81
|
+
patterns = options.get("patterns") or list(PLACEHOLDER_PATTERNS)
|
|
82
|
+
regex = re.compile(r"\b(" + "|".join(re.escape(p) for p in patterns) + r")\b", re.IGNORECASE | re.MULTILINE)
|
|
83
|
+
text = _text(request)
|
|
84
|
+
findings: List[_FINDING] = []
|
|
85
|
+
try:
|
|
86
|
+
for token in tokenize.generate_tokens(io.StringIO(text).readline):
|
|
87
|
+
if token.type == tokenize.COMMENT:
|
|
88
|
+
match = regex.search(token.string)
|
|
89
|
+
if match:
|
|
90
|
+
findings.append((token.start[0], token.start[1] + 1, "PLACEHOLDER-COMMENT",
|
|
91
|
+
f"comment contains placeholder {match.group(1).upper()}"))
|
|
92
|
+
except (tokenize.TokenError, IndentationError, SyntaxError):
|
|
93
|
+
pass
|
|
94
|
+
tree = _tree(text, request.path)
|
|
95
|
+
if tree is not None:
|
|
96
|
+
for node in ast.walk(tree):
|
|
97
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Module)):
|
|
98
|
+
docstring = ast.get_docstring(node, clean=False)
|
|
99
|
+
match = regex.search(docstring) if docstring else None
|
|
100
|
+
if match:
|
|
101
|
+
findings.append((getattr(node, "lineno", 1), getattr(node, "col_offset", 0) + 1, "PLACEHOLDER-DOCSTRING",
|
|
102
|
+
f"docstring contains placeholder {match.group(1).upper()}"))
|
|
103
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
|
104
|
+
match = regex.search(node.value)
|
|
105
|
+
if match:
|
|
106
|
+
findings.append((node.lineno, node.col_offset + 1, "PLACEHOLDER-STRING",
|
|
107
|
+
f"string literal contains placeholder {match.group(1).upper()}"))
|
|
108
|
+
return _diagnostics("placeholders", request.path, findings)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _is_ellipsis(stmt: ast.stmt) -> bool:
|
|
112
|
+
return isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant) and stmt.value.value is Ellipsis
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class StubsChecker(CheckerPlugin):
|
|
116
|
+
"""Functions and methods whose whole body is ``pass``, ``...``, ``raise NotImplementedError`` or ``return None``."""
|
|
117
|
+
|
|
118
|
+
_METADATA = _python_metadata("stubs")
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def metadata(self) -> CheckerMetadata:
|
|
122
|
+
return self._METADATA
|
|
123
|
+
|
|
124
|
+
def check(self, request: CheckRequest) -> List[Diagnostic]:
|
|
125
|
+
parse_options("stubs", request.args, {})
|
|
126
|
+
tree = _tree(_text(request), request.path)
|
|
127
|
+
findings: List[_FINDING] = []
|
|
128
|
+
if tree is None:
|
|
129
|
+
return []
|
|
130
|
+
owners: Dict[int, str] = {}
|
|
131
|
+
for parent in ast.walk(tree):
|
|
132
|
+
if isinstance(parent, ast.ClassDef):
|
|
133
|
+
for item in parent.body:
|
|
134
|
+
owners[id(item)] = parent.name
|
|
135
|
+
for node in ast.walk(tree):
|
|
136
|
+
if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) or len(node.body) != 1:
|
|
137
|
+
continue
|
|
138
|
+
body = node.body[0]
|
|
139
|
+
if isinstance(body, ast.Pass):
|
|
140
|
+
kind = "PASS"
|
|
141
|
+
elif _is_ellipsis(body):
|
|
142
|
+
kind = "ELLIPSIS"
|
|
143
|
+
elif (isinstance(body, ast.Raise) and isinstance(body.exc, ast.Call)
|
|
144
|
+
and isinstance(body.exc.func, ast.Name) and body.exc.func.id == "NotImplementedError"):
|
|
145
|
+
kind = "NOT-IMPLEMENTED"
|
|
146
|
+
elif isinstance(body, ast.Return) and isinstance(body.value, ast.Constant) and body.value.value is None:
|
|
147
|
+
if any(isinstance(d, ast.Name) and d.id == "abstractmethod" for d in node.decorator_list):
|
|
148
|
+
continue
|
|
149
|
+
kind = "RETURN-NONE"
|
|
150
|
+
else:
|
|
151
|
+
continue
|
|
152
|
+
owner = owners.get(id(node))
|
|
153
|
+
name = f"{owner}.{node.name}" if owner else node.name
|
|
154
|
+
findings.append((node.lineno, node.col_offset + 1, f"STUB-{kind}", f"{name} is a stub ({kind.lower().replace('-', ' ')})"))
|
|
155
|
+
return _diagnostics("stubs", request.path, findings)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class EmptyImplementationsChecker(CheckerPlugin):
|
|
159
|
+
"""Methods of a class whose body is empty, ``pass``, ``...`` or a docstring only (abstract ones are skipped)."""
|
|
160
|
+
|
|
161
|
+
_METADATA = _python_metadata("empty_implementations")
|
|
162
|
+
|
|
163
|
+
@property
|
|
164
|
+
def metadata(self) -> CheckerMetadata:
|
|
165
|
+
return self._METADATA
|
|
166
|
+
|
|
167
|
+
def check(self, request: CheckRequest) -> List[Diagnostic]:
|
|
168
|
+
options = parse_options("empty_implementations", request.args, {"ignore_abstract": as_bool})
|
|
169
|
+
ignore_abstract = options.get("ignore_abstract", True)
|
|
170
|
+
tree = _tree(_text(request), request.path)
|
|
171
|
+
if tree is None:
|
|
172
|
+
return []
|
|
173
|
+
findings: List[_FINDING] = []
|
|
174
|
+
for node in ast.walk(tree):
|
|
175
|
+
if not isinstance(node, ast.ClassDef):
|
|
176
|
+
continue
|
|
177
|
+
is_abc = any(isinstance(base, ast.Name) and base.id == "ABC" for base in node.bases)
|
|
178
|
+
for item in node.body:
|
|
179
|
+
if not isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
180
|
+
continue
|
|
181
|
+
is_abstract = is_abc or any(
|
|
182
|
+
isinstance(d, ast.Name) and d.id == "abstractmethod" for d in item.decorator_list
|
|
183
|
+
)
|
|
184
|
+
if is_abstract and ignore_abstract:
|
|
185
|
+
continue
|
|
186
|
+
body = item.body
|
|
187
|
+
if not body:
|
|
188
|
+
kind = "EMPTY"
|
|
189
|
+
elif len(body) == 1 and isinstance(body[0], ast.Pass):
|
|
190
|
+
kind = "PASS"
|
|
191
|
+
elif len(body) == 1 and _is_ellipsis(body[0]):
|
|
192
|
+
kind = "ELLIPSIS"
|
|
193
|
+
elif (len(body) == 1 and isinstance(body[0], ast.Expr) and isinstance(body[0].value, ast.Constant)
|
|
194
|
+
and isinstance(body[0].value.value, str)):
|
|
195
|
+
kind = "DOCSTRING-ONLY"
|
|
196
|
+
else:
|
|
197
|
+
continue
|
|
198
|
+
findings.append((item.lineno, item.col_offset + 1, f"EMPTY-{kind}",
|
|
199
|
+
f"method {node.name}.{item.name} has an empty implementation ({kind.lower().replace('-', ' ')})"))
|
|
200
|
+
return _diagnostics("empty_implementations", request.path, findings)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
class FileLengthChecker(CheckerPlugin):
|
|
204
|
+
"""A file longer than ``max_lines`` lines (default 400); any format."""
|
|
205
|
+
|
|
206
|
+
_METADATA = CheckerMetadata(
|
|
207
|
+
check_id="file_length", kind=KIND_BUILTIN, contract_version="1",
|
|
208
|
+
format_ids=("python", "json", "yaml", "toml", "ini", "xml", "markdown", "jsonl", "plain_text", "csv", "sql", "onec_query", "bsl"),
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
@property
|
|
212
|
+
def metadata(self) -> CheckerMetadata:
|
|
213
|
+
return self._METADATA
|
|
214
|
+
|
|
215
|
+
def check(self, request: CheckRequest) -> List[Diagnostic]:
|
|
216
|
+
options = parse_options("file_length", request.args, {"max_lines": as_positive_int})
|
|
217
|
+
limit = options.get("max_lines", DEFAULT_MAX_FILE_LINES)
|
|
218
|
+
source = request.source
|
|
219
|
+
lines = len(source.splitlines()) if isinstance(source, (str, bytes)) else 0
|
|
220
|
+
if lines <= limit:
|
|
221
|
+
return []
|
|
222
|
+
return [
|
|
223
|
+
Diagnostic(
|
|
224
|
+
tool="file_length", code="FILE-LENGTH", severity=Severity.WARNING, path=request.path, line=1, column=1,
|
|
225
|
+
message=f"file has {lines} lines, exceeding the limit of {limit} by {lines - limit}",
|
|
226
|
+
)
|
|
227
|
+
]
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Builtin syntax checkers of the statement formats: ``sql_syntax`` and ``onec_query_syntax``.
|
|
2
|
+
|
|
3
|
+
Author: Vasiliy Zdanovskiy
|
|
4
|
+
email: vasilyvz@gmail.com
|
|
5
|
+
|
|
6
|
+
Each reports the first construct that never closes (string, quoted identifier, block comment, dollar quote),
|
|
7
|
+
at the 1-based line and column of its opening. Codes are ``SYNTAX-SQL`` and ``SYNTAX-ONEC_QUERY``. The
|
|
8
|
+
checkers live in the engine so that the Code Analysis server can call them; the format plugins declare them
|
|
9
|
+
through ``checker_plugin``.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from typing import List
|
|
15
|
+
|
|
16
|
+
from tree_engine.checks.model import Diagnostic, Severity
|
|
17
|
+
from tree_engine.checks.plugin import CheckerMetadata, CheckerPlugin, CheckRequest, KIND_BUILTIN
|
|
18
|
+
from tree_engine.plugins._statements import Dialect, find_unterminated
|
|
19
|
+
from tree_engine.plugins.onec_query_format import ONEC_QUERY_DIALECT
|
|
20
|
+
from tree_engine.plugins.sql_format import SQL_DIALECT
|
|
21
|
+
|
|
22
|
+
__all__ = ["SqlSyntaxChecker", "OnecQuerySyntaxChecker"]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class _StatementSyntaxChecker(CheckerPlugin):
|
|
26
|
+
_DIALECT: Dialect
|
|
27
|
+
_CODE = ""
|
|
28
|
+
_METADATA: CheckerMetadata
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def metadata(self) -> CheckerMetadata:
|
|
32
|
+
return self._METADATA
|
|
33
|
+
|
|
34
|
+
def check(self, request: CheckRequest) -> List[Diagnostic]:
|
|
35
|
+
source = request.source
|
|
36
|
+
text = source.decode("utf-8", errors="replace") if isinstance(source, bytes) else source
|
|
37
|
+
if text.startswith(""):
|
|
38
|
+
text = text[1:]
|
|
39
|
+
found = find_unterminated(text, self._DIALECT)
|
|
40
|
+
if found is None:
|
|
41
|
+
return []
|
|
42
|
+
line = text.count("\n", 0, found.offset) + 1
|
|
43
|
+
column = found.offset - (text.rfind("\n", 0, found.offset) + 1) + 1
|
|
44
|
+
return [
|
|
45
|
+
Diagnostic(
|
|
46
|
+
tool=self._METADATA.check_id,
|
|
47
|
+
code=self._CODE,
|
|
48
|
+
severity=Severity.ERROR,
|
|
49
|
+
message=f"unterminated {found.what} opened at line {line}, column {column}",
|
|
50
|
+
path=request.path,
|
|
51
|
+
line=line,
|
|
52
|
+
column=column,
|
|
53
|
+
)
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class SqlSyntaxChecker(_StatementSyntaxChecker):
|
|
58
|
+
"""Unterminated string, quoted identifier, block comment or dollar quote in SQL."""
|
|
59
|
+
|
|
60
|
+
_DIALECT = SQL_DIALECT
|
|
61
|
+
_CODE = "SYNTAX-SQL"
|
|
62
|
+
_METADATA = CheckerMetadata(
|
|
63
|
+
check_id="sql_syntax",
|
|
64
|
+
kind=KIND_BUILTIN,
|
|
65
|
+
contract_version="1",
|
|
66
|
+
file_extensions=(".sql",),
|
|
67
|
+
format_ids=("sql",),
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class OnecQuerySyntaxChecker(_StatementSyntaxChecker):
|
|
72
|
+
"""Unterminated string in a 1C query (``//`` is the only comment mark)."""
|
|
73
|
+
|
|
74
|
+
_DIALECT = ONEC_QUERY_DIALECT
|
|
75
|
+
_CODE = "SYNTAX-ONEC_QUERY"
|
|
76
|
+
_METADATA = CheckerMetadata(
|
|
77
|
+
check_id="onec_query_syntax",
|
|
78
|
+
kind=KIND_BUILTIN,
|
|
79
|
+
contract_version="1",
|
|
80
|
+
file_extensions=(".q1c",),
|
|
81
|
+
format_ids=("onec_query",),
|
|
82
|
+
)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""The ``jsonl_syntax`` builtin checker: every line that is not valid JSON (decision D-CN, owner answers 9-11).
|
|
2
|
+
|
|
3
|
+
Author: Vasiliy Zdanovskiy
|
|
4
|
+
email: vasilyvz@gmail.com
|
|
5
|
+
|
|
6
|
+
Declared by the jsonl format plugin through ``checker_plugin``; the registry finds it by itself. One ``SYNTAX-JSONL``
|
|
7
|
+
error per line the jsonl plugin turns into a ``jsonl:invalid_record`` node (the same per-line classification). The
|
|
8
|
+
position is the 1-based line only; the column is the fixed value 1. Blank lines are not errors.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from typing import List
|
|
14
|
+
|
|
15
|
+
from tree_engine.checks.model import Diagnostic, Severity
|
|
16
|
+
from tree_engine.checks.plugin import CheckerMetadata, CheckerPlugin, CheckRequest, KIND_BUILTIN
|
|
17
|
+
from tree_engine.plugins.jsonl_format import jsonl_failures
|
|
18
|
+
|
|
19
|
+
__all__ = ["JsonlSyntaxChecker"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class JsonlSyntaxChecker(CheckerPlugin):
|
|
23
|
+
"""Reports every invalid record of a JSON Lines file."""
|
|
24
|
+
|
|
25
|
+
_METADATA = CheckerMetadata(
|
|
26
|
+
check_id="jsonl_syntax",
|
|
27
|
+
kind=KIND_BUILTIN,
|
|
28
|
+
contract_version="1",
|
|
29
|
+
file_extensions=(".jsonl", ".ndjson"),
|
|
30
|
+
format_ids=("jsonl",),
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def metadata(self) -> CheckerMetadata:
|
|
35
|
+
return self._METADATA
|
|
36
|
+
|
|
37
|
+
def check(self, request: CheckRequest) -> List[Diagnostic]:
|
|
38
|
+
return [
|
|
39
|
+
Diagnostic(
|
|
40
|
+
tool="jsonl_syntax",
|
|
41
|
+
code="SYNTAX-JSONL",
|
|
42
|
+
severity=Severity.ERROR,
|
|
43
|
+
message=item["message"] or "invalid JSON record",
|
|
44
|
+
path=request.path,
|
|
45
|
+
line=item["line"],
|
|
46
|
+
column=1,
|
|
47
|
+
)
|
|
48
|
+
for item in jsonl_failures(request.source)
|
|
49
|
+
]
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""The fifteen shipped checkers, in registration order.
|
|
2
|
+
|
|
3
|
+
Author: Vasiliy Zdanovskiy
|
|
4
|
+
email: vasilyvz@gmail.com
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import List
|
|
10
|
+
|
|
11
|
+
from tree_engine.checks.plugin import CheckerPlugin
|
|
12
|
+
|
|
13
|
+
__all__ = ["shipped_checkers"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def shipped_checkers() -> List[CheckerPlugin]:
|
|
17
|
+
"""Every shipped checker: syntax, xml_wellformed, compile, docstrings, encoding, the four fleet rules, the six tools."""
|
|
18
|
+
from tree_engine.checks.builtin.compile_check import CompileChecker
|
|
19
|
+
from tree_engine.checks.builtin.docstrings import DocstringsChecker
|
|
20
|
+
from tree_engine.checks.builtin.encoding import EncodingChecker
|
|
21
|
+
from tree_engine.checks.builtin.fleet_rules import (
|
|
22
|
+
EmptyImplementationsChecker,
|
|
23
|
+
FileLengthChecker,
|
|
24
|
+
PlaceholdersChecker,
|
|
25
|
+
StubsChecker,
|
|
26
|
+
)
|
|
27
|
+
from tree_engine.checks.builtin.syntax import SyntaxChecker
|
|
28
|
+
from tree_engine.checks.builtin.xml_wellformed import XmlWellformedChecker
|
|
29
|
+
from tree_engine.checks.external.bandit import BanditChecker
|
|
30
|
+
from tree_engine.checks.external.black import BlackChecker
|
|
31
|
+
from tree_engine.checks.external.flake8 import Flake8Checker
|
|
32
|
+
from tree_engine.checks.external.isort import IsortChecker
|
|
33
|
+
from tree_engine.checks.external.mypy import MypyChecker
|
|
34
|
+
from tree_engine.checks.external.ruff import RuffChecker
|
|
35
|
+
|
|
36
|
+
return [
|
|
37
|
+
SyntaxChecker(),
|
|
38
|
+
XmlWellformedChecker(),
|
|
39
|
+
CompileChecker(),
|
|
40
|
+
DocstringsChecker(),
|
|
41
|
+
EncodingChecker(),
|
|
42
|
+
PlaceholdersChecker(),
|
|
43
|
+
StubsChecker(),
|
|
44
|
+
EmptyImplementationsChecker(),
|
|
45
|
+
FileLengthChecker(),
|
|
46
|
+
Flake8Checker(),
|
|
47
|
+
MypyChecker(),
|
|
48
|
+
BlackChecker(),
|
|
49
|
+
IsortChecker(),
|
|
50
|
+
BanditChecker(),
|
|
51
|
+
RuffChecker(),
|
|
52
|
+
]
|