stmts.txt 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. Statements and expressions
  2. ==========================
  3. Nim uses the common statement/expression paradigm: Statements do not
  4. produce a value in contrast to expressions. However, some expressions are
  5. statements.
  6. Statements are separated into `simple statements`:idx: and
  7. `complex statements`:idx:.
  8. Simple statements are statements that cannot contain other statements like
  9. assignments, calls or the ``return`` statement; complex statements can
  10. contain other statements. To avoid the `dangling else problem`:idx:, complex
  11. statements always have to be indented. The details can be found in the grammar.
  12. Statement list expression
  13. -------------------------
  14. Statements can also occur in an expression context that looks
  15. like ``(stmt1; stmt2; ...; ex)``. This is called
  16. an statement list expression or ``(;)``. The type
  17. of ``(stmt1; stmt2; ...; ex)`` is the type of ``ex``. All the other statements
  18. must be of type ``void``. (One can use ``discard`` to produce a ``void`` type.)
  19. ``(;)`` does not introduce a new scope.
  20. Discard statement
  21. -----------------
  22. Example:
  23. .. code-block:: nim
  24. proc p(x, y: int): int =
  25. result = x + y
  26. discard p(3, 4) # discard the return value of `p`
  27. The ``discard`` statement evaluates its expression for side-effects and
  28. throws the expression's resulting value away.
  29. Ignoring the return value of a procedure without using a discard statement is
  30. a static error.
  31. The return value can be ignored implicitly if the called proc/iterator has
  32. been declared with the `discardable`:idx: pragma:
  33. .. code-block:: nim
  34. proc p(x, y: int): int {.discardable.} =
  35. result = x + y
  36. p(3, 4) # now valid
  37. An empty ``discard`` statement is often used as a null statement:
  38. .. code-block:: nim
  39. proc classify(s: string) =
  40. case s[0]
  41. of SymChars, '_': echo "an identifier"
  42. of '0'..'9': echo "a number"
  43. else: discard
  44. Void context
  45. ------------
  46. In a list of statements every expression except the last one needs to have the
  47. type ``void``. In addition to this rule an assignment to the builtin ``result``
  48. symbol also triggers a mandatory ``void`` context for the subsequent expressions:
  49. .. code-block:: nim
  50. proc invalid*(): string =
  51. result = "foo"
  52. "invalid" # Error: value of type 'string' has to be discarded
  53. .. code-block:: nim
  54. proc valid*(): string =
  55. let x = 317
  56. "valid"
  57. Var statement
  58. -------------
  59. Var statements declare new local and global variables and
  60. initialize them. A comma separated list of variables can be used to specify
  61. variables of the same type:
  62. .. code-block:: nim
  63. var
  64. a: int = 0
  65. x, y, z: int
  66. If an initializer is given the type can be omitted: the variable is then of the
  67. same type as the initializing expression. Variables are always initialized
  68. with a default value if there is no initializing expression. The default
  69. value depends on the type and is always a zero in binary.
  70. ============================ ==============================================
  71. Type default value
  72. ============================ ==============================================
  73. any integer type 0
  74. any float 0.0
  75. char '\\0'
  76. bool false
  77. ref or pointer type nil
  78. procedural type nil
  79. sequence nil (*not* ``@[]``)
  80. string nil (*not* "")
  81. tuple[x: A, y: B, ...] (default(A), default(B), ...)
  82. (analogous for objects)
  83. array[0..., T] [default(T), ...]
  84. range[T] default(T); this may be out of the valid range
  85. T = enum cast[T](0); this may be an invalid value
  86. ============================ ==============================================
  87. The implicit initialization can be avoided for optimization reasons with the
  88. `noinit`:idx: pragma:
  89. .. code-block:: nim
  90. var
  91. a {.noInit.}: array [0..1023, char]
  92. If a proc is annotated with the ``noinit`` pragma this refers to its implicit
  93. ``result`` variable:
  94. .. code-block:: nim
  95. proc returnUndefinedValue: int {.noinit.} = discard
  96. The implicit initialization can be also prevented by the `requiresInit`:idx:
  97. type pragma. The compiler requires an explicit initialization for the object
  98. and all of its fields. However it does a `control flow analysis`:idx: to prove
  99. the variable has been initialized and does not rely on syntactic properties:
  100. .. code-block:: nim
  101. type
  102. MyObject = object {.requiresInit.}
  103. proc p() =
  104. # the following is valid:
  105. var x: MyObject
  106. if someCondition():
  107. x = a()
  108. else:
  109. x = a()
  110. use x
  111. let statement
  112. -------------
  113. A ``let`` statement declares new local and global `single assignment`:idx:
  114. variables and binds a value to them. The syntax is the same as that of the ``var``
  115. statement, except that the keyword ``var`` is replaced by the keyword ``let``.
  116. Let variables are not l-values and can thus not be passed to ``var`` parameters
  117. nor can their address be taken. They cannot be assigned new values.
  118. For let variables the same pragmas are available as for ordinary variables.
  119. Tuple unpacking
  120. ---------------
  121. In a ``var`` or ``let`` statement tuple unpacking can be performed. The special
  122. identifier ``_`` can be used to ignore some parts of the tuple:
  123. .. code-block:: nim
  124. proc returnsTuple(): (int, int, int) = (4, 2, 3)
  125. let (x, _, z) = returnsTuple()
  126. Const section
  127. -------------
  128. `Constants`:idx: are symbols which are bound to a value. The constant's value
  129. cannot change. The compiler must be able to evaluate the expression in a
  130. constant declaration at compile time.
  131. Nim contains a sophisticated compile-time evaluator, so procedures which
  132. have no side-effect can be used in constant expressions too:
  133. .. code-block:: nim
  134. import strutils
  135. const
  136. constEval = contains("abc", 'b') # computed at compile time!
  137. The rules for compile-time computability are:
  138. 1. Literals are compile-time computable.
  139. 2. Type conversions are compile-time computable.
  140. 3. Procedure calls of the form ``p(X)`` are compile-time computable if
  141. ``p`` is a proc without side-effects (see the `noSideEffect pragma
  142. <#pragmas-nosideeffect-pragma>`_ for details) and if ``X`` is a
  143. (possibly empty) list of compile-time computable arguments.
  144. Constants cannot be of type ``ptr``, ``ref`` or ``var``, nor can
  145. they contain such a type.
  146. Static statement/expression
  147. ---------------------------
  148. A static statement/expression can be used to enforce compile
  149. time evaluation explicitly. Enforced compile time evaluation can even evaluate
  150. code that has side effects:
  151. .. code-block::
  152. static:
  153. echo "echo at compile time"
  154. It's a static error if the compiler cannot perform the evaluation at compile
  155. time.
  156. The current implementation poses some restrictions for compile time
  157. evaluation: Code which contains ``cast`` or makes use of the foreign function
  158. interface cannot be evaluated at compile time. Later versions of Nim will
  159. support the FFI at compile time.
  160. If statement
  161. ------------
  162. Example:
  163. .. code-block:: nim
  164. var name = readLine(stdin)
  165. if name == "Andreas":
  166. echo "What a nice name!"
  167. elif name == "":
  168. echo "Don't you have a name?"
  169. else:
  170. echo "Boring name..."
  171. The ``if`` statement is a simple way to make a branch in the control flow:
  172. The expression after the keyword ``if`` is evaluated, if it is true
  173. the corresponding statements after the ``:`` are executed. Otherwise
  174. the expression after the ``elif`` is evaluated (if there is an
  175. ``elif`` branch), if it is true the corresponding statements after
  176. the ``:`` are executed. This goes on until the last ``elif``. If all
  177. conditions fail, the ``else`` part is executed. If there is no ``else``
  178. part, execution continues with the next statement.
  179. In ``if`` statements new scopes begin immediately after the ``if``/``elif``/``else`` keywords and ends after the corresponding *then* block.
  180. For visualization purposes the scopes have been enclosed in ``{| |}`` in the following example:
  181. .. code-block:: nim
  182. if {| (let m = input =~ re"(\w+)=\w+"; m.isMatch):
  183. echo "key ", m[0], " value ", m[1] |}
  184. elif {| (let m = input =~ re""; m.isMatch):
  185. echo "new m in this scope" |}
  186. else: {|
  187. echo "m not declared here" |}
  188. Case statement
  189. --------------
  190. Example:
  191. .. code-block:: nim
  192. case readline(stdin)
  193. of "delete-everything", "restart-computer":
  194. echo "permission denied"
  195. of "go-for-a-walk": echo "please yourself"
  196. else: echo "unknown command"
  197. # indentation of the branches is also allowed; and so is an optional colon
  198. # after the selecting expression:
  199. case readline(stdin):
  200. of "delete-everything", "restart-computer":
  201. echo "permission denied"
  202. of "go-for-a-walk": echo "please yourself"
  203. else: echo "unknown command"
  204. The ``case`` statement is similar to the if statement, but it represents
  205. a multi-branch selection. The expression after the keyword ``case`` is
  206. evaluated and if its value is in a *slicelist* the corresponding statements
  207. (after the ``of`` keyword) are executed. If the value is not in any
  208. given *slicelist* the ``else`` part is executed. If there is no ``else``
  209. part and not all possible values that ``expr`` can hold occur in a
  210. ``slicelist``, a static error occurs. This holds only for expressions of
  211. ordinal types. "All possible values" of ``expr`` are determined by ``expr``'s
  212. type. To suppress the static error an ``else`` part with an
  213. empty ``discard`` statement should be used.
  214. For non ordinal types it is not possible to list every possible value and so
  215. these always require an ``else`` part.
  216. As a special semantic extension, an expression in an ``of`` branch of a case
  217. statement may evaluate to a set or array constructor; the set or array is then
  218. expanded into a list of its elements:
  219. .. code-block:: nim
  220. const
  221. SymChars: set[char] = {'a'..'z', 'A'..'Z', '\x80'..'\xFF'}
  222. proc classify(s: string) =
  223. case s[0]
  224. of SymChars, '_': echo "an identifier"
  225. of '0'..'9': echo "a number"
  226. else: echo "other"
  227. # is equivalent to:
  228. proc classify(s: string) =
  229. case s[0]
  230. of 'a'..'z', 'A'..'Z', '\x80'..'\xFF', '_': echo "an identifier"
  231. of '0'..'9': echo "a number"
  232. else: echo "other"
  233. When statement
  234. --------------
  235. Example:
  236. .. code-block:: nim
  237. when sizeof(int) == 2:
  238. echo "running on a 16 bit system!"
  239. elif sizeof(int) == 4:
  240. echo "running on a 32 bit system!"
  241. elif sizeof(int) == 8:
  242. echo "running on a 64 bit system!"
  243. else:
  244. echo "cannot happen!"
  245. The ``when`` statement is almost identical to the ``if`` statement with some
  246. exceptions:
  247. * Each condition (``expr``) has to be a constant expression (of type ``bool``).
  248. * The statements do not open a new scope.
  249. * The statements that belong to the expression that evaluated to true are
  250. translated by the compiler, the other statements are not checked for
  251. semantics! However, each condition is checked for semantics.
  252. The ``when`` statement enables conditional compilation techniques. As
  253. a special syntactic extension, the ``when`` construct is also available
  254. within ``object`` definitions.
  255. When nimvm statement
  256. --------------------
  257. ``nimvm`` is a special symbol, that may be used as expression of ``when nimvm``
  258. statement to differentiate execution path between runtime and compile time.
  259. Example:
  260. .. code-block:: nim
  261. proc someProcThatMayRunInCompileTime(): bool =
  262. when nimvm:
  263. # This code runs in compile time
  264. result = true
  265. else:
  266. # This code runs in runtime
  267. result = false
  268. const ctValue = someProcThatMayRunInCompileTime()
  269. let rtValue = someProcThatMayRunInCompileTime()
  270. assert(ctValue == true)
  271. assert(rtValue == false)
  272. ``when nimvm`` statement must meet the following requirements:
  273. * Its expression must always be ``nimvm``. More complex expressions are not
  274. allowed.
  275. * It must not contain ``elif`` branches.
  276. * It must contain ``else`` branch.
  277. * Code in branches must not affect semantics of the code that follows the
  278. ``when nimvm`` statement. E.g. it must not define symbols that are used in
  279. the following code.
  280. Return statement
  281. ----------------
  282. Example:
  283. .. code-block:: nim
  284. return 40+2
  285. The ``return`` statement ends the execution of the current procedure.
  286. It is only allowed in procedures. If there is an ``expr``, this is syntactic
  287. sugar for:
  288. .. code-block:: nim
  289. result = expr
  290. return result
  291. ``return`` without an expression is a short notation for ``return result`` if
  292. the proc has a return type. The `result`:idx: variable is always the return
  293. value of the procedure. It is automatically declared by the compiler. As all
  294. variables, ``result`` is initialized to (binary) zero:
  295. .. code-block:: nim
  296. proc returnZero(): int =
  297. # implicitly returns 0
  298. Yield statement
  299. ---------------
  300. Example:
  301. .. code-block:: nim
  302. yield (1, 2, 3)
  303. The ``yield`` statement is used instead of the ``return`` statement in
  304. iterators. It is only valid in iterators. Execution is returned to the body
  305. of the for loop that called the iterator. Yield does not end the iteration
  306. process, but execution is passed back to the iterator if the next iteration
  307. starts. See the section about iterators (`Iterators and the for statement`_)
  308. for further information.
  309. Block statement
  310. ---------------
  311. Example:
  312. .. code-block:: nim
  313. var found = false
  314. block myblock:
  315. for i in 0..3:
  316. for j in 0..3:
  317. if a[j][i] == 7:
  318. found = true
  319. break myblock # leave the block, in this case both for-loops
  320. echo found
  321. The block statement is a means to group statements to a (named) ``block``.
  322. Inside the block, the ``break`` statement is allowed to leave the block
  323. immediately. A ``break`` statement can contain a name of a surrounding
  324. block to specify which block is to leave.
  325. Break statement
  326. ---------------
  327. Example:
  328. .. code-block:: nim
  329. break
  330. The ``break`` statement is used to leave a block immediately. If ``symbol``
  331. is given, it is the name of the enclosing block that is to leave. If it is
  332. absent, the innermost block is left.
  333. While statement
  334. ---------------
  335. Example:
  336. .. code-block:: nim
  337. echo "Please tell me your password:"
  338. var pw = readLine(stdin)
  339. while pw != "12345":
  340. echo "Wrong password! Next try:"
  341. pw = readLine(stdin)
  342. The ``while`` statement is executed until the ``expr`` evaluates to false.
  343. Endless loops are no error. ``while`` statements open an `implicit block`,
  344. so that they can be left with a ``break`` statement.
  345. Continue statement
  346. ------------------
  347. A ``continue`` statement leads to the immediate next iteration of the
  348. surrounding loop construct. It is only allowed within a loop. A continue
  349. statement is syntactic sugar for a nested block:
  350. .. code-block:: nim
  351. while expr1:
  352. stmt1
  353. continue
  354. stmt2
  355. Is equivalent to:
  356. .. code-block:: nim
  357. while expr1:
  358. block myBlockName:
  359. stmt1
  360. break myBlockName
  361. stmt2
  362. Assembler statement
  363. -------------------
  364. The direct embedding of assembler code into Nim code is supported
  365. by the unsafe ``asm`` statement. Identifiers in the assembler code that refer to
  366. Nim identifiers shall be enclosed in a special character which can be
  367. specified in the statement's pragmas. The default special character is ``'`'``:
  368. .. code-block:: nim
  369. {.push stackTrace:off.}
  370. proc addInt(a, b: int): int =
  371. # a in eax, and b in edx
  372. asm """
  373. mov eax, `a`
  374. add eax, `b`
  375. jno theEnd
  376. call `raiseOverflow`
  377. theEnd:
  378. """
  379. {.pop.}
  380. If the GNU assembler is used, quotes and newlines are inserted automatically:
  381. .. code-block:: nim
  382. proc addInt(a, b: int): int =
  383. asm """
  384. addl %%ecx, %%eax
  385. jno 1
  386. call `raiseOverflow`
  387. 1:
  388. :"=a"(`result`)
  389. :"a"(`a`), "c"(`b`)
  390. """
  391. Instead of:
  392. .. code-block:: nim
  393. proc addInt(a, b: int): int =
  394. asm """
  395. "addl %%ecx, %%eax\n"
  396. "jno 1\n"
  397. "call `raiseOverflow`\n"
  398. "1: \n"
  399. :"=a"(`result`)
  400. :"a"(`a`), "c"(`b`)
  401. """
  402. Using statement
  403. ---------------
  404. The using statement provides syntactic convenience in modules where
  405. the same parameter names and types are used over and over. Instead of:
  406. .. code-block:: nim
  407. proc foo(c: Context; n: Node) = ...
  408. proc bar(c: Context; n: Node, counter: int) = ...
  409. proc baz(c: Context; n: Node) = ...
  410. One can tell the compiler about the convention that a parameter of
  411. name ``c`` should default to type ``Context``, ``n`` should default to
  412. ``Node`` etc.:
  413. .. code-block:: nim
  414. using
  415. c: Context
  416. n: Node
  417. counter: int
  418. proc foo(c, n) = ...
  419. proc bar(c, n, counter) = ...
  420. proc baz(c, n) = ...
  421. The ``using`` section uses the same indentation based grouping syntax as
  422. a ``var`` or ``let`` section.
  423. Note that ``using`` is not applied for ``template`` since untyped template
  424. parameters default to the type ``system.untyped``.
  425. If expression
  426. -------------
  427. An `if expression` is almost like an if statement, but it is an expression.
  428. Example:
  429. .. code-block:: nim
  430. var y = if x > 8: 9 else: 10
  431. An if expression always results in a value, so the ``else`` part is
  432. required. ``Elif`` parts are also allowed.
  433. When expression
  434. ---------------
  435. Just like an `if expression`, but corresponding to the when statement.
  436. Case expression
  437. ---------------
  438. The `case expression` is again very similar to the case statement:
  439. .. code-block:: nim
  440. var favoriteFood = case animal
  441. of "dog": "bones"
  442. of "cat": "mice"
  443. elif animal.endsWith"whale": "plankton"
  444. else:
  445. echo "I'm not sure what to serve, but everybody loves ice cream"
  446. "ice cream"
  447. As seen in the above example, the case expression can also introduce side
  448. effects. When multiple statements are given for a branch, Nim will use
  449. the last expression as the result value, much like in an `expr` template.
  450. Table constructor
  451. -----------------
  452. A table constructor is syntactic sugar for an array constructor:
  453. .. code-block:: nim
  454. {"key1": "value1", "key2", "key3": "value2"}
  455. # is the same as:
  456. [("key1", "value1"), ("key2", "value2"), ("key3", "value2")]
  457. The empty table can be written ``{:}`` (in contrast to the empty set
  458. which is ``{}``) which is thus another way to write as the empty array
  459. constructor ``[]``. This slightly unusual way of supporting tables
  460. has lots of advantages:
  461. * The order of the (key,value)-pairs is preserved, thus it is easy to
  462. support ordered dicts with for example ``{key: val}.newOrderedTable``.
  463. * A table literal can be put into a ``const`` section and the compiler
  464. can easily put it into the executable's data section just like it can
  465. for arrays and the generated data section requires a minimal amount
  466. of memory.
  467. * Every table implementation is treated equal syntactically.
  468. * Apart from the minimal syntactic sugar the language core does not need to
  469. know about tables.
  470. Type conversions
  471. ----------------
  472. Syntactically a `type conversion` is like a procedure call, but a
  473. type name replaces the procedure name. A type conversion is always
  474. safe in the sense that a failure to convert a type to another
  475. results in an exception (if it cannot be determined statically).
  476. Ordinary procs are often preferred over type conversions in Nim: For instance,
  477. ``$`` is the ``toString`` operator by convention and ``toFloat`` and ``toInt``
  478. can be used to convert from floating point to integer or vice versa.
  479. Type casts
  480. ----------
  481. Example:
  482. .. code-block:: nim
  483. cast[int](x)
  484. Type casts are a crude mechanism to interpret the bit pattern of
  485. an expression as if it would be of another type. Type casts are
  486. only needed for low-level programming and are inherently unsafe.
  487. The addr operator
  488. -----------------
  489. The ``addr`` operator returns the address of an l-value. If the type of the
  490. location is ``T``, the `addr` operator result is of the type ``ptr T``. An
  491. address is always an untraced reference. Taking the address of an object that
  492. resides on the stack is **unsafe**, as the pointer may live longer than the
  493. object on the stack and can thus reference a non-existing object. One can get
  494. the address of variables, but one can't use it on variables declared through
  495. ``let`` statements:
  496. .. code-block:: nim
  497. let t1 = "Hello"
  498. var
  499. t2 = t1
  500. t3 : pointer = addr(t2)
  501. echo repr(addr(t2))
  502. # --> ref 0x7fff6b71b670 --> 0x10bb81050"Hello"
  503. echo cast[ptr string](t3)[]
  504. # --> Hello
  505. # The following line doesn't compile:
  506. echo repr(addr(t1))
  507. # Error: expression has no address