@dataparade/cli 0.0.31 → 0.0.33
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.
- package/README.md +56 -1
- package/dist/package.json +4 -3
- package/dist/src/ai-enrichment/fallbacks.js +12 -1
- package/dist/src/cli.js +50 -4
- package/dist/src/core/pipeline/omit-internal-implementation.js +13 -6
- package/dist/src/diff/register-diff-command.d.ts +4 -0
- package/dist/src/diff/register-diff-command.js +79 -0
- package/dist/src/diff/run-diff.d.ts +80 -0
- package/dist/src/diff/run-diff.js +206 -0
- package/dist/src/diff/upload-diff.d.ts +26 -0
- package/dist/src/diff/upload-diff.js +69 -0
- package/dist/src/facts/apply-answers.js +1 -1
- package/dist/src/facts/build-facts.d.ts +3 -1
- package/dist/src/facts/build-facts.js +10 -1
- package/dist/src/facts/identity.d.ts +27 -0
- package/dist/src/facts/identity.js +203 -0
- package/dist/src/facts/io.d.ts +2 -0
- package/dist/src/facts/io.js +7 -0
- package/dist/src/facts/scan-stamps.d.ts +55 -0
- package/dist/src/facts/scan-stamps.js +165 -0
- package/dist/src/facts/schema.d.ts +243 -7
- package/dist/src/facts/schema.js +71 -1
- package/dist/src/kb/answer-fingerprint.d.ts +44 -0
- package/dist/src/kb/answer-fingerprint.js +173 -0
- package/dist/src/kb/brief.d.ts +8 -1
- package/dist/src/kb/brief.js +18 -2
- package/dist/src/kb/land.js +3 -0
- package/dist/src/kb/register-kb-commands.js +7 -1
- package/dist/src/output/git-context.d.ts +25 -0
- package/dist/src/output/git-context.js +122 -0
- package/dist/src/output/scan-output-excludes.js +5 -1
- package/dist/src/output/write-scan-knowledge.d.ts +2 -0
- package/dist/src/output/write-scan-knowledge.js +1 -0
- package/dist/src/platform-api/dataparade-app-base-url.d.ts +8 -4
- package/dist/src/platform-api/dataparade-app-base-url.js +10 -5
- package/dist/src/platform-api/upload-client.d.ts +1 -1
- package/dist/src/platform-api/upload-client.js +32 -1
- package/dist/src/platform-api/upload.types.d.ts +55 -0
- package/dist/src/sensitive-scan/process.d.ts +5 -0
- package/dist/src/sensitive-scan/process.js +48 -0
- package/dist/src/sensitive-scan/project.d.ts +12 -0
- package/dist/src/sensitive-scan/project.js +177 -0
- package/dist/src/sensitive-scan/report.d.ts +50 -0
- package/dist/src/sensitive-scan/report.js +32 -0
- package/dist/src/sensitive-scan/sessions.d.ts +2 -0
- package/dist/src/sensitive-scan/sessions.js +120 -0
- package/dist/src/ui/scan-progress-renderer.d.ts +1 -0
- package/dist/src/ui/scan-progress-renderer.js +8 -0
- package/dist/src/upload/build-preview-url.d.ts +2 -2
- package/dist/src/upload/build-preview-url.js +4 -4
- package/dist/src/upload/run-upload.js +6 -2
- package/dist/src/upload/types.d.ts +2 -0
- package/dist/tests/unit/ai-enrichment/fallbacks.spec.js +30 -0
- package/dist/tests/unit/core/omit-internal-implementation.spec.js +21 -0
- package/dist/tests/unit/diff/run-diff.spec.d.ts +1 -0
- package/dist/tests/unit/diff/run-diff.spec.js +189 -0
- package/dist/tests/unit/diff/upload-diff.spec.d.ts +1 -0
- package/dist/tests/unit/diff/upload-diff.spec.js +81 -0
- package/dist/tests/unit/facts/apply-answers.spec.js +1 -1
- package/dist/tests/unit/facts/build-facts.spec.js +67 -1
- package/dist/tests/unit/facts/identity.spec.d.ts +1 -0
- package/dist/tests/unit/facts/identity.spec.js +148 -0
- package/dist/tests/unit/facts/scan-stamps.spec.d.ts +1 -0
- package/dist/tests/unit/facts/scan-stamps.spec.js +95 -0
- package/dist/tests/unit/kb/answer-fingerprint.spec.d.ts +1 -0
- package/dist/tests/unit/kb/answer-fingerprint.spec.js +157 -0
- package/dist/tests/unit/kb/kb-interview-loop.spec.js +16 -0
- package/dist/tests/unit/output/git-context.spec.d.ts +1 -0
- package/dist/tests/unit/output/git-context.spec.js +98 -0
- package/dist/tests/unit/platform-api/dataparade-app-base-url.spec.js +9 -0
- package/dist/tests/unit/platform-api/upload-client.spec.js +101 -1
- package/dist/tests/unit/sensitive-scan/project.spec.d.ts +1 -0
- package/dist/tests/unit/sensitive-scan/project.spec.js +98 -0
- package/dist/tests/unit/upload/build-preview-url.spec.js +4 -0
- package/dist/tests/unit/upload/collect-scan-sidecars.spec.js +1 -0
- package/dist/tests/unit/upload/run-upload.spec.js +32 -0
- package/dist/vendor/kb-compare/dist/src/canonical.d.ts +80 -0
- package/dist/vendor/kb-compare/dist/src/canonical.js +119 -0
- package/dist/vendor/kb-compare/dist/src/change-set.d.ts +144 -0
- package/dist/vendor/kb-compare/dist/src/change-set.js +80 -0
- package/dist/vendor/kb-compare/dist/src/comparable.d.ts +23 -0
- package/dist/vendor/kb-compare/dist/src/comparable.js +48 -0
- package/dist/vendor/kb-compare/dist/src/compare.d.ts +52 -0
- package/dist/vendor/kb-compare/dist/src/compare.js +370 -0
- package/dist/vendor/kb-compare/dist/src/fingerprint.d.ts +40 -0
- package/dist/vendor/kb-compare/dist/src/fingerprint.js +88 -0
- package/dist/vendor/kb-compare/dist/src/index.d.ts +15 -0
- package/dist/vendor/kb-compare/dist/src/index.js +34 -0
- package/dist/vendor/kb-compare/dist/src/input.d.ts +128 -0
- package/dist/vendor/kb-compare/dist/src/input.js +75 -0
- package/dist/vendor/kb-compare/dist/src/slot-rules.d.ts +69 -0
- package/dist/vendor/kb-compare/dist/src/slot-rules.js +203 -0
- package/dist/vendor/kb-compare/dist/src/summary.d.ts +3 -0
- package/dist/vendor/kb-compare/dist/src/summary.js +47 -0
- package/dist/vendor/kb-compare/package.json +6 -0
- package/dist/vendor/scanner/dist/src/analyzers/python/python-detection-config.d.ts +11 -0
- package/dist/vendor/scanner/dist/src/analyzers/python/python-detection-config.js +2 -0
- package/dist/vendor/scanner/dist/src/analyzers/registry.d.ts +2 -0
- package/dist/vendor/scanner/dist/src/analyzers/registry.js +3 -2
- package/dist/vendor/scanner/dist/src/analyzers/typescript/typescript-detection-config.d.ts +17 -0
- package/dist/vendor/scanner/dist/src/analyzers/typescript/typescript-detection-config.js +11 -0
- package/dist/vendor/scanner/dist/src/classifier/application-injection.js +5 -0
- package/dist/vendor/scanner/dist/src/classifier/component-factory.js +33 -3
- package/dist/vendor/scanner/dist/src/classifier/enhance.js +14 -0
- package/dist/vendor/scanner/dist/src/classifier/external-url-third-party.d.ts +8 -0
- package/dist/vendor/scanner/dist/src/classifier/external-url-third-party.js +43 -2
- package/dist/vendor/scanner/dist/src/classifier/postprocessing.js +4 -1
- package/dist/vendor/scanner/dist/src/config/third-party-detection-config.d.ts +41 -0
- package/dist/vendor/scanner/dist/src/config/third-party-detection-config.js +65 -1
- package/dist/vendor/scanner/dist/src/core/pipeline/stable-component-ids.d.ts +8 -0
- package/dist/vendor/scanner/dist/src/core/pipeline/stable-component-ids.js +11 -1
- package/dist/vendor/scanner/dist/src/core/pipeline/structural-scan.js +2 -0
- package/dist/vendor/scanner/dist/src/eval/canonical/scanner/components.d.ts +5 -0
- package/dist/vendor/scanner/dist/src/eval/canonical/scanner/components.js +10 -2
- package/dist/vendor/scanner/dist/src/eval/canonical/scanner/data-flows.js +4 -4
- package/dist/vendor/scanner/dist/src/index.d.ts +1 -1
- package/dist/vendor/scanner/dist/src/index.js +4 -2
- package/dist/vendor/scanner/dist/src/patterns/config.js +7 -1
- package/dist/vendor/scanner/dist/src/patterns/detectors/git-remote-owner.d.ts +14 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/git-remote-owner.js +108 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/python-outbound-http.d.ts +93 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/python-outbound-http.js +1206 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/python-source.d.ts +180 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/python-source.js +1022 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/python.d.ts +6 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/python.js +49 -1
- package/dist/vendor/scanner/dist/src/patterns/detectors/repo-declared-domains.d.ts +2 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/repo-declared-domains.js +80 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/source-module-index.d.ts +23 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/source-module-index.js +145 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/typescript-outbound-http.d.ts +30 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/typescript-outbound-http.js +575 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/typescript.js +12 -0
- package/dist/vendor/scanner/dist/src/patterns/engine.js +6 -1
- package/dist/vendor/scanner/package.json +3 -1
- package/dist/vendor/scanner/patterns/classifier/third-party.classifier.yaml +198 -0
- package/dist/vendor/scanner/patterns/component-taxonomy.yaml +1 -1
- package/dist/vendor/scanner/patterns/python.patterns.yaml +10 -0
- package/dist/vendor/scanner/patterns/third-party.patterns.yaml +271 -0
- package/dist/vendor/scanner/patterns/typescript.patterns.yaml +21 -0
- package/package.json +4 -3
|
@@ -0,0 +1,1022 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Small structural model of one Python source file for same-file value resolution
|
|
4
|
+
* (DATAP-818): logical lines (multi-line calls joined), def/class scopes, assignments,
|
|
5
|
+
* `with ... as` bindings, return statements and a tolerant expression parser.
|
|
6
|
+
*
|
|
7
|
+
* It is synchronous and line-agnostic on purpose: the pattern detectors run without the
|
|
8
|
+
* tree-sitter engine, and the line-regex parser in `src/analyzers/python/parser.ts`
|
|
9
|
+
* only sees the first call on each physical line.
|
|
10
|
+
*/
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.PyExprParser = void 0;
|
|
13
|
+
exports.buildPySourceModel = buildPySourceModel;
|
|
14
|
+
exports.dottedName = dottedName;
|
|
15
|
+
exports.exprText = exprText;
|
|
16
|
+
const STRING_PREFIX = /[rRbBuUfF]/;
|
|
17
|
+
/** Index just past a string literal whose opening quote is at `quoteAt`, or -1. */
|
|
18
|
+
function scanString(src, quoteAt) {
|
|
19
|
+
const q = src[quoteAt];
|
|
20
|
+
const triple = src.startsWith(q.repeat(3), quoteAt);
|
|
21
|
+
let i = quoteAt + (triple ? 3 : 1);
|
|
22
|
+
while (i < src.length) {
|
|
23
|
+
const ch = src[i];
|
|
24
|
+
if (ch === "\\") {
|
|
25
|
+
i += 2;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
if (triple) {
|
|
29
|
+
if (src.startsWith(q.repeat(3), i))
|
|
30
|
+
return i + 3;
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
if (ch === q)
|
|
34
|
+
return i + 1;
|
|
35
|
+
if (ch === "\n")
|
|
36
|
+
return i;
|
|
37
|
+
}
|
|
38
|
+
i += 1;
|
|
39
|
+
}
|
|
40
|
+
return src.length;
|
|
41
|
+
}
|
|
42
|
+
/** Start offset of the string prefix (`f`, `rb`, ...) before a quote at `quoteAt`. */
|
|
43
|
+
function prefixStart(src, quoteAt) {
|
|
44
|
+
let p = quoteAt;
|
|
45
|
+
while (p > 0 && quoteAt - p < 2 && STRING_PREFIX.test(src[p - 1] ?? ""))
|
|
46
|
+
p -= 1;
|
|
47
|
+
if (p < quoteAt && /[\w]/.test(src[p - 1] ?? ""))
|
|
48
|
+
return quoteAt;
|
|
49
|
+
return p;
|
|
50
|
+
}
|
|
51
|
+
function lexSpans(src) {
|
|
52
|
+
const strings = [];
|
|
53
|
+
const comments = [];
|
|
54
|
+
let i = 0;
|
|
55
|
+
while (i < src.length) {
|
|
56
|
+
const ch = src[i];
|
|
57
|
+
if (ch === "#") {
|
|
58
|
+
const nl = src.indexOf("\n", i);
|
|
59
|
+
const end = nl === -1 ? src.length : nl;
|
|
60
|
+
comments.push({ start: i, end });
|
|
61
|
+
i = end;
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (ch === "'" || ch === '"') {
|
|
65
|
+
const end = scanString(src, i);
|
|
66
|
+
strings.push({ start: prefixStart(src, i), end });
|
|
67
|
+
i = Math.max(end, i + 1);
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
i += 1;
|
|
71
|
+
}
|
|
72
|
+
return { strings, comments };
|
|
73
|
+
}
|
|
74
|
+
const MULTI_OPS = ["**=", "//=", ">>=", "<<=", "...", "**", "//", "==", "!=", "<=", ">=", "->", ":=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<", ">>"];
|
|
75
|
+
/** Tokenize `src[from, to)`; offsets stay absolute. Comments are skipped. */
|
|
76
|
+
function tokenize(src, from, to) {
|
|
77
|
+
const out = [];
|
|
78
|
+
let i = from;
|
|
79
|
+
while (i < to) {
|
|
80
|
+
const ch = src[i];
|
|
81
|
+
if (ch === "#") {
|
|
82
|
+
const nl = src.indexOf("\n", i);
|
|
83
|
+
i = nl === -1 || nl > to ? to : nl;
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
if (/\s/.test(ch) || ch === "\\") {
|
|
87
|
+
i += 1;
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
if (/[A-Za-z_]/.test(ch)) {
|
|
91
|
+
let j = i + 1;
|
|
92
|
+
while (j < to && /\w/.test(src[j]))
|
|
93
|
+
j += 1;
|
|
94
|
+
const quote = src[j];
|
|
95
|
+
if ((quote === "'" || quote === '"') && j - i <= 2 && /^[rRbBuUfF]+$/.test(src.slice(i, j))) {
|
|
96
|
+
const end = Math.min(scanString(src, j), to);
|
|
97
|
+
out.push({ kind: "str", text: src.slice(i, end), start: i, end });
|
|
98
|
+
i = end;
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
out.push({ kind: "name", text: src.slice(i, j), start: i, end: j });
|
|
102
|
+
i = j;
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (ch === "'" || ch === '"') {
|
|
106
|
+
const end = Math.min(scanString(src, i), to);
|
|
107
|
+
out.push({ kind: "str", text: src.slice(i, end), start: i, end });
|
|
108
|
+
i = end;
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
if (/[0-9]/.test(ch) || (ch === "." && /[0-9]/.test(src[i + 1] ?? ""))) {
|
|
112
|
+
let j = i + 1;
|
|
113
|
+
while (j < to && /[\w.]/.test(src[j]))
|
|
114
|
+
j += 1;
|
|
115
|
+
out.push({ kind: "num", text: src.slice(i, j), start: i, end: j });
|
|
116
|
+
i = j;
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
const multi = MULTI_OPS.find((op) => src.startsWith(op, i));
|
|
120
|
+
const len = multi ? multi.length : 1;
|
|
121
|
+
out.push({ kind: "op", text: src.slice(i, i + len), start: i, end: i + len });
|
|
122
|
+
i += len;
|
|
123
|
+
}
|
|
124
|
+
return out;
|
|
125
|
+
}
|
|
126
|
+
const OPEN = { "(": ")", "[": "]", "{": "}" };
|
|
127
|
+
class ParseError extends Error {
|
|
128
|
+
}
|
|
129
|
+
/** Body text and flags of a string token (`f"..."` -> {f: true, body}). */
|
|
130
|
+
function splitStringToken(text) {
|
|
131
|
+
let p = 0;
|
|
132
|
+
while (p < text.length && text[p] !== "'" && text[p] !== '"')
|
|
133
|
+
p += 1;
|
|
134
|
+
const prefix = text.slice(0, p).toLowerCase();
|
|
135
|
+
const q = text[p];
|
|
136
|
+
const triple = text.startsWith(q.repeat(3), p);
|
|
137
|
+
const open = triple ? 3 : 1;
|
|
138
|
+
let close = open;
|
|
139
|
+
if (text.length - p >= open * 2 && text.endsWith(q.repeat(open)))
|
|
140
|
+
close = open;
|
|
141
|
+
else
|
|
142
|
+
close = 0;
|
|
143
|
+
const body = text.slice(p + open, close > 0 ? text.length - close : text.length);
|
|
144
|
+
return { prefix, body, bodyOffset: p + open };
|
|
145
|
+
}
|
|
146
|
+
class PyExprParser {
|
|
147
|
+
constructor(src, tokens) {
|
|
148
|
+
this.src = src;
|
|
149
|
+
this.tokens = tokens;
|
|
150
|
+
this.pos = 0;
|
|
151
|
+
}
|
|
152
|
+
static parseRange(src, from, to) {
|
|
153
|
+
const tokens = tokenize(src, from, to);
|
|
154
|
+
if (tokens.length === 0)
|
|
155
|
+
return { kind: "other", start: from, end: to };
|
|
156
|
+
const parser = new PyExprParser(src, tokens);
|
|
157
|
+
try {
|
|
158
|
+
const expr = parser.parseExprList();
|
|
159
|
+
return expr;
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return { kind: "other", start: from, end: to };
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/** Parse every call in a token range (nested calls included). */
|
|
166
|
+
static callsInRange(src, from, to) {
|
|
167
|
+
const tokens = tokenize(src, from, to);
|
|
168
|
+
const out = [];
|
|
169
|
+
for (let i = 0; i < tokens.length; i += 1) {
|
|
170
|
+
const t = tokens[i];
|
|
171
|
+
if (t.kind !== "name")
|
|
172
|
+
continue;
|
|
173
|
+
const prev = tokens[i - 1];
|
|
174
|
+
if (prev && prev.kind === "op" && prev.text === ".")
|
|
175
|
+
continue;
|
|
176
|
+
// NAME (. NAME)* (
|
|
177
|
+
let j = i + 1;
|
|
178
|
+
while (tokens[j]?.text === "." && tokens[j + 1]?.kind === "name")
|
|
179
|
+
j += 2;
|
|
180
|
+
if (tokens[j]?.text !== "(")
|
|
181
|
+
continue;
|
|
182
|
+
const parser = new PyExprParser(src, tokens);
|
|
183
|
+
parser.pos = i;
|
|
184
|
+
try {
|
|
185
|
+
const node = parser.parsePostfix();
|
|
186
|
+
collectCalls(node, out);
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
// Unparseable call: skip it.
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
// Deduplicate (nested calls are reached from several starts).
|
|
193
|
+
const seen = new Set();
|
|
194
|
+
return out.filter((c) => {
|
|
195
|
+
const key = `${c.start}:${c.end}`;
|
|
196
|
+
if (seen.has(key))
|
|
197
|
+
return false;
|
|
198
|
+
seen.add(key);
|
|
199
|
+
return true;
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
peek(offset = 0) {
|
|
203
|
+
return this.tokens[this.pos + offset];
|
|
204
|
+
}
|
|
205
|
+
next() {
|
|
206
|
+
const t = this.tokens[this.pos];
|
|
207
|
+
if (!t)
|
|
208
|
+
throw new ParseError("eof");
|
|
209
|
+
this.pos += 1;
|
|
210
|
+
return t;
|
|
211
|
+
}
|
|
212
|
+
isOp(text, offset = 0) {
|
|
213
|
+
const t = this.peek(offset);
|
|
214
|
+
return !!t && t.kind === "op" && t.text === text;
|
|
215
|
+
}
|
|
216
|
+
isName(text, offset = 0) {
|
|
217
|
+
const t = this.peek(offset);
|
|
218
|
+
return !!t && t.kind === "name" && t.text === text;
|
|
219
|
+
}
|
|
220
|
+
expectOp(text) {
|
|
221
|
+
const t = this.next();
|
|
222
|
+
if (t.kind !== "op" || t.text !== text)
|
|
223
|
+
throw new ParseError(`expected ${text}`);
|
|
224
|
+
return t;
|
|
225
|
+
}
|
|
226
|
+
/** Skip a balanced bracket group starting at the current token; returns its end offset. */
|
|
227
|
+
skipGroup() {
|
|
228
|
+
const open = this.next();
|
|
229
|
+
const close = OPEN[open.text];
|
|
230
|
+
let depth = 1;
|
|
231
|
+
while (depth > 0) {
|
|
232
|
+
const t = this.next();
|
|
233
|
+
if (t.kind !== "op")
|
|
234
|
+
continue;
|
|
235
|
+
if (OPEN[t.text])
|
|
236
|
+
depth += 1;
|
|
237
|
+
else if (t.text === ")" || t.text === "]" || t.text === "}")
|
|
238
|
+
depth -= 1;
|
|
239
|
+
if (depth === 0) {
|
|
240
|
+
if (t.text !== close)
|
|
241
|
+
throw new ParseError("mismatched");
|
|
242
|
+
return t.end;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return open.end;
|
|
246
|
+
}
|
|
247
|
+
parseExprList() {
|
|
248
|
+
const first = this.parseExpr();
|
|
249
|
+
if (!this.isOp(","))
|
|
250
|
+
return first;
|
|
251
|
+
const elts = [first];
|
|
252
|
+
while (this.isOp(",")) {
|
|
253
|
+
this.next();
|
|
254
|
+
if (!this.peek() || this.isOp(")") || this.isOp("]") || this.isOp("="))
|
|
255
|
+
break;
|
|
256
|
+
elts.push(this.parseExpr());
|
|
257
|
+
}
|
|
258
|
+
return { kind: "tuple", elts, start: first.start, end: elts[elts.length - 1].end };
|
|
259
|
+
}
|
|
260
|
+
parseExpr() {
|
|
261
|
+
if (this.isName("lambda")) {
|
|
262
|
+
const start = this.next().start;
|
|
263
|
+
// Lambdas never yield URLs here; consume up to the end of the enclosing argument.
|
|
264
|
+
let end = start;
|
|
265
|
+
while (this.peek() && !this.isOp(",") && !this.isOp(")") && !this.isOp("]") && !this.isOp("}")) {
|
|
266
|
+
const t = this.peek();
|
|
267
|
+
if (t.kind === "op" && OPEN[t.text])
|
|
268
|
+
end = this.skipGroup();
|
|
269
|
+
else
|
|
270
|
+
end = this.next().end;
|
|
271
|
+
}
|
|
272
|
+
return { kind: "other", start, end };
|
|
273
|
+
}
|
|
274
|
+
const body = this.parseOr();
|
|
275
|
+
if (this.isName("if")) {
|
|
276
|
+
this.next();
|
|
277
|
+
this.parseOr();
|
|
278
|
+
if (!this.isName("else"))
|
|
279
|
+
throw new ParseError("ifexp");
|
|
280
|
+
this.next();
|
|
281
|
+
const orelse = this.parseExpr();
|
|
282
|
+
return { kind: "ifexp", body, orelse, start: body.start, end: orelse.end };
|
|
283
|
+
}
|
|
284
|
+
if (this.isName("for")) {
|
|
285
|
+
// Generator expression: keep the element, skip the clauses.
|
|
286
|
+
let end = body.end;
|
|
287
|
+
while (this.peek() && !this.isOp(",") && !this.isOp(")") && !this.isOp("]") && !this.isOp("}")) {
|
|
288
|
+
const t = this.peek();
|
|
289
|
+
if (t.kind === "op" && OPEN[t.text])
|
|
290
|
+
end = this.skipGroup();
|
|
291
|
+
else
|
|
292
|
+
end = this.next().end;
|
|
293
|
+
}
|
|
294
|
+
return { kind: "other", start: body.start, end };
|
|
295
|
+
}
|
|
296
|
+
return body;
|
|
297
|
+
}
|
|
298
|
+
parseOr() {
|
|
299
|
+
return this.parseBool("or", () => this.parseBool("and", () => this.parseNot()));
|
|
300
|
+
}
|
|
301
|
+
parseBool(op, operand) {
|
|
302
|
+
const first = operand();
|
|
303
|
+
if (!this.isName(op))
|
|
304
|
+
return first;
|
|
305
|
+
const values = [first];
|
|
306
|
+
while (this.isName(op)) {
|
|
307
|
+
this.next();
|
|
308
|
+
values.push(operand());
|
|
309
|
+
}
|
|
310
|
+
return { kind: "boolop", op, values, start: first.start, end: values[values.length - 1].end };
|
|
311
|
+
}
|
|
312
|
+
parseNot() {
|
|
313
|
+
if (this.isName("not")) {
|
|
314
|
+
const start = this.next().start;
|
|
315
|
+
const operand = this.parseNot();
|
|
316
|
+
return { kind: "other", start, end: operand.end };
|
|
317
|
+
}
|
|
318
|
+
return this.parseComparison();
|
|
319
|
+
}
|
|
320
|
+
parseComparison() {
|
|
321
|
+
const left = this.parseArith();
|
|
322
|
+
const COMPARE = new Set(["==", "!=", "<", ">", "<=", ">=", "|", "&", "^", "<<", ">>"]);
|
|
323
|
+
let end = left.end;
|
|
324
|
+
let compared = false;
|
|
325
|
+
for (;;) {
|
|
326
|
+
const t = this.peek();
|
|
327
|
+
if (!t)
|
|
328
|
+
break;
|
|
329
|
+
if (t.kind === "op" && COMPARE.has(t.text)) {
|
|
330
|
+
this.next();
|
|
331
|
+
}
|
|
332
|
+
else if (t.kind === "name" && (t.text === "in" || t.text === "is")) {
|
|
333
|
+
this.next();
|
|
334
|
+
if (this.isName("not"))
|
|
335
|
+
this.next();
|
|
336
|
+
}
|
|
337
|
+
else if (t.kind === "name" && t.text === "not" && this.isName("in", 1)) {
|
|
338
|
+
this.next();
|
|
339
|
+
this.next();
|
|
340
|
+
}
|
|
341
|
+
else
|
|
342
|
+
break;
|
|
343
|
+
end = this.parseArith().end;
|
|
344
|
+
compared = true;
|
|
345
|
+
}
|
|
346
|
+
return compared ? { kind: "other", start: left.start, end } : left;
|
|
347
|
+
}
|
|
348
|
+
parseArith() {
|
|
349
|
+
let left = this.parseTerm();
|
|
350
|
+
while (this.isOp("+") || this.isOp("-")) {
|
|
351
|
+
const op = this.next().text;
|
|
352
|
+
const right = this.parseTerm();
|
|
353
|
+
left = { kind: "binop", op, left, right, start: left.start, end: right.end };
|
|
354
|
+
}
|
|
355
|
+
return left;
|
|
356
|
+
}
|
|
357
|
+
parseTerm() {
|
|
358
|
+
let left = this.parseUnary();
|
|
359
|
+
while (this.isOp("*") || this.isOp("/") || this.isOp("%") || this.isOp("//") || this.isOp("@")) {
|
|
360
|
+
const op = this.next().text;
|
|
361
|
+
const right = this.parseUnary();
|
|
362
|
+
left = { kind: "binop", op, left, right, start: left.start, end: right.end };
|
|
363
|
+
}
|
|
364
|
+
return left;
|
|
365
|
+
}
|
|
366
|
+
parseUnary() {
|
|
367
|
+
if (this.isOp("-") || this.isOp("+") || this.isOp("~")) {
|
|
368
|
+
const start = this.next().start;
|
|
369
|
+
const operand = this.parseUnary();
|
|
370
|
+
return { kind: "other", start, end: operand.end };
|
|
371
|
+
}
|
|
372
|
+
if (this.isName("await")) {
|
|
373
|
+
this.next();
|
|
374
|
+
return this.parseUnary();
|
|
375
|
+
}
|
|
376
|
+
if (this.isOp("*") || this.isOp("**")) {
|
|
377
|
+
// Star-expression inside a call or literal.
|
|
378
|
+
const start = this.next().start;
|
|
379
|
+
const operand = this.parseUnary();
|
|
380
|
+
return { kind: "other", start, end: operand.end };
|
|
381
|
+
}
|
|
382
|
+
const base = this.parsePostfix();
|
|
383
|
+
if (this.isOp("**")) {
|
|
384
|
+
this.next();
|
|
385
|
+
const exp = this.parseUnary();
|
|
386
|
+
return { kind: "other", start: base.start, end: exp.end };
|
|
387
|
+
}
|
|
388
|
+
return base;
|
|
389
|
+
}
|
|
390
|
+
parsePostfix() {
|
|
391
|
+
let node = this.parseAtom();
|
|
392
|
+
for (;;) {
|
|
393
|
+
if (this.isOp(".") && this.peek(1)?.kind === "name") {
|
|
394
|
+
this.next();
|
|
395
|
+
const name = this.next();
|
|
396
|
+
node = { kind: "attr", object: node, attr: name.text, start: node.start, end: name.end };
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
399
|
+
if (this.isOp("(")) {
|
|
400
|
+
node = this.parseCallArgs(node);
|
|
401
|
+
continue;
|
|
402
|
+
}
|
|
403
|
+
if (this.isOp("[")) {
|
|
404
|
+
const end = this.skipGroup();
|
|
405
|
+
node = { kind: "subscript", value: node, start: node.start, end };
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
return node;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
/** `[a, b]`, `{a, b}` or `{k: v}`; comprehensions throw and fall back to `other`. */
|
|
412
|
+
parseCollection() {
|
|
413
|
+
const open = this.next();
|
|
414
|
+
const close = OPEN[open.text];
|
|
415
|
+
const elts = [];
|
|
416
|
+
const entries = [];
|
|
417
|
+
const spreads = [];
|
|
418
|
+
while (!this.isOp(close)) {
|
|
419
|
+
if (this.isOp("**")) {
|
|
420
|
+
this.next();
|
|
421
|
+
spreads.push(this.parseExpr());
|
|
422
|
+
}
|
|
423
|
+
else {
|
|
424
|
+
const first = this.parseExpr();
|
|
425
|
+
if (first.kind === "other" && this.isName("for", 0))
|
|
426
|
+
throw new ParseError("comprehension");
|
|
427
|
+
if (this.isOp(":")) {
|
|
428
|
+
this.next();
|
|
429
|
+
const value = this.parseExpr();
|
|
430
|
+
const key = first.kind === "str" && first.parts.length === 1 && typeof first.parts[0] === "string" ? first.parts[0] : undefined;
|
|
431
|
+
entries.push({ ...(key !== undefined ? { key } : {}), value });
|
|
432
|
+
elts.push(value);
|
|
433
|
+
}
|
|
434
|
+
else {
|
|
435
|
+
elts.push(first);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
if (this.isName("for"))
|
|
439
|
+
throw new ParseError("comprehension");
|
|
440
|
+
if (this.isOp(",")) {
|
|
441
|
+
this.next();
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
if (!this.isOp(close))
|
|
445
|
+
throw new ParseError("collection");
|
|
446
|
+
}
|
|
447
|
+
const end = this.next().end;
|
|
448
|
+
const isDict = open.text === "{" && (entries.length > 0 || spreads.length > 0);
|
|
449
|
+
return { kind: "coll", elts, ...(isDict ? { entries, spreads } : {}), start: open.start, end };
|
|
450
|
+
}
|
|
451
|
+
parseCallArgs(func) {
|
|
452
|
+
this.expectOp("(");
|
|
453
|
+
const args = [];
|
|
454
|
+
const kwargs = [];
|
|
455
|
+
const starKwargs = [];
|
|
456
|
+
while (!this.isOp(")")) {
|
|
457
|
+
if (this.peek()?.kind === "name" && this.isOp("=", 1)) {
|
|
458
|
+
const name = this.next().text;
|
|
459
|
+
this.next();
|
|
460
|
+
kwargs.push({ name, value: this.parseExpr() });
|
|
461
|
+
}
|
|
462
|
+
else if (this.isOp("**")) {
|
|
463
|
+
this.next();
|
|
464
|
+
starKwargs.push(this.parseExpr());
|
|
465
|
+
}
|
|
466
|
+
else {
|
|
467
|
+
args.push(this.parseExpr());
|
|
468
|
+
}
|
|
469
|
+
if (this.isOp(",")) {
|
|
470
|
+
this.next();
|
|
471
|
+
continue;
|
|
472
|
+
}
|
|
473
|
+
if (!this.isOp(")"))
|
|
474
|
+
throw new ParseError("call args");
|
|
475
|
+
}
|
|
476
|
+
const close = this.expectOp(")");
|
|
477
|
+
return { kind: "call", func, args, kwargs, starKwargs, start: func.start, end: close.end };
|
|
478
|
+
}
|
|
479
|
+
parseAtom() {
|
|
480
|
+
const t = this.peek();
|
|
481
|
+
if (!t)
|
|
482
|
+
throw new ParseError("eof");
|
|
483
|
+
if (t.kind === "str") {
|
|
484
|
+
const parts = [];
|
|
485
|
+
const start = t.start;
|
|
486
|
+
let end = t.end;
|
|
487
|
+
while (this.peek()?.kind === "str") {
|
|
488
|
+
const tok = this.next();
|
|
489
|
+
end = tok.end;
|
|
490
|
+
parts.push(...stringParts(this.src, tok));
|
|
491
|
+
}
|
|
492
|
+
return { kind: "str", parts: mergeStrParts(parts), start, end };
|
|
493
|
+
}
|
|
494
|
+
if (t.kind === "name") {
|
|
495
|
+
this.next();
|
|
496
|
+
if (t.text === "None" || t.text === "True" || t.text === "False") {
|
|
497
|
+
return { kind: "const", value: t.text, start: t.start, end: t.end };
|
|
498
|
+
}
|
|
499
|
+
return { kind: "name", id: t.text, start: t.start, end: t.end };
|
|
500
|
+
}
|
|
501
|
+
if (t.kind === "num") {
|
|
502
|
+
this.next();
|
|
503
|
+
return { kind: "const", value: t.text, start: t.start, end: t.end };
|
|
504
|
+
}
|
|
505
|
+
if (t.text === "(") {
|
|
506
|
+
const open = this.next();
|
|
507
|
+
if (this.isOp(")")) {
|
|
508
|
+
const close = this.next();
|
|
509
|
+
return { kind: "tuple", elts: [], start: open.start, end: close.end };
|
|
510
|
+
}
|
|
511
|
+
const inner = this.parseExprList();
|
|
512
|
+
const close = this.expectOp(")");
|
|
513
|
+
return { ...inner, start: open.start, end: close.end };
|
|
514
|
+
}
|
|
515
|
+
if (t.text === "[" || t.text === "{") {
|
|
516
|
+
const saved = this.pos;
|
|
517
|
+
try {
|
|
518
|
+
return this.parseCollection();
|
|
519
|
+
}
|
|
520
|
+
catch {
|
|
521
|
+
this.pos = saved;
|
|
522
|
+
const start = t.start;
|
|
523
|
+
const end = this.skipGroup();
|
|
524
|
+
return { kind: "other", start, end };
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
throw new ParseError(`unexpected ${t.text}`);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
exports.PyExprParser = PyExprParser;
|
|
531
|
+
function collectCalls(node, out) {
|
|
532
|
+
switch (node.kind) {
|
|
533
|
+
case "call":
|
|
534
|
+
out.push(node);
|
|
535
|
+
collectCalls(node.func, out);
|
|
536
|
+
for (const a of node.args)
|
|
537
|
+
collectCalls(a, out);
|
|
538
|
+
for (const k of node.kwargs)
|
|
539
|
+
collectCalls(k.value, out);
|
|
540
|
+
for (const k of node.starKwargs)
|
|
541
|
+
collectCalls(k, out);
|
|
542
|
+
return;
|
|
543
|
+
case "attr":
|
|
544
|
+
collectCalls(node.object, out);
|
|
545
|
+
return;
|
|
546
|
+
case "subscript":
|
|
547
|
+
collectCalls(node.value, out);
|
|
548
|
+
return;
|
|
549
|
+
default:
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
function mergeStrParts(parts) {
|
|
554
|
+
const out = [];
|
|
555
|
+
for (const part of parts) {
|
|
556
|
+
const last = out[out.length - 1];
|
|
557
|
+
if (typeof part === "string" && typeof last === "string")
|
|
558
|
+
out[out.length - 1] = last + part;
|
|
559
|
+
else
|
|
560
|
+
out.push(part);
|
|
561
|
+
}
|
|
562
|
+
return out;
|
|
563
|
+
}
|
|
564
|
+
/** Literal text and embedded expressions of one string token. */
|
|
565
|
+
function stringParts(src, tok) {
|
|
566
|
+
const { prefix, body, bodyOffset } = splitStringToken(tok.text);
|
|
567
|
+
if (!prefix.includes("f"))
|
|
568
|
+
return [body];
|
|
569
|
+
const parts = [];
|
|
570
|
+
let literal = "";
|
|
571
|
+
const base = tok.start + bodyOffset;
|
|
572
|
+
let i = 0;
|
|
573
|
+
while (i < body.length) {
|
|
574
|
+
const ch = body[i];
|
|
575
|
+
if (ch === "{" && body[i + 1] === "{") {
|
|
576
|
+
literal += "{";
|
|
577
|
+
i += 2;
|
|
578
|
+
continue;
|
|
579
|
+
}
|
|
580
|
+
if (ch === "}" && body[i + 1] === "}") {
|
|
581
|
+
literal += "}";
|
|
582
|
+
i += 2;
|
|
583
|
+
continue;
|
|
584
|
+
}
|
|
585
|
+
if (ch !== "{") {
|
|
586
|
+
literal += ch;
|
|
587
|
+
i += 1;
|
|
588
|
+
continue;
|
|
589
|
+
}
|
|
590
|
+
// Find the end of the replacement field and of its expression part.
|
|
591
|
+
let depth = 0;
|
|
592
|
+
let j = i + 1;
|
|
593
|
+
let exprEnd = -1;
|
|
594
|
+
let quote;
|
|
595
|
+
for (; j < body.length; j += 1) {
|
|
596
|
+
const c = body[j];
|
|
597
|
+
if (quote) {
|
|
598
|
+
if (c === quote)
|
|
599
|
+
quote = undefined;
|
|
600
|
+
continue;
|
|
601
|
+
}
|
|
602
|
+
if (c === "'" || c === '"') {
|
|
603
|
+
quote = c;
|
|
604
|
+
continue;
|
|
605
|
+
}
|
|
606
|
+
if (c === "(" || c === "[" || c === "{")
|
|
607
|
+
depth += 1;
|
|
608
|
+
else if (c === ")" || c === "]")
|
|
609
|
+
depth -= 1;
|
|
610
|
+
else if (c === "}") {
|
|
611
|
+
if (depth === 0)
|
|
612
|
+
break;
|
|
613
|
+
depth -= 1;
|
|
614
|
+
}
|
|
615
|
+
else if (depth === 0 && exprEnd === -1 && (c === ":" || (c === "!" && body[j + 1] !== "="))) {
|
|
616
|
+
exprEnd = j;
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
if (exprEnd === -1)
|
|
620
|
+
exprEnd = j;
|
|
621
|
+
let exprText = body.slice(i + 1, exprEnd);
|
|
622
|
+
if (exprText.trimEnd().endsWith("="))
|
|
623
|
+
exprText = exprText.trimEnd().slice(0, -1);
|
|
624
|
+
if (literal)
|
|
625
|
+
parts.push(literal);
|
|
626
|
+
literal = "";
|
|
627
|
+
parts.push(PyExprParser.parseRange(src, base + i + 1, base + i + 1 + exprText.length));
|
|
628
|
+
i = j + 1;
|
|
629
|
+
}
|
|
630
|
+
if (literal)
|
|
631
|
+
parts.push(literal);
|
|
632
|
+
return parts;
|
|
633
|
+
}
|
|
634
|
+
// ── Model ─────────────────────────────────────────────────────────────────
|
|
635
|
+
function buildLineStarts(src) {
|
|
636
|
+
const starts = [0];
|
|
637
|
+
for (let i = 0; i < src.length; i += 1)
|
|
638
|
+
if (src[i] === "\n")
|
|
639
|
+
starts.push(i + 1);
|
|
640
|
+
return starts;
|
|
641
|
+
}
|
|
642
|
+
function lineAt(starts, offset) {
|
|
643
|
+
let lo = 0;
|
|
644
|
+
let hi = starts.length - 1;
|
|
645
|
+
while (lo < hi) {
|
|
646
|
+
const mid = (lo + hi + 1) >> 1;
|
|
647
|
+
if (starts[mid] <= offset)
|
|
648
|
+
lo = mid;
|
|
649
|
+
else
|
|
650
|
+
hi = mid - 1;
|
|
651
|
+
}
|
|
652
|
+
return lo + 1;
|
|
653
|
+
}
|
|
654
|
+
function logicalLines(src, spans, starts) {
|
|
655
|
+
const skip = [...spans.strings, ...spans.comments].sort((a, b) => a.start - b.start);
|
|
656
|
+
const out = [];
|
|
657
|
+
let depth = 0;
|
|
658
|
+
let stmtStart = -1;
|
|
659
|
+
let lastCode = -1;
|
|
660
|
+
let k = 0;
|
|
661
|
+
const flush = () => {
|
|
662
|
+
if (stmtStart === -1)
|
|
663
|
+
return;
|
|
664
|
+
const end = lastCode + 1;
|
|
665
|
+
const startLine = lineAt(starts, stmtStart);
|
|
666
|
+
const lineStart = starts[startLine - 1];
|
|
667
|
+
out.push({
|
|
668
|
+
start: stmtStart,
|
|
669
|
+
end,
|
|
670
|
+
startLine,
|
|
671
|
+
endLine: lineAt(starts, Math.max(stmtStart, end - 1)),
|
|
672
|
+
indent: stmtStart - lineStart,
|
|
673
|
+
text: src.slice(stmtStart, end),
|
|
674
|
+
});
|
|
675
|
+
stmtStart = -1;
|
|
676
|
+
lastCode = -1;
|
|
677
|
+
};
|
|
678
|
+
let i = 0;
|
|
679
|
+
while (i < src.length) {
|
|
680
|
+
while (k < skip.length && skip[k].end <= i)
|
|
681
|
+
k += 1;
|
|
682
|
+
const span = skip[k];
|
|
683
|
+
if (span && span.start <= i && i < span.end) {
|
|
684
|
+
const isComment = src[span.start] === "#";
|
|
685
|
+
if (!isComment) {
|
|
686
|
+
if (stmtStart === -1)
|
|
687
|
+
stmtStart = span.start;
|
|
688
|
+
lastCode = span.end - 1;
|
|
689
|
+
}
|
|
690
|
+
i = span.end;
|
|
691
|
+
continue;
|
|
692
|
+
}
|
|
693
|
+
const ch = src[i];
|
|
694
|
+
if (ch === "\n") {
|
|
695
|
+
const continued = lastCode >= 0 && src[lastCode] === "\\";
|
|
696
|
+
if (depth <= 0 && !continued) {
|
|
697
|
+
depth = 0;
|
|
698
|
+
flush();
|
|
699
|
+
}
|
|
700
|
+
i += 1;
|
|
701
|
+
continue;
|
|
702
|
+
}
|
|
703
|
+
if (ch === ";" && depth <= 0) {
|
|
704
|
+
flush();
|
|
705
|
+
i += 1;
|
|
706
|
+
continue;
|
|
707
|
+
}
|
|
708
|
+
if (!/\s/.test(ch)) {
|
|
709
|
+
if (stmtStart === -1)
|
|
710
|
+
stmtStart = i;
|
|
711
|
+
lastCode = i;
|
|
712
|
+
if (ch === "(" || ch === "[" || ch === "{")
|
|
713
|
+
depth += 1;
|
|
714
|
+
else if (ch === ")" || ch === "]" || ch === "}")
|
|
715
|
+
depth -= 1;
|
|
716
|
+
}
|
|
717
|
+
i += 1;
|
|
718
|
+
}
|
|
719
|
+
flush();
|
|
720
|
+
return out;
|
|
721
|
+
}
|
|
722
|
+
function newScope(kind, name, parent, startLine) {
|
|
723
|
+
return { kind, name, parent, startLine, endLine: startLine, params: [], decorators: [], lines: [], children: [], assignments: [], returns: [] };
|
|
724
|
+
}
|
|
725
|
+
/** Split `src[from, to)` at top-level commas; returns [start, end) ranges. */
|
|
726
|
+
function splitTopLevel(src, from, to, sep = ",") {
|
|
727
|
+
const out = [];
|
|
728
|
+
const tokens = tokenize(src, from, to);
|
|
729
|
+
let depth = 0;
|
|
730
|
+
let segStart = from;
|
|
731
|
+
for (const t of tokens) {
|
|
732
|
+
if (t.kind !== "op")
|
|
733
|
+
continue;
|
|
734
|
+
if (OPEN[t.text])
|
|
735
|
+
depth += 1;
|
|
736
|
+
else if (t.text === ")" || t.text === "]" || t.text === "}")
|
|
737
|
+
depth -= 1;
|
|
738
|
+
else if (depth === 0 && t.text === sep) {
|
|
739
|
+
out.push([segStart, t.start]);
|
|
740
|
+
segStart = t.end;
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
out.push([segStart, to]);
|
|
744
|
+
return out.filter(([a, b]) => src.slice(a, b).trim().length > 0);
|
|
745
|
+
}
|
|
746
|
+
function parseParams(src, from, to) {
|
|
747
|
+
const params = [];
|
|
748
|
+
for (const [a, b] of splitTopLevel(src, from, to)) {
|
|
749
|
+
const tokens = tokenize(src, a, b);
|
|
750
|
+
const nameTok = tokens.find((t) => t.kind === "name");
|
|
751
|
+
if (!nameTok || tokens[0]?.text === "*" && tokens.length === 1)
|
|
752
|
+
continue;
|
|
753
|
+
if (tokens[0]?.kind === "op" && tokens[0].text === "/")
|
|
754
|
+
continue;
|
|
755
|
+
const eq = tokens.find((t, idx) => t.kind === "op" && t.text === "=" && idx > 0);
|
|
756
|
+
const colon = tokens.find((t, idx) => t.kind === "op" && t.text === ":" && idx > 0);
|
|
757
|
+
const annotation = colon ? src.slice(colon.end, eq ? eq.start : b).trim() : "";
|
|
758
|
+
const star = tokens[0]?.text === "**" ? "kwargs" : tokens[0]?.text === "*" ? "args" : undefined;
|
|
759
|
+
params.push({
|
|
760
|
+
name: nameTok.text,
|
|
761
|
+
...(star ? { star } : {}),
|
|
762
|
+
...(annotation ? { annotation } : {}),
|
|
763
|
+
...(eq ? { defaultExpr: PyExprParser.parseRange(src, eq.end, b) } : {}),
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
return params;
|
|
767
|
+
}
|
|
768
|
+
/** First top-level `=` of an assignment statement (not `==`, `<=`, `+=` ...). */
|
|
769
|
+
function assignmentEquals(src, line) {
|
|
770
|
+
const tokens = tokenize(src, line.start, line.end);
|
|
771
|
+
let depth = 0;
|
|
772
|
+
for (const t of tokens) {
|
|
773
|
+
if (t.kind === "name" && depth === 0 && /^(if|elif|while|for|return|with|assert|lambda|def|class|import|from|del|raise|yield)$/.test(t.text)) {
|
|
774
|
+
return undefined;
|
|
775
|
+
}
|
|
776
|
+
if (t.kind !== "op")
|
|
777
|
+
continue;
|
|
778
|
+
if (OPEN[t.text])
|
|
779
|
+
depth += 1;
|
|
780
|
+
else if (t.text === ")" || t.text === "]" || t.text === "}")
|
|
781
|
+
depth -= 1;
|
|
782
|
+
else if (depth === 0 && t.text === "=")
|
|
783
|
+
return t;
|
|
784
|
+
}
|
|
785
|
+
return undefined;
|
|
786
|
+
}
|
|
787
|
+
function targetNames(src, from, to) {
|
|
788
|
+
let text = src.slice(from, to).trim();
|
|
789
|
+
// Annotated assignment `name: Type = value`.
|
|
790
|
+
const annotated = /^([A-Za-z_][\w.]*)\s*:/.exec(text);
|
|
791
|
+
if (annotated)
|
|
792
|
+
return [annotated[1]];
|
|
793
|
+
text = text.replace(/^[([]|[)\]]$/g, "");
|
|
794
|
+
return text
|
|
795
|
+
.split(",")
|
|
796
|
+
.map((part) => part.trim().replace(/^\*/, ""))
|
|
797
|
+
.filter((part) => /^[A-Za-z_][\w]*(\.[A-Za-z_]\w*)*$/.test(part));
|
|
798
|
+
}
|
|
799
|
+
const modelCache = new Map();
|
|
800
|
+
function buildPySourceModel(content) {
|
|
801
|
+
const cached = modelCache.get(content);
|
|
802
|
+
if (cached)
|
|
803
|
+
return cached;
|
|
804
|
+
const model = buildModelUncached(content);
|
|
805
|
+
modelCache.clear();
|
|
806
|
+
modelCache.set(content, model);
|
|
807
|
+
return model;
|
|
808
|
+
}
|
|
809
|
+
function buildModelUncached(src) {
|
|
810
|
+
const starts = buildLineStarts(src);
|
|
811
|
+
const spans = lexSpans(src);
|
|
812
|
+
const lines = logicalLines(src, spans, starts);
|
|
813
|
+
const totalLines = starts.length;
|
|
814
|
+
const module = newScope("module", "<module>", undefined, 1);
|
|
815
|
+
module.endLine = totalLines;
|
|
816
|
+
const stack = [{ indent: -1, scope: module }];
|
|
817
|
+
const allFunctions = [];
|
|
818
|
+
let pendingDecorators = [];
|
|
819
|
+
for (const line of lines) {
|
|
820
|
+
while (stack.length > 1 && line.indent <= stack[stack.length - 1].indent) {
|
|
821
|
+
const closed = stack.pop();
|
|
822
|
+
closed.scope.endLine = Math.max(closed.scope.endLine, prevEndLine(closed.scope));
|
|
823
|
+
}
|
|
824
|
+
const owner = stack[stack.length - 1].scope;
|
|
825
|
+
owner.lines.push(line);
|
|
826
|
+
if (line.text.startsWith("@")) {
|
|
827
|
+
pendingDecorators.push(line.text.slice(1).trim());
|
|
828
|
+
continue;
|
|
829
|
+
}
|
|
830
|
+
const def = /^(?:async\s+)?def\s+([A-Za-z_]\w*)\s*\(/.exec(line.text);
|
|
831
|
+
const cls = /^class\s+([A-Za-z_]\w*)/.exec(line.text);
|
|
832
|
+
if (def) {
|
|
833
|
+
const fn = newScope("function", def[1], owner, line.startLine);
|
|
834
|
+
fn.decorators = pendingDecorators;
|
|
835
|
+
const open = line.start + def[0].length - 1;
|
|
836
|
+
const close = matchingClose(src, open, line.end);
|
|
837
|
+
fn.params = parseParams(src, open + 1, close);
|
|
838
|
+
fn.endLine = line.endLine;
|
|
839
|
+
owner.children.push(fn);
|
|
840
|
+
allFunctions.push(fn);
|
|
841
|
+
stack.push({ indent: line.indent, scope: fn });
|
|
842
|
+
pendingDecorators = [];
|
|
843
|
+
// One-line body: `def f(): return X`.
|
|
844
|
+
const colon = src.indexOf(":", close);
|
|
845
|
+
if (colon !== -1 && colon < line.end - 1) {
|
|
846
|
+
const rest = src.slice(colon + 1, line.end).trim();
|
|
847
|
+
if (rest.startsWith("return ")) {
|
|
848
|
+
const from = src.indexOf("return", colon) + "return".length;
|
|
849
|
+
fn.returns.push(PyExprParser.parseRange(src, from, line.end));
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
continue;
|
|
853
|
+
}
|
|
854
|
+
if (cls) {
|
|
855
|
+
const scope = newScope("class", cls[1], owner, line.startLine);
|
|
856
|
+
scope.decorators = pendingDecorators;
|
|
857
|
+
scope.endLine = line.endLine;
|
|
858
|
+
owner.children.push(scope);
|
|
859
|
+
stack.push({ indent: line.indent, scope });
|
|
860
|
+
pendingDecorators = [];
|
|
861
|
+
continue;
|
|
862
|
+
}
|
|
863
|
+
pendingDecorators = [];
|
|
864
|
+
indexStatement(src, line, owner);
|
|
865
|
+
}
|
|
866
|
+
while (stack.length > 1) {
|
|
867
|
+
const closed = stack.pop();
|
|
868
|
+
closed.scope.endLine = Math.max(closed.scope.endLine, prevEndLine(closed.scope));
|
|
869
|
+
}
|
|
870
|
+
const calls = [];
|
|
871
|
+
const scopeAt = (line) => innermostScope(module, line);
|
|
872
|
+
for (const line of lines) {
|
|
873
|
+
if (/^(?:async\s+)?def\s|^class\s|^@/.test(line.text)) {
|
|
874
|
+
// Default values and decorators can hold calls, but never request calls.
|
|
875
|
+
continue;
|
|
876
|
+
}
|
|
877
|
+
const scope = scopeAt(line.startLine);
|
|
878
|
+
for (const node of PyExprParser.callsInRange(src, line.start, line.end)) {
|
|
879
|
+
calls.push({
|
|
880
|
+
node,
|
|
881
|
+
callee: dottedName(node.func),
|
|
882
|
+
scope,
|
|
883
|
+
startLine: lineAt(starts, node.start),
|
|
884
|
+
endLine: lineAt(starts, Math.max(node.start, node.end - 1)),
|
|
885
|
+
});
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
const imports = parseImports(lines);
|
|
889
|
+
return {
|
|
890
|
+
content: src,
|
|
891
|
+
module,
|
|
892
|
+
calls,
|
|
893
|
+
imports,
|
|
894
|
+
lineOf: (offset) => lineAt(starts, offset),
|
|
895
|
+
scopeAt,
|
|
896
|
+
functionsNamed: (name) => allFunctions.filter((fn) => fn.name === name),
|
|
897
|
+
};
|
|
898
|
+
}
|
|
899
|
+
function prevEndLine(scope) {
|
|
900
|
+
const lastLine = scope.lines[scope.lines.length - 1];
|
|
901
|
+
const lastChild = scope.children[scope.children.length - 1];
|
|
902
|
+
return Math.max(lastLine?.endLine ?? scope.startLine, lastChild?.endLine ?? scope.startLine);
|
|
903
|
+
}
|
|
904
|
+
function matchingClose(src, open, limit) {
|
|
905
|
+
const tokens = tokenize(src, open, limit);
|
|
906
|
+
let depth = 0;
|
|
907
|
+
for (const t of tokens) {
|
|
908
|
+
if (t.kind !== "op")
|
|
909
|
+
continue;
|
|
910
|
+
if (OPEN[t.text])
|
|
911
|
+
depth += 1;
|
|
912
|
+
else if (t.text === ")" || t.text === "]" || t.text === "}") {
|
|
913
|
+
depth -= 1;
|
|
914
|
+
if (depth === 0)
|
|
915
|
+
return t.start;
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
return limit;
|
|
919
|
+
}
|
|
920
|
+
function innermostScope(scope, line) {
|
|
921
|
+
for (const child of scope.children) {
|
|
922
|
+
if (line > child.startLine && line <= child.endLine)
|
|
923
|
+
return innermostScope(child, line);
|
|
924
|
+
if (line === child.startLine && child.kind === "function")
|
|
925
|
+
return scope;
|
|
926
|
+
}
|
|
927
|
+
return scope;
|
|
928
|
+
}
|
|
929
|
+
function indexStatement(src, line, owner) {
|
|
930
|
+
const text = line.text;
|
|
931
|
+
if (/^return\b/.test(text)) {
|
|
932
|
+
const from = line.start + "return".length;
|
|
933
|
+
if (from < line.end)
|
|
934
|
+
owner.returns.push(PyExprParser.parseRange(src, from, line.end));
|
|
935
|
+
return;
|
|
936
|
+
}
|
|
937
|
+
const withMatch = /^(?:async\s+)?with\s/.exec(text);
|
|
938
|
+
if (withMatch) {
|
|
939
|
+
const colon = lastTopLevelColon(src, line);
|
|
940
|
+
const from = line.start + withMatch[0].length;
|
|
941
|
+
for (const [a, b] of splitTopLevel(src, from, colon)) {
|
|
942
|
+
const segment = src.slice(a, b);
|
|
943
|
+
const as = /\s+as\s+([\w.]+|\([^)]*\))\s*$/.exec(segment);
|
|
944
|
+
if (!as)
|
|
945
|
+
continue;
|
|
946
|
+
const exprEnd = a + as.index;
|
|
947
|
+
const value = PyExprParser.parseRange(src, a, exprEnd);
|
|
948
|
+
for (const target of targetNames(src, b - as[1].length, b)) {
|
|
949
|
+
owner.assignments.push({ target, value, line: line.startLine, scope: owner });
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
return;
|
|
953
|
+
}
|
|
954
|
+
const eq = assignmentEquals(src, line);
|
|
955
|
+
if (!eq)
|
|
956
|
+
return;
|
|
957
|
+
const value = PyExprParser.parseRange(src, eq.end, line.end);
|
|
958
|
+
for (const target of targetNames(src, line.start, eq.start)) {
|
|
959
|
+
owner.assignments.push({ target, value, line: line.startLine, scope: owner });
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
function lastTopLevelColon(src, line) {
|
|
963
|
+
const tokens = tokenize(src, line.start, line.end);
|
|
964
|
+
let depth = 0;
|
|
965
|
+
let last = line.end;
|
|
966
|
+
for (const t of tokens) {
|
|
967
|
+
if (t.kind !== "op")
|
|
968
|
+
continue;
|
|
969
|
+
if (OPEN[t.text])
|
|
970
|
+
depth += 1;
|
|
971
|
+
else if (t.text === ")" || t.text === "]" || t.text === "}")
|
|
972
|
+
depth -= 1;
|
|
973
|
+
else if (depth === 0 && t.text === ":")
|
|
974
|
+
last = t.start;
|
|
975
|
+
}
|
|
976
|
+
return last;
|
|
977
|
+
}
|
|
978
|
+
function parseImports(lines) {
|
|
979
|
+
const out = [];
|
|
980
|
+
for (const line of lines) {
|
|
981
|
+
const text = line.text.replace(/\s+/g, " ");
|
|
982
|
+
const from = /^from ([\w.]+) import (.+)$/.exec(text);
|
|
983
|
+
if (from) {
|
|
984
|
+
const aliases = new Map();
|
|
985
|
+
const names = [];
|
|
986
|
+
for (const raw of from[2].replace(/[()]/g, "").split(",")) {
|
|
987
|
+
const m = /^\s*(\w+)(?:\s+as\s+(\w+))?\s*$/.exec(raw);
|
|
988
|
+
if (!m)
|
|
989
|
+
continue;
|
|
990
|
+
names.push(m[1]);
|
|
991
|
+
aliases.set(m[2] ?? m[1], m[1]);
|
|
992
|
+
}
|
|
993
|
+
out.push({ module: from[1], names, aliases });
|
|
994
|
+
continue;
|
|
995
|
+
}
|
|
996
|
+
const imp = /^import (.+)$/.exec(text);
|
|
997
|
+
if (imp) {
|
|
998
|
+
for (const raw of imp[1].split(",")) {
|
|
999
|
+
const m = /^\s*([\w.]+)(?:\s+as\s+(\w+))?\s*$/.exec(raw);
|
|
1000
|
+
if (!m)
|
|
1001
|
+
continue;
|
|
1002
|
+
const aliases = new Map([[m[2] ?? m[1].split(".")[0], m[1]]]);
|
|
1003
|
+
out.push({ module: m[1], names: [], aliases });
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
return out;
|
|
1008
|
+
}
|
|
1009
|
+
/** `a.b.c` for a name/attribute chain, else undefined. */
|
|
1010
|
+
function dottedName(expr) {
|
|
1011
|
+
if (expr.kind === "name")
|
|
1012
|
+
return expr.id;
|
|
1013
|
+
if (expr.kind === "attr") {
|
|
1014
|
+
const base = dottedName(expr.object);
|
|
1015
|
+
return base ? `${base}.${expr.attr}` : undefined;
|
|
1016
|
+
}
|
|
1017
|
+
return undefined;
|
|
1018
|
+
}
|
|
1019
|
+
/** Source text of an expression. */
|
|
1020
|
+
function exprText(model, expr) {
|
|
1021
|
+
return model.content.slice(expr.start, expr.end);
|
|
1022
|
+
}
|