编写我自己的C ++编译器 [英] Writing my own C++ compiler

查看:153
本文介绍了编写我自己的C ++编译器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在c ++中编写我自己的c ++编译器。让我们说我要在VS中构建它。
主要思想是它必须已经能够编译自身,这意味着我不能使用STL,boost等库,我可以吗?
所以,这是否意味着我必须从头开始做一切 - 从词法分析器到二进制代码生成?

解决方案


这意味着我不能使用STL,boost等库。


为什么不呢?他们不使用任何魔法(因为它),只有纯C ++。所以如果你的编译器知道所有的C ++,这不应该是一个问题。这当然是完全可笑的,考虑到C ++可能是最难以解析编程语言存在今天,从头构建一个编译器可能需要几百(!)的人年。 (我实际上没有发明这个数字 - 我读它在某个地方。不幸的是,我现在找不到源。)



但是,完全假设所以假设的答案是:不,你可以使用现有的库。



那么为什么C ++这么难编译? p>

首先,C ++是一种上下文相关的语言。生成这样的语法的解析器要困难得多。然而,这仍然是最简单的方面之一。使C ++真的很难的是与声明/定义,名称查找(考虑依赖于参数的名称查找)隐式转换规则相关的一些规则,当然还有模板的解析。我认为现有的编译器在所有情况下都不会有正确的模板。



考虑 Andrej Alexandrescu的写作模板函数版本的 min max 版本。他声称没有编译器成功编译他的(理论上正确的)代码:


这将是那么好,提到。遗憾的是,Min不能使用任何我可以访问的编译器。公平地说,每个编译器对不同的代码片段进行阻塞。



I want to write my own c++ compiler in c++. Let´s say I´m going to build it in VS. The main idea is that it must have been able to compile itself, which means I cannot use STL, boost, etc. libraries, can I? So, does it mean that I must do everything from scratch - from lexical analyser to binary code generation?

解决方案

which means I cannot use STL, boost, etc. libraries, can I?

Why not? They don't use any magic (as it were), only plain C++. So if your compiler knows all of C++, this shouldn't be a problem. Which is of course completely ludicrous, considering that C++ is probably the hardest to parse programming language in existence today, and that building a compiler from scratch would probably take hundreds (!) of man-years. (I didn't actually invent this number – I read it somewhere. Unfortunately, I'm unable to find the source now.)

But then, I guess the question was completely hypothetical so the hypothetical answer is: no, you can use existing libraries.

So why is C++ so hard to compile?

First off, C++ is a context sensitive language. Producing a parser for such a grammar is much harder. However, this is still one of the simplest aspects. What makes C++ really hard are certain rules relating to declarations/definitions, name lookup (consider argument-dependent name lookup) implicit conversion rules, and of course the resolution of templates. I think no existing compiler gets templates right in all circumstances.

Consider Andrej Alexandrescu's efford to write template-function versions of min and max that behave as correctly as the macro version. He claims that no compiler succeeds in compiling his (theoretically correct) code:

It would all be so nice, but there's a little detail worth mentioning. Sadly, Min doesn't work with any compiler I have access to. In fairness, each compiler chokes on a different piece of code.

这篇关于编写我自己的C ++编译器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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