175 points · by rep_movsd · 9y ago · 81 comments
It took me a while to understand why every iteration of C++ brings so many (often Turing-complete or close) side effect horrors. The reason is that C++ is more than a language: it is part of an actually philosophical quest that language design is about.
It is about trying to bridge the language of the machines and the language of human abstractions as closely as possible. In itself it does not necessarily lead to the best language possible, but it explores an interesting limit.
One can use higher level languages like Haskel, Prolog or even a bit lower like Ruby or Python and code nice abstractions. By doing so, however, the programmer typically loses track of what the machine implementation will be.
C++ strives to be a language where you can still feel what the machine will actually implement while you code high-level abstractions.
That is their goal, that is their quest. In doing so there are many side-effects that pop up, but their effort is commendable.
That so many people still use it is impressive but, I think, irrelevant to the priorities they typically set.
> It is about trying to bridge the language of the machines and the language of human abstractions as closely as possible. In itself it does not necessarily lead to the best language possible, but it explores an interesting limit.
> C++ strives to be a language where you can still feel what the machine will actually implement while you code high-level abstractions.
This has been false ever since the earliest days of ANSI C. The C and C++ standards define an abstract machine that is quite far from any machine that exists today. Type-based aliasing rules, to name one important example, are something that has almost nothing to do with anything that exists in the hardware.
It's quite enlightening to read the description of LLVM IR [1] and observe how far it is from anything a machine does. In fact, LLVM IR is quite a bit lower level than C is, as memory is untyped in LLVM IR without metadata: this is not at all the case in C.
In reality, C++ is an attempt to build a high-level language on top of the particular abstract virtual machine specification that happened to be the accidental byproduct of a consensus process among hardware/compiler vendors in 1989. It turns out that this has been a very helpful endeavor for a lot of people, but I don't think we should claim that it's anything more than that. There's nothing "philosophically" interesting about the C89 virtual machine.
You can go low level with most high level languages, what sets C++ apart is that using low-level instructions have generally zero overhead. ptr2 = static_cast<uint8_t*>(ptr)+5; pretty much maps to the assembly code you would expect.
And the semantics of those operations are dictated not by what the underlying machine does but what the C++ abstract machine does, which is very different. The underlying memory is still typed.
> You can go low level with most high level languages, what sets C++ apart is that using low-level instructions have generally zero overhead.
That's true for the JVM, .NET, even JS...
> ptr2 = static_cast<uint8_t*>(ptr)+5; pretty much maps to the assembly code you would expect.
No, it doesn't, not after optimizations and undefined behavior. It's perfectly acceptable for the compiler to turn that into a no-op if, for example, "ptr" was a null pointer.
CPUs no longer commonly implement integer overflow checking, granular hardware based memory safety primitives, efficient user level exception handling, etc.
Sure it's possible to do high level things while knowing what the machine will end up doing but if you have to be a guru to be able to do so... then can you really say that?
I'd say "C++ strives to be a language where expert C++ compiler writers can feel what the machine will actually implement while you code high-level abstractions (provided you're using the compiler you wrote yourself)"
Once you measure a performance issue you can focus in on one part or algorithm and map abstractions onto hardware, which can't be done in many languages. Because hardware is different this process is often different. Even between two members of the x86 family there are different ways things can be optimized and the compiler puts a bunch of reasonable defaults in. Once you know the sane defaults are not good enough you can trade effort for efficiency as much as you want and keep getting gains for a long time.
Trying to go to the machine code each C++ build is like trying to understand the JVM bytecode for each java build. I don't know why so many care, because you only need to do this on occasion. I suspect the culture of performance causes people giving talks to focus on this. Then people consuming talks place disproportionate value on this.
This is clearly happening with constexpr and template metaprogramming now. Few people really need it but there is huge focus because a few smart people needed it to solve their problems, and those people are also prolific speakers and, bloggers and authors. Where are all the talks on best practices around smart pointers, thread synchronization tools, class composition, and other common issues that affect correctness, design or other aspects of creating software? I want to see more on Hazard pointers and other pooled smart pointers, these are a real replacement for general purpose garbage collection, but the community prefers to talk about compile HTML parsing (not that these are mutually exclusive, but there is only so much attention).
The work shown here is impressive, but the point is that it should not be. D has shown that variable initialization at compile time can be painless.
The main limitations I find are: a) Lack of support in the standard library (e.g., you should code your own sort, vector class, etc.)
b) Terrible Terrible Terrible compilation times.
c) Lack of a dynamic memory allocation within constexpr.
constexpr functions are not evaluated while parsing (e.g., the code is not compiled and then executed). My use case, which was to avoid a 1 second preprocessing time while loading a library, took more than 20 minutes to compile and used more than 60 GB of RAM (on GCC7, CLANG did not even manage to compile).
Stuff like initializing a bitset can easily eat all your ram (e.g. this fails to compile): #include <bitset> int main() { std::bitset<102410241024> bs; } https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63728
A lot of the STL is already being constexpr-ized (as Stephen T Lavalej has mentioned)
This code i wrote takes about 5 seconds on gcc and 1.5 seconds on clang to compile for a 1000 node HTML template (about 28 KB). Definitely slow, but not really really slow.
I have a feeling recursion slows down the compile time, I will attempt an iteration based version eventually and see.
Considering that one of the greatest C++ programmers of all time (Andrei) is now a D person, that's proof enough.
But for some reason, this sort of C++ shenanigan is intensely satisfying to me.
I guess it's a narrow complexity fetish.
(Note, by "used" here I mean utilizing most of the language, and the full ecosysstem of libraries, or at least most of it; not a mode that is supported in theory but useless in practice.)
Mind to share why a GC seems to be unaccceptable for you?
(You can argue that purely functional code is useless in real life and that C++ shouldn't strive to be purely functional, but that's another argument.)
(eval-when (:compile-toplevel)
...)
You can also have read-time macros or load-time values, depending on what you need. (defmacro html (string)
(some-html-parser-library:parse string))
Or you could use a function and a compiler macro to make it more of an optimization -- if the argument is known at compile-time just parse it then, otherwise wait til runtime: (defun html (string)
(some-html-parser-library:parse string))
(define-compiler-macro html (&whole form string)
(if (constantp string)
`',(some-html-parser-library:parse string)
form))
Actual example, using `string-upcase` to stand in for an HTML parsing library: (defun html (string)
(string-upcase string))
(define-compiler-macro html (&whole form string)
(if (constantp string)
`',(string-upcase string)
form))
(defun foo (arg)
(print (html arg))
(print (html "compile-time"))
nil)
(foo "run-time")
; "RUN-TIME"
; "COMPILE-TIME"
(disassemble 'foo)
; disassembly for FOO
; Size: 128 bytes. Origin: #x10106A207D
; 7D: 498B4C2460 MOV RCX, [R12+96] ; thread.binding-stack-pointer
; no-arg-parsing entry point
; 82: 48894DF8 MOV [RBP-8], RCX
; 86: 488D5C24F0 LEA RBX, [RSP-16]
; 8B: 4883EC18 SUB RSP, 24
; 8F: 488B55F0 MOV RDX, [RBP-16]
; 93: 488B0576FFFFFF MOV RAX, [RIP-138] ; #<SB-KERNEL:FDEFN HTML>
; 9A: B902000000 MOV ECX, 2
; 9F: 48892B MOV [RBX], RBP
; A2: 488BEB MOV RBP, RBX
; A5: FF5009 CALL QWORD PTR [RAX+9]
; A8: 480F42E3 CMOVB RSP, RBX
; AC: 488D5C24F0 LEA RBX, [RSP-16]
; B1: 4883EC18 SUB RSP, 24
; B5: 488B055CFFFFFF MOV RAX, [RIP-164] ; #<SB-KERNEL:FDEFN COMMON-LISP:PRINT>
; BC: B902000000 MOV ECX, 2
; C1: 48892B MOV [RBX], RBP
; C4: 488BEB MOV RBP, RBX
; C7: FF5009 CALL QWORD PTR [RAX+9]
; CA: 488D5C24F0 LEA RBX, [RSP-16]
; CF: 4883EC18 SUB RSP, 24
; D3: 488B1546FFFFFF MOV RDX, [RIP-186] ; "COMPILE-TIME"
; DA: 488B0537FFFFFF MOV RAX, [RIP-201] ; #<SB-KERNEL:FDEFN COMMON-LISP:PRINT>
; E1: B902000000 MOV ECX, 2
; E6: 48892B MOV [RBX], RBP
; E9: 488BEB MOV RBP, RBX
; EC: FF5009 CALL QWORD PTR [RAX+9]
; EF: BA17001020 MOV EDX, 537919511
; F4: 488BE5 MOV RSP, RBP
; F7: F8 CLC
; F8: 5D POP RBP
; F9: C3 RET
; FA: 0F0B10 BREAK 16 ; Invalid argument count trap
`html` is only called once, to handle the call that isn't known at compile time.C++ should really get proper metaprogramming, with support for user-defined error messages. All this template stuff always seemed like an awful hack to me: Fighting the compiler instead of being the compiler.
Going from templates to constexpr is like moving from a war zone to a forest. It's still scary and dark, but at least you know what hit you. static_printf is coming soon.
The error message looks incomprehensible, but the last couple of lines give you enough information - the error string and the line number - it looks much better on the console since its colorized
> It is a hack, but what else is there eh?
The non-hacky way to do this sort of thing in both C and C++ is to just use less clever two-phase compilation as part of your build process.I.e. you'd have your template compiler extract the HTML from your source (or more easily, dedicated template files), parse, validate and compile them. The end result of that would then be embedded in your binary somehow.
The gettext set of tools are a good example how how this works in another related domain. You extract strings from your program, they and the contents of corresponding .po files are validated, then compiled to efficient .mo binary files for runtime use.
All someone has to do here is #include my header and write their templates with a small suffix and prefix.
No need to install, configure, script and so on.
Your argument is similar to saying "Why should an IDE parse your code and underline errors? We can run make everytime"
Another advantage of my approach is that you have access to the parsed template as a data structure - that you can compose or modify as you wish.
The only other way to do this is to parse at runtime - which is definitely slower
This is as scary as a bunny painted in camouflage.
How does one debug complex constexpr code? I assume there's no printf.
It'd be really cool if it supported some kind of interpolation, like Jinja templates, so it could generate dynamic page templates at compile time.
template <typename T, typename ...Ts>
void show_types()
{ static_assert((T*)nullptr, "Type log"); }
int main()
{
show_types<int, float, bool>();
}
When trying to compile this, using something like `g++ show-type.cpp`, you'll get this output: show-type.cpp: In instantiation of ‘void show_types() [with T = int; Ts = {float, bool}]’:
show-type.cpp:7:32: required from here
show-type.cpp:3:3: error: static assertion failed: Type log
{ static_assert((T*)nullptr, "Type log"); }
The same can be done for non-type template args, of course.T::asdfasdf();
Although I might start using yours.
#define constexpr
Which makes all the code plain code that executes at runtime, then you can put your couts and use your debuggers.
Its orders of magnitude simpler than dealing with template meta-programming.
constexpr_printf is the feature I want most of all. There is actually a patch for gcc that implements this.
I dont know how Jinja works, but the idea here is you do templating at runtime, but your templates get compiled down to a tree like DS at compiletime
I decided to use a runtime DS to allow things like splicing and looping templates etc.
It's also possible to make the runtime render the compiled time DS directly, which should be even faster if your requirements are simple enough
By malformed are we talking about incorrectly closed, or actual invalid HTML? HTML doesn't require all tags be closed...
The HTML specification has a grammar and defines whats allowed - a subset/derivation of XHTML/SGML and their ilk
There are a bunch of test template files in the test/ folder that demonstrate what kinds of errors are caught.
This has changed since the advent of the HTML5 specification, the primary purpose of which was to retroactively describe existing browser HTML parsing behaviours and to document and specify them comprehensively in all of their complexity.
The wisdom of this abominably complex approach may be questionable, but it's certainly no longer "loosely" defined.
I'd be curious as to whether this implements HTML5...
The specification allowing for "implicit" tags is something that just doesn't make any bloody sense to me. It feels like someone looked at all warnings in a compiler and said, I'll just explicitly define exactly how I want each warning to behave, so that it is no longer dangerous behavior.
It parses out a pretty large example HTML file without any trouble