Skip to content

Commit 759e348

Browse files
committed
chore(gates): keep scope boundaries in the Vitest mock-site reader
A parameter initializer, a switch discriminant, a class static block and a namespace body each have a scope boundary the reader flattened into the enclosing scope, so a later declaration hid a real mock of a provider.
1 parent 3a2b428 commit 759e348

3 files changed

Lines changed: 119 additions & 11 deletions

File tree

‎scripts/layering/layering-ast.ts‎

Lines changed: 45 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -184,10 +184,15 @@ function isFunctionNode(node: AstNode): boolean {
184184
);
185185
}
186186

187+
/** Bodies that open their own `var` scope: a `var` inside one never reaches the enclosing function. */
188+
function isVarScopeBoundary(node: AstNode): boolean {
189+
return isFunctionNode(node) || node.type === 'StaticBlock' || node.type === 'TSModuleBlock';
190+
}
191+
187192
function hoistedVarNames(node: unknown, into: string[]): void {
188193
for (const child of Array.isArray(node) ? node : [node]) {
189194
const record = asNode(child);
190-
if (record === undefined || isFunctionNode(record)) continue;
195+
if (record === undefined || isVarScopeBoundary(record)) continue;
191196
if (record.type === 'VariableDeclaration' && record.kind === 'var') {
192197
for (const declarator of nodeList(record.declarations)) {
193198
patternNames(asNode(declarator)?.id, into);
@@ -197,18 +202,20 @@ function hoistedVarNames(node: unknown, into: string[]): void {
197202
}
198203
}
199204

200-
/** Names `node` itself declares for its own subtree: parameters, `var`s, block-level lexical declarations. */
205+
/**
206+
* Names `node` declares for its own subtree: parameters, block-level lexical declarations, and the
207+
* `var`s of a static block or namespace body. A function's own `var`s join its body only
208+
* (`childScope`), since a parameter initializer runs before the body declarations exist.
209+
*/
201210
function scopeBindings(node: AstNode): string[] {
202211
const names: string[] = [];
203212
if (isFunctionNode(node)) {
204213
for (const param of nodeList(node.params)) patternNames(param, names);
205214
if (node.type === 'FunctionExpression') patternNames(node.id, names);
215+
} else if (node.type === 'StaticBlock' || node.type === 'TSModuleBlock') {
216+
lexicalNames(nodeList(node.body), names);
206217
hoistedVarNames(node.body, names);
207-
} else if (
208-
node.type === 'BlockStatement' ||
209-
node.type === 'StaticBlock' ||
210-
node.type === 'TSModuleBlock'
211-
) {
218+
} else if (node.type === 'BlockStatement') {
212219
lexicalNames(nodeList(node.body), names);
213220
} else if (node.type === 'ClassExpression') {
214221
patternNames(node.id, names);
@@ -226,10 +233,36 @@ function scopeBindings(node: AstNode): string[] {
226233
return names;
227234
}
228235

236+
function withNames(scope: ReadonlySet<string>, names: readonly string[]): ReadonlySet<string> {
237+
return names.length > 0 ? new Set([...scope, ...names]) : scope;
238+
}
239+
240+
/**
241+
* The scope a child property sees. Most children see everything the node declares; a switch
242+
* discriminant runs before the case declarations exist, and only a function body sees the
243+
* function's `var`s.
244+
*/
245+
function childScope(
246+
node: AstNode,
247+
key: string,
248+
outer: ReadonlySet<string>,
249+
inner: ReadonlySet<string>,
250+
): ReadonlySet<string> {
251+
if (node.type === 'SwitchStatement' && key === 'discriminant') return outer;
252+
if (isFunctionNode(node) && key === 'body') {
253+
const vars: string[] = [];
254+
hoistedVarNames(node.body, vars);
255+
return withNames(inner, vars);
256+
}
257+
return inner;
258+
}
259+
229260
/**
230261
* `visitAst` that also hands the visitor the names declared by the enclosing scopes: function
231262
* 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.
263+
* parameters. A parameter initializer, a switch discriminant, a static block and a namespace
264+
* body keep their own boundaries. A `with` statement or `eval` can rebind names invisibly and is
265+
* not modelled.
233266
*/
234267
export function visitAstScoped(
235268
node: unknown,
@@ -242,8 +275,9 @@ export function visitAstScoped(
242275
}
243276
const record = asNode(node);
244277
if (record === undefined) return;
245-
const declared = scopeBindings(record);
246-
const scope = declared.length > 0 ? new Set([...shadowed, ...declared]) : shadowed;
278+
const scope = withNames(shadowed, scopeBindings(record));
247279
visitor(record, scope);
248-
for (const child of Object.values(record)) visitAstScoped(child, scope, visitor);
280+
for (const [key, child] of Object.entries(record)) {
281+
visitAstScoped(child, childScope(record, key, shadowed, scope), visitor);
282+
}
249283
}

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

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,66 @@ test('an alias is not a mock receiver where an enclosing scope redeclares its na
112112
);
113113
});
114114

115+
test('a parameter initializer sees the parameters but not the body declarations', () => {
116+
const alias = "import { vi as mocks } from 'vitest';";
117+
assert.deepEqual(
118+
specs(
119+
alias,
120+
"function bodyVar(x = mocks.mock('a')) { var mocks; }",
121+
"const arrow = (x = mocks.doMock('b')) => { var mocks; };",
122+
"function bodyFunction(x = mocks.mock('c')) { function mocks() {} }",
123+
"const method = { run(x = mocks.mock('d')) { var mocks; } };",
124+
),
125+
['a', 'b', 'c', 'd'],
126+
);
127+
assert.deepEqual(
128+
specs(
129+
alias,
130+
"function earlier(mocks, x = mocks.mock('e')) {}",
131+
"const arrow = (mocks, x = mocks.mock('f')) => x;",
132+
"const expression = function mocks(x = mocks.mock('g')) {};",
133+
"function body(x) { var mocks = other; return mocks.mock('h'); }",
134+
),
135+
[],
136+
);
137+
});
138+
139+
test('a switch discriminant sees the enclosing scope, not the case declarations', () => {
140+
const alias = "import { vi as mocks } from 'vitest';";
141+
assert.deepEqual(specs(alias, "switch (mocks.mock('a')) { case 0: let mocks; }"), ['a']);
142+
assert.deepEqual(
143+
specs(alias, "switch (kind) { case 0: const mocks = other; mocks.mock('b'); }"),
144+
[],
145+
);
146+
assert.deepEqual(
147+
specs(alias, "switch (kind) { case 0: let mocks; break; default: mocks.mock('c'); }"),
148+
[],
149+
);
150+
});
151+
152+
test('a static block and a namespace body are var scopes of their own', () => {
153+
const alias = "import { vi as mocks } from 'vitest';";
154+
assert.deepEqual(
155+
specs(
156+
alias,
157+
"function staticVar() { class C { static { var mocks; } } mocks.mock('a'); }",
158+
"function namespaceVar() { namespace N { var mocks = other; } mocks.mock('b'); }",
159+
"class D { static { var mocks = other; } } mocks.mock('c');",
160+
),
161+
['a', 'b', 'c'],
162+
);
163+
assert.deepEqual(
164+
specs(
165+
alias,
166+
"class C { static { var mocks = other; mocks.mock('d'); } }",
167+
"class E { static { if (flag) { var mocks = other; } mocks.mock('e'); } }",
168+
"namespace N { var mocks = other; mocks.mock('f'); }",
169+
"namespace M { if (flag) { var mocks = other; } mocks.mock('g'); }",
170+
),
171+
[],
172+
);
173+
});
174+
115175
test('the global vi and vitest names stay mock receivers beside import aliases', () => {
116176
assert.deepEqual(
117177
specs(

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,20 @@ test('an alias an enclosing scope redeclares is a local object, not the mock API
288288
}
289289
});
290290

291+
test('a mock of a provider survives a shadow that only a later scope boundary declares', () => {
292+
for (const policy of POLICIES) {
293+
const entry = "'@agent-device/provider-webdriver/plugin'";
294+
const vitest = "import { vi as mocks } from 'vitest';";
295+
for (const text of [
296+
`${vitest}\nfunction f(x = mocks.mock(${entry})) { var mocks; }`,
297+
`${vitest}\nswitch (mocks.mock(${entry})) { case 0: let mocks; }`,
298+
`${vitest}\nfunction f() { class C { static { var mocks; } } mocks.mock(${entry}); }`,
299+
]) {
300+
assert.equal(check(policy, {}, source(policy, text)).length, 1, `${policy.name}: ${text}`);
301+
}
302+
}
303+
});
304+
291305
test('relative reach out of the package directory is refused', () => {
292306
for (const policy of POLICIES) {
293307
for (const specifier of [

0 commit comments

Comments
 (0)