TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Left-Recursive Peg Grammars

52 点作者 pauloxnet超过 5 年前

5 条评论

tanin超过 5 年前
Great blog. I haven&#x27;t used PEG and have learned a lot from this post. However, handling left-recursive in PEG seems complex.<p>I&#x27;ve recently written a Java parser by hand (<a href="https:&#x2F;&#x2F;github.com&#x2F;tanin47&#x2F;javaparser.rs" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;tanin47&#x2F;javaparser.rs</a>) and aimed to emulate a bottom-up parsing as much as possible.<p>The hand-written bottom-up parsing approach seems more intuitive because it enables us to construct`left` + `right` immediately before looking further.<p>For the same problem, the hand-written bottom-up parsing approach would look like below:<p><pre><code> def expr1(input): left, input = expr2(input) return expr1_tail(left, input) def expr1_tail(left, input): if input[0] == &#x27;+&#x27;: right, input = expr2(s[1..]); new_expr = BinaryOp(left, input[0], right); return expr1_tail(new_expr, input); else: return left, input def term(s): if input[0] == &#x27;(&#x27;: new_expr, input = expr1(input[1..]) assert input[0] == &#x27;)&#x27; return new_expr, input[1..] else # parsing numbers here return number, the_rest_of_input </code></pre> (Please excuse my python... I&#x27;m a bit rusty)
评论 #20807807 未加载
mcherm超过 5 年前
I got all the way to the end of the article without noticing who the author was, thinking &quot;what a clearly written piece -- I should keep an eye out for this author in the future&quot;.<p>Then I realized it was an author I knew.
kd5bjo超过 5 年前
I’m not sure if taking the longest match is necessarily right. Imagine a (nonsensical) rule like:<p><pre><code> LeftRec &lt;= LeftRec ‘+’ Term &#x2F; “ok” &#x2F; [a-z]*[0-9] </code></pre> According to PEG, “ok3” should consume only “ok” here, and leave the 3.
axilmar超过 5 年前
Well, I had the same epiphany 5 years ago, and I implemented it in a C++ library here:<p><a href="https:&#x2F;&#x2F;github.com&#x2F;axilmar&#x2F;parserlib" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;axilmar&#x2F;parserlib</a><p>It&#x27;s nice to be able to handle left-recursive grammars in a PEG parser. It feels liberating. Although I never used it to write my dream programming language :-).<p>Note that the same thing can be done via a stack of alternate parsers: when the recursive parser is on top of the stack, then the one below it shall be chosen.
aardshark超过 5 年前
For those who just want to read the article without Medium nonsense: <a href="https:&#x2F;&#x2F;outline.com&#x2F;jWuKxc" rel="nofollow">https:&#x2F;&#x2F;outline.com&#x2F;jWuKxc</a>