Hello folks,
Does anyone know why templates don't "auto-import" symbols defined in their residence file? :( Minimal example:
# test.nim
import strutils
template test_template*() =
echo (1.0/3.0).formatFloat(precision=3)
proc test_proc*() =
echo (1.0/3.0).formatFloat(precision=3)
# other.nim
import test
test_proc() # ok
test_template() # fail:
# /tmp/other.nim(4, 14) template/generic instantiation of `test_template` from here
# /tmp/test.nim(5, 17) Error: attempting to call undeclared routine: 'formatFloat'
Is it a new feature or a bug? I think it worked in a different way some time ago.
Nim Compiler Version 1.1.1 [Linux: amd64]
Compiled at 2020-02-25
git hash: db540a0223480134598fb4806c55510cdef36bf1
It works if you define it like this:
# test.nim
import strutils
template test_template*() =
echo formatFloat(1.0/3.0,precision=3)
#echo (1.0/3.0).formatFloat(precision=3)
proc test_proc*() =
echo (1.0/3.0).formatFloat(precision=3)
Still seems like a bug.Hmm, I think it always worked like this. Template just substitute code. If the code where you have template can't access some thing... then it's an error.
It also is an error if template calls a private proc:
proc b() = # private b
echo "hi"
tempalte a*() = # public a
b()
Calling a() in another module will not work because b() is private.
it works if you change the template:
template test_template*() =
echo formatFloat((1.0/3.0), precision=3)
See https://nim-lang.org/docs/manual.html#templates-limitations-of-the-method-call-syntax and https://nim-lang.org/docs/manual.html#generics-symbol-lookup-in-generics
Your code works @treeform as long as you fix the typo in tempalte
proc b() =
echo "hi"
template a*() =
b()
Inside template a, b is a sym,closedSymChoice or openSymChoice so it works regardless of whether or not b is private or not.
use bind
import strutils
template test_template*() =
bind formatFloat
echo (1.0/3.0).formatFloat(precision=3)
proc test_proc*() =
echo (1.0/3.0).formatFloat(precision=3)
https://nim-lang.org/docs/manual.html#generics-bind-statement
https://github.com/nim-lang/Nim/wiki/Nim-for-Python-Programmers#Templates
Far from perfect, but better than nothing, Templates explanation.