syntax.txt 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. Syntax
  2. ======
  3. This section lists Nim's standard syntax. How the parser handles
  4. the indentation is already described in the `Lexical Analysis`_ section.
  5. Nim allows user-definable operators.
  6. Binary operators have 11 different levels of precedence.
  7. Associativity
  8. -------------
  9. Binary operators whose first character is ``^`` are right-associative, all
  10. other binary operators are left-associative.
  11. .. code-block:: nim
  12. proc `^/`(x, y: float): float =
  13. # a right-associative division operator
  14. result = x / y
  15. echo 12 ^/ 4 ^/ 8 # 24.0 (4 / 8 = 0.5, then 12 / 0.5 = 24.0)
  16. echo 12 / 4 / 8 # 0.375 (12 / 4 = 3.0, then 3 / 8 = 0.375)
  17. Precedence
  18. ----------
  19. Unary operators always bind stronger than any binary
  20. operator: ``$a + b`` is ``($a) + b`` and not ``$(a + b)``.
  21. If an unary operator's first character is ``@`` it is a `sigil-like`:idx:
  22. operator which binds stronger than a ``primarySuffix``: ``@x.abc`` is parsed
  23. as ``(@x).abc`` whereas ``$x.abc`` is parsed as ``$(x.abc)``.
  24. For binary operators that are not keywords the precedence is determined by the
  25. following rules:
  26. Operators ending in either ``->``, ``~>`` or ``=>`` are called
  27. `arrow like`:idx:, and have the lowest precedence of all operators.
  28. If the operator ends with ``=`` and its first character is none of
  29. ``<``, ``>``, ``!``, ``=``, ``~``, ``?``, it is an *assignment operator* which
  30. has the second lowest precedence.
  31. Otherwise precedence is determined by the first character.
  32. ================ =============================================== ================== ===============
  33. Precedence level Operators First character Terminal symbol
  34. ================ =============================================== ================== ===============
  35. 10 (highest) ``$ ^`` OP10
  36. 9 ``* / div mod shl shr %`` ``* % \ /`` OP9
  37. 8 ``+ -`` ``+ - ~ |`` OP8
  38. 7 ``&`` ``&`` OP7
  39. 6 ``..`` ``.`` OP6
  40. 5 ``== <= < >= > != in notin is isnot not of`` ``= < > !`` OP5
  41. 4 ``and`` OP4
  42. 3 ``or xor`` OP3
  43. 2 ``@ : ?`` OP2
  44. 1 *assignment operator* (like ``+=``, ``*=``) OP1
  45. 0 (lowest) *arrow like operator* (like ``->``, ``=>``) OP0
  46. ================ =============================================== ================== ===============
  47. Whether an operator is used a prefix operator is also affected by preceding
  48. whitespace (this parsing change was introduced with version 0.13.0):
  49. .. code-block:: nim
  50. echo $foo
  51. # is parsed as
  52. echo($foo)
  53. Grammar
  54. -------
  55. The grammar's start symbol is ``module``.
  56. .. include:: ../grammar.txt
  57. :literal: