忽略 Antlr4 中的空格(在某些部分) [英] Ignoring whitespace (in certain parts) in Antlr4

查看:77
本文介绍了忽略 Antlr4 中的空格(在某些部分)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 antlr 不太熟悉.我使用的是第 4 版,并且我有一个语法,其中空格在某些部分并不重要(但在其他部分可能很重要,或者更确切地说是运气).

I am not so familiar with antlr. I am using version 4 and I have a grammar where whitespace is not important in some parts (but it might be in others, or rather its luck).

假设我们有以下语法

grammar Foo;
program : A* ;
A  : ID '@' ID '(' IDList ')' ';' ;
ID : [a-zA-Z]+ ;
IDList : ID (',' IDList)* ;
WS : [ \t\r\n]+ -> skip ;

和一个测试输入

foo@bar(X,Y);
foo@baz  ( z,Z) ;

第一行被正确解析而第二行没有.我不想用空格不相关的地方来玷污我的规则,因为我的实际语法比玩具示例更复杂.如果不清楚部分 ID'@'ID 不应有空格.任何其他位置的空白都应该无关紧要.

The first line is parsed correctly whereas the second one is not. I don't want to polute my rules with the places where whitespace is not relevant, since my actual grammar is more complicated than the toy example. In case it's not clear the part ID'@'ID should not have a whitespace. Whitespace in any other position shouldn't matter at all.

推荐答案

ID '@' ID 定义为词法标记而不是解析器标记.

Define ID '@' ID as lexer token rather than as parser token.

A  : AID '(' IDList ')' ';' ;

AID : [a-zA-Z]+ '@' [a-zA-Z]+;

其他选项

  • 启用/禁用令牌流中的空格,例如这里
  • 使用词法分析器模式启用/禁用空格(可能是一个问题,因为词法分析器模式是在上下文中触发的,这在您的情况下不容易确定)

这篇关于忽略 Antlr4 中的空格(在某些部分)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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