Skip to content

Official Codebase of 3DCodeVerse

Python

languages: one ImportCollector for the cadquery and urdf lints, and blender's second finding factory goes

gaoypeng4bbf919db2d9
diff --git a/harness/codeverse3d/languages/_ast_lint.py b/harness/codeverse3d/languages/_ast_lint.py
index 1f1602be..a1896e4a 100644
--- a/harness/codeverse3d/languages/_ast_lint.py
+++ b/harness/codeverse3d/languages/_ast_lint.py
@@ -1,7 +1,8 @@
"""Shared AST-lint primitives for the python authoring languages (blender, cadquery, opengl_python).
Each language keeps its own collector and rules — only the language-neutral
-pieces live here: :func:`dotted` (dotted-name of an Attribute/Name chain), the
+pieces live here: :func:`dotted` (dotted-name of an Attribute/Name chain),
+:class:`ImportCollector` (the ``{top-level module: first line}`` visitor), the
:data:`BASE_FORBIDDEN_IMPORTS` floor every language's forbidden set must
include (a drift test pins the superset), and :func:`check_imports` (the
forbidden → ERROR / not-allowed → WARN routing, with the finding text owned by
@@ -27,6 +28,21 @@ BASE_FORBIDDEN_IMPORTS: frozenset[str] = frozenset({
})
+class ImportCollector(ast.NodeVisitor):
+ """``imports``: ``{top-level module: first line}`` of every import, in document order
+ (a subclass visits the rest of the tree for its own rules)."""
+
+ def __init__(self) -> None:
+ self.imports: dict[str, int] = {}
+
+ def visit_Import(self, node: ast.Import) -> None:
+ for a in node.names:
+ self.imports.setdefault(a.name.split(".")[0], node.lineno)
+
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
+ self.imports.setdefault((node.module or "").split(".")[0], node.lineno)
+
+
def safe_parse(source: str, filename: str = "<src>") -> tuple[ast.AST | None, BaseException | None]:
"""``ast.parse`` that never raises: ``(tree, None)`` or ``(None, exception)``.
diff --git a/harness/codeverse3d/languages/blender/__init__.py b/harness/codeverse3d/languages/blender/__init__.py
index c0b6d13b..71ac3ac0 100644
--- a/harness/codeverse3d/languages/blender/__init__.py
+++ b/harness/codeverse3d/languages/blender/__init__.py
@@ -326,11 +326,6 @@ def _rel(ws: Workspace, p: Path) -> str:
return p.relative_to(ws.root).as_posix()
-def _finding(sev: Severity, target: str, msg: str, hint: str, line: int | None = None) -> GateFinding:
- return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=hint,
- data={"line": line} if line else {})
-
-
def _exported_functions(tree: ast.Module) -> set[str]:
return {n.name for n in tree.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
@@ -363,28 +358,28 @@ def _layout_rules(ws: Workspace, parts: list[Path], entry_tree: ast.Module | Non
target = _rel(ws, p)
stem = p.stem
if stem != to_snake(stem):
- out.append(_finding(E, target, f"part file name '{p.name}' is not snake_case",
- f"rename to src/{PARTS_DIR}/{to_snake(stem)}.py (the harness maps plan part "
- f"'{stem}' → that file) and fix the import in model.py"))
+ out.append(_f(E, f"part file name '{p.name}' is not snake_case", target=target,
+ hint=f"rename to src/{PARTS_DIR}/{to_snake(stem)}.py (the harness maps plan part "
+ f"'{stem}' → that file) and fix the import in model.py"))
continue
tree, _ = safe_parse(p.read_text(), target)
if tree is None:
continue # reported by the per-file lint
fn = f"build_{stem}"
if fn not in _exported_functions(tree):
- out.append(_finding(E, target, f"{target} does not define `def {fn}()`",
- f"every part file exports `def {fn}() -> bpy.types.Object` returning the named object "
- f"at its world pose; model.py calls it (`from {PARTS_DIR}.{stem} import {fn}`)"))
+ out.append(_f(E, f"{target} does not define `def {fn}()`", target=target,
+ hint=f"every part file exports `def {fn}() -> bpy.types.Object` returning the named object "
+ f"at its world pose; model.py calls it (`from {PARTS_DIR}.{stem} import {fn}`)"))
for node in tree.body:
if isinstance(node, ast.Expr) and isinstance(node.value, ast.Call):
name = getattr(node.value.func, "id", "")
if name.startswith("build_") or name == "main":
- out.append(_finding(W, target, f"{target} calls `{name}()` at import time",
- "part files only DEFINE builders; model.py calls them once (a module-level "
- "call here builds the part twice → auto-suffixed 'Name.001')", node.lineno))
+ out.append(_f(W, f"{target} calls `{name}()` at import time", node.lineno, target=target,
+ hint="part files only DEFINE builders; model.py calls them once (a module-level "
+ "call here builds the part twice → auto-suffixed 'Name.001')"))
if entry_tree is not None and stem not in imported:
- out.append(_finding(W, target, f"{target} is never imported by src/model.py → its part is not built",
- f"add `from {PARTS_DIR}.{stem} import {fn}` to model.py and call `{fn}()` in main()"))
+ out.append(_f(W, f"{target} is never imported by src/model.py → its part is not built", target=target,
+ hint=f"add `from {PARTS_DIR}.{stem} import {fn}` to model.py and call `{fn}()` in main()"))
return out
@@ -393,9 +388,9 @@ def lint_workspace(ws: Workspace) -> GateReport:
t0 = time.monotonic()
entry = ws.src / "model.py"
if not entry.is_file():
- return GateReport(gate=GATE, passed=False, duration_ms=0, findings=[_finding(
- Severity.ERROR, ENTRY_REL, f"{ENTRY_REL} is missing",
- "create src/model.py (entry: imports src/parts/<snake>.py builders and calls them; see the skeleton)")])
+ return GateReport(gate=GATE, passed=False, duration_ms=0, findings=[_f(
+ Severity.ERROR, f"{ENTRY_REL} is missing", target=ENTRY_REL,
+ hint="create src/model.py (entry: imports src/parts/<snake>.py builders and calls them; see the skeleton)")])
parts = part_files(ws)
findings: list[GateFinding] = []
for p in source_files(ws):
diff --git a/harness/codeverse3d/languages/cadquery/__init__.py b/harness/codeverse3d/languages/cadquery/__init__.py
index d83d033a..4e62cfc5 100644
--- a/harness/codeverse3d/languages/cadquery/__init__.py
+++ b/harness/codeverse3d/languages/cadquery/__init__.py
@@ -16,6 +16,7 @@ from codeverse3d.contracts.plan import PartPlan, Plan, StaticPlan
from codeverse3d.conventions import MAX_TRIS_OBJECT, PASCAL_RE, to_pascal, to_snake
from codeverse3d.languages._ast_lint import (
BASE_FORBIDDEN_IMPORTS,
+ ImportCollector,
check_imports,
describe_parse_failure,
dotted,
@@ -92,21 +93,13 @@ def _f(sev: Severity, msg: str, line: int | None = None, hint: str = "", target:
return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=hint, data={"line": line} if line else {})
-class _Collector(ast.NodeVisitor):
+class _Collector(ImportCollector):
def __init__(self) -> None:
- self.imports: dict[str, int] = {}
+ super().__init__()
self.calls: list[tuple[str, ast.Call]] = []
self.add_calls: list[ast.Call] = []
self.name_kw: list[str] = []
- def visit_Import(self, node: ast.Import) -> None:
- for a in node.names:
- top = a.name.split(".")[0]
- self.imports.setdefault(top, node.lineno)
-
- def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
- self.imports.setdefault((node.module or "").split(".")[0], node.lineno)
-
def visit_Call(self, node: ast.Call) -> None:
name = dotted(node.func)
self.calls.append((name, node))
diff --git a/harness/codeverse3d/languages/urdf/__init__.py b/harness/codeverse3d/languages/urdf/__init__.py
index 0284b55b..9265cc6a 100644
--- a/harness/codeverse3d/languages/urdf/__init__.py
+++ b/harness/codeverse3d/languages/urdf/__init__.py
@@ -24,6 +24,7 @@ from codeverse3d.contracts.plan import ArticulatedPlan, JointPlan, PartPlan, Pla
from codeverse3d.conventions import to_snake
from codeverse3d.languages._ast_lint import (
BASE_FORBIDDEN_IMPORTS,
+ ImportCollector,
check_imports,
describe_parse_failure,
dotted,
@@ -417,21 +418,12 @@ def _lint_joint(el: ET.Element, jname: str, link_names: list[str], parent_of: di
# ------------------------------------------------------------------ model.py
-class _Visitor(ast.NodeVisitor):
+class _Visitor(ImportCollector):
def __init__(self) -> None:
+ super().__init__()
self.findings: list[GateFinding] = []
- self.imports: dict[str, int] = {} # top-level module → first line
self.strings: set[str] = set()
- def visit_Import(self, node: ast.Import) -> None:
- for a in node.names:
- self.imports.setdefault(a.name.split(".")[0], node.lineno)
- self.generic_visit(node)
-
- def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
- self.imports.setdefault((node.module or "").split(".")[0], node.lineno)
- self.generic_visit(node)
-
def visit_Call(self, node: ast.Call) -> None:
chain = dotted(node.func)
for prefix, why in FORBIDDEN_BPY_PREFIXES: