This chapter describes in detail the second phase of the translation process
called parsing.
How the parser handles the indentation is described in Chapter 12, Lexical
analysis.
Nim allows user-definable operators. Binary operators have 11 different
levels of precedence.
13.1. Associativity
Binary operators whose first character is ^ are right-associative, all other
binary operators are left-associative.
proc ^/(x, y: float): float =
# a right-associative division operator
result = x / y
echo 12 ^/ 4 ^/ 8 # 24.0 (4 / 8 = 0.5, then 12 / 0.5 = 24.0) echo 12 / 4 / 8 # 0.375 (12 / 4 = 3.0, then 3 / 8 = 0.375) 13.1.1. Precedence Unary operators always bind stronger than any binary operator: $a + b is ($a) + b and not $(a + b). If a unary operator’s first character is @, it is a sigil-like operator which binds stronger than a primarySuffix: @x.abc is parsed as (@x).abc whereas $x.abc is parsed as $(x.abc). For binary operators that are not keywords, the precedence is determined by
63
the following rules: Operators ending in either →, ~> or => are called arrow-like, and have the lowest precedence of all operators. If the operator ends with = and its first character is none of <, >, !, =, ~, ?, it is an assignment operator which has the second-lowest precedence. Otherwise, precedence is determined by the first character. Table 4. Precedence levels Precedence Operators First Terminal level character symbol 10 (highest) $ ^ OP10 9 * / div mod shl shr % * % \ / OP9 8 + - + - ~ | OP8 7 & & OP7 6 .. . OP6 5 == <= < >= > != in notin is = < > ! OP5
isnot not of as from
4 and OP4 3 or xor OP3 2 @ : ? OP2 1 assignment operator (like +=, OP1
*=)
0 (lowest) arrow-like operator (like ->, OP0
=>)
Whether an operator is used as a prefix operator is also affected by preceding whitespace: echo $foo # is parsed as echo($foo) 64
Spacing also determines whether (a, b) is parsed as an
argument list of a call or whether it is parsed as a tuple
constructor:
echo(1, 2) # pass 1 and 2 to echo
echo (1, 2) # pass the tuple (1, 2) to echo
13.2. Dot-like operators Terminal symbol in the grammar: DOTLIKEOP. Dot-like operators are operators starting with ., but not with .., for example .?. Dot-like operators have the same precedence as ., so that a.?b.c is parsed as (a.?b).c instead of a.?(b.c).
The rules of operator precedence were designed to be as
“intuitive” as possible and so that you can avoid many
parenthesis in practice. However, you are not supposed to
learn the rules by heart, if in doubt use parenthesis explicitly:
(a and b) or c # is more readable than
a and b or c
Other syntax rules are described in the following sections along the semantics of described construct like an if statement. The complete and formal grammar can found in Appendix A, Grammar.