3

here' a code I want to compile:

macro defineSomething(amount:expr):stmt=
   var amountInt = intVal(amount).int
   # Boring staff

defineSomething(42);

It works perfectly. I have all I want inside my macro I can operate staff in my own way.

But then I think, that, It would be better to remove magic number to some const settings:

const MAGIC_AMOUNT:int = 42

# Whole lot of strings
defineSomething(MAGIC_AMOUNT)

This code fails. Because MAGIC_AMOUNT literally is not integer value unlike 42 magic number.

So, how to get my variable value inside the macros in nim?

Vasiliy Stavenko
  • 1,174
  • 1
  • 12
  • 29

2 Answers2

4

By default, macros will receive AST expressions and not values. If your macro needs to work with concrete values, you need to use static parameters:

macro defineSomething(amount: static[int]): stmt=
  echo "int value: ", amount + 100

const MAGIC_AMOUNT = 42

defineSomething(43)
defineSomething(MAGIC_AMOUNT)

This will print at compile-time:

int value: 143
int value: 142
zah
  • 5,314
  • 1
  • 34
  • 31
3

Expressions are untyped. Since you really want to get integers you can specify the parameter to be typed and then this should compile:

import macros

macro defineSomething(amount: typed):stmt=
  echo getType(amount)
  var amountInt = intVal(amount).int
  echo "Hey ", amount_int

const MAGIC_AMOUNT = 42
defineSomething(43)
defineSomething(MAGIC_AMOUNT)

Or just use a normal int as the parameter type unless you want to be passed other types as well to case on the parameter's kind inside your macro.

Grzegorz Adam Hankiewicz
  • 7,349
  • 1
  • 36
  • 78