1

So, I am trying to learn me a bit of ruby, a bit of TDD and a bit of Treetop.

I have the following grammar for parsing string literals:

grammar Str
  rule string
    '"'
    (
      !'"' . / '\"'
    )*
    '"'
  end
end

And the following test method:

def test_strings
  assert @parser.parse('"Hi there!"')
  assert !@parser.parse('"This is not" valid')
  assert @parser.parse('"He said, \"Well done!\""')
end

The third test (the one with the backslashes) does not pass (the string is not parsed): why?

Thanks!

Rom1
  • 3,167
  • 2
  • 22
  • 39

1 Answers1

2

You need to swap the order of the escaped-quote check:

(
  '\"' / !'"' .
)*

As another example, your grammar would also match this:

"he said, \"

Flipping the check correctly fails that as well.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • Thanks, that was it ! Funnily enough, the example I posted was the one that features in the official documentation [here](http://treetop.rubyforge.org/pitfalls_and_advanced_techniques.html) – Rom1 Dec 17 '11 at 17:57
  • Just a note: the example is now fixed int the Treetop website. – Rom1 Dec 19 '11 at 11:06