我为 bool 表达式创建了一个语法,现在我正在尝试实现访问者来评估它。
有人告诉我们,没有必要通过语义分析使语法词法分析器和解析器规则过于复杂,因为从访问者那里提供有意义的错误消息要好得多。
所以我正在尝试检查访问者中的类型一致性、日期正确性等。令我惊讶的是,除了抛出异常之外,没有其他方法(至少我没有看到)报告来自访问者的错误。如果我抛出异常,我将无法继续进行表达式验证并立即检测到所有错误。此外,我必须以某种方式捕获所有解析异常类型(我应该如何知道它们?)。总而言之,异常抛出似乎不是正确的解决方案。
您能告诉我如何计划在访问者遍历期间报告表达式语义错误吗?
最佳答案
由于您定义了访问者,因此您可以创建并传递一个对象,它将向其报告错误。
简单的例子:
public interface IErrorReporter
{
void ReportError(ParserRuleContext context, string error);
}
public class ValidationVisitor : YourLanguageBaseVisitor<Whatever>
{
private readonly IErrorReporter _errorReporter;
public ValidationVisitor(IErrorReporter errorReporter)
{
_errorReporter = errorReporter;
}
public override Whatever VisitSomeNode(YourLanguageParser.SomeNodeContext context)
{
if (context.GetText() != "expected")
_errorReporter.ReportError(context, "Invalid text");
return Visit(context.someSubNode());
}
}
然后像这样验证:
var parseTree = DoTheParsingStuff();
// Implement that one, store the errors in a list
var errorReporter = new SimpleErrorReporter();
new ValidationVisitor(errorReporter).Visit(parseTree);
if (errorReporter.Errors.Count > 0)
{
// Display errors
}
ParserRuleContext
可用于定位错误发生的位置(行/列等),否则您可以实现任何适合您的错误报告需要的内容。
旁注:如果您计划有很多访客,那么 building an AST然后然后基于此进行验证从长远来看可能是有益的。您需要决定是否值得。
关于c# - 如何报告来自 ANTLR 4 Visitor 的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32381068/