Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make scala parser fail

Tags:

scala

so I have something like this:

class MyParser extends JavaTokenParsers {
    var m = new HashMap[String,String]
    def store = ("var" ~> ident "=") ~ ident ^^ {
        case k ~ v => m += k -> v
    }
    def stored_val = ident ^^ {
        case k => m(k)
    }
}

And my problem is that what I really want to do is have the parser stored_val fail so that other parsers have the chance to match the input. But what happens now is that the map throws when it can't find the value.

I tried implementing stored_val like this:

def stored_val = ident => {
    case k => if (m.contains(k)) m(k) else failure("identifier not found")
}

But the problem with that is failure returns Parser[Nothing] which is a different type than String.

like image 641
Kevin Avatar asked Feb 08 '11 23:02

Kevin


1 Answers

You can use the ^? combinator which accepts a partial function (Scaladoc):

def stored_val: Parser[String] = ident ^? {
    case k if m.contains(k) => m(k)
}

I pushed a full example with tests to Github.

like image 72
lachdrache Avatar answered Oct 16 '22 00:10

lachdrache