Skip to content

Commit

Permalink
fix: parser strictMode option (babel#13548)
Browse files Browse the repository at this point in the history
  • Loading branch information
overlookmotel authored and nicolo-ribaudo committed Jul 30, 2021
1 parent c0d54ce commit 815766c
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 1 deletion.
6 changes: 5 additions & 1 deletion packages/babel-parser/src/tokenizer/state.js
Expand Up @@ -33,7 +33,11 @@ export default class State {

init(options: Options): void {
this.strict =
options.strictMode === false ? false : options.sourceType === "module";
options.strictMode === false
? false
: options.strictMode === true
? true
: options.sourceType === "module";

this.curLine = options.startLine;
this.startLoc = this.endLoc = this.curPosition();
Expand Down
59 changes: 59 additions & 0 deletions packages/babel-parser/test/options.js
@@ -0,0 +1,59 @@
import { parse } from "../lib";

describe("options", () => {
describe("strictMode", () => {
const CODE = "function f(x, x) {}";

function expectToSucceed(opts) {
expect(parse(CODE, opts).program.body[0]).toMatchObject({
type: "FunctionDeclaration",
id: { type: "Identifier", name: "f" },
generator: false,
async: false,
params: [
{ type: "Identifier", name: "x" },
{ type: "Identifier", name: "x" },
],
body: {
type: "BlockStatement",
body: [],
directives: [],
},
});
}

function expectToFail(opts) {
expect(() => parse(CODE, opts)).toThrow(
new SyntaxError("Argument name clash. (1:14)"),
);
}

describe("sourceType module", () => {
it("default parses as strict mode", () => {
expectToFail({ sourceType: "module" });
});

it("false parses as sloppy mode", () => {
expectToSucceed({ sourceType: "module", strictMode: false });
});

it("true parses as strict mode", () => {
expectToFail({ sourceType: "module", strictMode: true });
});
});

describe("sourceType script", () => {
it("default parses as sloppy mode", () => {
expectToSucceed({ sourceType: "script" });
});

it("false parses as sloppy mode", () => {
expectToSucceed({ sourceType: "script", strictMode: false });
});

it("true parses as strict mode", () => {
expectToFail({ sourceType: "script", strictMode: true });
});
});
});
});

0 comments on commit 815766c

Please sign in to comment.