Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add dynamic import #834

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 13 additions & 0 deletions acorn-loose/src/expression.js
Original file line number Diff line number Diff line change
Expand Up @@ -295,11 +295,24 @@ lp.parseExprAtom = function() {
case tt.backQuote:
return this.parseTemplate()

case tt._import:
if (this.options.ecmaVersion > 10) {
return this.parseDynamicImport()
} else {
return this.dummyIdent()
}

default:
return this.dummyIdent()
}
}

lp.parseDynamicImport = function() {
const node = this.startNode()
this.next()
return this.finishNode(node, "Import")
}

lp.parseNew = function() {
let node = this.startNode(), startIndent = this.curIndent, line = this.curLineStart
let meta = this.parseIdent(true)
Expand Down
6 changes: 6 additions & 0 deletions acorn-loose/src/statement.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,12 @@ lp.parseStatement = function() {
return this.parseClass(true)

case tt._import:
if (this.options.ecmaVersion > 10 && this.lookAhead(1).type === tt.parenL) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any chance we could move this into parseExport and do away with the lookAhead (by simply consuming the import token and looking at the next token)?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That seems to make cases like var dynImport = import; work in acorn loose mode, which probably isn't desirable?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, that's not what I mean—inside parseImport, after calling .next() for the import token, you'd first look for (, and parse a dynamic import only if you see it (which would change the signature of parseDynamicImport to require a start position and expect the first token to already be consumed).

node.expression = this.parseExpression()
this.semicolon()
return this.finishNode(node, "ExpressionStatement")
}

return this.parseImport()

case tt._export:
Expand Down
33 changes: 31 additions & 2 deletions acorn/src/expression.js
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ pp.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow)
this.yieldPos = 0
this.awaitPos = 0
this.awaitIdentPos = 0
let exprList = this.parseExprList(tt.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors)
let exprList = this.parseExprList(tt.parenR, this.options.ecmaVersion >= 8 && base.type !== "Import", false, refDestructuringErrors)
if (maybeAsyncArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) {
this.checkPatternErrors(refDestructuringErrors, false)
this.checkYieldAwaitInDefaultParams()
Expand All @@ -299,6 +299,16 @@ pp.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow)
let node = this.startNodeAt(startPos, startLoc)
node.callee = base
node.arguments = exprList
if (node.callee.type === "Import") {
if (node.arguments.length !== 1) {
this.raise(node.start, "import() requires exactly one argument")
}

const importArg = node.arguments[0]
if (importArg && importArg.type === "SpreadElement") {
this.raise(importArg.start, "... is not allowed in import()")
}
}
base = this.finishNode(node, "CallExpression")
} else if (this.type === tt.backQuote) {
let node = this.startNodeAt(startPos, startLoc)
Expand Down Expand Up @@ -409,11 +419,27 @@ pp.parseExprAtom = function(refDestructuringErrors) {
case tt.backQuote:
return this.parseTemplate()

case tt._import:
if (this.options.ecmaVersion > 10) {
return this.parseDynamicImport()
} else {
return this.unexpected()
}

default:
this.unexpected()
}
}

pp.parseDynamicImport = function() {
const node = this.startNode()
this.next()
if (this.type !== tt.parenL) {
this.unexpected()
}
return this.finishNode(node, "Import")
}

pp.parseLiteral = function(value) {
let node = this.startNode()
node.value = value
Expand Down Expand Up @@ -522,7 +548,10 @@ pp.parseNew = function() {
}
let startPos = this.start, startLoc = this.startLoc
node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true)
if (this.eat(tt.parenL)) node.arguments = this.parseExprList(tt.parenR, this.options.ecmaVersion >= 8, false)
if (this.options.ecmaVersion > 10 && node.callee.type === "Import") {
this.raise(node.callee.start, "Cannot use new with import(...)")
}
if (this.eat(tt.parenL)) node.arguments = this.parseExprList(tt.parenR, this.options.ecmaVersion >= 8 && node.callee.type !== "Import", false)
else node.arguments = empty
return this.finishNode(node, "NewExpression")
}
Expand Down
8 changes: 8 additions & 0 deletions acorn/src/statement.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,14 @@ pp.parseStatement = function(context, topLevel, exports) {
case tt.semi: return this.parseEmptyStatement(node)
case tt._export:
case tt._import:
if (this.options.ecmaVersion > 10 && starttype === tt._import) {
skipWhiteSpace.lastIndex = this.pos
let skip = skipWhiteSpace.exec(this.input)
let next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next)
if (nextCh === 40) // '('
return this.parseExpressionStatement(node, this.parseExpression())
}

if (!this.options.allowImportExportEverywhere) {
if (!topLevel)
this.raise(this.start, "'import' and 'export' may only appear at the top level")
Expand Down
2 changes: 1 addition & 1 deletion acorn/src/tokentype.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ export const types = {
_class: kw("class", startsExpr),
_extends: kw("extends", beforeExpr),
_export: kw("export"),
_import: kw("import"),
_import: kw("import", startsExpr),
_null: kw("null", startsExpr),
_true: kw("true", startsExpr),
_false: kw("false", startsExpr),
Expand Down
3 changes: 1 addition & 2 deletions bin/run_test262.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,13 @@ const unsupportedFeatures = [
"class-static-fields-private",
"class-static-fields-public",
"class-static-methods-private",
"dynamic-import",
"export-star-as-namespace-from-module",
"import.meta",
"numeric-separator-literal"
];

run(
(content, {sourceType}) => parse(content, {sourceType, ecmaVersion: 10, allowHashBang: true}),
(content, {sourceType}) => parse(content, {sourceType, ecmaVersion: 11, allowHashBang: true}),
{
testsDirectory: path.dirname(require.resolve("test262/package.json")),
skip: test => (test.attrs.features && unsupportedFeatures.some(f => test.attrs.features.includes(f))),
Expand Down
1 change: 1 addition & 0 deletions test/run.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
require("./tests-regexp-2018.js");
require("./tests-json-superset.js");
require("./tests-optional-catch-binding.js");
require("./tests-dynamic-import.js");
var acorn = require("../acorn")
var acorn_loose = require("../acorn-loose")

Expand Down
128 changes: 128 additions & 0 deletions test/tests-dynamic-import.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
// Tests for ECMAScript 2020 dynamic import

if (typeof exports != 'undefined') {
var test = require('./driver.js').test;
var testFail = require('./driver.js').testFail;
}

test(
"import('dynamicImport.js')",
{
type: 'Program',
start: 0,
end: 26,
body: [
{
type: 'ExpressionStatement',
start: 0,
end: 26,
expression: {
type: 'CallExpression',
start: 0,
end: 26,
callee: { type: 'Import', start: 0, end: 6 },
arguments: [
{
type: 'Literal',
start: 7,
end: 25,
value: 'dynamicImport.js',
raw: "'dynamicImport.js'"
}
]
}
}
],
sourceType: 'script'
},
{ ecmaVersion: 11 }
);

test(
"function* a() { yield import('http'); }",
{
type: 'Program',
start: 0,
end: 39,
body: [
{
type: 'FunctionDeclaration',
start: 0,
end: 39,
id: { type: 'Identifier', start: 10, end: 11, name: 'a' },
expression: false,
generator: true,
async: false,
params: [],
body: {
type: 'BlockStatement',
start: 14,
end: 39,
body: [
{
type: 'ExpressionStatement',
start: 16,
end: 37,
expression: {
type: 'YieldExpression',
start: 16,
end: 36,
delegate: false,
argument: {
type: 'CallExpression',
start: 22,
end: 36,
callee: { type: 'Import', start: 22, end: 28 },
arguments: [{ type: 'Literal', start: 29, end: 35, value: 'http', raw: "'http'" }]
}
}
}
]
}
}
],
sourceType: 'script'
},
{ ecmaVersion: 11 }
);

testFail('function failsParse() { return import.then(); }', 'Unexpected token (1:37)', {
ecmaVersion: 11,
loose: false
});

testFail("var dynImport = import; dynImport('http');", 'Unexpected token (1:22)', {
ecmaVersion: 11,
loose: false
});

testFail("import('test.js')", 'Unexpected token (1:6)', {
ecmaVersion: 10,
loose: false,
sourceType: 'module'
});

testFail("import()", 'import() requires exactly one argument (1:0)', {
ecmaVersion: 11,
loose: false
});

testFail("import(a, b)", 'import() requires exactly one argument (1:0)', {
ecmaVersion: 11,
loose: false
});

testFail("import(...[a])", '... is not allowed in import() (1:7)', {
ecmaVersion: 11,
loose: false
});

testFail("import(source,)", 'Unexpected token (1:14)', {
ecmaVersion: 11,
loose: false
});

testFail("new import(source)", 'Cannot use new with import(...) (1:4)', {
ecmaVersion: 11,
loose: false
});
Copy link
Contributor

@mysticatea mysticatea Jun 4, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would you add more fail tests?

  • import(); ... unexpected token ')'.
  • import(a, b); ... unexpected token ','.
  • import(source,); ... unexpected token ','.
  • var a = import(source); ... unexpected token 'import' if ecmaVersion < 11.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated to consider these as errors and added test cases as well.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you!