Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / codegen / inline / declaration_edits.py: 100%
61 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Render top-level imports and source snippets from inline patch IR."""
17from __future__ import annotations
19import ast
20from collections import defaultdict
21from collections.abc import Iterable
23from hyper_parallel.codegen.astkit.edits import TextEdit, insert_after_imports
24from hyper_parallel.codegen.inline.ir import ImportPatch, ModuleSnippetPatch
27def declaration_edits(
28 source_text: str,
29 import_end: int | None,
30 docstring_end: int | None,
31 imports: Iterable[ImportPatch],
32 snippets: Iterable[ModuleSnippetPatch],
33) -> list[TextEdit]:
34 """Build ordered edits for generated imports and top-level snippets."""
35 edits = []
36 import_nodes = [node for node in ast.parse(source_text).body if isinstance(node, (ast.Import, ast.ImportFrom))]
37 if import_nodes:
38 # Component bases must follow the complete last import, not its line start.
39 import_end = sum(len(line) for line in source_text.splitlines(keepends=True)[:import_nodes[-1].end_lineno])
40 lines = _render_imports(source_text, imports)
41 if lines:
42 edits.append(insert_after_imports(
43 source_text,
44 import_end,
45 "\n" + "\n".join(lines) + "\n",
46 default_offset=docstring_end or 0,
47 ))
48 parts = _render_snippets(source_text, snippets)
49 if parts:
50 edits.append(insert_after_imports(
51 source_text,
52 import_end,
53 "\n\n" + "\n\n".join(parts) + "\n",
54 default_offset=docstring_end or 0,
55 ))
56 return edits
59def _render_snippets(source_text: str, snippets: Iterable[ModuleSnippetPatch]) -> list[str]:
60 """Keep shared native definitions once, rejecting conflicting source bindings."""
61 definitions = _declared_bindings(source_text)
62 parts = []
63 for snippet in snippets:
64 text = snippet.text.strip("\n")
65 if not text or text in parts:
66 continue
67 current = _declared_bindings(text)
68 for name, definition in current.items():
69 if name in definitions and definitions[name] != definition:
70 raise ValueError(f"codegen: conflicting source definition {name!r}")
71 if current and current.keys() <= definitions.keys():
72 continue
73 definitions.update(current)
74 parts.append(text)
75 return parts
78def _declared_bindings(source: str) -> dict[str, str]:
79 """Index native definitions and early-bound aliases without evaluating them."""
80 result = {}
81 for node in ast.parse(source).body:
82 if isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
83 result[node.name] = ast.dump(node)
84 elif isinstance(node, (ast.Assign, ast.AnnAssign)):
85 targets = node.targets if isinstance(node, ast.Assign) else (node.target,)
86 for target in targets:
87 for name in ast.walk(target):
88 if isinstance(name, ast.Name) and isinstance(name.ctx, ast.Store):
89 result[name.id] = ast.dump(node)
90 return result
93def _render_imports(
94 source_text: str, imports: Iterable[ImportPatch]
95) -> list[str]:
96 """Render import patches as deduplicated, grouped import lines."""
97 grouped: dict[str, set[str]] = defaultdict(set)
98 lines: list[str] = []
99 for patch in imports:
100 if patch.raw:
101 if patch.raw not in source_text and patch.raw not in lines:
102 lines.append(patch.raw)
103 continue
104 grouped[patch.module].update(patch.names)
105 for module in sorted(grouped):
106 line = f"from {module} import {', '.join(sorted(grouped[module]))}"
107 if line not in source_text:
108 lines.append(line)
109 return lines
112__all__ = ["declaration_edits"]