Hi,
How does the compiler work? Here is what I understand/think right now, please correct me if I'm wrong.
Let's compile to binary with gcc. There are two kind of operations: which can be run at compile time (magic functions), and which cannot be run at compile time (for example functions call to C code with importc). The statements and expressions with type macro, const, template and when are calculated at compile time, and then the code is converted to a tree (Abstract Syntax Tree), which is compiled to C source. Gcc is called to create the binary.
Thus the compiler must be able to evaluate the AST as long as it contains simpler magic functions. Is this fast?
Let's assume that I want to generate code at runtime.
Thanks, Peter
compiler/nimeval.nim exports a proc execute*(program: string) which does what you're after: It compiles a Nim program to Nim's AST then to bytecode and then runs the bytecode. compiler/vmops.nim shows how some math and os procs are hooked into the VM so that they can be run even though they end up using importc'ed stuff at runtime.
You just need to install the compiler Nimble package for this to work, but I'm not aware of anybody who uses it, so ... there be dragons.
Is it fast? I beat Python's VM in the tests that I did with it. So Nim interprets code faster at compile-time than Python does at runtime. Ymmv of course.
Thank you, both.
@Araq I like dragons, so I'll report them when I find one.
Thanks, Peter
I tried to use compiler as a dependency, but it appears that trying to use compiler >= 0.11.2 fails, and the last version published on Nimble is 0.10.3. This version, though, does not work with nim 0.11.2 (which I guess makes sense).
Would it be possible to get a later version published on nimble?