From 47ba231a9b3f7183df3c76822b25b3db425fce23 Mon Sep 17 00:00:00 2001 From: Timothy Flynn Date: Mon, 20 Jan 2025 11:43:41 -0500 Subject: [PATCH] LibJS: Do not consume "with" tokens in import statements as identifiers The "with" statement is its own token (TokenType::With), and thus would fail to parse as an identifier. We've already asserted that the token we are parsing is "with" or "assert", so just consume it. --- Libraries/LibJS/Parser.cpp | 2 +- Libraries/LibJS/Tests/modules/json-module.mjs | 2 ++ Libraries/LibJS/Tests/modules/json-modules.js | 35 ++++++++++++++++++- 3 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 Libraries/LibJS/Tests/modules/json-module.mjs diff --git a/Libraries/LibJS/Parser.cpp b/Libraries/LibJS/Parser.cpp index a546c6bcdbc..1f0ee5f97ee 100644 --- a/Libraries/LibJS/Parser.cpp +++ b/Libraries/LibJS/Parser.cpp @@ -4589,7 +4589,7 @@ ModuleRequest Parser::parse_module_request() return request; VERIFY(m_state.current_token.original_value().is_one_of("with"sv, "assert"sv)); - consume(TokenType::Identifier); + consume(); consume(TokenType::CurlyOpen); while (!done() && !match(TokenType::CurlyClose)) { diff --git a/Libraries/LibJS/Tests/modules/json-module.mjs b/Libraries/LibJS/Tests/modules/json-module.mjs new file mode 100644 index 00000000000..cce3701a766 --- /dev/null +++ b/Libraries/LibJS/Tests/modules/json-module.mjs @@ -0,0 +1,2 @@ +import json from "./json-module.json" with { type: "json" }; +export default json; diff --git a/Libraries/LibJS/Tests/modules/json-modules.js b/Libraries/LibJS/Tests/modules/json-modules.js index 84d4f796280..2c4605e45a1 100644 --- a/Libraries/LibJS/Tests/modules/json-modules.js +++ b/Libraries/LibJS/Tests/modules/json-modules.js @@ -1,5 +1,5 @@ describe("basic behavior", () => { - test("can import json modules", () => { + test("can import json modules (with import function)", () => { let passed = false; let error = null; let result = null; @@ -31,4 +31,37 @@ describe("basic behavior", () => { expect(jsonResult).toHaveProperty("array", [1, 2, 3]); expect(jsonResult).toHaveProperty("map", { innerValue: "innerValue" }); }); + + test("can import json modules (with import statement)", () => { + let passed = false; + let error = null; + let result = null; + + import("./json-module.mjs") + .then(jsonObj => { + passed = true; + result = jsonObj; + }) + .catch(err => { + error = err; + }); + + runQueuedPromiseJobs(); + + if (error) throw error; + + console.log(JSON.stringify(result)); + expect(passed).toBeTrue(); + + expect(result).not.toBeNull(); + expect(result).not.toBeUndefined(); + + const jsonResult = result.default; + expect(jsonResult).not.toBeNull(); + expect(jsonResult).not.toBeUndefined(); + + expect(jsonResult).toHaveProperty("value", "value"); + expect(jsonResult).toHaveProperty("array", [1, 2, 3]); + expect(jsonResult).toHaveProperty("map", { innerValue: "innerValue" }); + }); });