Reputation: 15366
Why this string to enum converter macro fails to compile? play
import std/macros, std/strutils
macro autoconvert(TT: type[enum]) =
let fname = "to" & $(TT)
quote do:
converter `fname`*(s: string): `TT` = parse_enum[`TT`](s)
type Tag* = enum movies, books
autoconvert Tag
Error
play.nim(12, 13) template/generic instantiation of `autoconvert` from here
play.nim(7, 3) Error: identifier expected, but found '"toTag"'
UPDATE:
The solution is to use ident "to" & $(TT)
, but why it doesn't work with just string or newLit
?
Upvotes: 1
Views: 214
Reputation: 495
You're using a string literal as the procedure name instead of an identifer ident("to" & $(TT))
solves the issue, but you're also using a macro instead of a template. The reason it doesnt work with a lit is that a literal is "toTag"
whereas an identifer is toTag
. I suggest looking at the treeRepr
and repr
of the result to see what is happening. The following is the afformentioned template way.
import std/strutils
template autoConvert*(TT: type[enum]) {.dirty.} =
converter toTag*(s: string): TT = parse_enum[TT](s)
type Tag* = enum movies, books
autoconvert Tag
Upvotes: 3