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/__init__.py
ADDED
doppelcode/__main__.py
ADDED
doppelcode/aliascheck.py
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
"""Import safety for alias-shaped names the AI wrote itself.
|
|
2
|
+
|
|
3
|
+
The reverse mapping turns every DoppelCode alias back into its real name. That is right for plain uses of
|
|
4
|
+
existing names (`fn_0002(ctx)`), but wrong when the AI *coins* a name in DoppelCode's style: a new parameter
|
|
5
|
+
called `v_0048` would silently become `fips_expected`, a new string "str_0013" would become "ALL PASS".
|
|
6
|
+
|
|
7
|
+
On the lines the AI added or changed, three things are flagged (plain references stay silent):
|
|
8
|
+
|
|
9
|
+
declares a known alias in a declaration position (function, parameter, local, field, type, macro)
|
|
10
|
+
that the old version of the same file did not declare - the AI reused it for something new
|
|
11
|
+
unknown an alias-shaped name that is not in the vault (`fn_0017`): a new name in DoppelCode's style
|
|
12
|
+
string a string literal that is exactly "str_NNNN" and was not in the old version of the file
|
|
13
|
+
|
|
14
|
+
Flagged files are not merged until every finding is resolved with --rename OLD=new or --accept.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import difflib
|
|
20
|
+
import re
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
|
|
23
|
+
from . import lexer, strhide
|
|
24
|
+
from .languages import LANGUAGES
|
|
25
|
+
from .vault import KIND_PREFIX, OPAQUE_PREFIX
|
|
26
|
+
|
|
27
|
+
_PREFIXES = sorted({p.rstrip("_") for p in KIND_PREFIX.values()} | {OPAQUE_PREFIX.rstrip("_")}, key=len,
|
|
28
|
+
reverse=True)
|
|
29
|
+
ALIAS_RE = re.compile(r"(?:%s)_\d{4,}" % "|".join(_PREFIXES))
|
|
30
|
+
STRING_ID_BODY_RE = re.compile(r"str_\d{4,}")
|
|
31
|
+
KIND_OF_PREFIX = {p.rstrip("_"): k for k, p in KIND_PREFIX.items()}
|
|
32
|
+
|
|
33
|
+
_SKIP = (lexer.WS, lexer.NEWLINE, lexer.COMMENT)
|
|
34
|
+
_START = {"", "(", ",", ";", "{", "}"}
|
|
35
|
+
_QUALIFIERS = {
|
|
36
|
+
"const", "static", "extern", "volatile", "register", "inline", "unsigned", "signed", "long", "short",
|
|
37
|
+
"struct", "enum", "union", "public", "private", "protected", "internal", "final", "readonly", "override",
|
|
38
|
+
"virtual", "async", "export", "sealed", "abstract", "mutable", "constexpr", "thread_local", "transient",
|
|
39
|
+
"synchronized", "default", "out", "ref", "in", "params", "this", "partial", "unsafe", "new",
|
|
40
|
+
}
|
|
41
|
+
_TYPE_KEYWORDS = {
|
|
42
|
+
"int", "char", "void", "float", "double", "long", "short", "unsigned", "signed", "bool", "_Bool", "auto",
|
|
43
|
+
"byte", "sbyte", "ushort", "uint", "ulong", "decimal", "string", "object", "boolean", "number", "any",
|
|
44
|
+
"dynamic", "wchar_t", "char16_t", "char32_t", "char8_t",
|
|
45
|
+
}
|
|
46
|
+
_TYPE_INTRO = {"struct", "union", "enum", "class", "interface", "record", "namespace"}
|
|
47
|
+
_BINDING_KW = {
|
|
48
|
+
"javascript": {"var", "let", "const", "function"},
|
|
49
|
+
"typescript": {"var", "let", "const", "function", "type"},
|
|
50
|
+
"csharp": {"var", "delegate"},
|
|
51
|
+
"java": {"var"},
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class Finding:
|
|
57
|
+
rel: str # twin path of the file
|
|
58
|
+
line: int
|
|
59
|
+
token: str # the alias as the AI wrote it (for strings: str_NNNN, without quotes)
|
|
60
|
+
kind: str # "declares" | "unknown" | "string"
|
|
61
|
+
meaning: str | None # what the alias means in the vault (None: not in the vault)
|
|
62
|
+
value: str | None = None # "secret": the literal that replaced the alias
|
|
63
|
+
|
|
64
|
+
def describe(self) -> str:
|
|
65
|
+
where = f"{self.rel}:{self.line}"
|
|
66
|
+
if self.kind == "withheld":
|
|
67
|
+
return (f"{where}: edit to withheld function {self.token} ({self.meaning}) not merged - apply it on "
|
|
68
|
+
f"the original yourself, or take the AI's version with --accept {self.token}")
|
|
69
|
+
if self.kind == "secret":
|
|
70
|
+
return (f"{where}: {self.token} is a secret constant the AI replaced by the literal {self.value} - "
|
|
71
|
+
f"--accept {self.token} takes {self.value}, --rename {self.token}=@keep keeps the secret, "
|
|
72
|
+
f"--rename {self.token}=@secret takes {self.value} and marks it secret")
|
|
73
|
+
if self.kind == "declares":
|
|
74
|
+
return (f"{where}: {self.token} is declared here as something new, but {self.token} already means "
|
|
75
|
+
f"'{self.meaning}' - it would be restored as '{self.meaning}'")
|
|
76
|
+
if self.kind == "unknown":
|
|
77
|
+
return f"{where}: {self.token} is a new name in DoppelCode's alias style (not in the vault)"
|
|
78
|
+
if self.meaning is not None:
|
|
79
|
+
return (f"{where}: \"{self.token}\" is a new string, but {self.token} already means "
|
|
80
|
+
f"{self.meaning} - it would be restored as that text")
|
|
81
|
+
return f"{where}: \"{self.token}\" is a new string in DoppelCode's placeholder style (not in the vault)"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def changed_lines(old: str | None, new: str) -> set[int]:
|
|
85
|
+
"""1-based numbers of the lines in ``new`` that were added or changed relative to ``old``."""
|
|
86
|
+
new_lines = new.splitlines()
|
|
87
|
+
if old is None:
|
|
88
|
+
return set(range(1, len(new_lines) + 1))
|
|
89
|
+
sm = difflib.SequenceMatcher(None, old.splitlines(), new_lines, autojunk=False)
|
|
90
|
+
out: set[int] = set()
|
|
91
|
+
for op, _, _, j1, j2 in sm.get_opcodes():
|
|
92
|
+
if op in ("replace", "insert"):
|
|
93
|
+
out.update(range(j1 + 1, j2 + 1))
|
|
94
|
+
return out
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _significant(src: str, lang: str) -> list[tuple[lexer.Token, int]]:
|
|
98
|
+
"""Tokens without whitespace / comments, each with its 1-based line number."""
|
|
99
|
+
out, line = [], 1
|
|
100
|
+
for t in lexer.tokenize(src, lang):
|
|
101
|
+
if t.kind not in _SKIP:
|
|
102
|
+
out.append((t, line))
|
|
103
|
+
line += t.text.count("\n")
|
|
104
|
+
return out
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def declared_positions(sig: list[tuple[lexer.Token, int]], lang: str) -> set[int]:
|
|
108
|
+
"""Indexes (into ``sig``) of identifiers that are being declared."""
|
|
109
|
+
if lang == "python":
|
|
110
|
+
return _python_decls(sig)
|
|
111
|
+
kw = LANGUAGES[lang].keywords
|
|
112
|
+
binding = _BINDING_KW.get(lang, set())
|
|
113
|
+
texts = [t.text for t, _ in sig]
|
|
114
|
+
out: set[int] = set()
|
|
115
|
+
for i, (t, _) in enumerate(sig):
|
|
116
|
+
if t.kind != lexer.IDENT or t.text in kw:
|
|
117
|
+
continue
|
|
118
|
+
prev = texts[i - 1] if i else ""
|
|
119
|
+
nxt = texts[i + 1] if i + 1 < len(texts) else ""
|
|
120
|
+
if i and sig[i - 1][0].kind == lexer.DIRECTIVE and prev == "define":
|
|
121
|
+
out.add(i)
|
|
122
|
+
elif prev in binding:
|
|
123
|
+
out.add(i)
|
|
124
|
+
elif prev in _TYPE_INTRO:
|
|
125
|
+
if nxt in ("{", ":", ";", "<", "extends", "implements", "("):
|
|
126
|
+
out.add(i)
|
|
127
|
+
elif nxt in ("(", "[", "=", ",", ";", ")", ":", "{") and _typed(sig, texts, i, kw):
|
|
128
|
+
out.add(i)
|
|
129
|
+
return out
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _typed(sig, texts: list[str], i: int, kw: frozenset) -> bool:
|
|
133
|
+
"""`Type name`, `Type *name`, `List<int> name`, `int[] name`, with a sensible token before the type."""
|
|
134
|
+
j = i - 1
|
|
135
|
+
while j >= 0 and texts[j] in ("*", "&", "&&", "?", "]", "["):
|
|
136
|
+
j -= 1
|
|
137
|
+
if j < 0:
|
|
138
|
+
return False
|
|
139
|
+
if texts[j] == ">": # generic type: skip back to the matching '<'
|
|
140
|
+
depth = 0
|
|
141
|
+
while j >= 0:
|
|
142
|
+
depth += texts[j] == ">"
|
|
143
|
+
depth -= texts[j] == "<"
|
|
144
|
+
if depth == 0:
|
|
145
|
+
break
|
|
146
|
+
j -= 1
|
|
147
|
+
j -= 1
|
|
148
|
+
if j < 0 or sig[j][0].kind != lexer.IDENT:
|
|
149
|
+
return False
|
|
150
|
+
tok = sig[j][0]
|
|
151
|
+
if tok.kind != lexer.IDENT or (tok.text in kw and tok.text not in _TYPE_KEYWORDS):
|
|
152
|
+
return False
|
|
153
|
+
before = texts[j - 1] if j else ""
|
|
154
|
+
return before in _START or before in _QUALIFIERS or before in _TYPE_KEYWORDS
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _python_decls(sig) -> set[int]:
|
|
158
|
+
texts = [t.text for t, _ in sig]
|
|
159
|
+
out: set[int] = set()
|
|
160
|
+
depth, in_def = 0, False
|
|
161
|
+
for i, (t, line) in enumerate(sig):
|
|
162
|
+
prev = texts[i - 1] if i else ""
|
|
163
|
+
nxt = texts[i + 1] if i + 1 < len(texts) else ""
|
|
164
|
+
if t.kind == lexer.PUNCT:
|
|
165
|
+
if t.text in "([{":
|
|
166
|
+
depth += 1
|
|
167
|
+
elif t.text in ")]}":
|
|
168
|
+
depth -= 1
|
|
169
|
+
if depth == 0:
|
|
170
|
+
in_def = False
|
|
171
|
+
continue
|
|
172
|
+
if t.kind != lexer.IDENT:
|
|
173
|
+
continue
|
|
174
|
+
if t.text == "def" or t.text == "class":
|
|
175
|
+
in_def = t.text == "def"
|
|
176
|
+
continue
|
|
177
|
+
line_start = i == 0 or sig[i - 1][1] != line
|
|
178
|
+
if prev in ("def", "class", "as", "for", "import"):
|
|
179
|
+
out.add(i)
|
|
180
|
+
elif in_def and depth == 1 and prev in ("(", ",", "*", "**") and nxt in (",", ")", "=", ":"):
|
|
181
|
+
out.add(i) # parameter
|
|
182
|
+
elif line_start and nxt in ("=", ":") and depth == 0 and (i + 2 >= len(texts) or texts[i + 2] != "="):
|
|
183
|
+
out.add(i) # x = ... / x: int = ...
|
|
184
|
+
elif (prev == "." and i >= 2 and texts[i - 2] == "self" and nxt == "="
|
|
185
|
+
and (i < 3 or sig[i - 3][1] != line)):
|
|
186
|
+
out.add(i) # self.x = ... (a field)
|
|
187
|
+
return out
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def find(rel: str, old: str | None, new: str, lang: str, aliases: dict[str, str],
|
|
191
|
+
strings: dict[str, str], secrets: frozenset[str] | set[str] = frozenset()) -> list[Finding]:
|
|
192
|
+
"""Findings on the added / changed lines of one code file. ``aliases``: alias -> real name;
|
|
193
|
+
``secrets``: the K_ aliases of secret constants."""
|
|
194
|
+
changed = changed_lines(old, new)
|
|
195
|
+
if not changed:
|
|
196
|
+
return []
|
|
197
|
+
sig = _significant(new, lang)
|
|
198
|
+
secret_out = _secret_replacements(rel, old, new, lang, sig, secrets, aliases) if old and secrets else []
|
|
199
|
+
decls = declared_positions(sig, lang)
|
|
200
|
+
old_declared: set[str] = set()
|
|
201
|
+
if old is not None:
|
|
202
|
+
old_sig = _significant(old, lang)
|
|
203
|
+
old_declared = {old_sig[i][0].text for i in declared_positions(old_sig, lang)}
|
|
204
|
+
out: list[Finding] = []
|
|
205
|
+
seen: set[tuple[int, str, str]] = set()
|
|
206
|
+
for i, (t, line) in enumerate(sig):
|
|
207
|
+
if line not in changed:
|
|
208
|
+
continue
|
|
209
|
+
f = None
|
|
210
|
+
if t.kind == lexer.IDENT and ALIAS_RE.fullmatch(t.text):
|
|
211
|
+
if t.text not in aliases:
|
|
212
|
+
f = Finding(rel, line, t.text, "unknown", None)
|
|
213
|
+
elif i in decls and t.text not in old_declared:
|
|
214
|
+
f = Finding(rel, line, t.text, "declares", aliases[t.text])
|
|
215
|
+
elif t.kind == lexer.STRING:
|
|
216
|
+
m = strhide.LIT_RE.match(t.text)
|
|
217
|
+
if m and STRING_ID_BODY_RE.fullmatch(m.group("body")) and (old is None or t.text not in old):
|
|
218
|
+
body = m.group("body")
|
|
219
|
+
f = Finding(rel, line, body, "string", strings.get(body))
|
|
220
|
+
if f and (f.line, f.token, f.kind) not in seen:
|
|
221
|
+
seen.add((f.line, f.token, f.kind))
|
|
222
|
+
out.append(f)
|
|
223
|
+
return out + secret_out
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def reused_in_new_functions(rel: str, old: str | None, new: str, lang: str, aliases: dict[str, str]) -> list[str]:
|
|
227
|
+
"""Warnings (not blocking): a new Python function binds an existing alias as a parameter or local
|
|
228
|
+
(pilot round 2: analyze_file used v_0005 = 'features' for its own local). It imports fine - the
|
|
229
|
+
name comes back as the old meaning - but that may not be what the AI meant."""
|
|
230
|
+
if lang != "python":
|
|
231
|
+
return []
|
|
232
|
+
changed = changed_lines(old, new)
|
|
233
|
+
if not changed:
|
|
234
|
+
return []
|
|
235
|
+
old_defs = set()
|
|
236
|
+
if old is not None:
|
|
237
|
+
old_sig = _significant(old, lang)
|
|
238
|
+
old_defs = {old_sig[i + 1][0].text for i, (t, _) in enumerate(old_sig[:-1]) if t.text == "def"}
|
|
239
|
+
sig = _significant(new, lang)
|
|
240
|
+
decls = declared_positions(sig, lang)
|
|
241
|
+
out, seen = [], set()
|
|
242
|
+
current = None # (name, def line) of the function the token is in
|
|
243
|
+
for i, (t, line) in enumerate(sig):
|
|
244
|
+
if t.text == "def" and i + 1 < len(sig):
|
|
245
|
+
current = (sig[i + 1][0].text, line)
|
|
246
|
+
continue
|
|
247
|
+
if (current and current[1] in changed and current[0] not in old_defs and i in decls
|
|
248
|
+
and t.kind == lexer.IDENT and t.text in aliases and t.text != current[0]
|
|
249
|
+
and line in changed and (t.text, current[0]) not in seen):
|
|
250
|
+
seen.add((t.text, current[0]))
|
|
251
|
+
out.append(f"{rel}:{line}: the new function {current[0]} uses {t.text} for its own variable; "
|
|
252
|
+
f"{t.text} means '{aliases[t.text]}', so it comes back as '{aliases[t.text]}' "
|
|
253
|
+
f"(--rename {t.text}=<name> gives it its own name)")
|
|
254
|
+
return out
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _secret_replacements(rel, old, new, lang, sig, secrets, aliases) -> list[Finding]:
|
|
258
|
+
"""A K_ alias that disappeared from a changed block in which a new number appeared: the AI replaced
|
|
259
|
+
a secret constant by a literal value."""
|
|
260
|
+
from .secretconst import PY_IMPORT_RE # the twin-only import line lists every alias
|
|
261
|
+
old = PY_IMPORT_RE.sub("\n", old) # blank, not removed: line numbers stay
|
|
262
|
+
new = PY_IMPORT_RE.sub("\n", new)
|
|
263
|
+
sig = _significant(new, lang)
|
|
264
|
+
old_sig = _significant(old, lang)
|
|
265
|
+
old_k = {t.text for t, _ in old_sig if t.kind == lexer.IDENT and t.text in secrets}
|
|
266
|
+
gone = old_k - {t.text for t, _ in sig if t.kind == lexer.IDENT and t.text in secrets}
|
|
267
|
+
if not gone:
|
|
268
|
+
return []
|
|
269
|
+
old_lines, new_lines = old.splitlines(), new.splitlines()
|
|
270
|
+
sm = difflib.SequenceMatcher(None, old_lines, new_lines, autojunk=False)
|
|
271
|
+
out = []
|
|
272
|
+
for op, i1, i2, j1, j2 in sm.get_opcodes():
|
|
273
|
+
if op != "replace":
|
|
274
|
+
continue
|
|
275
|
+
block_old = "\n".join(old_lines[i1:i2])
|
|
276
|
+
old_numbers = {t.text for t, ln in old_sig if t.kind == lexer.NUMBER and i1 < ln <= i2}
|
|
277
|
+
numbers = [(t.text, ln) for t, ln in sig if t.kind == lexer.NUMBER and j1 < ln <= j2
|
|
278
|
+
and t.text not in old_numbers]
|
|
279
|
+
for alias in sorted(gone):
|
|
280
|
+
if numbers and re.search(r"\b%s\b" % alias, block_old):
|
|
281
|
+
text, line = numbers.pop(0)
|
|
282
|
+
out.append(Finding(rel, line, alias, "secret", aliases.get(alias), text))
|
|
283
|
+
return out
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def replace_number(text: str, lang: str, line: int, number: str, replacement: str) -> str:
|
|
287
|
+
"""Replace the first number token ``number`` on ``line`` by ``replacement``."""
|
|
288
|
+
out, ln, done = [], 1, False
|
|
289
|
+
for t in lexer.tokenize(text, lang):
|
|
290
|
+
if not done and ln == line and t.kind == lexer.NUMBER and t.text == number:
|
|
291
|
+
out.append(replacement)
|
|
292
|
+
done = True
|
|
293
|
+
else:
|
|
294
|
+
out.append(t.text)
|
|
295
|
+
ln += t.text.count("\n")
|
|
296
|
+
return "".join(out)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def apply_renames(new: str, lang: str, changed: set[int], renames: dict[str, str]) -> str:
|
|
300
|
+
"""Replace renamed aliases on the changed lines: identifiers by name, string literals "str_NNNN" by the
|
|
301
|
+
new literal text given in ``renames`` (already a complete literal body)."""
|
|
302
|
+
if not renames:
|
|
303
|
+
return new
|
|
304
|
+
out, line = [], 1
|
|
305
|
+
for t in lexer.tokenize(new, lang):
|
|
306
|
+
text = t.text
|
|
307
|
+
if line in changed:
|
|
308
|
+
if t.kind == lexer.IDENT and text in renames:
|
|
309
|
+
text = renames[text]
|
|
310
|
+
elif t.kind == lexer.STRING:
|
|
311
|
+
m = strhide.LIT_RE.match(text)
|
|
312
|
+
if m and m.group("body") in renames and STRING_ID_BODY_RE.fullmatch(m.group("body")):
|
|
313
|
+
text = f'{m.group("pre")}{m.group("q")}{renames[m.group("body")]}{m.group("q")}'
|
|
314
|
+
out.append(text)
|
|
315
|
+
line += t.text.count("\n")
|
|
316
|
+
return "".join(out)
|
doppelcode/analyze.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Identifier statistics and lexical kind inference."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
from . import lexer
|
|
8
|
+
from .lexer import COND_DIRECTIVES, IDENT, TEXT_DIRECTIVES, Token
|
|
9
|
+
|
|
10
|
+
MACRO, TYPE, FUNC, VAR = "macro", "type", "func", "var"
|
|
11
|
+
_PRIORITY = {VAR: 0, FUNC: 1, TYPE: 2, MACRO: 3}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class NameStats:
|
|
16
|
+
kind: str = VAR
|
|
17
|
+
code_uses: int = 0
|
|
18
|
+
cond_uses: int = 0 # inside #if / #ifdef / #ifndef / #elif / #undef
|
|
19
|
+
text_dir_uses: int = 0 # inside #pragma / #error / #warning / #line
|
|
20
|
+
defined_macro: bool = False
|
|
21
|
+
order: int = 0 # first-seen order, for stable numbering
|
|
22
|
+
|
|
23
|
+
def promote(self, kind: str) -> None:
|
|
24
|
+
if _PRIORITY[kind] > _PRIORITY[self.kind]:
|
|
25
|
+
self.kind = kind
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def only_external_conditions(self) -> bool:
|
|
29
|
+
"""Used only in conditionals/pragmas and never #defined here: an external config macro."""
|
|
30
|
+
return self.code_uses == 0 and not self.defined_macro
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _typedef_names(tokens: list[Token], sig: list[int], start: int) -> tuple[list[str], int]:
|
|
34
|
+
"""Names declared by the typedef starting at sig[start]. Returns (names, index after ';')."""
|
|
35
|
+
names: list[str] = []
|
|
36
|
+
brace = paren = 0
|
|
37
|
+
pos = start + 1
|
|
38
|
+
while pos < len(sig):
|
|
39
|
+
t = tokens[sig[pos]]
|
|
40
|
+
if t.directive is not None:
|
|
41
|
+
pos += 1
|
|
42
|
+
continue
|
|
43
|
+
txt = t.text
|
|
44
|
+
if txt == "{":
|
|
45
|
+
brace += 1
|
|
46
|
+
elif txt == "}":
|
|
47
|
+
brace -= 1
|
|
48
|
+
elif txt == "(":
|
|
49
|
+
paren += 1
|
|
50
|
+
# function-pointer typedef: ( * NAME )
|
|
51
|
+
if (brace == 0 and pos + 3 < len(sig) and tokens[sig[pos + 1]].text == "*"
|
|
52
|
+
and tokens[sig[pos + 2]].kind == IDENT and tokens[sig[pos + 3]].text == ")"):
|
|
53
|
+
names.append(tokens[sig[pos + 2]].text)
|
|
54
|
+
elif txt == ")":
|
|
55
|
+
paren -= 1
|
|
56
|
+
elif brace == 0 and paren == 0 and t.kind == IDENT and pos + 1 < len(sig):
|
|
57
|
+
nxt = tokens[sig[pos + 1]].text
|
|
58
|
+
if nxt in (";", ",", "["):
|
|
59
|
+
names.append(txt)
|
|
60
|
+
if txt == ";" and brace == 0:
|
|
61
|
+
return names, pos + 1
|
|
62
|
+
pos += 1
|
|
63
|
+
return names, pos
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def analyze(tokens: list[Token], stats: dict[str, NameStats]) -> None:
|
|
67
|
+
"""Accumulate per-identifier statistics of one file into ``stats``."""
|
|
68
|
+
sig = lexer.significant(tokens)
|
|
69
|
+
for pos, k in enumerate(sig):
|
|
70
|
+
t = tokens[k]
|
|
71
|
+
if t.kind != IDENT:
|
|
72
|
+
continue
|
|
73
|
+
st = stats.get(t.text)
|
|
74
|
+
if st is None:
|
|
75
|
+
st = stats[t.text] = NameStats(order=len(stats))
|
|
76
|
+
d = t.directive
|
|
77
|
+
if d in COND_DIRECTIVES:
|
|
78
|
+
st.cond_uses += 1
|
|
79
|
+
continue
|
|
80
|
+
if d in TEXT_DIRECTIVES:
|
|
81
|
+
st.text_dir_uses += 1
|
|
82
|
+
continue
|
|
83
|
+
st.code_uses += 1
|
|
84
|
+
prev = tokens[sig[pos - 1]] if pos > 0 else None
|
|
85
|
+
nxt = tokens[sig[pos + 1]].text if pos + 1 < len(sig) else None
|
|
86
|
+
if d == "define" and prev is not None and prev.kind == lexer.DIRECTIVE:
|
|
87
|
+
st.defined_macro = True
|
|
88
|
+
st.promote(MACRO)
|
|
89
|
+
elif prev is not None and prev.text in ("struct", "union", "enum", "class", "namespace"):
|
|
90
|
+
st.promote(TYPE)
|
|
91
|
+
elif nxt == "(":
|
|
92
|
+
st.promote(FUNC)
|
|
93
|
+
|
|
94
|
+
pos = 0
|
|
95
|
+
while pos < len(sig):
|
|
96
|
+
t = tokens[sig[pos]]
|
|
97
|
+
if t.kind == IDENT and t.text == "typedef" and t.directive is None:
|
|
98
|
+
names, pos = _typedef_names(tokens, sig, pos)
|
|
99
|
+
for name in names:
|
|
100
|
+
if name in stats:
|
|
101
|
+
stats[name].promote(TYPE)
|
|
102
|
+
continue
|
|
103
|
+
pos += 1
|