简体   繁体   English

从类似BNF的语法到Java或C ++

[英]From BNF-like grammar to Java or C++

I will use this code for a very basic calculator compiler and a interpreter. 我将将此代码用于非常基本的计算器编译器和解释器。

How can I convert this grammar into C++ or Java? 如何将该语法转换为C ++或Java?

expr         ->term moreterms

moreterms    -> +term {print(‘+’)} moreterms
         |­‐term {print(‘‐’)} moreterms
         |ε

term        ->factor morefactors

morefactors ->*factor {print(‘*’)} morefactors
         |/factor {print(‘/’)} morefactors
         |ε

factor      ->(expr)
         |id {print(id)}
         |num {print(num)}  

There are many tools that take grammars and generate parsers, ranging from Yacc to boost spirit. 有很多采用语法并生成解析器的工具,从Yacc到增强精神。

The art of writing parsers has been widely studied. 编写解析器的技术已得到广泛研究。 It isn't trivial. 这不是小事。 One approach is to determine if you can make your BNF into an LR(1) grammar and write a LR parser for it. 一种方法是确定是否可以将BNF转换为LR(1)语法并为其编写LR解析器。

An easy way to parse is to split your parsing into tokenizing (where you bundle things into identifiers), and syntax tree generation. 解析的一种简单方法是将解析分为标记化(将内容捆绑到标识符中)和语法树生成。

Wikipedia has a cursory description of LR parsing. Wikipedia粗略地描述了LR解析。 Knuth's Canonical LR(1) parser is also worth looking at. Knuth的Canonical LR(1)解析器也值得一看。

Teaching how to write an LR(1) parser (with whatever restrictions, let alone an LR(k) parser) is a matter of a short college course or a book chapter, not a stack overflow post. 教授如何编写LR(1)解析器(无论有什么限制,更不用说LR(k)解析器)都是一门大学课程或一本书的简短内容,而不是堆栈溢出文章。

But the general idea is you read from left to right. 但总体思路是您从左到右阅读。 You look ahead k tokens (typically 1) to determine which rule to apply to the next token you encounter. 您可以预见k个令牌(通常为1个),以确定要应用于遇到的下一个令牌的规则。 You build the parse tree from the bottom-up. 您从下至上构建了分析树。

There are lots of technical details, techniques, quirks and problems. 有很多技术细节,技术,怪癖和问题。 Not every BNF grammar can be turned into a LR(1) grammar, let alone the restricted ones that many parse generators can handle. 并非每个BNF语法都可以转化为LR(1)语法,更不用说许多解析生成器可以处理的受限语法了。

As mentioend by @UnholySheep, The Dragon Book is the book that most people learn these techniques from. 作为@UnholySheep的指导, 书》是大多数人从中学习这些技术的书。

Did you have a look at Yacc ? 您看过Yacc吗? This could be doing exactly what you are looking for. 这可能正是您想要的。

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

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