- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/worker/project/definitions.ts?version=278&format=json
421 linesFirst import 87% · codex-capacity-chair 12% · engine 1% · infra-split 1%Last change codex-capacity-chair in version 175, 5 versions changed it
You're reading version 278. The newest is 318, and no version since then changed this file.
1// Where names are defined in a view, and which names a set of lines uses,
2// for the changed-definition rule (#11): publishing is refused when new code
3// uses a name whose definition changed in work published after the agent's
4// base. Like names.ts, this never parses; it reads the shapes a
5// definition has in the usual languages.
6//
7// What counts as a name's definition, only at the top level of a file (an
8// unindented line: what another file can import; never a local, a
9// parameter or a method):
10// - a function or Go func: its header, from the name through the parameter
11// list and return type to the opening brace (or the colon or arrow), so a
12// body edit is not a definition change;
13// - a type, interface, enum, struct or trait: the whole block, since its
14// shape is what users rely on;
15// - a class: its header line;
16// - a const/let/var/val, or a name assigned at the start of a line: the
17// declaring line, or the header when the value is a function.
18//
19// A use means a definition only through an import of it, or in the file
20// that defines it (project.ts, #definitionCore).
22import type { LineId, ReadView } from "../../src/engine/index.ts";
23import { withDefinitionCode } from "./definition-code.ts";
24import { holdsNoCode, isCommonName } from "./names.ts";
26export interface Definition {
27 readonly name: string;
28 readonly file: string;
29 /** Visible lines [start, end) of the file, 0-based. */
30 readonly start: number;
31 readonly end: number;
32 readonly lines: readonly LineId[];
33 /** The definition's text as written (with strings and comments), one line per line. */
34 readonly text: string;
35}
37const NAME = "[A-Za-z_$][A-Za-z0-9_$]*";
38const KEYWORD_DEF = new RegExp(`\\b(function\\*?|class|def|fn|type|interface|enum|struct|trait)\\s+(${NAME})`);
39const GO_FUNC = new RegExp(`\\bfunc\\s+(?:\\([^)]*\\)\\s*)?(${NAME})`);
40const VAR_DEF = new RegExp(`\\b(?:const|let|var|val)\\s+(${NAME})\\s*(?::[^=]*)?=`);
41const METHOD = new RegExp(
42 `^\\s*(?:(?:public|private|protected|static|async|override|readonly|abstract|get|set|export|default)\\s+)*\\*?(${NAME})\\s*(?:<[^()]*>)?\\s*\\(`,
43);
44/** Words that open a statement, never a definition's name, in the usual languages. */
45const KEYWORDS = new Set([
46 "if",
47 "else",
48 "elif",
49 "for",
50 "foreach",
51 "while",
52 "do",
53 "switch",
54 "case",
55 "match",
56 "when",
57 "catch",
58 "try",
59 "except",
60 "finally",
61 "with",
62 "return",
63 "yield",
64 "await",
65 "throw",
66 "raise",
67 "new",
68 "delete",
69 "typeof",
70 "void",
71 "in",
72 "of",
73 "unless",
74 "until",
75 "loop",
76 "select",
77 "go",
78 "defer",
79 "assert",
80 "print",
81 "super",
82 "this",
83 "self",
84 "import",
85 "export",
86 "from",
87 "require",
88 "function",
89 "lambda",
90]);
91const TOP_ASSIGN = new RegExp(`^(${NAME})\\s*(?::[^=]*)?=(?![=>])`);
92const MAX_HEADER = 30;
94const cache = new WeakMap<ReadView, Map<string, readonly Definition[]>>();
96/**
97 * Every definition in the view's code files (or only in `files`), by name.
98 * Each file's definitions are cached per view.
99 */
100export function definitionsIn(view: ReadView, files?: Iterable<string>): Map<string, Definition[]> {
101 let perFile = cache.get(view);
102 if (!perFile) {
103 perFile = new Map();
104 cache.set(view, perFile);
105 }
106 const out = new Map<string, Definition[]>();
107 for (const file of files ?? view.paths()) {
108 let defs = perFile.get(file);
109 if (!defs) {
110 defs = definitionsInFile(view, file);
111 perFile.set(file, defs);
112 }
113 for (const def of defs) {
114 const list = out.get(def.name);
115 if (list) list.push(def);
116 else out.set(def.name, [def]);
117 }
118 }
119 return out;
120}
122function definitionsInFile(view: ReadView, file: string, keepCommon = false): Definition[] {
123 if (holdsNoCode(file) || !view.hasFile(file)) return [];
124 const out: Definition[] = [];
125 const visible = view.buildLines(file);
126 return withDefinitionCode(view, visible, (code) => {
127 for (let i = 0; i < code.length; i++) {
128 // Only top-level declarations: what another file can import. Locals,
129 // parameters and methods are indented.
130 if (/^\s/.test(code[i]!)) continue;
131 const found = defineAt(code, i);
132 if (!found || (!keepCommon && (found.name.length < 3 || isCommonName(found.name)))) continue;
133 out.push({
134 name: found.name,
135 file,
136 start: i,
137 end: found.end,
138 lines: visible.slice(i, found.end).map((l) => l.id),
139 text: visible
140 .slice(i, found.end)
141 .map((l) => l.text)
142 .join("\n"),
143 });
144 }
145 return out;
146 });
147}
149/**
150 * Top-level definitions defined more than once in one file, common names
151 * included (two `parse` functions in a file are a mistake whatever the name).
152 * Each spans its whole block, body and all, for showing to the agent.
153 */
154export function definedTwice(view: ReadView, file: string): Map<string, Definition[]> {
155 const out = new Map<string, Definition[]>();
156 const all = definitionsInFile(view, file, true);
157 const count = new Map<string, number>();
158 for (const d of all) count.set(d.name, (count.get(d.name) ?? 0) + 1);
159 if (![...count.values()].some((n) => n > 1)) return out;
160 const visible = view.buildLines(file);
161 return withDefinitionCode(view, visible, (code) => {
162 for (const d of all) {
163 if (count.get(d.name)! < 2) continue;
164 const end = Math.max(d.end, wholeBlockEnd(code, d.start));
165 const whole: Definition = {
166 ...d,
167 end,
168 lines: visible.slice(d.start, end).map((l) => l.id),
169 text: visible
170 .slice(d.start, end)
171 .map((l) => l.text)
172 .join("\n"),
173 };
174 const list = out.get(d.name);
175 if (list) list.push(whole);
176 else out.set(d.name, [whole]);
177 }
178 return out;
179 });
180}
182/**
183 * Where a top-level definition starting on line i ends (exclusive), body
184 * included: the line where its braces close, or, for an indented block
185 * (Python), the line before the next one back at its indentation.
186 */
187function wholeBlockEnd(code: readonly string[], i: number): number {
188 let depth = 0;
189 let opened = false;
190 for (let j = i; j < code.length && j < i + 2000; j++) {
191 for (const c of code[j]!) {
192 if (c === "{" || c === "(" || c === "[") {
193 depth++;
194 if (c === "{") opened = true;
195 } else if (c === "}" || c === ")" || c === "]") depth--;
196 }
197 if (opened && depth <= 0) return j + 1;
198 if (!opened && depth <= 0 && /:\s*$/.test(code[j]!)) {
199 // An indented block: up to the next non-blank line at the top level.
200 let k = j + 1;
201 while (k < code.length && (code[k]!.trim() === "" || /^\s/.test(code[k]!))) k++;
202 while (k > j + 1 && code[k - 1]!.trim() === "") k--;
203 return k;
204 }
205 if (!opened && depth <= 0 && /[;,]\s*$/.test(code[j]!)) return j + 1;
206 }
207 return i + 1;
208}
210/** A definition starting on line i: its name and where it ends (exclusive). */
211/**
212 * Whether a declaration found at `at` starts its line, after modifiers
213 * only: `export const x`, `async function f`, `pub fn g`. A `let` inside
214 * `for (let i = 0; ...)` or a `function` passed as an argument is not a
215 * definition of the file (#37).
216 */
217const LEADS =
218 /^\s*(?:(?:export|default|declare|async|public|private|protected|static|abstract|override|readonly|pub(?:\([a-z]+\))?|unsafe|extern|const|final|sealed|open|data|inline|private\[this\])\s+)*$/;
219function startsLine(line: string, at: number): boolean {
220 return LEADS.test(line.slice(0, at));
221}
223function defineAt(code: readonly string[], i: number): { name: string; end: number } | undefined {
224 const line = code[i]!;
225 const found = KEYWORD_DEF.exec(line);
226 const kw = found && startsLine(line, found.index) ? found : null;
227 if (kw) {
228 const [, keyword, name] = kw;
229 if (keyword === "class") return { name: name!, end: i + 1 };
230 if (
231 keyword === "type" ||
232 keyword === "interface" ||
233 keyword === "enum" ||
234 keyword === "struct" ||
235 keyword === "trait"
236 ) {
237 return { name: name!, end: blockEnd(code, i, kw.index) };
238 }
239 return { name: name!, end: headerEnd(code, i, kw.index) ?? i + 1 };
240 }
241 const go = GO_FUNC.exec(line);
242 if (go && startsLine(line, go.index)) return { name: go[1]!, end: headerEnd(code, i, go.index) ?? i + 1 };
243 const v = VAR_DEF.exec(line);
244 if (v && startsLine(line, v.index)) {
245 const rest = line.slice(v.index + v[0].length);
246 if (/^\s*(?:async\s+)?(?:function\b|\(|[A-Za-z_$][\w$]*\s*=>)/.test(rest)) {
247 return { name: v[1]!, end: headerEnd(code, i, v.index + v[0].length) ?? i + 1 };
248 }
249 return { name: v[1]!, end: i + 1 };
250 }
251 const m = METHOD.exec(line);
252 // `for (...) {`, `while (...) {` and `if (...) {` look like a method with a body; a keyword names nothing (#37).
253 if (m && !KEYWORDS.has(m[1]!)) {
254 // A method definition, not a call: after its parameters comes a body.
255 const end = headerEnd(code, i, m.index, true);
256 if (end !== undefined) return { name: m[1]!, end };
257 }
258 const t = TOP_ASSIGN.exec(line);
259 if (t) return { name: t[1]!, end: i + 1 };
260 return undefined;
261}
263/**
264 * The end of a function header starting at line i, column `from`: once the
265 * parentheses close, the header ends at the line holding `{`, `=>` or a
266 * trailing `:` (Python). With `needBody`, a `;` or `,` first means it was a
267 * call, not a definition (undefined).
268 */
269function headerEnd(code: readonly string[], i: number, from: number, needBody = false): number | undefined {
270 let depth = 0;
271 let opened = false;
272 for (let j = i; j < code.length && j < i + MAX_HEADER; j++) {
273 const line = j === i ? code[j]!.slice(from) : code[j]!;
274 for (let k = 0; k < line.length; k++) {
275 const c = line[k]!;
276 if (c === "(") {
277 depth++;
278 opened = true;
279 } else if (c === ")") depth--;
280 else if (depth === 0 && opened) {
281 if (c === "{") return j + 1;
282 if (c === "=" && line[k + 1] === ">") return j + 1;
283 if (c === ";" || c === ",") return needBody ? undefined : j + 1;
284 if (c === "=" && needBody) return undefined;
285 }
286 }
287 if (depth === 0 && opened && /:\s*$/.test(line)) return j + 1;
288 }
289 return needBody ? undefined : opened ? i + 1 : undefined;
290}
292/** The end of a braced (or one-line) block starting at line i, column `from`. */
293function blockEnd(code: readonly string[], i: number, from: number): number {
294 let depth = 0;
295 let opened = false;
296 for (let j = i; j < code.length && j < i + 500; j++) {
297 const line = j === i ? code[j]!.slice(from) : code[j]!;
298 for (const c of line) {
299 if (c === "{" || c === "(" || c === "[") {
300 depth++;
301 opened = true;
302 } else if (c === "}" || c === ")" || c === "]") depth--;
303 else if (c === ";" && depth === 0) return j + 1;
304 }
305 if (opened && depth <= 0) return j + 1;
306 if (!opened && j === i && !/[=:{]\s*$/.test(line) && !/\b(?:struct|enum|interface|trait)\b/.test(line))
307 return j + 1;
308 }
309 return i + 1;
310}
312const importCache = new WeakMap<ReadView, Map<string, ReadonlyMap<string, string>>>();
314/**
315 * Names a file imports by name, and the project file each comes from, when
316 * that file is in the view: JavaScript and TypeScript `import { a, b } from
317 * "./x"` (also across lines; an aliased name is left out) and `import a
318 * from "./x"`, and Python `from
319 * x.y import a, b`. Lets a use of a name be matched to the definition it
320 * means instead of every definition with that name.
321 */
322export function importsOf(view: ReadView, file: string): ReadonlyMap<string, string> {
323 let perFile = importCache.get(view);
324 if (!perFile) {
325 perFile = new Map();
326 importCache.set(view, perFile);
327 }
328 let out = perFile.get(file);
329 if (out) return out;
330 const found = new Map<string, string>();
331 const text = view.text(file);
332 for (const m of text.matchAll(/\bimport\s+(?:type\s+)?([^;]*?)\s+from\s+['"]([^'"]+)['"]/g)) {
333 const target = resolveModule(view, file, m[2]!);
334 if (!target) continue;
335 // A default import: `import body from "./x"` or `import body, { a } from "./x"`.
336 const def = /^([A-Za-z_$][\w$]*)\s*(?:,|$)/.exec(m[1]!.trim());
337 if (def) found.set(def[1]!, target);
338 const named = /\{([^}]*)\}/.exec(m[1]!);
339 if (!named) continue;
340 for (const part of named[1]!.split(",")) {
341 const name = part.trim().replace(/^type\s+/, "");
342 if (/^[A-Za-z_$][\w$]*$/.test(name)) found.set(name, target);
343 }
344 }
345 for (const m of text.matchAll(/^\s*from\s+(\.*[\w.]*)\s+import\s+\(?([^)\n]*)\)?/gm)) {
346 const target = resolvePython(view, file, m[1]!);
347 if (!target) continue;
348 for (const part of m[2]!.split(",")) {
349 const name = part.trim();
350 if (/^[A-Za-z_]\w*$/.test(name)) found.set(name, target);
351 }
352 }
353 out = found;
354 perFile.set(file, out);
355 return out;
356}
358function dirOf(path: string): string {
359 const i = path.lastIndexOf("/");
360 return i < 0 ? "" : path.slice(0, i);
361}
363function joinPath(dir: string, rel: string): string {
364 const parts = dir === "" ? [] : dir.split("/");
365 for (const p of rel.split("/")) {
366 if (p === "" || p === ".") continue;
367 if (p === "..") parts.pop();
368 else parts.push(p);
369 }
370 return parts.join("/");
371}
373function resolveModule(view: ReadView, from: string, spec: string): string | undefined {
374 if (!spec.startsWith(".")) return undefined;
375 const base = joinPath(dirOf(from), spec);
376 const stem = base.replace(/\.(?:js|mjs|cjs|jsx)$/, "");
377 for (const candidate of [
378 base,
379 `${stem}.ts`,
380 `${stem}.tsx`,
381 `${stem}.js`,
382 `${stem}.mjs`,
383 `${stem}/index.ts`,
384 `${stem}/index.js`,
385 ]) {
386 if (view.hasFile(candidate)) return candidate;
387 }
388 return undefined;
389}
391function resolvePython(view: ReadView, from: string, spec: string): string | undefined {
392 const dots = /^\.*/.exec(spec)![0].length;
393 const rest = spec.slice(dots).replace(/\./g, "/");
394 let dir = dots > 0 ? dirOf(from) : "";
395 for (let i = 1; i < dots; i++) dir = dirOf(dir);
396 const base = rest === "" ? dir : joinPath(dir, rest);
397 for (const candidate of [`${base}.py`, `${base}/__init__.py`]) if (view.hasFile(candidate)) return candidate;
398 if (dots === 0) {
399 const local = joinPath(dirOf(from), rest);
400 for (const candidate of [`${local}.py`, `${local}/__init__.py`]) if (view.hasFile(candidate)) return candidate;
401 }
402 return undefined;
403}
405/**
406 * The names some lines of code use (identifiers that aren't common names),
407 * from code text. A name right after a dot (`x.body`, `x?.body`) is a
408 * property, not a use of a definition, so it is left out; a spread
409 * (`...body`) is a use.
410 */
411export function usedNames(code: string): string[] {
412 const out: string[] = [];
413 for (const m of code.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)) {
414 const w = m[0];
415 if (w.length < 3 || isCommonName(w)) continue;
416 const at = m.index;
417 if (at > 0 && code[at - 1] === "." && !(at >= 3 && code.slice(at - 3, at) === "...")) continue;
418 out.push(w);
419 }
420 return out;
421}