如何管理 ANTLR 中的可选空格? [英] How do I manage optional whitespace in ANTLR?

查看:22
本文介绍了如何管理 ANTLR 中的可选空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析 ANTLR 中的数据文件 - 它具有可选的空格,例如

I am trying to parse a data file in ANTLR - it has optional whitespace exemplified by

 3 6
  97   12
 15 18

下面显示了该行的起点和终点.末尾有一个换行符,没有制表符.

The following shows where the line starts and ends are. There is a newline at the end and there are no tabs.

^ 3 6$
^  97   12$
^ 15 18$
^

我的语法是:

lines   :   line+;
line    :   ws1 {System.out.println("WSOPT :"+$ws1.text+":");} 
                num1 {System.out.println("NUM1 "+$num1.text);} 
                ws2 {System.out.println("WS :"+$ws2.text+":");}
                num2 {System.out.println("NUM2 "+$num2.text);} 
                NEWLINE
    ;
num1    :    INT    ;
num2    :    INT    ;
ws1 :   WSOPT;
ws2 :   WS;

INT     : '0'..'9'+;
NEWLINE :    '\r'? '\n';
//WS    :   (' '|'\t' )+ ;
WS  :   (' ')+ ;
WSOPT   :   (' ')* ;

这给了

line 1:0 mismatched input ' ' expecting WSOPT
WSOPT :null:
NUM1 3
WS : :
NUM2 6
line 2:0 mismatched input '   ' expecting WSOPT
WSOPT :null:
NUM1 97
WS :   :
NUM2 12
BUILD SUCCESSFUL (total time: 1 second)

(即前导 WS 未被识别,最后一行被遗漏).

(i.e. the leading WS has not been recognised and the last line has been missed).

我想解析没有空格开头的行,例如:

I would like to parse lines which start without whitespace, such as:

^12    34$
^ 23 97$

但我随后收到如下错误:

but I then get errors such as:

line 1:0 required (...)+ loop did not match anything at input ' '

我很欣赏在 ANTLR 中解析 WS 的一般解释.

I'd appreciate general explanations of parsing WS in ANTLR.

EDIT @jitter 有一个有用的答案 - {ignore=WS} 没有出现在我正在使用的Definitive ANTLR reference"书中,所以很明显一个棘手的领域.

EDIT @jitter has a useful answer - {ignore=WS} does not appear in the "Definitive ANTLR reference" book that I am working from so it is clearly a tricky area.

仍然需要帮助我已将其修改为:

lines   :   line line line;
line
options { ignore=WS; }
        :
                ws1  {System.out.println("WSOPT :"+$ws1.text+":");} 
                num1 {System.out.println("NUM1 "+$num1.text);} 
                ws2  {System.out.println("WS :"+$ws2.text+":");}
                num2 {System.out.println("NUM2 "+$num2.text);} 
                NEWLINE
    ;

但得到错误:

illegal option ignore

EDIT 显然这已从 V3 中删除:http://www.antlr.org/pipermail/antlr-interest/2007-February/019423.html

EDIT apparently this has been removed from V3: http://www.antlr.org/pipermail/antlr-interest/2007-February/019423.html

推荐答案

我已经设法使用词法分析器结构来实现这一点,例如:

I have managed to get this working using lexer constructs such as:

WS  :   (' ')+ {skip();};

WSOPT   :       (' ')* {skip();};

但不在新行中.然后在解析器结构中,例如:

but not in the NEWLINE. Then in the parser constructs such as:

num1 num2 NEWLINE;

关键是去除词法分析器中除 NEWLINE 之外的所有 WS.

The key was to strip all WS in the lexer except the NEWLINE.

这篇关于如何管理 ANTLR 中的可选空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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