Skip to content

Is it possible to understand, when does semantic predicates work and they doesn't? #4780

Open
@dims12

Description

@dims12

Below are two grammars.

In this grammar, semantic predicates do "work". I.e. if they are false, rules don't match and if they are true, rules do match:

parser grammar MyParser;

options {
    tokenVocab=MyLexer;
}

expr
    : term
    | expr asterisk expr (asterisk expr)*
    | expr plus expr (plus expr)*
    ;

plus: {_input.LT(1).getText().equals("+")}? SPECID;
asterisk: {_input.LT(1).getText().equals("*")}? SPECID;


term
    : ALNUMID
    | STRID
    | LPAREN expr RPAREN
    ;

and in this grammar, semantic predicates don't work. I.e. if they are false, rules still match bu error is printed.

expr
    : add
    | mult
    | term
    ;


mult
    : term (asterisk) term ((asterisk) term)*
    ;

add
    : (term|mult) plus (term|mult) (plus (term|mult))*
    ;


plus: {_input.LT(1).getText().equals("+")}? SPECID;
asterisk: {_input.LT(1).getText().equals("*")}? SPECID;



term
    : ALNUMID
    | STRID
    | LPAREN expr RPAREN
    ;

In both cases I am trying to run simple tests to parse 2 + 2 and 2 * 2.

Is it possible to understand beforehand, will definition work or not? What is the logic here?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions