Hello,
I am trying to write a language that compiles to nim. But i can't find out how to generate nim code and then transform it to a string. I have this "dumb" proc, but i get this error Error: request to generate code for .compileTime proc: newCall
proc parser(tokens: seq[string]): string =
var tokens_left = tokens
let test_node = newCall("echo", newIntLitNode(0))
return $test_node
I tried with a macro as such :
macro parser(tokens: seq[string]): untyped =
var tokens_left = tokens
let test_node = newCall("echo", newIntLitNode(0))
return test_node
let code = parser(tokens).repr()
But in this case i get this error : Error: expression 'echo(["0"])' has no type (or is ambiguous)
Does anyone have an idea on how to do this? I don't want to generate the code by directly writing out strings to be sure i generate valid nim code. This is why i thought about using nim's ast directly.
Thank you
Nim's macro system works at compile-time, so your language would need to be fed into the macro as constant strings. This is unlikely what you want, instead use the Nim compiler as an API.
See for example how c2nim does it: https://github.com/nim-lang/c2nim/blob/master/c2nim.nim#L108
You then need to work with PNode instead of NimNode but the ASTs are nearly identical.
If you just want to hack around for fun you can do something like this:
import macros
macro parser(tokens: static seq[string]): string =
var tokens_left = tokens
var test_node = newCall("echo")
for token in tokens:
test_node.add newLit(token.len)
return newLit(repr(test_node))
const
tokens = @["hello", "world"]
code = parser(tokens)
echo code
But as Araq pointed out Nim's macro system works on compile-time, so all of your compilation would happen while compiling the Nim program.
You could have a look at nimja (.https://github.com/enthus1ast/nimja ).
It is not a full blown language on its own, but it still resembles all parts of a language/compile: Lexing/Tokenizing, Parsing, Code generation.
Lexing: https://github.com/enthus1ast/nimja/blob/master/src/nimja/lexer.nim
Parsing: https://github.com/enthus1ast/nimja/blob/master/src/nimja/parser.nim#L107
Code generation: https://github.com/enthus1ast/nimja/blob/master/src/nimja/parser.nim#L254