- 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=100&format=json
192 linesFirst import 90% · engine 10% · pinch 1%Last change pinch in version 78, 3 versions changed it
You're reading version 100. The newest is 318, and 7 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 View } from "../../src/engine/index.ts";
8import { type Origin, touchedFiles } from "./collisions.ts";
9import { type Definition, definitionsIn, importsOf, usedNames } from "./definitions.ts";
10import { codeOfLines, declaredIn, holdsNoCode } from "./names.ts";
11import { definitionText } from "./news.ts";
12import type { Collision } from "./project.ts";
14export interface DefinitionCollision {
15 /** For news: told once per name and version. */
16 readonly key: string;
17 /** The first newer atom that changed the definition. */
18 readonly by: AtomId;
19 readonly collision: Collision;
20 readonly news: string;
21}
23/** Compare a name's definitions as text, in any order. */
24export function signature(defs: readonly Definition[]): string {
25 return defs
26 .map((d) => `${d.file}\u0000${d.text}`)
27 .sort()
28 .join("\u0001");
29}
31const EMPTY_NAMES: ReadonlySet<string> = new Set();
33/** Where one of an atom's inserted runs ends (its lines' k), and the node it hangs off. */
34interface RunEnd {
35 readonly end: number;
36 readonly parent: string;
37}
39export class DefinitionRule {
40 readonly #graph: Graph;
41 readonly #origin: (atom: AtomId, spaceName: string) => Origin;
42 readonly #replacedCache = new Map<string, ReadonlySet<string>>();
44 constructor(graph: Graph, origin: (atom: AtomId, spaceName: string) => Origin) {
45 this.#graph = graph;
46 this.#origin = origin;
47 }
49 /**
50 * The names used on the lines a new line's change replaced (#25): when the
51 * run holding the line hangs off a line its own atom deleted, that run
52 * replaced the block of lines the atom deleted just before it in `base`.
53 * A pure insertion replaced nothing.
54 */
55 #replacedNames(line: LineId, base: View, runsOf: Map<AtomId, readonly RunEnd[]>): ReadonlySet<string> {
56 const g = this.#graph;
57 const info = g.line(line);
58 if (!info) return EMPTY_NAMES;
59 const atom = g.atom(info.atom);
60 // Where each of the atom's runs ends, worked out once per check (abso issue 158): reading a run's
61 // lines can mean reading its text back from the log, so not once per line of a big change.
62 let runs = runsOf.get(atom.id);
63 if (!runs) {
64 let k = 0;
65 runs = atom.inserts.map((run) => ({ end: (k += run.lines.length), parent: run.parent }));
66 runsOf.set(atom.id, runs);
67 }
68 const parent = runs.find((r) => info.k < r.end)?.parent;
69 if (parent === undefined || parent.startsWith("^") || !g.deletersOf(parent).includes(atom.id)) return EMPTY_NAMES;
70 const key = `${atom.id} ${parent}`;
71 let names = this.#replacedCache.get(key);
72 if (!names) {
73 const file = base.fileOf(parent);
74 const seq = base.sequence(file);
75 const out = new Set<string>();
76 for (let at = base.sequenceIndex(file, parent); at >= 0; at--) {
77 const l = seq[at]!;
78 if (!g.deletersOf(l.id).includes(atom.id)) {
79 if (l.visible) break; // the block ends at a line the change kept
80 continue; // a line deleted before: not part of the block
81 }
82 for (const name of usedNames(l.text)) out.add(name);
83 }
84 names = out;
85 this.#replacedCache.set(key, names);
86 }
87 return names;
88 }
90 /**
91 * Names the `draft` atoms' lines in `view` use whose definition changed
92 * between `baseView` and `nowView`, by an atom of `newer`. A name the
93 * draft declares itself is its own. A changed definition is any difference
94 * in the text of the name's definitions (see definitions.ts), including one
95 * that disappeared; a use that imports the name, or sits in a file that
96 * defines it, only counts that definition.
97 */
98 collisions(
99 draft: ReadonlySet<AtomId>,
100 view: View,
101 baseView: View,
102 nowView: View,
103 newer: ReadonlySet<AtomId>,
104 spaceName: string,
105 ): DefinitionCollision[] {
106 if (draft.size === 0 || newer.size === 0) return [];
107 const uses = new Map<string, { file: string; index: number }[]>();
108 const declared = new Set<string>();
109 const runsOf = new Map<AtomId, readonly RunEnd[]>();
110 // Only files the draft wrote lines in can hold its lines.
111 const draftFiles = touchedFiles(this.#graph, draft, [view]);
112 for (const file of [...draftFiles].sort()) {
113 if (holdsNoCode(file) || !view.hasFile(file)) continue;
114 const visible = view.lines(file);
115 if (!visible.some((l) => draft.has(l.atom))) continue;
116 const code = codeOfLines(visible.map((l) => l.text));
117 visible.forEach((line, i) => {
118 if (!draft.has(line.atom)) return;
119 for (const name of declaredIn(code[i]!)) declared.add(name);
120 // Only names the change added: a use already on the lines it replaced is not the draft's to answer for.
121 const before = this.#replacedNames(line.id, baseView, runsOf);
122 for (const name of usedNames(code[i]!)) {
123 if (before.has(name)) continue;
124 const list = uses.get(name);
125 if (list) list.push({ file, index: i });
126 else uses.set(name, [{ file, index: i }]);
127 }
128 });
129 }
130 for (const name of declared) uses.delete(name);
131 if (uses.size === 0) return [];
133 // A definition can only have changed in a file the newer work touched.
134 const touched = touchedFiles(this.#graph, newer, [baseView, nowView]);
135 const baseDefs = definitionsIn(baseView, touched);
136 const nowDefs = definitionsIn(nowView, touched);
137 const out: DefinitionCollision[] = [];
138 for (const [name, where] of [...uses].sort(([a], [b]) => (a < b ? -1 : 1))) {
139 // Which definitions the uses mean: the file each use imports the name
140 // from, or its own file when it defines the name at the top level. A
141 // use with neither (a local, a parameter, a global, a name another
142 // language brings in some other way) means none: the rule only speaks
143 // when it knows which definition a use means.
144 const scope = new Set<string>();
145 for (const w of new Set(where.map((x) => x.file))) {
146 const from = importsOf(view, w).get(name) ?? (definitionsIn(view, [w]).has(name) ? w : undefined);
147 if (from !== undefined) scope.add(from);
148 }
149 if (scope.size === 0) continue;
150 const inScope = (d: Definition): boolean => scope.has(d.file);
151 const before = baseDefs.get(name)?.filter(inScope);
152 if (!before?.length) continue; // not defined in what the drafter saw: nothing it relies on
153 const after = (nowDefs.get(name) ?? []).filter(inScope);
154 if (signature(before) === signature(after)) continue;
155 // Who changed it: newer writers of the new definition's lines, or newer deleters of the old one's.
156 const by = new Set<AtomId>();
157 for (const d of after)
158 for (const line of d.lines) if (newer.has(this.#graph.line(line)!.atom)) by.add(this.#graph.line(line)!.atom);
159 for (const d of before)
160 for (const line of d.lines) for (const x of this.#graph.deletersOf(line)) if (newer.has(x)) by.add(x);
161 const first = [...by].sort((p, q) => this.#graph.atom(p).seq - this.#graph.atom(q).seq)[0];
162 if (first === undefined) continue;
163 const origin = this.#origin(first, spaceName);
164 const file = where[0]!.file;
165 const indexes = where.filter((w) => w.file === file).map((w) => w.index);
166 const lo = Math.min(...indexes);
167 const hi = Math.max(...indexes);
168 const visible = view.lines(file);
169 const def = after[0];
170 const theirs = def
171 ? { file: def.file, lines: [def.start + 1, def.end] as [number, number], text: `${def.text}\n` }
172 : { file: before[0]!.file, lines: [before[0]!.start + 1, before[0]!.start] as [number, number], text: "" };
173 const collision: Collision = {
174 kind: "definition",
175 name,
176 file,
177 yours: { lines: [lo + 1, hi + 1], text: joinLines(visible.slice(lo, hi + 1).map((l) => l.text)) },
178 theirs: { ...theirs, ...origin },
179 };
180 const change = def
181 ? `changes the definition of ${name} (${def.file} line ${def.start + 1})`
182 : `removes the definition of ${name}`;
183 out.push({
184 key: `def ${name} ${origin.draft ?? ""} ${origin.version}`,
185 by: first,
186 collision,
187 news: definitionText(origin, change, name, file, lo + 1),
188 });
189 }
190 return out;
191 }
192}