I'm trying to iterate only a slice of the children of a NimNode, but i'm not able to find a way to do it
macro xyz(body: untyped): untyped =
for child in body[1 .. ^1]:
echo child.astGenRepr
xyz:
var q = 1
var p = 2
var r = 3
Produces:
/usercode/in.nim(2, 22) Error: type mismatch: got <NimNode, HSlice[system.int, system.BackwardsIndex]>
but expected one of:
proc `[]`(s: string; i: BackwardsIndex): char
first type mismatch at position: 0
proc `[]`(s: var string; i: BackwardsIndex): var char
first type mismatch at position: 0
proc `[]`[I: Ordinal; T](a: T; i: I): T
first type mismatch at position: 0
proc `[]`[Idx, T; U, V: Ordinal](a: array[Idx, T]; x: HSlice[U, V]): seq[T]
first type mismatch at position: 0
proc `[]`[Idx, T](a: array[Idx, T]; i: BackwardsIndex): T
first type mismatch at position: 0
proc `[]`[Idx, T](a: var array[Idx, T]; i: BackwardsIndex): var T
first type mismatch at position: 0
proc `[]`[T, U: Ordinal](s: string; x: HSlice[T, U]): string
first type mismatch at position: 0
proc `[]`[T; U, V: Ordinal](s: openArray[T]; x: HSlice[U, V]): seq[T]
first type mismatch at position: 0
proc `[]`[T](s: openArray[T]; i: BackwardsIndex): T
first type mismatch at position: 0
proc `[]`[T](s: var openArray[T]; i: BackwardsIndex): var T
first type mismatch at position: 0
template `[]`(s: string; i: int): char
first type mismatch at position: 0
expression: `[]`(body, 1 .. BackwardsIndex(1))
Is there a way to achieve that ?
One way is to capture all elements into a sequence and then iterate over it:
import std/[macros, sequtils]
macro xyz(body: untyped): untyped =
let children = toSeq(body.items())
for child in children[1 .. ^1]:
echo child.astGenRepr
xyz:
var q = 1
var p = 2
var r = 3
Don't forget that you can use almost all of Nim stdlib during compile-time :)
The easiest way to do it is to import the macros module which includes the slice operator for the NimNode type:
import macros
macro xyz(body: untyped): untyped =
for child in body[1 .. ^1]:
echo child.astGenRepr
xyz:
var q = 1
var p = 2
var r = 3
Oh yes, it seems to work when importing macros indeed.
Side question, is this not working because .children is a function call returning some kind of iterator right ?
for child in body.children[1 .. ^1]: