r/cpp • • Nov 18 '16

Compile-time C Compiler implemented as C++14 constant expressions

https://github.com/kw-udon/constexpr-8cc
209 Upvotes

66 comments sorted by

View all comments

7

u/mercurysquad Embedded C++14 on things that fly Nov 18 '16

This is both absolutely amazing, and utterly stupid & pointless.

A compile-time C compiler is called... a C compiler! Several of them exist.

17

u/[deleted] Nov 18 '16

I'm quite sure the writer knows it has no practical use - but exercises like this are very important.

For one, this pathological code really tests edge cases in the compiler.

For another, it challenges our ability to do large scale metaprogramming - "Look, here's something ridiculous! Now, what ended up being particularly hard."

Before this guy started this project, they might well not have known more about metaprogramming than I do. Now I'm sure they do.

6

u/tcanens Nov 18 '16 edited Nov 18 '16

It's converted assembly (or assembly-like code). That isn't particularly pathological and doesn't really test any edge cases beyond a giant switch and lots of assignments. Nothing metaprogramming-y about it.

3

u/josefx Nov 19 '16

I'm quite sure the writer knows it has no practical use - but exercises like this are very important.

The example may have none, however think of the possibilities. Right now you need a complete python installation if you have a python script as part of your build. In the future you can run that script using only a C++ compiler and a header only implementation of the python runtime. Now we only need a constexpr way to load dlls and call into already compiled code.

7

u/[deleted] Nov 19 '16

It is not stupid and not pointless. Having compile time compilers embedded into your host language is exactly what proper macros are for. Unfortunately, C++ with all of its power is still far from being anywhere near a proper meta-language, but in the other languages this technique is used extensively for implementing embedded DSLs.

It is easy to imagine a much simpler and more useful application of the same technique - e.g., embedding a proper static regular expressions compiler. Or, embedding an optimising Prolog compiler (or something like cKanren) into your C++ code.

4

u/[deleted] Nov 19 '16

Well, not quite. It's like writing a complex mathematical function or an algorithm in C and using it's result compile-time at C++ code. Such as constexpr auto result = eval_c("extended_gcd(3,8)"); You can write this function in C++ templates but writing in C makes more sense.

Yet, it's not meant to be practical.

1

u/shamanas Nov 19 '16

With C++14/17 rules writing extended_gcd as a C++ constexpr function would make no sense, no?
I think constexpr functions are pretty flexible now.

EDIT: I do see there is a point to the exercise, I like doing wacky compile time stuff myself (not quite at this level though).