Skip to content

Commit 8a1a6f9

Browse files
committed
chore(gates): restore lexical shadowing in the Vitest mock-site reader
A local that redeclares an imported Vitest alias is not the mock API; the shared isolation walk must not report a provider edge for it.
1 parent 1f23138 commit 8a1a6f9

5 files changed

Lines changed: 177 additions & 12 deletions

File tree

‎scripts/layering/layering-ast.ts‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,3 +134,116 @@ export function destructuredDynamicImportBindings(
134134
visit(program);
135135
return captures;
136136
}
137+
138+
function patternNames(pattern: unknown, into: string[]): void {
139+
const node = asNode(pattern);
140+
if (node === undefined) return;
141+
switch (node.type) {
142+
case 'Identifier':
143+
into.push(node.name as string);
144+
break;
145+
case 'ObjectPattern':
146+
for (const property of nodeList(node.properties)) {
147+
const entry = asNode(property);
148+
patternNames(entry?.type === 'Property' ? entry.value : entry, into);
149+
}
150+
break;
151+
case 'ArrayPattern':
152+
for (const element of nodeList(node.elements)) patternNames(element, into);
153+
break;
154+
case 'AssignmentPattern':
155+
patternNames(node.left, into);
156+
break;
157+
case 'RestElement':
158+
patternNames(node.argument, into);
159+
break;
160+
case 'TSParameterProperty':
161+
patternNames(node.parameter, into);
162+
break;
163+
}
164+
}
165+
166+
function lexicalNames(statements: unknown[], into: string[]): void {
167+
for (const statement of statements) {
168+
const node = asNode(statement);
169+
if (node?.type === 'VariableDeclaration' && node.kind !== 'var') {
170+
for (const declarator of nodeList(node.declarations)) {
171+
patternNames(asNode(declarator)?.id, into);
172+
}
173+
} else if (node?.type === 'FunctionDeclaration' || node?.type === 'ClassDeclaration') {
174+
patternNames(node.id, into);
175+
}
176+
}
177+
}
178+
179+
function isFunctionNode(node: AstNode): boolean {
180+
return (
181+
node.type === 'FunctionDeclaration' ||
182+
node.type === 'FunctionExpression' ||
183+
node.type === 'ArrowFunctionExpression'
184+
);
185+
}
186+
187+
function hoistedVarNames(node: unknown, into: string[]): void {
188+
for (const child of Array.isArray(node) ? node : [node]) {
189+
const record = asNode(child);
190+
if (record === undefined || isFunctionNode(record)) continue;
191+
if (record.type === 'VariableDeclaration' && record.kind === 'var') {
192+
for (const declarator of nodeList(record.declarations)) {
193+
patternNames(asNode(declarator)?.id, into);
194+
}
195+
}
196+
for (const value of Object.values(record)) hoistedVarNames(value, into);
197+
}
198+
}
199+
200+
/** Names `node` itself declares for its own subtree: parameters, `var`s, block-level lexical declarations. */
201+
function scopeBindings(node: AstNode): string[] {
202+
const names: string[] = [];
203+
if (isFunctionNode(node)) {
204+
for (const param of nodeList(node.params)) patternNames(param, names);
205+
if (node.type === 'FunctionExpression') patternNames(node.id, names);
206+
hoistedVarNames(node.body, names);
207+
} else if (
208+
node.type === 'BlockStatement' ||
209+
node.type === 'StaticBlock' ||
210+
node.type === 'TSModuleBlock'
211+
) {
212+
lexicalNames(nodeList(node.body), names);
213+
} else if (node.type === 'ClassExpression') {
214+
patternNames(node.id, names);
215+
} else if (node.type === 'SwitchStatement') {
216+
for (const switchCase of nodeList(node.cases)) {
217+
lexicalNames(nodeList(asNode(switchCase)?.consequent), names);
218+
}
219+
} else if (node.type === 'ForStatement') {
220+
lexicalNames([node.init], names);
221+
} else if (node.type === 'ForInStatement' || node.type === 'ForOfStatement') {
222+
lexicalNames([node.left], names);
223+
} else if (node.type === 'CatchClause') {
224+
patternNames(node.param, names);
225+
}
226+
return names;
227+
}
228+
229+
/**
230+
* `visitAst` that also hands the visitor the names declared by the enclosing scopes: function
231+
* parameters and `var`s, block-level `let`/`const`/`function`/`class`, loop heads and `catch`
232+
* parameters. A `with` statement or `eval` can rebind names invisibly and is not modelled.
233+
*/
234+
export function visitAstScoped(
235+
node: unknown,
236+
shadowed: ReadonlySet<string>,
237+
visitor: (node: AstNode, shadowed: ReadonlySet<string>) => void,
238+
): void {
239+
if (Array.isArray(node)) {
240+
for (const child of node) visitAstScoped(child, shadowed, visitor);
241+
return;
242+
}
243+
const record = asNode(node);
244+
if (record === undefined) return;
245+
const declared = scopeBindings(record);
246+
const scope = declared.length > 0 ? new Set([...shadowed, ...declared]) : shadowed;
247+
visitor(record, scope);
248+
for (const child of Object.values(record)) visitAstScoped(child, scope, visitor);
249+
}

‎scripts/layering/model-mock-bindings.test.ts‎

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,14 +83,32 @@ test('a vitest namespace member other than vi or vitest is not the mock API', ()
8383
);
8484
});
8585

86-
test('an alias a local redeclares still counts, so the walk only over-reports', () => {
86+
test('an alias is not a mock receiver where an enclosing scope redeclares its name', () => {
8787
assert.deepEqual(
8888
specs(
8989
"import { vi as mocks } from 'vitest';",
90+
"import * as testing from 'vitest';",
9091
"function parameter(mocks) { mocks.mock('a'); }",
91-
"mocks.mock('b');",
92+
"const arrow = (testing) => testing.vi.mock('b');",
93+
"{ const mocks = other; mocks.mock('c'); }",
94+
"function hoisted() { if (flag) { var mocks = other; } mocks.mock('d'); }",
95+
"try {} catch (mocks) { mocks.mock('e'); }",
96+
"for (const { mocks } of list) mocks.mock('f');",
97+
"switch (kind) { case 1: class testing {} testing.vi.mock('g'); }",
98+
"const expression = function mocks() { mocks.mock('h'); };",
99+
"const named = class mocks { run() { mocks.mock('i'); } };",
100+
"namespace Fixture { const testing = other; testing.vi.mock('j'); }",
92101
),
93-
['a', 'b'],
102+
[],
103+
);
104+
assert.deepEqual(
105+
specs(
106+
"import { vi as mocks } from 'vitest';",
107+
'function unrelated(mocks) { return mocks; }',
108+
'{ const mocks = other; }',
109+
"mocks.mock('outside');",
110+
),
111+
['outside'],
94112
);
95113
});
96114

‎scripts/layering/model.ts‎

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
nodeList,
1111
propertyName,
1212
visitAst,
13+
visitAstScoped,
1314
type AstNode,
1415
} from './layering-ast.ts';
1516
import { declaredRootModuleZone } from './root-module-zones.ts';
@@ -369,28 +370,40 @@ function vitestImportBindings(program: unknown): VitestBindings {
369370
return { apis, namespaces };
370371
}
371372

372-
/** The global names `vi` and `vitest`, and the local names a `vitest` import binds to them. */
373-
function isMockApiReceiver(node: unknown, bindings: VitestBindings): boolean {
373+
/**
374+
* The global names `vi` and `vitest` always count. An imported alias or namespace counts only
375+
* while no enclosing scope redeclares its local name.
376+
*/
377+
function isMockApiReceiver(
378+
node: unknown,
379+
bindings: VitestBindings,
380+
shadowed: ReadonlySet<string>,
381+
): boolean {
374382
const receiver = unwrapExpression(node);
375383
if (receiver?.type === 'Identifier') {
376384
const name = receiver.name as string;
377-
return MODULE_MOCK_RECEIVERS.has(name) || bindings.apis.has(name);
385+
return MODULE_MOCK_RECEIVERS.has(name) || (bindings.apis.has(name) && !shadowed.has(name));
378386
}
379387
if (receiver?.type !== 'MemberExpression') return false;
380388
const owner = unwrapExpression(receiver.object);
381389
const key = memberKey(receiver);
382390
return (
383391
owner?.type === 'Identifier' &&
384392
bindings.namespaces.has(owner.name as string) &&
393+
!shadowed.has(owner.name as string) &&
385394
key !== undefined &&
386395
MODULE_MOCK_RECEIVERS.has(key)
387396
);
388397
}
389398

390-
function mockCallMethod(callee: unknown, bindings: VitestBindings): string | undefined {
399+
function mockCallMethod(
400+
callee: unknown,
401+
bindings: VitestBindings,
402+
shadowed: ReadonlySet<string>,
403+
): string | undefined {
391404
const member = unwrapExpression(callee);
392405
if (member?.type !== 'MemberExpression') return undefined;
393-
if (!isMockApiReceiver(member.object, bindings)) return undefined;
406+
if (!isMockApiReceiver(member.object, bindings, shadowed)) return undefined;
394407
const method = memberKey(member);
395408
return method !== undefined && MODULE_MOCK_METHODS.has(method) ? method : undefined;
396409
}
@@ -405,8 +418,7 @@ function mockCallMethod(callee: unknown, bindings: VitestBindings): string | und
405418
* The receiver is the global `vi`/`vitest`, a name a top-level `import { vi as x } from 'vitest'`
406419
* binds to either, or a member `vi`/`vitest` of a `import * as ns from 'vitest'` namespace. Only
407420
* those import declarations are resolved: a value copied through a variable or a dynamic import
408-
* is not followed, and a local that redeclares an alias's name still counts as the alias, so the
409-
* walk can only over-report.
421+
* is not followed.
410422
*/
411423
export function parseModuleMockSpecifiers(source: string): { spec: string; line: number }[] {
412424
const parsed = parseSync('layering-mocks.ts', source);
@@ -417,9 +429,9 @@ export function parseModuleMockSpecifiers(source: string): { spec: string; line:
417429
}
418430
const bindings = vitestImportBindings(parsed.program);
419431
const sites: { spec: string; line: number }[] = [];
420-
visitAst(parsed.program, (node) => {
432+
visitAstScoped(parsed.program, new Set(), (node, shadowed) => {
421433
if (node.type !== 'CallExpression') return;
422-
if (mockCallMethod(node.callee, bindings) === undefined) return;
434+
if (mockCallMethod(node.callee, bindings, shadowed) === undefined) return;
423435
const args = node.arguments;
424436
const spec = Array.isArray(args) ? literalSpecifier(args[0]) : undefined;
425437
if (spec !== undefined) {

‎scripts/layering/package-boundaries-specifier-sites.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ test('specifier sites skip alias calls on other modules, other exports and type-
7373
"fromOther.mock('a');",
7474
"notMock.mock('b');",
7575
"typeOnly.mock('c');",
76+
"function shadow(notMock) { notMock.mock('d'); }",
7677
].join('\n'),
7778
),
7879
['1:not-vitest', '2:vitest', '3:vitest'],

‎scripts/layering/package-isolation.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,27 @@ test('an import ignores comments, non-literal mock arguments, other objects and
258258
}
259259
});
260260

261+
test('an alias an enclosing scope redeclares is a local object, not the mock API', () => {
262+
for (const policy of POLICIES) {
263+
const entry = "'@agent-device/provider-webdriver/plugin'";
264+
const vitest = "import { vi as mocks } from 'vitest';";
265+
for (const text of [
266+
`${vitest}\nfunction f(mocks) { mocks.mock(${entry}); }`,
267+
`${vitest}\nconst f = (mocks) => mocks.doMock(${entry});`,
268+
`${vitest}\n{ const mocks = other; mocks.mock(${entry}); }`,
269+
`import * as testing from 'vitest';\nconst f = (testing) => testing.vi.mock(${entry});`,
270+
]) {
271+
assert.deepEqual(check(policy, {}, source(policy, text)), [], `${policy.name}: ${text}`);
272+
}
273+
const found = check(
274+
policy,
275+
{},
276+
source(policy, `${vitest}\nfunction f(mocks) { return mocks; }\nmocks.mock(${entry});`),
277+
);
278+
assert.equal(found.length, 1, policy.name);
279+
}
280+
});
281+
261282
test('relative reach out of the package directory is refused', () => {
262283
for (const policy of POLICIES) {
263284
for (const specifier of [

0 commit comments

Comments
 (0)