我开发了一个Antlr3.4语法,它生成一个AST供以后解析。生成的解析器使用 Antlr 的 C 接口。当解析器遇到意外的标记时,它会添加
“树错误节点”到 AST 令牌流并继续处理输入。(内部“树错误节点”表示 ANTLR3_TOKEN_INVALID。)
当我将解析器的输出传递给 AST 解析器时,它会在"Tree Error Node"
. 无论如何处理 AST 流中的无效令牌?
我在用着:
- libantlr3c-3.4
- antlr3.4
我发现您可以覆盖树适配器方法“errorNode”以发出用户指定的令牌。然后可以在 AST 解析器中处理该令牌。
您需要使用上述方法覆盖 Match() 并执行解析器的恢复(这是 c# 伪代码):
public override object Match(IIntStream input, int ttype, BitSet follow)
{
if (needs recover)
{
... Recover from mismatch, i.e. skip until next valid terminal.
}
return base.Match(input, ttype, follow);
}
此外,您需要从不匹配的令牌中恢复:
protected override object RecoverFromMismatchedToken(IIntStream input, int ttype, BitSet follow)
{
if (needs recover)
{
if (unwanted token(input, ttype))
{
.. go to the next valid terminal
.. consume as if ok
.. return next valid token
}
if (missing token(input, follow))
{
.. go to the next valid terminal
.. insert missing symbol and return
}
.. othwerwise throw
}
.. call base recovery(input, ttype, follow);
}
如果还有其他问题,请告诉我。