I apologize for bugging folks if this is already answered in the docs somewhere.
Is there there a way to enforce that the parameter to a procedure is resolvable at compile time?
Or, if not that, that the passed in parameter is a string literal?
Something like:
proc fooBar(a: const string): string =
# stuff about `a` goes here blah blah
result = "[" & a & "]"
const hello = "hello"
var maybeHello = "hello"
var x = fooBar("hello") # good
var y = fooBar(hello) # also good
var z = fooBar(maybeHello) # generates a compile-time error
I know I can do this via a macro, but am curious if there is some way to do this with a proc.
Yep, there's AST-based overloading in Nim :)
proc fooBar(a: string{lit|`const`}): string =
# stuff about `a` goes here blah blah
result = "[" & a & "]"
const hello = "hello"
var maybeHello = "hello"
var x = fooBar("hello") # good
var y = fooBar(hello) # also good
var z = fooBar(maybeHello) # generates a compile-time error
See https://nim-lang.org/docs/manual_experimental.html#ast-based-overloading
for another non experimental option using static may also achieve the same result you are looking for
proc fooBar(a: static string): string =
# stuff about `a` goes here blah blah
result = "[" & a & "]"
const hello = "hello"
var maybeHello = "hello"
var x = fooBar("hello") # good
var y = fooBar(hello) # also good
var z = fooBar(maybeHello) # generates a compile-time error
Now you've done it @Araq, @zahary, static is considered stable! Time sure flies.