ANTLR命题逻辑评估器

时间:2013-06-11 17:44:15

标签: java eclipse antlr evaluate

我正在尝试在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 。无论如何都要找出错误的位置或如何解决它?

1 个答案:

答案 0 :(得分:1)

有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