求生成C代码时非常简单的ANTLR错误处理示例

发布于 2024-08-17 00:00:59 字数 572 浏览 3 评论 0原文

我想生成C代码。我不会一次一行地从输入文件中读取(例如,编译器可能会这样做)。相反,我将在用户输入到达时对其进行解析,一次一行。

我更愿意检测并处理词法分析器/解析器中的错误输入,例如,

/* lexer tokens */
foo : "FOO";
bar : "BAR";
baz : "BAZ";
/* grammar*/
grammar : foo "=" BAZ 
        | foo "=" BAR 
        | <some non-existent Antrl-else> :  {printf(stderr, "bad input\n");}
        ;

好吧,如果我无法在词法分析器/解析器中捕获它,似乎我需要使用 displayRecognitionError() 但如何??

谁能给我指出一个非常简单的示例,它生成 C 代码并显示无效输入的一些错误处理?

谢谢!


好吧,赏金,耶!

但只是为了获得真正的、有效的答案,以及真正的、有效的代码。没有 wxamp 就没有“使用方法 X()”。

I want to generate C code. I will not be reading from an input file, one line at a time (as, for instance, a compiler might). Rather, I will be parsing user input as it arrives, one line at a time.

I would prefer to detect and handle bad input in the lexer/parser, e.g

/* lexer tokens */
foo : "FOO";
bar : "BAR";
baz : "BAZ";
/* grammar*/
grammar : foo "=" BAZ 
        | foo "=" BAR 
        | <some non-existent Antrl-else> :  {printf(stderr, "bad input\n");}
        ;

OK, if I can't catch it in the lexer/parser, it seems like I need to use displayRecognitionError() but how??

Can anyone point me at a very simple example which generates C code and shows some error handling of invalid input?

Thanks!


Ok, bounty, yippee!

But only for a real, working answer, with real, working code. No "use method X()" without an wxample.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

美羊羊 2024-08-24 00:00:59

您最有可能寻找的是 displayRecognition错误() 函数。该函数在您感兴趣的情况下被调用,并且是 C 运行时的一部分。

如果您想查看如何使用此功能的示例,请查看 此邮件列表帖子。尽管此代码混合了 C 和 C++,但您应该能够从中找出您需要的内容。

What you are most likely looking for is the displayRecognitionError() function. This function is called in the cases that you are interested in, and is part of the C runtime.

If you want to see an example of how to use this function, look at this mailing list post. Although this code mixes C and C++, you should be able to work out what you need from it.

时光与爱终年不遇 2024-08-24 00:00:59

在 Java 中处理识别异常的过程如下:

grammar X;

// ...

@rulecatch{
  catch(RecognitionException rex) {
    // do something
  }
}

// parser rules

// lexer rules 

换句话说,只需在 @rulecatch{ ... } 块内添加一些自定义 C 代码即可。

Handling a recognition exception in Java would go like this:

grammar X;

// ...

@rulecatch{
  catch(RecognitionException rex) {
    // do something
  }
}

// parser rules

// lexer rules 

In other words, simply add some custom C code inside the @rulecatch{ ... } block.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文