Question

I have (finally) completed a parser, which processes my DSL and translates it to my domain objects. Now I want to add some proper error handling, and I wish to add the line numbers to the errors reported by the parser.

The examples and answers I found here and here seem to indicate that I have to modify my domain objects to extend scala.util.parsing.input.Positional. The example is a bit too simplistic for my case, and (due to my inexperience) it seems my case doesn't quite fit this paradigm.

The main problem I have is that I do not want my domain objects to directly extend Positional. They are used elsewhere in the program that does not have anything to do with the parsing (the parser is just an extension of the program to create a different way to input the data). Also, I don't know how to handle cases which output String (or other classes which I don't have any control of). There is also the issue that my domain objects already extend other objects of the program, I can't simply change the hierarchy that way.

Is there any alternative way to handle this cleanly, without modifying the domain objects and coupling them with the Positional? (Apologies if I am asking something trivial that has to do with implementing traits etc. because I am still new to Scala)

No correct solution

OTHER TIPS

You could use a scala.util.matching.Regex.MatchIterator to build something like this

type Token = String

trait TokenIterator extends Iterator[Token] {
  def next: Token
  def hasNext: Boolean
  def pos: Int
}

class Tokenizer(regexStr: String, input: String) {
  val regex = regexStr.r

  def iterator: TokenIterator = new TokenIterator {
    val iter = regex.findAllIn(input)
    var pos = 0
    def next = {
      val n = iter.next
      pos = iter.start
      n
    }
    def hasNext = iter.hasNext
  }
}

val str = "3 + 4 - 5"
val iter = new Tokenizer("""d+|\S+?""", str).iterator

while(iter.hasNext) {
  val token = iter.next
  val pos = iter.pos
  println(pos + ": " + token)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top