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/strhide.py ADDED
@@ -0,0 +1,188 @@
1
+ """Hiding of string literals: "Sample rate: %d Hz\\n" -> "str_0002 %d\\n".
2
+
3
+ The placeholder keeps the literal's prefix and quotes and its *skeleton* - format specifiers
4
+ (%d, %-10s, %%), escapes (\\n, \\x1b) and f-string fields ({name}) - so printf-style calls stay
5
+ valid and the AI still sees the call's shape. Literals without a word of 3+ letters ("%02x",
6
+ "\\n") carry no meaning and are left alone.
7
+
8
+ Restore puts the original back; if the AI edited around the id ("str_0002 %u\\n (mono)") the
9
+ original wording is rebuilt around the AI's specifiers and additions.
10
+ Shared by DoppelCode (twin, prefix str_) and msgobf (messages, prefix st_).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import re
16
+
17
+ # Python triple quotes are one quote: in '"""text {"a", "b"}"""' the body must not start with '""'
18
+ # (librosa: a docstring became "str_1015 {"xlim_changed", ...}", a syntax error)
19
+ LIT_RE = re.compile(r'(?P<pre>(?:u8|[LuUfFrRbB]{1,2}|\$+@?|@\$*)?)(?P<q>"""|\'\'\'|["\'`])(?P<body>.*)(?P=q)\Z',
20
+ re.S)
21
+ _LEGACY_LIT_RE = re.compile(r'(?P<pre>(?:u8|[LuUfFrRbB]{1,2}|\$+@?|@\$*)?)(?P<q>["\'`])(?P<body>.*)(?P=q)\Z', re.S)
22
+ SPEC_RE = re.compile(r"\\(?:[0-7]{1,3}|x[0-9A-Fa-f]+|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8}|.)"
23
+ r"|%%|%[-+ #0]*(?:\*|\d+)?(?:\.(?:\*|\d+))?(?:hh|h|ll|l|L|z|j|t|I64|I32|I)?"
24
+ r"[diouxXeEfgGcspnaA]"
25
+ r"|\{\{|\}\}" # escaped braces: f"{{ url }}" is text, not a field
26
+ r"|\{[^{}\n]*\}", re.S)
27
+ _WORD_RE = re.compile(r"[^\W\d_]{2,}") # "F1", "Hz", "dB" are words too (pilot round 4)
28
+
29
+
30
+ # File and folder names in strings ("InputFiles//", "rec_01.dat", "data/out.bin", "C:\\x\\y.wav") get
31
+ # file-shaped aliases instead of str_ ids, so the twin program still finds its (renamed) data files.
32
+ _PATH_BODY_RE = re.compile(r"(?:[A-Za-z]:)?(?:\.{1,2}|[\w.\-]+)?(?:(?:/|\\\\)+(?:\.{1,2}|[\w.\-]+)?)*")
33
+ _EXT_RE = re.compile(r"\.[A-Za-z][A-Za-z0-9]{0,5}$")
34
+ _PATH_WORD_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
35
+
36
+
37
+ def is_path_literal(token: str) -> bool:
38
+ m = LIT_RE.match(token)
39
+ if not m:
40
+ return False
41
+ body = m.group("body")
42
+ if not body or not _PATH_BODY_RE.fullmatch(body) or not re.search(r"[A-Za-z]{2}", body):
43
+ return False
44
+ return "/" in body or "\\\\" in body or bool(_EXT_RE.search(body))
45
+
46
+
47
+ def path_words(token: str) -> list[tuple[str, str]]:
48
+ """(word, "dir" | "file") for the names in a path literal; extensions and drive letters stay."""
49
+ body = LIT_RE.match(token).group("body")
50
+ body = re.sub(r"^[A-Za-z]:", "", body)
51
+ parts = [p for p in re.split(r"/|\\\\", body)]
52
+ out = []
53
+ for i, part in enumerate(parts):
54
+ if not part or part in (".", ".."):
55
+ continue
56
+ is_last = i == len(parts) - 1
57
+ name = _EXT_RE.sub("", part) if is_last else part
58
+ for w in _PATH_WORD_RE.findall(name):
59
+ out.append((w, "file" if is_last else "dir"))
60
+ return out
61
+
62
+
63
+ def is_module_specifier(prev: str, prev2: str) -> bool:
64
+ """The string names a module: require("x"), import("x"), import ... from "x", import "x".
65
+ Hiding it would break loading the library (and it names a public package anyway)."""
66
+ return prev in ("from", "import") or (prev == "(" and prev2 in ("require", "import"))
67
+
68
+
69
+ def should_hide(body: str) -> bool:
70
+ if re.fullmatch(r"__\w+__", body): # "__main__", "__init__": runtime names, not text
71
+ return False
72
+ if re.fullmatch(r"[vV]?\d+(?:\.\d+)+(?:[-+.~][0-9A-Za-z]+)*", body):
73
+ return False # "8.23.1-DEV": a version, read back by build scripts (curl)
74
+ return bool(_WORD_RE.search(SPEC_RE.sub(" ", body)))
75
+
76
+
77
+ def is_raw(pre: str) -> bool:
78
+ """Raw / verbatim literals (Python r'', C# @"", C++ R"()"): a backslash is not an escape."""
79
+ return "r" in pre.lower() or "@" in pre
80
+
81
+
82
+ def _spec_tokens(body: str):
83
+ """The specifiers, escapes, '{{' / '}}' and {fields} of a body, in order. A field is matched with its
84
+ nested braces: f"{header:{width}}" and f"{name + f'_{n}'}" are one field each (libopus scripts)."""
85
+ i, n = 0, len(body)
86
+ while i < n:
87
+ if body.startswith(("{{", "}}"), i):
88
+ yield body[i:i + 2]
89
+ i += 2
90
+ continue
91
+ if body[i] == "{":
92
+ depth, j = 0, i
93
+ while j < n:
94
+ if body[j] == "{":
95
+ depth += 1
96
+ elif body[j] == "}":
97
+ depth -= 1
98
+ if depth == 0:
99
+ break
100
+ j += 1
101
+ if j < n:
102
+ yield body[i:j + 1]
103
+ i = j + 1
104
+ continue
105
+ i += 1 # an unbalanced '{': text
106
+ continue
107
+ m = SPEC_RE.match(body, i)
108
+ if m and m.end() > i and not m.group(0).startswith("{"):
109
+ yield m.group(0)
110
+ i = m.end()
111
+ continue
112
+ i += 1
113
+
114
+
115
+ def skeleton(body: str, raw: bool = False, quote: str = "", fstring: bool = False) -> str:
116
+ """The specifiers, escapes and {fields} of a literal body. In a plain string, a {field} that holds the
117
+ literal's own quote character is prose ({"xlim_changed", ...} in a docstring), not a format field: left
118
+ out. In an f-string every field is code and stays."""
119
+ q = "" if fstring else quote[:1]
120
+ return "".join(t if t.startswith("\\") else " " + t for t in _spec_tokens(body)
121
+ if not (raw and t.startswith("\\")) and not (q and t.startswith("{") and t != "{{"
122
+ and q in t))
123
+
124
+
125
+ def hide_literal(token: str, store: dict[str, str], ids: dict[str, str], alloc, shown: str | None = None) -> str:
126
+ """``store``: id -> original literal; ``ids``: original literal -> id (kept in sync).
127
+ ``shown``: the literal with its interpolation fields already translated ({text} -> {v_0007}); the
128
+ placeholder's skeleton is taken from it, while the vault keeps the original."""
129
+ m = LIT_RE.match(token)
130
+ if not m or not should_hide(m.group("body")):
131
+ return shown or token
132
+ cid = ids.get(token)
133
+ if cid is None:
134
+ cid = alloc()
135
+ store[cid] = token
136
+ ids[token] = cid
137
+ sm = LIT_RE.match(shown) if shown else m
138
+ return (f'{m.group("pre")}{m.group("q")}{cid}'
139
+ f'{skeleton((sm or m).group("body"), is_raw(m.group("pre")), m.group("q"), "f" in m.group("pre").lower())}'
140
+ f'{m.group("q")}')
141
+
142
+
143
+ def _rebuild(original_body: str, after: str) -> str:
144
+ """Put the original wording back around the AI's version of the skeleton.
145
+
146
+ ``after`` is what follows the id in the AI's literal, e.g. " %u (fatal)\\n" for an original
147
+ "CBC encrypt error %d\\n". When the AI kept the number of specifiers, slot i gets the original
148
+ text i, then whatever the AI added there; otherwise the original wording comes first and the
149
+ AI's text follows unchanged (never duplicating the original's specifiers)."""
150
+ texts = SPEC_RE.split(original_body)
151
+ specs = list(SPEC_RE.finditer(after))
152
+ if len(specs) != len(texts) - 1:
153
+ return re.sub(r" +", " ", "".join(texts)).rstrip(" ") + after
154
+ out, last = [], 0
155
+ for i, m in enumerate(specs):
156
+ gap = after[last:m.start()]
157
+ if not m.group(0).startswith("\\") and gap.startswith(" "):
158
+ gap = gap[1:] # the space the skeleton put before %-specifiers
159
+ out.append(texts[i] + gap + m.group(0))
160
+ last = m.end()
161
+ return "".join(out) + texts[-1] + after[last:]
162
+
163
+
164
+ def restore_literal(token: str, store: dict[str, str], id_re: re.Pattern) -> str:
165
+ m = LIT_RE.match(token)
166
+ if not m:
167
+ return token
168
+ body = m.group("body")
169
+ hits = [h for h in id_re.finditer(body) if h.group(0) in store]
170
+ if not hits:
171
+ return token
172
+ if len(hits) == 1:
173
+ orig = store[hits[0].group(0)]
174
+ for rx in (LIT_RE, _LEGACY_LIT_RE): # cobf <= 0.6.2 read '"""' as '"' + body '""...""'
175
+ om = rx.match(orig)
176
+ if om and token in (f'{om.group("pre")}{om.group("q")}{hits[0].group(0)}'
177
+ f'{skeleton(om.group("body"), is_raw(om.group("pre")), q, "f" in om.group("pre").lower())}'
178
+ f'{om.group("q")}'
179
+ for q in (om.group("q"), "")):
180
+ return orig # untouched placeholder
181
+ out, last = [], 0
182
+ for i, h in enumerate(hits):
183
+ om = LIT_RE.match(store[h.group(0)])
184
+ end = hits[i + 1].start() if i + 1 < len(hits) else len(body)
185
+ out.append(body[last:h.start()])
186
+ out.append(_rebuild(om.group("body"), body[h.end():end]) if om else body[h.start():end])
187
+ last = end
188
+ return f'{m.group("pre")}{m.group("q")}{"".join(out)}{m.group("q")}'
@@ -0,0 +1,192 @@
1
+ """Compilers for Java, C# and JavaScript / TypeScript, used by `check`.
2
+
3
+ The rule is the same as for C: the original is built first; when the original does not build with the
4
+ tool found here, its files are reported NOT CHECKED (with the reason) - only an error that the twin has
5
+ and the original does not counts as a twin error. The twin's code is never run: javac runs without
6
+ annotation processors, csc without analyzers, and JS / TS is only compiled (syntax), not executed.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import glob
12
+ import json
13
+ import os
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ from dataclasses import dataclass, field
18
+ from pathlib import Path
19
+
20
+ NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
21
+
22
+
23
+ @dataclass
24
+ class Tool:
25
+ name: str # shown in the report, e.g. "javac 21.0.11"
26
+ cmd: list[str] # program and fixed arguments
27
+ env: dict | None = None
28
+ kind: str = "" # csc: "roslyn" | "dotnet" | "framework"
29
+ refs: list[str] = field(default_factory=list) # csc on the .NET SDK: reference assemblies
30
+
31
+
32
+ def _run(cmd: list[str], env: dict | None = None, cwd: Path | None = None,
33
+ timeout: int = 300) -> subprocess.CompletedProcess:
34
+ return subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", env=env,
35
+ cwd=cwd, timeout=timeout, creationflags=NO_WINDOW)
36
+
37
+
38
+ def _existing(cands) -> list[str]:
39
+ out = []
40
+ for c in cands:
41
+ if c and Path(c).is_file() and str(c) not in out:
42
+ out.append(str(c))
43
+ return out
44
+
45
+
46
+ def _globs(patterns: list[str]) -> list[str]:
47
+ found = []
48
+ for pat in patterns:
49
+ found += sorted(glob.glob(pat), reverse=True) # newest version first
50
+ return found
51
+
52
+
53
+ # ---------------------------------------------------------------------------------------------- Java
54
+ def find_javac(configured: str | None = None) -> Tool | None:
55
+ home = Path.home()
56
+ cands = [configured] if configured else []
57
+ cands.append(shutil.which("javac"))
58
+ if os.environ.get("JAVA_HOME"):
59
+ cands += [Path(os.environ["JAVA_HOME"]) / "bin" / "javac.exe", Path(os.environ["JAVA_HOME"]) / "bin" / "javac"]
60
+ cands += _globs([str(home / ".jdks" / "*" / "bin" / "javac.exe"),
61
+ r"C:\Program Files\Java\*\bin\javac.exe",
62
+ r"C:\Program Files\Eclipse Adoptium\*\bin\javac.exe",
63
+ r"C:\Program Files\Microsoft\jdk-*\bin\javac.exe",
64
+ r"C:\Program Files\Zulu\*\bin\javac.exe",
65
+ r"C:\Program Files\Android\Android Studio\jbr\bin\javac.exe"])
66
+ for path in _existing(cands):
67
+ try:
68
+ p = _run([path, "-version"], timeout=60)
69
+ except (OSError, subprocess.SubprocessError):
70
+ continue
71
+ if p.returncode == 0:
72
+ return Tool((p.stdout + p.stderr).strip() or "javac", [path])
73
+ return None
74
+
75
+
76
+ # ------------------------------------------------------------------------------------------------ C#
77
+ def find_csc(configured: str | None = None) -> Tool | None:
78
+ if configured:
79
+ return Tool("csc", [configured], kind="roslyn" if "roslyn" in configured.lower() else "framework") \
80
+ if Path(configured).is_file() or shutil.which(configured) else None
81
+ # 1. Visual Studio / Build Tools: Roslyn csc.exe (modern C#, targets .NET Framework).
82
+ for path in _existing(_globs([r"C:\Program Files\Microsoft Visual Studio\*\*\MSBuild\Current\Bin\Roslyn\csc.exe",
83
+ r"C:\Program Files (x86)\Microsoft Visual Studio\*\*\MSBuild\Current\Bin\Roslyn\csc.exe"])):
84
+ return Tool("csc (Visual Studio Roslyn)", [path], kind="roslyn")
85
+ # 2. .NET SDK: dotnet + sdk/<v>/Roslyn/bincore/csc.dll with the reference pack's assemblies.
86
+ dotnet = _existing([shutil.which("dotnet"), r"C:\Program Files\dotnet\dotnet.exe",
87
+ str(Path.home() / ".dotnet" / "dotnet.exe")])
88
+ if dotnet:
89
+ root = Path(dotnet[0]).resolve().parent
90
+ cscs = _globs([str(root / "sdk" / "*" / "Roslyn" / "bincore" / "csc.dll")])
91
+ packs = _globs([str(root / "packs" / "Microsoft.NETCore.App.Ref" / "*" / "ref" / "net*")])
92
+ if cscs and packs:
93
+ refs = sorted(glob.glob(str(Path(packs[0]) / "*.dll")))
94
+ return Tool("csc (.NET SDK " + Path(cscs[0]).parents[2].name + ")", [dotnet[0], cscs[0]],
95
+ kind="dotnet", refs=refs)
96
+ # 3. .NET Framework csc: always on Windows, but only C# 5 (no $"", =>, using var ...).
97
+ for path in _existing([shutil.which("csc"), r"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe",
98
+ r"C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe"]):
99
+ return Tool("csc (.NET Framework 4, C# 5 only)", [path], kind="framework")
100
+ return None
101
+
102
+
103
+ # ------------------------------------------------------------------------------------ JavaScript / TS
104
+ def find_node(configured: str | None = None) -> Tool | None:
105
+ cands = [configured] if configured else []
106
+ cands += [shutil.which("node"), r"C:\Program Files\nodejs\node.exe"]
107
+ for path in _existing(cands):
108
+ return Tool("node", [path])
109
+ # VS Code ships Node (Electron); ELECTRON_RUN_AS_NODE makes Code.exe behave as plain node.
110
+ local = os.environ.get("LOCALAPPDATA", "")
111
+ for path in _existing([os.path.join(local, "Programs", "Microsoft VS Code", "Code.exe"),
112
+ r"C:\Program Files\Microsoft VS Code\Code.exe"]):
113
+ env = dict(os.environ, ELECTRON_RUN_AS_NODE="1")
114
+ return Tool("node (VS Code)", [path], env=env)
115
+ return None
116
+
117
+
118
+ _NODE_CHECK = r"""
119
+ const fs = require('fs'), vm = require('vm'), mod = require('module');
120
+ process.removeAllListeners('warning');
121
+ const out = {};
122
+ for (const f of JSON.parse(fs.readFileSync(process.argv[process.argv.length - 1], 'utf8'))) {
123
+ let err = null;
124
+ try {
125
+ let src = fs.readFileSync(f, 'utf8');
126
+ if (/\.[cm]?tsx?$/i.test(f)) {
127
+ if (typeof mod.stripTypeScriptTypes !== 'function') throw new Error('NOTS this Node cannot read TypeScript');
128
+ src = mod.stripTypeScriptTypes(src, { mode: 'strip' });
129
+ }
130
+ try { new vm.Script(mod.wrap(src), { filename: f }); }
131
+ catch (e) {
132
+ if (!(e instanceof SyntaxError) || typeof vm.SourceTextModule !== 'function') throw e;
133
+ new vm.SourceTextModule(src, { identifier: f }); // ES module (import / export)
134
+ }
135
+ } catch (e) {
136
+ const where = String(e && e.stack || '').split('\n').find(l => l.includes(f)) || '';
137
+ const m = where.match(/:(\d+)/);
138
+ err = (e && e.message || String(e)) + (m ? ' (line ' + m[1] + ')' : '');
139
+ }
140
+ out[f] = err;
141
+ }
142
+ process.stdout.write(JSON.stringify(out));
143
+ """
144
+
145
+
146
+ def node_syntax(tool: Tool, files: list[Path], workdir: Path) -> dict[str, str | None]:
147
+ """{path: None (ok) or error} - files are compiled by V8, never run. TS types are stripped first."""
148
+ lst = workdir / "node_files.json"
149
+ lst.write_text(json.dumps([str(f) for f in files]), encoding="utf-8")
150
+ script = workdir / "node_check.js"
151
+ script.write_text(_NODE_CHECK, encoding="utf-8")
152
+ p = _run([*tool.cmd, "--experimental-vm-modules", "--no-warnings", str(script), str(lst)], env=tool.env)
153
+ try:
154
+ return json.loads(p.stdout)
155
+ except ValueError:
156
+ raise RuntimeError((p.stderr or p.stdout).strip()[:300] or f"node exit {p.returncode}") from None
157
+
158
+
159
+ # ---------------------------------------------------------------------------------------- compilation
160
+ def javac(tool: Tool, files: list[Path], outdir: Path) -> tuple[bool, list[str]]:
161
+ outdir.mkdir(parents=True, exist_ok=True)
162
+ args = [*tool.cmd, "-proc:none", "-implicit:none", "-nowarn", "-encoding", "UTF-8", "-cp", str(outdir),
163
+ "-d", str(outdir), *map(str, files)]
164
+ p = _run(args, cwd=outdir)
165
+ return p.returncode == 0, _errors(p, r"error:")
166
+
167
+
168
+ def csc(tool: Tool, files: list[Path], outdir: Path, target: str | None = None) -> tuple[bool, list[str], str]:
169
+ """Compile (target "exe" / "library"). Without a target: exe, and a library when there is no Main
170
+ (CS5001). Returns (ok, errors, target used)."""
171
+ outdir.mkdir(parents=True, exist_ok=True)
172
+ base = [*tool.cmd, "/nologo", "/warn:0"]
173
+ if tool.kind in ("roslyn", "dotnet"):
174
+ base.append("/langversion:latest")
175
+ if tool.kind == "dotnet":
176
+ base += ["/nostdlib", *[f"/r:{r}" for r in tool.refs]]
177
+ ok, errs = False, []
178
+ for tgt in ([target] if target else ["exe", "library"]):
179
+ out = outdir / ("app.exe" if tgt == "exe" else "app.dll")
180
+ p = _run([*base, f"/t:{tgt}", f"/out:{out}", *map(str, files)], cwd=outdir)
181
+ ok, errs = p.returncode == 0, _errors(p, r"error CS\d+")
182
+ if ok or not any("CS5001" in e for e in errs):
183
+ return ok, errs, tgt
184
+ return ok, errs, "library"
185
+
186
+
187
+ def _errors(p: subprocess.CompletedProcess, pattern: str) -> list[str]:
188
+ lines = [ln.strip() for ln in (p.stdout + "\n" + p.stderr).splitlines()]
189
+ errs = [ln for ln in lines if re.search(pattern, ln)]
190
+ if p.returncode != 0 and not errs:
191
+ errs = [ln for ln in lines if ln][:3] or [f"exit code {p.returncode}"]
192
+ return errs