当我尝试使用 Spirit 解析内容时,我不断遇到堆栈溢出

发布于 2024-07-26 09:26:17 字数 840 浏览 1 评论 0原文

我想当我开始出现堆栈溢出时,是时候来这里询问了;)

我现在正在尝试学习如何使用 Boost Spirit。 我已经弄清楚了基本的事情。 由于我手边有 K&R(其中包含 C 的语法),我决定看看是否可以为该语言创建一个接受器。 无论如何,这或多或少是我最初的目标,因为我最终想使用它作为预处理器从数据结构和其他东西中收集一些信息。

我能够解析常量和字符串,但是当我尝试解析它时,我开始遇到问题。

postfix_expression = 
    primary_expression
    // omitting some other rules for simplicity's sake
    | (postfix_expression >> chseq+p("++"))
    | (postfix_expression >> chseq_p("--"));

primary_expression = 
    identifier
    | constant
    | string_literal;

// The parsers for constants and strings are 
// pretty trivial so I'm not going to C+P them here. 

当我传递像 i++ 这样的东西时,它会失败。 我认为这是因为 i 是有效的 primary_expression,因此它不会继续检查 ++- -。 我尝试将其放在底部,然后出现堆栈溢出。 我在这里遇到了一些无限左递归,但我不知道如何解决它。

I figured when I started getting stack overflow it was time to come here to ask ;)

I'm trying to learn how to use Boost Spirit right now. I've figured out the basic stuff. Since I had K&R handy (which contains the grammar of C) I decided to see if I could make an acceptor for the language. This was more or less my original goal anyway, since I eventually want to use this as a preprocessor to gather some information from data structures and stuff.

I'm able to parse constants and strings, but when I try to parse this I start having problems.

postfix_expression = 
    primary_expression
    // omitting some other rules for simplicity's sake
    | (postfix_expression >> chseq+p("++"))
    | (postfix_expression >> chseq_p("--"));

primary_expression = 
    identifier
    | constant
    | string_literal;

// The parsers for constants and strings are 
// pretty trivial so I'm not going to C+P them here. 

When I pass in something like i++ it fails. I assume this is because i is a valid primary_expression and so it doesn't go on to check for the ++ or --. I tried putting it at the bottom, and then I get stack overflows. I'm getting some infinite left recursion here but I don't know how to solve it.

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

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

发布评论

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

评论(1

轻拂→两袖风尘 2024-08-02 09:26:17

你必须摆脱左递归。 这篇维基百科文章解释了一些技术:

http://en.wikipedia.org/wiki/Left_recursion

然而,这可能是不可能的。 C 具有相当灵活的语法,并且可能无法提供足够的上下文来允许递归下降解析器运行,除非 Boost Spirit 允许回溯。 或者你可以做到,但关联会倒退。

您可能最好使用基于 LALR 的工具,例如 bison。

You'll have to get rid of the left recursion. This Wikipedia article explains some techniques:

http://en.wikipedia.org/wiki/Left_recursion

However, it may not be possible. C has a pretty flexible syntax and may not provide enough context to allow a recursive descent parser to function unless Boost Spirit allows backtracking. Or you'll be able to do it but the associations will be backwards.

You may be better off using an LALR based tool such as bison.

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