2

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

4

1 回答 1

2

有3个问题:

  • {$value ||= $b.value;}应该{$value = $value || $b.value;}
  • {$value &&= $b.value;}应该{$value = $value && $b.value;}
  • $term规则的第四个选项中的标签term不明确:is 可以引用规则本身,或者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
于 2013-06-11T18:15:54.867 回答