Hello,
im trying to define a type with a template using this code
template createType(name, fields: untyped): untyped =
type name = ref object
fields
createType foo:
bar: int
buz: float
Now from my understanding this should be turned into:
type foo = ref object
bar: int
buz: float
but when i compile this code i get this error
Error: ':' or '=' expected, but got 'createType'
Now i have a feeling that i simply misunderstanding how templates work but from the nim documentation theyre described as follows
A template is a simple form of a macro: It is a simple substitution mechanism that operates on Nim's abstract syntax trees. It is processed in the semantic pass of the compiler.
and as i understand, any parameter is simply replaced by the argument called with the function, i also know that i could just use macro's but they seem overkill for what im trying to do.
Any help would be appreciated, Thanks.
The syntax trees are for better or worse are indeed not the same so the substitution fails. In one case it's and nnkIdentDef node, in the other a nnkExprColonExpr node.
You need a macro to do it properly but even then it's a bad idea because your createType macro doesn't do anything useful and once it does, it obfuscates that a type construction is going on.
The better solution is:
macro declareOps(x: untyped): untyped = ...
declareOps:
type foo = ref object
bar: int
buz: float
Thanks for your reply,
I think my misunderstanding came from the fact that i assumed that templates simply replaced the code with argument, not the tree itself but the text, but now i see that i would probably lead to many issues if you simply replaced the text.
Also the example i gave left out a lot of code just to show the core error i was having.
Thanks for your help!!