Kishore R
Kishore R

Reputation: 43

Scala External DSL -- Multi line string literal

I am trying to define an external DSL using the scala parser combinators. I see that the 'stringLit' token parser does not accomodate multi line strings using the triple quotes. Is there something similar to a multiLineStringLit in the scala parser combinator world?

Thanks in advance, Kishore

Upvotes: 3

Views: 1040

Answers (1)

Travis Brown
Travis Brown

Reputation: 139038

Not that I'm aware of, but it's not too hard to write your own:

import scala.util.parsing.combinator._

object myParser extends JavaTokenParsers {
  def mlStringLiteral: Parser[String] = (
    "\"\"\"" +
    """(\n|[^"\p{Cntrl}\\]|\\[\\/bfnrt]|\\u[a-fA-F0-9]{4})*""" +
    "\"\"\""
  ).r
}

This is just stringLiteral with a couple of minor edits: I've changed the delimiter from " to """ and added \n to the character match.

scala> val s = "\"\"\"This is a multi-\nline string literal.\"\"\""
s: java.lang.String = 
"""This is a multi-
line string literal."""

scala> myParser.parseAll(myParser.mlStringLiteral, s)
res0: myParser.ParseResult[String] = 
[2.24] parsed: """This is a multi-
line string literal."""

It's not an exact match for Scala's implementation of multi-line string literals (you can't have an unescaped " in the string, for example), but it can easily be tweaked, and may work for you as it is.

Upvotes: 3

Related Questions