Antlr(词法分析器):匹配正确的标记

发布于 2024-09-27 08:28:08 字数 551 浏览 1 评论 0原文

在我的 Antlr3 语法中,我有几个“重叠”的词法分析器规则,如下所示:

NAT: ('0' .. '9')+ ;
INT: ('+' | '-')? ('0' .. '9')+ ;
BITVECTOR: ('0' | '1')* ;

虽然像 100110123 这样的标记可以与多个规则匹配,但它是总是由上下文决定它必须是其中的哪一个。示例:

s: a | b | c ;
a: '<' NAT '>' ;
b: '{' INT '}' ;
c: '[' BITVECTOR ']' ;

输入 {17} 应匹配 {INT},但词法分析器已经确定 17 是 NAT 令牌。我怎样才能防止这种行为? backtrack 选项已设置为 true,但它似乎只影响解析器规则。

In my Antlr3 grammar, I have several "overlapping" lexer rules, like this:

NAT: ('0' .. '9')+ ;
INT: ('+' | '-')? ('0' .. '9')+ ;
BITVECTOR: ('0' | '1')* ;

Although tokens like 100110 and 123 can be matched by more than one of those rules, it is always determined by context which of them it has to be. Example:

s: a | b | c ;
a: '<' NAT '>' ;
b: '{' INT '}' ;
c: '[' BITVECTOR ']' ;

The input {17} should then match {, INT, and }, but the lexer has already decided that 17 is a NAT-token. How can I prevent this behavior? The backtrack option is already set to true, but it only seems to affect parser rules.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半岛未凉 2024-10-04 08:28:08

可能有一种复杂的方法可以使词法分析器对上下文敏感,但一般来说,这就是您希望解析器处理的事情,并且您希望词法分析器仅提供令牌流。我的建议是重构你的词法分析器以返回 DIGITSSIGN 并让你的解析器计算出上下文中的数字代表什么类型的数字。

There might be a complex way to make the lexer context-sensitive, but in general that's what you want the parser to take care of, and you want your lexer to just provide a stream of tokens. My recommendation is to refactor your lexer to return DIGITS and SIGN and let your parser work out what kind of number the digits represent by the context.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文