Antlr4 unexpectedly stops parsing expression

后端 未结 2 869
长情又很酷
长情又很酷 2020-12-20 02:04

I\'m developing a simple calculator with the formula grammar:

grammar Formula ;
expr :  expr POW expr             # pow
     | MINUS expr          


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-20 02:28

    But "column a" * "column b" input unexpectedly stops parsing

    If I run your grammar with ANTLR 4.6, it does not stop parsing, it parses the whole file and displays in pink what the parser can't match :

    The dots represent spaces.

    And there is an important error message :

    line 1:10 mismatched input ' * ' expecting {, '*', '/', '+', '-', '%', '^'}
    

    As I explain here as soon as you have a "mismatched" error, add -tokens to grun.

    With "column a"*"column b" :

    $ grun Formula expr -tokens -diagnostics t1.text
    [@0,0:0='"',<'"'>,1:0]
    [@1,1:8='column a',,1:1]
    [@2,9:9='"',<'"'>,1:9]
    [@3,10:10='*',<'*'>,1:10]
    [@4,11:11='"',<'"'>,1:11]
    [@5,12:19='column b',,1:12]
    [@6,20:20='"',<'"'>,1:20]
    [@7,22:21='',,2:0]
    

    With "column a" * "column b":

    $ grun Formula expr -tokens -diagnostics t2.text
    [@0,0:0='"',<'"'>,1:0]
    [@1,1:8='column a',,1:1]
    [@2,9:9='"',<'"'>,1:9]
    [@3,10:12=' * ',,1:10]
    [@4,13:13='"',<'"'>,1:13]
    [@5,14:21='column b',,1:14]
    [@6,22:22='"',<'"'>,1:22]
    [@7,24:23='',,2:0]
    line 1:10 mismatched input ' * ' expecting {, '*', '/', '+', '-', '%', '^'}
    

    you immediately see that " * "is interpreted as COLUMN.

    Many questions about matching input with lexer rules have been asked these last days :

    extraneous input

    ordering

    greedy

    ambiguity

    expression

    So many times that Lucas has posted a false question just to make an answer which summarizes all that problematic : disambiguate.

提交回复
热议问题