Skip to content

Commit

Permalink
Make variable accessible after initialization
Browse files Browse the repository at this point in the history
  • Loading branch information
lahmatiy committed Dec 7, 2019
1 parent 6814e90 commit 690dd9e
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
6 changes: 4 additions & 2 deletions src/compile.js
Original file line number Diff line number Diff line change
Expand Up @@ -338,9 +338,11 @@ module.exports = function compile(ast, suggestRanges = [], statMode = false) {
put('$');
walk(node.name);
} else {
put('/*bad ref: $');
put('typeof $');
walk(node.name);
put('*/undefined');
put('!=="undefined"?$');
walk(node.name);
put(':undefined');
}
break;

Expand Down
27 changes: 24 additions & 3 deletions test/variables.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,35 @@ describe('definitions', () => {
);
});

it('should return undefined when refer to never defined variable', () => {
assert.deepEqual(
query('$a:$b;$a')(),
undefined
);
});

it('should throw when access before initialization', () => {
assert.throws(
() => query('$a:$a;')(),
/\$a is not defined|Cannot access '\$a' before initialization/
);
});

it('should return a value when access after initialization', () => {
assert.deepEqual(
query('$a:=>foo.map($a) or foo;{ foo: { foo: 42 }}.map($a)')(),
42
);
});

it('should throw when redefine a variable defined in the same scope', () => {
assert.throws(
() => query('$a;$a;')(),
new RegExp('Identifier \'\\$a\' has already been declared')
/Identifier '\$a' has already been declared/
);
});

it('should not throw when variables with the same name defined in different scopes', () => {
it('should not throw when variables with the same name defined in another scope', () => {
assert.doesNotThrow(
() => query('$a;.($b;) + .($b;)')()
);
Expand All @@ -66,7 +87,7 @@ describe('definitions', () => {
it('should throw when redefine a variable defined in parent scope', () => {
assert.throws(
() => query('$a;.($a;)')(),
new RegExp('Identifier \'\\$a\' has already been declared')
/Identifier '\$a' has already been declared/
);
});

Expand Down

0 comments on commit 690dd9e

Please sign in to comment.