简体   繁体   中英

BNF Grammar for propositional logic ANTLR

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.

(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');

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:

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