编写编程语言解析器的最佳实践 [英] Best practices for writing a programming language parser

查看:160
本文介绍了编写编程语言解析器的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写解析器时,我应该遵循哪些最佳实践?

解决方案

收到的智慧是使用解析器生成器+语法,这似乎是一个好的建议,因为你使用一个严格的工具,大概减少的努力和潜在的bug这样做。



使用解析器生成器语法必须是上下文无关的。如果你正在设计要解析的languauge,那么你可以控制它。如果你不确定那么它可能会花费你很多的努力,如果你开始语法路线。即使在实践中它是上下文无关的,除非语法是巨大的,可以更简单地编写一个递归体面解析器。



无上下文不仅使解析器生成器可行,而且还使得手工编码的解析器更简单。你最终得到的是每个短语一个(或两个)函数。这是如果你整理和命名代码干净不是一个语法难以看到(如果你的IDE可以显示你调用hierachies,那么你可以几乎看到什么语法是)。 b

  • 更好的效果

  • 更好地控制输出

  • 可以处理小偏差,例如使用不是100%上下文无关的语法



  • 我不是说语法总是不合适,经常被成本和风险权衡。



    (我相信他们的论据似乎很有吸引力,并且对他们有一般的偏见,因为它是一种信号,表明一个更具计算机科学素养的方式。 )


    Are there any best practices that I should follow while writing a parser?

    解决方案

    The received wisdom is to use parser generators + grammars and it seems like good advice, because you are using a rigorous tool and presumably reducing effort and potential for bugs in doing so.

    To use a parser generator the grammar has to be context free. If you are designing the languauge to be parsed then you can control this. If you are not sure then it could cost you a lot of effort if you start down the grammar route. Even if it is context free in practice, unless the grammar is enormous, it can be simpler to hand code a recursive decent parser.

    Being context free does not only make the parser generator possible, but it also makes hand coded parsers a lot simpler. What you end up with is one (or two) functions per phrase. Which is if you organise and name the code cleanly is not much harder to see than a grammar (if your IDE can show you call hierachies then you can pretty much see what the grammar is).

    The advantages:-

    • Simpler build
    • Better performance
    • Better control of output
    • Can cope with small deviations, e.g. work with a grammar that is not 100% context free

    I am not saying grammars are always unsuitable, but often the benefits are minimal and are often out weighed by the costs and risks.

    (I believe the arguments for them are speciously appealing and that there is a general bias for them as it is a way of signaling that one is more computer-science literate.)

    这篇关于编写编程语言解析器的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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