ANTLR 命题逻辑评估器 [英] ANTLR Propositional Logic Evaluator
本文介绍了ANTLR 命题逻辑评估器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 ANTLR 中创建一个语法来评估命题逻辑公式.所以对于输入 (1 & 0) |1
,应该返回true
.
I'm trying to create a grammar in ANTLR that evaluates propositional logic formulas. So for the input (1 & 0) | 1
, it should return true
.
我已经构建了以下内容:
I have constructed the following:
code returns[boolean value]
: formula EOF {$value = $formula.value;}
;
formula returns [boolean value]
: equiv {$value = $equiv.value;}
;
equiv returns [boolean value]
: a=implies {$value = $a.value;}
( '#' b=implies {$value = $value == $b.value;}
)*
;
implies returns [boolean value]
: a=or {$value = $a.value;}
( '>' b=or {$value = !$value || $b.value;}
)*
;
or returns [boolean value]
: a=and {$value = $a.value;}
( '|' b=and {$value ||= $b.value;}
)*
;
and returns [boolean value]
: a=term {$value = $a.value;}
( '&' b=term {$value &&= $b.value;}
)*
;
term returns [boolean value]
: '(' formula ')' {$value = $formula.value;}
| '0' {$value = false;}
| '1' {$value = true;}
| '¬' term {$value = !$term.value;}
;
WHITESPACE: (' '|'\t'|'\r'|'\f'|'\n')+{$channel = HIDDEN;} ;
但是我不断收到错误java.lang.NoSuchFieldError:offendingToken.无论如何要找出错误所在或如何修复它?
However I keep getting the error java.lang.NoSuchFieldError: offendingToken. Is there anyway to find out where the error is or how to fix it?
推荐答案
有3个问题:
{$value ||= $b.value;}
应该是{$value = $value ||$b.value;}
{$value &&= $b.value;}
应该是{$value = $value &&$b.value;}
term
规则的第四个选项中的标签$term
不明确:可以指规则本身,也可以指term
后跟'¬'
{$value ||= $b.value;}
should be{$value = $value || $b.value;}
{$value &&= $b.value;}
should be{$value = $value && $b.value;}
- the label
$term
in the fourth alternative of theterm
rule is ambiguous: is could refer to the rule itself, or theterm
followed by'¬'
即,以下内容:
I.e., the following:
term returns [boolean value]
: ...
| '¬' term {$value = !$term.value;}
;
应该是:
term returns [boolean value]
: ...
| '¬' t=term {$value = !$t.value;}
;
进行这些更改后,以下测试类:
Having made those changes, the following test class:
import org.antlr.runtime.*;
public class Main {
public static void main(String[] args) throws Exception {
String source = "(1 & 0) | 1";
TestLexer lexer = new TestLexer(new ANTLRStringStream(source));
TestParser parser = new TestParser(new CommonTokenStream(lexer));
System.out.println(source + " = " + parser.code());
}
}
产生所需的输出:
java -cp antlr-3.3.jar org.antlr.Tool Test.g
javac -cp antlr-3.3.jar *.java
java -cp .:antlr-3.3.jar Main
(1 & 0) | 1 = true
这篇关于ANTLR 命题逻辑评估器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文