From 89ab83467e9c82e19163ce1f3b025809a2e9af29 Mon Sep 17 00:00:00 2001 From: Arthurvroum Date: Wed, 25 Nov 2026 03:43:14 +0100 Subject: [PATCH] fix: keep same-named functions of different files apart in the stack view Merging the stack reports of a workspace indexed functions by name: two files each defining a static helper became one row, mixing the location of one with the stack size of the other. The CodeLens and the sidebar lookups used the name too. - A function is identified by its name and the file defining it. Names defined in a single file keep their name as id; the others get name@file. Functions without a known file are still merged by name. - Calls are resolved within the file that made them, then to the only definition of that name elsewhere; an ambiguous name is not linked. - The CodeLens shows and focuses the definition of its own file, and the sidebar shows the file next to names that several functions share. Fixes #42 --- media/main.js | 8 ++-- media/stackTree.js | 39 ++++++++++++---- src/codelens/CtraceCodeLensProvider.ts | 4 +- src/ctrace/StackManager.ts | 28 +++++++++--- src/ctrace/StackParser.ts | 61 +++++++++++++++++++------- src/extension.ts | 3 +- src/test/stackManager.test.ts | 26 +++++++++++ src/test/stackParser.test.ts | 36 +++++++++++++++ src/test/stackTree.test.ts | 18 ++++++++ src/types/stack.ts | 6 +++ 10 files changed, 194 insertions(+), 35 deletions(-) create mode 100644 src/test/stackManager.test.ts diff --git a/media/main.js b/media/main.js index 1ca549a..410cb58 100755 --- a/media/main.js +++ b/media/main.js @@ -701,7 +701,7 @@ case 'focus-stack-tab': switchResultTab('stack'); if (msg.functionName && stackModel) { - const id = stackTreeLib.resolveName(stackModel, msg.functionName); + const id = stackTreeLib.resolveName(stackModel, msg.functionName, msg.file); if (id) { revealStackFunction(id); } } break; @@ -1008,7 +1008,7 @@ const name = document.createElement('span'); name.className = 'stack-row-name'; - appendHighlighted(name, node.name, query); + appendHighlighted(name, stackTreeLib.displayName(stackModel, row.id), query); const badges = document.createElement('span'); badges.className = 'stack-row-badges'; @@ -1218,8 +1218,8 @@ const link = document.createElement('button'); link.type = 'button'; link.className = 'stack-link'; - link.textContent = id; - link.title = `Show ${id} in the tree`; + link.textContent = stackTreeLib.displayName(stackModel, id); + link.title = `Show ${link.textContent} in the tree`; link.addEventListener('click', () => revealStackFunction(id)); row.appendChild(link); }); diff --git a/media/stackTree.js b/media/stackTree.js index 367dd59..4effdea 100644 --- a/media/stackTree.js +++ b/media/stackTree.js @@ -29,7 +29,9 @@ const nodes = new Map(); for (const node of report?.callGraph?.nodes ?? []) { nodes.set(node.id, { ...node }); } for (const fn of report?.functions ?? []) { - nodes.set(fn.name, { ...(nodes.get(fn.name) ?? {}), ...fn, id: fn.name, name: fn.name }); + // A merged report gives same-named functions of different files their own id. + const id = fn.id ?? fn.name; + nodes.set(id, { ...(nodes.get(id) ?? {}), ...fn, id, name: fn.name }); } const children = new Map(); @@ -76,7 +78,11 @@ const standalone = [...nodes.keys()].filter(id => !linked.has(id)).sort(compare); const peak = Math.max(1, report?.peakStack || 0, ...[...nodes.values()].map(node => node.maxStack || 0)); - const model = { nodes, children, parents, roots, standalone, peak, callCount, hotKeys: new Set(), hotPath: [] }; + const nameCounts = new Map(); + nodes.forEach(node => nameCounts.set(node.name, (nameCounts.get(node.name) ?? 0) + 1)); + // Names shared by several functions: the UI adds their file to tell them apart. + const duplicateNames = new Set([...nameCounts].filter(([, count]) => count > 1).map(([name]) => name)); + const model = { nodes, children, parents, roots, standalone, peak, callCount, duplicateNames, hotKeys: new Set(), hotPath: [] }; model.hotPath = computeHotPath(model); // Prefixes of the path are hot too: they are the rows leading to it. model.hotPath.forEach((_, index) => model.hotKeys.add(keyOf(topLevelPrefix(model, model.hotPath[0]), model.hotPath.slice(0, index + 1)))); @@ -256,13 +262,30 @@ return null; } - /** CodeLens passes unqualified names: `run` must find `Worker::run`. */ - function resolveName(model, name) { + /** + * CodeLens passes unqualified names: `run` must find `Worker::run`. With + * `file`, the definition in that file wins over same-named ones elsewhere. + */ + function resolveName(model, name, file) { if (!name) { return null; } - if (model.nodes.has(name)) { return name; } const suffix = `::${name}`; - const match = [...model.nodes.keys()].filter(id => id.endsWith(suffix)).sort(byPeakThenName(model.nodes)); - return match[0] ?? null; + const all = [...model.nodes.values()]; + const exact = all.filter(node => node.name === name); + const candidates = (exact.length > 0 ? exact : all.filter(node => node.name.endsWith(suffix))) + .sort((a, b) => byPeakThenName(model.nodes)(a.id, b.id)); + if (file) { + const inFile = candidates.find(node => node.file === file); + if (inFile) { return inFile.id; } + } + return candidates[0]?.id ?? null; + } + + /** Name to show for a function: with its file when another function shares the name. */ + function displayName(model, id) { + const node = model.nodes.get(id); + if (!node) { return id; } + if (!model.duplicateNames.has(node.name) || !node.file) { return node.name; } + return `${node.name} · ${String(node.file).split(/[\\/]/).pop()}`; } /** Key of the row a nested row hangs from, or null at the top level. */ @@ -271,5 +294,5 @@ return index < 0 ? null : key.slice(0, index); } - return { STANDALONE_KEY, createModel, defaultExpanded, allExpanded, flattenTree, rankedRows, pathTo, resolveName, parentKey }; + return { STANDALONE_KEY, createModel, defaultExpanded, allExpanded, flattenTree, rankedRows, pathTo, resolveName, displayName, parentKey }; })); diff --git a/src/codelens/CtraceCodeLensProvider.ts b/src/codelens/CtraceCodeLensProvider.ts index b8096ba..4114a39 100755 --- a/src/codelens/CtraceCodeLensProvider.ts +++ b/src/codelens/CtraceCodeLensProvider.ts @@ -55,7 +55,7 @@ function collectFunctionLenses( )); // 2. Stack Footprint & Recursion Action - const stackInfo = StackManager.instance.getFunction(cleanName); + const stackInfo = StackManager.instance.getFunction(cleanName, documentUri.fsPath); if (stackInfo) { const recursionText = (stackInfo.isRecursive || stackInfo.hasInfiniteSelfRecursion) ? '⚠️ Recursion: Cycle detected' @@ -68,7 +68,7 @@ function collectFunctionLenses( { title: footprintTitle, command: 'ctrace.focusStackFunction', - arguments: [cleanName], + arguments: [cleanName, documentUri.fsPath], tooltip: `Peak stack usage: ${stackInfo.maxStack} bytes. Click to view in Stack Visualizer.`, } )); diff --git a/src/ctrace/StackManager.ts b/src/ctrace/StackManager.ts index 876fc26..da30f61 100644 --- a/src/ctrace/StackManager.ts +++ b/src/ctrace/StackManager.ts @@ -4,7 +4,8 @@ import type { StackFunction, StackReport } from '../types/stack'; export class StackManager { private static _instance: StackManager; private _latestReport: StackReport | null = null; - private _functionMap = new Map(); + // name → every definition with that name: two files can each define one. + private _functionMap = new Map(); private _onDidUpdateStackData = new vscode.EventEmitter(); public readonly onDidUpdateStackData = this._onDidUpdateStackData.event; @@ -20,20 +21,37 @@ export class StackManager { this._latestReport = report; this._functionMap.clear(); + const index = (name: string, fn: StackFunction) => { + const list = this._functionMap.get(name) ?? []; + list.push(fn); + this._functionMap.set(name, list); + }; for (const fn of report.functions) { - this._functionMap.set(fn.name, fn); + index(fn.name, fn); // Also store without namespace or qualifiers if any const simpleName = fn.name.split('::').pop() ?? fn.name; if (simpleName !== fn.name) { - this._functionMap.set(simpleName, fn); + index(simpleName, fn); } } this._onDidUpdateStackData.fire(); } - public getFunction(name: string): StackFunction | undefined { - return this._functionMap.get(name); + /** + * The definition of `name` in `file`. Without a match in that file, only + * a definition whose file is unknown is returned: another file's function + * of the same name is a different function. + */ + public getFunction(name: string, file?: string): StackFunction | undefined { + const candidates = this._functionMap.get(name) ?? []; + if (file) { + const inFile = candidates.find(fn => fn.file === file); + if (inFile) { return inFile; } + const unknownFile = candidates.filter(fn => !fn.file); + return unknownFile.length === 1 ? unknownFile[0] : undefined; + } + return candidates.length === 1 ? candidates[0] : undefined; } public getLatestReport(): StackReport | null { diff --git a/src/ctrace/StackParser.ts b/src/ctrace/StackParser.ts index cbfafb3..2e460ac 100644 --- a/src/ctrace/StackParser.ts +++ b/src/ctrace/StackParser.ts @@ -152,11 +152,13 @@ function buildCallGraph( functions: StackFunction[], sourceCode?: string ): { nodes: CallGraphNode[]; edges: CallGraphEdge[]; chains: CallChainStep[][] } { + // Callees are ids: names in a single-file report, see StackFunction.id. + const idOf = (f: StackFunction) => f.id ?? f.name; const fnMap = new Map(); - functions.forEach(f => fnMap.set(f.name, f)); + functions.forEach(f => fnMap.set(idOf(f), f)); const nodes: CallGraphNode[] = functions.map(f => ({ - id: f.name, + id: idOf(f), name: f.name, file: f.file, line: f.line, @@ -192,7 +194,7 @@ function buildCallGraph( // Prefer call relationships supplied by the analyzer when available. for (const fn of functions) { for (const callee of fn.callees ?? []) { - if (fnMap.has(callee)) { addEdge(fn.name, callee, fn.name === callee); } + if (fnMap.has(callee)) { addEdge(idOf(fn), callee, idOf(fn) === callee); } } } @@ -236,7 +238,7 @@ function buildCallGraph( const isCycle = visited.has(fnName); currentPath.push({ - name: fnName, + name: fn?.name ?? fnName, localStack: local, cumulativeStack: newCumulative, isRecursive: fn?.isRecursive || isCycle, @@ -263,7 +265,7 @@ function buildCallGraph( currentPath.pop(); } - traverse(root.name, 0); + traverse(idOf(root), 0); } // If no chains were formed (e.g. disjoint functions), make a 1-step chain per function @@ -306,7 +308,13 @@ export function mergeStackReports(reports: StackReport[]): StackReport | null { if (!reports || reports.length === 0) { return null; } if (reports.length === 1) { return reports[0]; } - const functionMap = new Map(); + // A function is identified by its name and the file defining it: two + // translation units can each have their own `static int helper()`. + // Functions without a known file (e.g. inline ones from a header) are + // merged by name, as the same definition seen from several files. + const identityOf = (fn: StackFunction) => fn.file ? `${fn.name}\u0000${fn.file}` : fn.name; + const merged = new Map(); + const identitiesByName = new Map>(); let peakStack = 0; let recursiveCount = 0; let stackLimit = 8388608; @@ -322,9 +330,12 @@ export function mergeStackReports(reports: StackReport[]): StackReport | null { recursiveCount += report.recursiveCount || 0; for (const fn of report.functions || []) { - const existing = functionMap.get(fn.name); + const identity = identityOf(fn); + if (!identitiesByName.has(fn.name)) { identitiesByName.set(fn.name, new Set()); } + identitiesByName.get(fn.name)!.add(identity); + const existing = merged.get(identity); if (!existing) { - functionMap.set(fn.name, { ...fn }); + merged.set(identity, { ...fn, callees: [], callers: [] }); } else { existing.localStack = Math.max(existing.localStack, fn.localStack); existing.maxStack = Math.max(existing.maxStack, fn.maxStack); @@ -334,17 +345,37 @@ export function mergeStackReports(reports: StackReport[]): StackReport | null { existing.exceedsLimit = existing.exceedsLimit || fn.exceedsLimit; if (!existing.file && fn.file) { existing.file = fn.file; } if (!existing.line && fn.line) { existing.line = fn.line; } - if (fn.callees?.length) { - existing.callees = Array.from(new Set([...(existing.callees || []), ...fn.callees])); - } - if (fn.callers?.length) { - existing.callers = Array.from(new Set([...(existing.callers || []), ...fn.callers])); - } } } } - const functions = Array.from(functionMap.values()); + // Ids stay plain names unless a name has several definitions. + for (const fn of merged.values()) { + fn.id = identitiesByName.get(fn.name)!.size > 1 && fn.file ? `${fn.name}@${fn.file}` : fn.name; + } + + // Calls are resolved within the report that saw them: a call to `helper` + // from a.c goes to a.c's helper. A name defined elsewhere only once is an + // external function; a name defined in several other files is ambiguous + // and left unlinked rather than guessed. + for (const report of reports) { + if (!report) { continue; } + const local = new Map((report.functions || []).map(fn => [fn.name, merged.get(identityOf(fn))!])); + for (const fn of report.functions || []) { + const caller = merged.get(identityOf(fn))!; + for (const calleeName of fn.callees ?? []) { + const callee = local.get(calleeName) ?? uniqueByName(calleeName); + if (callee && !caller.callees!.includes(callee.id!)) { caller.callees!.push(callee.id!); } + } + } + } + + function uniqueByName(name: string): StackFunction | undefined { + const identities = identitiesByName.get(name); + return identities && identities.size === 1 ? merged.get([...identities][0]) : undefined; + } + + const functions = Array.from(merged.values()); if (functions.length === 0) { return null; } const { nodes, edges, chains } = buildCallGraph(functions); diff --git a/src/extension.ts b/src/extension.ts index a498c0d..bb45f10 100755 --- a/src/extension.ts +++ b/src/extension.ts @@ -762,11 +762,12 @@ export function activate(context: vscode.ExtensionContext) { ); context.subscriptions.push( - vscode.commands.registerCommand('ctrace.focusStackFunction', async (functionName?: string) => { + vscode.commands.registerCommand('ctrace.focusStackFunction', async (functionName?: string, file?: string) => { await vscode.commands.executeCommand('workbench.view.extension.ctrace-sidebar-view'); sidebarProvider.postMessage({ type: 'focus-stack-tab', functionName, + file: typeof file === 'string' ? file : undefined, }); }) ); diff --git a/src/test/stackManager.test.ts b/src/test/stackManager.test.ts new file mode 100644 index 0000000..0863fb5 --- /dev/null +++ b/src/test/stackManager.test.ts @@ -0,0 +1,26 @@ +import * as assert from 'assert'; +import { StackManager } from '../ctrace/StackManager'; + +suite('StackManager Test Suite', () => { + teardown(() => StackManager.instance.clear()); + + const fn = (name: string, file: string | undefined, maxStack: number) => + ({ name, file, localStack: maxStack, maxStack, isRecursive: false }); + + test('CodeLens gets the definition of the file it is shown in', () => { + StackManager.instance.updateStackData({ + peakStack: 32, recursiveCount: 0, + functions: [fn('helper', '/w/a.c', 16), fn('helper', '/w/b.c', 32)], + }); + assert.strictEqual(StackManager.instance.getFunction('helper', '/w/a.c')?.maxStack, 16); + assert.strictEqual(StackManager.instance.getFunction('helper', '/w/b.c')?.maxStack, 32); + // c.c has no helper of its own: another file's is not shown there. + assert.strictEqual(StackManager.instance.getFunction('helper', '/w/c.c'), undefined); + }); + + test('a definition whose file is unknown is still found', () => { + StackManager.instance.updateStackData({ peakStack: 8, recursiveCount: 0, functions: [fn('inline_fn', undefined, 8)] }); + assert.strictEqual(StackManager.instance.getFunction('inline_fn', '/w/a.h')?.maxStack, 8); + assert.strictEqual(StackManager.instance.getFunction('inline_fn')?.maxStack, 8); + }); +}); diff --git a/src/test/stackParser.test.ts b/src/test/stackParser.test.ts index 6b87c67..2d1a95d 100644 --- a/src/test/stackParser.test.ts +++ b/src/test/stackParser.test.ts @@ -2,6 +2,42 @@ import * as assert from 'assert'; import { parseStackReport, mergeStackReports } from '../ctrace/StackParser'; suite('StackParser Test Suite', () => { + test('same-named functions of two files stay distinct after merging', () => { + const report = (fns: [string, number][]) => fns + .map(([name, peak]) => `Function: ${name} \n\tlocal stack: ${peak} bytes\n\tmax stack (including callees): ${peak} bytes\n`) + .join('\n'); + // Each file has its own static helper, called by a function of that file. + const aSource = 'static int helper(int n) { return n; }\nint main(void) { return helper(1); }\n'; + const bSource = 'static int helper(int n) { return n * 2; }\nint run(void) { return helper(2); }\n'; + const a = parseStackReport(report([['helper', 16], ['main', 48]]), aSource, '/w/a.c')!; + const b = parseStackReport(report([['helper', 32], ['run', 64]]), bSource, '/w/b.c')!; + + const merged = mergeStackReports([a, b])!; + const helpers = merged.functions.filter(fn => fn.name === 'helper'); + assert.strictEqual(helpers.length, 2, 'one row per definition'); + const inA = helpers.find(fn => fn.file === '/w/a.c')!; + const inB = helpers.find(fn => fn.file === '/w/b.c')!; + assert.strictEqual(inA.maxStack, 16); + assert.strictEqual(inB.maxStack, 32); + assert.strictEqual(inA.line, 1); + assert.strictEqual(inB.line, 1); + assert.notStrictEqual(inA.id, inB.id); + + // Each call reaches the helper of its own file. + const edges = merged.callGraph!.edges.map(edge => `${edge.from} -> ${edge.to}`).sort(); + assert.deepStrictEqual(edges, [`main -> ${inA.id}`, `run -> ${inB.id}`].sort()); + assert.deepStrictEqual(inA.callers, ['main']); + assert.deepStrictEqual(inB.callers, ['run']); + // Names defined once keep their name as id. + assert.ok(merged.functions.some(fn => fn.id === 'main')); + }); + + test('a function seen by several files without a known file is merged by name', () => { + const report = 'Function: inline_header_fn \n\tlocal stack: 8 bytes\n\tmax stack (including callees): 8 bytes\n'; + const merged = mergeStackReports([parseStackReport(report)!, parseStackReport(report)!])!; + assert.strictEqual(merged.functions.filter(fn => fn.name === 'inline_header_fn').length, 1); + }); + test('functions defined in the analysed file get its path, so the Stack Tree can jump to them', () => { const report = [ 'Function: helper ', '\tlocal stack: 16 bytes', '\tmax stack (including callees): 16 bytes', '', diff --git a/src/test/stackTree.test.ts b/src/test/stackTree.test.ts index 7ce4f6a..ca2553b 100644 --- a/src/test/stackTree.test.ts +++ b/src/test/stackTree.test.ts @@ -137,6 +137,24 @@ suite('Stack call tree Test Suite', () => { assert.strictEqual(lib.resolveName(model, 'missing'), null); }); + test('same-named functions of different files are told apart', () => { + const model = lib.createModel({ + peakStack: 64, + functions: [ + { id: 'helper@/w/a.c', name: 'helper', file: '/w/a.c', line: 1, localStack: 16, maxStack: 16, isRecursive: false }, + { id: 'helper@/w/b.c', name: 'helper', file: '/w/b.c', line: 1, localStack: 32, maxStack: 32, isRecursive: false }, + { id: 'main', name: 'main', file: '/w/a.c', localStack: 8, maxStack: 24, isRecursive: false }, + ], + callGraph: { nodes: [], chains: [], edges: [{ from: 'main', to: 'helper@/w/a.c' }] }, + }); + assert.strictEqual(model.nodes.size, 3); + assert.strictEqual(lib.resolveName(model, 'helper', '/w/a.c'), 'helper@/w/a.c'); + assert.strictEqual(lib.resolveName(model, 'helper', '/w/b.c'), 'helper@/w/b.c'); + assert.strictEqual(lib.displayName(model, 'helper@/w/b.c'), 'helper · b.c'); + assert.strictEqual(lib.displayName(model, 'main'), 'main'); + assert.deepStrictEqual(model.children.get('main'), ['helper@/w/a.c']); + }); + test('an empty report does not throw', () => { const model = lib.createModel({ functions: [], peakStack: 0 }); assert.deepStrictEqual(lib.flattenTree(model, {}).rows, []); diff --git a/src/types/stack.ts b/src/types/stack.ts index 5589517..bce2ce4 100644 --- a/src/types/stack.ts +++ b/src/types/stack.ts @@ -1,4 +1,10 @@ export interface StackFunction { + /** + * Unique key in a merged workspace report: the name, or `name@file` when + * several files define a function with that name (e.g. two static helpers). + * Absent in a single-file report, where the name is unique. + */ + id?: string; name: string; file?: string; line?: number;