Compile a string

How would you go about compiling a string containing zig code? I had a look at src/main.zig but my head hurts now…

Write it to a file, invoke the compiler on it.

This is actually why the build system is important. This exact maneuver that @kristoff is mentioning is one of the reasons why C++ codebases get complicated (see numpy’s ndimensional array implementation). They generate files on the fly that other existing files depend upon that don’t exist yet. In the case of numpy, they create piles of code this way using a foreign build system that is already hard to reason about.

If you keep it simple and use the build system to do this, you can keep all of this logic in one place and what @kristoff is mentioning becomes fairly easy to reason about.

More generally, the point is that there’s no eval() in Zig and that 99% of the time this kind of metaprogramming urge should not be indulged.

Instead of operating on strings, in Zig is more idiomatic to go through comptime and give semantic structure to what you’re doing.

In the remaining 1% of cases, you might be in a situation where you can’t use comptime and so the correct solution, as AndrewCodeDev suggested, is to use the build system to orchestrate a codegen process.


Thank both of you for your answer.

So for the record, let’s assume that I am in the 1% of case that needs this, my understanding is that, to the question “How do I compile a string in zig”, the actual answer is: “you can’t”, which is a perfectly reasonable answer to me.

Thanks again!

Edit: Had a look at zls and this is indeed their strategy. They just call ChildProcess with the zig compiler. I naively though they would just embed a zig compiler.