Why two different macros functions share variable namespace in Nim?

Viewed 106

The code below won't compile, because of redeclaration of the let a variable.

But if the second test template commented out it would work.

Why it works that way, and how to fix it?

playground

template test*(name: string, body) =
  block: body

template test*(name: string, group: string, body) =
  block: body

test "a1":
  let a = 1

test "a2":
  let a = 1
1 Answers

The body argument to the first template gets typechecked as there is an overload on it where there is a typed argument in the same place. I think your best option for now is to remove the : string annotation on group. To fix this Nim needs to alter its overload semantics in a case like this where it's obvious the arities don't match, but that might be unpredictable.

Thanks to hlaaftana for providing the answer in the GitHub Issue

So the fixed code would be:

template test*(name: string, body) =
  block: body

template test*(name: string, group, body) =
  block: body

test "a1":
  let a = 1

test "a2":
  let a = 1
Related