This page is no longer maintained — Please continue to the home page at www.scala-lang.org

JavaTokenParsers.stringLiteral

No replies
Travis Vachon
Joined: 2009-03-29,
User offline. Last seen 42 years 45 weeks ago.

Hi folks

I've noticed come across some unexpected behavior with
JavaTokenParsers.stringLiteral and was hoping someone on this list
might be able to help.

I've implemented a JSON parser per the tutorial in "Programming in
Scala", but noticed that JSON strings are being parsed into Scala
Strings with leading and trailing quotes (").

To be more precise:

scala> import scala.util.parsing.combinator._
import scala.util.parsing.combinator._

scala> class S extends JavaTokenParsers
defined class S

scala> val p = new S
p: S = S@4072e154

scala> p.parseAll(p.stringLiteral, """ "one" """).get
res0: String = "one"

scala> p.parseAll(p.stringLiteral, """ "one" """).get.charAt(0)
res1: Char = "

scala> p.parseAll(p.stringLiteral, """ "one" """).get == "one"
res2: Boolean = false

scala> p.parseAll(p.stringLiteral, """ "one" """).get == "\"one\""
res3: Boolean = true

This behavior seems counter to the behavior suggested in PiS, and as a
result seems like a bug. Is it? If not, is anyone familiar with the
motivation for the current behavior?

As is, I need to implement an additional helper method like:

def string: Parser[String] =
stringLiteral ^^ (s => new RichString(s.slice(1, s.length() - 1)))

(though this is probably less elegant than it could be)

Thoughts?

Thanks!

Travis Vachon

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland