2

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?

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156

1 Answers1

6

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?

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
  • actually I was completely NOOB, I had some other tokens defined and one of them was matching. So I guess in the lexer it was tokenizing it, which then meant when it was parsing it would see the wrong token ( even though it could parse the characters ) – Keith Nicholas Dec 22 '10 at 20:36
  • and seriously, you should write a C# tutorial, your answers on here about antlr and C# have been a great...no.....AWESOME help! – Keith Nicholas Dec 22 '10 at 20:41
  • @Keith, yeah, I commented about the ANTLR & C# tutorial before to you (which I removed since I made a bit of a vague suggestion in that same comment...). It's still my planning to do so. When I do, I will post it here on SO as a Q&A like I did with my (short) [explanation on ANTLR's semantic predicates](http://stackoverflow.com/questions/3056441/what-is-a-semantic-predicate-in-antlr). – Bart Kiers Dec 22 '10 at 20:47