Ignoring C-style comments in a Scala combinator parser
Asked Answered
T

1

9

What is the most simple way to make my parser respect (ignore) C-style comments. I'm interested in both comment types, though a solution for only one type is also welcome.

I'm currently simply extending JavaTokenParsers.

Tecumseh answered 10/5, 2011 at 15:42 Comment(1)
which parser library are you using?Armenta
F
12

You can use a simple regular expression, as long as you don't nest comments. Put it inside whiteSpace:

scala> object T extends JavaTokenParsers {
     |    protected override val whiteSpace = """(\s|//.*|(?m)/\*(\*(?!/)|[^*])*\*/)+""".r
     |    def simpleParser = ident+
     | }
defined module T

scala> val testString = """ident // comment to the end of line
     | another ident /* start comment
     | end comment */ final ident"""
testString: java.lang.String = 
ident // comment to the end of line
another ident /* start comment
end comment */ final ident

scala> T.parseAll(T.simpleParser, testString)
res0: T.ParseResult[List[String]] = [3.27] parsed: List(ident, another, ident, final, ident)
Fulfill answered 10/5, 2011 at 18:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.