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/translate.py
ADDED
|
@@ -0,0 +1,599 @@
|
|
|
1
|
+
"""Forward (obfuscate) and reverse (restore) translation of file contents and paths."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
from . import lexer, strhide
|
|
8
|
+
from .lexer import CHAR, COMMENT, HEADER, IDENT, PUNCT, STRING, TEXT_DIRECTIVES
|
|
9
|
+
|
|
10
|
+
WORD_RE = re.compile(r"\w+")
|
|
11
|
+
# A generated name (fn_0005, mod_0001, ...) used as part of a longer word the AI coined:
|
|
12
|
+
# fn_0005_checked, test_v_0014. Generated names end in 4 digits and never occur in the
|
|
13
|
+
# original, so a non-digit right after them is always a boundary.
|
|
14
|
+
_NAME_LIST_RE = re.compile(r"\s*[A-Za-z_]\w*(?:\s*,\s*[A-Za-z_]\w*)+\s*")
|
|
15
|
+
_DOTTED_RE = re.compile(r"[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)+")
|
|
16
|
+
COINED_RE = re.compile(r"(?<![A-Za-z0-9])([A-Za-z]+_\d{4,})(?!\d)")
|
|
17
|
+
# Hidden comments: the twin holds "// cmt_0007" or "/* cmt_0007 */"; the vault holds the text.
|
|
18
|
+
_FIELD_IDENT_RE = re.compile(r"(?<![\w$])[A-Za-z_]\w*")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def interpolated(token: str, lang: str) -> bool:
|
|
22
|
+
"""f"{x}" (Python), $"{x}" (C#), `${x}` (JS / TS): the braces contain code."""
|
|
23
|
+
if lang == "python":
|
|
24
|
+
pre = re.match(r"[A-Za-z]*", token).group(0)
|
|
25
|
+
return "f" in pre.lower()
|
|
26
|
+
if lang == "csharp":
|
|
27
|
+
return token.startswith(("$", "@$"))
|
|
28
|
+
if lang in ("javascript", "typescript"):
|
|
29
|
+
return token.startswith("`") and "${" in token
|
|
30
|
+
return False
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _split_field(field: str) -> int:
|
|
34
|
+
"""Where the code of an f-string field ends: the first top-level '!' conversion or ':' format spec
|
|
35
|
+
(not '!=' / ':='), outside nested brackets and quotes."""
|
|
36
|
+
depth, quote, i = 0, "", 0
|
|
37
|
+
while i < len(field):
|
|
38
|
+
c = field[i]
|
|
39
|
+
if quote:
|
|
40
|
+
if c == quote:
|
|
41
|
+
quote = ""
|
|
42
|
+
elif c in "'\"":
|
|
43
|
+
quote = c
|
|
44
|
+
elif c in "([{":
|
|
45
|
+
depth += 1
|
|
46
|
+
elif c in ")]}":
|
|
47
|
+
depth -= 1
|
|
48
|
+
elif depth == 0 and c in "!:" and field[i + 1:i + 2] != "=":
|
|
49
|
+
return i
|
|
50
|
+
i += 1
|
|
51
|
+
return len(field)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def map_fields(token: str, lang: str, fn, num_fn=None) -> str:
|
|
55
|
+
"""Apply ``fn`` to every identifier inside the code fields of an interpolated literal; ``num_fn``
|
|
56
|
+
(Python: secret constants) to the numbers in the code part of a field, never in its format spec."""
|
|
57
|
+
js = lang in ("javascript", "typescript")
|
|
58
|
+
out, i, n = [], 0, len(token)
|
|
59
|
+
while i < n:
|
|
60
|
+
c = token[i]
|
|
61
|
+
if not js and token.startswith(("{{", "}}"), i): # escaped brace
|
|
62
|
+
out.append(token[i:i + 2])
|
|
63
|
+
i += 2
|
|
64
|
+
continue
|
|
65
|
+
start = token.startswith("${", i) if js else c == "{"
|
|
66
|
+
if not start:
|
|
67
|
+
out.append(c)
|
|
68
|
+
i += 1
|
|
69
|
+
continue
|
|
70
|
+
j = i + (2 if js else 1)
|
|
71
|
+
depth = 1
|
|
72
|
+
while j < n and depth:
|
|
73
|
+
if token[j] in "{[(":
|
|
74
|
+
depth += 1
|
|
75
|
+
elif token[j] in "}])":
|
|
76
|
+
depth -= 1
|
|
77
|
+
j += 1
|
|
78
|
+
head = 2 if js else 1
|
|
79
|
+
field = token[i + head:j - 1] if depth == 0 else token[i + head:j]
|
|
80
|
+
tail = ""
|
|
81
|
+
if num_fn is not None:
|
|
82
|
+
cut = _split_field(field)
|
|
83
|
+
field, tail = num_fn(field[:cut]), field[cut:]
|
|
84
|
+
out.append(token[i:i + head] + _FIELD_IDENT_RE.sub(lambda m: fn(m.group(0)), field) + tail
|
|
85
|
+
+ ("}" if depth == 0 else ""))
|
|
86
|
+
i = j
|
|
87
|
+
return "".join(out)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
# Calls that look code up by a name given as a string: that string must be renamed with the code.
|
|
91
|
+
_BY_NAME_SECOND = {"getattr", "hasattr", "setattr", "delattr", "dlsym", "GetProcAddress"} # f(obj, "name")
|
|
92
|
+
_BY_NAME_FIRST = {"attrgetter", "methodcaller", "GetMethod", "GetProperty", "GetField", "GetMember",
|
|
93
|
+
"GetEvent", "GetNestedType", "getMethod", "getField", "getDeclaredMethod",
|
|
94
|
+
"getDeclaredField", "getConstructor"} # f("name")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
COMMENT_PREFIX = "cmt_"
|
|
98
|
+
STRING_PREFIX = "str_"
|
|
99
|
+
STRING_ID_RE = re.compile(r"(?<![A-Za-z0-9_])str_\d{4,}(?!\d)")
|
|
100
|
+
COMMENT_ID_RE = re.compile(r"(?<![A-Za-z0-9_])cmt_\d{4,}(?!\d)")
|
|
101
|
+
PLACEHOLDER_RE = re.compile(r"//\s*(cmt_\d{4,})\s*|/\*\s*(cmt_\d{4,})\s*\*/|#\s*(cmt_\d{4,})\s*")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def comment_placeholder(cid: str, original: str) -> str:
|
|
105
|
+
"""Placeholder in the file's own comment syntax, with the same number of lines as the original
|
|
106
|
+
(keeps __LINE__ and diffs aligned)."""
|
|
107
|
+
newlines = original.count("\n")
|
|
108
|
+
if original.startswith("#"): # Python, Makefile, CMake: line comments only
|
|
109
|
+
return f"# {cid}"
|
|
110
|
+
if original.startswith("//") and not newlines:
|
|
111
|
+
return f"// {cid}"
|
|
112
|
+
return f"/* {cid}" + "\n" * newlines + " */"
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
_BUILD_PLACEHOLDER_RE = re.compile(r"#[ \t]*(cmt_\d{4,})(?!\d)")
|
|
116
|
+
_PART_RE = re.compile(r"[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+")
|
|
117
|
+
# Parts too common in code to say anything about a project.
|
|
118
|
+
_COMMON_PARTS = {
|
|
119
|
+
"data", "size", "buffer", "count", "index", "length", "init", "read", "write", "test", "main", "file",
|
|
120
|
+
"name", "value", "values", "error", "status", "result", "input", "output", "start", "stop", "open",
|
|
121
|
+
"close", "list", "table", "type", "flag", "flags", "mode", "temp", "next", "last", "first", "info",
|
|
122
|
+
"config", "state", "context", "param", "params", "check", "build", "clean", "target", "source",
|
|
123
|
+
"include", "debug", "release", "make", "path", "string", "number", "char", "byte", "bytes", "bits",
|
|
124
|
+
"uint", "float", "double", "long", "short", "self", "print", "format", "line", "item", "items", "default",
|
|
125
|
+
"handle", "update", "reset", "get", "set", "with", "from", "into", "self", "none", "true", "false",
|
|
126
|
+
# build and command-line words (CMakeLists.txt, CI files, configure options): every project has them
|
|
127
|
+
"cmake", "version", "versions", "option", "options", "enable", "enabled", "disable", "disabled", "feature",
|
|
128
|
+
"features", "tests", "testing", "install", "library", "libs", "static", "shared", "define", "defines",
|
|
129
|
+
"platform", "compiler", "linker", "project", "package", "support", "example", "examples", "command",
|
|
130
|
+
"script", "workflow", "verbose", "required", "optional", "found", "files", "dirs", "directory", "version",
|
|
131
|
+
"sources", "headers", "private", "public", "interface", "have", "fixed", "supported", "current", "group",
|
|
132
|
+
"system", "generic", "common", "utils", "util", "tools", "host", "arch", "native",
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
# Build files (CMakeLists.txt, *.cmake, Makefile, *.mk): the build language's own words are never renamed,
|
|
137
|
+
# even when a project identifier has the same spelling (libopus: a Python variable 'endif' turned every CMake
|
|
138
|
+
# 'endif()' into 'v_0056()'). Commands are the words written as 'name(' at the start of a statement.
|
|
139
|
+
BUILD_KEYWORDS = {
|
|
140
|
+
"if", "else", "elseif", "endif", "foreach", "endforeach", "while", "endwhile", "function", "endfunction",
|
|
141
|
+
"macro", "endmacro", "block", "endblock", "return", "break", "continue", "set", "unset", "option",
|
|
142
|
+
"include", "ifeq", "ifneq", "ifdef", "ifndef", "define", "endef", "export", "unexport", "override",
|
|
143
|
+
"vpath", "sinclude", "private", "undefine",
|
|
144
|
+
}
|
|
145
|
+
# a command starts a statement: 'if(', 'string(' at the start of a line (or after ';'); a 'NAME(' inside a
|
|
146
|
+
# quoted regex is not one (curl: "#define LIBCURL_VERSION( |_NUM )")
|
|
147
|
+
_BUILD_CMD_RE = re.compile(r"(?:^|;)[ \t]*([A-Za-z_]\w*)(?=[ \t]*\()", re.M)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
# -DNAME / -UNAME in build files (compiler flags): NAME is the code's macro, renamed with it
|
|
151
|
+
# A file name in a build file (configure.ac, opus.pc.in, include/curl/curlver.h): translated as a path, like
|
|
152
|
+
# the file is named in the twin - not word by word (libopus: configure.ac became file_0165.ac)
|
|
153
|
+
_DFLAG_RE = re.compile(r"(?<![\w-])-[DU](?P<d>[A-Za-z_]\w*)|\w+")
|
|
154
|
+
_BUILD_EXTS = ("c|cc|cpp|cxx|h|hh|hpp|hxx|in|am|ac|mk|cmake|txt|py|pc|def|rc|s|S|asm|json|ld|map|inc|m4|sh|bat|"
|
|
155
|
+
"ps1|toml|cfg|ini|yml|yaml")
|
|
156
|
+
BUILD_WORD_RE = re.compile(r"(?<![\w.\-$])(?P<p>[A-Za-z0-9_][\w\-./]*\.(?:%s)(?:\.(?:%s))*)(?![\w\-])"
|
|
157
|
+
r"|(?<![\w-])-[DU](?P<d>[A-Za-z_]\w*)"
|
|
158
|
+
# a compiler / tool option ('-Wwrite-strings', '-fno-common', '--enable-x'): the tool's
|
|
159
|
+
r"|(?P<o>(?<![\w-])--?[A-Za-z][\w\-+=.,:]*)"
|
|
160
|
+
r"|(?<![\w\-])(?P<h>[A-Za-z0-9_]+(?:-[A-Za-z0-9_]+)+)(?![\w\-])"
|
|
161
|
+
r"|\w+" % (_BUILD_EXTS, _BUILD_EXTS))
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
TEXT_WORD_RE = re.compile(r"(?<![\w.\-$])(?P<p>[A-Za-z0-9_][\w\-./]*\.(?:%s)(?:\.(?:%s))*)(?![\w\-])"
|
|
165
|
+
r"|(?<![\w-])-[DU](?P<d>[A-Za-z_]\w*)|\w+" % (_BUILD_EXTS, _BUILD_EXTS))
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def build_language_words(s: str, cmake: bool = False) -> set[int]:
|
|
169
|
+
"""Start offsets of the words in a build-file text that belong to the build language. CMake files: every
|
|
170
|
+
CMake command, keyword, built-in variable and property (cmake_words), e.g. string(REGEX MATCH ...)."""
|
|
171
|
+
cmds = {m.start(1) for m in _BUILD_CMD_RE.finditer(s)}
|
|
172
|
+
if cmake:
|
|
173
|
+
from .cmake_words import COMMANDS, WORDS
|
|
174
|
+
return cmds | {m.start() for m in WORD_RE.finditer(s)
|
|
175
|
+
if m.group(0) in WORDS or m.group(0).lower() in COMMANDS or m.group(0).lower() in BUILD_KEYWORDS}
|
|
176
|
+
return cmds | {m.start() for m in WORD_RE.finditer(s) if m.group(0).lower() in BUILD_KEYWORDS}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def word_parts(word: str) -> set[str]:
|
|
180
|
+
"""'falcon_selftest' -> {'falcon', 'selftest'}; 'FalconAesContext' -> {'falcon', 'aes', 'context'}."""
|
|
181
|
+
return {p.lower() for chunk in word.split("_") for p in _PART_RE.findall(chunk)}
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def name_parts(names) -> set[str]:
|
|
185
|
+
"""Distinctive parts of the project's renamed names: 4+ letters, not common code words, and used in
|
|
186
|
+
at least two different names (so 'falcon' from falcon_encrypt_block and FalconAesContext)."""
|
|
187
|
+
seen: dict[str, int] = {}
|
|
188
|
+
for n in names:
|
|
189
|
+
for p in word_parts(n):
|
|
190
|
+
if len(p) >= 4 and p not in _COMMON_PARTS:
|
|
191
|
+
seen[p] = seen.get(p, 0) + 1
|
|
192
|
+
return {p for p, c in seen.items() if c >= 2}
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def build_comment_start(line: str) -> int:
|
|
196
|
+
"""Index of the '#' comment in a Makefile / CMake line, or -1 (skips '\\#' and '#' inside quotes)."""
|
|
197
|
+
return build_comment_scan(line)[0]
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def build_comment_scan(line: str, quote: str = "", quotes: str = "\"'") -> tuple[int, str]:
|
|
201
|
+
"""(index of the '#' comment or -1, the quote still open at the end of the line). ``quote``: a string
|
|
202
|
+
opened on an earlier line - CMake strings span lines, and '#include <x.h>' inside one is not a comment
|
|
203
|
+
(curl CMake/OtherTests.cmake). CMake quotes only with '"'."""
|
|
204
|
+
for i, ch in enumerate(line):
|
|
205
|
+
if quote:
|
|
206
|
+
if ch == quote and (i == 0 or line[i - 1] != "\\"):
|
|
207
|
+
quote = ""
|
|
208
|
+
elif ch in quotes:
|
|
209
|
+
quote = ch
|
|
210
|
+
elif ch == "#" and (i == 0 or line[i - 1] != "\\"):
|
|
211
|
+
return i, ""
|
|
212
|
+
return -1, quote
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def comment_body(original: str) -> str:
|
|
216
|
+
if original.startswith("/*"):
|
|
217
|
+
body = original[2:-2]
|
|
218
|
+
else:
|
|
219
|
+
body = original[1:] if original.startswith("#") else original[2:]
|
|
220
|
+
return body.strip()
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
class Translator:
|
|
224
|
+
"""One direction of the mapping.
|
|
225
|
+
|
|
226
|
+
words: word -> word (identifiers, file stems, extra words), applied to code and text.
|
|
227
|
+
stems: subset of ``words`` keys that are file stems, used for paths and #include.
|
|
228
|
+
dirs: directory name -> directory name.
|
|
229
|
+
"""
|
|
230
|
+
|
|
231
|
+
def __init__(self, words: dict[str, str], stems: set[str], dirs: dict[str, str],
|
|
232
|
+
scrub_comments: bool = True, scrub_strings: bool = True, protect_text_directives: bool = True,
|
|
233
|
+
hide_comments: bool = False, comment_store: dict[str, str] | None = None, comment_alloc=None,
|
|
234
|
+
hide_strings: bool = False, string_store: dict[str, str] | None = None, string_alloc=None):
|
|
235
|
+
self.words = words
|
|
236
|
+
self.stems = stems
|
|
237
|
+
self.dirs = dirs
|
|
238
|
+
self.scrub_comments = scrub_comments
|
|
239
|
+
# hide_comments (forward): replace every comment by a placeholder; comment_store maps
|
|
240
|
+
# placeholder id -> original comment and is shared with the vault; comment_alloc() -> new id.
|
|
241
|
+
self.hide_comments = hide_comments
|
|
242
|
+
self.comment_store = comment_store if comment_store is not None else {}
|
|
243
|
+
self.comment_alloc = comment_alloc
|
|
244
|
+
self._comment_ids: dict[str, str] | None = None
|
|
245
|
+
# hide_strings (forward): "Sample rate: %d Hz\n" -> "str_0002 %d\n" (see strhide.py)
|
|
246
|
+
self.hide_strings = hide_strings
|
|
247
|
+
self.string_store = string_store if string_store is not None else {}
|
|
248
|
+
self.string_alloc = string_alloc
|
|
249
|
+
self._string_ids: dict[str, str] | None = None
|
|
250
|
+
self.scrub_strings = scrub_strings
|
|
251
|
+
self.protect_text_directives = protect_text_directives
|
|
252
|
+
|
|
253
|
+
def names_only(self) -> "Translator":
|
|
254
|
+
"""Same renaming, but strings and comments untouched: the twin as the compiler would see it if
|
|
255
|
+
only names had changed - used to prove that renaming changes no machine code."""
|
|
256
|
+
return Translator(self.words, self.stems, self.dirs, scrub_comments=False, scrub_strings=False,
|
|
257
|
+
protect_text_directives=self.protect_text_directives)
|
|
258
|
+
|
|
259
|
+
def reversed(self) -> "Translator":
|
|
260
|
+
"""Inverse translator. Reverse always restores everything (policies only limit the forward pass)."""
|
|
261
|
+
inv_words = {g: o for o, g in self.words.items()}
|
|
262
|
+
inv_stems = {self.words[s] for s in self.stems if s in self.words}
|
|
263
|
+
inv_dirs = {g: o for o, g in self.dirs.items()}
|
|
264
|
+
tr = Translator(inv_words, inv_stems, inv_dirs, True, True, False, comment_store=self.comment_store,
|
|
265
|
+
string_store=self.string_store)
|
|
266
|
+
tr.coined = True
|
|
267
|
+
return tr
|
|
268
|
+
|
|
269
|
+
coined = False # reverse only: also restore generated names inside longer words and hidden comments
|
|
270
|
+
|
|
271
|
+
def word(self, w: str) -> str:
|
|
272
|
+
hit = self.words.get(w)
|
|
273
|
+
if hit is not None:
|
|
274
|
+
return hit
|
|
275
|
+
if self.coined and "_" in w:
|
|
276
|
+
words = self.words
|
|
277
|
+
return COINED_RE.sub(lambda m: words.get(m.group(1), m.group(1)), w)
|
|
278
|
+
if w.endswith("_CODE") and w[:-5] in self.words:
|
|
279
|
+
# CMake check_type_size(T SIZEOF_X) also sets SIZEOF_X_CODE, which config templates use (curl)
|
|
280
|
+
return self.words[w[:-5]] + "_CODE"
|
|
281
|
+
return w
|
|
282
|
+
|
|
283
|
+
# -- content ---------------------------------------------------------
|
|
284
|
+
def text(self, s: str) -> str:
|
|
285
|
+
if self.secret_text is not None:
|
|
286
|
+
from .secretconst import sub_text_numbers
|
|
287
|
+
s = sub_text_numbers(s, lambda m: self._secret_num(m.group(0)))
|
|
288
|
+
# '-DUSE_FAST' (a compiler flag in a .pc.in, a CI file or a string) names the macro USE_FAST
|
|
289
|
+
# a file name ("tool_setup.h" printed by a Perl helper) follows the file, like in build files
|
|
290
|
+
return TEXT_WORD_RE.sub(lambda m: self._text_path(m.group("p")) if m.group("p")
|
|
291
|
+
else m.group(0)[:2] + self.word(m.group("d")) if m.group("d")
|
|
292
|
+
else self.word(m.group(0)), s)
|
|
293
|
+
|
|
294
|
+
def build_text(self, s: str, cmake: bool = False) -> str:
|
|
295
|
+
"""Makefile / CMake: names renamed (not the build language's own words), and with comments "hide"
|
|
296
|
+
every '#' comment -> '# cmt_0001'. Also the reverse direction (restore), with hide_comments off."""
|
|
297
|
+
out = []
|
|
298
|
+
quote = ""
|
|
299
|
+
for line in s.splitlines(keepends=True):
|
|
300
|
+
body = line.rstrip("\r\n")
|
|
301
|
+
i, quote = build_comment_scan(body, quote, '"' if cmake else "\"'")
|
|
302
|
+
if not self.hide_comments:
|
|
303
|
+
i = -1
|
|
304
|
+
if i < 0:
|
|
305
|
+
out.append(self._build_code(line, cmake))
|
|
306
|
+
else:
|
|
307
|
+
out.append(self._build_code(body[:i], cmake) + self._hide_comment(body[i:]) + line[len(body):])
|
|
308
|
+
return "".join(out)
|
|
309
|
+
|
|
310
|
+
def _build_code(self, s: str, cmake: bool = False) -> str:
|
|
311
|
+
if self.secret_text is not None:
|
|
312
|
+
from .secretconst import sub_text_numbers
|
|
313
|
+
s = sub_text_numbers(s, lambda m: self._secret_num(m.group(0)))
|
|
314
|
+
keep = build_language_words(s, cmake)
|
|
315
|
+
|
|
316
|
+
def word(w: str, at: int) -> str:
|
|
317
|
+
if at in keep or w in self.build_keep:
|
|
318
|
+
return w
|
|
319
|
+
if w in self.path_words: # a project file or folder name (examples list, subdir)
|
|
320
|
+
return self._file_name(w) if w in self.stems else self.dirs.get(w, w)
|
|
321
|
+
return self.word(w)
|
|
322
|
+
|
|
323
|
+
def one(m: re.Match) -> str:
|
|
324
|
+
if m.group("p"):
|
|
325
|
+
return self._text_path(m.group("p"))
|
|
326
|
+
if m.group("d"):
|
|
327
|
+
return m.group(0)[:2] + self.word(m.group("d"))
|
|
328
|
+
if m.group("o"):
|
|
329
|
+
return m.group("o")
|
|
330
|
+
if m.group("h"): # cmdline-opts, 10-at-a-time: a name, or words joined by '-'
|
|
331
|
+
if m.group("h") in self.path_words or m.group("h") in self.build_keep:
|
|
332
|
+
return self.dirs.get(m.group("h"), m.group("h"))
|
|
333
|
+
return WORD_RE.sub(lambda w: word(w.group(0), m.start() + w.start()), m.group("h"))
|
|
334
|
+
return word(m.group(0), m.start())
|
|
335
|
+
return BUILD_WORD_RE.sub(one, s)
|
|
336
|
+
|
|
337
|
+
def restore_build_comments(self, s: str) -> str:
|
|
338
|
+
store = self.comment_store
|
|
339
|
+
return _BUILD_PLACEHOLDER_RE.sub(
|
|
340
|
+
lambda m: store[m.group(1)] if store.get(m.group(1), "").startswith("#") else m.group(0), s)
|
|
341
|
+
|
|
342
|
+
def c_source(self, src: str) -> str:
|
|
343
|
+
return self.code_source(src, "c")
|
|
344
|
+
|
|
345
|
+
# Secret constants (forward only): number text in comments / strings -> K_ alias, or None.
|
|
346
|
+
secret_text = None
|
|
347
|
+
secret_plan = None
|
|
348
|
+
# this file's function bodies whose text also hides small secret-table elements (see
|
|
349
|
+
# secretconst.local_small_values), and the values for the token being translated
|
|
350
|
+
secret_spans = None
|
|
351
|
+
_local_small = None
|
|
352
|
+
library_keys: set[str] = frozenset() # Python keys of library dicts: hide mode leaves them as they are
|
|
353
|
+
# names of the project's files (first part) and folders: in build files they name files, not identifiers
|
|
354
|
+
path_words: set[str] = frozenset()
|
|
355
|
+
copied_names: set[str] = frozenset() # names of the files the twin carries (configure.ac, opus.pc.in)
|
|
356
|
+
# build-file names that stay: CMake target names when file names are kept (libopus.a, not libv_5840.a)
|
|
357
|
+
build_keep: set[str] = frozenset()
|
|
358
|
+
|
|
359
|
+
def _secret_num(self, text: str):
|
|
360
|
+
alias = self.secret_text(text)
|
|
361
|
+
if alias is None and self._local_small:
|
|
362
|
+
from .secretconst import num_value
|
|
363
|
+
if num_value(text) in self._local_small and self.secret_plan is not None:
|
|
364
|
+
alias = self.secret_plan._text_alias(text)
|
|
365
|
+
return alias
|
|
366
|
+
|
|
367
|
+
def _secret_numbers(self, s: str) -> str:
|
|
368
|
+
"""Comments / strings kept as they are: only marked secret values are hidden (they always are)."""
|
|
369
|
+
if self.secret_text is None:
|
|
370
|
+
return s
|
|
371
|
+
from .secretconst import sub_text_numbers
|
|
372
|
+
return sub_text_numbers(s, lambda m: self._secret_num(m.group(0)))
|
|
373
|
+
|
|
374
|
+
def _field_numbers(self, code: str) -> str:
|
|
375
|
+
"""Secret numbers in the code of an f-string field: code, so the alias is imported in the twin."""
|
|
376
|
+
plan = self.secret_plan
|
|
377
|
+
if plan is None or not (plan.scalars or plan.table_values):
|
|
378
|
+
return code
|
|
379
|
+
from .secretconst import TEXT_NUM_RE
|
|
380
|
+
return TEXT_NUM_RE.sub(lambda m: plan.text_alias(m.group(0), code=True) or m.group(0), code)
|
|
381
|
+
|
|
382
|
+
def code_source(self, src: str, lang: str = "c", secrets: dict[int, tuple[int, str]] | None = None) -> str:
|
|
383
|
+
"""``secrets``: offset of a secret literal (or table) in ``src`` -> (end offset, K_ alias)."""
|
|
384
|
+
out: list[str] = []
|
|
385
|
+
stack: list[str] = [] # label of each open ( or [ : callee name, "__all__", "[index"
|
|
386
|
+
prev: list[str] = ["", ""] # last two significant token texts
|
|
387
|
+
toks = lexer.tokenize(src, lang)
|
|
388
|
+
pos, skip_to = 0, -1
|
|
389
|
+
for idx, t in enumerate(toks):
|
|
390
|
+
start, pos = pos, pos + len(t.text)
|
|
391
|
+
if start < skip_to:
|
|
392
|
+
continue # inside a table that was replaced as a whole
|
|
393
|
+
if secrets and start in secrets:
|
|
394
|
+
skip_to, alias = secrets[start]
|
|
395
|
+
out.append(alias)
|
|
396
|
+
prev = [prev[-1], alias]
|
|
397
|
+
continue
|
|
398
|
+
k = t.kind
|
|
399
|
+
if self.secret_spans and k in (COMMENT, STRING, CHAR):
|
|
400
|
+
text_mode = (self.scrub_comments or self.hide_comments) if k == COMMENT \
|
|
401
|
+
else (self.scrub_strings or self.hide_strings)
|
|
402
|
+
self._local_small = next((v for a, b, v in self.secret_spans if a <= start < b),
|
|
403
|
+
None) if text_mode else None
|
|
404
|
+
if k == PUNCT and t.text in "([":
|
|
405
|
+
label = prev[-1] if t.text == "(" else ("__all__" if prev[-2] == "__all__" and prev[-1] == "="
|
|
406
|
+
else "[index" if prev[-1] not in ("", "=", ",", "(", "[")
|
|
407
|
+
else "")
|
|
408
|
+
stack.append(label)
|
|
409
|
+
elif k == PUNCT and t.text in ")]" and stack:
|
|
410
|
+
stack.pop()
|
|
411
|
+
if k == IDENT:
|
|
412
|
+
if self.protect_text_directives and t.directive in TEXT_DIRECTIVES:
|
|
413
|
+
out.append(t.text)
|
|
414
|
+
else:
|
|
415
|
+
out.append(self.word(t.text))
|
|
416
|
+
elif k == COMMENT:
|
|
417
|
+
if self.coined:
|
|
418
|
+
out.append(self._restore_comment(t.text))
|
|
419
|
+
elif self.hide_comments:
|
|
420
|
+
out.append(self._hide_comment(t.text))
|
|
421
|
+
else:
|
|
422
|
+
out.append(self.text(t.text) if self.scrub_comments else self._secret_numbers(t.text))
|
|
423
|
+
elif k in (STRING, CHAR):
|
|
424
|
+
# code inside f"{x}" / $"{x}" / `${x}` is translated whatever the string policy
|
|
425
|
+
code = map_fields(t.text, lang, self.word, self._field_numbers if lang == "python" else None) \
|
|
426
|
+
if k == STRING and interpolated(t.text, lang) else t.text
|
|
427
|
+
lit = strhide.LIT_RE.match(t.text) if k == STRING and stack else None
|
|
428
|
+
if lit and lit.group("body") in self.words and self._by_name(stack[-1], prev[-1], lang, toks, idx):
|
|
429
|
+
out.append(self.text(t.text)) # the string names code: rename it with the code
|
|
430
|
+
elif self.coined and k == STRING and self.string_store:
|
|
431
|
+
out.append(strhide.restore_literal(self.text(t.text), self.string_store, STRING_ID_RE))
|
|
432
|
+
elif (self.hide_strings and k == STRING and t.directive not in TEXT_DIRECTIVES
|
|
433
|
+
and not strhide.is_path_literal(t.text)
|
|
434
|
+
and not strhide.is_module_specifier(prev[-1], prev[-2])
|
|
435
|
+
and not self._library_flag(t.text, stack)
|
|
436
|
+
and not (lit and lang == "python" and lit.group("body") in self.library_keys)):
|
|
437
|
+
out.append(self._secret_numbers(self._hide_string(t.text, code)))
|
|
438
|
+
elif self.scrub_strings:
|
|
439
|
+
out.append(self._scrub_string(code, t.text))
|
|
440
|
+
elif k == STRING and (strhide.is_path_literal(t.text)
|
|
441
|
+
or strhide.is_module_specifier(prev[-1], prev[-2])):
|
|
442
|
+
out.append(self.path_text(code)) # "./falconRadio", "rec_01.dat": renamed files
|
|
443
|
+
else:
|
|
444
|
+
out.append(self._secret_numbers(code))
|
|
445
|
+
elif k == HEADER:
|
|
446
|
+
out.append(t.text[0] + self.path(t.text[1:-1]) + t.text[-1])
|
|
447
|
+
else:
|
|
448
|
+
out.append(t.text)
|
|
449
|
+
if k not in (lexer.WS, lexer.NEWLINE, COMMENT):
|
|
450
|
+
prev = [prev[-1], t.text]
|
|
451
|
+
self._local_small = None
|
|
452
|
+
return "".join(out)
|
|
453
|
+
|
|
454
|
+
_FLAG_RE = re.compile(r"[\w.+\-/:]{1,24}")
|
|
455
|
+
|
|
456
|
+
def _library_flag(self, token: str, stack: list[str]) -> bool:
|
|
457
|
+
"""A one-word literal passed straight to a library call - warnings.filterwarnings('ignore'),
|
|
458
|
+
butter(..., btype='band'), open(p, 'rb'), x.encode('utf-8'): a mode the library reads, so it stays
|
|
459
|
+
(names in it are still replaced). Prose, and anything passed to the project's own functions, is
|
|
460
|
+
hidden."""
|
|
461
|
+
if not stack or not stack[-1] or not re.fullmatch(r"[A-Za-z_]\w*", stack[-1]) or stack[-1] in self.words:
|
|
462
|
+
return False
|
|
463
|
+
m = strhide.LIT_RE.match(token)
|
|
464
|
+
return bool(m) and not m.group("pre").lower().count("f") and bool(self._FLAG_RE.fullmatch(m.group("body")))
|
|
465
|
+
|
|
466
|
+
@staticmethod
|
|
467
|
+
def _by_name(label: str, before: str, lang: str, toks, idx: int) -> bool:
|
|
468
|
+
if label in _BY_NAME_SECOND and before == ",":
|
|
469
|
+
return True
|
|
470
|
+
if label in _BY_NAME_FIRST and before == "(":
|
|
471
|
+
return True
|
|
472
|
+
if label == "__all__" and lang == "python" and before in ("[", ","):
|
|
473
|
+
return True
|
|
474
|
+
if label == "[index" and lang in ("javascript", "typescript") and before == "[":
|
|
475
|
+
nxt = next((t.text for t in toks[idx + 1:] if t.kind not in (lexer.WS, lexer.NEWLINE)), "")
|
|
476
|
+
return nxt == "]" # obj["name"]
|
|
477
|
+
return False
|
|
478
|
+
|
|
479
|
+
# -- comments --------------------------------------------------------
|
|
480
|
+
def _hide_comment(self, text: str) -> str:
|
|
481
|
+
if self._comment_ids is None:
|
|
482
|
+
self._comment_ids = {orig: cid for cid, orig in self.comment_store.items()}
|
|
483
|
+
cid = self._comment_ids.get(text)
|
|
484
|
+
if cid is None:
|
|
485
|
+
if self.comment_alloc is None:
|
|
486
|
+
raise ValueError("hide_comments needs comment_alloc")
|
|
487
|
+
cid = self.comment_alloc()
|
|
488
|
+
self.comment_store[cid] = text
|
|
489
|
+
self._comment_ids[text] = cid
|
|
490
|
+
return comment_placeholder(cid, text)
|
|
491
|
+
|
|
492
|
+
def _hide_string(self, text: str, shown: str | None = None) -> str:
|
|
493
|
+
m = strhide.LIT_RE.match(text)
|
|
494
|
+
body = m.group("body") if m else ""
|
|
495
|
+
names = [x for x in re.split(r"\s*,\s*", body.strip())] if _NAME_LIST_RE.fullmatch(body) else []
|
|
496
|
+
names_code = body in self.words and not self.words[body].startswith(self._FILE_ALIASES)
|
|
497
|
+
if m and (names_code or (
|
|
498
|
+
_DOTTED_RE.fullmatch(body) and any(p in self.words for p in body.split(".")))
|
|
499
|
+
or len(names) > 1):
|
|
500
|
+
# ... and "A4, tuning" names parameters (pytest.mark.parametrize, namedtuple)
|
|
501
|
+
# "fn_name" names a renamed identifier (getattr(o, "x"), __all__, nameof), and
|
|
502
|
+
# "pkg.util.data" a module (importlib.resources.files, import_module): rename it the same way
|
|
503
|
+
# instead of hiding it, so the code keeps working (librosa twin).
|
|
504
|
+
return self.text(text)
|
|
505
|
+
if self._string_ids is None:
|
|
506
|
+
self._string_ids = {orig: sid for sid, orig in self.string_store.items()}
|
|
507
|
+
if self.string_alloc is None:
|
|
508
|
+
raise ValueError("hide_strings needs string_alloc")
|
|
509
|
+
return strhide.hide_literal(text, self.string_store, self._string_ids, self.string_alloc, shown)
|
|
510
|
+
|
|
511
|
+
def _restore_comment(self, text: str) -> str:
|
|
512
|
+
m = PLACEHOLDER_RE.fullmatch(text)
|
|
513
|
+
if m:
|
|
514
|
+
cid = m.group(1) or m.group(2) or m.group(3)
|
|
515
|
+
if cid in self.comment_store:
|
|
516
|
+
return self.comment_store[cid]
|
|
517
|
+
out = self.text(text)
|
|
518
|
+
if self.comment_store and "cmt_" in out:
|
|
519
|
+
# The AI edited a placeholder comment ("// cmt_0007 - now also checks NULL"): put the
|
|
520
|
+
# original wording back where the id is referenced.
|
|
521
|
+
store = self.comment_store
|
|
522
|
+
out = COMMENT_ID_RE.sub(lambda m: comment_body(store[m.group(0)]) if m.group(0) in store
|
|
523
|
+
else m.group(0), out)
|
|
524
|
+
return out
|
|
525
|
+
|
|
526
|
+
# -- paths -----------------------------------------------------------
|
|
527
|
+
def _file_name(self, name: str) -> str:
|
|
528
|
+
stem, dot, ext = name.rpartition(".")
|
|
529
|
+
if not dot:
|
|
530
|
+
stem, ext = name, ""
|
|
531
|
+
if stem in self.stems and stem in self.words:
|
|
532
|
+
return self.words[stem] + (dot + ext if dot else "")
|
|
533
|
+
first, dot1, rest = name.partition(".")
|
|
534
|
+
if dot1 and first in self.stems and first in self.words: # config.h.cmake.in, config.h
|
|
535
|
+
return self.words[first] + "." + rest
|
|
536
|
+
return name
|
|
537
|
+
|
|
538
|
+
_FILE_ALIASES = ("file_", "dir_")
|
|
539
|
+
|
|
540
|
+
def _scrub_string(self, code: str, token: str) -> str:
|
|
541
|
+
"""strings "scrub": names replaced, but a word that is only a data-file or folder name stays unless
|
|
542
|
+
the string is a path to it - curl's test server sent "dir_0007/1.1" instead of "HTTP/1.1", and
|
|
543
|
+
b'verifiedserver' became b'file_0117' (behaviour changed)."""
|
|
544
|
+
if strhide.is_path_literal(token) and self._names_project_path(token):
|
|
545
|
+
return self.text(code)
|
|
546
|
+
if self.secret_text is not None:
|
|
547
|
+
from .secretconst import sub_text_numbers
|
|
548
|
+
code = sub_text_numbers(code, lambda m: self._secret_num(m.group(0)))
|
|
549
|
+
|
|
550
|
+
def one(m: re.Match) -> str:
|
|
551
|
+
new = self.word(m.group(0))
|
|
552
|
+
return m.group(0) if new.startswith(self._FILE_ALIASES) and new != m.group(0) else new
|
|
553
|
+
return WORD_RE.sub(one, code)
|
|
554
|
+
|
|
555
|
+
def _names_project_path(self, token: str) -> bool:
|
|
556
|
+
"""The literal's last path part is a project file or folder ("rec_01.dat", "InputFiles//")."""
|
|
557
|
+
m = strhide.LIT_RE.match(token)
|
|
558
|
+
parts = [x for x in re.split(r"[\\/]+", m.group("body") if m else token) if x]
|
|
559
|
+
if not parts:
|
|
560
|
+
return False
|
|
561
|
+
last = parts[-1]
|
|
562
|
+
stem = last.rsplit(".", 1)[0] if "." in last[1:] else last
|
|
563
|
+
alias = self.words.get(stem, "")
|
|
564
|
+
return (stem in self.stems or last in self.dirs or alias.startswith(self._FILE_ALIASES + ("mod_",)))
|
|
565
|
+
|
|
566
|
+
def _text_path(self, token: str) -> str:
|
|
567
|
+
"""A file name or path written in text or a build file, translated like the file it names: code files
|
|
568
|
+
and folders by their twin names, data files and data folders by their aliases (rec_01.dat,
|
|
569
|
+
HTTP/verifiedserver.txt); any other part stays (tool_setup.h when file names are kept)."""
|
|
570
|
+
parts = token.split("/")
|
|
571
|
+
out = []
|
|
572
|
+
for i, part in enumerate(parts):
|
|
573
|
+
if i < len(parts) - 1:
|
|
574
|
+
alias = self.words.get(part, "")
|
|
575
|
+
out.append(self.dirs.get(part) or (alias if alias.startswith("dir_") or (self.coined and alias)
|
|
576
|
+
else part))
|
|
577
|
+
continue
|
|
578
|
+
name = self._file_name(part)
|
|
579
|
+
if name == part and part not in self.copied_names: # a data file, not a file the twin carries
|
|
580
|
+
stem, dot, ext = part.partition(".")
|
|
581
|
+
alias = self.words.get(stem, "")
|
|
582
|
+
if alias.startswith(("file_", "dir_")) or (self.coined and stem in self.words):
|
|
583
|
+
name = alias + dot + ext if alias else part
|
|
584
|
+
out.append(name)
|
|
585
|
+
return "/".join(out)
|
|
586
|
+
|
|
587
|
+
def path_text(self, s: str) -> str:
|
|
588
|
+
"""Rename only the project's file and folder names in a string (strings policy "keep"): the twin
|
|
589
|
+
must still find its renamed modules and data files, but no other word changes."""
|
|
590
|
+
files = {w for w in self.stems if w in self.words}
|
|
591
|
+
return WORD_RE.sub(lambda m: self.words[m.group(0)] if m.group(0) in files
|
|
592
|
+
else self.dirs.get(m.group(0), m.group(0)), s)
|
|
593
|
+
|
|
594
|
+
def path(self, rel: str) -> str:
|
|
595
|
+
"""Translate a '/'-separated relative path (directory names + file stem)."""
|
|
596
|
+
parts = rel.split("/")
|
|
597
|
+
out = [self.dirs.get(p, p) for p in parts[:-1]]
|
|
598
|
+
out.append(self._file_name(parts[-1]))
|
|
599
|
+
return "/".join(out)
|