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
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Comments an AI dropped while rewriting code.
|
|
2
|
+
|
|
3
|
+
With ``comments: hide`` the twin's comments are placeholders (``// cmt_0040``). An AI that returns a whole
|
|
4
|
+
function often leaves them out (pilot round 3: 9 comments of process_audio_file and main), and import would
|
|
5
|
+
then delete the real comments from the original. A placeholder the AI dropped next to code it kept is put
|
|
6
|
+
back; one that went together with the code around it (a deleted block) stays deleted.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import difflib
|
|
12
|
+
import re
|
|
13
|
+
|
|
14
|
+
_ID = r"cmt_\d{4,}"
|
|
15
|
+
# A line that is only a placeholder comment: // cmt_0001, /* cmt_0001 */, # cmt_0001
|
|
16
|
+
COMMENT_LINE_RE = re.compile(rf"^[ \t]*(?://[ \t]*{_ID}|/\*[ \t]*{_ID}[ \t]*\*/|#[ \t]*{_ID})[ \t]*$")
|
|
17
|
+
# A placeholder comment at the end of a code line
|
|
18
|
+
TRAILING_RE = re.compile(rf"[ \t]*(?://[ \t]*{_ID}|/\*[ \t]*{_ID}[ \t]*\*/)[ \t]*$")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _norm(line: str) -> str:
|
|
22
|
+
return "".join(line.split())
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def keep(old: str | None, new: str) -> tuple[str, int]:
|
|
26
|
+
"""``new`` with the placeholder comments the AI dropped from kept code put back, and how many."""
|
|
27
|
+
if not old or "cmt_" not in old:
|
|
28
|
+
return new, 0
|
|
29
|
+
nl = "\r\n" if "\r\n" in new else "\n"
|
|
30
|
+
old_lines = old.replace("\r\n", "\n").split("\n")
|
|
31
|
+
new_lines = new.replace("\r\n", "\n").split("\n")
|
|
32
|
+
present = set(re.findall(_ID, new))
|
|
33
|
+
out: list[str] = []
|
|
34
|
+
count = 0
|
|
35
|
+
sm = difflib.SequenceMatcher(None, old_lines, new_lines, autojunk=False)
|
|
36
|
+
for op, i1, i2, j1, j2 in sm.get_opcodes():
|
|
37
|
+
olds, news = old_lines[i1:i2], new_lines[j1:j2]
|
|
38
|
+
if op == "equal" or op == "insert":
|
|
39
|
+
out += news
|
|
40
|
+
continue
|
|
41
|
+
if op == "delete":
|
|
42
|
+
# only comments (and blank lines) went: the AI dropped them, the code is still there
|
|
43
|
+
if all(COMMENT_LINE_RE.match(l) or not l.strip() for l in olds):
|
|
44
|
+
back = [l for l in olds if COMMENT_LINE_RE.match(l) and re.search(_ID, l).group(0) not in present]
|
|
45
|
+
out += back
|
|
46
|
+
count += len(back)
|
|
47
|
+
continue
|
|
48
|
+
if all(COMMENT_LINE_RE.match(l) or not l.strip() for l in olds) and not any(l.strip() for l in news):
|
|
49
|
+
# comments turned into empty lines: the comments come back in their place
|
|
50
|
+
back = [l for l in olds if COMMENT_LINE_RE.match(l) and re.search(_ID, l).group(0) not in present]
|
|
51
|
+
out += back + news[len(back):]
|
|
52
|
+
count += len(back)
|
|
53
|
+
continue
|
|
54
|
+
# replace: walk the new lines; before each one, put back the comment lines that stood right before
|
|
55
|
+
# the matching old line; restore trailing comments of lines whose code is unchanged
|
|
56
|
+
old_code = {} # normalised code -> index in olds
|
|
57
|
+
for k, l in enumerate(olds):
|
|
58
|
+
if not COMMENT_LINE_RE.match(l):
|
|
59
|
+
old_code.setdefault(_norm(TRAILING_RE.sub("", l)), k)
|
|
60
|
+
used = set()
|
|
61
|
+
for l in news:
|
|
62
|
+
k = old_code.get(_norm(TRAILING_RE.sub("", l))) if l.strip() else None
|
|
63
|
+
if k is not None and k not in used:
|
|
64
|
+
used.add(k)
|
|
65
|
+
c = k - 1
|
|
66
|
+
lead = []
|
|
67
|
+
while c >= 0 and (COMMENT_LINE_RE.match(olds[c]) or not olds[c].strip()) and c not in used:
|
|
68
|
+
if COMMENT_LINE_RE.match(olds[c]) and re.search(_ID, olds[c]).group(0) not in present:
|
|
69
|
+
lead.insert(0, olds[c])
|
|
70
|
+
used.add(c)
|
|
71
|
+
c -= 1
|
|
72
|
+
out += lead
|
|
73
|
+
count += len(lead)
|
|
74
|
+
m = TRAILING_RE.search(olds[k])
|
|
75
|
+
if m and not TRAILING_RE.search(l) and re.search(_ID, m.group(0)).group(0) not in present:
|
|
76
|
+
l = l.rstrip() + m.group(0)
|
|
77
|
+
count += 1
|
|
78
|
+
out.append(l)
|
|
79
|
+
return nl.join(out), count
|
doppelcode/config.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Per-project configuration (``<project>/.doppel/config.json``)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import copy
|
|
6
|
+
import fnmatch
|
|
7
|
+
import json
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
STATE_DIR = ".doppel"
|
|
11
|
+
LEGACY_STATE_DIR = ".cobf" # cobf <= 0.7.0b2: still read; rename it to .doppel
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def state_dir_name(root: Path) -> str:
|
|
15
|
+
""".doppel, or the old .doppel folder of a project made with DoppelCode (until it is renamed)."""
|
|
16
|
+
if not (root / STATE_DIR).exists() and (root / LEGACY_STATE_DIR).is_dir():
|
|
17
|
+
return LEGACY_STATE_DIR
|
|
18
|
+
return STATE_DIR
|
|
19
|
+
|
|
20
|
+
DEFAULT_CONFIG: dict = {
|
|
21
|
+
"twin_dir": None, # default: <parent>/obf_<hash6>
|
|
22
|
+
"c_extensions": [".c", ".h"],
|
|
23
|
+
# build templates (*.cmake.in, *.h.in, *.pc.in) and packaging files (pyproject.toml, setup.cfg,
|
|
24
|
+
# MANIFEST.in, requirements*.txt) are text: the twin needs them to build with the project's own tools
|
|
25
|
+
"text_extensions": [".txt", ".md", ".mk", ".cmake", ".json", ".yml", ".yaml", ".ld", ".cfg", ".ini", ".in", ".am", ".ac", ".inc",
|
|
26
|
+
".rc", ".def", ".pl", ".pm", ".sh", ".bash", ".bat", ".cmd", ".ps1", ".awk",
|
|
27
|
+
".toml"],
|
|
28
|
+
"text_filenames": ["Makefile", "makefile", "GNUmakefile", "CMakeLists.txt", "MANIFEST.in", "setup.cfg",
|
|
29
|
+
"Makefile.inc"],
|
|
30
|
+
"ignore": [".git", ".svn", ".hg", ".doppel", ".cobf", ".vscode", ".vs", ".idea", ".claude", ".settings", ".metadata",
|
|
31
|
+
"build", "*.o", "*.obj", "*.exe", "*.a", "*.lib", "*.so", "*.dll", "*.elf", "*.bin", "*.hex",
|
|
32
|
+
"*.map", "*.suo", "*.user", "*.sdf", "*.ipch", "*.code-workspace", "c_cpp_properties.json"],
|
|
33
|
+
"exclude": [], # third-party: copied verbatim, its identifiers are kept
|
|
34
|
+
"copy_verbatim": [], # other files to copy unchanged (default: not copied)
|
|
35
|
+
"keep": [], # identifiers never renamed
|
|
36
|
+
"keep_prefixes": [],
|
|
37
|
+
"keep_regex": [],
|
|
38
|
+
"force_rename": [], # renamed even if they look external
|
|
39
|
+
"build_names": "keep", # "keep" | "rename": build-file names made of project name parts
|
|
40
|
+
"rename_words": [], # extra words renamed everywhere (e.g. binary names in Makefile)
|
|
41
|
+
"keep_short": 2, # identifiers with len <= this are kept
|
|
42
|
+
"naming": "kind", # "kind" (fn_0001, v_0001, T_0001, M_0001) or "opaque" (id_0001)
|
|
43
|
+
"comments": "scrub", # "keep" | "scrub" (names only) | "hide" (whole comment -> // cmt_0001)
|
|
44
|
+
"data_files": "none", # "none" | "build": copy the text files build files name (build inputs)
|
|
45
|
+
# | "copy": also the data files the code names, renamed
|
|
46
|
+
"strings": "scrub", # "keep" | "scrub" (names only) | "hide" (literal -> "str_0001 %d\n");
|
|
47
|
+
# default "hide" when functions are withheld or secrets are marked
|
|
48
|
+
"rename_files": True, # not set: false when the project has a CMake build (or a build file
|
|
49
|
+
# that computes file paths), so the twin builds with it
|
|
50
|
+
"keep_test_names": True, # pytest projects: test_* / Test* / pytest_* names and pytest's fixture
|
|
51
|
+
# names stay (pytest finds them by name; the test names are visible)
|
|
52
|
+
"rename_dirs": False,
|
|
53
|
+
"compiler": None, # default: auto-detect gcc/clang
|
|
54
|
+
"include_dirs": [], # extra system include dirs to harvest
|
|
55
|
+
"cxx_compiler": None, # g++ / clang++ for C++ (default: next to the C compiler)
|
|
56
|
+
"javac": None, # Java compiler (default: PATH, JAVA_HOME, ~/.jdks, Android Studio)
|
|
57
|
+
"csc": None, # C# compiler (default: Visual Studio Roslyn, .NET SDK, .NET Framework)
|
|
58
|
+
"node": None, # Node.js for the JS / TS syntax check (default: PATH, then VS Code's)
|
|
59
|
+
"compile_flags": [], # extra flags for the compile check; [] = the compiler's default
|
|
60
|
+
# C dialect, like a plain "gcc main.c" build (e.g. M_PI is defined)
|
|
61
|
+
"sensitive_terms": [], # substrings that must not appear in the twin (leak check)
|
|
62
|
+
"leak_allow": [], # words the owner accepts in the twin (the public project name, ...):
|
|
63
|
+
# not reported by check; secret values and absolute paths always are
|
|
64
|
+
"secret_symbols": [], # secret constants: every number assigned to these names (original names)
|
|
65
|
+
"secret_values": [], # secret constants: every occurrence of these literals ("0.97", "145")
|
|
66
|
+
"secret_files": [], # every `secrets suggest` candidate in these files / folders is secret
|
|
67
|
+
"secret_functions": [], # ... and in these functions ("src/f.c::func", "m.py::Class" = all methods)
|
|
68
|
+
"core_functions": [], # bodies withheld from the AI: "file.py::Class.method", "src/f.c::func"
|
|
69
|
+
"core_modules": [], # every function body of these files / folders is withheld ("dsp/")
|
|
70
|
+
"withheld_purpose": {}, # optional, "file.py::func" -> one line written by the owner, listed in
|
|
71
|
+
# the twin's AGENTS.md so the AI picks the right withheld function
|
|
72
|
+
"exposure_budget": {}, # folder -> max share of its function bodies ever exported, {"dsp/": 0.3}
|
|
73
|
+
"twin_ignore": [".git", ".claude", ".vscode", ".idea", "build", "__pycache__", "*.pyc"],
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
PROTECTION_KEYS = ("core_functions", "core_modules", "secret_symbols", "secret_values", "secret_files",
|
|
78
|
+
"secret_functions")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def user_config(root: Path) -> dict:
|
|
82
|
+
"""Only what <project>/.doppel/config.json sets (no defaults)."""
|
|
83
|
+
path = root / state_dir_name(root) / "config.json"
|
|
84
|
+
if not path.exists():
|
|
85
|
+
return {}
|
|
86
|
+
user = json.loads(path.read_text(encoding="utf-8"))
|
|
87
|
+
unknown = set(user) - set(DEFAULT_CONFIG)
|
|
88
|
+
if unknown:
|
|
89
|
+
raise ValueError(f"{path}: unknown config keys {sorted(unknown)}")
|
|
90
|
+
return user
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def load_config(root: Path) -> dict:
|
|
94
|
+
cfg = copy.deepcopy(DEFAULT_CONFIG)
|
|
95
|
+
user = user_config(root)
|
|
96
|
+
cfg.update(user)
|
|
97
|
+
# Withheld functions / secret constants: user-facing strings would still tell the purpose and the
|
|
98
|
+
# features ("ACCURATE REAL-TIME GENDER VOICE DETECTOR", pilot round 2 R2.3), so strings are hidden
|
|
99
|
+
# unless the project sets "strings" itself.
|
|
100
|
+
if "strings" not in user and any(cfg[k] for k in PROTECTION_KEYS):
|
|
101
|
+
cfg["strings"] = "hide"
|
|
102
|
+
cfg["strings_by_default"] = True
|
|
103
|
+
return cfg
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# decided from the project when the config does not set them (see Project._auto_config)
|
|
107
|
+
AUTO_KEYS = ("rename_files", "keep_test_names")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def write_default_config(root: Path) -> Path:
|
|
111
|
+
path = root / state_dir_name(root) / "config.json"
|
|
112
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
113
|
+
if not path.exists():
|
|
114
|
+
data = {k: v for k, v in DEFAULT_CONFIG.items() if k not in AUTO_KEYS}
|
|
115
|
+
path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
|
|
116
|
+
return path
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
COMMENT_MODES = ("keep", "scrub", "hide")
|
|
120
|
+
STRING_MODES = ("keep", "scrub", "hide")
|
|
121
|
+
DATA_MODES = ("none", "build", "copy")
|
|
122
|
+
BUILD_NAME_MODES = ("keep", "rename")
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def set_config_value(root: Path, key: str, value) -> Path:
|
|
126
|
+
"""Set one key in <project>/.doppel/config.json (created with only that key if missing)."""
|
|
127
|
+
if key not in DEFAULT_CONFIG:
|
|
128
|
+
raise ValueError(f"unknown config key {key}")
|
|
129
|
+
path = root / state_dir_name(root) / "config.json"
|
|
130
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
131
|
+
data = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
|
|
132
|
+
if data.get(key) != value:
|
|
133
|
+
data[key] = value
|
|
134
|
+
tmp = path.with_suffix(".tmp")
|
|
135
|
+
tmp.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
|
|
136
|
+
tmp.replace(path)
|
|
137
|
+
return path
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def path_matches(rel: str, patterns: list[str]) -> bool:
|
|
141
|
+
"""Match a posix relative path against glob patterns.
|
|
142
|
+
|
|
143
|
+
A pattern without '/' matches any single path component (``build`` matches
|
|
144
|
+
``a/build/x.c``); a pattern with '/' matches the path or a directory prefix.
|
|
145
|
+
"""
|
|
146
|
+
parts = rel.split("/")
|
|
147
|
+
for pat in patterns:
|
|
148
|
+
pat = pat.rstrip("/")
|
|
149
|
+
if "/" not in pat:
|
|
150
|
+
if any(fnmatch.fnmatchcase(p, pat) for p in parts):
|
|
151
|
+
return True
|
|
152
|
+
continue
|
|
153
|
+
base = pat[:-3] if pat.endswith("/**") else pat
|
|
154
|
+
if fnmatch.fnmatchcase(rel, pat) or fnmatch.fnmatchcase(rel, base) or rel.startswith(base + "/"):
|
|
155
|
+
return True
|
|
156
|
+
return False
|
doppelcode/declare.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
"""What a source file declares, for the languages with the "declared" renaming policy.
|
|
2
|
+
|
|
3
|
+
``scan(src, tokens, lang)`` returns a FileDecl:
|
|
4
|
+
declared name -> kind ("type" | "func" | "var") for names the file defines
|
|
5
|
+
members (receiver, name) pairs of member accesses: obj.name, obj?.name, obj->name, A::name
|
|
6
|
+
imports names bound by imports of other modules (import X, using X.Y, require(...))
|
|
7
|
+
modules module names imported (Python), for harvesting their public names
|
|
8
|
+
|
|
9
|
+
Python uses the standard ``ast`` module (precise); C#, Java, JavaScript and TypeScript use token
|
|
10
|
+
patterns: type-introducing keywords, typed declarations ("Type name =", "Type name)"), JS
|
|
11
|
+
const/let/var/function, parameters of function definitions, arrow functions and lambdas.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import ast
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
|
|
19
|
+
from . import lexer
|
|
20
|
+
from . import pyparse
|
|
21
|
+
from .languages import LANGUAGES
|
|
22
|
+
|
|
23
|
+
TYPE, FUNC, VAR = "type", "func", "var"
|
|
24
|
+
|
|
25
|
+
_TYPE_INTRO = {"class", "struct", "interface", "enum", "record", "namespace", "type", "trait", "delegate"}
|
|
26
|
+
_MODIFIERS = {"public", "private", "protected", "internal", "static", "readonly", "const", "final", "abstract",
|
|
27
|
+
"virtual", "override", "sealed", "async", "extern", "volatile", "transient", "synchronized",
|
|
28
|
+
"native", "partial", "new", "unsafe", "required", "default", "export", "declare", "get", "set",
|
|
29
|
+
"fixed", "ref", "out", "in", "params", "this", "scoped", "let", "var", "val"}
|
|
30
|
+
_NOT_TYPE = {"return", "new", "throw", "else", "case", "goto", "using", "in", "is", "as", "await", "yield",
|
|
31
|
+
"typeof", "sizeof", "nameof", "instanceof", "delete", "void", "of", "extends", "implements",
|
|
32
|
+
"import", "package", "from", "with", "when", "and", "or", "not", "break", "continue", "do"}
|
|
33
|
+
_AFTER_DECL = {";", "=", ",", ")", "(", "[", "{", ":"}
|
|
34
|
+
_SELF = {"this", "self", "cls", "base", "super"}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class FileDecl:
|
|
39
|
+
declared: dict[str, str] = field(default_factory=dict)
|
|
40
|
+
members: list[tuple[str, str]] = field(default_factory=list)
|
|
41
|
+
imports: set[str] = field(default_factory=set)
|
|
42
|
+
import_pairs: list[tuple[str, str, bool]] = field(default_factory=list) # (name, module, relative)
|
|
43
|
+
by_path: bool = False # JS / TS: modules are named by path ("crypto" external, "./x" project)
|
|
44
|
+
modules: set[str] = field(default_factory=set)
|
|
45
|
+
kwargs: list[tuple[str, str]] = field(default_factory=list) # (callee root name, keyword)
|
|
46
|
+
member_declared: set[str] | None = None # Python: names defined AS members (methods, self.x, fields)
|
|
47
|
+
overrides: list[tuple[tuple[str, ...], str]] = field(default_factory=list) # (base roots, method)
|
|
48
|
+
|
|
49
|
+
def add(self, name: str, kind: str) -> None:
|
|
50
|
+
prio = {VAR: 0, FUNC: 1, TYPE: 2}
|
|
51
|
+
if name and prio[kind] >= prio.get(self.declared.get(name, VAR), 0):
|
|
52
|
+
self.declared[name] = kind
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def scan(src: str, tokens: list[lexer.Token], lang: str) -> FileDecl:
|
|
56
|
+
if lang == "python":
|
|
57
|
+
return _python(src, tokens)
|
|
58
|
+
return _clike(tokens, lang)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# -- members (shared) ---------------------------------------------------------------------------------
|
|
62
|
+
def _members(sig: list[lexer.Token], out: FileDecl) -> None:
|
|
63
|
+
for k in range(2, len(sig)):
|
|
64
|
+
t = sig[k]
|
|
65
|
+
if t.kind != lexer.IDENT:
|
|
66
|
+
continue
|
|
67
|
+
p1, p2 = sig[k - 1].text, sig[k - 2]
|
|
68
|
+
recv = None
|
|
69
|
+
if p1 == "." and p2.kind == lexer.IDENT:
|
|
70
|
+
recv = p2.text
|
|
71
|
+
elif p1 == "." and k >= 3 and p2.text == "?" and sig[k - 3].kind == lexer.IDENT: # a?.b
|
|
72
|
+
recv = sig[k - 3].text
|
|
73
|
+
elif p1 in (">", ":") and k >= 3 and p2.text in ("-", ":") and sig[k - 3].kind == lexer.IDENT:
|
|
74
|
+
recv = sig[k - 3].text # a->b, A::b
|
|
75
|
+
elif p1 == "." and p2.text in (")", "]"):
|
|
76
|
+
recv = "?" # f().x: unknown
|
|
77
|
+
if recv is not None:
|
|
78
|
+
out.members.append((recv, t.text))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
# -- C#, Java, JavaScript, TypeScript -----------------------------------------------------------------
|
|
82
|
+
def _match_paren(sig: list[lexer.Token], k: int) -> int:
|
|
83
|
+
depth = 0
|
|
84
|
+
for j in range(k, len(sig)):
|
|
85
|
+
if sig[j].text == "(":
|
|
86
|
+
depth += 1
|
|
87
|
+
elif sig[j].text == ")":
|
|
88
|
+
depth -= 1
|
|
89
|
+
if depth == 0:
|
|
90
|
+
return j
|
|
91
|
+
return len(sig) - 1
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _clike(tokens: list[lexer.Token], lang: str) -> FileDecl:
|
|
95
|
+
out = FileDecl(by_path=lang in ("javascript", "typescript"))
|
|
96
|
+
profile = LANGUAGES[lang]
|
|
97
|
+
sig = [t for t in tokens if t.kind not in (lexer.WS, lexer.NEWLINE, lexer.COMMENT) and t.directive is None]
|
|
98
|
+
js = lang in ("javascript", "typescript")
|
|
99
|
+
type_keywords = {"int", "long", "short", "byte", "char", "float", "double", "decimal", "bool", "boolean",
|
|
100
|
+
"string", "object", "var", "void", "dynamic", "uint", "ulong", "ushort", "sbyte", "nint",
|
|
101
|
+
"nuint", "number", "any", "unknown", "never", "bigint", "symbol"}
|
|
102
|
+
n = len(sig)
|
|
103
|
+
|
|
104
|
+
def text(j: int) -> str | None:
|
|
105
|
+
return sig[j].text if 0 <= j < n else None
|
|
106
|
+
|
|
107
|
+
def is_ident(j: int) -> bool:
|
|
108
|
+
return 0 <= j < n and sig[j].kind == lexer.IDENT
|
|
109
|
+
|
|
110
|
+
def params(open_k: int) -> None:
|
|
111
|
+
"""Names in a parameter list ( ... ): identifiers followed by , ) = : ? (after an optional type)."""
|
|
112
|
+
close = _match_paren(sig, open_k)
|
|
113
|
+
depth = 0
|
|
114
|
+
for j in range(open_k + 1, close):
|
|
115
|
+
tx = sig[j].text
|
|
116
|
+
if tx in "([{<":
|
|
117
|
+
depth += 1
|
|
118
|
+
elif tx in ")]}>":
|
|
119
|
+
depth -= 1
|
|
120
|
+
elif depth == 0 and is_ident(j) and text(j + 1) in (",", ")", "=", ":", "?") \
|
|
121
|
+
and sig[j].text not in profile.keywords:
|
|
122
|
+
if text(j - 1) != "=" and text(j - 1) != ".":
|
|
123
|
+
out.add(sig[j].text, VAR)
|
|
124
|
+
|
|
125
|
+
for k, t in enumerate(sig):
|
|
126
|
+
tx = t.text
|
|
127
|
+
# imports bound to names
|
|
128
|
+
if tx in ("using", "import") and (lang in ("csharp", "java") or js) and text(k + 1) != "(":
|
|
129
|
+
j = k + 1
|
|
130
|
+
bound, path = [], ""
|
|
131
|
+
while j < n and text(j) != ";" and not (js and j > k + 1 and sig[j - 1].kind == lexer.STRING):
|
|
132
|
+
if is_ident(j) and text(j) not in ("static", "from", "as", "type", "default", "global"):
|
|
133
|
+
bound.append(sig[j].text)
|
|
134
|
+
elif sig[j].kind == lexer.STRING:
|
|
135
|
+
path = sig[j].text.strip("'\"`")
|
|
136
|
+
j += 1
|
|
137
|
+
dotted = path or ".".join(bound)
|
|
138
|
+
if lang == "csharp" and any(sig[x].text in ("(", "var", "new", "await") for x in range(k + 1, j)):
|
|
139
|
+
bound = [] # "using var x = new ..." / "using (...)" is a statement
|
|
140
|
+
for name in bound:
|
|
141
|
+
out.imports.add(name)
|
|
142
|
+
out.import_pairs.append((name, dotted, dotted.startswith(".")))
|
|
143
|
+
continue
|
|
144
|
+
if js and tx == "require" and text(k + 1) == "(" and n > k + 2 and sig[k + 2].kind == lexer.STRING:
|
|
145
|
+
path = sig[k + 2].text.strip("'\"`")
|
|
146
|
+
j = k - 2
|
|
147
|
+
names = []
|
|
148
|
+
if is_ident(j) and text(k - 1) == "=":
|
|
149
|
+
names = [sig[j].text]
|
|
150
|
+
elif text(k - 1) == "=" and text(k - 2) == "}": # const { A, B } = require(...)
|
|
151
|
+
j = k - 3
|
|
152
|
+
while j >= 0 and text(j) != "{":
|
|
153
|
+
if is_ident(j) and text(j - 1) != ":":
|
|
154
|
+
names.append(sig[j].text)
|
|
155
|
+
j -= 1
|
|
156
|
+
for name in names:
|
|
157
|
+
out.imports.add(name)
|
|
158
|
+
out.import_pairs.append((name, path, path.startswith(".")))
|
|
159
|
+
if t.kind != lexer.IDENT or tx in profile.keywords and tx not in type_keywords:
|
|
160
|
+
# arrow functions: ( params ) => / ( params ) ->
|
|
161
|
+
if tx == ")" and ((text(k + 1) == "=" and text(k + 2) == ">") or
|
|
162
|
+
(lang == "java" and text(k + 1) == "-" and text(k + 2) == ">")):
|
|
163
|
+
depth, j = 0, k
|
|
164
|
+
while j >= 0:
|
|
165
|
+
if sig[j].text == ")":
|
|
166
|
+
depth += 1
|
|
167
|
+
elif sig[j].text == "(":
|
|
168
|
+
depth -= 1
|
|
169
|
+
if depth == 0:
|
|
170
|
+
break
|
|
171
|
+
j -= 1
|
|
172
|
+
if j >= 0:
|
|
173
|
+
params(j)
|
|
174
|
+
continue
|
|
175
|
+
prev, nxt = text(k - 1), text(k + 1)
|
|
176
|
+
# JS / TS: this.name = ... declares a field
|
|
177
|
+
if js and prev == "." and text(k - 2) == "this" and nxt == "=" and text(k + 2) not in ("=", ">"):
|
|
178
|
+
out.add(tx, VAR)
|
|
179
|
+
continue
|
|
180
|
+
# x => ... / x -> ... (single-parameter lambda)
|
|
181
|
+
if (nxt == "=" and text(k + 2) == ">") or (lang == "java" and nxt == "-" and text(k + 2) == ">"):
|
|
182
|
+
if prev not in (".",):
|
|
183
|
+
out.add(tx, VAR)
|
|
184
|
+
continue
|
|
185
|
+
if prev in _TYPE_INTRO and not (prev == "type" and lang != "typescript"):
|
|
186
|
+
out.add(tx, TYPE)
|
|
187
|
+
continue
|
|
188
|
+
if js and prev == "function" or (js and prev == "*" and text(k - 2) == "function"):
|
|
189
|
+
out.add(tx, FUNC)
|
|
190
|
+
if nxt == "(":
|
|
191
|
+
params(k + 1)
|
|
192
|
+
continue
|
|
193
|
+
if js and prev in ("const", "let", "var"):
|
|
194
|
+
out.add(tx, VAR)
|
|
195
|
+
continue
|
|
196
|
+
if js and prev in ("{", "[", ",") and _in_destructuring(sig, k):
|
|
197
|
+
if nxt != ":" or text(k + 2) is None:
|
|
198
|
+
out.add(tx, VAR)
|
|
199
|
+
continue
|
|
200
|
+
if js and prev == "function" and nxt == "(":
|
|
201
|
+
params(k + 1)
|
|
202
|
+
# JS/TS class members: name( ... ) { and fields name = / name: (in a class body)
|
|
203
|
+
if js and nxt == "(" and prev in ("{", "}", ";", "static", "async", "get", "set", "*", "public",
|
|
204
|
+
"private", "protected", "readonly", "override"):
|
|
205
|
+
close = _match_paren(sig, k + 1)
|
|
206
|
+
if text(close + 1) in ("{", ":"):
|
|
207
|
+
out.add(tx, FUNC)
|
|
208
|
+
params(k + 1)
|
|
209
|
+
continue
|
|
210
|
+
# typed declarations: Type name ;|=|,|)|(|[|{|:
|
|
211
|
+
if nxt in _AFTER_DECL or (lang == "csharp" and nxt == "in") or (lang == "java" and nxt == ":"):
|
|
212
|
+
p = k - 1
|
|
213
|
+
if text(p) in ("?", "*"): # nullable / pointer
|
|
214
|
+
p -= 1
|
|
215
|
+
type_ok = False
|
|
216
|
+
if is_ident(p) and text(p) not in _NOT_TYPE and (text(p) not in profile.keywords
|
|
217
|
+
or text(p) in type_keywords):
|
|
218
|
+
before = text(p - 1)
|
|
219
|
+
type_ok = before in (None, "{", "}", ";", "(", ",", "<", "[", ")", ".") or before in _MODIFIERS \
|
|
220
|
+
or (before is not None and before in profile.keywords) or before == ">"
|
|
221
|
+
if before == "." and lang != "csharp" and lang != "java":
|
|
222
|
+
type_ok = False
|
|
223
|
+
elif text(p) in (">", "]"): # generic / array type
|
|
224
|
+
type_ok = True
|
|
225
|
+
if js and lang == "javascript":
|
|
226
|
+
type_ok = False # JS has no typed declarations
|
|
227
|
+
if lang == "typescript" and not (text(p) in (">", "]") or text(p) in type_keywords):
|
|
228
|
+
type_ok = type_ok and text(p - 1) not in (".",) and text(p) in type_keywords
|
|
229
|
+
if type_ok:
|
|
230
|
+
kind = FUNC if nxt == "(" else VAR
|
|
231
|
+
out.add(tx, kind)
|
|
232
|
+
if nxt == "(":
|
|
233
|
+
params(k + 1)
|
|
234
|
+
continue
|
|
235
|
+
# TypeScript / JS: "name: Type" fields and parameters inside a class body or parameter list
|
|
236
|
+
if lang == "typescript" and nxt == ":" and prev in ("{", ";", ",", "(", "readonly", "public",
|
|
237
|
+
"private", "protected", "static"):
|
|
238
|
+
out.add(tx, VAR)
|
|
239
|
+
_members(sig, out)
|
|
240
|
+
return out
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _in_destructuring(sig: list[lexer.Token], k: int) -> bool:
|
|
244
|
+
"""True when sig[k] sits in a { ... } or [ ... ] pattern right after const/let/var."""
|
|
245
|
+
depth = 0
|
|
246
|
+
for j in range(k - 1, -1, -1):
|
|
247
|
+
tx = sig[j].text
|
|
248
|
+
if tx in ("}", "]"):
|
|
249
|
+
depth += 1
|
|
250
|
+
elif tx in ("{", "["):
|
|
251
|
+
if depth == 0:
|
|
252
|
+
return j > 0 and sig[j - 1].text in ("const", "let", "var")
|
|
253
|
+
depth -= 1
|
|
254
|
+
elif tx in (";", "=", "(", ")"):
|
|
255
|
+
return False
|
|
256
|
+
return False
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
# -- Python --------------------------------------------------------------------------------------------
|
|
260
|
+
def _python(src: str, tokens: list[lexer.Token]) -> FileDecl:
|
|
261
|
+
out = FileDecl()
|
|
262
|
+
try:
|
|
263
|
+
tree = pyparse.parse(src)
|
|
264
|
+
except (SyntaxError, ValueError):
|
|
265
|
+
return _python_fallback(tokens)
|
|
266
|
+
for node in ast.walk(tree):
|
|
267
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
268
|
+
out.add(node.name, FUNC)
|
|
269
|
+
a = node.args
|
|
270
|
+
for arg in [*a.posonlyargs, *a.args, *a.kwonlyargs, a.vararg, a.kwarg]:
|
|
271
|
+
if arg is not None:
|
|
272
|
+
out.add(arg.arg, VAR)
|
|
273
|
+
elif isinstance(node, ast.Lambda):
|
|
274
|
+
a = node.args
|
|
275
|
+
for arg in [*a.posonlyargs, *a.args, *a.kwonlyargs, a.vararg, a.kwarg]:
|
|
276
|
+
if arg is not None:
|
|
277
|
+
out.add(arg.arg, VAR)
|
|
278
|
+
elif isinstance(node, ast.ClassDef):
|
|
279
|
+
out.add(node.name, TYPE)
|
|
280
|
+
roots = tuple(r for r in (_root(b) for b in node.bases) if r)
|
|
281
|
+
if roots: # methods may override / implement the base's hooks
|
|
282
|
+
for item in node.body:
|
|
283
|
+
if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
284
|
+
out.overrides.append((roots, item.name))
|
|
285
|
+
elif isinstance(node, ast.Call):
|
|
286
|
+
root = _root(node.func) or "?"
|
|
287
|
+
for kw in node.keywords:
|
|
288
|
+
if kw.arg:
|
|
289
|
+
out.kwargs.append((root, kw.arg))
|
|
290
|
+
elif isinstance(node, ast.Name) and isinstance(node.ctx, (ast.Store, ast.Del)):
|
|
291
|
+
out.add(node.id, VAR)
|
|
292
|
+
elif isinstance(node, ast.Attribute) and isinstance(node.ctx, ast.Store):
|
|
293
|
+
out.add(node.attr, VAR)
|
|
294
|
+
elif isinstance(node, (ast.Global, ast.Nonlocal)):
|
|
295
|
+
for name in node.names:
|
|
296
|
+
out.add(name, VAR)
|
|
297
|
+
elif isinstance(node, ast.ExceptHandler) and node.name:
|
|
298
|
+
out.add(node.name, VAR)
|
|
299
|
+
elif isinstance(node, ast.Import):
|
|
300
|
+
for alias in node.names:
|
|
301
|
+
out.modules.add(alias.name)
|
|
302
|
+
bound = alias.asname or alias.name.split(".")[0]
|
|
303
|
+
out.imports.add(bound)
|
|
304
|
+
out.import_pairs.append((bound, alias.name, False))
|
|
305
|
+
elif isinstance(node, ast.ImportFrom):
|
|
306
|
+
if node.module and node.level == 0:
|
|
307
|
+
out.modules.add(node.module)
|
|
308
|
+
for alias in node.names:
|
|
309
|
+
out.imports.add(alias.asname or alias.name)
|
|
310
|
+
out.import_pairs.append((alias.name, node.module or "", node.level > 0))
|
|
311
|
+
if alias.asname:
|
|
312
|
+
out.add(alias.asname, VAR)
|
|
313
|
+
elif hasattr(ast, "MatchAs") and isinstance(node, ast.MatchAs) and node.name:
|
|
314
|
+
out.add(node.name, VAR)
|
|
315
|
+
elif hasattr(ast, "MatchStar") and isinstance(node, ast.MatchStar) and node.name:
|
|
316
|
+
out.add(node.name, VAR)
|
|
317
|
+
out.member_declared = set()
|
|
318
|
+
for node in ast.walk(tree):
|
|
319
|
+
if isinstance(node, ast.ClassDef):
|
|
320
|
+
for item in node.body:
|
|
321
|
+
if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
322
|
+
out.member_declared.add(item.name)
|
|
323
|
+
elif isinstance(item, (ast.Assign, ast.AnnAssign)):
|
|
324
|
+
for t in (item.targets if isinstance(item, ast.Assign) else [item.target]):
|
|
325
|
+
if isinstance(t, ast.Name):
|
|
326
|
+
out.member_declared.add(t.id)
|
|
327
|
+
elif isinstance(node, ast.Attribute) and isinstance(node.ctx, ast.Store):
|
|
328
|
+
out.member_declared.add(node.attr)
|
|
329
|
+
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) and \
|
|
330
|
+
node in getattr(tree, "body", []):
|
|
331
|
+
out.member_declared.add(node.name) # module-level: reachable as module.name
|
|
332
|
+
sig = [t for t in tokens if t.kind not in (lexer.WS, lexer.NEWLINE, lexer.COMMENT)]
|
|
333
|
+
_members(sig, out)
|
|
334
|
+
return out
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _root(node: ast.AST) -> str | None:
|
|
338
|
+
"""Leftmost name of an expression: json.dumps -> json, a.b.c() -> a, Base[T] -> Base."""
|
|
339
|
+
while True:
|
|
340
|
+
if isinstance(node, ast.Name):
|
|
341
|
+
return node.id
|
|
342
|
+
if isinstance(node, (ast.Attribute, ast.Subscript, ast.Call)):
|
|
343
|
+
node = node.value if not isinstance(node, ast.Call) else node.func
|
|
344
|
+
continue
|
|
345
|
+
return None
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _python_fallback(tokens: list[lexer.Token]) -> FileDecl:
|
|
349
|
+
"""Snippets that do not parse: def / class names and simple assignments."""
|
|
350
|
+
out = FileDecl()
|
|
351
|
+
sig = [t for t in tokens if t.kind not in (lexer.WS, lexer.COMMENT)]
|
|
352
|
+
for k, t in enumerate(sig):
|
|
353
|
+
if t.kind != lexer.IDENT:
|
|
354
|
+
continue
|
|
355
|
+
prev = sig[k - 1].text if k else "\n"
|
|
356
|
+
nxt = sig[k + 1].text if k + 1 < len(sig) else ""
|
|
357
|
+
if prev == "def":
|
|
358
|
+
out.add(t.text, FUNC)
|
|
359
|
+
elif prev == "class":
|
|
360
|
+
out.add(t.text, TYPE)
|
|
361
|
+
elif prev in ("\n", "for", ",") and nxt in ("=", ",", "in") and t.text not in LANGUAGES["python"].keywords:
|
|
362
|
+
out.add(t.text, VAR)
|
|
363
|
+
_members([t for t in sig if t.kind != lexer.NEWLINE], out)
|
|
364
|
+
return out
|