Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / codegen / astkit / edits.py: 89%
44 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"""Positional text edits over a modeling source.
17The forward lowerer (emit/parallel) turns a collection of structural plan
18(index.py) into a list of ``TextEdit``s and replays them. All offsets are byte
19offsets into the *original* text; ``apply_edits`` validates ordering and never
20edits the same span twice, so a malformed edit set fails loudly instead of
21silently corrupting the file.
23Only the edits are positional; every helper that builds an edit from a
24``FunctionInfo`` / span does the spelling itself. Nothing here imports torch.
25"""
26from __future__ import annotations
28from dataclasses import dataclass
29from typing import Optional, Sequence
32@dataclass
33class TextEdit:
34 """One ``[start, end)`` byte-span replacement in a source string."""
36 start: int
37 end: int
38 replacement: str
40 def __post_init__(self) -> None:
41 if self.start < 0 or self.end < self.start:
42 raise ValueError(
43 f"TextEdit has an invalid span: start={self.start} end={self.end}"
44 )
47def apply_edits(text: str, edits: Sequence[TextEdit]) -> str:
48 """Replay ``edits`` on ``text``, earliest-first for stable ordering.
50 Edits are authored against the *original* text. Applying one splice shifts
51 every later offset by the edit's length delta, so each edit is re-anchored
52 by the cumulative drift of the edits before it. Edits must be
53 non-overlapping and stay within the original text — checked up front.
54 """
55 ordered = sorted(edits, key=lambda e: (e.start, e.end))
56 if ordered:
57 prev_end = ordered[0].start
58 for edit in ordered:
59 if edit.start < prev_end:
60 raise ValueError(
61 f"apply_edits: overlapping edits — [{edit.start}, {edit.end}) "
62 f"overlaps the previous edit ending at {prev_end}"
63 )
64 if edit.end > len(text):
65 raise ValueError(
66 f"apply_edits: edit [{edit.start}, {edit.end}) exceeds text "
67 f"length {len(text)}"
68 )
69 prev_end = edit.end
71 out = list(text)
72 shift = 0
73 for edit in ordered:
74 start = edit.start + shift
75 end = edit.end + shift
76 replacement = edit.replacement
77 out[start:end] = replacement
78 shift += len(replacement) - (edit.end - edit.start)
79 return "".join(out)
82def replace_function_body(
83 source_text: str,
84 func: "FunctionInfo",
85 new_body: str,
86 *,
87 indent: str = " ",
88) -> tuple[TextEdit, ...]:
89 """Build the edit that swaps ``func``'s body for ``new_body``.
91 ``new_body`` is the replacement body WITHOUT line indentation — every line
92 is re-indented to the method's existing indent (``func``'s first body
93 statement). A docstring inside the body is preserved by the caller (the
94 lowerer emits it explicitly). A single-line/pass body has no replaceable
95 span: the whole method is rewritten as ``def <name>(...):\n<indented body>``
96 from the file text's own signature line.
98 Returns an empty tuple when there is nothing to replace (a function with
99 no body span and no way to anchor).
100 """
101 if func.body_start is None or func.body_end is None:
102 return ()
103 # Re-indent per line, preserving blank lines and inner indentation. The
104 # caller renders ``new_body`` at column-0-relative depth (blank lines carry
105 # no indentation), so a statement's relative nesting survives; only the
106 # method's own ``indent`` is applied once.
107 body_lines = [
108 (indent + line) if line.strip() else ""
109 for line in new_body.splitlines(keepends=True)
110 ]
111 replacement = "".join(body_lines)
112 # Composed source can place the next class directly after the consumed newline.
113 if not replacement.endswith("\n") and source_text[func.body_end:func.body_end + 1] not in ("", "\n", "\r"):
114 replacement += "\n"
115 return (TextEdit(func.body_start, func.body_end, replacement),)
118def insert_after_imports(
119 source_text: str,
120 import_end: Optional[int],
121 insert_text: str,
122 *,
123 default_offset: int = 0,
124) -> Optional[TextEdit]:
125 """Build an edit inserting ``insert_text`` right after the import block.
127 ``import_end`` is the byte offset just past the last import statement. A
128 ``None`` ``import_end`` means no import block: fall back to
129 ``default_offset`` (the docstring end or 0). Returns ``None`` when there is
130 no sensible anchor — caller treats that as "insert at the top".
131 """
132 anchor = import_end if import_end is not None else default_offset
133 if anchor < 0 or anchor > len(source_text):
134 return None
135 # Keep the inserted text on its own lines, bracketed by newlines, so it
136 # never glues onto a trailing comment or the first statement.
137 return TextEdit(anchor, anchor, "\n" + insert_text + "\n")
140__all__ = [
141 "TextEdit",
142 "apply_edits",
143 "insert_after_imports",
144 "replace_function_body",
145]