Files
lucisv/editors/vscode/hierarchySections.js
Guoliang ChenandClaude Mythos 5.2 e9f5090632
ci / checks (push) Successful in 52s
ci / corpus (push) Successful in 15s
release / build-and-publish (push) Successful in 4m59s
Release 0.65.2: the Hierarchy pane shows where you are
TODO §71.6. The rows leading to the file being edited are lit in the
extension's Hierarchy pane: every instance of the module the open file
declares in a light, bright orange with a solid bar and a bold label, each
ancestor a shade dimmer with a narrower bar, down to a floor. A pure module
(hierarchyCurrent.js) computes each module's distance with one breadth-first
search up the instantiation graph; the webview repaints only the rows whose
level changed, with no server request and no tree rebuild. Six theme colours
under contributes.colors and the setting lucisv.hierarchy.highlightCurrent.
hierarchyPalette_test.js computes label contrast (>= 4.5:1 on every level,
six built-in themes) and neighbour distinctness from the shipped defaults.

Dev, QA (pass with findings, one fix round) and lead review are in
docs/features/hierarchy-current-path/README.md. Not seen in a running editor.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.2) and
editors/vscode/CHANGELOG.md.

Gates: tools/gates.sh PASS on this tree (20261119-043114), node 12/0.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 04:32:43 -08:00

463 lines
17 KiB
JavaScript

// DUT-centred sections over the flat hierarchy model. A design holds hundreds
// of modules and one — or a few — that matter: the DUT, usually with a
// testbench above it. Starring a module splits the pane into, per DUT, its
// forward subtree and an upward tree of everything that instantiates it, and
// then one section for every module that is in neither. No `vscode` dependency,
// so plain Node tests cover all of it. See
// docs/features/dut-hierarchy/README.md.
//
// **Nothing here materializes a tree.** Sections are composed out of the same
// lazily-expanded nodes `hierarchyModel.js` builds: a section holds one root
// node, and the level below a row is built when the user opens it. The one
// thing built per snapshot is the reverse index — module → the instances that
// name it — which is a single pass over the modules already resident.
//
// Ids are prefixed per section (`dut:aes/root:file#1:7`), and every descendant
// id is derived from its parent's, so one prefix moves a whole subtree into its
// own section. That is what lets a module that is below one DUT and above
// another appear in both sections and open independently in each.
const { childrenOf, idForPath, rootNode } = require('./hierarchyModel');
/** The menu items an instance row has always offered, in their fixed order. */
const INSTANCE_ACTIONS = [
{ action: 'copyPath', label: 'Copy Full Path' },
{ action: 'definition', label: 'Show Definition' },
{ action: 'instance', label: 'Show Instance' },
{ action: 'bookmark', label: 'Highlight / Bookmark' },
{ action: 'openRight', label: 'Open on the Right' },
];
const STAR = { action: 'starDut', label: 'Star as DUT' };
const UNSTAR = { action: 'unstarDut', label: 'Unstar DUT' };
/** A DUT the workspace settings name cannot be unstarred from the pane, because
* the pane will not edit a checked-in file on the user's behalf. */
const LOCKED = {
action: 'lockedDut',
label: 'DUT from settings',
disabled: true,
title: 'This DUT comes from the lucisv.hierarchy.duts setting. Remove it there to unstar it.',
};
function compareText(a, b) {
const foldedA = a.toLowerCase();
const foldedB = b.toLowerCase();
if (foldedA < foldedB) return -1;
if (foldedA > foldedB) return 1;
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
function compareEdges(a, b) {
return compareText(a.module.moduleName, b.module.moduleName)
|| compareText(a.instance.instanceName, b.instance.instanceName)
|| compareText(a.instance.site.uri, b.instance.site.uri)
|| a.instance.site.selectionRange.start.line - b.instance.site.selectionRange.start.line;
}
/// Module id → the `{ module, instance }` edges that instantiate it, in a
/// deterministic order. One pass per snapshot, memoized on the model, because
/// the upward tree asks this question once per opened row.
function parentIndex(model) {
if (model.parentsByTarget) return model.parentsByTarget;
const index = new Map();
for (const module of model.modules) {
for (const instance of module.instances) {
if (!instance.targetId) continue;
const found = index.get(instance.targetId) || [];
found.push({ module, instance });
index.set(instance.targetId, found);
}
}
for (const edges of index.values()) edges.sort(compareEdges);
model.parentsByTarget = index;
return index;
}
/// The declarations of a starred name: the first one is what the sections show,
/// and more than one makes the section ambiguous.
function declarationsNamed(model, name) {
return model.modules.filter((module) => module.moduleName === name);
}
/// The section list §56 specifies: per starred DUT, in starred order, its
/// forward subtree and its upward tree, then everything else.
function sections(model, duts) {
const list = [];
const excluded = new Set();
for (const name of duts) {
const found = declarationsNamed(model, name);
const [module] = found;
list.push(dutSection(model, name, module, found.length > 1));
list.push(parentsSection(model, name, module, found.length > 1));
if (!module) continue;
collectSubtree(model, module, excluded);
collectAncestors(model, module, excluded);
}
list.push({ kind: 'others', roots: othersRoots(model, excluded) });
return list;
}
/// The `others` section's roots. "All other modules" is **additive**: `others`
/// holds every module that is in no DUT's forward subtree and no DUT's ancestor
/// closure — not `model.roots` minus that set. A monitor the DV bench
/// instantiates beside the DUT is not a child of the DUT, so it belongs here;
/// the exclusion took away every parent it had, so it is re-rooted at the top
/// of the section rather than dropped out of the pane.
///
/// The roots are the members of that set with no parent left inside it. A
/// module that still has one is shown under that parent, so nothing appears
/// twice: reachable from one excluded and one ordinary parent, it stays where
/// it always was. Nothing appears twice the long way round either — a path from
/// one module of the set to another cannot leave it, because a module *above*
/// an ancestor of the DUT is itself an ancestor and a module *below* the DUT's
/// subtree is itself in it, and both are excluded. Roots come out in the
/// model's own order — alphabetically, then the ones only a cycle reaches,
/// which is what `model.roots` does.
///
/// A root's forward subtree is the plain one, **unfiltered**: a module that is
/// also below a DUT is still shown under its parent here, exactly as it is
/// today. A DUT itself can never turn up in it — everything that instantiates a
/// DUT is in that DUT's ancestor closure and is therefore excluded from the set
/// this walks.
function othersRoots(model, excluded) {
const plain = new Set();
const recursive = new Set();
const covered = new Set();
const take = (module, into) => {
into.add(module.id);
coverSubtree(model, module, covered);
};
// The pane's own roots, minus the excluded: with nothing starred this is the
// whole answer and it is byte-identical to `model.roots`.
for (const { module, fallback } of model.roots) {
if (!excluded.has(module.id)) take(module, fallback ? recursive : plain);
}
// Then what the exclusion orphaned: every parent it has is inside a DUT
// section, and no root reaches it, so this is the only place left to show it.
for (const module of model.modules) {
if (excluded.has(module.id) || covered.has(module.id)) continue;
if (hasParentInOthers(model, module, excluded)) continue;
take(module, plain);
}
// Whatever is still unreached is inside a recursive component that no root
// enters — the model's own fallback rule, marked the way it marks it.
for (const module of model.modules) {
if (excluded.has(module.id) || covered.has(module.id)) continue;
take(module, recursive);
}
const roots = model.modules.filter((module) => plain.has(module.id))
.map((module) => ({ module, fallback: false }));
for (const module of model.modules) {
if (recursive.has(module.id)) roots.push({ module, fallback: true });
}
return roots;
}
/// Does a module the `others` set still holds instantiate this one? Then it is
/// already on screen under that module and must not be re-rooted beside it.
function hasParentInOthers(model, module, excluded) {
return (parentIndex(model).get(module.id) || [])
.some((edge) => !excluded.has(edge.module.id));
}
/// Everything an `others` root puts on screen: its forward subtree over the
/// module graph, excluded modules included, because that subtree is not
/// filtered. A module already covered was descended through, so is everything
/// below it — which is what keeps the whole pass linear.
function coverSubtree(model, start, covered) {
const stack = [start];
while (stack.length > 0) {
const module = stack.pop();
if (covered.has(module.id)) continue;
covered.add(module.id);
for (const instance of module.instances) {
const target = instance.targetId && model.byId.get(instance.targetId);
if (target) stack.push(target);
}
}
}
function dutSection(model, name, module, ambiguous) {
if (!module) return { kind: 'dut', name, root: undefined, ambiguous };
// Exactly the node the plain view would show for this module, including its
// `recursive` marking when the module is only a root because of a cycle.
const plain = model.roots.find((root) => root.module.id === module.id);
const root = rootNode(model, module, Boolean(plain && plain.fallback));
root.id = `${prefixFor('dut', name)}${root.id}`;
return { kind: 'dut', name, root, ambiguous };
}
function parentsSection(model, name, module, ambiguous) {
if (!module) return { kind: 'parents', name, root: undefined, ambiguous };
return { kind: 'parents', name, root: upRootNode(model, name, module), ambiguous };
}
/// The DUT itself, as the root of the upward tree.
function upRootNode(model, name, module) {
return {
id: `${prefixFor('parents', name)}up:${module.id}`,
kind: 'module',
up: true,
moduleName: module.moduleName,
label: module.moduleName,
detail: '',
depth: 0,
parentId: null,
fullPath: undefined,
hasChildren: (parentIndex(model).get(module.id) || []).length > 0,
warning: false,
definition: module.definition,
definitions: [module.definition],
site: undefined,
moduleId: module.id,
seen: new Set([module.id]),
};
}
/// One module that instantiates `parent`'s module, named by the instance that
/// does it. A module already on the path upward closes a cycle: it is shown,
/// marked, and does not open again — the forward tree's rule, upside down.
function upNode(model, parent, { module, instance }) {
const repeated = parent.seen.has(module.id);
const seen = new Set(parent.seen);
seen.add(module.id);
return {
id: `${parent.id}>${instance.id}`,
kind: 'module',
up: true,
moduleName: module.moduleName,
instanceName: instance.instanceName,
label: module.moduleName,
detail: repeated ? 'recursive' : `via ${instance.instanceName}`,
depth: parent.depth + 1,
parentId: parent.id,
fullPath: undefined,
hasChildren: !repeated && (parentIndex(model).get(module.id) || []).length > 0,
warning: repeated,
definition: module.definition,
definitions: [module.definition],
site: instance.site,
moduleId: module.id,
seen,
};
}
/// The level below a row, whichever direction its section runs in.
function childrenIn(model, node) {
if (!node.up) return childrenOf(model, node);
return (parentIndex(model).get(node.moduleId) || [])
.map((edge) => upNode(model, node, edge));
}
/// Every module reachable downward from the DUT, over the module graph rather
/// than the expanded tree, so a diamond costs one visit and a cycle terminates.
///
/// The visited set is this walk's own, not the shared `into`: a module already
/// in `into` may have been put there as another DUT's *ancestor*, in which case
/// nothing below it has been collected yet and stopping there would leave the
/// exclusion short.
function collectSubtree(model, start, into) {
const stack = [start];
const seen = new Set();
while (stack.length > 0) {
const module = stack.pop();
if (seen.has(module.id)) continue;
seen.add(module.id);
into.add(module.id);
for (const instance of module.instances) {
const target = instance.targetId && model.byId.get(instance.targetId);
if (target) stack.push(target);
}
}
}
/// The same walk upward: every module that instantiates the DUT, transitively.
function collectAncestors(model, start, into) {
const index = parentIndex(model);
const stack = [start];
const seen = new Set();
while (stack.length > 0) {
const module = stack.pop();
if (seen.has(module.id)) continue;
seen.add(module.id);
into.add(module.id);
for (const edge of index.get(module.id) || []) stack.push(edge.module);
}
}
/// The id prefix a DUT's two sections stamp on their rows. The bookmark's
/// ancestor expansion needs them: the chain the model resolves is unprefixed,
/// and the copy of it inside a section is the same chain behind one of these.
function sectionPrefixes(duts) {
return duts.flatMap((name) => [prefixFor('dut', name), prefixFor('parents', name)]);
}
function prefixFor(kind, name) {
return `${kind}:${name}/`;
}
/** The `others` section's row id; it has no DUT name to be keyed by. */
const OTHERS_ID = 'sec:others';
/** A section header's row id, stable across renders. */
function headerId(section) {
return section.kind === 'others' ? OTHERS_ID : `sec:${section.kind}:${section.name}`;
}
/// What a star opens on the user's behalf, once, when the DUT list changes: the
/// two new sections and the DUT row at the top of each. Starring is an explicit
/// act — the second exception to "nothing expands by itself", after a
/// bookmark's ancestor chain.
function defaultOpenIds(list) {
const ids = [];
for (const section of list) {
if (section.kind === 'others') continue;
ids.push(headerId(section));
if (section.root) ids.push(section.root.id);
}
return ids;
}
function headerLabel(section) {
if (section.kind === 'dut') return `DUT: ${section.name}`;
if (section.kind === 'parents') return `Parents of ${section.name}`;
return 'Other modules';
}
function headerIcon(section) {
if (section.kind === 'dut') return '★';
return section.kind === 'parents' ? '↑' : '▤';
}
function headerDetail(section) {
if (section.kind === 'others') return `${section.roots.length}`;
return section.ambiguous ? 'ambiguous' : '';
}
/// The rows the sectioned tree shows: every section header, and under an open
/// header the rows of its tree. Same shape as `treeRows`, one level deeper.
function sectionRows(model, list, expanded, bookmarkPath) {
const rows = [];
const nodes = new Map();
const bookmarkId = bookmarkPath ? idForPath(model, bookmarkPath) : undefined;
function push(node) {
nodes.set(node.id, node);
rows.push({
id: node.id,
kind: node.kind,
label: node.label,
detail: node.detail,
moduleName: node.moduleName,
depth: node.depth + 1,
hasChildren: node.hasChildren,
expanded: expanded.has(node.id),
warning: node.warning,
bookmarked: isBookmarked(node.id, bookmarkId),
});
if (!expanded.has(node.id) || !node.hasChildren) return;
for (const child of childrenIn(model, node)) push(child);
}
for (const section of list) {
const id = headerId(section);
rows.push({
id,
kind: 'section',
label: headerLabel(section),
detail: headerDetail(section),
icon: headerIcon(section),
depth: 0,
hasChildren: true,
expanded: expanded.has(id),
warning: false,
bookmarked: false,
});
if (!expanded.has(id)) continue;
if (section.kind === 'others') {
for (const root of section.roots) push(rootNode(model, root.module, root.fallback));
} else if (section.root) {
push(section.root);
} else {
rows.push(missingRow(section, id));
}
}
return { rows, nodes, bookmarkId };
}
/// A starred name the snapshot no longer holds keeps its sections rather than
/// vanishing silently: the user renamed or deleted the module and needs to see
/// that, not a pane that quietly forgot what they starred.
function missingRow(section, id) {
return {
id: `${id}/missing`,
kind: 'notice',
label: `${section.name} is not in the index`,
detail: '',
icon: '⚠',
depth: 1,
hasChildren: false,
expanded: false,
warning: true,
bookmarked: false,
};
}
/// A bookmark is a path from a root, and the same path exists once per section
/// that contains it — behind that section's prefix.
function isBookmarked(id, bookmarkId) {
if (!bookmarkId) return false;
return id === bookmarkId || id.endsWith(`/${bookmarkId}`);
}
/// What a row's menu is chosen by: its kind, whether its module is a DUT, and
/// whether that DUT came from the settings rather than from a star.
function decorate(rows, duts, locked) {
const starred = new Set(duts);
const fromSettings = new Set(locked);
return rows.map((row) => {
if (row.kind === 'section' || row.kind === 'notice') {
return { ...row, contextValue: row.kind };
}
if (!row.moduleName || !starred.has(row.moduleName)) {
return { ...row, contextValue: row.kind };
}
if (!fromSettings.has(row.moduleName)) {
return { ...row, contextValue: `${row.kind}.dut` };
}
return { ...row, contextValue: `${row.kind}.dut.locked`, title: LOCKED.title };
});
}
/// `contextValue` → the menu that row offers. Sent once per render, so the
/// renderer holds no rule of its own and this table is the whole contract.
function menuTable() {
return {
section: [],
notice: [],
module: [STAR],
'module.dut': [UNSTAR],
'module.dut.locked': [LOCKED],
instance: [...INSTANCE_ACTIONS, STAR],
'instance.dut': [...INSTANCE_ACTIONS, UNSTAR],
'instance.dut.locked': [...INSTANCE_ACTIONS, LOCKED],
};
}
module.exports = {
LOCKED,
OTHERS_ID,
decorate,
defaultOpenIds,
headerId,
menuTable,
parentIndex,
sectionPrefixes,
sectionRows,
sections,
};