214 points · by orbifold · 6y ago · 139 comments
But, I think this trend might lead to extremely hard to read code, and there is a good chance that this hard-to-read code will be treated as some black box/voodoo.
It might not be a better idea than self-modifying machine code or some of the wildest C macros...
At least compile time reflection and code generation will catch a large chunk of bugs that would otherwise be deferred to runtime. I will take a puzzling compile time error message over having to debug runtime reflection errors any day.
Another explanation is that playing around with annotations and AST decorations/rewriters is an excellent excuse for procrastinating through your day without having to deal with mundane business code :). I also think there's a psychological effect at work here where you're dellusioning yourself into being a "tool developer" and part of an academic discourse when you throw around annotation libs, to deflect from the harsh reality that you're working in cost-center IT. Or maybe a kind of inner migration from an enterprise code base which you can't identify with, and wish to put a fence against, as in "they" (your lib users) vs "us" (elite metaprogrogrammers). As someone else said, today's Spring-heavy Java code bases express behaviour through "anything and everything except actual Java code". C++ developers should take a look at Spring MVC in particular to see if that really is what they want, where the relative sequence of method parameters has significance, and when presented slightly different will result in service request routing 404ing, which you find out only by examining 600-items stack traces with multiple reflection pits.
This is also why we have banished all forms of reflection based serialization in favour of hand-written JSON mappings. Yes, they are a bit tedious to write, but it isn't actually that bad. As a plus, you get type errors up front, and you avoid strange errors due to e.g. third party `Map` libraries that the reflection based "magic" cannot figure out how to handle correctly. If the amount of work gets out of hand, you can always turn to code generation later if it is deemed worth it.
That being said, I think generic programming and avoidance of boilerplate does have its merits as it can help reduce the cost of abstractions. But it absolutely must be done in a principled way rather than be a result of quick and dirty hacks such as C macros, Java reflection and C++ templates, which all accidentally give you an advanced metaprogramming environment with little safety. An example of an approach that I like is the "Generics SOP" approach in Haskell, although I do recognize that the type-level programming that it involves is not for everyone: https://www.andres-loeh.de/TrueSumsOfProducts/
I don't understand why it would be bad to make it impossible to have Spring-like frameworks in C++. A metric ton of useful things have been written in it, and are only written much more painstakingly in C++.
Metaprogramming is pretty wide, ranging from primitive textual substitutions like C macros to type-aware hygienic macros ala rust, and from limited scope like C++ templates to full-on program writing like in lisp.
In C and C++ (current versions) the entire module system is built-up around the metaprogramming hack of doing #ifdef header guards. Even this is a bit error prone, but the alternative is only expressible as a compiler intrisic (#pragma once).
In languages like C, Go and early Java, the lack of generics (a type of metaprogramming) makes it impossible to write type-safe generic algorithms forcing casts to void*, interface{} and Object resp.
Implementing type checking for printf-like constructs requires compiler-intrinsics or C++17 constexpr meta-programming.
In C and C++ you must manually implement serialization and deserialization for structs and everything else that is naturally expressed and iterating over the elements of a struct. Alternatively you could use something like protobuf, which (surprise!) has compiles your protobuf file into a C++ program you can include. Using something like Rust's serde is /much/ simpler, and is only possible due to metaprogramming.
Gotta agree here, you're shifting a lot of complexity from your code to the metaprogramming from the serde crate.
Sure it's difficult to use proc_macro style metaprogramming, but the user gets much simpler code.
How hard it will be to debug is more dependent on the available tools to link the error to some source code.
For example, there's a huge load of source to source compilers used in the web stack now. This is not such a big deal it seems, probably because debuggers make an adequate job to link the error to the original source. Actually I didn't directly touched Babylscript and so on, but I didn't saw much complaint about traceability of errors, so here I just guess: a more informed point of view would be valuable here.
Self-modifying code might have been its purpose in highly resource constrained environment. But otherwise, in my opinion, generating a whole distinct source or tailoring a runnable AST has always been more understandable while offering the same level of flexibility.
This already happens with metaprogramming in C++. See e.g. the source of the Boost Preprocessor library. Circle just makes this code a bit easier to read. Even code using the library: compare the compile-time Duff's device generation in https://www.boost.org/doc/libs/1_72_0/libs/preprocessor/doc/... to that in https://github.com/seanbaxter/circle/blob/master/examples/RE... .
I believe the facilities provided by circle would make most of the Tablegen infrastructure redundant.
If I understand the Circle docs correctly...
[...] searched for in the pre-loaded standard binaries: libc, libm, libpthread, libstdc++ and libc++abi.
Additional libraries may be loaded with the -M compiler switch. When the requested function is found,
a foreign-function call is made, [...]
...all libraries are fair game? And I guess you might be able to do your own function/dll probing with libdl.Do you guys see this as a feature or a liability?
Compilers are _far_ from security hardened and an attacker slipping something evil into the output binary is probably equally as bad anyway (you distribute it to your users after all). Ultimately you shouldn't be compiling code you don't trust without a good reason and appropriate precautions.
As a counterexample, as far as I'm aware Common Lisp makes no distinction between execution that occurs at compile time versus run time. It still seems to be doing pretty well though!
That's not quite phrased correctly. Common Lisp very well makes such a distinction, but allows code to be executed at compile time, load time or run time. See http://www.lispworks.com/documentation/HyperSpec/Body/s_eval... for detaills.
With C++ the template syntax is so horrible convoluted, that I doubt people get the idea of compile-time expressions. What is allowed, and what forbidden.
They are only done locally, which is sometimes not what you want. syscalls, fileio, Config checks are not done at runtime, and this is for 99% a bug. You really need to know what you do. And each such sideffect is only done once, when you run the compiler. Not at the client.
- people writing external code generators (moc, MIDL, tinyrefl, a random python script, and a hundred other possibilities)
- people doing code generation in their build system (CMake allows that relatively easily for instance)
- people doing code generation with macros (verdigris instead of moc, boost.pp)
- people writing clang extensions which get outdated in 6 months due to LLVM code churn (https://github.com/AustinBrunkhorst/CPP-Reflection and a few others)
e.g. just look at one of the latest C++ questions on SO : https://stackoverflow.com/a/61623940/1495627
People are ressorting to friggin bash scripts because they don't have that feature. Between unmaintainable bash scripts, and type-checked C++ code, what do you think is better ?
Currently, I am writing JS and TS code and I do quite a bit of code generation. It's great -- it goes into my repo so I get nice diffs when I make a change, I have easily debuggable code and my generator-code can be "unclean" and support weird edge cases through simple if-statements. Of course, my younger self would feel contempt bordering on pity for someone like me who clearly has no sense of beauty, or integrity, really. :-)
Boost libraries fall into this category.
Chandler Carruth had a nice talk at CppCon 2019 about how widespread usage of protobuf wound up causing the Compiler to time out on single translation units in the Google code base.
I think this is a killer feature. Between execution policies and constexpr-all-the-things, I really think C++ is set to pull away in a way that other languages will have difficulty competing with.
I can't help but think C++ will be one of these things digital archeologists will look back in disbelief.
And I mean both amazed as well as flabbergasted disbelief.
What pleasant surprise(s) exactly are you talking about?
Actually, never mind.
After a year of Rust I see myself touching C++ code next when I'm 70 and they need some old farts to fix code no one can or wants to touch any more.
And they pay five digits/day (adjusted for inflation) for that service by that time. Now that will be the only 'pleasant surprise' I presage coming from C++ to me in the foreseeable future. ;)
I get what you're saying, C++ is worlds away from where it was even 15 years ago. Don't downplay it's complexity though.
All I can say is that there should be a variation of Greenspun's tenth rule:
Any sufficiently complicated programming language becomes an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp.
Still, I want to have that C++.
--
[0] - http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p070...; the examples from the later parts of the paper show how great it would be to have something like that in C++.
While most ecosystems are moving to hermetic, reproducible builds this is going full steam on the other direction. Goodbye 'it works on my machine' hello 'it works on Jane's machine when Ryan builds it on Tuesdays. Oh Ryan WFH on Tuesday so it gets built on his home machine!'
I wanted to like this but it seems to have gone way too far. It is a college project gone wild.
But I don't understand what you mean with "an implementation trade-off"?
While here the metalanguage is itself a C++-lookalike, in my project I wound up with something that is perhaps better described as a weird TeX (which seems to be what happens naturally when your machine model is based on binding and substitution).
On one hand, C++ is surely more powerful/expressive and there is elegance to having the language and metalanguage use the same idiom. On the other, I feel like this might actually making Circle a bit more confusing to use at times, as it becomes less clear exactly when what parts of the code are executed, and you could even imagine a typo accidentally lifting a part of the code from runtime to compile time, resulting in mystifying bugs. (I am myself puzzled by the "serialize structs generically" example: does it imply that the template is specialised before the @meta for is executed?)
[1]: https://github.com/seanbaxter/circle/blob/master/gems/rpn.md...
Also, wondering when and if the source code of Circle itself will be available.
Nim has generics, templates and macors. Macros are procedural, and they make things like generating a dsl for your software or library a simple matter.
All with a reasonably simple pythonic syntax.
As a historical note, PL/I had a preprocessor that itself was a subset of PL/I. I don't recall any type safety features, but was quite useful for creating DSLs within a program.
"it's like c++ that went away to train with the league of shadows and came back 15 years later and became batman"
The repo description literally says two things: Circle is a C++ automation language, and Circle trained with the League of Shadows. The rest requires clicks.
That's a terrible way to drive adoption for something that obviously was difficult to build. Sometimes being earnest and straightforward is the best way to break down skepticism, not by using meaningless hipster taglines.
How hard is it to write a one-sentence explanation of what a project is that doesn't involve ninjas?
I wonder if C++ should pull a Python 3 and clean up the syntax. Given that the transition for Py3 took more than a decade maybe they should do it in small but frequent language upgrades instead.
As for whether it'd be considered a new language or not, it depends. I wouldn't consider Py3 a new language even though it's not backwards compatible.
I actually don't see a problem keeping the old syntax alive. I do see a problem with new programmers using obsolete constructs
The advantage of this is that I can then use the same metadata JSON to generate documentation, or whatever I want.
Second, one of the biggest issues with lisp is that macros end up sort of slow, especially when you're using them + lists to replicate ADTs with pattern matching (versus, say, ML, which can do very fast dispatch based on types). Doesn't Nim fall into that same trap?
I want to finalize my optimizations with run-time-available information - and to make run-time-definable compositions of pieces of code.
Something like this: https://blog.quarkslab.com/easyjit-just-in-time-compilation-...
but better still.
But there is no iterating over or building members of an interface (the closest thing SystemVerilog has to a user defined type).
I find the idea of using this as a rapid testing and exploration of potential new C++ features quite interesting.
I wonder how this compares to hygienic macros that some languages support?
struct ??? {
@meta for(int i = 0; i < sizeof...(types_t); ++i)
types_t...[i] @(i);
};Oh no.
$ circle taco4.cxx -I /home/sean/projects/opensource/taco/include -M /home/sean/projects/opensource/taco/Debug/lib/libtaco.so -filetype=ll
Creating compute_1 function
macro expansion: taco4.cxx:428:3
error in expansion of macro auto call_taco(const char*, const options_t&)
code injection: taco4.cxx:420:6
error thrown in @expression("c")
error: @expression:1:1
undeclared identifier 'c'
A well-defined meta language would probably have way better error messages than an accidentally-discovered language based on insane template hacks.Mix that in with a supercharged comptime constructions, and I'm quite terrified. I don't have these issues with macros anymore, thanks to templates, but I nearly prefer them.