TODO §56 (docs/features/dut-hierarchy), the owner's request of 2026-09-06.
Client-only, over the flat `lucisv/moduleHierarchy` snapshot the server
already sends. `hierarchySections.js`: per starred DUT, in starred
order, the DUT's forward subtree (the DUT at the top) and an upward tree
from the DUT through every module that instantiates it (labelled `via
<instance>`, cycles cut with one `recursive` row), then one section for
every module in no DUT's subtree or ancestor closure, re-rooted where
its only parents are DUT ancestors (the review ruling — a monitor beside
the DUT under the same bench stays on screen); a module both below one
DUT and above another appears in both DUT sections; a starred name the
index lacks keeps its sections with a "not in the index" row. Star and
unstar from the webview row menu (the pane is a WebviewView, so the
menu is the renderer's, driven by a `menuTable()` per render), the
`lucisv.hierarchy.{starDut,unstarDut,clearDuts}` commands and title
actions, persistence in `workspaceState` in starred order, and the
`lucisv.hierarchy.duts` setting whose entries show locked. With nothing
starred the pane is byte-identical to before (pinned).
opentitan `hw/ip` (847 modules): `aes` → 3 sections with `tb` in its
parents and 5 modules under `aes_tb` re-rooted into others; `aes` +
`hmac` → 5 sections; every module reachable in both configurations; QA's
200-trial fuzz found no overlap and no gap. `extract_test.js` added to
`.vscodeignore`.
(Committed after the 0.48.0 version commit: the release chain broke at a
test-output grep and cut the tag one commit early; the tag is moved here.)
Co-Authored-By: Claude Fable 5.1 <[email protected]>
591 lines
21 KiB
JavaScript
591 lines
21 KiB
JavaScript
// Pure model for the lucisv hierarchy webview. No VS Code dependency: the
|
||
// graph, sorting, fuzzy matching and bookmark rules are driven by plain Node
|
||
// tests and the extension host only performs I/O/navigation.
|
||
//
|
||
// **The hierarchy is held flat and expanded lazily.** The first shape of this
|
||
// file materialized every path of the whole design the moment a snapshot
|
||
// arrived — a module instantiated in ten places duplicated its entire subtree
|
||
// ten times — and then walked that tree, scored two names per node and shipped
|
||
// the whole thing to the webview on *every keystroke*. That is the freeze the
|
||
// owner hit (2026-08-29). What is resident now is exactly the snapshot: modules
|
||
// and their instances, plus one prebuilt lowercased search index. A tree row is
|
||
// built only when the user opens its parent, and a query is answered by one
|
||
// pass over the flat index. See
|
||
// docs/features/vscode-hierarchy-sidebar/README.md.
|
||
|
||
// The wire is deliberately narrow — a file table, four-number ranges, no ids
|
||
// and no per-instance definition copies — because the whole design is re-sent
|
||
// on every index change and 11.6 MB of it blocked the server's request queue.
|
||
// Everything below `validateSnapshot` works on the wide shape
|
||
// (`{ uri, range: { start, end }, selectionRange }`, an id per row, a
|
||
// `definitions` array per instance), which this file rebuilds once per
|
||
// snapshot.
|
||
const SCHEMA_VERSION = 2;
|
||
|
||
/** How many search rows are rendered before the view says "N more…". */
|
||
const SEARCH_LIMIT = 200;
|
||
|
||
/** One `[startLine, startCharacter, endLine, endCharacter]` from the wire. */
|
||
function isWireRange(value) {
|
||
return Array.isArray(value) && value.length === 4
|
||
&& value.every((n) => Number.isInteger(n) && n >= 0);
|
||
}
|
||
|
||
function toRange(wire) {
|
||
return {
|
||
start: { line: wire[0], character: wire[1] },
|
||
end: { line: wire[2], character: wire[3] },
|
||
};
|
||
}
|
||
|
||
function isWireLocation(value, files) {
|
||
return value && Number.isInteger(value.file) && value.file >= 0 && value.file < files.length
|
||
&& isWireRange(value.range) && isWireRange(value.selectionRange);
|
||
}
|
||
|
||
function toLocation(wire, files) {
|
||
return {
|
||
uri: files[wire.file],
|
||
range: toRange(wire.range),
|
||
selectionRange: toRange(wire.selectionRange),
|
||
};
|
||
}
|
||
|
||
/** The row id the server used to send: unique because two declarations cannot
|
||
* begin at one position in one file, and stable across refreshes. */
|
||
function idOf(location) {
|
||
return `${location.uri}#${location.selectionRange.start.line}:${location.selectionRange.start.character}`;
|
||
}
|
||
|
||
function locationKey(location) {
|
||
const start = location.selectionRange.start;
|
||
const end = location.selectionRange.end;
|
||
return `${location.uri}|${start.line}:${start.character}-${end.line}:${end.character}`;
|
||
}
|
||
|
||
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 compareModules(a, b) {
|
||
return compareText(a.moduleName, b.moduleName)
|
||
|| compareText(a.definition.uri, b.definition.uri)
|
||
|| a.definition.selectionRange.start.line - b.definition.selectionRange.start.line
|
||
|| a.definition.selectionRange.start.character - b.definition.selectionRange.start.character;
|
||
}
|
||
|
||
function compareInstances(a, b) {
|
||
return compareText(a.instanceName, b.instanceName)
|
||
|| compareText(a.moduleName, b.moduleName)
|
||
|| compareText(a.site.uri, b.site.uri)
|
||
|| a.site.selectionRange.start.line - b.site.selectionRange.start.line
|
||
|| a.site.selectionRange.start.character - b.site.selectionRange.start.character;
|
||
}
|
||
|
||
function validateSnapshot(value) {
|
||
if (!value || value.schemaVersion !== SCHEMA_VERSION || !Number.isInteger(value.revision)
|
||
|| typeof value.complete !== 'boolean' || !Array.isArray(value.modules)
|
||
|| !Array.isArray(value.files) || !value.files.every((uri) => typeof uri === 'string')) {
|
||
throw new Error('The language server returned an unsupported hierarchy snapshot.');
|
||
}
|
||
const files = value.files;
|
||
const ids = new Set();
|
||
const modules = value.modules.map((module) => {
|
||
if (!module || typeof module.moduleName !== 'string' || module.moduleName === ''
|
||
|| !isWireLocation(module.definition, files) || !Array.isArray(module.instances)) {
|
||
throw new Error('The language server returned a malformed hierarchy module.');
|
||
}
|
||
const definition = toLocation(module.definition, files);
|
||
const id = idOf(definition);
|
||
if (ids.has(id)) throw new Error('The hierarchy snapshot contains a duplicate module id.');
|
||
ids.add(id);
|
||
const instances = module.instances.map((instance) => {
|
||
if (!instance || typeof instance.instanceName !== 'string' || instance.instanceName === ''
|
||
|| typeof instance.moduleName !== 'string' || instance.moduleName === ''
|
||
|| !isWireLocation(instance.site, files)) {
|
||
throw new Error('The language server returned a malformed hierarchy instance.');
|
||
}
|
||
const site = toLocation(instance.site, files);
|
||
return {
|
||
id: idOf(site),
|
||
instanceName: instance.instanceName,
|
||
moduleName: instance.moduleName,
|
||
site,
|
||
definitions: [],
|
||
};
|
||
});
|
||
instances.sort(compareInstances);
|
||
return { id, moduleName: module.moduleName, definition, instances };
|
||
});
|
||
modules.sort(compareModules);
|
||
|
||
// What the server used to repeat on every instance: the declarations its
|
||
// module name resolves to. Every one of them is a module in this same
|
||
// snapshot, so the lookup is exact rather than an approximation of it — and
|
||
// the answer is deterministic because `modules` is already sorted.
|
||
const byName = new Map();
|
||
for (const module of modules) {
|
||
const found = byName.get(module.moduleName) || [];
|
||
found.push(module.definition);
|
||
byName.set(module.moduleName, found);
|
||
}
|
||
for (const module of modules) {
|
||
for (const instance of module.instances) {
|
||
instance.definitions = (byName.get(instance.moduleName) || []).slice();
|
||
}
|
||
}
|
||
return { schemaVersion: SCHEMA_VERSION, revision: value.revision, complete: value.complete, modules };
|
||
}
|
||
|
||
function buildHierarchy(raw) {
|
||
const snapshot = validateSnapshot(raw);
|
||
const byId = new Map(snapshot.modules.map((module) => [module.id, module]));
|
||
const moduleAt = new Map(snapshot.modules.map((module) => [
|
||
locationKey(module.definition), module,
|
||
]));
|
||
|
||
// An instance resolves to a module exactly when its type names one
|
||
// declaration. Resolved once here, not once per render.
|
||
for (const module of snapshot.modules) {
|
||
for (const instance of module.instances) {
|
||
const target = instance.definitions.length === 1
|
||
? moduleAt.get(locationKey(instance.definitions[0]))
|
||
: undefined;
|
||
instance.targetId = target ? target.id : undefined;
|
||
instance.unresolved = instance.definitions.length === 0;
|
||
instance.ambiguous = instance.definitions.length > 1;
|
||
}
|
||
}
|
||
|
||
const parented = new Set();
|
||
for (const module of snapshot.modules) {
|
||
for (const instance of module.instances) {
|
||
if (instance.targetId) parented.add(instance.targetId);
|
||
}
|
||
}
|
||
|
||
// Reachability over the *module* graph, not over the expanded tree: the
|
||
// question "is this module already shown somewhere" needs one visit per
|
||
// module, and the expanded tree has no bound.
|
||
const reached = new Set();
|
||
function reach(start) {
|
||
const stack = [start];
|
||
while (stack.length > 0) {
|
||
const module = stack.pop();
|
||
if (reached.has(module.id)) continue;
|
||
reached.add(module.id);
|
||
for (const instance of module.instances) {
|
||
const target = instance.targetId && byId.get(instance.targetId);
|
||
if (target) stack.push(target);
|
||
}
|
||
}
|
||
}
|
||
|
||
const roots = [];
|
||
for (const module of snapshot.modules) {
|
||
if (parented.has(module.id)) continue;
|
||
roots.push({ module, fallback: false });
|
||
reach(module);
|
||
}
|
||
// Whatever a root never reaches is inside a recursive component: show it,
|
||
// marked, so `A -> B -> A` is visible without an infinite tree.
|
||
for (const module of snapshot.modules) {
|
||
if (reached.has(module.id)) continue;
|
||
roots.push({ module, fallback: true });
|
||
reach(module);
|
||
}
|
||
|
||
const entries = searchIndex(snapshot.modules);
|
||
return {
|
||
revision: snapshot.revision,
|
||
complete: snapshot.complete,
|
||
modules: snapshot.modules,
|
||
byId,
|
||
roots,
|
||
entries,
|
||
// Reused per query rather than allocated per keystroke.
|
||
scores: new Int32Array(entries.length),
|
||
counts: new Int32Array(MAX_SCORE + 1),
|
||
};
|
||
}
|
||
|
||
/// One flat, prelowered row per module and per instance — built once per
|
||
/// snapshot, scanned once per query. Nothing here is per-path: an instance
|
||
/// appears once however many times the tree would show it.
|
||
function searchIndex(modules) {
|
||
const entries = [];
|
||
for (const module of modules) {
|
||
const lowerModule = module.moduleName.toLowerCase();
|
||
const [moduleLetters, moduleDigits] = maskOf(lowerModule);
|
||
entries.push({
|
||
kind: 'module',
|
||
module,
|
||
instance: undefined,
|
||
lowerModule,
|
||
lowerInstance: '',
|
||
moduleLetters,
|
||
moduleDigits,
|
||
instanceLetters: 0,
|
||
instanceDigits: 0,
|
||
});
|
||
for (const instance of module.instances) {
|
||
const type = instance.moduleName.toLowerCase();
|
||
const name = instance.instanceName.toLowerCase();
|
||
const [typeLetters, typeDigits] = maskOf(type);
|
||
const [nameLetters, nameDigits] = maskOf(name);
|
||
entries.push({
|
||
kind: 'instance',
|
||
module,
|
||
instance,
|
||
lowerModule: type,
|
||
lowerInstance: name,
|
||
moduleLetters: typeLetters,
|
||
moduleDigits: typeDigits,
|
||
instanceLetters: nameLetters,
|
||
instanceDigits: nameDigits,
|
||
});
|
||
}
|
||
}
|
||
return entries;
|
||
}
|
||
|
||
// A deterministic subsequence score. Higher wins; -1 is no match. The first
|
||
// tier keeps the ordering intuitive, the bonuses make `u_f` prefer `u_fifo`
|
||
// over a scattered set of the same letters. Both sides are already lowercase,
|
||
// and `needle` arrives split into characters: lowercasing and re-splitting per
|
||
// call is what made one keystroke allocate once per name in the workspace.
|
||
function scoreLower(haystack, needle, chars) {
|
||
if (needle === '') return 0;
|
||
if (haystack === needle) return 10000;
|
||
if (haystack.startsWith(needle)) return 8000 - (haystack.length - needle.length);
|
||
const at = haystack.indexOf(needle);
|
||
if (at >= 0) return 6000 - at * 10 - (haystack.length - needle.length);
|
||
|
||
let cursor = 0;
|
||
let score = 0;
|
||
let previous = -2;
|
||
for (let k = 0; k < chars.length; k += 1) {
|
||
const found = haystack.indexOf(chars[k], cursor);
|
||
if (found < 0) return -1;
|
||
score += 10;
|
||
if (found === previous + 1) score += 18;
|
||
if (found === 0 || !isWordCharacter(haystack.charCodeAt(found - 1))) score += 12;
|
||
score -= found;
|
||
previous = found;
|
||
cursor = found + 1;
|
||
}
|
||
return score;
|
||
}
|
||
|
||
/// `a`–`z` or `0`–`9`, on an already-lowercased string. A character that is
|
||
/// neither opens a word, which is where the word-boundary bonus is paid.
|
||
function isWordCharacter(code) {
|
||
return (code >= 97 && code <= 122) || (code >= 48 && code <= 57);
|
||
}
|
||
|
||
/// Which characters a name contains, as two bit sets: letters, `_` and
|
||
/// "something else" in the first, digits in the second. A subsequence match
|
||
/// needs every one of the query's characters to be present, so a name whose
|
||
/// bits do not cover the query's cannot match and is never scored — which is
|
||
/// what keeps a query that matches almost nothing as cheap as one that matches
|
||
/// almost everything.
|
||
function maskOf(lower) {
|
||
let letters = 0;
|
||
let digits = 0;
|
||
for (let at = 0; at < lower.length; at += 1) {
|
||
const code = lower.charCodeAt(at);
|
||
if (code >= 97 && code <= 122) letters |= 1 << (code - 97);
|
||
else if (code >= 48 && code <= 57) digits |= 1 << (code - 48);
|
||
else if (code === 95) letters |= 1 << 26;
|
||
else letters |= 1 << 27;
|
||
}
|
||
return [letters, digits];
|
||
}
|
||
|
||
function fuzzyScore(text, query) {
|
||
const needle = query.trim().toLowerCase();
|
||
return scoreLower(text.toLowerCase(), needle, [...needle]);
|
||
}
|
||
|
||
/// The highest score `scoreLower` can return, plus the instance-name tie-break
|
||
/// point. Scores are small non-negative integers, which is what lets the top of
|
||
/// a very large result set be found by counting rather than by sorting.
|
||
const MAX_SCORE = 10001;
|
||
|
||
/// Every entry the query matches, best first, capped at `limit`.
|
||
///
|
||
/// **No sort over the whole result set.** A one-letter query matches nearly
|
||
/// every name in the workspace, and sorting 100 000 hits to show 200 of them is
|
||
/// most of a frame on its own. Scores are bounded integers, so the cutoff is
|
||
/// found by counting hits per score and walking down from the top — one extra
|
||
/// pass over an array, and only the rows actually shown are ever built. Ties
|
||
/// are broken by index order, which is modules alphabetically and then
|
||
/// instances alphabetically, so the answer is deterministic without comparing
|
||
/// any strings.
|
||
function searchHierarchy(model, query, limit = SEARCH_LIMIT) {
|
||
const needle = query.trim().toLowerCase();
|
||
if (needle === '') return { rows: [], total: 0, truncated: 0 };
|
||
const entries = model.entries;
|
||
const scores = model.scores;
|
||
const counts = model.counts;
|
||
counts.fill(0);
|
||
|
||
const chars = [...needle];
|
||
const [wantLetters, wantDigits] = maskOf(needle);
|
||
let total = 0;
|
||
for (let at = 0; at < entries.length; at += 1) {
|
||
const entry = entries[at];
|
||
let score = -1;
|
||
if ((entry.moduleLetters & wantLetters) === wantLetters
|
||
&& (entry.moduleDigits & wantDigits) === wantDigits) {
|
||
score = scoreLower(entry.lowerModule, needle, chars);
|
||
}
|
||
if (entry.kind === 'instance'
|
||
&& (entry.instanceLetters & wantLetters) === wantLetters
|
||
&& (entry.instanceDigits & wantDigits) === wantDigits) {
|
||
const own = scoreLower(entry.lowerInstance, needle, chars);
|
||
// An instance-name tie wins by one, as the UI contract specifies.
|
||
if (own >= 0 && own + 1 > score) score = own + 1;
|
||
}
|
||
if (score > MAX_SCORE) score = MAX_SCORE;
|
||
scores[at] = score;
|
||
if (score >= 0) {
|
||
counts[score] += 1;
|
||
total += 1;
|
||
}
|
||
}
|
||
|
||
// The lowest score that still fits inside `limit`, and how many rows of
|
||
// exactly that score may be taken.
|
||
let cutoff = 0;
|
||
let above = 0;
|
||
for (let score = MAX_SCORE; score >= 0; score -= 1) {
|
||
if (above + counts[score] >= limit || score === 0) {
|
||
cutoff = score;
|
||
break;
|
||
}
|
||
above += counts[score];
|
||
}
|
||
let roomAtCutoff = Math.max(0, limit - above);
|
||
|
||
const taken = [];
|
||
for (let at = 0; at < entries.length && taken.length < limit; at += 1) {
|
||
const score = scores[at];
|
||
if (score < cutoff) continue;
|
||
if (score === cutoff) {
|
||
if (roomAtCutoff === 0) continue;
|
||
roomAtCutoff -= 1;
|
||
}
|
||
taken.push({ at, score });
|
||
}
|
||
taken.sort((a, b) => b.score - a.score || a.at - b.at);
|
||
const rows = taken.map(({ at }) => searchRow(entries[at]));
|
||
return { rows, total, truncated: Math.max(0, total - rows.length) };
|
||
}
|
||
|
||
function searchLabel(entry) {
|
||
return entry.kind === 'module'
|
||
? entry.module.moduleName
|
||
: `${entry.instance.instanceName} (${entry.instance.moduleName})`;
|
||
}
|
||
|
||
function searchId(entry) {
|
||
return entry.kind === 'module'
|
||
? `find:${entry.module.id}`
|
||
: `find:${entry.module.id}>${entry.instance.id}`;
|
||
}
|
||
|
||
function searchRow(entry) {
|
||
return {
|
||
id: searchId(entry),
|
||
kind: entry.kind,
|
||
label: searchLabel(entry),
|
||
moduleName: entry.kind === 'module' ? entry.module.moduleName : entry.instance.moduleName,
|
||
// Where the row lives, since a flat hit has no one path to show.
|
||
detail: entry.kind === 'module' ? 'module' : `in ${entry.module.moduleName}`,
|
||
depth: 0,
|
||
hasChildren: false,
|
||
expanded: false,
|
||
warning: entry.kind === 'instance' && (entry.instance.unresolved || entry.instance.ambiguous),
|
||
};
|
||
}
|
||
|
||
/// What a search row points at, for navigation and the context menu.
|
||
function searchTarget(model, id) {
|
||
if (typeof id !== 'string' || !id.startsWith('find:')) return undefined;
|
||
const [moduleId, instanceId] = id.slice('find:'.length).split('>');
|
||
const module = model.byId.get(moduleId);
|
||
if (!module) return undefined;
|
||
if (instanceId === undefined) {
|
||
return {
|
||
kind: 'module',
|
||
moduleName: module.moduleName,
|
||
definition: module.definition,
|
||
definitions: [module.definition],
|
||
site: undefined,
|
||
};
|
||
}
|
||
const instance = module.instances.find((candidate) => candidate.id === instanceId);
|
||
if (!instance) return undefined;
|
||
const target = instance.targetId && model.byId.get(instance.targetId);
|
||
return {
|
||
kind: 'instance',
|
||
moduleName: instance.moduleName,
|
||
instanceName: instance.instanceName,
|
||
definition: target && target.definition,
|
||
definitions: instance.definitions,
|
||
site: instance.site,
|
||
};
|
||
}
|
||
|
||
/// The rows the tree shows: every root, then the children of every row the
|
||
/// user has opened. Nothing below a closed row is built at all.
|
||
function treeRows(model, 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,
|
||
// The module the row is about — for an instance, its type. What the DUT
|
||
// sections decide a row's context menu from.
|
||
moduleName: node.moduleName,
|
||
depth: node.depth,
|
||
hasChildren: node.hasChildren,
|
||
expanded: expanded.has(node.id),
|
||
warning: node.warning,
|
||
bookmarked: node.id === bookmarkId,
|
||
});
|
||
if (!expanded.has(node.id) || !node.hasChildren) return;
|
||
for (const child of childrenOf(model, node)) push(child);
|
||
}
|
||
|
||
for (const { module, fallback } of model.roots) push(rootNode(model, module, fallback));
|
||
return { rows, nodes, bookmarkId };
|
||
}
|
||
|
||
function rootNode(model, module, fallback) {
|
||
return {
|
||
id: `root:${module.id}`,
|
||
kind: 'module',
|
||
moduleName: module.moduleName,
|
||
label: module.moduleName,
|
||
detail: fallback ? 'recursive' : '',
|
||
depth: 0,
|
||
parentId: null,
|
||
fullPath: module.moduleName,
|
||
hasChildren: module.instances.length > 0,
|
||
warning: fallback,
|
||
definition: module.definition,
|
||
definitions: [module.definition],
|
||
site: undefined,
|
||
moduleId: module.id,
|
||
seen: new Set([module.id]),
|
||
};
|
||
}
|
||
|
||
function childrenOf(model, node) {
|
||
const module = model.byId.get(node.moduleId);
|
||
if (!module) return [];
|
||
return module.instances.map((instance) => instanceNode(model, node, instance));
|
||
}
|
||
|
||
function instanceNode(model, parent, instance) {
|
||
const target = instance.targetId && model.byId.get(instance.targetId);
|
||
const recursive = Boolean(target && parent.seen.has(target.id));
|
||
const seen = new Set(parent.seen);
|
||
if (target) seen.add(target.id);
|
||
return {
|
||
id: `${parent.id}>${instance.id}`,
|
||
kind: 'instance',
|
||
moduleName: instance.moduleName,
|
||
instanceName: instance.instanceName,
|
||
label: `${instance.instanceName} (${instance.moduleName})`,
|
||
detail: instance.unresolved ? 'unresolved'
|
||
: (instance.ambiguous ? 'ambiguous' : (recursive ? 'recursive' : '')),
|
||
depth: parent.depth + 1,
|
||
parentId: parent.id,
|
||
fullPath: `${parent.fullPath}.${instance.instanceName}`,
|
||
hasChildren: Boolean(target) && !recursive && target.instances.length > 0,
|
||
warning: instance.unresolved || instance.ambiguous || recursive,
|
||
definition: target && target.definition,
|
||
definitions: instance.definitions,
|
||
site: instance.site,
|
||
moduleId: target && !recursive ? target.id : undefined,
|
||
seen,
|
||
};
|
||
}
|
||
|
||
/// The chain of row ids leading to a full path such as `TB.dut.inst1`, or
|
||
/// `undefined` when the path no longer exists or no longer names one row.
|
||
///
|
||
/// Walked from the roots rather than looked up in a table of every path,
|
||
/// because that table is the thing this file stopped building.
|
||
///
|
||
/// A DUT section's rows carry a path relative to the DUT (`aes.u_ctrl`), whose
|
||
/// head is a module no root walk can reach, so a head that names no root is
|
||
/// retried over every module. The roots-first order keeps every path that
|
||
/// resolved before resolving to exactly the same chain.
|
||
function bookmarkChain(model, path) {
|
||
if (typeof path !== 'string' || path === '') return undefined;
|
||
const [head, ...rest] = path.split('.');
|
||
const fromRoots = uniqueChain(model, model.roots.map(({ module }) => module), head, rest);
|
||
if (fromRoots) return fromRoots;
|
||
return uniqueChain(model, model.modules, head, rest);
|
||
}
|
||
|
||
function uniqueChain(model, modules, head, rest) {
|
||
let found;
|
||
for (const module of modules) {
|
||
if (module.moduleName !== head) continue;
|
||
const chain = descend(model, rootNode(model, module, false), rest);
|
||
if (!chain) continue;
|
||
if (found) return undefined; // the path names more than one row
|
||
found = chain;
|
||
}
|
||
return found;
|
||
}
|
||
|
||
function descend(model, node, names) {
|
||
const chain = [node.id];
|
||
let current = node;
|
||
for (const name of names) {
|
||
const matches = childrenOf(model, current).filter((child) => child.instanceName === name);
|
||
if (matches.length !== 1) return undefined;
|
||
[current] = matches;
|
||
chain.push(current.id);
|
||
}
|
||
return chain;
|
||
}
|
||
|
||
function idForPath(model, path) {
|
||
const chain = bookmarkChain(model, path);
|
||
return chain && chain[chain.length - 1];
|
||
}
|
||
|
||
module.exports = {
|
||
SEARCH_LIMIT,
|
||
bookmarkChain,
|
||
buildHierarchy,
|
||
childrenOf,
|
||
fuzzyScore,
|
||
idForPath,
|
||
locationKey,
|
||
rootNode,
|
||
searchHierarchy,
|
||
searchTarget,
|
||
treeRows,
|
||
validateSnapshot,
|
||
};
|