除了它本身在一条线上之外,如何使`\ n`显着?

时间:2015-06-07 15:57:02

标签: antlr antlr4

以下是我的尝试:

parse : statement (NL statement)* EOF ;

statement : assignment '.' #assignmentStatement
          | empty_line     #emptyLineStatement
          ;

// bunch of stuff omitted for brevity

empty_line : WS* NL+ ;          // want to ignore empty lines
WS : (' '|'\r'|'\t')+ -> skip ; // ignore whitespace
NL : '\n';                      // new line is significant

这是我的测试输入:

PI -> 3.14159265359.

sqr(x) x * x.
z -> sqr(x:3).

circumference(r) PI * sqr(x:r).

fib(x) fib(x:x-1) + fib(x:x-2).
fib(x:2) 1.
fib(x:1) 1.
fib(x:0) 0.

我从解析器中收到以下错误:

line 2:0 no viable alternative at input '\n'
line 5:0 no viable alternative at input '\n'
line 7:0 no viable alternative at input '\n'

以及Visitor的以下输出:

PI = 3.14159265359;;
ASSIGN sqr WITH x FROM [] RETURNING x TIMES x;
ASSIGN z AS CALL sqr WITH x = 3;
ASSIGN circumference WITH r FROM [] RETURNING PI TIMES CALL sqr WITH x = r;
ASSIGN fib WITH x FROM [] RETURNING CALL fib WITH x = x MINUS 1 PLUS CALL fib WITH x = x MINUS 2;
IF fib MATCHES x = 2 RETURN 1;
IF fib MATCHES x = 1 RETURN 1;
IF fib MATCHES x = 0 RETURN 0

如果我删除空行,则不会产生解析器错误,并且所有内容都按预期进行解析:

PI -> 3.14159265359.
sqr(x) x * x.
z -> sqr(x:3).
circumference(r) PI * sqr(x:r).
fib(x) fib(x:x-1) + fib(x:x-2).
fib(x:2) 1.
fib(x:1) 1.
fib(x:0) 0.

预期输出:

PI = 3.14159265359;;
ASSIGN sqr WITH x FROM [] RETURNING x TIMES x;
ASSIGN z AS CALL sqr WITH x = 3;
ASSIGN circumference WITH r FROM [] RETURNING PI TIMES CALL sqr WITH x = r;
ASSIGN fib WITH x FROM [] RETURNING CALL fib WITH x = x MINUS 1 PLUS CALL fib WITH x = x MINUS 2;
IF fib MATCHES x = 2 RETURN 1;
IF fib MATCHES x = 1 RETURN 1;
IF fib MATCHES x = 0 RETURN 0

我尝试了empty_line规则的各种变体,但它从未改变过,所以我遗漏了一些非常基本的东西。

如何解析只有\n或全whitespace\n的空行?

1 个答案:

答案 0 :(得分:0)

解决方案:

我改变了:

NL : '\n' ;

为:

NL : '\n'+ ;

并且错误消失了!

注意:

这并未解决将空行匹配为重要行的能力。