YAML 解析 - lex 还是手卷? [英] YAML parsing - lex or hand-rolled?

查看:18
本文介绍了YAML 解析 - lex 还是手卷?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个简单的 YAML 解析器,我从 yaml.org 阅读了规范,在开始之前,我想知道编写手动解析器是否更好,或者使用 lex (flex/bison).我查看了 libyaml (C 库) -似乎没有使用 lex/yacc.YAML(不包括流样式),似乎更面向行,所以,是吗更容易编写手动解析器,或使用 flex/bison谢谢.

I am trying to write a simple YAML parser, I read the spec from yaml.org, before I start, I was wondering if it is better to write a hand-rolled parser, or use lex (flex/bison). I looked at the libyaml (C library) - doesn't seem to use lex/yacc. YAML (excluding the flow styles), seems to be more line-oriented, so, is it easier to write a hand-rolled parser, or use flex/bison Thanks.

推荐答案

这个答案基本上是对以下问题的回答:我应该滚动自己的解析器还是使用解析器生成器?"和 YAML 关系不大.但尽管如此,它还是会回答"你的问题.

您需要问的问题不是这是否适用于这种给定的语言/语法",而是我是否有信心实现它".事实是,您要解析的大多数格式都只能与生成的解析器一起使用.另一个事实是,使用简单的手写递归下降解析器.

The question you need to ask is not "does this work with this given language/grammar", but "do I feel confident to implement this". The truth of the matter is that most formats you want to parse will just work with a generated parser. The other truth is that it is feasible to parse even complex languages with a simple hand written recursive descent parser.

我已经为 EDDL 编写了一个递归下降解析器(C 和结构化元素) 和 INI 的 bison/flex 解析器.我选择了这些示例,因为它们违背直觉,并且外部要求决定了决定.

I have written among others, a recursive descent parser for EDDL (C and structured elements) and a bison/flex parser for INI. I picked these examples, because they go against intuition and exterior requirements dictated the decision.

既然我在技术层面上建立了它是可能的,为什么你会选择一个而不是另一个?这是一个很难回答的问题,这里有一些关于这个主题的想法:

Since I established on a technical level it is possible, why would you pick one over the other? This is really hard question to answer, here are some thoughts on the subject:

  • 编写一个好的词法分析器真的很难.在大多数情况下,使用 flex 生成词法分析器是有意义的.手动滚动您自己的词法分析器几乎没有什么用处,除非您有非常奇特的输入格式.
  • 使用 bison 或类似的生成器可以使用于解析的语法显式可见.这里的主要收获是,在五年内维护您的解析器的开发人员将立即看到所使用的语法,并可以将其与任何规范进行比较.
  • 使用递归下降解析器非常清楚解析器中发生的情况.这为优雅地处理 harry 冲突提供了简单的方法.您可以编写一个简单的 if,而不是将整个语法重新排列为 LALR1.
  • 在开发解析器时,您可以忽略细节";使用手写解析器,使用野牛这几乎是不可能的.在野牛中,语法必须有效,否则生成器不会做任何事情.
  • Bison 擅长指出语法中的形式缺陷.不幸的是,您只能独自修复它们.手动滚动解析器时,您只会在解析器读取废话时发现缺陷.

这不是一个或另一个的明确答案,但它为您指明了正确的方向.既然您似乎是为了好玩而编写解析器,我认为您应该编写这两种类型的解析器.

This is not a definite answer for one or the other, but it points you in the right direction. Since it appears that you are writing the parser for fun, I think you should have written both types of parser.

这篇关于YAML 解析 - lex 还是手卷?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆