简体   繁体   English

右递归文法还是左递归?

[英]Right recursive grammar or left recursive?

I have little to no knowledge of what I'm about to ask, so I would like a suggestion based on the level of skills required to implemented a parser for the given grammar ( since I'm a beginner in this kind of formal approach to parsers and languages ).我几乎不知道我要问什么,所以我想根据为给定语法实现解析器所需的技能水平提出建议(因为我是这种正式方法的初学者解析器和语言)。

Just by going back of a couple of years, this situation reminds me a little of Pascal grammar vs C/C++ grammar, this left vs right stuff.回到几年前,这种情况让我想起了一些 Pascal 语法与 C/C++ 语法,这左与右的东西。

But I'm not going to do any of that, my purpose is to implement a simple parser for a markup language for documents like Markdown.但我不会做任何这些,我的目的是为 Markdown 等文档的标记语言实现一个简单的解析器。

So considering that I'm starting with a markup language in mind, I want to keep things simple, which is the easiest one to handle between this 2 options and why .因此,考虑到我从一种标记语言开始,我想保持简单,这是这两个选项和原因之间最容易处理的选项。 Another kind of grammar could be an easier option for me ?另一种语法对我来说可能是一个更简单的选择? If yes which one do you suggest ?如果是,你建议哪一个?

Right recursive vs. left recursive mostly comes down to how you're going to implement the parser.右递归与左递归主要取决于您将如何实现解析器。

If you're going to do a top-down (eg, recursive descent) parser, you normally want to use right recursion in the grammar (and for pure recursive descent, that's the only option).如果您要进行自顶向下(例如,递归下降)解析器,您通常希望在语法中使用右递归(对于纯递归下降,这是唯一的选择)。

If you're going to do a bottom-up parser, you normally want to use left recursion.如果要进行自底向上的解析器,通常要使用左递归。 Bottom up parsers are normally generated with a parser generator like Yacc or Bison, most of which can handle right recursion if needed, but can handle left recursion more efficiently, so it's preferred as long as it doesn't adversely affect semantics.自下而上的解析器通常使用 Yacc 或 Bison 等解析器生成器生成,如果需要,它们中的大多数可以处理右递归,但可以更有效地处理左递归,因此它是首选,只要它不会对语义产生不利影响。

It depends upon what type of parser you are using.这取决于您使用的解析器类型。 If you use an LL type, you have to use right recursion.如果使用 LL 类型,则必须使用右递归。

If you use an LR type, you can use either left or right recursion.如果使用 LR 类型,则可以使用左递归或右递归。 However, left recursion minimizes stack depth.然而,左递归最小化了堆栈深度。

Well there are two basic types of grammars:那么有两种基本类型的语法:

LL(k) = Left to tight, leftmost derivation, k symbols look ahead
LR(k) = Left to right, rightmost derivation, k symbols look ahead

LR parsers are much more difficult to write by hand, however, they are more powerful then LL parsers. LR 解析器手动编写要困难得多,但是,它们比 LL 解析器更强大。 If you are looking at some popular parser generator tools:如果您正在查看一些流行的解析器生成器工具:

ANTLR : a LL parser
BISON:  a LALR(1) parser (a type of LR parser but a bit less powerful)
CUP:    a LALR(1) parser (outputs Java / C# code)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM