Repository navigation
Expand file tree
/
Copy path_codegen_inject.py
More file actions
196 lines (168 loc) · 6.83 KB
/
Copy path_codegen_inject.py
File metadata and controls
196 lines (168 loc) · 6.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# Copyright (c) 2026 Jonathan Embley-Riches. All rights reserved.
"""URLab codegen — text-injection machinery.
Pure text operations: locate ``// --- CODEGEN_<tag>_START/END ---``
marker pairs in a source file, splice a body between them, and emit
diagnostics when the body has unbalanced braces or the markers are
missing.
The brace-aware helpers (``_find_matching_brace``,
``_strip_cpp_braces_in_strings``, ``_check_brace_balance``) live
here too because the banner-overwrite audit + the brace-balance
gate both consume them."""
from __future__ import annotations
import os
import re
from typing import Dict, List, Optional, Sequence, Tuple
from _codegen_core import _diag_add, FileWrite
def _make_tag_pair(tag: str) -> Tuple[str, str]:
return (f"// --- CODEGEN_{tag}_START ---", f"// --- CODEGEN_{tag}_END ---")
def _strip_cpp_braces_in_strings(text: str) -> str:
"""Remove characters that look like braces but live inside a
string/char literal or comment. Used by ``_check_brace_balance``
so a diagnostic message containing ``"{"`` doesn't trip the
balance gate."""
text = re.sub(r"//[^\n]*", "", text)
text = re.sub(r"/\*.*?\*/", "", text, flags=re.DOTALL)
text = re.sub(r'"(?:\\.|[^"\\])*"', '""', text)
text = re.sub(r"'(?:\\.|[^'\\])*'", "''", text)
return text
def _find_matching_brace(text: str, open_idx: int) -> Optional[int]:
"""Return the index of the ``}`` matching the ``{`` at
``open_idx``. Tracks brace depth across string/char literals and
line/block comments so a nested ``{`` inside a TEXT(...) literal
doesn't shift the balance. Returns None on EOF / unmatched."""
if open_idx < 0 or open_idx >= len(text) or text[open_idx] != "{":
return None
depth = 1
i = open_idx + 1
in_str: Optional[str] = None
while i < len(text) and depth > 0:
ch = text[i]
if in_str is not None:
if ch == "\\" and i + 1 < len(text):
i += 2
continue
if ch == in_str:
in_str = None
i += 1
continue
if ch == "/" and i + 1 < len(text) and text[i + 1] == "/":
nl = text.find("\n", i)
i = nl if nl != -1 else len(text)
continue
if ch == "/" and i + 1 < len(text) and text[i + 1] == "*":
end = text.find("*/", i + 2)
i = end + 2 if end != -1 else len(text)
continue
if ch in ('"', "'"):
in_str = ch
elif ch == "{":
depth += 1
elif ch == "}":
depth -= 1
if depth == 0:
return i
i += 1
return None
def _check_brace_balance(body: str, tag: str, source: str) -> None:
"""Emit a diagnostic when an injected block has an obvious brace
imbalance."""
stripped = _strip_cpp_braces_in_strings(body)
opens = stripped.count("{")
closes = stripped.count("}")
if opens != closes:
_diag_add(
f"[diagnostic] {source}: injected block for tag "
f"CODEGEN_{tag} has unbalanced braces (open={opens}, "
f"close={closes}). The generated .cpp will not compile.",
source=source,
)
_TAG_PATTERN_CACHE: Dict[str, "re.Pattern[str]"] = {}
def _tag_pattern(tag: str) -> "re.Pattern[str]":
pat = _TAG_PATTERN_CACHE.get(tag)
if pat is None:
start, end = _make_tag_pair(tag)
pat = re.compile(
r"([ \t]*)(" + re.escape(start) + r")(.*?)([ \t]*)(" + re.escape(end) + r")",
re.DOTALL,
)
_TAG_PATTERN_CACHE[tag] = pat
return pat
def inject_between_tags(file_text: str, tag: str, new_inner: str,
*, balance_source: Optional[str] = None) -> Tuple[str, bool]:
"""Replace the content between ``// --- CODEGEN_<tag>_START ---``
and ``// --- CODEGEN_<tag>_END ---`` with ``new_inner``. Returns
(new_text, was_found).
The END marker's leading whitespace is rewritten to match the
START marker's indent. When ``new_inner`` is empty or
whitespace-only the block collapses so START + END sit on
adjacent lines with no stray blank line between them.
When ``balance_source`` is set, emit a diagnostic if the injected
block has unbalanced braces."""
pattern = _tag_pattern(tag)
matched = [False]
def repl(m: re.Match) -> str:
matched[0] = True
start_indent = m.group(1)
trimmed = new_inner.rstrip()
if trimmed:
body = "\n" + trimmed + "\n" + start_indent
else:
# Empty body: collapse to one newline so START + END sit
# adjacent (no stray blank line between them).
body = "\n" + start_indent
return m.group(1) + m.group(2) + body + m.group(5)
new_text = pattern.sub(repl, file_text)
if matched[0] and balance_source:
_check_brace_balance(new_inner, tag, balance_source)
return new_text, matched[0]
def _inject_tags_into_cpp(
cpp_path: str,
tagged_bodies: Sequence[Tuple[str, str]],
writes: List[FileWrite],
*,
diag_source: str,
) -> None:
"""Open ``cpp_path`` once, inject every (tag, body) pair, surface
a diagnostic for each missing marker pair, append (or update) a
single FileWrite if any tag actually changed the text.
Phase ordering: earlier phases (e.g. ``_phase_categories``) may have
queued a FileWrite for the same path. Reading from disk in that case
would be stale — the later phase would inject into the PRE-cleanup
text and the post-cleanup IMPORT/EXPORT block would be lost on
apply. Use the pending write's content when present, and replace
it in-place so duplicate FileWrites for the same path don't show
up in ``apply_writes``."""
pending_idx: Optional[int] = None
for i in range(len(writes) - 1, -1, -1):
if writes[i].path == cpp_path:
pending_idx = i
break
if pending_idx is not None:
text = writes[pending_idx].content
elif os.path.exists(cpp_path):
with open(cpp_path, "r", encoding="utf-8") as f:
text = f.read()
else:
_diag_add(
f"[diagnostic] {diag_source}: host .cpp '{cpp_path}' does "
f"not exist; no blocks injected.",
source=diag_source,
)
return
new_text = text
for tag, body in tagged_bodies:
new_text, ok = inject_between_tags(
new_text, tag, body, balance_source=diag_source,
)
if not ok:
_diag_add(
f"[diagnostic] {diag_source}: '{cpp_path}' is missing "
f"the CODEGEN_{tag}_START/END marker pair.",
source=diag_source,
)
if new_text == text:
return
if pending_idx is not None:
writes[pending_idx] = FileWrite(path=cpp_path, content=new_text)
else:
writes.append(FileWrite(path=cpp_path, content=new_text))