Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

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