我是 PEG 解析的新手,并试图编写一个简单的解析器来解析一个表达式,例如:“term1 OR term2 anotherterm”,理想情况下,它看起来像一个 AST:
OR
-----------|---------
| |
"term1" "term2 anotherterm"
我目前正在使用 Grappa ( https://github.com/fge/grappa ),但它甚至不匹配更基本的表达式“term1 OR term2”。这就是我所拥有的:
package grappa;
import com.github.fge.grappa.annotations.Label;
import com.github.fge.grappa.parsers.BaseParser;
import com.github.fge.grappa.rules.Rule;
public class ExprParser extends BaseParser<Object> {
@Label("expr")
Rule expr() {
return sequence(terms(), wsp(), string("OR"), wsp(), terms(), push(match()));
}
@Label("terms")
Rule terms() {
return sequence(whiteSpaces(),
join(term()).using(wsp()).min(0),
whiteSpaces());
}
@Label("term")
Rule term() {
return sequence(oneOrMore(character()), push(match()));
}
Rule character() {
return anyOf(
"0123456789" +
"abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"-_");
}
@Label("whiteSpaces")
Rule whiteSpaces() {
return join(zeroOrMore(wsp())).using(sequence(optional(cr()), lf())).min(0);
}
}
谁能指出我正确的方向?