gpt4 book ai didi

java - ANTLR 命题逻辑求值器

转载 作者:行者123 更新时间:2023-11-30 09:21:20 25 4
gpt4 key购买 nike

我正在尝试在 ANTLR 中创建一个评估命题逻辑公式的语法。所以对于输入 (1 & 0) | 1,它应该返回true

我构建了以下内容:

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。有没有办法找出错误的位置或如何修复它?

最佳答案

有3个问题:

  • {$value ||= $b.value;} 应该是 {$value = $value || $b.value;}
  • {$value &&= $b.value;} 应该是 {$value = $value && $b.value;}
  • term 规则的第四个选项中的标签 $term 是不明确的:它可以引用规则本身,或者 term后跟 '¬'


即,以下内容:

term returns [boolean value]
: ...
| '¬' term {$value = !$term.value;}
;

应该是:

term returns [boolean value]
: ...
| '¬' t=term {$value = !$t.value;}
;

进行了这些更改后,下面的测试类:

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

关于java - ANTLR 命题逻辑求值器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17050433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com