我为ANTLR解析器和lexer编写了下面的语法,用于为逻辑公式构建树,如果有人能帮忙的话,我会问几个问题:
class AntlrFormulaParser extends Parser;
options {
buildAST = true;
}
biconexpr : impexpr (BICONDITIONAL^ impexpr)*;
impexpr : orexpr (IMPLICATION^ orexpr)*;
orexpr : andexpr (DISJUNCTION^ andexpr)*;
andexpr : notexpr (CONJUNCTION^ notexpr)*;
notexpr : (NEGATION^)? formula;
formula
: atom
| LEFT_PAREN! biconexpr RIGHT_PAREN!
;
atom
: CHAR
| TRUTH
| FALSITY
;
class AntlrFormulaLexer extends Lexer;
// Atoms
CHAR: 'a'..'z';
TRUTH: ('\u22A4' | 'T');
FALSITY: ('\u22A5' | 'F');
// Grouping
LEFT_PAREN: '(';
RIGHT_PAREN: ')';
NEGATION: ('\u00AC' | '~' | '!');
CONJUNCTION: ('\u2227' | '&' | '^');
DISJUNCTION: ('\u2228' | '|' | 'V');
IMPLICATION: ('\u2192' | "->");
BICONDITIONAL: ('\u2194' | "<->");
WHITESPACE : (' ' | '\t' | '\r' | '\n') { $setType(Token.SKIP); };树语法:
tree grammar AntlrFormulaTreeParser;
options {
tokenVocab=AntlrFormula;
ASTLabelType=CommonTree;
}
expr returns [Formula f]
: ^(BICONDITIONAL f1=expr f2=expr) {
$f = new Biconditional(f1, f2);
}
| ^(IMPLICATION f1=expr f2=expr) {
$f = new Implication(f1, f2);
}
| ^(DISJUNCTION f1=expr f2=expr) {
$f = new Disjunction(f1, f2);
}
| ^(CONJUNCTION f1=expr f2=expr) {
$f = new Conjunction(f1, f2);
}
| ^(NEGATION f1=expr) {
$f = new Negation(f1);
}
| CHAR {
$f = new Atom($CHAR.getText());
}
| TRUTH {
$f = Atom.TRUTH;
}
| FALSITY {
$f = Atom.FALSITY;
}
;我在上述语法方面遇到的问题如下:
如果有人能帮我解决这几个问题,我会非常感激的。谢谢您:)
发布于 2011-01-10 01:34:27
我将以下定义改为:
IMPLICATION: ('\u2192' | '->');
BICONDITIONAL: ('\u2194' | '<->');注:"->“vs”>“
为了解决错误问题:
formula
: (
atom
| LEFT_PAREN! biconexpr RIGHT_PAREN!
) EOF
;出发地:http://www.antlr.org/wiki/pages/viewpage.action?pageId=4554943
修正了针对antlr 3.3编译的语法(除Antlrforma.g外):
grammar AntlrFormula;
options {
output = AST;
}
program : formula ;
formula : atom | LEFT_PAREN! biconexpr RIGHT_PAREN! ;
biconexpr : impexpr (BICONDITIONAL^ impexpr)*;
impexpr : orexpr (IMPLICATION^ orexpr)*;
orexpr : andexpr (DISJUNCTION^ andexpr)*;
andexpr : notexpr (CONJUNCTION^ notexpr)*;
notexpr : (NEGATION^)? formula;
atom
: CHAR
| TRUTH
| FALSITY
;
// Atoms
CHAR: 'a'..'z';
TRUTH: ('\u22A4' | 'T');
FALSITY: ('\u22A5' | 'F');
// Grouping
LEFT_PAREN: '(';
RIGHT_PAREN: ')';
NEGATION: ('\u00AC' | '~' | '!');
CONJUNCTION: ('\u2227' | '&' | '^');
DISJUNCTION: ('\u2228' | '|' | 'V');
IMPLICATION: ('\u2192' | '->');
BICONDITIONAL: ('\u2194' | '<->');
WHITESPACE : (' ' | '\t' | '\r' | '\n') { $channel = HIDDEN; };链接到antlr 3.3二进制:http://www.antlr.org/download/antlr-3.3-complete.jar
您将需要尝试匹配程序规则,以匹配完整的文件。
这个类是可测试的:
import org.antlr.runtime.*;
public class Main {
public static void main(String[] args) {
AntlrFormulaLexer lexer = new AntlrFormulaLexer(new ANTLRStringStream("(~ab)"));
AntlrFormulaParser p = new AntlrFormulaParser(new CommonTokenStream(lexer));
try {
p.program();
if ( p.failed() || p.getNumberOfSyntaxErrors() != 0) {
System.out.println("failed");
}
} catch (RecognitionException e) {
e.printStackTrace();
}
}
}https://stackoverflow.com/questions/4642986
复制相似问题