const assert = require('assert/strict'); const fs = require('fs'); const path = require('path'); const { buildHierarchy, treeRows } = require('./hierarchyModel'); const { sectionRows, sections } = require('./hierarchySections'); const { BAR_COLOR, LIT_COLORS, cssVariableFor, currentPath, levelChanges, litLevel, matchingFiles, rowLevels, } = require('./hierarchyCurrent'); /** A snapshot from `{ module: [instantiated type, …] }`, one file per module * (`file:///.sv`), instance names `u_` (`u__` for a * repeat). A type naming no module is an unresolved instance. */ function design(graph, extraDeclarations = []) { const names = Object.keys(graph); const files = [...names.map((name) => `file:///${name}.sv`), ...extraDeclarations.map((name) => `file:///${name}_2.sv`)]; const place = (file, line) => ({ file, range: [line, 0, line, 9], selectionRange: [line, 1, line, 5] }); const modules = names.map((name, file) => { const counts = new Map(); const instances = graph[name].map((type, line) => { const n = (counts.get(type) || 0) + 1; counts.set(type, n); return { instanceName: n === 1 ? `u_${type}` : `u_${type}_${n}`, moduleName: type, site: place(file, line + 1) }; }); return { moduleName: name, definition: place(file, 0), instances }; }); // A second declaration of an existing name, in its own file: ambiguous. extraDeclarations.forEach((name, at) => { modules.push({ moduleName: name, definition: place(names.length + at, 0), instances: [] }); }); return buildHierarchy({ schemaVersion: 2, revision: 1, complete: true, files, modules }); } /** The current-file path for one module's file. */ function pathFor(model, name) { return currentPath(model, matchingFiles(model, (uri) => uri === `file:///${name}.sv`)); } /** Every row of the plain tree, every row opened. */ function openTree(model) { const expanded = new Set(); for (;;) { const tree = treeRows(model, expanded, ''); const before = expanded.size; for (const row of tree.rows) if (row.hasChildren) expanded.add(row.id); if (expanded.size === before) return { ...tree, list: [] }; } } /** Label → level for the rows that are lit, in row order. */ function lit(tree, pathValue) { const levels = rowLevels(tree.rows, tree.nodes, tree.list, pathValue); return tree.rows.filter((row) => levels.has(row.id)) .map((row) => [`${' '.repeat(row.depth)}${row.label}`, levels.get(row.id)]); } function distancesMapToLevelsWithAFloor() { assert.deepEqual([0, 1, 2, 3, 4, 5, 40].map(litLevel), [0, 1, 2, 3, 4, 4, 4]); assert.equal(litLevel(undefined), undefined); assert.equal(litLevel(-1), undefined); assert.equal(litLevel(1.5), undefined); assert.equal(LIT_COLORS.length, 5, 'one colour per level, the floor included'); } /** VS Code turns only the first dot into a dash (`themeing.ts`), so an id with * two dots would reach the webview under a name no stylesheet expects. */ function colourIdsHaveOneDotAndTheCssUsesTheirVariables() { assert.equal(cssVariableFor('lucisv.hierarchyCurrent'), '--vscode-lucisv-hierarchyCurrent'); assert.equal(cssVariableFor('a.b.c'), '--vscode-a-b.c', 'first dot only, as VS Code does'); const css = fs.readFileSync(path.join(__dirname, 'media', 'hierarchy.css'), 'utf8'); assert(css.includes(`var(${cssVariableFor(BAR_COLOR)},`), 'hierarchy.css paints the bar with its colour'); assert.equal(BAR_COLOR.split('.').length, 2, `${BAR_COLOR} has exactly one dot`); LIT_COLORS.forEach((id, level) => { assert.equal(id.split('.').length, 2, `${id} has exactly one dot`); assert(css.includes(`.row[data-lit="${level}"] { --lit: var(${cssVariableFor(id)},`), `hierarchy.css paints level ${level} with ${id}`); }); } function packageJsonContributesTheColoursAndTheSetting() { const manifest = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8')); const ours = manifest.contributes.colors.filter((colour) => colour.id.startsWith('lucisv.hierarchy')); assert.deepEqual(ours.map((colour) => colour.id), [...LIT_COLORS, BAR_COLOR], 'contributed exactly, in level order'); const bar = ours.at(-1); for (const theme of ['dark', 'light', 'highContrast', 'highContrastLight']) { assert.match(bar.defaults[theme], /^#[0-9A-F]{6}$/, `the bar is opaque in ${theme}`); } const colours = ours.slice(0, -1); for (const colour of colours) { assert(colour.description, `${colour.id} has a description`); for (const theme of ['dark', 'light', 'highContrast', 'highContrastLight']) { assert.match(colour.defaults[theme], /^#[0-9A-F]{8}$/, `${colour.id} has a translucent ${theme} default`); } } // Dimmer each step: the alpha falls level by level in every theme. for (const theme of ['dark', 'light', 'highContrast', 'highContrastLight']) { const alphas = colours.map((colour) => parseInt(colour.defaults[theme].slice(7), 16)); assert(alphas.every((alpha, at) => at === 0 || alpha < alphas[at - 1]), `${theme} dims level by level`); assert(alphas.at(-1) > 0, `${theme}'s floor is still visible`); } const setting = manifest.contributes.configuration.properties['lucisv.hierarchy.highlightCurrent']; assert.equal(setting.type, 'boolean'); assert.equal(setting.default, true); } function theCurrentRowAndEachAncestorAreLitByDistance() { const model = design({ tb: ['dut'], dut: ['leaf', 'other'], leaf: [], other: [], lonely: [] }); assert.deepEqual(lit(openTree(model), pathFor(model, 'leaf')), [ ['tb', 2], [' u_dut (dut)', 1], [' u_leaf (leaf)', 0], ], 'the sibling and the unrelated root stay unlit'); assert.deepEqual(lit(openTree(model), pathFor(model, 'tb')), [['tb', 0]]); } /** The point of the feature: a closed tree still says where the file is. */ function aClosedTreeLightsTheRowsItShows() { const model = design({ tb: ['dut'], dut: ['leaf'], leaf: [] }); const closed = { ...treeRows(model, new Set(), ''), list: [] }; assert.deepEqual(lit(closed, pathFor(model, 'leaf')), [['tb', 2]]); } function everyInstanceAndItsChainIsLitAndTheNearestDistanceWins() { // `shared` is under `top` directly and through `mid`, twice. const model = design({ top: ['mid', 'shared'], mid: ['shared', 'shared'], shared: [] }); assert.deepEqual(lit(openTree(model), pathFor(model, 'shared')), [ ['top', 1], [' u_mid (mid)', 1], [' u_shared (shared)', 0], [' u_shared_2 (shared)', 0], [' u_shared (shared)', 0], ], 'top is one level above its own instance, not two through mid'); } function deepAncestorsShareTheFloor() { const model = design({ a: ['b'], b: ['c'], c: ['d'], d: ['e'], e: ['f'], f: [] }); assert.deepEqual(lit(openTree(model), pathFor(model, 'f')).map(([, level]) => level), [4, 4, 3, 2, 1, 0]); } /** A file declaring two modules lights both, each with its own path. */ function aFileDeclaringTwoModulesLightsBoth() { const model = design({ top: ['x', 'y'], x: [], y: [] }); const both = currentPath(model, matchingFiles(model, (uri) => uri === 'file:///x.sv' || uri === 'file:///y.sv')); assert.deepEqual(lit(openTree(model), both), [['top', 1], [' u_x (x)', 0], [' u_y (y)', 0]]); } /** A row that cannot open is lit only when it is itself current: an unresolved * or ambiguous type names no one module, and a `recursive` repeat leads * nowhere on screen. */ function rowsThatCannotOpenAreOnlyEverCurrent() { const ambiguous = design({ top: ['dup', 'ghost'], dup: [] }, ['dup']); assert.deepEqual(lit(openTree(ambiguous), pathFor(ambiguous, 'dup')), [['dup', 0]], 'the declaration in the file is lit; the ambiguous instance names no one module, so top is not above it'); const cycle = design({ top: ['a'], a: ['b'], b: ['a'] }); assert.deepEqual(lit(openTree(cycle), pathFor(cycle, 'a')), [ ['top', 1], [' u_a (a)', 0], [' u_b (b)', 1], [' u_a (a)', 0], ], 'the recursive repeat is current itself; b, between them, is one above it'); const rows = lit(openTree(cycle), pathFor(cycle, 'b')); assert.deepEqual(rows, [['top', 2], [' u_a (a)', 1], [' u_b (b)', 0]], 'the recursive `a` under b does not open, so it is not lit as b\'s parent'); } function aFileNoModuleIsDeclaredInLightsNothing() { const model = design({ top: ['leaf'], leaf: [] }); assert.equal(currentPath(model, matchingFiles(model, () => false)), undefined); const tree = openTree(model); assert.equal(rowLevels(tree.rows, tree.nodes, tree.list, undefined).size, 0); } function theFileComparisonIsAskedOncePerFile() { const model = design({ top: ['leaf', 'leaf'], leaf: [] }); const asked = []; matchingFiles(model, (uri) => { asked.push(uri); return false; }); assert.deepEqual(asked.sort(), ['file:///leaf.sv', 'file:///top.sv']); } /** DUT sections: the forward section lights like the plain tree, the upward * "Parents of" tree lights the current file's parents by the same distance, * and every header is one level dimmer than the nearest module it holds. */ function sectionsLightTheirTreesAndTheirHeaders() { const model = design({ tb: ['dut', 'mon'], dut: ['leaf'], leaf: [], mon: [], lonely: [] }); const list = sections(model, ['dut']); const expanded = new Set(['sec:dut:dut', 'sec:parents:dut', 'sec:others']); for (let round = 0; round < 4; round += 1) { for (const row of sectionRows(model, list, expanded, '').rows) if (row.hasChildren) expanded.add(row.id); } const tree = { ...sectionRows(model, list, expanded, ''), list }; assert.deepEqual(lit(tree, pathFor(model, 'leaf')), [ ['DUT: dut', 1], [' dut', 1], [' u_leaf (leaf)', 0], ['Parents of dut', 2], [' dut', 1], [' tb', 2], ], "the forward section is the path down to leaf; the upward one is leaf's parents, dimmer going up the design"); assert.deepEqual(lit(tree, pathFor(model, 'tb')), [ ['Parents of dut', 1], [' tb', 0], ], 'tb is current wherever it is shown; the DUT is below it, so it is not lit'); // mon is beside the DUT, not above it: the upward tree holds mon's parent tb, // and mon itself is re-rooted in "Other modules" (dut-hierarchy's rule). assert.deepEqual(lit(tree, pathFor(model, 'mon')), [ ['Parents of dut', 2], [' tb', 1], ['Other modules', 1], [' mon', 0], ]); assert.deepEqual(lit(tree, pathFor(model, 'lonely')), [ ['Other modules', 1], [' lonely', 0], ]); // Closed sections still say which ones hold the file or its parents. const closed = { ...sectionRows(model, list, new Set(), ''), list }; assert.deepEqual(lit(closed, pathFor(model, 'leaf')), [['DUT: dut', 1], ['Parents of dut', 2]]); assert.deepEqual(lit(closed, pathFor(model, 'lonely')), [['Other modules', 1]]); } /** A recursive repeat in the upward tree is still its own module, so it is lit * as that module — the upward rule has no "cannot open" exception. */ function anUpwardRepeatIsLitAsItsModule() { const model = design({ top: ['a'], a: ['b'], b: ['a', 'leaf'], leaf: [] }); const list = sections(model, ['b']); const expanded = new Set(['sec:parents:b']); for (let round = 0; round < 5; round += 1) { for (const row of sectionRows(model, list, expanded, '').rows) if (row.hasChildren) expanded.add(row.id); } const tree = { ...sectionRows(model, list, expanded, ''), list }; const levels = rowLevels(tree.rows, tree.nodes, tree.list, pathFor(model, 'leaf')); const upward = tree.rows.filter((row) => row.id === 'sec:parents:b' || row.id.startsWith('parents:')) .map((row) => [`${' '.repeat(row.depth)}${row.label}`, levels.get(row.id)]); assert.deepEqual(upward, [ ['Parents of b', 2], [' b', 1], [' a', 2], [' b', 1], [' top', 3], ], 'the repeated b closes the cycle and does not open, but is still b, one above leaf'); } function changesNameOnlyTheRowsWhoseLevelMoved() { const before = new Map([['a', 0], ['b', 1], ['c', 2]]); const after = new Map([['a', 0], ['b', 2], ['d', 0]]); assert.deepEqual(levelChanges(before, after), [['b', 2], ['d', 0], ['c', null]]); assert.deepEqual(levelChanges(after, after), []); } /** Ids are untouched: lighting is a separate answer, never part of a row's id. */ function lightingNeverChangesRowIds() { const model = design({ tb: ['dut'], dut: ['leaf'], leaf: [] }); const tree = openTree(model); const ids = tree.rows.map((row) => row.id); rowLevels(tree.rows, tree.nodes, tree.list, pathFor(model, 'leaf')); assert.deepEqual(openTree(model).rows.map((row) => row.id), ids); } /** QA, 2026-11-19: edge cases the suite did not pin. */ function anEmptySnapshotLightsNothing() { const model = buildHierarchy({ schemaVersion: 2, revision: 1, complete: true, files: [], modules: [] }); assert.equal(currentPath(model, matchingFiles(model, () => true)), undefined); } /** Two chains of different length to one ancestor: the shorter one is its * distance, and each row on the longer chain keeps its own. */ function theShorterOfTwoUnequalChainsWins() { const model = design({ top: ['a', 'leaf'], a: ['b'], b: ['c'], c: ['leaf'], leaf: [] }); assert.deepEqual(lit(openTree(model), pathFor(model, 'leaf')), [ ['top', 1], [' u_a (a)', 3], [' u_b (b)', 2], [' u_c (c)', 1], [' u_leaf (leaf)', 0], [' u_leaf (leaf)', 0], ]); } /** A module instantiating itself terminates, and its cut repeat is lit only * when it is the current module. */ function aSelfInstantiatingModuleTerminates() { const model = design({ top: ['a'], a: ['a', 'leaf'], leaf: [] }); assert.deepEqual(lit(openTree(model), pathFor(model, 'leaf')), [['top', 2], [' u_a (a)', 1], [' u_leaf (leaf)', 0]]); assert.deepEqual(lit(openTree(model), pathFor(model, 'a')), [['top', 1], [' u_a (a)', 0], [' u_a (a)', 0]]); } const tests = [ anEmptySnapshotLightsNothing, theShorterOfTwoUnequalChainsWins, aSelfInstantiatingModuleTerminates, distancesMapToLevelsWithAFloor, colourIdsHaveOneDotAndTheCssUsesTheirVariables, packageJsonContributesTheColoursAndTheSetting, theCurrentRowAndEachAncestorAreLitByDistance, aClosedTreeLightsTheRowsItShows, everyInstanceAndItsChainIsLitAndTheNearestDistanceWins, deepAncestorsShareTheFloor, aFileDeclaringTwoModulesLightsBoth, rowsThatCannotOpenAreOnlyEverCurrent, aFileNoModuleIsDeclaredInLightsNothing, theFileComparisonIsAskedOncePerFile, sectionsLightTheirTreesAndTheirHeaders, anUpwardRepeatIsLitAsItsModule, changesNameOnlyTheRowsWhoseLevelMoved, lightingNeverChangesRowIds, ]; for (const test of tests) test(); console.log(`hierarchy current path: OK — ${tests.length} checks: distances and the floor, colour ids and CSS variables, the manifest, every instance lit, nearest distance wins, closed trees and sections, the upward tree, cycles and unresolved rows`);