简体   繁体   中英

ANTLR4 Javascript parser RegExp and division operator conflict

I am writing a JS parser using antlr4. I am basically using the grammar file posted on Antlr's grammar repository (ECMAScript.g4) as the basis.

The grammar defines the regex rule as below, which in itself is not a problem.

RegularExpressionLiteral: '/' RegularExpressionBody '/' RegularExpressionFlags ;

However, the parser thinks an expression code like this a regex.

var x = a / b + c / d;

I wonder if there is a easy fix for this conflict. Thanks!

You probably didn't include all the code from the grammar. Be sure to include all the code inside the @member blocks: they are responsible for determining if an / should be considered a division operator, or a regex delimiter.

When I run the following test class:

public class Main {

    public static void main(String[] args) throws Exception {
        ECMAScriptLexer lexer = new ECMAScriptLexer(new ANTLRInputStream("var x = a / b + c / d;"));
        ECMAScriptParser parser = new ECMAScriptParser(new CommonTokenStream(lexer));
        ECMAScriptParser.ProgramContext ctx = parser.program();
        new TreeViewer(Arrays.asList(ECMAScriptParser.ruleNames), ctx).open();
    }
}

The following screen is shown:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM