gpt4 book ai didi

antlr - 如何使用 antlr 语法定义重复固定次数的模式规则

转载 作者:行者123 更新时间:2023-12-04 15:02:38 36 4
gpt4 key购买 nike

我知道“+”、“?”和 '*'。但是,如果我希望某事重复 5 次,该怎么办?例如,如果标识符必须是长度为 5 的十六进制数字符串?

更具体地说,我正在考虑定义一个无限长度的通用词法分析器规则,然后在解析时计算它重复了多少次,如果等于 5,则将其重命名为另一种类型的标记,但是如何我这样做?或者有什么简单的方法?

最佳答案

at parsing time count how many time it repeated, if it equals to 5, then rename it as another type of token, but how can I do this? Or is there some easy way?



是的,您可以使用消除歧义的语义谓词 ( explanation ) 来做到这一点:
grammar T;

parse
: (short_num | long_num)+ EOF
;

short_num
: {input.LT(1).getText().length() == 5}? NUM
;

long_num
: {input.LT(1).getText().length() == 8}? NUM
;

NUM
: '0'..'9'+
;

SP
: ' ' {skip();}
;

它将解析输入 12345 12345678 如下:

enter image description here

但是您也可以根据匹配文本的某些属性更改词法分析器中标记的类型,如下所示:
grammar T;

parse
: (SHORT | LONG)+ EOF
;

NUM
: '0'..'9'+
{
if(getText().length() == 5) $type = SHORT;
if(getText().length() == 8) $type = LONG;
// when the length is other than 5 or 8, the type of the token will stay NUM
}
;

SP
: ' ' {skip();}
;

fragment SHORT : ;
fragment LONG : ;

这将导致相同的输入被解析如下:

enter image description here

关于antlr - 如何使用 antlr 语法定义重复固定次数的模式规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9594573/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com