0

I'm trying to create a BNF Grammar in Antlr for propositional logic but I keep getting the error:

java.lang.NoSuchFieldError: offendingToken

As there is no line number displayed, I don't know where the error is. The build is successful, but when I type in an example input, the tree stops at sentence, the first item defined in the BNF.

Here is my BNF:

grammar Grammar;

options {
    language = Java;
    output = AST;
    ASTLabelType=CommonTree;   
}

@header { 
    package antlr;
}

@members { 

}

@lexer::header { //lexer
    package antlr;
}

@lexer::members {

}

sentence: atomicsentence | complexsentence;

atomicsentence: 'T' | 'F' | symbol;

complexsentence: unop sentence | sentence binop sentence | (sentence);

unop: 'NOT';

binop: 'AND' | 'OR' | 'IMPLIES' | 'EQUIVALENT'; 

symbol: (LEXRULE)+;

LEXRULE: ('a'..'z')|('A'..'Z');

If you comment out complexsentence in sentence, the atomicsentence part works, until it terminates because there is no EOF. I'm unsure as to where this should go as adding it to sentence does not work.

Charlie
  • 1
  • 2

2 Answers2

1

(edited)

I have refactored your grammar, so it should work as you intended.

grammar Grammar;

options {
    language = Java;
    output = AST;
    ASTLabelType=CommonTree;   
}

tokens {
    CODE;
       }

@header { 
    package antlr;
}

@members { 

}

@lexer::header { //lexer
    package antlr;
}

@lexer::members {

}

code    :   sentence -> ^(CODE code);

sentence: UNOP? complexsentence (BINOP sentence)?;

atomicsentence: 'T' | 'F' | SYMBOL;

complexsentence: atomicsentence | '(' sentence ')';

UNOP: 'NOT';

BINOP: 'AND' | 'OR' | 'IMPLIES' | 'EQUIVALENT'; 

SYMBOL: LEXRULE+;

fragment
LEXRULE: ('a'..'z')|('A'..'Z');
Andremoniy
  • 34,031
  • 20
  • 135
  • 241
  • Sorry I'm new to antlr but yes I did mean '(' sentence ')' for allowing users to use brackets in the input. However with this fixed, the same error is still produced. – Charlie Jan 17 '13 at 13:14
1

Your grammar is left recursive, which ANTLR mentions when trying to generate a parser:

[17:31:32] error(210): The following sets of rules are mutually left-recursive [complexsentence, sentence] [17:31:32] Aborting because the following rules are mutually left-recursive: [[T.complexsentence,index=4,line=15], [T.sentence,index=2,line=11]]

The rule sentence matches a complexsentence, and the complexsentence rule in its turn matches a sentence. ANTLR (v3) cannot cope with such left-recursive rules.

Another problem with your grammar is that you have no lexer rule for whiate spaces, yet your example input "NOT p" contains a white space.

For a simple expression parser using ANTLR, see:

Community
  • 1
  • 1
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288