0

I have a simple grammar defined below using Antlr 3:

grammar i;

@header {
package com.data;
}

null        : 'null';
true        : 'true';
false       : 'false';
value       : true | false | null | STRING | INTEGER | FLOAT;
elements    : (value (',' value)*)MINIMUMDIGIT;
STRING  : ('a'..'z'|'A'..'Z')+;
MINIMUMDIGIT    : ('0'..'9');
INTEGER : '0'..'9'+;
FLOAT       : INTEGER'.'INTEGER;
WS      : (' '|'\t'|'\f'|'\n'|'\r')+ {skip();}; // handle white space between keywords

When I try to do the interpretation of the elements in ANTLRWorks, the elements displays correct. However, I also a a NoViableAltException.

I have tried:

true

It displays true and then a NoViableAltException

I have true, true, true, true and it displays true,true,true,true and then a NoViableAltException.

Can you help where I am going wrong? Looking at many similar posts, but unable to find the solution to this problem. The Exception is shown in the graph during the interpretation and no Exception shown on the Console.

EDIT:

The user has to enter a single value, but it can follow multiple values separted by a comma each time. According to Antlr, Antlr allows you define a optional (?), zero or more (*) or one or more (+). There is no such thing as only one. So the MINIMUMDIGIT is used to control the only one.

Example:

insert      : 'INSERT INTO table' 'VALUES' '('elements')'';';

What I am trying to achive is when the insert is executed, elements has to have atleast one value or it could have multiple values. According to the syntax defined above, it allows zero or more.

As soon as I change the elements to:

elements : (value (',' value)*)+;

this does not work. When I enter comma, the comma displays. It also accepts values with no commas. The comma is necessary. That's why I introduced the MINIMUMDIGIT.

4

1 回答 1

0

根据 Antlr,Antlr 允许您定义一个可选的 (?)、零个或多个 (*) 或一个或多个 (+)。

同意。

没有只有一个这样的东西。

不对。默认情况下,引用的规则只匹配一次。因此,如果elements定义为elements: value;,则elements匹配一个且仅一个 value

同样,如果elementselements : (value (',' value)*);(没有尾随?+*),它将匹配以下每一行:

value
value , value
value , value , value

它将不匹配以下任何行:

(empty input)
value value
, value
value , , 

我认为你需要的只是elements: (value (',' value)*);.

于 2012-11-27T16:14:30.517 回答