2

我有一个组合的 ANTLR 语法,它将寻找特定的标记/标记组合。有些代币可以使用 0 次或 1 次。我想将“找到”或“未找到”值存储到这些标记的哈希图中。我已经知道,在令牌可用的情况下如何做到这一点。但是对于尚未找到的令牌,我该怎么做。
以下示例显示它非常简化:

grammar Expr;

@header {
import java.util.HashMap;
}

@members {
HashMap<String,String> memory = new HashMap<String,String>();
}

statements: ONE  
      (WS TWO {memory.put("two","found");})? 
      WS THREE EOF;    

ONE: 'one';
TWO: 'two';
THREE: 'three';
WS: ' ';

是否有可能直接在这个语法中找出“TWO”没有找到,因此给 HashMap 赋予了不同的值?

memory.put("two","not found");
4

1 回答 1

2

是否有可能直接在这个语法中找出“TWO”没有找到,因此给 HashMap 赋予了不同的值?

当然,像这样:

statements
 : ONE WS ( TWO WS THREE EOF {memory.put("two","found");}
          | THREE EOF        {memory.put("two","not found");}
          )
 ;    

编辑

或者,如果您有更多可选标记(TWO,THREE并且FOUR是可选的),请执行以下操作:

statements
 : ONE (WS TWO memory.put("two","found");     | memory.put("two","not found");) 
       (WS THREE memory.put("three","found"); | memory.put("three","not found");) 
       (WS FOUR memory.put("four","found");   | memory.put("four","not found");) 
   EOF
 ;

或者这样的东西也应该起作用:

statements
 : ONE (WS TWO)? (WS THREE)? (WS FOUR)?
   {
     memory.put("two", $TWO.text == null ? "not found" : "found");
     memory.put("three", $THREE.text == null ? "not found" : "found");
     memory.put("four", $FOUR.text == null ? "not found" : "found");
   }
 ;
于 2013-03-01T19:09:40.697 回答