I'm writing a macro that parses over object types and generates various functions on it's fields. For the most part it works.
However, I'm will likely encountering folks trying to do this:
type
ssnType = Option[int]
type
Person = object
age: Option[int]
ssn: ssnType
My macro can handle the "age" field because it's true type is easily parsed in the Node tree. Both "Option" and "int" are known types and in a bracket. Got it.
"ssnType" is also visible, but that is an unknown type made by the library user.
Is there a way, given the string or symbol "ssnType", to somehow glean it's earlier definition of "Option[int]"?
I've tried various plays with getTypeImpl and getTypeImpl, but I suspect I'm missing some key knowledge.
Here you go
import macros, options
type
ssnType = Option[int]
type
Person = object
age: Option[int]
ssn: ssnType
proc isOptionInt(x: NimNode): bool =
sameType(x, getType(Option[int]))
macro checkOptionInt(x: typed): untyped =
result = newLit(x.isOptionInt)
echo checkOptionInt(typeof(Person().ssn))
Note that you can turn a typedesc into a NimNode with getType, but there is no way to turn a NimNode representing a type back to a typedesc, and the corresponding feature request was closed (https://github.com/nim-lang/Nim/issues/6785), so keep your typedescs around as long as possible.
You can get the ssn typedef with this:
macro ssnTypeImpl(T: typedesc): untyped =
let ssnField = T.getType[1].getType[2][1]
echo ssnField.getTypeInst.getImpl.treeRepr
ssnTypeImpl(Person)