Keith Nicholas
Keith Nicholas

Reputation: 44288

How to solve a problem with ANTLR mismatch input

given the grammar

test    : 'test' ID '\n' 'begin' '\n'  'end' '\n' -> ^(TEST ID);

ID  :   ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*
    ;

and a test string of

"test blah\n begin\n end\n"

resulting in

line 1:0 mismatched input 'test blah\\n begin\\n end\\n' expecting 'test'
<mismatched token: [@0,0:21='test blah\\n begin\\n end\\n',<12>,1:0], resync=test blah
 begin
 end
>

whats gone wrong here?

Upvotes: 2

Views: 2301

Answers (1)

Bart Kiers
Bart Kiers

Reputation: 170148

When you use '\n' in your grammar rules, you're not matching a backslash+n but a new line character. And it looks like your input does not contain new line characters but backslash+n's.

So, my guess is you need to either change your test rule into:

test    
  : 'test' ID '\\n' 'begin' '\\n'  'end' '\\n'
  ;

resulting in the parse-tree:

alt text

or leave your test rule as is but change your input into:

test blah
begin
end

resulting in the parse-tree:

alt text

If that is not the case, could you post a SSCCE: a small, full working demo that I (or someone else can run) that shows this error?

Upvotes: 6

Related Questions