标记的 ANTLR 语法表达式求值,可以使用 0 次或 1 次

标签 antlr grammar

我有一个组合的 ANTLR 语法,它应该寻找特定的标记/标记组合。有些 token 可以使用 0 次或 1 次。 我想将“找到”或“未找到”值存储到这些 token 的 HashMap 中。我已经知道,在 token 可用的情况下如何执行此操作。但是对于尚未找到的 token 我该如何做。
以下示例显示它非常简化:

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");

最佳答案

Is there a possibility to find out directly within this grammar, that "TWO" was not found and therefore put a different value to the HashMap?

当然,像这样:

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

编辑

或者,如果您有更多可选 token (TWOTHREE4 是可选的),请执行以下操作:

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");
   }
 ;

关于标记的 ANTLR 语法表达式求值,可以使用 0 次或 1 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15163846/

相关文章:

parsing - ANTLR语法: parser- and lexer literals

java - ANTLR4:消耗所有剩余输入直到 EOF

python - lark-parser 缩进 DSL 和多行文档字符串

parsing - 手动解析简单语法

Java解析器重命名变量

javascript - 为什么 antlr4 在 LT 上会卡住!*

python - 在 antlr4 python3 目标中将 java 转换为 python

antlr - 解析器规则中不能使用范围元素?

Linux shell : unexpected EOF while looking for matching `"'

parsing - 规范语法中的结构差异