- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/worker/project/definition-rule.ts?version=308&format=json
252 linesFirst import 62% · capacity 29% · engine 7% · codex-capacity-chair 2% · pinch 1%Last change capacity in version 283, 8 versions changed it
You're reading version 308. The newest is 318, and 2 versions since then changed this file.
1// The changed-definition rule (#11, #25), moved out of project.ts (abso issue
2// 123): a draft collides with newer work that changed or removed the
3// definition of a name the draft's own lines use. Plain reads of the graph and
4// views; the project hands in who published an atom, and keeps the rule's
5// cache for its life.
7import { type AtomId, type Graph, joinLines, type LineId, type ReadView } from "../../src/engine/index.ts";
8import { type Origin, touchedFiles } from "./collisions.ts";
9import { type Definition, definitionsIn, importsOf, usedNames } from "./definitions.ts";
10import { definitionsBytes, type KeptParts, usesBytes } from "./kept-parts.ts";
11import { codeOfLines, declaredIn, holdsNoCode } from "./names.ts";
12import { definitionText } from "./news.ts";
13import type { Collision } from "./project.ts";
15export interface DefinitionCollision {
16 /** For news: told once per name and version. */
17 readonly key: string;
18 /** The first newer atom that changed the definition. */
19 readonly by: AtomId;
20 readonly collision: Collision;
21 readonly news: string;
22}
24/** Compare a name's definitions as text, in any order. */
25export function signature(defs: readonly Definition[]): string {
26 return defs
27 .map((d) => `${d.file}\u0000${d.text}`)
28 .sort()
29 .join("\u0001");
30}
32const EMPTY_NAMES: ReadonlySet<string> = new Set();
34/** Where one of an atom's inserted runs ends (its lines' k), and the node it hangs off. */
35interface RunEnd {
36 readonly end: number;
37 readonly parent: string;
38}
40/** Definitions in the files newer work touched, before it and with it. */
41interface Changed {
42 readonly baseDefs: ReturnType<typeof definitionsIn>;
43 readonly nowDefs: ReturnType<typeof definitionsIn>;
44}
46/** Names a draft's lines use that they don't declare, with where. */
47type Uses = ReadonlyMap<string, readonly { file: string; index: number }[]>;
49export class DefinitionRule {
50 readonly #graph: Graph;
51 readonly #origin: (atom: AtomId, spaceName: string) => Origin;
52 readonly #replacedCache = new Map<string, ReadonlySet<string>>();
53 /** A draft's uses, kept while it is asked about with the same views: draft collisions ask once per other agent. */
54 readonly #usesCache = new WeakMap<ReadonlySet<AtomId>, { view: ReadView; base: ReadView; uses: Uses }>();
55 /** The newer work's definitions before and after, kept while it is asked about with the same views. */
56 readonly #changedCache = new WeakMap<ReadonlySet<AtomId>, { base: ReadView; now: ReadView; defs: Changed }>();
58 constructor(graph: Graph, origin: (atom: AtomId, spaceName: string) => Origin) {
59 this.#graph = graph;
60 this.#origin = origin;
61 }
63 /**
64 * The names used on the lines a new line's change replaced (#25): when the
65 * run holding the line hangs off a line its own atom deleted, that run
66 * replaced the block of lines the atom deleted just before it in `base`.
67 * A pure insertion replaced nothing.
68 */
69 #replacedNames(line: LineId, base: ReadView, runsOf: Map<AtomId, readonly RunEnd[]>): ReadonlySet<string> {
70 const g = this.#graph;
71 // The line's atom and place in it from its id (abso Capacity): line() reads its text as well.
72 if (g.lineN(line) < 0) return EMPTY_NAMES;
73 const dot = line.indexOf(".");
74 const atom = g.atom(line.slice(0, dot));
75 const k = Number(line.slice(dot + 1));
76 // Where each of the atom's runs ends, worked out once per check (abso issue 158): reading a run's
77 // lines can mean reading its text back from the log, so not once per line of a big change.
78 let runs = runsOf.get(atom.id);
79 if (!runs) {
80 let k = 0;
81 runs = atom.inserts.map((run) => ({ end: (k += run.lines.length), parent: run.parent }));
82 runsOf.set(atom.id, runs);
83 }
84 const parent = runs.find((r) => k < r.end)?.parent;
85 if (parent === undefined || parent.startsWith("^") || !g.deletersOf(parent).includes(atom.id)) return EMPTY_NAMES;
86 const key = `${atom.id} ${parent}`;
87 let names = this.#replacedCache.get(key);
88 if (!names) {
89 const file = base.fileOf(parent);
90 const seq = base.sequence(file);
91 const out = new Set<string>();
92 for (let at = base.sequenceIndex(file, parent); at >= 0; at--) {
93 const l = seq[at]!;
94 if (!g.deletersOf(l.id).includes(atom.id)) {
95 if (l.visible) break; // the block ends at a line the change kept
96 continue; // a line deleted before: not part of the block
97 }
98 for (const name of usedNames(l.text)) out.add(name);
99 }
100 names = out;
101 this.#replacedCache.set(key, names);
102 }
103 return names;
104 }
106 /**
107 * Names the `draft` atoms' lines in `view` use whose definition changed
108 * between `baseView` and `nowView`, by an atom of `newer`. A name the
109 * draft declares itself is its own. A changed definition is any difference
110 * in the text of the name's definitions (see definitions.ts), including one
111 * that disappeared; a use that imports the name, or sits in a file that
112 * defines it, only counts that definition. `nowView` may be a function, called only when the draft uses a name.
113 * With `kept` (draft collisions, abso Capacity), the draft's uses and the newer work's definitions are kept between
114 * calls under keys that name everything they depend on.
115 */
116 collisions(
117 draft: ReadonlySet<AtomId>,
118 view: ReadView,
119 baseView: ReadView,
120 nowView: ReadView | (() => ReadView),
121 newer: ReadonlySet<AtomId>,
122 spaceName: string,
123 kept?: { parts: KeptParts; uses: string; changed: string },
124 names?: ReadonlySet<string>,
125 ): DefinitionCollision[] {
126 if (draft.size === 0 || newer.size === 0) return [];
127 const uses = kept
128 ? kept.parts.get(`uses ${kept.uses}`, () => this.#usesOf(draft, view, baseView), usesBytes)
129 : this.#usesFor(draft, view, baseView);
130 if (uses.size === 0) return [];
131 // Only these names can collide (a publish's news, news.ts): a draft that uses none of them has none, and the
132 // definitions changed since its base needn't be worked out.
133 if (names && ![...uses.keys()].some((name) => names.has(name))) return [];
134 const nowOf = () => (typeof nowView === "function" ? nowView() : nowView);
135 const { baseDefs, nowDefs } = kept
136 ? kept.parts.get(
137 `changed ${kept.changed}`,
138 () => this.#changed(newer, baseView, nowOf()),
139 (c) => definitionsBytes(c.baseDefs) + definitionsBytes(c.nowDefs),
140 )
141 : this.#changedFor(newer, baseView, nowOf());
142 const out: DefinitionCollision[] = [];
143 for (const [name, where] of [...uses].sort(([a], [b]) => (a < b ? -1 : 1))) {
144 // Which definitions the uses mean: the file each use imports the name
145 // from, or its own file when it defines the name at the top level. A
146 // use with neither (a local, a parameter, a global, a name another
147 // language brings in some other way) means none: the rule only speaks
148 // when it knows which definition a use means.
149 const scope = new Set<string>();
150 for (const w of new Set(where.map((x) => x.file))) {
151 const from = importsOf(view, w).get(name) ?? (definitionsIn(view, [w]).has(name) ? w : undefined);
152 if (from !== undefined) scope.add(from);
153 }
154 if (scope.size === 0) continue;
155 const inScope = (d: Definition): boolean => scope.has(d.file);
156 const before = baseDefs.get(name)?.filter(inScope);
157 if (!before?.length) continue; // not defined in what the drafter saw: nothing it relies on
158 const after = (nowDefs.get(name) ?? []).filter(inScope);
159 if (signature(before) === signature(after)) continue;
160 // Who changed it: newer writers of the new definition's lines, or newer deleters of the old one's.
161 const by = new Set<AtomId>();
162 for (const d of after)
163 for (const line of d.lines) if (newer.has(this.#graph.lineAtom(line)!)) by.add(this.#graph.lineAtom(line)!);
164 for (const d of before)
165 for (const line of d.lines) for (const x of this.#graph.deletersOf(line)) if (newer.has(x)) by.add(x);
166 const first = [...by].sort((p, q) => this.#graph.atom(p).seq - this.#graph.atom(q).seq)[0];
167 if (first === undefined) continue;
168 const origin = this.#origin(first, spaceName);
169 const file = where[0]!.file;
170 const indexes = where.filter((w) => w.file === file).map((w) => w.index);
171 const lo = Math.min(...indexes);
172 const hi = Math.max(...indexes);
173 const visible = view.lines(file);
174 const def = after[0];
175 const theirs = def
176 ? { file: def.file, lines: [def.start + 1, def.end] as [number, number], text: `${def.text}\n` }
177 : { file: before[0]!.file, lines: [before[0]!.start + 1, before[0]!.start] as [number, number], text: "" };
178 const collision: Collision = {
179 kind: "definition",
180 name,
181 file,
182 yours: { lines: [lo + 1, hi + 1], text: joinLines(visible.slice(lo, hi + 1).map((l) => l.text)) },
183 theirs: { ...theirs, ...origin },
184 };
185 const change = def
186 ? `changes the definition of ${name} (${def.file} line ${def.start + 1})`
187 : `removes the definition of ${name}`;
188 out.push({
189 key: `def ${name} ${origin.draft ?? ""} ${origin.version}`,
190 by: first,
191 collision,
192 news: definitionText(origin, change, name, file, lo + 1),
193 });
194 }
195 return out;
196 }
198 /** The draft's uses, kept while it is asked about with the same views. */
199 #usesFor(draft: ReadonlySet<AtomId>, view: ReadView, baseView: ReadView): Uses {
200 let kept = this.#usesCache.get(draft);
201 if (!kept || kept.view !== view || kept.base !== baseView) {
202 kept = { view, base: baseView, uses: this.#usesOf(draft, view, baseView) };
203 this.#usesCache.set(draft, kept);
204 }
205 return kept.uses;
206 }
208 /** The newer work's definitions before and after, kept while it is asked about with the same views. */
209 #changedFor(newer: ReadonlySet<AtomId>, baseView: ReadView, now: ReadView): Changed {
210 let changed = this.#changedCache.get(newer);
211 if (!changed || changed.base !== baseView || changed.now !== now) {
212 changed = { base: baseView, now, defs: this.#changed(newer, baseView, now) };
213 this.#changedCache.set(newer, changed);
214 }
215 return changed.defs;
216 }
218 /** Definitions in the files the newer work touched, before it and with it: only there can one have changed. */
219 #changed(newer: ReadonlySet<AtomId>, baseView: ReadView, now: ReadView): Changed {
220 const touched = touchedFiles(this.#graph, newer, [baseView, now]);
221 return { baseDefs: definitionsIn(baseView, touched), nowDefs: definitionsIn(now, touched) };
222 }
224 /** The names the draft's lines use and don't declare, less those the lines they replaced already used. */
225 #usesOf(draft: ReadonlySet<AtomId>, view: ReadView, baseView: ReadView): Uses {
226 const uses = new Map<string, { file: string; index: number }[]>();
227 const declared = new Set<string>();
228 const runsOf = new Map<AtomId, readonly RunEnd[]>();
229 // Only files the draft wrote lines in can hold its lines.
230 const draftFiles = touchedFiles(this.#graph, draft, [view]);
231 for (const file of [...draftFiles].sort()) {
232 if (holdsNoCode(file) || !view.hasFile(file)) continue;
233 const visible = view.lines(file);
234 if (!visible.some((l) => draft.has(l.atom))) continue;
235 const code = codeOfLines(visible.map((l) => l.text));
236 visible.forEach((line, i) => {
237 if (!draft.has(line.atom)) return;
238 for (const name of declaredIn(code[i]!)) declared.add(name);
239 // Only names the change added: a use already on the lines it replaced is not the draft's to answer for.
240 const before = this.#replacedNames(line.id, baseView, runsOf);
241 for (const name of usedNames(code[i]!)) {
242 if (before.has(name)) continue;
243 const list = uses.get(name);
244 if (list) list.push({ file, index: i });
245 else uses.set(name, [{ file, index: i }]);
246 }
247 });
248 }
249 for (const name of declared) uses.delete(name);
250 return uses;
251 }
252}