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

查看:508
本文介绍了忽略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天全站免登陆