Hey, I'm trying to do some interop with another language during compile time and I'm wondering if there's a way to infer the base type of an object by somehow climbing the AST either forwards from root or backwards from a leaf (preferably backwards).
Say I have this case
impost std/macros
type MyInt = int
dumpTree:
proc test(a: MyInt): void = discard
the result of which is
StmtList
ProcDef
Ident "test"
Empty
Empty
FormalParams
Ident "void"
IdentDefs
Ident "a"
Ident "MyInt"
Empty
Empty
Empty
StmtList
DiscardStmt
Empty
Is it possible to climb the AST from within the macro knowing the identity of MyInt is the leaf node. I need to somehow resolve it into int. I know that when I would need to terminate as there's only a couple primitive types I need this to expand to in cases where these objects would subclass something else.
You'll want to use getType, getImpl and friends. Depends a bit on your exact use case, but creating a working example (that is a bit useless), for example:
import macros
type MyInt = int
proc test(a: MyInt): void = discard
macro foo(fn: typed): untyped =
let fnImpl = fn.getImpl
let p = fnImpl.params
let arg = p[1] # argument 1
let typ = arg[1] # type of first argument
echo typ.getType.treerepr
# Sym "int"
foo(test)
For the getType etc. procedures, see:
https://nim-lang.github.io/Nim/macros.html#getType%2CNimNode