diff --git a/packages/babel-parser/src/tokenizer/state.js b/packages/babel-parser/src/tokenizer/state.js index b46819164f8d..35ddf50a8cda 100644 --- a/packages/babel-parser/src/tokenizer/state.js +++ b/packages/babel-parser/src/tokenizer/state.js @@ -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(); diff --git a/packages/babel-parser/test/options.js b/packages/babel-parser/test/options.js new file mode 100644 index 000000000000..6aa494f9db0e --- /dev/null +++ b/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 }); + }); + }); + }); +});