doppelcode 0.7.0b5.post1__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.
- doppelcode/__init__.py +3 -0
- doppelcode/__main__.py +5 -0
- doppelcode/aliascheck.py +316 -0
- doppelcode/analyze.py +103 -0
- doppelcode/cli.py +462 -0
- doppelcode/cmake_words.py +621 -0
- doppelcode/commentkeep.py +79 -0
- doppelcode/config.py +156 -0
- doppelcode/declare.py +364 -0
- doppelcode/encodingfix.py +124 -0
- doppelcode/headers.py +115 -0
- doppelcode/keepset.py +84 -0
- doppelcode/languages.py +168 -0
- doppelcode/ledger.py +233 -0
- doppelcode/lexer.py +294 -0
- doppelcode/merge.py +86 -0
- doppelcode/project.py +2343 -0
- doppelcode/pyharvest.py +121 -0
- doppelcode/pyparse.py +14 -0
- doppelcode/secretconst.py +899 -0
- doppelcode/strhide.py +188 -0
- doppelcode/toolchains.py +192 -0
- doppelcode/translate.py +599 -0
- doppelcode/vault.py +85 -0
- doppelcode/withhold.py +151 -0
- doppelcode-0.7.0b5.post1.dist-info/METADATA +418 -0
- doppelcode-0.7.0b5.post1.dist-info/RECORD +31 -0
- doppelcode-0.7.0b5.post1.dist-info/WHEEL +5 -0
- doppelcode-0.7.0b5.post1.dist-info/entry_points.txt +2 -0
- doppelcode-0.7.0b5.post1.dist-info/licenses/LICENSE +77 -0
- doppelcode-0.7.0b5.post1.dist-info/top_level.txt +1 -0
doppelcode/ledger.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""Exposure ledger: what code was made available to an AI, and when.
|
|
2
|
+
|
|
3
|
+
File ``.doppel/ledger.jsonl`` - one JSON object per line, append-only, kept forever (an audit trail):
|
|
4
|
+
|
|
5
|
+
{"time": "...Z", "event": "export", "session": "s_0007", "file": "src/resample.c",
|
|
6
|
+
"symbol": "resample_block", "kind": "body", "sha": "<hash of the normalised body>"}
|
|
7
|
+
|
|
8
|
+
Events: ``export`` (a function body or a secret alias written into the twin), ``msgobf`` (a message
|
|
9
|
+
hidden by the message tool contained a whole function body of the project), ``override`` (export ran
|
|
10
|
+
over an exposure budget). It records what was *made available*, not what an AI actually read.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import ast
|
|
16
|
+
import hashlib
|
|
17
|
+
import json
|
|
18
|
+
import re
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from datetime import datetime, timezone
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
from . import lexer
|
|
24
|
+
from . import pyparse
|
|
25
|
+
from .languages import LANGUAGES
|
|
26
|
+
|
|
27
|
+
LEDGER = "ledger.jsonl"
|
|
28
|
+
_SKIP = (lexer.WS, lexer.NEWLINE, lexer.COMMENT)
|
|
29
|
+
_NOT_FUNCS = {"if", "for", "while", "switch", "catch", "return", "sizeof", "do", "else", "using", "lock", "fixed",
|
|
30
|
+
"foreach", "synchronized", "with", "elif", "try", "unsafe", "checked", "unchecked", "when", "until",
|
|
31
|
+
"function", "typeof", "decltype", "alignof", "defined", "assert", "static_assert", "case", "throw",
|
|
32
|
+
"new", "delete", "await", "yield", "in", "of", "is", "as", "not", "and", "or", "lambda"}
|
|
33
|
+
_SCOPES = {"class", "struct", "namespace", "interface", "enum", "record", "union", "impl", "object"}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class Function:
|
|
38
|
+
symbol: str # qualified name in the original: Class.method, namespace.func
|
|
39
|
+
sha: str # hash of the body with whitespace normalised
|
|
40
|
+
start_line: int
|
|
41
|
+
end_line: int
|
|
42
|
+
body_start: int = -1 # character offsets of the body: '{' .. '}' inclusive, or Python's first
|
|
43
|
+
body_end: int = -1 # statement (docstring included) .. end of the function
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def body_hash(text: str) -> str:
|
|
47
|
+
return hashlib.sha256(re.sub(r"\s+", " ", text).strip().encode("utf-8", errors="surrogateescape")).hexdigest()[:16]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def functions(src: str, lang: str) -> list[Function]:
|
|
51
|
+
"""Functions (with bodies) of one source file. Python from the syntax tree, the others from the
|
|
52
|
+
lexer: a name, its parameter list and a brace-matched body."""
|
|
53
|
+
if lang == "python":
|
|
54
|
+
return _python_functions(src)
|
|
55
|
+
if lang not in LANGUAGES:
|
|
56
|
+
return []
|
|
57
|
+
toks, line, pos, offs = [], 1, 0, []
|
|
58
|
+
for t in lexer.tokenize(src, lang):
|
|
59
|
+
if t.kind not in _SKIP and t.directive is None:
|
|
60
|
+
toks.append((t, line))
|
|
61
|
+
offs.append(pos)
|
|
62
|
+
line += t.text.count("\n")
|
|
63
|
+
pos += len(t.text)
|
|
64
|
+
texts = [t.text for t, _ in toks]
|
|
65
|
+
lines = src.splitlines()
|
|
66
|
+
out: list[Function] = []
|
|
67
|
+
scopes: list[tuple[str, int]] = [] # (name, brace depth at which it ends)
|
|
68
|
+
depth, i = 0, 0
|
|
69
|
+
pending_scope: str | None = None
|
|
70
|
+
while i < len(toks):
|
|
71
|
+
t, ln = toks[i]
|
|
72
|
+
if t.kind == lexer.IDENT and t.text in _SCOPES and i + 1 < len(toks) and toks[i + 1][0].kind == lexer.IDENT:
|
|
73
|
+
pending_scope = toks[i + 1][0].text
|
|
74
|
+
if texts[i] == "{":
|
|
75
|
+
depth += 1
|
|
76
|
+
if pending_scope:
|
|
77
|
+
scopes.append((pending_scope, depth))
|
|
78
|
+
pending_scope = None
|
|
79
|
+
elif texts[i] == "}":
|
|
80
|
+
if scopes and scopes[-1][1] == depth:
|
|
81
|
+
scopes.pop()
|
|
82
|
+
depth -= 1
|
|
83
|
+
elif texts[i] == ";":
|
|
84
|
+
pending_scope = None
|
|
85
|
+
elif t.kind == lexer.IDENT and t.text not in _NOT_FUNCS and i + 1 < len(toks) and texts[i + 1] == "(":
|
|
86
|
+
j, d = i + 1, 0
|
|
87
|
+
while j < len(toks): # the parameter list
|
|
88
|
+
d += texts[j] == "("
|
|
89
|
+
d -= texts[j] == ")"
|
|
90
|
+
if d == 0:
|
|
91
|
+
break
|
|
92
|
+
j += 1
|
|
93
|
+
k = j + 1
|
|
94
|
+
if k < len(toks) and texts[k] == ":" and (k + 1 >= len(toks) or texts[k + 1] != ":"):
|
|
95
|
+
d = 0 # C++ constructor: skip the initializer list
|
|
96
|
+
while k < len(toks) and k - j < 200 and not (texts[k] == "{" and d == 0):
|
|
97
|
+
d += texts[k] == "("
|
|
98
|
+
d -= texts[k] == ")"
|
|
99
|
+
k += 1
|
|
100
|
+
while k < len(toks) and texts[k] not in ("{", ";", "=", ",", ")") and k - j < 12:
|
|
101
|
+
k += 1 # const, noexcept, throws X, -> T
|
|
102
|
+
is_call = i > 0 and texts[i - 1] in (".", "new", "=", "return")
|
|
103
|
+
if k < len(toks) and texts[k] == "{" and not is_call:
|
|
104
|
+
e, d = k, 0
|
|
105
|
+
while e < len(toks):
|
|
106
|
+
d += texts[e] == "{"
|
|
107
|
+
d -= texts[e] == "}"
|
|
108
|
+
if d == 0:
|
|
109
|
+
break
|
|
110
|
+
e += 1
|
|
111
|
+
end_line = toks[min(e, len(toks) - 1)][1]
|
|
112
|
+
prefix = ".".join(s for s, _ in scopes)
|
|
113
|
+
name = (prefix + "." if prefix else "") + t.text.replace("::", ".")
|
|
114
|
+
if i >= 2 and texts[i - 1] == "::":
|
|
115
|
+
name = toks[i - 2][0].text + "." + name
|
|
116
|
+
elif i >= 3 and texts[i - 1] == ":" and texts[i - 2] == ":":
|
|
117
|
+
name = (prefix + "." if prefix else "") + toks[i - 3][0].text + "." + t.text
|
|
118
|
+
n = sum(1 for f in out if f.symbol == name or f.symbol.startswith(name + "#"))
|
|
119
|
+
if n:
|
|
120
|
+
name += f"#{n + 1}" # overloads: checksum, checksum#2
|
|
121
|
+
body = "\n".join(lines[ln - 1:end_line])
|
|
122
|
+
e_last = min(e, len(toks) - 1)
|
|
123
|
+
out.append(Function(name, body_hash(body), ln, end_line, offs[k],
|
|
124
|
+
offs[e_last] + len(texts[e_last])))
|
|
125
|
+
i = e + 1
|
|
126
|
+
continue
|
|
127
|
+
i += 1
|
|
128
|
+
return out
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _python_functions(src: str) -> list[Function]:
|
|
132
|
+
try:
|
|
133
|
+
tree = pyparse.parse(src)
|
|
134
|
+
except SyntaxError:
|
|
135
|
+
return []
|
|
136
|
+
lines = src.splitlines()
|
|
137
|
+
keep = src.splitlines(keepends=True)
|
|
138
|
+
starts = [0]
|
|
139
|
+
for ln in keep:
|
|
140
|
+
starts.append(starts[-1] + len(ln))
|
|
141
|
+
|
|
142
|
+
def offset(lineno: int, col_bytes: int) -> int:
|
|
143
|
+
text = keep[lineno - 1] if lineno - 1 < len(keep) else ""
|
|
144
|
+
return starts[lineno - 1] + len(text.encode("utf-8", errors="surrogateescape")[:col_bytes].decode("utf-8", errors="ignore"))
|
|
145
|
+
|
|
146
|
+
out: list[Function] = []
|
|
147
|
+
|
|
148
|
+
def visit(node, prefix: str) -> None:
|
|
149
|
+
for child in ast.iter_child_nodes(node):
|
|
150
|
+
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
151
|
+
name = prefix + child.name
|
|
152
|
+
end = child.end_lineno or child.lineno
|
|
153
|
+
start = min([d.lineno for d in child.decorator_list] + [child.lineno])
|
|
154
|
+
first = child.body[0]
|
|
155
|
+
out.append(Function(name, body_hash("\n".join(lines[start - 1:end])), start, end,
|
|
156
|
+
offset(first.lineno, first.col_offset),
|
|
157
|
+
offset(child.end_lineno, child.end_col_offset)))
|
|
158
|
+
visit(child, name + ".")
|
|
159
|
+
elif isinstance(child, ast.ClassDef):
|
|
160
|
+
visit(child, prefix + child.name + ".")
|
|
161
|
+
else:
|
|
162
|
+
visit(child, prefix)
|
|
163
|
+
visit(tree, "")
|
|
164
|
+
return out
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
# ---------------------------------------------------------------------------------------------- file
|
|
168
|
+
def now() -> str:
|
|
169
|
+
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def read(state_dir: Path) -> list[dict]:
|
|
173
|
+
p = state_dir / LEDGER
|
|
174
|
+
if not p.is_file():
|
|
175
|
+
return []
|
|
176
|
+
out = []
|
|
177
|
+
for line in p.read_text(encoding="utf-8").splitlines():
|
|
178
|
+
line = line.strip()
|
|
179
|
+
if line:
|
|
180
|
+
try:
|
|
181
|
+
out.append(json.loads(line))
|
|
182
|
+
except ValueError:
|
|
183
|
+
continue # a damaged line never stops the report
|
|
184
|
+
return out
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def append(state_dir: Path, events: list[dict]) -> None:
|
|
188
|
+
if not events:
|
|
189
|
+
return
|
|
190
|
+
state_dir.mkdir(parents=True, exist_ok=True)
|
|
191
|
+
with (state_dir / LEDGER).open("a", encoding="utf-8") as fh:
|
|
192
|
+
for e in events:
|
|
193
|
+
fh.write(json.dumps(e, ensure_ascii=False) + "\n")
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def last_sent(events: list[dict]) -> dict[tuple[str, str], dict]:
|
|
197
|
+
"""(file, symbol) -> the last body event."""
|
|
198
|
+
out: dict[tuple[str, str], dict] = {}
|
|
199
|
+
for e in events:
|
|
200
|
+
if e.get("kind") == "body":
|
|
201
|
+
out[(e.get("file", ""), e.get("symbol", ""))] = e
|
|
202
|
+
return out
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def folder_of(rel: str) -> str:
|
|
206
|
+
return rel.rsplit("/", 1)[0] + "/" if "/" in rel else "./"
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
# ---------------------------------------------------------------------------------------------- msgobf
|
|
210
|
+
def record_message(project_root: Path, text: str, lang: str | None, state_dir_name: str | None = None) -> int:
|
|
211
|
+
"""The message tool hid ``text`` for an AI: log every whole function body of the project in it.
|
|
212
|
+
Returns the number of bodies found. Never raises (the message tool must not fail because of it)."""
|
|
213
|
+
try:
|
|
214
|
+
from .project import Project
|
|
215
|
+
if not lang:
|
|
216
|
+
return 0
|
|
217
|
+
found = {f.sha: f for f in functions(text, lang)}
|
|
218
|
+
if not found:
|
|
219
|
+
return 0
|
|
220
|
+
proj = Project(project_root)
|
|
221
|
+
files, _ = proj.scan()
|
|
222
|
+
events = []
|
|
223
|
+
for f in files:
|
|
224
|
+
if f.excluded or f.mode != lang and not (lang in ("c", "cpp") and f.mode in ("c", "cpp")):
|
|
225
|
+
continue
|
|
226
|
+
for fn in functions(f.data.decode("utf-8", errors="replace"), f.mode):
|
|
227
|
+
if fn.sha in found:
|
|
228
|
+
events.append({"time": now(), "event": "msgobf", "session": "msgobf", "file": f.rel,
|
|
229
|
+
"symbol": fn.symbol, "kind": "body", "sha": fn.sha})
|
|
230
|
+
append(Path(project_root) / state_dir_name if state_dir_name else proj.state_dir, events)
|
|
231
|
+
return len(events)
|
|
232
|
+
except Exception: # noqa: BLE001 - logging only
|
|
233
|
+
return 0
|
doppelcode/lexer.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
"""Lossless lexer for C, C++, C#, Java, JavaScript, TypeScript and Python.
|
|
2
|
+
|
|
3
|
+
``tokenize(src, lang)`` returns a list of Token objects whose texts concatenate back to ``src``
|
|
4
|
+
exactly. Only the token kinds that matter for renaming are distinguished; everything else is kept
|
|
5
|
+
as opaque text. ``lang`` is a key of languages.LANGUAGES (default "c").
|
|
6
|
+
|
|
7
|
+
String forms handled per language:
|
|
8
|
+
C / C++ "..." '...' with L u U u8 prefixes, C++ raw R"delim(...)delim"
|
|
9
|
+
C# "..." '...' @"verbatim" $"interpolated" $@"..." @$"..." and raw triple-quoted strings
|
|
10
|
+
Java "..." '...' and triple-quoted text blocks
|
|
11
|
+
JS / TS "..." '...' (both strings) and `template ${literals}`
|
|
12
|
+
Python '...' "..." and triple-quoted strings, with r b u f prefixes (an f-string is one token)
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import re
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
|
|
20
|
+
from .languages import LANGUAGES
|
|
21
|
+
|
|
22
|
+
IDENT = "ident"
|
|
23
|
+
NUMBER = "number"
|
|
24
|
+
STRING = "string"
|
|
25
|
+
CHAR = "char"
|
|
26
|
+
COMMENT = "comment"
|
|
27
|
+
WS = "ws"
|
|
28
|
+
NEWLINE = "newline"
|
|
29
|
+
PUNCT = "punct"
|
|
30
|
+
HEADER = "header" # <file.h> or "file.h" after #include
|
|
31
|
+
DIRECTIVE = "directive" # the name right after '#' at line start (define, include, region, ...)
|
|
32
|
+
|
|
33
|
+
_IDENT_RE = re.compile(r"[^\W\d]\w*")
|
|
34
|
+
_PPNUM_RE = re.compile(r"\.?\d(?:[eEpP][+-]|[\w.'])*")
|
|
35
|
+
_WS_RE = re.compile(r"[ \t\r\f\v]+")
|
|
36
|
+
_C_STRING_PREFIXES = {"L", "u", "U", "u8"}
|
|
37
|
+
_CPP_RAW_PREFIXES = {"R", "LR", "uR", "UR", "u8R"}
|
|
38
|
+
|
|
39
|
+
INCLUDE_DIRECTIVES = {"include", "include_next", "import"}
|
|
40
|
+
# Directives whose identifiers are "conditions" (external config macros / C# symbols).
|
|
41
|
+
COND_DIRECTIVES = {"if", "ifdef", "ifndef", "elif", "elifdef", "elifndef", "undef"}
|
|
42
|
+
# Directives whose words are free text / compiler words.
|
|
43
|
+
TEXT_DIRECTIVES = {"pragma", "error", "warning", "line", "ident", "sccs", "region", "endregion", "nullable"}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(slots=True)
|
|
47
|
+
class Token:
|
|
48
|
+
kind: str
|
|
49
|
+
text: str
|
|
50
|
+
directive: str | None = None # name of the preprocessor directive this token is part of
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _scan_quoted(src: str, i: int, quote: str, multiline: bool = False) -> int:
|
|
54
|
+
"""Return index just past the closing quote (or end of line if unterminated)."""
|
|
55
|
+
n = len(src)
|
|
56
|
+
j = i + 1
|
|
57
|
+
while j < n:
|
|
58
|
+
c = src[j]
|
|
59
|
+
if c == "\\" and j + 1 < n:
|
|
60
|
+
j += 2
|
|
61
|
+
continue
|
|
62
|
+
if c == quote:
|
|
63
|
+
return j + 1
|
|
64
|
+
if c == "\n" and not multiline:
|
|
65
|
+
return j
|
|
66
|
+
j += 1
|
|
67
|
+
return n
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _scan_verbatim(src: str, i: int) -> int:
|
|
71
|
+
"""C# @"..." : no escapes, "" is a quote, may span lines. ``i`` is at the opening quote."""
|
|
72
|
+
n = len(src)
|
|
73
|
+
j = i + 1
|
|
74
|
+
while j < n:
|
|
75
|
+
if src[j] == '"':
|
|
76
|
+
if j + 1 < n and src[j + 1] == '"':
|
|
77
|
+
j += 2
|
|
78
|
+
continue
|
|
79
|
+
return j + 1
|
|
80
|
+
j += 1
|
|
81
|
+
return n
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _scan_quote_run(src: str, i: int) -> int:
|
|
85
|
+
"""C# raw / Java text block: N>=3 quotes ... the same N quotes. ``i`` is at the first quote."""
|
|
86
|
+
k = i
|
|
87
|
+
while k < len(src) and src[k] == '"':
|
|
88
|
+
k += 1
|
|
89
|
+
run = k - i
|
|
90
|
+
end = src.find('"' * run, k)
|
|
91
|
+
return len(src) if end < 0 else end + run
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _scan_cpp_raw(src: str, i: int) -> int:
|
|
95
|
+
"""C++ R"delim( ... )delim". ``i`` is at the opening quote."""
|
|
96
|
+
paren = src.find("(", i + 1)
|
|
97
|
+
if paren < 0 or paren - i > 17:
|
|
98
|
+
return _scan_quoted(src, i, '"')
|
|
99
|
+
delim = src[i + 1:paren]
|
|
100
|
+
end = src.find(")" + delim + '"', paren + 1)
|
|
101
|
+
return len(src) if end < 0 else end + len(delim) + 2
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _line_comment_end(src: str, i: int) -> int:
|
|
105
|
+
n = len(src)
|
|
106
|
+
j = i + 2
|
|
107
|
+
while j < n:
|
|
108
|
+
if src[j] == "\n":
|
|
109
|
+
k = j - 1
|
|
110
|
+
if k >= 0 and src[k] == "\r":
|
|
111
|
+
k -= 1
|
|
112
|
+
if k >= 0 and src[k] == "\\": # line continuation inside // comment
|
|
113
|
+
j += 1
|
|
114
|
+
continue
|
|
115
|
+
return j
|
|
116
|
+
j += 1
|
|
117
|
+
return n
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def tokenize(src: str, lang: str = "c") -> list[Token]:
|
|
121
|
+
if lang == "python":
|
|
122
|
+
return _tokenize_python(src)
|
|
123
|
+
profile = LANGUAGES.get(lang, LANGUAGES["c"])
|
|
124
|
+
c_family = lang in ("c", "cpp")
|
|
125
|
+
tokens: list[Token] = []
|
|
126
|
+
append = tokens.append
|
|
127
|
+
i = 0
|
|
128
|
+
n = len(src)
|
|
129
|
+
line_start = True
|
|
130
|
+
directive: str | None = None
|
|
131
|
+
expect_directive_name = False
|
|
132
|
+
|
|
133
|
+
while i < n:
|
|
134
|
+
c = src[i]
|
|
135
|
+
|
|
136
|
+
if c == "\n":
|
|
137
|
+
append(Token(NEWLINE, c))
|
|
138
|
+
i += 1
|
|
139
|
+
line_start = True
|
|
140
|
+
directive = None
|
|
141
|
+
expect_directive_name = False
|
|
142
|
+
continue
|
|
143
|
+
|
|
144
|
+
if c == "\\":
|
|
145
|
+
m = re.match(r"\\\r?\n", src[i:i + 3])
|
|
146
|
+
if m:
|
|
147
|
+
append(Token(WS, m.group(0), directive))
|
|
148
|
+
i += len(m.group(0))
|
|
149
|
+
continue
|
|
150
|
+
|
|
151
|
+
m = _WS_RE.match(src, i)
|
|
152
|
+
if m:
|
|
153
|
+
append(Token(WS, m.group(0), directive))
|
|
154
|
+
i = m.end()
|
|
155
|
+
continue
|
|
156
|
+
|
|
157
|
+
if c == "/" and i + 1 < n:
|
|
158
|
+
nxt = src[i + 1]
|
|
159
|
+
if nxt == "/":
|
|
160
|
+
j = _line_comment_end(src, i)
|
|
161
|
+
append(Token(COMMENT, src[i:j], directive))
|
|
162
|
+
i = j
|
|
163
|
+
continue
|
|
164
|
+
if nxt == "*":
|
|
165
|
+
j = src.find("*/", i + 2)
|
|
166
|
+
j = n if j < 0 else j + 2
|
|
167
|
+
append(Token(COMMENT, src[i:j], directive))
|
|
168
|
+
i = j
|
|
169
|
+
continue
|
|
170
|
+
|
|
171
|
+
if c_family and directive in INCLUDE_DIRECTIVES and c in "<\"":
|
|
172
|
+
close = ">" if c == "<" else "\""
|
|
173
|
+
j = src.find(close, i + 1)
|
|
174
|
+
eol = src.find("\n", i + 1)
|
|
175
|
+
if j >= 0 and (eol < 0 or j < eol):
|
|
176
|
+
append(Token(HEADER, src[i:j + 1], directive))
|
|
177
|
+
i = j + 1
|
|
178
|
+
line_start = False
|
|
179
|
+
continue
|
|
180
|
+
|
|
181
|
+
# C# special strings: @"..." $"..." $@"..." @$"..." and raw """...""" (also $"""...""")
|
|
182
|
+
if lang == "csharp" and c in "@$":
|
|
183
|
+
m = re.match(r'(?:\$+@?|@\$*)(?=")', src[i:i + 8])
|
|
184
|
+
if m:
|
|
185
|
+
q = i + len(m.group(0))
|
|
186
|
+
if src.startswith('"""', q):
|
|
187
|
+
j = _scan_quote_run(src, q)
|
|
188
|
+
elif "@" in m.group(0):
|
|
189
|
+
j = _scan_verbatim(src, q)
|
|
190
|
+
else:
|
|
191
|
+
j = _scan_quoted(src, q, '"')
|
|
192
|
+
append(Token(STRING, src[i:j], directive))
|
|
193
|
+
i = j
|
|
194
|
+
line_start = False
|
|
195
|
+
continue
|
|
196
|
+
|
|
197
|
+
if c == '"' and lang in ("csharp", "java") and src.startswith('"""', i):
|
|
198
|
+
j = _scan_quote_run(src, i)
|
|
199
|
+
append(Token(STRING, src[i:j], directive))
|
|
200
|
+
i = j
|
|
201
|
+
line_start = False
|
|
202
|
+
continue
|
|
203
|
+
|
|
204
|
+
if c == "`" and lang in ("javascript", "typescript"):
|
|
205
|
+
j = _scan_quoted(src, i, "`", multiline=True)
|
|
206
|
+
append(Token(STRING, src[i:j], directive))
|
|
207
|
+
i = j
|
|
208
|
+
line_start = False
|
|
209
|
+
continue
|
|
210
|
+
|
|
211
|
+
if c == "\"" or c == "'":
|
|
212
|
+
j = _scan_quoted(src, i, c)
|
|
213
|
+
kind = STRING if c == "\"" or not profile.char_quote else CHAR
|
|
214
|
+
append(Token(kind, src[i:j], directive))
|
|
215
|
+
i = j
|
|
216
|
+
line_start = False
|
|
217
|
+
continue
|
|
218
|
+
|
|
219
|
+
m = _IDENT_RE.match(src, i)
|
|
220
|
+
if m:
|
|
221
|
+
word = m.group(0)
|
|
222
|
+
end = m.end()
|
|
223
|
+
if c_family and end < n and src[end] == '"' and word in _CPP_RAW_PREFIXES and lang == "cpp":
|
|
224
|
+
j = _scan_cpp_raw(src, end)
|
|
225
|
+
append(Token(STRING, src[i:j], directive))
|
|
226
|
+
i = j
|
|
227
|
+
line_start = False
|
|
228
|
+
continue
|
|
229
|
+
if c_family and word in _C_STRING_PREFIXES and end < n and src[end] in "\"'":
|
|
230
|
+
q = src[end]
|
|
231
|
+
j = _scan_quoted(src, end, q)
|
|
232
|
+
append(Token(STRING if q == "\"" else CHAR, src[i:j], directive))
|
|
233
|
+
i = j
|
|
234
|
+
line_start = False
|
|
235
|
+
continue
|
|
236
|
+
if expect_directive_name:
|
|
237
|
+
directive = word
|
|
238
|
+
expect_directive_name = False
|
|
239
|
+
append(Token(DIRECTIVE, word, directive))
|
|
240
|
+
else:
|
|
241
|
+
append(Token(IDENT, word, directive))
|
|
242
|
+
i = end
|
|
243
|
+
line_start = False
|
|
244
|
+
continue
|
|
245
|
+
|
|
246
|
+
if c.isdigit() or (c == "." and i + 1 < n and src[i + 1].isdigit()):
|
|
247
|
+
m = _PPNUM_RE.match(src, i)
|
|
248
|
+
append(Token(NUMBER, m.group(0), directive))
|
|
249
|
+
i = m.end()
|
|
250
|
+
line_start = False
|
|
251
|
+
continue
|
|
252
|
+
|
|
253
|
+
if c == "#" and line_start and profile.preprocessor:
|
|
254
|
+
expect_directive_name = True
|
|
255
|
+
directive = ""
|
|
256
|
+
append(Token(PUNCT, c, directive))
|
|
257
|
+
i += 1
|
|
258
|
+
line_start = False
|
|
259
|
+
continue
|
|
260
|
+
|
|
261
|
+
append(Token(PUNCT, c, directive))
|
|
262
|
+
expect_directive_name = False
|
|
263
|
+
i += 1
|
|
264
|
+
line_start = False
|
|
265
|
+
|
|
266
|
+
return tokens
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
# -- Python -------------------------------------------------------------------------------------
|
|
270
|
+
_PY_TOKEN_RE = re.compile(r"""
|
|
271
|
+
(?P<nl>\r?\n)
|
|
272
|
+
| (?P<ws>[ \t\f\v\r]+|\\\r?\n)
|
|
273
|
+
| (?P<comment>\#[^\r\n]*)
|
|
274
|
+
| (?P<string>(?i:rb|br|rf|fr|r|b|u|f)?(?:'''[\s\S]*?(?:'''|\Z)|\"\"\"[\s\S]*?(?:\"\"\"|\Z)
|
|
275
|
+
|'(?:\\[\s\S]|[^'\\\r\n])*'?|"(?:\\[\s\S]|[^"\\\r\n])*"?))
|
|
276
|
+
| (?P<ident>[^\W\d]\w*)
|
|
277
|
+
| (?P<number>(?:0[xXoObB][\w]+|\d[\d_]*\.?[\d_]*(?:[eE][+-]?\d+)?[jJ]?|\.\d[\d_]*(?:[eE][+-]?\d+)?[jJ]?))
|
|
278
|
+
| (?P<punct>[\s\S])
|
|
279
|
+
""", re.X)
|
|
280
|
+
_PY_KIND = {"nl": NEWLINE, "ws": WS, "comment": COMMENT, "string": STRING, "ident": IDENT, "number": NUMBER,
|
|
281
|
+
"punct": PUNCT}
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _tokenize_python(src: str) -> list[Token]:
|
|
285
|
+
return [Token(_PY_KIND[m.lastgroup], m.group(0)) for m in _PY_TOKEN_RE.finditer(src)]
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def untokenize(tokens: list[Token]) -> str:
|
|
289
|
+
return "".join(t.text for t in tokens)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def significant(tokens: list[Token]) -> list[int]:
|
|
293
|
+
"""Indices of tokens that are not whitespace, newline or comment."""
|
|
294
|
+
return [k for k, t in enumerate(tokens) if t.kind not in (WS, NEWLINE, COMMENT)]
|
doppelcode/merge.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""3-way merge of AI edits (already de-obfuscated) into the original file.
|
|
2
|
+
|
|
3
|
+
Uses ``git merge-file`` when available. Result kinds:
|
|
4
|
+
"theirs" - original untouched since last sync: take the AI version
|
|
5
|
+
"ours" - AI made no effective change: keep the original
|
|
6
|
+
"merged" - both changed different regions: clean merge
|
|
7
|
+
"conflict" - overlapping changes: merged text contains conflict markers
|
|
8
|
+
"nomerge" - both changed and no merge tool is available
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import difflib
|
|
14
|
+
import shutil
|
|
15
|
+
import subprocess
|
|
16
|
+
import tempfile
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
CRLF = b"\r\n"
|
|
20
|
+
LF = b"\n"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def git_path() -> str | None:
|
|
24
|
+
return shutil.which("git")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _eol(data: bytes) -> bytes:
|
|
28
|
+
crlf = data.count(CRLF)
|
|
29
|
+
return CRLF if crlf and crlf * 2 >= data.count(LF) else LF
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _to_eol(data: bytes, eol: bytes) -> bytes:
|
|
33
|
+
data = data.replace(CRLF, LF)
|
|
34
|
+
return data if eol == LF else data.replace(LF, eol)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _restyle(merged_lf: bytes, ours: bytes) -> bytes:
|
|
38
|
+
"""The merge result (LF line ends) in the original's line-end style. When the original mixes CRLF and LF,
|
|
39
|
+
every line kept from it keeps its own bytes; only the lines that changed take the usual style."""
|
|
40
|
+
eol = _eol(ours)
|
|
41
|
+
crlf = ours.count(CRLF)
|
|
42
|
+
if crlf == 0 or crlf == ours.count(LF):
|
|
43
|
+
return _to_eol(merged_lf, eol)
|
|
44
|
+
ours_lines = ours.splitlines(keepends=True)
|
|
45
|
+
new_lines = merged_lf.splitlines(keepends=True)
|
|
46
|
+
key = lambda line: line.rstrip(b"\r\n") # noqa: E731
|
|
47
|
+
sm = difflib.SequenceMatcher(None, [key(x) for x in ours_lines], [key(x) for x in new_lines], autojunk=False)
|
|
48
|
+
out: list[bytes] = []
|
|
49
|
+
for op, i1, i2, j1, j2 in sm.get_opcodes():
|
|
50
|
+
if op == "equal":
|
|
51
|
+
out += ours_lines[i1:i2]
|
|
52
|
+
else:
|
|
53
|
+
out += [key(x) + (eol if x.endswith(LF) else b"") for x in new_lines[j1:j2]]
|
|
54
|
+
return b"".join(out)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def merge3(ours: bytes, base: bytes | None, theirs: bytes, label: str = "file") -> tuple[str, bytes]:
|
|
58
|
+
# Line ends do not take part in the merge: editors and agents rewrite them (an agent adds LF lines to a CRLF
|
|
59
|
+
# file, the user's editor saves the whole file as CRLF again), and a line whose only change is its line end
|
|
60
|
+
# would conflict with the AI's next change next to it. The three are merged with LF line ends and the result
|
|
61
|
+
# gets the original's style back.
|
|
62
|
+
ours_n = _to_eol(ours, LF)
|
|
63
|
+
theirs_n = _to_eol(theirs, LF)
|
|
64
|
+
base_n = _to_eol(base, LF) if base is not None else None
|
|
65
|
+
if ours_n == theirs_n or theirs_n == base_n:
|
|
66
|
+
return "ours", ours
|
|
67
|
+
if base_n is not None and ours_n == base_n:
|
|
68
|
+
return "theirs", _restyle(theirs_n, ours)
|
|
69
|
+
git = git_path()
|
|
70
|
+
if base_n is None or git is None:
|
|
71
|
+
return "nomerge", theirs
|
|
72
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
73
|
+
paths = []
|
|
74
|
+
for name, data in (("ours", ours_n), ("base", base_n), ("theirs", theirs_n)):
|
|
75
|
+
p = Path(tmp) / name
|
|
76
|
+
p.write_bytes(data)
|
|
77
|
+
paths.append(str(p))
|
|
78
|
+
proc = subprocess.run(
|
|
79
|
+
[git, "merge-file", "-p", "-L", f"{label} (original)", "-L", f"{label} (last sync)",
|
|
80
|
+
"-L", f"{label} (AI)", *paths],
|
|
81
|
+
capture_output=True, timeout=60, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
|
82
|
+
if proc.returncode == 0:
|
|
83
|
+
return "merged", _restyle(proc.stdout, ours)
|
|
84
|
+
if 0 < proc.returncode < 128:
|
|
85
|
+
return "conflict", _restyle(proc.stdout, ours)
|
|
86
|
+
return "nomerge", theirs
|