r/ProgrammingLanguages • u/chri4_ • Jan 01 '26
Unpopular Opinion: Source generation is far superior to in-language metaprogramming
It allows me to do magical reflection-related things in both C and C++
* it's faster than in-language metaprogramming (see zig's metaprog for example, slows down hugely the compiler) (and codegen is faster because the generator can be written in C itself and run natively with -O3 instead of being interpreted by the language's metaprogramming vm, plus it can be easily be executed manually only when needed instead of at each compilation like how it happens with in language metaprog.).
* it's easier to debug, you can print stuff during the codegen, but also insert text in the output file, but also execute the script with a debugger
* it's easier to read, write and maintain, usually procedural meta programming in other languages can get very "mechanical" looking, it almost seems like you are writing a piece of the compiler for example
pub fn Vec(comptime T: type) type {
const fields = [_]std.builtin.Type.StructField{
.{ .name = "x", .type = T, .default_value = null, .is_comptime = false, .alignment = 0 },
.{ .name = "y", .type = T, .default_value = null, .is_comptime = false, .alignment = 0 },
.{ .name = "z", .type = T, .default_value = null, .is_comptime = false, .alignment = 0 },
.{ .name = "w", .type = T, .default_value = null, .is_comptime = false, .alignment = 0 },
};
return @Type(.{ .Struct = .{
.layout = .auto,
.fields = fields[0..],
.decls = &.{},
.is_tuple = false,
}});
}versus sourcegen script that simply says "struct {name} ..."
* it's the only way to do stuff like SOA in c++ for now.. and c++26 reflection looks awful (and super slow)
* you can do much more with source generation than with metaprogramming, for example I have a 3d modelling software that exports the models to a hardcoded array in a generated c file, i don't have to read or parse any asset file, i directly have all the data in the actual format i need it to be.
What's your opinion on this? Why do you think in language meta stuff is better?
86
u/The_Northern_Light Jan 01 '26
It is, and that’s a failing of the language, not a universal truth.
5
u/yuri-kilochek Jan 01 '26 edited Jan 01 '26
How do you e.g. reflect structs from libraries you don't control this way?
29
u/apocalyps3_me0w Jan 01 '26
it's easier to read, write and maintain
I think that is very debatable. I like the flexibility of code gen when language/library limitations make it hard to do it any other way, but having no IDE support makes it much easier to make mistakes, and you have the hassle of another build step.
3
u/bl4nkSl8 Jan 02 '26
The problems you list appear to be implementation details and are due to languages not optimizing the hell out of metaprogramming because they weren't designed as the primary programming approach.
You're also assuming that compiling code to do code gen, running it and then compiling the output is faster than interpretation... Which I think is questionable.
So yes, an unpopular opinion for multiple reasons.
18
u/pauseless Jan 01 '26 edited Jan 01 '26
What distinction are you drawing here? These are all different approaches to metaprogramming:
Lisp macros
Hell, there are even languages that do all their metaprogramming at runtime (Tcl)
I’m fine with all of them. My preference is lisp tradition, but I make do whatever.
What do you mean by enabling magical reflection things? In terms of what you can express, that’s most powerful in the languages with late binding and everything being dynamic. There’s obviously the danger argument there, and I don’t argue with that; one accepts the risk.
If the argument is just codegen and let the type system check it… fine. I’m very happy doing that when I write Go for money. I think codegen, by definition, lacks the expressivity and power of other languages, but it is also a nice constraint that does help prevent you being surprised.
Edit: I don’t get the Zig point. It’s plenty fast enough, and compile time is a one off cost. As long as it’s good enough, it’s fine. Nonetheless, the codegen cost is the same, no?
Edit 2: the last bullet point is just preprocessing data in the format you want.
37
u/divad1196 Jan 01 '26 edited Jan 01 '26
Metaprogramming isn't the same in all languages. C++ is more about reusability, Rust/Elixir allow you to define new syntax. There are many tools that does code generation, like Prisma.
It's not so much about "superior", they are different. Metaprogramming ships with the library, not the code generator. It also generate only things you need. For example, in C++, your template will generate the classes you need. With your code generation, you need to deal with it yourself.
There are a lot pros in favor of metaprogramming and you should be able to figure them out yourself, otherwise it's a clear sign that you didn't spend enough time on it. When you have multiple populat solutions, if you think that one is in all case superior, then you certainly don't know enough other solutions.
8
u/needleful Jan 01 '26
It depends on what you're doing. If you're doing compile-time reflection, like getting the fields of a struct or arguments to a function, there's no reason to run half the compiler a second time to get that information again in a script, not to mention the headache of turning a compiler into a library and learning how to use its API, rather than a syntax designed for metaprogramming.
A lot of metaprogramming is pure syntax transforming, though, like most Rust and Lisp macros, and for those I see the benefits you're talking about. If the compiler doesn't provide any information beyond the text, you might as well process it as text and get the performance and debugging from a separately compiled executable.
15
u/Smallpaul Jan 01 '26
Now try composing three or four different transformations.
13
u/poralexc Jan 01 '26
If you're using comptime for everything in Zig you're doing it wrong.
There are facilities for adding source generation steps like you mention in Zig's build system. I've got a few simple tools that setup microcontroller memory layouts from json config for example.
6
u/matthieum Jan 02 '26
Trade-offs!
Your statement is, simply put, way too generic. You've forgotten about trade-offs.
There are trade-offs to both meta-programming & source generation, and as such neither is strictly better or worse than the other: it very much depends on the usecase.
I'll use Rust as an example:
And since we're talking about Rust, this is leaving aside procedural macros & generic meta-programming, which also have their uses.
There's no silver bullet.
4
u/Sufficient_Meet6836 Jan 01 '26
Which languages implement your preferred way to do this?
4
u/theangeryemacsshibe SWCL, Utena Jan 02 '26
quasiquotation
6
u/Soupeeee Jan 01 '26
I have a lisp based project that uses macros and external code generation. They are useful for different things. The code generation takes a bunch of XML and C source files and output lisp code. These input files rarely change, and no type checking or any other processesing really needs to o be done. That's what external generation is good for.
Macros are better when you want to make language level changes or need to do something that would benefit other language facilities like type checking. Programming is code generation all the way down, and compilers are just really specialized generators.
3
u/PurpleYoshiEgg Jan 01 '26
The Fossil source code uses three preprocessors (four, if you count the C preprocessor) to help its C usage, especially containing HTML output via the second step translate.c.
I think code generation makes sense when used judiciously, and Fossil's use for it seems quite well-intentioned.
3
u/dist1ll Jan 01 '26
Interpreter is not the only way. If you want you can use a JIT compiler for the CTFE engine.
3
u/kwan_e tonal-lang Jan 02 '26
I actually agree, coming from C++. People got too carried away with the cool-kids template tricks, when they really should have begun the process of opening up the AST for compile-time programming.
The main problem with source generation is development environment integration, which isn't a problem if it is actually AST generation, rather than generation of literal text.
3
u/AlexReinkingYale Halide, Koka, P Jan 02 '26
Worth noting that your last use case is/will be covered by #embed in C23/C++26. It will feature much better performance than running a large textual array through the parser.
3
u/Ronin-s_Spirit Jan 02 '26
Can you clarify for me what's "in language" and what's "out language"? Why is Zig there in the mix? I thought it has compiler functions. What does C have to do with this? I thought it only has text based macros.
6
u/DokOktavo Jan 01 '26
I disagree with a lot of what you said :)
My main critique is boring: they're not the same tools, they don't have the exact same set of use cases, nor the same trade-offs.
I basically only use Zig now and I think the way it does metaprogramming is fantastic.
metaprogramming is slower than codegen, that I agree with. Although part of metaprog could be cached (not the case rn if i'm not mistaken).
if I'm doing logic-heavy stuff, the debugger does come in handy, and I do think it's a better use-case for codegen. But othewise
@compileErrorand@compileLogdo the trick just fine.Very bad example of hard to read-debug-maintain. This is the idiomatic and common way to do it:
This is very readable, debuggable and easy to maintain.
std.MultiArrayListwith codegen?As I said: they're not the same tool, you got to have both. Zig has both: the build system let's you write an executable (in Zig, or in C, or both, or fetch one), run it, and extract it's output in a
LazyPaththat can be the root of a Zig module. Bonus: it automatically uses the cache system, and works with ZLS. But the metaprogramming is still Zig's big strength imo. It makes some logic almost trivial to write, when it would be a hassle by just generating the source code, the tokens or even the AST. And if you want to generate the semantics, just write your own DSL at this point.2
u/GLC-ninja Jan 02 '26
I agree with this opinion. I literally created a language (Cp1 programming language) to make source generation a lot easier so I could simplify repetitive codes in my game. Debugging by looking at the generated source code is a huge plus, compare it to errors you get when using C++ templates. Not to mention that source generated codes can be cached and only regenerated in some conditions, making it really faster than the other.
2
u/gwillen Jan 03 '26
The main thing you lose is source-level error-reporting and debugging. If you can get that working with something like source maps, I think you've got a good proposition.
Of course, you also have big problems if your source generation / transformation step has bugs, which can give misleading failures in the generated code. And if you don't have very solid error checking in the generation / transformation step, you can end up with mysterious errors in the result, very far from the actual error in the input.
Basically, I think if you can get good error reporting and debugging facilities, this is probably great, and otherwise you will probably eventually regret it.
3
u/XDracam Jan 01 '26
C# fully agrees. A lot of frameworks and tools are moving from reflection to source generation, e.g.
[Regex]and JSON/MsgPack serialization. Every language should support something similar to Roslyn Analyzers and Generators.2
u/No_Pomegranate7508 Jan 01 '26
Hygienic macros are all you need?
1
u/SylvaraTheDev Jan 01 '26
Depends on lang. Metaprogramming in Elixir is quite nice.
1
u/AndreVallestero Jan 03 '26
Luckily, rust has both.
build.rsis provided as an escape hatch, but it's been super useful for the few times that I've actually needed it. In particular, it's superb for performance when needed to embed resources into the binary.1
u/max_buffer Jan 03 '26
LISP metaprogramming is great, so...
1
u/OldManNick Jan 04 '26
Lean 4, you can even define 2d syntax in it. https://github.com/dwrensha/lean4-maze/blob/main/Maze.lean. As soon as metaprogramming is defined, you can use it the very next line
1
u/tending Jan 05 '26
You only think this because the languages you use have terrible metaprogramming support. Learn lisp.
1
u/freshhawk Jan 12 '26
But you run in to the same problem as you always do when generating text (source code, sql statements, html, whatever). Composition and abstraction are too difficult once you start doing non-trivial stuff. Concating strings is nightmare so first you probably reach for a placeholder replacing template language, but they don't compose (or if it isn't logic-less like it should be and it is complex enough for that then it's not a templating language, it's a second much crappier language you're working with).
Next you end up where everyone does, some datastructure that represents the text (be it query or html or source or document fragment or whatever) that you can manipulate and wrap in abstractions, etc, etc. But when doing this with source that's just an AST or CST abstraction, which is ... metaprogramming. You also probably start to really appreciate what those lisp people are going on about when you see they have one less layer of abstraction between the data and the source.
So you aren't wrong, but if you keep going and try to do interesting stuff you're going to end up dealing with the complexity somehow and you definitely want to go more in a lispy direction than a c++ template lang direction since we've all learned from that mistake. You're going to end up using metaprogramming for the complex stuff eventually, insisting that using an array of text bytes as the data structure to store the tree you are manipulating is just silly at a certain point.
-1
u/Working_Bunch_9211 Jan 02 '26
There is should be no source generation, only metaprogramming, metaprogramming is superior
-15
u/ineffective_topos Jan 01 '26
In 2025 I think this is definitely the way. If nothing else more and more code is written by AI which doesn't have to waste any time on keystrokes (although more LOC is more chance for errors; that chance is dropping every few months)
There's a place for macros though e.g. in Rust derive macros, and they tend to just be much more trustworthy and consistent.