Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use correct scope in switch statements #4979

Merged
merged 3 commits into from May 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 0 additions & 3 deletions package.json
Expand Up @@ -143,9 +143,6 @@
"weak-napi": "^2.0.2",
"yargs-parser": "^21.1.1"
},
"overrides": {
"d3": "7.8.0"
},
"files": [
"dist/**/*.js",
"dist/*.d.ts",
Expand Down
15 changes: 14 additions & 1 deletion src/ast/nodes/SwitchStatement.ts
Expand Up @@ -6,19 +6,23 @@ import {
type InclusionContext
} from '../ExecutionContext';
import BlockScope from '../scopes/BlockScope';
import type ChildScope from '../scopes/ChildScope';
import type Scope from '../scopes/Scope';
import type * as NodeType from './NodeType';
import type SwitchCase from './SwitchCase';
import { type ExpressionNode, type IncludeChildren, StatementBase } from './shared/Node';
import type { ExpressionNode, GenericEsTreeNode, IncludeChildren } from './shared/Node';
import { StatementBase } from './shared/Node';

export default class SwitchStatement extends StatementBase {
declare cases: readonly SwitchCase[];
declare discriminant: ExpressionNode;
declare type: NodeType.tSwitchStatement;

private declare defaultCase: number | null;
private declare parentScope: ChildScope;

createScope(parentScope: Scope): void {
this.parentScope = parentScope as ChildScope;
this.scope = new BlockScope(parentScope);
}

Expand Down Expand Up @@ -89,6 +93,15 @@ export default class SwitchStatement extends StatementBase {
this.defaultCase = null;
}

parseNode(esTreeNode: GenericEsTreeNode) {
this.discriminant = new (this.context.getNodeConstructor(esTreeNode.discriminant.type))(
esTreeNode.discriminant,
this,
this.parentScope
);
super.parseNode(esTreeNode);
}

render(code: MagicString, options: RenderOptions): void {
this.discriminant.render(code, options);
if (this.cases.length > 0) {
Expand Down
3 changes: 3 additions & 0 deletions test/function/samples/switch-scope/_config.js
@@ -0,0 +1,3 @@
module.exports = defineTest({
description: 'uses correct scopes for switch statements'
});
10 changes: 10 additions & 0 deletions test/function/samples/switch-scope/main.js
@@ -0,0 +1,10 @@
const foo = 1;
let triggered = false;

switch (foo) {
case 1:
const foo = 2;
triggered = true;
}

assert.ok(triggered);