- 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?format=json
285 linesFirst import 51% · capacity 41% · engine 6% · codex-capacity-chair 1% · pinch 1%Last change capacity in version 316, 10 versions changed it
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, filesBytes, 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 one file 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 files the newer work touched, kept while it is asked about with the same views. */
56 readonly #touchedCache = new WeakMap<
57 ReadonlySet<AtomId>,
58 { base: ReadView; now: ReadView; files: ReadonlySet<string> }
59 >();
61 constructor(graph: Graph, origin: (atom: AtomId, spaceName: string) => Origin) {
62 this.#graph = graph;
63 this.#origin = origin;
64 }
66 /**
67 * The names used on the lines a new line's change replaced (#25): when the
68 * run holding the line hangs off a line its own atom deleted, that run
69 * replaced the block of lines the atom deleted just before it in `base`.
70 * A pure insertion replaced nothing.
71 */
72 #replacedNames(line: LineId, base: ReadView, runsOf: Map<AtomId, readonly RunEnd[]>): ReadonlySet<string> {
73 const g = this.#graph;
74 // The line's atom and place in it from its id (abso Capacity): line() reads its text as well.
75 if (g.lineN(line) < 0) return EMPTY_NAMES;
76 const dot = line.indexOf(".");
77 const atom = g.atom(line.slice(0, dot));
78 const k = Number(line.slice(dot + 1));
79 // Where each of the atom's runs ends, worked out once per check (abso issue 158): reading a run's
80 // lines can mean reading its text back from the log, so not once per line of a big change.
81 let runs = runsOf.get(atom.id);
82 if (!runs) {
83 let k = 0;
84 runs = atom.inserts.map((run) => ({ end: (k += run.lines.length), parent: run.parent }));
85 runsOf.set(atom.id, runs);
86 }
87 const parent = runs.find((r) => k < r.end)?.parent;
88 if (parent === undefined || parent.startsWith("^") || !g.deletersOf(parent).includes(atom.id)) return EMPTY_NAMES;
89 const key = `${atom.id} ${parent}`;
90 let names = this.#replacedCache.get(key);
91 if (!names) {
92 const file = base.fileOf(parent);
93 const seq = base.sequence(file);
94 const out = new Set<string>();
95 for (let at = base.sequenceIndex(file, parent); at >= 0; at--) {
96 const l = seq[at]!;
97 if (!g.deletersOf(l.id).includes(atom.id)) {
98 if (l.visible) break; // the block ends at a line the change kept
99 continue; // a line deleted before: not part of the block
100 }
101 for (const name of usedNames(l.text)) out.add(name);
102 }
103 names = out;
104 this.#replacedCache.set(key, names);
105 }
106 return names;
107 }
109 /**
110 * Names the `draft` atoms' lines in `view` use whose definition changed
111 * between `baseView` and `nowView`, by an atom of `newer`. A name the
112 * draft declares itself is its own. A changed definition is any difference
113 * in the text of the name's definitions (see definitions.ts), including one
114 * that disappeared; a use that imports the name, or sits in a file that
115 * defines it, only counts that definition. `nowView` may be a function, called only when the draft uses a name.
116 * With `kept` (draft collisions, abso Capacity), the draft's uses and the newer work's definitions are kept between
117 * calls under keys that name everything they depend on.
118 */
119 collisions(
120 draft: ReadonlySet<AtomId>,
121 view: ReadView,
122 baseView: ReadView,
123 nowView: ReadView | (() => ReadView),
124 newer: ReadonlySet<AtomId>,
125 spaceName: string,
126 kept?: { parts: KeptParts; uses: string; changed: string },
127 names?: ReadonlySet<string>,
128 /**
129 * The files the newer work changed, when the caller knows them without placing its lines (land and draft-state:
130 * shared's kept version files, abso 738); undefined, or one that answers undefined, and they're worked out here.
131 */
132 changedFiles?: () => ReadonlySet<string> | undefined,
133 ): DefinitionCollision[] {
134 if (draft.size === 0 || newer.size === 0) return [];
135 const uses = kept
136 ? kept.parts.get(`uses ${kept.uses}`, () => this.#usesOf(draft, view, baseView), usesBytes)
137 : this.#usesFor(draft, view, baseView);
138 if (uses.size === 0) return [];
139 // Only these names can collide (a publish's news, news.ts): a draft that uses none of them has none, and the
140 // definitions changed since its base needn't be worked out.
141 if (names && ![...uses.keys()].some((name) => names.has(name))) return [];
142 // Which definitions the uses mean: the file each use imports the name
143 // from, or its own file when it defines the name at the top level. A
144 // use with neither (a local, a parameter, a global, a name another
145 // language brings in some other way) means none: the rule only speaks
146 // when it knows which definition a use means.
147 const scopes = new Map<string, ReadonlySet<string>>();
148 for (const [name, where] of uses) {
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) scopes.set(name, scope);
155 }
156 if (scopes.size === 0) return [];
157 const nowOf = () => (typeof nowView === "function" ? nowView() : nowView);
158 // Only a file the newer work touched can hold a changed definition, and only one a use means can matter: just those
159 // files are laid out, before and with the newer work (abso 738). Laying out every file the newer work touched cost
160 // codex-prose-authorship-610's draft-state 494 files a view where its uses reach 7.
161 const touched =
162 changedFiles?.() ??
163 (kept
164 ? kept.parts.get(`touched ${kept.changed}`, () => this.#touched(newer, baseView, nowOf()), filesBytes)
165 : this.#touchedFor(newer, baseView, nowOf()));
166 const changed = new Map<string, Changed>();
167 const changedIn = (file: string): Changed => {
168 let c = changed.get(file);
169 if (!c) {
170 const make = (): Changed => ({
171 baseDefs: definitionsIn(baseView, [file]),
172 nowDefs: definitionsIn(nowOf(), [file]),
173 });
174 c = kept
175 ? kept.parts.get(
176 `changed ${kept.changed} ${file}`,
177 make,
178 (d) => definitionsBytes(d.baseDefs) + definitionsBytes(d.nowDefs),
179 )
180 : make();
181 changed.set(file, c);
182 }
183 return c;
184 };
185 const out: DefinitionCollision[] = [];
186 for (const [name, scope] of [...scopes].sort(([a], [b]) => (a < b ? -1 : 1))) {
187 // In the order the newer work touched its files, as when every touched file was laid out.
188 const files = [...touched].filter((f) => scope.has(f));
189 const before = files.flatMap((f) => changedIn(f).baseDefs.get(name) ?? []);
190 if (!before.length) continue; // not defined in what the drafter saw: nothing it relies on
191 const after = files.flatMap((f) => changedIn(f).nowDefs.get(name) ?? []);
192 if (signature(before) === signature(after)) continue;
193 // Who changed it: newer writers of the new definition's lines, or newer deleters of the old one's.
194 const by = new Set<AtomId>();
195 for (const d of after)
196 for (const line of d.lines) if (newer.has(this.#graph.lineAtom(line)!)) by.add(this.#graph.lineAtom(line)!);
197 for (const d of before)
198 for (const line of d.lines) for (const x of this.#graph.deletersOf(line)) if (newer.has(x)) by.add(x);
199 const first = [...by].sort((p, q) => this.#graph.atom(p).seq - this.#graph.atom(q).seq)[0];
200 if (first === undefined) continue;
201 const origin = this.#origin(first, spaceName);
202 const where = uses.get(name)!;
203 const file = where[0]!.file;
204 const indexes = where.filter((w) => w.file === file).map((w) => w.index);
205 const lo = Math.min(...indexes);
206 const hi = Math.max(...indexes);
207 const visible = view.lines(file);
208 const def = after[0];
209 const theirs = def
210 ? { file: def.file, lines: [def.start + 1, def.end] as [number, number], text: `${def.text}\n` }
211 : { file: before[0]!.file, lines: [before[0]!.start + 1, before[0]!.start] as [number, number], text: "" };
212 const collision: Collision = {
213 kind: "definition",
214 name,
215 file,
216 yours: { lines: [lo + 1, hi + 1], text: joinLines(visible.slice(lo, hi + 1).map((l) => l.text)) },
217 theirs: { ...theirs, ...origin },
218 };
219 const change = def
220 ? `changes the definition of ${name} (${def.file} line ${def.start + 1})`
221 : `removes the definition of ${name}`;
222 out.push({
223 key: `def ${name} ${origin.draft ?? ""} ${origin.version}`,
224 by: first,
225 collision,
226 news: definitionText(origin, change, name, file, lo + 1),
227 });
228 }
229 return out;
230 }
232 /** The draft's uses, kept while it is asked about with the same views. */
233 #usesFor(draft: ReadonlySet<AtomId>, view: ReadView, baseView: ReadView): Uses {
234 let kept = this.#usesCache.get(draft);
235 if (!kept || kept.view !== view || kept.base !== baseView) {
236 kept = { view, base: baseView, uses: this.#usesOf(draft, view, baseView) };
237 this.#usesCache.set(draft, kept);
238 }
239 return kept.uses;
240 }
242 /** The files the newer work touched, kept while it is asked about with the same views. */
243 #touchedFor(newer: ReadonlySet<AtomId>, baseView: ReadView, now: ReadView): ReadonlySet<string> {
244 let kept = this.#touchedCache.get(newer);
245 if (!kept || kept.base !== baseView || kept.now !== now) {
246 kept = { base: baseView, now, files: this.#touched(newer, baseView, now) };
247 this.#touchedCache.set(newer, kept);
248 }
249 return kept.files;
250 }
252 /** The files the newer work touched, before it and with it: only there can a definition have changed. */
253 #touched(newer: ReadonlySet<AtomId>, baseView: ReadView, now: ReadView): ReadonlySet<string> {
254 return touchedFiles(this.#graph, newer, [baseView, now]);
255 }
257 /** The names the draft's lines use and don't declare, less those the lines they replaced already used. */
258 #usesOf(draft: ReadonlySet<AtomId>, view: ReadView, baseView: ReadView): Uses {
259 const uses = new Map<string, { file: string; index: number }[]>();
260 const declared = new Set<string>();
261 const runsOf = new Map<AtomId, readonly RunEnd[]>();
262 // Only files the draft wrote lines in can hold its lines.
263 const draftFiles = touchedFiles(this.#graph, draft, [view]);
264 for (const file of [...draftFiles].sort()) {
265 if (holdsNoCode(file) || !view.hasFile(file)) continue;
266 const visible = view.lines(file);
267 if (!visible.some((l) => draft.has(l.atom))) continue;
268 const code = codeOfLines(visible.map((l) => l.text));
269 visible.forEach((line, i) => {
270 if (!draft.has(line.atom)) return;
271 for (const name of declaredIn(code[i]!)) declared.add(name);
272 // Only names the change added: a use already on the lines it replaced is not the draft's to answer for.
273 const before = this.#replacedNames(line.id, baseView, runsOf);
274 for (const name of usedNames(code[i]!)) {
275 if (before.has(name)) continue;
276 const list = uses.get(name);
277 if (list) list.push({ file, index: i });
278 else uses.set(name, [{ file, index: i }]);
279 }
280 });
281 }
282 for (const name of declared) uses.delete(name);
283 return uses;
284 }
285}