Skip to content

Commit

Permalink
Hoisting fixes (#2607)
Browse files Browse the repository at this point in the history
When hoisting a var, use UNKNOWN_EXPRESSION as the initializer instead
of the actual one. This prevents the initializer from being used during
the optimization step when it hasn't yet been assigned at runtime.
  • Loading branch information
lye authored and lukastaegert committed Dec 23, 2018
1 parent b42e7fb commit f8600a9
Show file tree
Hide file tree
Showing 7 changed files with 60 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/ast/scopes/BlockScope.ts
@@ -1,6 +1,7 @@
import { AstContext } from '../../Module';
import Identifier from '../nodes/Identifier';
import { ExpressionEntity } from '../nodes/shared/Expression';
import { UNKNOWN_EXPRESSION } from '../values';
import LocalVariable from '../variables/LocalVariable';
import Scope from './Scope';

Expand All @@ -14,7 +15,12 @@ export default class BlockScope extends Scope {
isHoisted: boolean = false
) {
if (isHoisted) {
return this.parent.addDeclaration(identifier, context, init, true) as LocalVariable;
return this.parent.addDeclaration(
identifier,
context,
UNKNOWN_EXPRESSION,
true
) as LocalVariable;
} else {
return super.addDeclaration(identifier, context, init, false) as LocalVariable;
}
Expand Down
3 changes: 3 additions & 0 deletions test/form/samples/hoisted-variable-case-stmt/_config.js
@@ -0,0 +1,3 @@
module.exports = {
description: 'Properly handles a variable hoisted from within a fallthrough switch case'
};
8 changes: 8 additions & 0 deletions test/form/samples/hoisted-variable-case-stmt/_expected.js
@@ -0,0 +1,8 @@
switch (someGlobal) {
case 1:
var hoisted = true;
case 2:
if (hoisted) {
throw "failed";
}
}
8 changes: 8 additions & 0 deletions test/form/samples/hoisted-variable-case-stmt/main.js
@@ -0,0 +1,8 @@
switch (someGlobal) {
case 1:
var hoisted = true;
case 2:
if (hoisted) {
throw "failed";
}
}
4 changes: 4 additions & 0 deletions test/form/samples/hoisted-variable-if-stmt/_config.js
@@ -0,0 +1,4 @@
module.exports = {
description:
'Properly renders branches which refer to hoisted variables from other lexical scopes'
};
15 changes: 15 additions & 0 deletions test/form/samples/hoisted-variable-if-stmt/_expected.js
@@ -0,0 +1,15 @@
if (false) {
var foo;
}

if (foo) {
console.log("nope");
}

{
var bar = true;
}

if (bar) {
console.log("ok");
}
15 changes: 15 additions & 0 deletions test/form/samples/hoisted-variable-if-stmt/main.js
@@ -0,0 +1,15 @@
if (false) {
var foo = true;
}

if (foo) {
console.log("nope");
}

if (true) {
var bar = true;
}

if (bar) {
console.log("ok");
}

0 comments on commit f8600a9

Please sign in to comment.