2

我对 Antlr 2.X 和 Antlr 3.1.X CSharp 和 python 目标非常熟悉。

但是,我现在被迫将 Antlr 3 C 目标用于项目。

我的问题是如何报告语法或树语法中的错误。

考虑一个匹配令牌的规则,我们将其放入映射中。我们要确保令牌是唯一的。通常,如果令牌已经在地图中,我会抛出异常并在 hte 解析器之外捕获异常以报告错误。

什么是 Antlr C 运行时等效于以下规则?

token_match: ID 
{
    if(mp.find($ID.Text))
        throw std::exception("Non unique token found");
}
4

1 回答 1

2

我建议使用您自己的方法来显示语义错误。但是,如果您需要为此留在 ANTLR:

首先,如果要创建自定义异常类型,则必须创建自己的错误处理程序。查看 antlr3baserecognizer.c:1000 的原文。

static void         
displayRecognitionErrorNew  (pANTLR3_BASE_RECOGNIZER recognizer,
                             pANTLR3_UINT8 * tokenNames)
{
...
    switch  (ex->type)
    {
    case    ANTLR3_UNWANTED_TOKEN_EXCEPTION:
...
    case    NUTF_EXCEPTION:
      printf("Non unique token found");
      break;

然后编写一些函数或规则代码来处理异常结构。查看 antlr3baserecognizer.c:325 以设置您的异常。

ex = antlr3ExceptionNew(ANTLR3_RECOGNITION_EXCEPTION,
                       (void *)ANTLR3_RECOGNITION_EX_NAME,
                       NULL,
                       ANTLR3_FALSE);

ex->type                = NUTF_EXCEPTION
ex->line                = ins->getLine (ins);
ex->charPositionInLine  = ins->getCharPositionInLine    (ins);  
ex->index               = is->index (is);
ex->streamName          = ins->fileName;
ex->message             = "That was totally unexpected";

接下来,您需要在检测到错误时实际抛出异常。我认为这样做的唯一方法是覆盖 mismatch() 添加您的代码并从您的规则中调用它。

static  void
mismatchNew(pANTLR3_BASE_RECOGNIZER recognizer, ANTLR3_UINT32 ttype, pANTLR3_BITSET_LIST follow)
{
  ...
}

最后告诉 ANTLR 使用你的新功能。

@parser::apifuncs {
  RECOGNIZER->displayRecognitionError       = displayRecognitionErrorNew;
  RECOGNIZER->antlr3RecognitionExceptionNew = antlr3RecognitionExceptionNewNew;
  RECOGNIZER->mismatch                      = mismatchNew;
}
于 2011-02-21T04:16:40.760 回答