如何在Antlr4中为具有零参数的函数编写语法 [英] How to write grammer in Antlr4 for function with zero argument
问题描述
我正在使用带有语法的参数lexmer,如下面的lexer和parser:
I'm having function with arguments grammer like below lexer and parser:
MyFunctionsLexer.g4
lexer grammar MyFunctionsLexer;
FUNCTION: 'FUNCTION';
NAME: [A-Za-z0-9]+;
DOT: '.';
COMMA: ',';
L_BRACKET: '(';
R_BRACKET: ')';
WS : [ \t\r\n]+ -> skip;
MyFunctionsParser.g4
parser grammar MyFunctionsParser;
options { tokenVocab=MyFunctionsLexer; }
functions : function* EOF;
function : FUNCTION '.' NAME '(' (function | argument (',' argument)*) ')';
argument: (NAME | function);
但是在解析器中接受带参数的函数或带参数的函数作为函数(嵌套函数).我正在使用访客模式进行验证.但是现在,如果我不带任何参数传递函数,则会引发错误.在上面的解析器中如何接受零参数函数.
But in parser is accepting function with arguments or function with argument as function(nested function). I am using visitor pattern for validation. But now if I pass function with no arguments it is throwing error. How to accept function with zero argument in the above parser.
工作输入示例:
FUNCTION.toString(String)
不工作输入示例:
FUNCTION.getTimestamp()
推荐答案
function : FUNCTION '.' NAME '(' (function | argument (',' argument)*) ')';
首先,这里的function |
确实很奇怪.从表面上看,这意味着您可以仅以单个函数调用作为参数或任意多个argument
来调用函数.但是由于argument
本身已经包含function
作为替代,因此只是多余的.因此,我们通过删除该部分来简化规则:
First of all the function |
here is really odd. At the face of it, it would mean that you can call a function with only a single function call as its argument or with arbitrarily many argument
s. But since argument
itself already contains function
as an alternative, it's simply redundant. So let's simplify the rule by removing that part:
function : FUNCTION '.' NAME '(' (argument (',' argument)*) ')';
那为什么不匹配没有参数的函数调用呢?因为逗号前的argument
不是可选的. ',' argument
部分已应用了*
,因此它可以出现任意次-包括零次.但是第一个argument
没有任何修饰符,因此它必须存在.
So why does this not match function calls without arguments? Because the argument
before the comma is not optional. The ',' argument
part has a *
applied to it, so it can appear any number of times - including zero. But the first argument
doesn't have any modifiers, so it needs to be there.
那么我们该如何改变呢?鉴于我只是将问题确定为第一个参数不是可选的,所以人们首先想到的是通过直接在其后添加?
(即argument? (',' argument)*
)来使argument
为可选,但这也允许构造例如FUNCTION.f(,X)
,您可能不想这么做.
So how can we change that? Given that I just identified the problem as the first argument not being optional, one's first thought might be to just make the argument
optional by adding a ?
directly after it (i.e. argument? (',' argument)*
), but that would also allow constructions such as FUNCTION.f(,X)
, which you presumably don't want to allow.
相反,应将?
应用于整个参数列表,如下所示:
Instead you should apply ?
to the whole list of arguments, like this:
(argument (',' argument)*)?
这样,它可以匹配参数后跟零个或多个'逗号后跟参数'的实例"或不匹配.
That way it can match either "an argument followed by zero or more instances of 'comma followed by argument'" or nothing.
这篇关于如何在Antlr4中为具有零参数的函数编写语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!