rai*_*inz 2 java peg parboiled grappa
我是PEG解析的新手,并试图编写一个简单的解析器来解析出一个像"term1 OR term2 anotherterm"这样的表达式,理想情况下是一个看起来像这样的AST:
OR
-----------|---------
| |
"term1" "term2 anotherterm"
Run Code Online (Sandbox Code Playgroud)
我目前正在使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
谁能指出我正确的方向?
(格拉巴酒的作者......)
好吧,那么,你似乎想要的实际上是一个解析树.
最近有一个扩展到grappa(2.0.x +)开发,可以满足您的需求:https://github.com/ChrisBrenton/grappa-parsetree.
Grappa,默认情况下,只是"盲目地"匹配文本并且有一个堆栈可供使用,所以你可以拥有,例如:
public Rule oneOrOneOrEtc()
{
return join(one(), push(match())).using(or()).min(1));
}
Run Code Online (Sandbox Code Playgroud)
但是你的所有匹配都会在堆栈中......不太实用,但在某些情况下仍然可以使用(例如,参见sonar-sslr-grappa).
在您的情况下,你想要这个包.你可以用它来做到这一点:
// define your root node
public final class Root
extends ParseNode
{
public Root(final String match, final List<ParseNode> children)
{
super(match, children);
}
}
// define your parse node
public final class Alternative
extends ParseNode
{
public Alternative(final String match, final List<ParseNode> children)
{
super(match, children);
}
}
Run Code Online (Sandbox Code Playgroud)
这是最小的实现.然后你的解析器看起来像这样:
@GenerateNode(Alternative.class)
public Rule alternative() // or whatever
{
return // whatever an alternative is
}
@GenerateNode(Root.class)
public Rule root
{
return join(alternative())
.using(or())
.min(1);
}
Run Code Online (Sandbox Code Playgroud)
这里发生的是因为根节点在替代之前匹配,例如,如果你有一个字符串:
a or b or c or d
Run Code Online (Sandbox Code Playgroud)
那么根节点将匹配"整个序列",并且它将具有与a,b,c和d匹配的四个备选.
这里有完整的学分,请克里斯托弗·布伦顿首先提出这个想法!
| 归档时间: |
|
| 查看次数: |
259 次 |
| 最近记录: |