Skip to content
This repository has been archived by the owner on Sep 10, 2023. It is now read-only.

Commit

Permalink
fix: Can not defined same key in object. close #14
Browse files Browse the repository at this point in the history
  • Loading branch information
axetroy committed Jun 13, 2018
1 parent 95d05a8 commit b06da7f
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 21 deletions.
2 changes: 1 addition & 1 deletion src/evaluate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -849,7 +849,7 @@ const visitors: EvaluateMap = {
const val = evaluate(path.createChild(node.value));
if (isIdentifier(node.key)) {
object[node.key.name] = val;
scope.const(node.key.name, val);
scope.var(node.key.name, val);
} else {
object[evaluate(path.createChild(node.key))] = val;
}
Expand Down
12 changes: 5 additions & 7 deletions src/scope.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Context } from "./context";
import { ErrDuplicateDeclard } from "./error";
import { Kind, KindType, ScopeType } from "./type";
import { Kind, KindType, ScopeType, isolatedScopeMap } from "./type";
import { Var } from "./var";

export class Scope {
Expand Down Expand Up @@ -164,12 +164,10 @@ export class Scope {
// tslint:disable-next-line
let targetScope: Scope = this;

while (
targetScope.parent !== null &&
// function and constructor has own scope
(targetScope.type !== ScopeType.Function &&
targetScope.type !== ScopeType.Constructor)
) {
// When to stop?
// 1. if the current scope is top-level scope
// 2. if the current scope type is one of types `function`, `constructor`
while (targetScope.parent !== null && !isolatedScopeMap[targetScope.type]) {
targetScope = targetScope.parent;
}

Expand Down
7 changes: 7 additions & 0 deletions src/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ export enum ScopeType {
Block
}

export const isolatedScopeMap = {
[ScopeType.Function]: true,
[ScopeType.Constructor]: true,
[ScopeType.Method]: true,
[ScopeType.Object]: true
};

export enum Kind {
Var = "var",
Const = "const",
Expand Down
26 changes: 13 additions & 13 deletions test/common/duplicate-object-key.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,18 @@ import vm from "../../src/vm";

test("allown duplicate object key", t => {
// TODO
// const sandbox: any = vm.createContext({});
// const obj = vm.runInContext(
// `
// var obj = {
// a: 1,
// a: 2,
// };
// module.exports = obj;
// `,
// sandbox
// );
// t.deepEqual(Object.keys(obj).length, 1);
// t.deepEqual(obj.a, 2);
const sandbox: any = vm.createContext({});
const obj = vm.runInContext(
`
var obj = {
a: 1,
a: 2,
};
module.exports = obj;
`,
sandbox
);
t.deepEqual(Object.keys(obj).length, 1);
t.deepEqual(obj.a, 2);
t.pass();
});

0 comments on commit b06da7f

Please sign in to comment.