Hi,
I have stumbled upon an issue with imports and $. Here is the sample code:
nim_example/token.nim
import strformat
type
Token* = object
token_type*: string
proc `$`*(self: Token): string =
return fmt"TokenType: {self.token_type}"
proc print_ident*(self: Token) =
echo "<some id>"
nim_example/scanner.nim
import token
type
Scanner* = object
source*: string
tokens: seq[Token]
proc scanTokens*(s: var Scanner): seq[Token] =
# (...)
s.tokens.add(Token(token_type: "EOF"))
return s.tokens
This code produces an import error (as expected):
nim_example.nim
import nim_example/scanner
# import nim_example/token -> because token is not imported
when isMainModule:
var s = Scanner(source: "some source")
var tokens = s.scanTokens()
for token in tokens:
token.print_ident()
--> /src/nim_example.nim(8, 10) Error: attempting to call undeclared routine: 'print_ident'
But this code does not produce an import error and produces the wrong output:
nim_example.nim
import nim_example/scanner
# import nim_example/token <-- if this is uncommented then it works
when isMainModule:
var s = Scanner(source: "some source")
var tokens = s.scanTokens()
for token in tokens:
echo token
--> Current output: `(token_type: "EOF")`
--> Expected without token import: compilation error
--> Expected with token import: 'TokenType: EOF' (this works)
It's a problem, because the $ code fails silently - it appears to be working, but the echo output is wrong. Is there some best practice to prevent such errors or is it maybe a compiler limitation?
the $ code fails silently
the code is not failing, in system (automatically imported) is defined a generic $ that is used by echo (and it would be overriden by the more specific $ in token.nim if imported).
I would say this behaviour is expected and there is nothing wrong about it.
n our code we some times add extra exports so that people don't have to write a bunch of imports just to use our code.
For example adding export token in scanner.nim so that importing scanner would also import token.
But we only do this for public APIs in topmost files: https://github.com/treeform/pixie/blob/master/src/pixie.nim#L7
import bumpy, chroma, flatty/binny, os, pixie/common, pixie/contexts,
pixie/fileformats/bmp, pixie/fileformats/gif, pixie/fileformats/jpeg,
pixie/fileformats/png, pixie/fileformats/ppm, pixie/fileformats/qoi,
pixie/fileformats/svg, pixie/fonts, pixie/images, pixie/internal,
pixie/paints, pixie/paths, strutils, vmath
export bumpy, chroma, common, contexts, fonts, images, paints, paths, vmath