Wosh
Wosh

Reputation: 1625

ANTLR4 grammar parser issue

I am relatively new to ANTLR so bear with me pls.

I have the following imitation of a grammar for parsing very simple first-order logic formulas:

grammar graph;


/*------------------------------------------------------------------
* PARSER RULES
*------------------------------------------------------------------*/

input
: 
TRUE | FALSE | formula | EOF
;

formula
: 
(element)+ ST condition
;

element 
:
quantifier IN domain
;

condition
:
atom EQUALS (assignment | atom)
;

atom
:
variable DOT property
;

quantifier 
:
(FOREACH | EXISTS) variable
;

domain
:
(GRAPH_A | GRAPH_B)
;

variable
:   
(NODE | EDGE)
;

property
:
(COLOR | VALUE)
;

assignment
:
(COLORTYPE | NUMBER)
;


/*------------------------------------------------------------------
* LEXER RULES
*------------------------------------------------------------------*/
COLORTYPE : ('a'..'z')+ ;

NUMBER : ('0'..'9')+ (DOT ('0'..'9')+)? ;

WS : [ \t\r\n]+ -> skip ;

EXISTS  : 'Exists' ;

FOREACH : 'Foreach' ;

TRUE : 'True' ;

FALSE : 'False' ;

ST : '->' ; 

NODE : 'node' ;

EDGE : 'edge' ;

IN : 'in' ;

GRAPH_A : 'GraphA' ;

GRAPH_B : 'GraphB' ;

COLOR : 'color' ;

VALUE : 'value' ;

EQUALS : '=' ;

DOT : '.' ; 

The grammar is pretty straightforward. I was able to generate the lexer and parser classes with

java org.antlr.v4.Tool graph.g4

but when I try to parse the following expression

Exists node in GraphA -> node.color = 'red'

I end up with the following error:

line 1:38 token recognition error at: '''

line 1:42 token recognition error at: '''

No method for rule r or it has arguments

What is the meaning of rule 'r'? How can I understand where the problem is coming for? Any help will be much appreciated!

Upvotes: 2

Views: 3894

Answers (4)

Diamantatos Paraskevas
Diamantatos Paraskevas

Reputation: 3894

i am a bit late i think, but

"No method for rule r or it has arguments"

this is produced because you are calling something like this

C:\>grun graph r -gui

you should instead use

C:\>grun graph input -gui

Upvotes: 0

Jeff French
Jeff French

Reputation: 1151

When I make the following changes to your grammar, it works for me:

  1. Move COLORTYPE to the end, since as others have mentioned, it matches before your keywords.

  2. Change your 'condition' rule to:

    atom EQUALS QUOTE? (assignment | atom) QUOTE?

  3. Add this at the end:

    QUOTE : '\'' ;

Upvotes: 1

Sam Harwell
Sam Harwell

Reputation: 99859

The problem is COLORTYPE matches the input red, but you actually specified 'red'. You need to do one of the following:

  1. Remove the quotes around red in your input.
  2. Add quotes to your COLORTYPE rule:

    COLORTYPE : '\'' [a-z]+ '\'';
    

Upvotes: 2

Terence Parr
Terence Parr

Reputation: 5962

Move COLORTYPE last; it also matches the keywords. ANTLR resolves ambiguities to the rule mentioned first.

Upvotes: 2

Related Questions