grammars-v4 icon indicating copy to clipboard operation
grammars-v4 copied to clipboard

Javascript "namespace import" incorrectly parsed as a "default import"

Open tencyle-yairm opened this issue 1 year ago • 0 comments
trafficstars

The following statement is the simplest namespace import as per the standard since 2015 through 2023

import * as ns1 from "mod1"

However, in the javascript parser .g4 file the above statement is incorrectly parsed as a "default import" and not as a "namespace import".

Excerpt from the standard of 2023:

16.2.2 Imports Syntax ImportDeclaration :    import ImportClause FromClause ;    import ModuleSpecifier ; ImportClause :    ImportedDefaultBinding    NameSpaceImport    NamedImports    ImportedDefaultBinding , NameSpaceImport    ImportedDefaultBinding , NamedImports NameSpaceImport :    * as ImportedBinding

I've corrected the javascript grammar and attached the commit diff bellow. However, since I'm new to Antlr and not sure the grammar is absolutely correct in the sense that it may accept illegal statements, I have decided not to make a pull request.

Additional fixes in the diff below:

  • namespace import must use the "AS" keyword, it is not optional
  • "export" was using the "importNamespace" rule, however, in export, the "AS" keyword is optional - hence, "exportNamespace" rule was created
diff --git a/javascript/javascript/JavaScriptParser.g4 b/javascript/javascript/JavaScriptParser.g4
index 0ddd9e23..9779068b 100644
--- a/javascript/javascript/JavaScriptParser.g4
+++ b/javascript/javascript/JavaScriptParser.g4
@@ -85,7 +85,8 @@ importStatement
     ;
 
 importFromBlock
-    : importDefault? (importNamespace | importModuleItems) importFrom eos
+    : importDefault? (importNamespace | importModuleItems)? importFrom eos
     | StringLiteral eos
     ;
 
@@ -110,11 +111,13 @@ importedBinding
     ;
 
 importDefault
-    : aliasName ','
+    : identifierName | (identifierName ',')
     ;
 
 importNamespace
-    : ('*' | identifierName) (As identifierName)?
+    : ('*' As identifierName)
     ;
 
 importFrom
@@ -124,14 +127,19 @@ importFrom
 aliasName
     : identifierName (As identifierName)?
     ;
 
 exportStatement
     : Export Default? (exportFromBlock | declaration) eos # ExportDeclaration
     | Export Default singleExpression eos                 # ExportDefaultDeclaration
     ;
 
+exportNamespace
+    : '*' (As identifierName)?
+    ;
+
 exportFromBlock
-    : importNamespace importFrom eos
+    : exportNamespace importFrom eos
     | exportModuleItems importFrom? eos
     ;

tencyle-yairm avatar Jan 16 '24 06:01 tencyle-yairm