Hello. How to check type inside macro?
import macros
type
T1 = object
s : string
proc checkTypeProc( t : typedesc )=
if t is T1:
echo "proc: is T1"
else:
echo "proc: not T1"
macro checkTypeMacro(t:static[typedesc]):untyped=
if t is T1:
result = quote do: echo "macro: is T1"
else:
result = quote do: echo "macro: not T1"
if isMainModule:
checkTypeProc(T1)
checkTypeMacro(T1)
# Output:
# proc: is T1
# macro: not T1
And unfortunately typeof(t) doesn't work either.
Found a workaround for places where type is still accessible. Call template that wraps macro and unpacks type data into macro's arguments.
import macros
type
T1 = object
s : string
T2 = object
proc checkType_Proc( t : typedesc )=
if t is T1:
echo "proc: ", t, " is T1"
else:
echo "proc: ", t, " is not T1"
macro checkType_Macro(t:static[typedesc]):untyped=
if t is T1:
result = quote do: echo "macro: ", $`t`, " is T1"
else:
result = quote do: echo "macro: ", $`t`, " is not T1"
template checkType_Template(t:typedesc)=
checkType_TemplateMacro( $`t`, t is T1 )
macro checkType_TemplateMacro( typeName: static[string], isT1: static[bool] ):untyped=
if isT1:
result = quote do: echo "templateMacro: ", $`typeName`, " is T1"
else:
result = quote do: echo "templateMacro: ", $`typeName`, " is not T1"
if isMainModule:
checkType_Proc(T1)
checkType_Proc(T2)
echo ""
checkType_Macro(T1)
checkType_Macro(T2)
echo ""
checkType_Template(T1)
checkType_Template(T2)
# Output
# proc: T1 is T1
# proc: T2 is not T1
#
# macro: T1 is not T1
# macro: T2 is not T1
#
# templateMacro: T1 is T1
# templateMacro: T2 is not T1