[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: seeking an OO or functional parser generator for Java
Lauri Alanko wrote:
>It has been done. It is not pretty.
>
>http://citeseer.nj.nec.com/dijkstra01lazy.html
>http://www.cs.uu.nl/~atze/Programming/JPC/readme.html
>
>
the last link:
> The basic idea of writing a parser in Java using the parsercombinator
> package is to write a parser using the errorcorrecting
> parsercombinators <http://www.cs.uu.nl/groups/ST/Software/UU_Parsing/>
> written in Haskell, checking them for correctness and then handcompile
> the resulting parser to Java.
I was hoping for perhaps a slightly more java-esq solution. Something
like (completely untested)
class Parser {
Object parse(TokenIterator ti) { throw new ParseFailed(); }
}
class TokenParser extends Parser {
String str;
TokenParser(String s) { str = s; }
Object parse(TokenIterator ti) {
Token t = ti.next();
if (!t.toString().equals(str))
ti.unread();
throw new ParseFailed();
}
return t;
}
}
class OrParser extends Parser {
Parser first,second;
OrParser(Parser f, Parser s) { first = f; second =s; }
Object parse(TokenIterator ti) {
try { return first.parse(ti) }
catch (ParseFailed e) { return second.parse(); }
}
}
...
// To parse the grammar "foo" | "bar"
OrParser op = new OrParser(new TokenParser("foo"), new TokenParser("bar"));
// now will only parse "bar"
op.first = new Parser();
...
Appart from casting from Object, it's not entirely horrible. A more
advanced solution would build up lookahead sets and guards.