An identifier is a symbol declared as a name for a variable, type, procedure, etc. The region of the program over which a declaration applies is called the scope of the declaration. Scopes can be nested. The meaning of an identifier is determined by the smallest enclosing scope in which the identifier is declared unless overloading resolution rules suggest otherwise. Symbols in Nim can be one of the following kind: • proc, func, iterator, converter, template, macro, method: These are called
routines. Routines can be called and perform computations.
• var: A variable that can be re-assigned. • let: A variable that cannot be re-assigned. • const: A symbol bound to a constant value. The value must be
computable at compile-time.
• type: A name for a type. • parameter: A name for a routine’s formal parameter. • result: A variable that represents a routine’s return value. • enum field: A value that belongs to an enum type. • object field: A field inside an object declaration. Symbols of kind “routine” or “enum field” can be overloaded. Multiple entries of an overloaded symbol can be accessible in a single scope. Overload resolution determines how these entries are resolved, ambiguous symbols produce a compile-time error. Non-overloaded symbols must be uniquely declared within a scope. Some examples:
67
block: # introduces a new scope
var x = 0 # valid
let x = "abc" # invalid as an 'x' was already declared
echo x # invalid: access of 'x' outside of its scope
proc p(x: int) = echo "int"
proc p(x: string) = echo "string" # valid, p is overloaded
p "abc" # valid invocation; overload resolution picks proc p(x: string)
Overloaded symbols can be accessed even though the symbols might be
shadowed by a non-overloadable symbol:
proc lenT: int = 1 #1
proc len(a: string): int = 2 #2
proc main =
let len = 3 # local variable 'len' shadows #1 and #2
echo len("xyz") # yet overload resolution selects #2 regardless
Only certain syntactic contexts such as routine calls trigger overload
resolution. In other contexts overload disambiguation is performed. The
corresponding sections Chapter 19, Overload resolution and Section 19.4,
“Overload disambiguation” contain the details.
68