Consider I have these modules which define the same functions (only implementation differs):
-math_precise.nim
-math_optimal.nim
-math_fast.nim
Now I want to include them based on compile-time option.
I know I can use
const math {.strdefine.}: string = "precise" # default value
when math == "precise": # <-- here I hardcode possible values
import math_precise
elif math == "fast":
import math_fast
And then
nim c -d:math:fast
1) What if I don't want to hardcode modules names and just import by name? Like
const math {.strdefine.}: string = "precise" # default value
import "math_" & math # <-- Error: invalid module name :( I guess I should play with macros?
2) Also, is there any way to import module by absolute location?
import /tmp/math_superfast
@Araq How can I do it with macros? getImpl returns the const's default value, not the strdefined one:
import macros
const module {.strdefine.}: string = "math"
macro importconst(name: string): untyped =
let value = name.symbol.getImpl
echo "variable name: ", name.repr
echo "default value: ", $value
result = newNimNode(nnkImportStmt).add(value)
static:
echo "actual value: ", module
importconst(module)
# for -d:module=ropes it prints:
# variable name: module
# default value: math
# Hint: math [Processing]
# actual value: ropes
I encountered this problem a few times before, actually. What we need here is a routine input of which are normal variables but output of which is code. But we only have code2code (macros) and data2data (procs)...
@Udiknedormin Here you can use static types that passes data to macros instead of a NimNode
import macros
const module {.strdefine.}: string = "math"
macro importconst(name: static[string]): untyped =
#let value = name.symbol.getImpl
#echo "variable name: ", name.repr
#echo "default value: ", $value
result = newNimNode(nnkImportStmt).add(newIdentNode(name))
static:
echo "actual value: ", module
importconst(module)
Same for import as statement, if anyone cares:
import macros
macro importString(path: static[string], alias: static[string]): untyped =
result = newNimNode(nnkImportStmt).add(
newNimNode(nnkInfix).add(
newIdentNode("as")
).add(
newIdentNode(path)
).add(
newIdentNode(alias)
)
)
importString("strutils", alias="su")