Antlr4:使用双点解析点尾浮点 [英] Antlr4: parse dot-ending float with double-dots

查看:132
本文介绍了Antlr4:使用双点解析点尾浮点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用点尾浮点数和双点测距数组来解析句子,但是无法做到这一点.

I'm trying to parse sentence with dot-ending float and double-dots ranging array, but cannot make it.

这是我的语法文件

grammar foo;

Digits
    :   [0-9]+
    ;

Real
    :   Digits* '.' Digits+
    |   Digits+ '.' Digits*
    ;

Range
    :   '..'
    ;

Whitespace
    :   [ \t]+
        -> skip
    ;

Newline
    :   (   '\r' '\n'?
        |   '\n'
        )
        -> skip
    ;

range
    :   Digits Range Digits
    ;

and(名为 foo.c 的文件)

and(file named foo.c)

代码1:

1..2

代码2:

1 ..2

我使用以下代码进行编译和测试:

I use following to compile and test:

antlr4 foo.g4
javac foo*.java
grun foo range -gui foo.c

代码1将出现错误:

line 1:2 token recognition error at: '. '
line 1:0 extraneous input '1.' expecting Digits
line 1:5 mismatched input '<EOF>' expecting '..'

但是我可以使用代码2来实现.

However I can make it with code 2.

添加额外的空间可以使它正确,但是我希望有一种语法可以解析代码1而无需额外的空间.

Adding extra space makes it correct, but I want to have a grammar that can parse code 1 without extra space.

推荐答案

这是ANTLR的词法分析器的工作方式:它尝试匹配尽可能多的字符.因此,输入 1..2 会生成2个 Real 令牌 1. .2 ,而不是3个令牌 Digits Range Digits .

That is how ANTLR's lexer works: it tries to match as much characters as possible. So the input 1..2 produces 2 Real tokens 1. and .2, and not the 3 tokens Digits, Range and Digits.

要创建3个令牌,您必须添加

To create 3 tokens, you will have to add a predicate in your lexer grammar. Try something like this:

FLOAT
 : [0-9]+ '.' {_input.LA(1) != '.'}?
 | [0-9]* '.' [0-9]+
 ;

INT
 : [0-9]+
 ;

RANGE
 : '..'
 ;

SPACE
 : [ \t\r\n] -> skip
 ;

如果我根据上述规则创建一个词法分析器,并将其输入为"1 2. .34 56..7 8.99999" ,则会得到以下标记:

If I create a lexer from the rules above, and feed it the input "1 2. .34 56..7 8.99999", I get the following tokens:

INT        '1'
FLOAT      '2.'
FLOAT      '.34'
INT        '56'
RANGE      '..'
INT        '7'
FLOAT      '8.99999'

这篇关于Antlr4:使用双点解析点尾浮点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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