ANTLR:将NULL解析为函数名称和参数 [英] ANTLR: parse NULL as a function name and a parameter

查看:179
本文介绍了ANTLR:将NULL解析为函数名称和参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在我的参数 null (值 null )和函数名称​​ 中同时使用"NULL"语法.参见以下简化示例:

I would like to be able to use 'NULL' as both a parameter (the value null) and a function name in my grammar. See this reduced example :

grammar test;

expr
  : value # valueExpr
  | FUNCTION_NAME '(' (expr (',' expr)* )* ')' # functionExpr
  ;


value
  : INT
  | 'NULL'
  ;

FUNCTION_NAME
  : [a-zA-Z] [a-zA-Z0-9]*
  ;


INT: [0-9]+;

现在,尝试解析:

NULL( 1 )

解析树的结果失败,因为它解析NULL作为值而不是函数名.

Results in the parse tree failing because it parses NULL as a value, and not a function name.

理想情况下,我甚至应该能够解析 NULL(NULL) ..

Ideally, I should even be able to parse NULL(NULL)..

您能告诉我这是否可行吗?如果可以,如何实现?

Can you tell me if this is possible, and if yes, how to make this happen?

推荐答案

语法中的'NULL'字符串定义了隐式标记类型,等效于在其中添加一些内容:

That 'NULL' string in your grammar defines an implicit token type, it's equivalent to adding something along this:

NULL: 'NULL';

在词法分析器规则的开头.当令牌匹配多个词法分析器规则时,将使用第一个规则,因此在语法中,隐式规则将获得优先级,并且您将获得类型为'NULL'的令牌.

At the start of the lexer rules. When a token matches several lexer rules, the first one is used, so in your grammar the implicit rule get priority, and you get a token of type 'NULL'.

一个简单的解决方案是为函数名称引入解析器规则,如下所示:

A simple solution would be to introduce a parser rule for function names, something like this:

function_name: FUNCTION_NAME | 'NULL';

,然后在您的 expr 规则中使用它.但这似乎很脆弱,如果 NULL 并不是语法中的关键字.还有其他解决方案,但是由于我不知道您希望语法如何扩展,因此我不确定该建议什么.

and then use that in your expr rule. But that seems brittle, if NULL is not intended to be a keyword in your grammar. There are other solution to this, but I'm not quite sure what to advise since I don't know how you expect your grammar to expand.

但是另一种解决方案可能是将 FUNCTION_NAME 重命名为 NAME ,摆脱'NAME'令牌类型,然后重写像这样expr :

But another solution could be to rename FUNCTION_NAME to NAME, get rid of the 'NAME' token type, and rewrite expr like that:

expr
  : value # valueExpr
  | NAME '(' (expr (',' expr)* )* ')' # functionExpr
  | {_input.LT(1).getText().equals("NULL")}? NAME # nullExpr
  ;

语义谓词在这里负责名称比较.

A semantic predicate takes care of the name comparison here.

这篇关于ANTLR:将NULL解析为函数名称和参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆