// The graph: every atom ever accepted, plus labels. Sets of atoms (states of // the codebase) are separate values; the graph only answers questions about // atoms and keeps indexes so those questions are cheap. import { atomId, attrKey, gapKey, isAtomId, isStartNode, lineId, lineKey, parseKey, posKey, seqOf, startNode, } from "./keys.ts"; import { ATTR_NAMES, type Atom, type AtomId, EngineError, type InsertRun, type Key, type Label, type LineId, type NodeId, REASON_KINDS, type Reason, } from "./types.ts"; /** * Where a line was written and what it says. Its text never changes. A move * can give it another parent in a set, even in another file: `view.parentOf` * and `view.fileOf` say where it is in a set. */ export interface LineInfo { readonly id: LineId; readonly atom: AtomId; readonly k: number; /** The file it was written in. */ readonly file: string; /** The node it was written after. */ readonly parent: NodeId; readonly text: string; } /** One relocation of a line, by the atom that made it; `k` is its place in that atom's moves. */ export interface RelocationInfo { readonly atom: AtomId; readonly line: LineId; readonly parent: NodeId; readonly k: number; } /** A `together` reason seen from one end: `other` is the atom at the far end. */ export interface TogetherLink { readonly other: AtomId; readonly text: string; /** The atom that carries the reason. */ readonly from: AtomId; } export const GRAPH_FORMAT = "ai-first-vcs.graph"; /** The saved form of a graph. Atoms are in seq order. */ export interface GraphJSON { readonly format: typeof GRAPH_FORMAT; readonly version: 1; readonly atoms: readonly Atom[]; readonly labels: readonly Label[]; } /** * An index entry that holds a lone value as itself, and a list only once there * are two (#46): most keys name one atom, and a list for each costs more than * the value. */ function pushOne(map: Map, key: K, value: V): void { const had = map.get(key); if (had === undefined) map.set(key, value); else if (Array.isArray(had)) had.push(value); else map.set(key, [had, value]); } function listOf(had: V | V[] | undefined): readonly V[] { return had === undefined ? EMPTY : Array.isArray(had) ? had : [had]; } function pushIndex(map: Map, key: K, value: V): void { const list = map.get(key); if (list) list.push(value); else map.set(key, [value]); } const EMPTY: readonly never[] = Object.freeze([]); /** * A run whose lines are read when asked for (#46, text on disk): a few fields * and a shared reader, where an object with its own accessor cost about 400 * bytes a run. */ class LazyRun implements InsertRun { readonly file: string; readonly parent: NodeId; readonly #text: (start: number, length: number) => readonly string[]; readonly #start: number; readonly #length: number; constructor( file: string, parent: NodeId, text: (start: number, length: number) => readonly string[], start: number, length: number, ) { this.file = file; this.parent = parent; this.#text = text; this.#start = start; this.#length = length; } get lines(): readonly string[] { return this.#text(this.#start, this.#length); } toJSON(): InsertRun { return { file: this.file, parent: this.parent, lines: this.lines }; } } /** Characters of atoms' text a graph that keeps text elsewhere holds at most (#46): about 8 MB. */ const TEXT_CACHE = 4_000_000; /** How many list items (deletes and keys) are kept read back (#46): publishes and syncs meet few atoms, but one reformat's atom can hold 100,000. */ const LIST_CACHE = 50_000; /** An atom's deletes and claim keys: kept in the log rather than in memory when the graph has a `lists` reader (#46). */ export interface AtomLists { readonly deletes: readonly LineId[]; readonly writes: readonly Key[]; readonly reads: readonly Key[]; readonly holds: readonly Key[]; } function listItems(l: AtomLists): number { return l.deletes.length + l.writes.length + l.reads.length + l.holds.length; } function frozenList(xs: readonly T[]): readonly T[] { return xs.length === 0 ? (EMPTY as readonly T[]) : Object.freeze([...xs]); } /** * An atom whose deletes, writes, reads and holds are read back through `read` (#46). The getters live on the * prototype, so each atom keeps one reader and a fixed shape, not four closures in a dictionary-mode object. */ class ListedAtom { readonly #read: () => AtomLists; constructor(fields: object, read: () => AtomLists) { Object.assign(this, fields); this.#read = read; } get deletes(): readonly LineId[] { return this.#read().deletes; } get writes(): readonly Key[] { return this.#read().writes; } get reads(): readonly Key[] { return this.#read().reads; } get holds(): readonly Key[] { return this.#read().holds; } toJSON(): object { return { ...this, ...this.#read() }; } } /** A growable array of 32-bit integers: a line's fields cost 4 bytes each, not an object and its strings (#46). */ class Ints { #buf: Int32Array | Uint8Array; /** bytes: values 0-255 only, one byte each. */ constructor(bytes = false) { this.#buf = bytes ? new Uint8Array(1024) : new Int32Array(1024); } length = 0; push(n: number): void { if (this.length === this.#buf.length) { const bigger = this.#buf instanceof Uint8Array ? new Uint8Array(this.#buf.length * 2) : new Int32Array(this.#buf.length * 2); bigger.set(this.#buf); this.#buf = bigger; } this.#buf[this.length++] = n; } at(i: number): number { return this.#buf[i]!; } set(i: number, n: number): void { this.#buf[i] = n; } } /** * A line id's place in the graph's line arrays, or -1: "a." is line * `base[seq] + k`. Hand-parsed, as seqOf is, with the same rules: no leading * zeros, and k within the lines its atom wrote. */ function parseLineId(id: string): { seq: number; k: number } | undefined { if (typeof id !== "string") return undefined; const n = id.length; if (n < 4 || id.charCodeAt(0) !== 97 /* a */) return undefined; let i = 1; let seq = 0; const seqStart = i; for (; i < n; i++) { const c = id.charCodeAt(i); if (c === 46 /* . */) break; if (c < 48 || c > 57) return undefined; seq = seq * 10 + (c - 48); } if (i === seqStart || i >= n - 1 || i - seqStart > 15 || (i - seqStart > 1 && id.charCodeAt(seqStart) === 48)) return undefined; const kStart = ++i; let k = 0; for (; i < n; i++) { const c = id.charCodeAt(i); if (c < 48 || c > 57) return undefined; k = k * 10 + (c - 48); } if (i - kStart > 15 || (i - kStart > 1 && id.charCodeAt(kStart) === 48)) return undefined; return { seq, k }; } export class Graph { #atoms: Atom[] = []; #lamport: number[] = []; // Lines, packed (#46): line n is the k-th line atom seq wrote, n = #lineBase[seq] + k. Each holds its // atom's seq, the file it was written in (an index into #paths) and its parent (a line's n, or -1 - a // path's index for a file's start). Its text stays in the atom. Ids and LineInfo objects are made only // when asked for, so a line costs about 16 bytes here instead of a record, its id and its parent's id. #lineBase: number[] = []; #lineAtom = new Ints(); #lineFile = new Ints(); #lineParent = new Ints(); /** Lines' text, when the graph keeps it; without it, it comes from `texts` (#46, text on disk). */ #lineText: string[] | undefined = []; #lineTotal = 0; /** Where an atom's lines' text is when the graph doesn't keep it: each run's lines, by the atom's seq. */ #texts: ((seq: number) => readonly (readonly string[])[]) | undefined; /** Recently read atoms' text, flattened, most recent last, up to TEXT_CACHE characters. */ #textCache = new Map(); #textCached = 0; /** * `texts`, when given, says where each atom's lines' text can be read back * (#46): the graph then keeps no text, only each line's place, and reads an * atom's text when a line of it is asked for, keeping the most recent. */ constructor( options: { texts?: (seq: number) => readonly (readonly string[])[]; lists?: (seq: number) => AtomLists } = {}, ) { if (options.texts) { this.#texts = options.texts; this.#lineText = undefined; } if (options.lists) this.#lists = options.lists; } /** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */ #lists: ((seq: number) => AtomLists) | undefined; /** Recently read atoms' lists, most recent last, up to LIST_CACHE atoms. */ #listCache = new Map(); #listCached = 0; /** An atom's deletes, writes, reads and holds, read back from where they are stored. */ #listsOf(seq: number): AtomLists { const hit = this.#listCache.get(seq); if (hit) { this.#listCache.delete(seq); this.#listCache.set(seq, hit); return hit; } const got = this.#lists!(seq); const lists: AtomLists = { deletes: frozenList(got.deletes), writes: frozenList(got.writes), reads: frozenList(got.reads), holds: frozenList(got.holds), }; this.#listCache.set(seq, lists); this.#listCached += listItems(lists); for (const [old, kept] of this.#listCache) { if (this.#listCached <= LIST_CACHE || old === seq) break; this.#listCache.delete(old); this.#listCached -= listItems(kept); } return lists; } /** The reader an atom's lists use; made apart from add() so it keeps no atom alive (see #reader). */ #listReader(seq: number): () => AtomLists { return () => this.#listsOf(seq); } /** * A claim key as the index keeps it (#46): a line's L:, P: and G: keys by its n (n * 4, + 1, + 2), so the * index holds numbers rather than one string per line; start-node and attribute keys stay strings. A key * naming a line the graph doesn't have stays a string, which nothing has claimed. */ #code(key: Key): Key | number { const t = key.charCodeAt(0); if (key.charCodeAt(1) !== 58 || key.charCodeAt(2) === 94) return key; // not "X:", or a start node "^" const k = t === 76 ? 0 : t === 80 ? 1 : t === 71 ? 2 : -1; // L, P, G if (k < 0) return key; const n = this.#lineN(key.slice(2)); return n < 0 ? key : n * 4 + k; } /** An atom's lines' text, in k order. */ #textOf(seq: number): readonly string[] { const hit = this.#textCache.get(seq); if (hit) { this.#textCache.delete(seq); this.#textCache.set(seq, hit); return hit; } const flat = this.#texts!(seq).flat(); let chars = 0; for (const t of flat) chars += t.length + 1; this.#textCache.set(seq, flat); this.#textCached += chars; for (const [old, lines] of this.#textCache) { if (this.#textCached <= TEXT_CACHE || old === seq) break; this.#textCache.delete(old); for (const t of lines) this.#textCached -= t.length + 1; } return flat; } /** * The reader an atom's runs use. Made in a function of its own: a closure made inside add() would * keep add()'s whole scope alive, the atom as given with all its text included. */ #reader(seq: number): (start: number, length: number) => readonly string[] { return (start, length) => this.#textOf(seq).slice(start, start + length); } /** Line n's text. */ #text(n: number): string { if (this.#lineText) return this.#lineText[n]!; const seq = this.#lineAtom.at(n); return this.#textOf(seq)[n - this.#lineBase[seq]!]!; } #paths: string[] = []; #pathIndex = new Map(); /** The first atom that deletes each line (its seq), or -1; a line deleted by more than one has the rest in #moreDeleters. */ #deleter = new Ints(); #moreDeleters = new Map(); #writers = new Map(); #readers = new Map(); #holders = new Map(); #dependents = new Map(); #resolvers = new Map(); #together = new Map(); #fileAtoms = new Map(); /** First lines of runs (their n), by the node they were written after: a line's n, or -1 - a path's index. */ #runStarts = new Map(); /** 1 for the first line of a run whose atom deleted the line it hangs off: the run replaces it. */ #replacing = new Ints(true); #relocations = new Map(); #relocatedTo = new Map(); /** The same relocations by node code (a line's n, or -1 - a path's index), for views laid out by number. */ #relocatedToCode = new Map(); #movers: AtomId[] = []; #atomFiles: (readonly string[])[] = []; /** Each atom's deleted lines by n, packed (#46), or undefined when it deletes none. */ #atomDeletes: (Int32Array | undefined)[] = []; #labels = new Map(); /** Each author's name kept once (#46). */ #authors = new Map(); /** Number of atoms (also the seq the next atom gets). */ get size(): number { return this.#atoms.length; } /** The id the next accepted atom must have. */ nextId(): AtomId { return atomId(this.#atoms.length); } has(id: AtomId): boolean { const seq = this.#seq(id); return seq >= 0 && seq < this.#atoms.length; } atom(id: AtomId): Atom { const seq = this.#seq(id); const atom = seq >= 0 ? this.#atoms[seq] : undefined; if (!atom) throw new EngineError("unknown-atom", `no atom ${id}`); return atom; } /** All atoms in seq order. */ atoms(): readonly Atom[] { return this.#atoms; } /** lamport(a) = 1 + max lamport of its deps; 0 for an atom with no deps (such as a0). */ lamport(id: AtomId): number { this.atom(id); return this.#lamport[this.#seq(id)]!; } /** Compare by priority (lamport, then seq). Negative when a comes first (is lower). */ comparePriority(a: AtomId, b: AtomId): number { return this.lamport(a) - this.lamport(b) || this.#seq(a) - this.#seq(b); } line(id: LineId): LineInfo | undefined { const n = this.#lineN(id); if (n < 0) return undefined; const seq = this.#lineAtom.at(n); return { id, atom: this.#atoms[seq]!.id, k: n - this.#lineBase[seq]!, file: this.#paths[this.#lineFile.at(n)]!, parent: this.#nodeName(this.#lineParent.at(n)), text: this.#text(n), }; } /** A line's text, or undefined for an unknown line: line(id).text without making the record. */ lineText(id: LineId): string | undefined { const n = this.#lineN(id); return n < 0 ? undefined : this.#text(n); } /** The atom that wrote a line, or undefined: line(id).atom without making the record. */ lineAtom(id: LineId): AtomId | undefined { const n = this.#lineN(id); return n < 0 ? undefined : this.#atoms[this.#lineAtom.at(n)]!.id; } /** The file a line was written in, or undefined: line(id).file without making the record. */ lineFile(id: LineId): string | undefined { const n = this.#lineN(id); return n < 0 ? undefined : this.#paths[this.#lineFile.at(n)]; } /** The node a line was written after, or undefined: line(id).parent without making the record. */ lineParent(id: LineId): NodeId | undefined { const n = this.#lineN(id); return n < 0 ? undefined : this.#nodeName(this.#lineParent.at(n)); } // By number, for views (#46) ------------------------------------------------------ // A line's n and a node's code (a line's n, or -1 - a path's index for a file's start) as the graph // keeps them, so a view can lay files out as arrays of numbers. For the engine's own use. /** A line id's n, or -1 for an unknown line. */ lineN(id: LineId): number { return this.#lineN(id); } /** A line's id from its n. */ lineIdOf(n: number): LineId { return this.#lineName(n); } /** The lines an atom deletes, from the graph's own packed copy (#46): never a read of the log. */ deletedLines(id: AtomId): readonly LineId[] { const ns = this.#atomDeletes[this.#seq(id)]; if (!ns) return EMPTY; const out: LineId[] = new Array(ns.length); for (let i = 0; i < ns.length; i++) out[i] = this.#lineName(ns[i]!); return out; } /** How many lines an atom deletes, without reading its lists. */ deleteCount(id: AtomId): number { return this.#atomDeletes[this.#seq(id)]?.length ?? 0; } textOf(n: number): string { return this.#text(n); } /** The seq of the atom that wrote line n. */ writerSeqOf(n: number): number { return this.#lineAtom.at(n); } /** Line n's k: its place among its atom's lines. */ kOf(n: number): number { return n - this.#lineBase[this.#lineAtom.at(n)]!; } /** The atom id with this seq, as the graph keeps it. */ idOfSeq(seq: number): AtomId { return this.#atoms[seq]!.id; } lamportOfSeq(seq: number): number { return this.#lamport[seq]!; } /** The file line n was written in. */ writtenIn(n: number): string { return this.#paths[this.#lineFile.at(n)]!; } /** The code of the node line n was written after. */ parentCodeOf(n: number): number { return this.#lineParent.at(n); } /** A node's code, or undefined for a node the graph doesn't know (a start node of a file nothing was written in). */ codeOf(node: NodeId): number | undefined { return this.#nodeCode(node); } /** The node a code names. */ nodeOf(code: number): NodeId { return this.#nodeName(code); } /** The start node's code for a path, or undefined when nothing was ever written in it. */ startCodeOf(path: string): number | undefined { const p = this.#pathIndex.get(path); return p === undefined ? undefined : -1 - p; } /** The lines (their n) written right after a node, as childrenOf, into `out`. */ childrenN(code: number, out: number[]): void { if ( code >= 0 && code + 1 < this.#lineTotal && this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) && this.#lineParent.at(code + 1) === code ) out.push(code + 1); const starts = this.#runStarts.get(code); if (starts === undefined) return; if (Array.isArray(starts)) out.push(...starts); else out.push(starts); } replacesN(n: number): boolean { return this.#replacing.at(n) === 1; } /** The seqs of every atom that deletes line n (none: an empty list, shared). */ deleterSeqsOf(n: number): readonly number[] { const first = this.#deleter.at(n); if (first < 0) return EMPTY; const more = this.#moreDeleters.get(n); return more ? [first, ...more] : [first]; } /** Every relocation that puts a line right after the node with this code. */ relocatedToCode(code: number): readonly RelocationInfo[] { return this.#relocatedToCode.get(code) ?? EMPTY; } /** How many lines every atom together has written. */ get lineCount(): number { return this.#lineTotal; } /** A line id's n, or -1 when no accepted atom wrote it. */ #lineN(id: LineId): number { const p = parseLineId(id); if (!p || p.seq >= this.#atoms.length) return -1; const base = this.#lineBase[p.seq]!; const end = p.seq + 1 < this.#lineBase.length ? this.#lineBase[p.seq + 1]! : this.#lineTotal; return p.k < end - base ? base + p.k : -1; } /** A line's id from its n. */ #lineName(n: number): LineId { const seq = this.#lineAtom.at(n); return `${this.#atoms[seq]!.id}.${n - this.#lineBase[seq]!}`; } /** A node's code: a line's n, or -1 - a path's index for a start node; undefined when unknown. */ #nodeCode(node: NodeId): number | undefined { if (isStartNode(node)) { const p = this.#pathIndex.get(node.slice(1)); return p === undefined ? undefined : -1 - p; } const n = this.#lineN(node); return n < 0 ? undefined : n; } #nodeName(code: number): NodeId { return code >= 0 ? this.#lineName(code) : startNode(this.#paths[-1 - code]!); } #pathOf(file: string): number { let p = this.#pathIndex.get(file); if (p === undefined) { p = this.#paths.push(file) - 1; this.#pathIndex.set(file, p); } return p; } /** The line ids an atom inserted, in k order. */ linesOf(id: AtomId): LineId[] { const atom = this.atom(id); const out: LineId[] = []; const seq = atom.seq; const count = (seq + 1 < this.#lineBase.length ? this.#lineBase[seq + 1]! : this.#lineTotal) - this.#lineBase[seq]!; for (let k = 0; k < count; k++) out.push(lineId(id, k)); return out; } /** Every atom that deletes this line (across the whole graph). */ deletersOf(line: LineId): readonly AtomId[] { const n = this.#lineN(line); if (n < 0) return EMPTY; const first = this.#deleter.at(n); if (first < 0) return EMPTY; const more = this.#moreDeleters.get(n); const out = [this.#atoms[first]!.id]; if (more) for (const seq of more) out.push(this.#atoms[seq]!.id); return out; } writersOf(key: Key): readonly AtomId[] { return listOf(this.#writers.get(this.#code(key))); } /** Atoms whose implicit reads include the key. */ readersOf(key: Key): readonly AtomId[] { return listOf(this.#readers.get(this.#code(key))); } /** Atoms whose explicit holds include the key. */ holdersOf(key: Key): readonly AtomId[] { return listOf(this.#holders.get(this.#code(key))); } /** Every atom that inserts or deletes a line of the file, in seq order. */ atomsIn(file: string): readonly AtomId[] { return this.#fileAtoms.get(file) ?? EMPTY; } /** * The files an atom inserts, deletes or moves lines in, or sets attributes * of, sorted. For lines, the file each was written in (or, for a move to a * start node, that file): a set's moves can have taken them elsewhere. */ filesOf(id: AtomId): readonly string[] { this.atom(id); return this.#atomFiles[this.#seq(id)]!; } /** Lines written right after a node (not counting moves), in seq order. */ childrenOf(node: NodeId): LineId[] { const out: LineId[] = []; const code = this.#nodeCode(node); if (code === undefined) return out; // The next line of the same run hangs off this one. if ( code >= 0 && code + 1 < this.#lineTotal && this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) && this.#lineParent.at(code + 1) === code ) { out.push(this.#lineName(code + 1)); } for (const n of listOf(this.#runStarts.get(code))) out.push(this.#lineName(n)); return out; } /** Whether a line starts a run whose atom deleted the line it hangs off. */ replaces(line: LineId): boolean { const n = this.#lineN(line); return n >= 0 && this.#replacing.at(n) === 1; } /** Every relocation of a line, in seq order. */ relocationsOf(line: LineId): readonly RelocationInfo[] { return this.#relocations.get(line) ?? EMPTY; } /** Every relocation that puts a line right after this node, in seq order. */ relocatedTo(node: NodeId): readonly RelocationInfo[] { return this.#relocatedTo.get(node) ?? EMPTY; } /** Atoms that move lines, in seq order. */ movers(): readonly AtomId[] { return this.#movers; } /** Atoms that list this one directly in their deps. */ dependentsOf(id: AtomId): readonly AtomId[] { return listOf(this.#dependents.get(id)); } /** Atoms whose `resolves` names this one. */ resolversOf(id: AtomId): readonly AtomId[] { return listOf(this.#resolvers.get(id)); } /** `together` reasons touching this atom, in either direction. */ togetherLinks(id: AtomId): readonly TogetherLink[] { return this.#together.get(id) ?? EMPTY; } /** * The atom plus everything it depends on, transitively. Computed on demand * and not cached: a cached set per atom costs memory quadratic in the length * of a dependency chain. Use `dependsOn` to ask about one pair. */ closure(id: AtomId): Set { return this.closureOf([id]); } /** The atoms plus everything they depend on, transitively. */ closureOf(ids: Iterable): Set { const out = new Set(); const stack: AtomId[] = []; for (const id of ids) { this.atom(id); if (!out.has(id)) { out.add(id); stack.push(id); } } while (stack.length > 0) { for (const d of this.atom(stack.pop()!).deps) { if (!out.has(d)) { out.add(d); stack.push(d); } } } return out; } /** Whether `b` is in the closure of `a` (an atom is in its own closure). */ dependsOn(a: AtomId, b: AtomId): boolean { const atom = this.atom(a); this.atom(b); return a === b || this.#reaches(atom.deps, b); } /** * Whether `target` is reachable along deps from any of `from` (themselves * included). A dependency always has a lower lamport than its dependent, so * the search never descends below the target's lamport. */ #reaches(from: Iterable, target: AtomId): boolean { const floor = this.#lamport[this.#seq(target)]!; const seen = new Set(); const stack = [...from]; while (stack.length > 0) { const cur = stack.pop()!; if (cur === target) return true; if (seen.has(cur)) continue; seen.add(cur); if (this.#lamport[this.#seq(cur)]! <= floor) continue; for (const d of this.atom(cur).deps) if (!seen.has(d)) stack.push(d); } return false; } /** * Accept an atom into the graph. It must carry the next id and seq, and * everything it touches must come from atoms in its dependency closure. * The atom is frozen. Adding to the graph does not add it to any set. */ add(atom: Atom): void { validateShape(atom); const seq = this.#atoms.length; const bad = (why: string): never => { throw new EngineError("bad-atom", `atom ${atom.id}: ${why}`); }; if (atom.seq !== seq || atom.id !== atomId(seq)) bad(`expected id ${atomId(seq)} with seq ${seq}`); const deps = new Set(); for (const d of atom.deps) { if (!this.has(d)) bad(`dependency ${d} is not in the graph`); if (deps.has(d)) bad(`dependency ${d} listed twice`); deps.add(d); } for (const d of [...atom.needs, ...atom.resolves]) { if (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`); } for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`); // Everything it touches must come from its closure. Derived deps name the // writers directly, so this is usually one lookup per writer. const below = new Map(); const inClosure = (writer: AtomId): boolean => { let hit = below.get(writer); if (hit === undefined) { hit = deps.has(writer) || this.#reaches(deps, writer); below.set(writer, hit); } return hit; }; const checkLine = (line: LineId, what: string): void => { const writer = this.lineAtom(line); if (writer === undefined) return bad(`${what} names unknown line ${line}`); if (!inClosure(writer)) bad(`${what} names line ${line} but ${writer} is not in its closure`); }; for (const run of atom.inserts) { if (isStartNode(run.parent)) { if (run.parent !== startNode(run.file)) bad(`run in ${run.file} starts at ${run.parent}`); } else { // The parent may have been moved into run.file, so its own file can differ. checkLine(run.parent, "an insert"); } } const moved = new Set(); for (const m of atom.moves ?? []) { checkLine(m.line, "a move"); if (!isStartNode(m.parent)) checkLine(m.parent, "a move"); if (m.line === m.parent) bad(`moves ${m.line} after itself`); if (moved.has(m.line)) bad(`moves ${m.line} twice`); moved.add(m.line); if (!atom.writes.includes(posKey(m.line)) || !atom.writes.includes(gapKey(m.parent))) { bad(`moves ${m.line} without writing ${posKey(m.line)} and ${gapKey(m.parent)}`); } } const deleted = new Set(); for (const line of atom.deletes) { checkLine(line, "a delete"); if (deleted.has(line)) bad(`deletes ${line} twice`); deleted.add(line); } const writes = new Set(atom.writes); for (const line of deleted) if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`); for (const key of [...atom.writes, ...atom.reads, ...atom.holds]) { const parsed = parseKey(key); if (parsed.kind === "line") checkLine(parsed.node, `key ${key}`); else if ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node)) checkLine(parsed.node, `key ${key}`); } // Accept. const frozen = freezeAtom( atom, (id) => this.#atoms[seqOf(id)]!.id, (author) => { let a = this.#authors.get(author); if (a === undefined) this.#authors.set(author, (a = author)); return a; }, this.#texts ? this.#reader(seq) : undefined, this.#lists ? this.#listReader(seq) : undefined, ); this.#atoms.push(frozen); let lam = 0; for (const d of deps) lam = Math.max(lam, this.lamport(d) + 1); this.#lamport.push(lam); // The run starts' parents and the deleted lines, as codes, before this atom's own lines exist. // The atom as given: with lists kept elsewhere, the frozen one reads them back from the log. const deletes = atom.deletes.length > 0 ? new Set(atom.deletes) : undefined; const deletedN = atom.deletes.map((line) => this.#lineN(line)); this.#atomDeletes.push(deletedN.length > 0 ? Int32Array.from(deletedN) : undefined); this.#lineBase.push(this.#lineTotal); for (const run of atom.inserts) { const file = this.#pathOf(run.file); let parent = isStartNode(run.parent) ? -1 - file : this.#lineN(run.parent); const first = this.#lineTotal; pushOne(this.#runStarts, parent, first); for (let i = 0; i < run.lines.length; i++) { const n = this.#lineTotal++; this.#lineAtom.push(seq); this.#lineFile.push(file); this.#lineParent.push(parent); this.#lineText?.push(run.lines[i]!); this.#deleter.push(-1); this.#replacing.push(i === 0 && deletes?.has(run.parent) ? 1 : 0); parent = n; } } (frozen.moves ?? []).forEach((m, i) => { const info: RelocationInfo = Object.freeze({ atom: frozen.id, line: m.line, parent: m.parent, k: i }); pushIndex(this.#relocations, m.line, info); pushIndex(this.#relocatedTo, m.parent, info); pushIndex( this.#relocatedToCode, isStartNode(m.parent) ? -1 - this.#pathOf(m.parent.slice(1)) : this.#lineN(m.parent), info, ); }); if (frozen.moves) this.#movers.push(frozen.id); for (const n of deletedN) { if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq); else pushIndex(this.#moreDeleters, n, seq); } for (const key of new Set(atom.writes)) pushOne(this.#writers, this.#code(key), frozen.id); for (const key of new Set(atom.reads)) pushOne(this.#readers, this.#code(key), frozen.id); for (const key of new Set(atom.holds)) pushOne(this.#holders, this.#code(key), frozen.id); for (const d of deps) pushOne(this.#dependents, d, frozen.id); for (const r of new Set(frozen.resolves)) pushOne(this.#resolvers, r, frozen.id); const files = new Set(); for (const run of atom.inserts) files.add(run.file); for (const n of deletedN) files.add(this.#paths[this.#lineFile.at(n)]!); for (const a of frozen.attrs ?? []) files.add(a.file); for (const m of frozen.moves ?? []) { files.add(this.lineFile(m.line)!); files.add(isStartNode(m.parent) ? m.parent.slice(1) : this.lineFile(m.parent)!); } this.#atomFiles.push(Object.freeze([...files].sort())); for (const file of files) pushIndex(this.#fileAtoms, file, frozen.id); for (const r of frozen.reasons) { if (r.kind !== "together" || r.to === frozen.id) continue; pushIndex(this.#together, frozen.id, { other: r.to, text: r.text, from: frozen.id }); pushIndex(this.#together, r.to, { other: frozen.id, text: r.text, from: frozen.id }); } } // Labels ----------------------------------------------------------------- /** * Add or replace a label. Label names may not look like atom ids. A base is * resolved to its head only when it is used, never followed further, so * bases may name each other in any shape. */ setLabel(label: Label): void { this.#putLabel(label, (name) => this.#labels.has(name)); } #putLabel(label: Label, isLabel: (name: string) => boolean): void { const bad = (why: string): never => { throw new EngineError("bad-label", `label ${JSON.stringify(label?.name)}: ${why}`); }; if (typeof label !== "object" || label === null) bad("not an object"); if (typeof label.name !== "string" || label.name === "") bad("needs a name"); if (isAtomId(label.name)) bad("a label name may not look like an atom id"); if (!this.has(label.head)) bad(`head ${label.head} is not in the graph`); if ( label.base !== undefined && !(typeof label.base === "string" && (isLabel(label.base) || this.has(label.base))) ) { bad(`base ${label.base} is neither a label nor an atom`); } if (label.base === label.name) bad("a label cannot be its own base"); if (typeof label.title !== "string" || typeof label.message !== "string") bad("needs a title and message"); if (label.follows !== undefined && !Array.isArray(label.follows)) bad("follows must be a list of label names"); const copy: Label = { name: label.name, head: label.head, ...(label.base !== undefined ? { base: label.base } : {}), title: label.title, message: label.message, ...(label.follows !== undefined ? { follows: Object.freeze([...label.follows]) } : {}), }; this.#labels.set(label.name, Object.freeze(copy)); } label(name: string): Label | undefined { return this.#labels.get(name); } /** Labels sorted by name. */ labels(): Label[] { return [...this.#labels.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); } /** * Remove a label. Labels that used it as their base get its head atom as * their base instead, so their contents don't change. */ removeLabel(name: string): boolean { const gone = this.#labels.get(name); if (!gone) return false; this.#labels.delete(name); for (const label of [...this.#labels.values()]) { if (label.base === name) this.#labels.set(label.name, Object.freeze({ ...label, base: gone.head })); } return true; } // JSON ------------------------------------------------------------------- toJSON(): GraphJSON { return { format: GRAPH_FORMAT, version: 1, atoms: this.#atoms, labels: this.labels() }; } /** Load a saved graph. Every atom is re-validated as it is added. */ static fromJSON(data: unknown): Graph { const bad = (why: string): never => { throw new EngineError("bad-json", why); }; if (typeof data !== "object" || data === null) bad("graph JSON must be an object"); const obj = data as Partial; if (obj.format !== GRAPH_FORMAT) bad(`format must be ${GRAPH_FORMAT}`); if (obj.version !== 1) bad(`unsupported version ${String(obj.version)}`); if (!Array.isArray(obj.atoms) || !Array.isArray(obj.labels)) bad("atoms and labels must be arrays"); const graph = new Graph(); for (const atom of obj.atoms!) graph.add(atom); // Labels may name each other as bases, in any order and any shape. const names = new Set(); for (const label of obj.labels!) { const name: unknown = (label as Partial