Docs say:
Quasi-quoting operator. Accepts an expression or a block and returns the AST that represents it. Within the quoted > AST, you are able to interpolate NimNode expressions from the surrounding scope
By this, I guess it likely means it pastes the sub-tree in at the given position? Or does it truly interpolate it in then reconstruct the AST from the resulting text?
I was trying to extend the class OOP programming macro form nim by example to create parametrized classes (e.g. Cage[Animal]. Is this even a sane idea? I notice expandMacros refers to expanding one level of macros, but I'm not sure that generics that come out of macros get handled?
I notice that
dumpTree:
class Cage[Animal] of RootObj:
var occupant: T
shows a BracketExpr node, while
dumpTree:
type Cage[Animal] of RootObj:
shows a GenericParams node, with no BracketExpr node anywhere. But I guess there's no reason to be scared about the lack of a common factor since BracketExpr is more general and the parser only produces GenericParams in a type context? Just recreate tree to taste?
This simple quote() code also confuses me:
import future
import macros
macro decDumbType(): untyped =
result =
macros.quote do:
type Dumb = ref object of RootObj
contents: int
method frobnicate(this: Dumb) {.base.} =
echo "frobnicating!"
expandMacros:
decDumbType()
by producing this:
- type
- Dumb112019 = ref object of RootObj
- contents: int
method frobnicate(this112017: Dumb112015) {.base.} = echo ["frobnicating!"]
generic_obj_mac.nim(31, 1) template/generic instantiation from here generic_obj_mac.nim(32, 14) Error: illformed AST: method frobnicate(this112017:
- Dumb112015) {.base.} =
- echo ["frobnicating!"]
why is Dumb being rewritten?
expandMacros with its conversion to typed is really fragile with today's compiler. Instead use this to see what's going on:
import future
import macros
macro decDumbType(): untyped =
result =
macros.quote do:
type Dumb = ref object of RootObj
contents: int
method frobnicate(this: Dumb) {.base.} =
echo "frobnicating!"
echo repr result
decDumbType()
- type
- Dumb112023 = ref object of RootObj
- contents: int
- method frobnicate(this112025: Dumb112023) {.base.} =
- echo "frobnicating!"
and I still don't understand why Dumb turns into Dumb112023, maybe I will later
Sorry to hear it breaks for you, it works on my compiler. :-/
But give quote + getAst at try, it's recommended over quote-do anyway, if I recall.
import macros
macro decDumbType(): untyped =
let sym = genSym(nnkType, "Dumb")
template decl(ty) =
type Dumb = ref object of RootObj
contents: int
method frobnicate(this: Dumb) {.base.} =
echo "frobnicating!"
result = getAst(decl(sym))
echo repr result
decDumbType()