I am working on a structured logging library for Nim similar to ln. I am having an issue with passing concepts to functions:
import streams, strutils, tables
type
F* = Table[string, string]
Fer* = concept x
x.f() is F
proc quoteIfContainsWhite*(s: string): string =
if find(s, {' ', '\t'}) >= 0 and s[0] != '"':
result = '"' & s & '"'
else:
result = s
type myfoo = object
bar: string
baz: string
proc f(m: myFoo): F =
result = {"myFoo:bar": m.bar, "myFoo:baz": m.baz}.toTable
proc log*(fer: Fer) = log fer.f()
proc log*(fs: varargs[F]) =
var res = ""
for f in fs:
for key, val in f.pairs:
res &= "$1=$2 " % [key, val.quoteIfContainsWhite]
echo res
when isMainModule:
let foo = myFoo(bar: "spam", baz: "eggs and ham")
log foo.f()
#log foo
import unittest
suite "slog":
test "type assertions":
check:
myFoo is Fer
test "key->val pairs directly work":
let myf = {"foo": "bar"}.toTable
check:
compiles: log myf
test "logging objects":
let foo = myFoo(bar: "this is a value", baz: "this is another value")
check:
compiles: log foo
if you uncomment the "log foo" line above, the compiler fails build with the following error:
[~/c/s/src] : nim --listCmd -r c slog.nim --verbosity:3
Hint: used config file '/home/xena/.choosenim/toolchains/nim-#devel/config/nim.cfg' [Conf]
Hint: system [Processing]
Hint: slog [Processing]
Hint: streams [Processing]
Hint: strutils [Processing]
Hint: parseutils [Processing]
Hint: math [Processing]
Hint: algorithm [Processing]
Hint: tables [Processing]
Hint: hashes [Processing]
slog.nim(1, 2) Hint: 'x' is declared but not used [XDeclaredButNotUsed]
slog.nim(34, 7) template/generic instantiation from here
slog.nim(21, 27) Error: type mismatch: got (F)
but expected one of:
proc log(fer: Fer)
slog.nim(34, 7) template/generic instantiation from here
slog.nim(6, 6) Fer: type mismatch: got (Alias)
but expected one of:
proc f(m: myfoo): F
slog.nim(34, 7) template/generic instantiation from here
slog.nim(6, 5) Fer: concept predicate failed
What am I doing wrong?