Jessica Kesey
Jessica Kesey

Reputation: 3

ANTLR4 Grammar extraneous / mismatched input error

I would like to declare a string which contains any character in my grammar, but doesn't works.

Here is my grammar: Syrius.g4

When I run it, I got the following error:

$ grun Syrius program
string test = "testString";
line 1:6 extraneous input ' ' expecting ID
line 1:11 mismatched input ' ' expecting ';'

What could be the problem with the grammar?

Upvotes: 0

Views: 283

Answers (1)

quepas
quepas

Reputation: 1003

Explanation

Your token STR : .; will match any character. STR is defined before WS lexeme thus, it will consume all the whitespace characters instead. When parsing string test = "testString"; the lexer will produce sequence of these tokens: string, STR, ID, ... and so on. But the parser is looking for a declaration rule which consists of string, ID, ... tokens.

Solution

Define STR token properly. Use this token in declaration parser rule:

STR : '"' .*? '"';
// (...)
declaration
    : 'int' ID ('=' INTEGER)? ';'
    | 'string' ID ('=' STR)? ';'
    ;

Upvotes: 1

Related Questions