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

查看:40
本文介绍了ANTLR:将 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天全站免登陆