const assert = require('assert/strict'); const { SEARCH_LIMIT, bookmarkChain, buildHierarchy, childrenOf, fuzzyScore, idForPath, searchHierarchy, searchTarget, treeRows, } = require('./hierarchyModel'); // The schema-2 wire the server sends: a file table, four-number ranges, no ids // and no per-instance `definitions` — the model rebuilds all three. const FILES = [ 'file:///tb.sv', 'file:///top.sv', 'file:///block.sv', 'file:///leaf.sv', 'file:///alpha.sv', ]; function site(file, line, start, end) { return { file, range: [line, 0, line, end + 3], selectionRange: [line, start, line, end] }; } function fixture() { return { schemaVersion: 2, revision: 3, complete: true, files: FILES, modules: [ { moduleName: 'top', definition: site(1, 0, 7, 10), instances: [ { instanceName: 'inst1', moduleName: 'block', site: site(1, 1, 8, 13) }, ] }, { moduleName: 'leaf', definition: site(3, 0, 7, 11), instances: [] }, { moduleName: 'TB', definition: site(0, 0, 7, 9), instances: [ { instanceName: 'dut', moduleName: 'top', site: site(0, 1, 6, 9) }, ] }, { moduleName: 'block', definition: site(2, 0, 7, 12), instances: [ { instanceName: 'inst2', moduleName: 'leaf', site: site(2, 1, 7, 12) }, ] }, { moduleName: 'alpha_root', definition: site(4, 0, 7, 17), instances: [] }, ], }; } /** The rows a view would show with `open` expanded, by label. */ function labels(model, open = []) { return treeRows(model, new Set(open), '').rows.map((row) => row.label); } function rootsAreAlphabeticalAndEverythingStartsCollapsed() { const model = buildHierarchy(fixture()); assert.deepEqual( model.roots.map(({ module }) => module.moduleName), ['alpha_root', 'TB'], 'the two modules nothing instantiates, case-insensitively alphabetical', ); // Owner, 2026-08-29: no level auto-expands. Opening the view shows the roots // and nothing under them. assert.deepEqual(labels(model), ['alpha_root', 'TB']); const [, tb] = treeRows(model, new Set(), '').rows; assert.equal(tb.hasChildren, true, 'but the twisty says there is more'); assert.equal(tb.expanded, false); } function openingOneLevelAtATimeWalksTheDesign() { const model = buildHierarchy(fixture()); const open = []; const openTo = (label) => { const row = treeRows(model, new Set(open), '').rows .find((candidate) => candidate.label === label); assert(row, `${label} is not on screen: ${labels(model, open).join(', ')}`); open.push(row.id); return row; }; openTo('TB'); assert.deepEqual(labels(model, open), ['alpha_root', 'TB', 'dut (top)']); openTo('dut (top)'); openTo('inst1 (block)'); assert.deepEqual(labels(model, open), [ 'alpha_root', 'TB', 'dut (top)', 'inst1 (block)', 'inst2 (leaf)', ]); const deep = treeRows(model, new Set(open), '').nodes.get(open[open.length - 1]); assert.equal(childrenOf(model, deep)[0].fullPath, 'TB.dut.inst1.inst2'); assert.equal(childrenOf(model, deep)[0].definition.uri, 'file:///leaf.sv'); } function rowIdsSurviveARefresh() { // What keeps the user's expansion state across a rescan: an id is composed // from URIs and declaration positions, not from array order. const first = buildHierarchy(fixture()); const shuffled = fixture(); shuffled.modules.reverse(); shuffled.revision = 4; const second = buildHierarchy(shuffled); const open = treeRows(first, new Set(), '').rows.map((row) => row.id); assert.deepEqual(treeRows(second, new Set(), '').rows.map((row) => row.id), open); assert.deepEqual(labels(second, open), labels(first, open)); } function bookmarksResolveByPathWithoutATableOfEveryPath() { const model = buildHierarchy(fixture()); const chain = bookmarkChain(model, 'TB.dut.inst1.inst2'); assert.equal(chain.length, 4); assert.equal(idForPath(model, 'TB.dut.inst1.inst2'), chain[3]); assert.equal(idForPath(model, 'TB.dut.nope'), undefined); assert.equal(idForPath(model, ''), undefined); // Expanding the chain's ancestors is what reveals the row. const { rows } = treeRows(model, new Set(chain.slice(0, -1)), 'TB.dut.inst1.inst2'); assert.equal(rows.filter((row) => row.bookmarked).length, 1); assert.equal(rows.find((row) => row.bookmarked).label, 'inst2 (leaf)'); } function searchScansTheFlatIndexAndKeepsAncestorContext() { const model = buildHierarchy(fixture()); const found = searchHierarchy(model, 'is2'); assert.equal(found.rows.length, 1, 'one row per instance, not one per path'); assert.equal(found.rows[0].label, 'inst2 (leaf)'); assert.equal(found.rows[0].detail, 'in block', 'the row says which module writes it'); assert.equal(searchHierarchy(model, 'tb.sv').total, 0, 'filenames are not searched'); assert.equal(searchHierarchy(model, 'TB.dut').total, 0, 'full paths are not searched'); assert.equal(searchHierarchy(model, '').total, 0, 'an empty query is not match-everything'); const target = searchTarget(model, found.rows[0].id); assert.equal(target.kind, 'instance'); assert.equal(target.site.uri, 'file:///block.sv'); assert.equal(target.definition.uri, 'file:///leaf.sv'); assert.equal(target.fullPath, undefined, 'a flat hit has no one path'); assert.equal(searchTarget(model, 'find:nope'), undefined); assert.equal(searchTarget(model, 'root:whatever'), undefined); } function recursionAndAmbiguityStayFinite() { // `A` and `B` instantiate each other — the cycle — and `B` instantiates `C`, // which two files declare, so every `C` row is ambiguous. Ambiguity is the // model's own conclusion from the module table: the wire says only that the // instance's type is spelled `C`. const model = buildHierarchy({ schemaVersion: 2, revision: 1, complete: true, files: ['file:///a.sv', 'file:///b.sv', 'file:///c.sv', 'file:///other-c.sv'], modules: [ { moduleName: 'A', definition: site(0, 0, 7, 8), instances: [ { instanceName: 'u_b', moduleName: 'B', site: site(0, 1, 4, 7) }, ] }, { moduleName: 'B', definition: site(1, 0, 7, 8), instances: [ { instanceName: 'u_a', moduleName: 'A', site: site(1, 1, 4, 7) }, { instanceName: 'u_amb', moduleName: 'C', site: site(1, 2, 4, 9) }, ] }, { moduleName: 'C', definition: site(2, 0, 7, 8), instances: [] }, { moduleName: 'C', definition: site(3, 0, 7, 8), instances: [] }, ], }); assert.deepEqual( model.roots.map(({ module, fallback }) => [module.moduleName, fallback]), [['C', false], ['C', false], ['A', true]], 'the two unparented `C` declarations, then one fallback root for the cycle', ); // Open A, then u_b: the `u_a` under it is the cycle closing, and it is a leaf. const open = []; for (const label of ['A', 'u_b (B)']) { open.push(treeRows(model, new Set(open), '').rows .find((candidate) => candidate.label === label).id); } const { rows } = treeRows(model, new Set(open), ''); const recursive = rows.find((row) => row.kind === 'instance' && row.detail === 'recursive'); assert(recursive, 'the repeated edge is present and marked'); assert.equal(recursive.label, 'u_a (A)'); assert.equal(recursive.hasChildren, false, 'and does not open again'); const ambiguous = rows.find((row) => row.detail === 'ambiguous'); assert(ambiguous, 'a type two files declare is ambiguous'); assert.equal(ambiguous.hasChildren, false); } function scoringIsDeterministic() { assert(fuzzyScore('inst2', 'inst2') > fuzzyScore('inst20', 'inst2')); assert(fuzzyScore('u_fifo', 'ufi') > fuzzyScore('unrelated_f_i', 'ufi')); assert.equal(fuzzyScore('module', 'xyz'), -1); } function malformedSnapshotsAreRejected() { assert.throws(() => buildHierarchy({ schemaVersion: 1, files: [], modules: [] }), /unsupported/); assert.throws(() => buildHierarchy({ ...fixture(), files: undefined }), /unsupported/); const noRange = fixture(); noRange.modules[0].definition.selectionRange = null; assert.throws(() => buildHierarchy(noRange), /malformed/); const shortRange = fixture(); shortRange.modules[0].instances[0].site.range = [1, 2, 3]; assert.throws(() => buildHierarchy(shortRange), /malformed/); const offTable = fixture(); offTable.modules[0].definition.file = FILES.length; assert.throws(() => buildHierarchy(offTable), /malformed/); } /** The wire is narrow; the model is not. Everything the rest of the extension * reads — a URI, `{ line, character }` positions, an id, the declarations an * instance's module name resolves to — is rebuilt here. */ function theNarrowWireIsRebuiltIntoTheWideModel() { const model = buildHierarchy(fixture()); const block = model.modules.find((module) => module.moduleName === 'block'); const [inst2] = block.instances; assert.equal(inst2.site.uri, 'file:///block.sv'); assert.deepEqual(inst2.site.selectionRange, { start: { line: 1, character: 7 }, end: { line: 1, character: 12 }, }); assert.equal(inst2.id, 'file:///block.sv#1:7'); assert.equal(inst2.definitions.length, 1, 'rebuilt from the module table'); assert.equal(inst2.definitions[0].uri, 'file:///leaf.sv'); assert.equal(inst2.unresolved, false); assert.equal(inst2.ambiguous, false); } /** The owner's freeze, turned into a budget. 20 000 modules and 100 000 * instances — six times opentitan — built once, then queried. What is asserted * is the shape of the cost with room to spare on a slow machine: an array scan * is microseconds per entry, so 120 000 entries is single-digit milliseconds * per query. */ function searchOverAHugeHierarchyStaysInsideItsBudget() { const MODULES = 20000; const PER_MODULE = 5; const files = []; const modules = []; for (let m = 0; m < MODULES; m += 1) { files.push(`file:///gen/mod_${m}.sv`); const instances = []; for (let i = 0; i < PER_MODULE; i += 1) { instances.push({ instanceName: `u_inst_${m}_${i}`, moduleName: `mod_${(m + i + 1) % MODULES}`, site: { file: m, range: [i + 1, 2, i + 1, 40], selectionRange: [i + 1, 6, i + 1, 20] }, }); } modules.push({ moduleName: `mod_${m}`, definition: { file: m, range: [0, 0, 9, 9], selectionRange: [0, 7, 0, 14] }, instances, }); } const snapshot = { schemaVersion: 2, revision: 1, complete: true, files, modules }; const builtAt = process.hrtime.bigint(); const model = buildHierarchy(snapshot); const buildMs = Number(process.hrtime.bigint() - builtAt) / 1e6; assert.equal(model.entries.length, MODULES * (PER_MODULE + 1)); assert(buildMs < 8000, `building the model took ${buildMs.toFixed(1)} ms`); // Rows are only built for what is open, so a collapsed tree over 100 000 // instances is one row per root and nothing else. const rowsAt = process.hrtime.bigint(); const { rows } = treeRows(model, new Set(), ''); const rowsMs = Number(process.hrtime.bigint() - rowsAt) / 1e6; assert(rows.length <= MODULES, 'a collapsed tree is at most one row per root'); assert(rowsMs < 500, `the collapsed tree took ${rowsMs.toFixed(1)} ms`); // Every prefix of a word typed one character at a time — the keystroke // sequence that froze the view. let worst = 0; for (const query of ['u', 'u_', 'u_i', 'u_in', 'u_ins', 'u_inst', 'u_inst_1', 'mod_999', 'zzz']) { const at = process.hrtime.bigint(); const found = searchHierarchy(model, query); const ms = Number(process.hrtime.bigint() - at) / 1e6; worst = Math.max(worst, ms); assert(found.rows.length <= SEARCH_LIMIT, `${query} rendered ${found.rows.length} rows`); if (found.total > SEARCH_LIMIT) { assert.equal(found.truncated, found.total - SEARCH_LIMIT, 'the "N more" count'); } } // Single-digit milliseconds is the target; 60 ms is the assertion, so a busy // machine does not fail a test that is about orders of magnitude. assert( worst < 60, `the slowest query took ${worst.toFixed(1)} ms over ${model.entries.length} entries`, ); if (process.env.LUCISV_SEARCH_TIMINGS) { console.log(` build ${buildMs.toFixed(1)} ms, collapsed tree ${rowsMs.toFixed(2)} ms, worst query ${worst.toFixed(2)} ms`); } } /** QA (2026-08-29): the counting cutoff must choose the same top rows a full * sort of every score would — checked here by hand, not by re-deriving * `truncated` from the same numbers the search already produced. Five * instances of one module, `leaf`, are scored against `fifo` by the * documented rule (exact/prefix/substring tiers, then the subsequence loop's * bonuses), and the ranking below is arithmetic anyone can redo: * "fifo" exact 10000 + 1 (instance tie) = 10001 * "fifo_ctrl" prefix, 8000 - (9-4) = 7996 * "ffifo" substring at 1, 6000-10-(5-4) +1 = 5990 * "u_fifo" substring at 2, 6000-20-(6-4) +1 = 5979 * "f_i_f_o" subsequence only +1 = 65 * "unrelated" no match at all -1 * so the top 3 are "fifo", "fifo_ctrl", "ffifo" in that order, and 2 more * (of the 5 real matches) are owed. */ function topKSearchMatchesWhatAFullSortWouldChoose() { const files = ['file:///top.sv', 'file:///leaf.sv']; const names = ['fifo', 'fifo_ctrl', 'ffifo', 'u_fifo', 'f_i_f_o', 'unrelated']; const instances = names.map((name, i) => ({ instanceName: name, moduleName: 'leaf', site: site(0, i + 1, 2, 6 + name.length), })); const snapshot = { schemaVersion: 2, revision: 1, complete: true, files, modules: [ { moduleName: 'top', definition: site(0, 0, 7, 10), instances }, { moduleName: 'leaf', definition: site(1, 0, 7, 11), instances: [] }, ], }; const model = buildHierarchy(snapshot); const found = searchHierarchy(model, 'fifo', 3); assert.deepEqual( found.rows.map((row) => row.label.split(' ')[0]), ['fifo', 'fifo_ctrl', 'ffifo'], 'the counting cutoff must agree with a full sort by hand', ); assert.equal(found.total, 5, 'exactly the five names that contain f, i, f, o in order'); assert.equal(found.truncated, 2, 'five real matches minus the three shown'); // The same query with no cap at all must return every match, in the same // relative order, as a cross-check that capping never reorders anything. const uncapped = searchHierarchy(model, 'fifo', 100); assert.deepEqual( uncapped.rows.map((row) => row.label.split(' ')[0]), ['fifo', 'fifo_ctrl', 'ffifo', 'u_fifo', 'f_i_f_o'], ); } /** QA (2026-08-29): the letter/digit bitmask is a coarse presence test — every * non-alphanumeric, non-`_` character shares one bit — so it must only ever * be more permissive than the real scorer, never less. Checked against an * independent, un-bitmasked subsequence check (`isSubsequence` below, which * does not use `maskOf` at all) over escaped-identifier-shaped names: an * instance name a real design can actually carry, with `$`, `.` and `[]` in * it, none of which are letters or digits and so all fold onto one bit. */ function theBitmaskPrefilterNeverExcludesATrueSubsequenceMatch() { function isSubsequence(haystack, needle) { let cursor = 0; for (const ch of needle) { cursor = haystack.indexOf(ch, cursor); if (cursor < 0) return false; cursor += 1; } return true; } const cases = [ ['\\pll.ref_clk[0]', 'pll.ref'], ['\\pll.ref_clk[0]', 'p.r[0'], ['a$b.c]d', 'a$c]d'], ['a$b.c]d', 'a.d'], ['zz9', 'z9'], ['a0z', 'a0z'], ]; for (const [haystack, needle] of cases) { assert( isSubsequence(haystack, needle), `premise: "${needle}" is really a subsequence of "${haystack}"`, ); assert( fuzzyScore(haystack, needle) >= 0, `the bitmask prefilter excluded a true match: "${needle}" in "${haystack}"`, ); } // End to end: the same names, reachable through `searchHierarchy`, not just // through the scorer it calls. const files = ['file:///top.sv', 'file:///leaf.sv']; const model = buildHierarchy({ schemaVersion: 2, revision: 1, complete: true, files, modules: [ { moduleName: 'top', definition: site(0, 0, 7, 10), instances: [ { instanceName: '\\pll.ref_clk[0]', moduleName: 'leaf', site: site(0, 1, 2, 20) }, ] }, { moduleName: 'leaf', definition: site(1, 0, 7, 11), instances: [] }, ], }); assert.equal(searchHierarchy(model, 'pll.ref').rows.length, 1); assert.equal(searchHierarchy(model, 'p.r[0').rows.length, 1); } for (const test of [ rootsAreAlphabeticalAndEverythingStartsCollapsed, openingOneLevelAtATimeWalksTheDesign, rowIdsSurviveARefresh, bookmarksResolveByPathWithoutATableOfEveryPath, searchScansTheFlatIndexAndKeepsAncestorContext, recursionAndAmbiguityStayFinite, scoringIsDeterministic, malformedSnapshotsAreRejected, theNarrowWireIsRebuiltIntoTheWideModel, searchOverAHugeHierarchyStaysInsideItsBudget, topKSearchMatchesWhatAFullSortWouldChoose, theBitmaskPrefilterNeverExcludesATrueSubsequenceMatch, ]) test(); console.log('hierarchy model: OK — collapsed roots, lazy levels, stable ids, bookmarks, search, cycles, validation, wire rebuilding, and the 120k-entry search budget');