manual_experimental.rst 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077
  1. .. default-role:: code
  2. =========================
  3. Nim Experimental Features
  4. =========================
  5. :Authors: Andreas Rumpf
  6. :Version: |nimversion|
  7. .. contents::
  8. About this document
  9. ===================
  10. This document describes features of Nim that are to be considered experimental.
  11. Some of these are not covered by the `.experimental` pragma or
  12. `--experimental` switch because they are already behind a special syntax and
  13. one may want to use Nim libraries using these features without using them
  14. oneself.
  15. **Note**: Unless otherwise indicated, these features are not to be removed,
  16. but refined and overhauled.
  17. Package level objects
  18. =====================
  19. Every Nim module resides in a (nimble) package. An object type can be attached
  20. to the package it resides in. If that is done, the type can be referenced from
  21. other modules as an `incomplete`:idx: object type. This feature allows to
  22. break up recursive type dependencies across module boundaries. Incomplete
  23. object types are always passed `byref` and can only be used in pointer like
  24. contexts (`var/ref/ptr IncompleteObject`) in general since the compiler does
  25. not yet know the size of the object. To complete an incomplete object
  26. the `package` pragma has to be used. `package` implies `byref`.
  27. As long as a type `T` is incomplete, neither `sizeof(T)` nor runtime
  28. type information for `T` is available.
  29. Example:
  30. .. code-block:: nim
  31. # module A (in an arbitrary package)
  32. type
  33. Pack.SomeObject = object ## declare as incomplete object of package 'Pack'
  34. Triple = object
  35. a, b, c: ref SomeObject ## pointers to incomplete objects are allowed
  36. ## Incomplete objects can be used as parameters:
  37. proc myproc(x: SomeObject) = discard
  38. .. code-block:: nim
  39. # module B (in package "Pack")
  40. type
  41. SomeObject* {.package.} = object ## Use 'package' to complete the object
  42. s, t: string
  43. x, y: int
  44. Void type
  45. =========
  46. The `void` type denotes the absence of any type. Parameters of
  47. type `void` are treated as non-existent, `void` as a return type means that
  48. the procedure does not return a value:
  49. .. code-block:: nim
  50. proc nothing(x, y: void): void =
  51. echo "ha"
  52. nothing() # writes "ha" to stdout
  53. The `void` type is particularly useful for generic code:
  54. .. code-block:: nim
  55. proc callProc[T](p: proc (x: T), x: T) =
  56. when T is void:
  57. p()
  58. else:
  59. p(x)
  60. proc intProc(x: int) = discard
  61. proc emptyProc() = discard
  62. callProc[int](intProc, 12)
  63. callProc[void](emptyProc)
  64. However, a `void` type cannot be inferred in generic code:
  65. .. code-block:: nim
  66. callProc(emptyProc)
  67. # Error: type mismatch: got (proc ())
  68. # but expected one of:
  69. # callProc(p: proc (T), x: T)
  70. The `void` type is only valid for parameters and return types; other symbols
  71. cannot have the type `void`.
  72. Covariance
  73. ==========
  74. Covariance in Nim can be introduced only through pointer-like types such
  75. as `ptr` and `ref`. Sequence, Array and OpenArray types, instantiated
  76. with pointer-like types will be considered covariant if and only if they
  77. are also immutable. The introduction of a `var` modifier or additional
  78. `ptr` or `ref` indirections would result in invariant treatment of
  79. these types.
  80. `proc` types are currently always invariant, but future versions of Nim
  81. may relax this rule.
  82. User-defined generic types may also be covariant with respect to some of
  83. their parameters. By default, all generic params are considered invariant,
  84. but you may choose the apply the prefix modifier `in` to a parameter to
  85. make it contravariant or `out` to make it covariant:
  86. .. code-block:: nim
  87. type
  88. AnnotatedPtr[out T] =
  89. metadata: MyTypeInfo
  90. p: ref T
  91. RingBuffer[out T] =
  92. startPos: int
  93. data: seq[T]
  94. Action {.importcpp: "std::function<void ('0)>".} [in T] = object
  95. When the designated generic parameter is used to instantiate a pointer-like
  96. type as in the case of `AnnotatedPtr` above, the resulting generic type will
  97. also have pointer-like covariance:
  98. .. code-block:: nim
  99. type
  100. GuiWidget = object of RootObj
  101. Button = object of GuiWidget
  102. ComboBox = object of GuiWidget
  103. var
  104. widgetPtr: AnnotatedPtr[GuiWidget]
  105. buttonPtr: AnnotatedPtr[Button]
  106. ...
  107. proc drawWidget[T](x: AnnotatedPtr[GuiWidget]) = ...
  108. # you can call procs expecting base types by supplying a derived type
  109. drawWidget(buttonPtr)
  110. # and you can convert more-specific pointer types to more general ones
  111. widgetPtr = buttonPtr
  112. Just like with regular pointers, covariance will be enabled only for immutable
  113. values:
  114. .. code-block:: nim
  115. proc makeComboBox[T](x: var AnnotatedPtr[GuiWidget]) =
  116. x.p = new(ComboBox)
  117. makeComboBox(buttonPtr) # Error, AnnotatedPtr[Button] cannot be modified
  118. # to point to a ComboBox
  119. On the other hand, in the `RingBuffer` example above, the designated generic
  120. param is used to instantiate the non-pointer `seq` type, which means that
  121. the resulting generic type will have covariance that mimics an array or
  122. sequence (i.e. it will be covariant only when instantiated with `ptr` and
  123. `ref` types):
  124. .. code-block:: nim
  125. type
  126. Base = object of RootObj
  127. Derived = object of Base
  128. proc consumeBaseValues(b: RingBuffer[Base]) = ...
  129. var derivedValues: RingBuffer[Derived]
  130. consumeBaseValues(derivedValues) # Error, Base and Derived values may differ
  131. # in size
  132. proc consumeBasePointers(b: RingBuffer[ptr Base]) = ...
  133. var derivedPointers: RingBuffer[ptr Derived]
  134. consumeBaseValues(derivedPointers) # This is legal
  135. Please note that Nim will treat the user-defined pointer-like types as
  136. proper alternatives to the built-in pointer types. That is, types such
  137. as `seq[AnnotatedPtr[T]]` or `RingBuffer[AnnotatedPtr[T]]` will also be
  138. considered covariant and you can create new pointer-like types by instantiating
  139. other user-defined pointer-like types.
  140. The contravariant parameters introduced with the `in` modifier are currently
  141. useful only when interfacing with imported types having such semantics.
  142. Automatic dereferencing
  143. =======================
  144. Automatic dereferencing is performed for the first argument of a routine call.
  145. This feature has to be enabled via `{.experimental: "implicitDeref".}`:
  146. .. code-block:: nim
  147. {.experimental: "implicitDeref".}
  148. proc depth(x: NodeObj): int = ...
  149. var
  150. n: Node
  151. new(n)
  152. echo n.depth
  153. # no need to write n[].depth either
  154. Code reordering
  155. ===============
  156. The code reordering feature can implicitly rearrange procedure, template, and
  157. macro definitions along with variable declarations and initializations at the top
  158. level scope so that, to a large extent, a programmer should not have to worry
  159. about ordering definitions correctly or be forced to use forward declarations to
  160. preface definitions inside a module.
  161. ..
  162. NOTE: The following was documentation for the code reordering precursor,
  163. which was {.noForward.}.
  164. In this mode, procedure definitions may appear out of order and the compiler
  165. will postpone their semantic analysis and compilation until it actually needs
  166. to generate code using the definitions. In this regard, this mode is similar
  167. to the modus operandi of dynamic scripting languages, where the function
  168. calls are not resolved until the code is executed. Here is the detailed
  169. algorithm taken by the compiler:
  170. 1. When a callable symbol is first encountered, the compiler will only note
  171. the symbol callable name and it will add it to the appropriate overload set
  172. in the current scope. At this step, it won't try to resolve any of the type
  173. expressions used in the signature of the symbol (so they can refer to other
  174. not yet defined symbols).
  175. 2. When a top level call is encountered (usually at the very end of the
  176. module), the compiler will try to determine the actual types of all of the
  177. symbols in the matching overload set. This is a potentially recursive process
  178. as the signatures of the symbols may include other call expressions, whose
  179. types will be resolved at this point too.
  180. 3. Finally, after the best overload is picked, the compiler will start
  181. compiling the body of the respective symbol. This in turn will lead the
  182. compiler to discover more call expressions that need to be resolved and steps
  183. 2 and 3 will be repeated as necessary.
  184. Please note that if a callable symbol is never used in this scenario, its
  185. body will never be compiled. This is the default behavior leading to best
  186. compilation times, but if exhaustive compilation of all definitions is
  187. required, using `nim check` provides this option as well.
  188. Example:
  189. .. code-block:: nim
  190. {.experimental: "codeReordering".}
  191. proc foo(x: int) =
  192. bar(x)
  193. proc bar(x: int) =
  194. echo(x)
  195. foo(10)
  196. Variables can also be reordered as well. Variables that are *initialized* (i.e.
  197. variables that have their declaration and assignment combined in a single
  198. statement) can have their entire initialization statement reordered. Be wary of
  199. what code is executed at the top level:
  200. .. code-block:: nim
  201. {.experimental: "codeReordering".}
  202. proc a() =
  203. echo(foo)
  204. var foo = 5
  205. a() # outputs: "5"
  206. ..
  207. TODO: Let's table this for now. This is an *experimental feature* and so the
  208. specific manner in which `declared` operates with it can be decided in
  209. eventuality, because right now it works a bit weirdly.
  210. The values of expressions involving `declared` are decided *before* the
  211. code reordering process, and not after. As an example, the output of this
  212. code is the same as it would be with code reordering disabled.
  213. .. code-block:: nim
  214. {.experimental: "codeReordering".}
  215. proc x() =
  216. echo(declared(foo))
  217. var foo = 4
  218. x() # "false"
  219. It is important to note that reordering *only* works for symbols at top level
  220. scope. Therefore, the following will *fail to compile:*
  221. .. code-block:: nim
  222. {.experimental: "codeReordering".}
  223. proc a() =
  224. b()
  225. proc b() =
  226. echo("Hello!")
  227. a()
  228. Named argument overloading
  229. ==========================
  230. Routines with the same type signature can be called differently if a parameter
  231. has different names. This does not need an `experimental` switch, but is an
  232. unstable feature.
  233. .. code-block:: Nim
  234. proc foo(x: int) =
  235. echo "Using x: ", x
  236. proc foo(y: int) =
  237. echo "Using y: ", y
  238. foo(x = 2)
  239. # Using x: 2
  240. foo(y = 2)
  241. # Using y: 2
  242. Do notation
  243. ===========
  244. As a special more convenient notation, proc expressions involved in procedure
  245. calls can use the `do` keyword:
  246. .. code-block:: nim
  247. sort(cities) do (x,y: string) -> int:
  248. cmp(x.len, y.len)
  249. # Less parenthesis using the method plus command syntax:
  250. cities = cities.map do (x:string) -> string:
  251. "City of " & x
  252. # In macros, the do notation is often used for quasi-quoting
  253. macroResults.add quote do:
  254. if not `ex`:
  255. echo `info`, ": Check failed: ", `expString`
  256. `do` is written after the parentheses enclosing the regular proc params.
  257. The proc expression represented by the do block is appended to them.
  258. In calls using the command syntax, the do block will bind to the immediately
  259. preceding expression, transforming it in a call.
  260. `do` with parentheses is an anonymous `proc`; however a `do` without
  261. parentheses is just a block of code. The `do` notation can be used to
  262. pass multiple blocks to a macro:
  263. .. code-block:: nim
  264. macro performWithUndo(task, undo: untyped) = ...
  265. performWithUndo do:
  266. # multiple-line block of code
  267. # to perform the task
  268. do:
  269. # code to undo it
  270. Special Operators
  271. =================
  272. dot operators
  273. -------------
  274. **Note**: Dot operators are still experimental and so need to be enabled
  275. via `{.experimental: "dotOperators".}`.
  276. Nim offers a special family of dot operators that can be used to
  277. intercept and rewrite proc call and field access attempts, referring
  278. to previously undeclared symbol names. They can be used to provide a
  279. fluent interface to objects lying outside the static confines of the
  280. type system such as values from dynamic scripting languages
  281. or dynamic file formats such as JSON or XML.
  282. When Nim encounters an expression that cannot be resolved by the
  283. standard overload resolution rules, the current scope will be searched
  284. for a dot operator that can be matched against a re-written form of
  285. the expression, where the unknown field or proc name is passed to
  286. an `untyped` parameter:
  287. .. code-block:: nim
  288. a.b # becomes `.`(a, b)
  289. a.b(c, d) # becomes `.`(a, b, c, d)
  290. The matched dot operators can be symbols of any callable kind (procs,
  291. templates and macros), depending on the desired effect:
  292. .. code-block:: nim
  293. template `.`(js: PJsonNode, field: untyped): JSON = js[astToStr(field)]
  294. var js = parseJson("{ x: 1, y: 2}")
  295. echo js.x # outputs 1
  296. echo js.y # outputs 2
  297. The following dot operators are available:
  298. operator `.`
  299. ------------
  300. This operator will be matched against both field accesses and method calls.
  301. operator `.()`
  302. ---------------
  303. This operator will be matched exclusively against method calls. It has higher
  304. precedence than the `.` operator and this allows one to handle expressions like
  305. `x.y` and `x.y()` differently if one is interfacing with a scripting language
  306. for example.
  307. operator `.=`
  308. -------------
  309. This operator will be matched against assignments to missing fields.
  310. .. code-block:: nim
  311. a.b = c # becomes `.=`(a, b, c)
  312. Call operator
  313. -------------
  314. The call operator, `()`, matches all kinds of unresolved calls and takes
  315. precedence over dot operators, however it does not match missing overloads
  316. for existing routines. The experimental `callOperator` switch must be enabled
  317. to use this operator.
  318. .. code-block:: nim
  319. {.experimental: "callOperator".}
  320. template `()`(a: int, b: float): untyped = $(a, b)
  321. block:
  322. let a = 1.0
  323. let b = 2
  324. doAssert b(a) == `()`(b, a)
  325. doAssert a.b == `()`(b, a)
  326. block:
  327. let a = 1.0
  328. proc b(): int = 2
  329. doAssert not compiles(b(a))
  330. doAssert not compiles(a.b) # `()` not called
  331. block:
  332. let a = 1.0
  333. proc b(x: float): int = int(x + 1)
  334. let c = 3.0
  335. doAssert not compiles(a.b(c)) # gives a type mismatch error same as b(a, c)
  336. doAssert (a.b)(c) == `()`(a.b, c)
  337. Not nil annotation
  338. ==================
  339. **Note:** This is an experimental feature. It can be enabled with
  340. `{.experimental: "notnil"}`.
  341. All types for which `nil` is a valid value can be annotated with the `not
  342. nil` annotation to exclude `nil` as a valid value:
  343. .. code-block:: nim
  344. {.experimental: "notnil"}
  345. type
  346. PObject = ref TObj not nil
  347. TProc = (proc (x, y: int)) not nil
  348. proc p(x: PObject) =
  349. echo "not nil"
  350. # compiler catches this:
  351. p(nil)
  352. # and also this:
  353. var x: PObject
  354. p(x)
  355. The compiler ensures that every code path initializes variables which contain
  356. non-nilable pointers. The details of this analysis are still to be specified
  357. here.
  358. .. include:: manual_experimental_strictnotnil.rst
  359. Concepts
  360. ========
  361. Concepts, also known as "user-defined type classes", are used to specify an
  362. arbitrary set of requirements that the matched type must satisfy.
  363. Concepts are written in the following form:
  364. .. code-block:: nim
  365. type
  366. Comparable = concept x, y
  367. (x < y) is bool
  368. Stack[T] = concept s, var v
  369. s.pop() is T
  370. v.push(T)
  371. s.len is Ordinal
  372. for value in s:
  373. value is T
  374. The concept is a match if:
  375. a) all of the expressions within the body can be compiled for the tested type
  376. b) all statically evaluable boolean expressions in the body must be true
  377. The identifiers following the `concept` keyword represent instances of the
  378. currently matched type. You can apply any of the standard type modifiers such
  379. as `var`, `ref`, `ptr` and `static` to denote a more specific type of
  380. instance. You can also apply the `type` modifier to create a named instance of
  381. the type itself:
  382. .. code-block:: nim
  383. type
  384. MyConcept = concept x, var v, ref r, ptr p, static s, type T
  385. ...
  386. Within the concept body, types can appear in positions where ordinary values
  387. and parameters are expected. This provides a more convenient way to check for
  388. the presence of callable symbols with specific signatures:
  389. .. code-block:: nim
  390. type
  391. OutputStream = concept var s
  392. s.write(string)
  393. In order to check for symbols accepting `type` params, you must prefix
  394. the type with the explicit `type` modifier. The named instance of the
  395. type, following the `concept` keyword is also considered to have the
  396. explicit modifier and will be matched only as a type.
  397. .. code-block:: nim
  398. type
  399. # Let's imagine a user-defined casting framework with operators
  400. # such as `val.to(string)` and `val.to(JSonValue)`. We can test
  401. # for these with the following concept:
  402. MyCastables = concept x
  403. x.to(type string)
  404. x.to(type JSonValue)
  405. # Let's define a couple of concepts, known from Algebra:
  406. AdditiveMonoid* = concept x, y, type T
  407. x + y is T
  408. T.zero is T # require a proc such as `int.zero` or 'Position.zero'
  409. AdditiveGroup* = concept x, y, type T
  410. x is AdditiveMonoid
  411. -x is T
  412. x - y is T
  413. Please note that the `is` operator allows one to easily verify the precise
  414. type signatures of the required operations, but since type inference and
  415. default parameters are still applied in the concept body, it's also possible
  416. to describe usage protocols that do not reveal implementation details.
  417. Much like generics, concepts are instantiated exactly once for each tested type
  418. and any static code included within the body is executed only once.
  419. Concept diagnostics
  420. -------------------
  421. By default, the compiler will report the matching errors in concepts only when
  422. no other overload can be selected and a normal compilation error is produced.
  423. When you need to understand why the compiler is not matching a particular
  424. concept and, as a result, a wrong overload is selected, you can apply the
  425. `explain` pragma to either the concept body or a particular call-site.
  426. .. code-block:: nim
  427. type
  428. MyConcept {.explain.} = concept ...
  429. overloadedProc(x, y, z) {.explain.}
  430. This will provide Hints in the compiler output either every time the concept is
  431. not matched or only on the particular call-site.
  432. Generic concepts and type binding rules
  433. ---------------------------------------
  434. The concept types can be parametric just like the regular generic types:
  435. .. code-block:: nim
  436. ### matrixalgo.nim
  437. import std/typetraits
  438. type
  439. AnyMatrix*[R, C: static int; T] = concept m, var mvar, type M
  440. M.ValueType is T
  441. M.Rows == R
  442. M.Cols == C
  443. m[int, int] is T
  444. mvar[int, int] = T
  445. type TransposedType = stripGenericParams(M)[C, R, T]
  446. AnySquareMatrix*[N: static int, T] = AnyMatrix[N, N, T]
  447. AnyTransform3D* = AnyMatrix[4, 4, float]
  448. proc transposed*(m: AnyMatrix): m.TransposedType =
  449. for r in 0 ..< m.R:
  450. for c in 0 ..< m.C:
  451. result[r, c] = m[c, r]
  452. proc determinant*(m: AnySquareMatrix): int =
  453. ...
  454. proc setPerspectiveProjection*(m: AnyTransform3D) =
  455. ...
  456. --------------
  457. ### matrix.nim
  458. type
  459. Matrix*[M, N: static int; T] = object
  460. data: array[M*N, T]
  461. proc `[]`*(M: Matrix; m, n: int): M.T =
  462. M.data[m * M.N + n]
  463. proc `[]=`*(M: var Matrix; m, n: int; v: M.T) =
  464. M.data[m * M.N + n] = v
  465. # Adapt the Matrix type to the concept's requirements
  466. template Rows*(M: typedesc[Matrix]): int = M.M
  467. template Cols*(M: typedesc[Matrix]): int = M.N
  468. template ValueType*(M: typedesc[Matrix]): typedesc = M.T
  469. -------------
  470. ### usage.nim
  471. import matrix, matrixalgo
  472. var
  473. m: Matrix[3, 3, int]
  474. projectionMatrix: Matrix[4, 4, float]
  475. echo m.transposed.determinant
  476. setPerspectiveProjection projectionMatrix
  477. When the concept type is matched against a concrete type, the unbound type
  478. parameters are inferred from the body of the concept in a way that closely
  479. resembles the way generic parameters of callable symbols are inferred on
  480. call sites.
  481. Unbound types can appear both as params to calls such as `s.push(T)` and
  482. on the right-hand side of the `is` operator in cases such as `x.pop is T`
  483. and `x.data is seq[T]`.
  484. Unbound static params will be inferred from expressions involving the `==`
  485. operator and also when types dependent on them are being matched:
  486. .. code-block:: nim
  487. type
  488. MatrixReducer[M, N: static int; T] = concept x
  489. x.reduce(SquareMatrix[N, T]) is array[M, int]
  490. The Nim compiler includes a simple linear equation solver, allowing it to
  491. infer static params in some situations where integer arithmetic is involved.
  492. Just like in regular type classes, Nim discriminates between `bind once`
  493. and `bind many` types when matching the concept. You can add the `distinct`
  494. modifier to any of the otherwise inferable types to get a type that will be
  495. matched without permanently inferring it. This may be useful when you need
  496. to match several procs accepting the same wide class of types:
  497. .. code-block:: nim
  498. type
  499. Enumerable[T] = concept e
  500. for v in e:
  501. v is T
  502. type
  503. MyConcept = concept o
  504. # this could be inferred to a type such as Enumerable[int]
  505. o.foo is distinct Enumerable
  506. # this could be inferred to a different type such as Enumerable[float]
  507. o.bar is distinct Enumerable
  508. # it's also possible to give an alias name to a `bind many` type class
  509. type Enum = distinct Enumerable
  510. o.baz is Enum
  511. On the other hand, using `bind once` types allows you to test for equivalent
  512. types used in multiple signatures, without actually requiring any concrete
  513. types, thus allowing you to encode implementation-defined types:
  514. .. code-block:: nim
  515. type
  516. MyConcept = concept x
  517. type T1 = auto
  518. x.foo(T1)
  519. x.bar(T1) # both procs must accept the same type
  520. type T2 = seq[SomeNumber]
  521. x.alpha(T2)
  522. x.omega(T2) # both procs must accept the same type
  523. # and it must be a numeric sequence
  524. As seen in the previous examples, you can refer to generic concepts such as
  525. `Enumerable[T]` just by their short name. Much like the regular generic types,
  526. the concept will be automatically instantiated with the bind once auto type
  527. in the place of each missing generic param.
  528. Please note that generic concepts such as `Enumerable[T]` can be matched
  529. against concrete types such as `string`. Nim doesn't require the concept
  530. type to have the same number of parameters as the type being matched.
  531. If you wish to express a requirement towards the generic parameters of
  532. the matched type, you can use a type mapping operator such as `genericHead`
  533. or `stripGenericParams` within the body of the concept to obtain the
  534. uninstantiated version of the type, which you can then try to instantiate
  535. in any required way. For example, here is how one might define the classic
  536. `Functor` concept from Haskell and then demonstrate that Nim's `Option[T]`
  537. type is an instance of it:
  538. .. code-block:: nim
  539. :test: "nim c $1"
  540. import std/[sugar, typetraits]
  541. type
  542. Functor[A] = concept f
  543. type MatchedGenericType = genericHead(typeof(f))
  544. # `f` will be a value of a type such as `Option[T]`
  545. # `MatchedGenericType` will become the `Option` type
  546. f.val is A
  547. # The Functor should provide a way to obtain
  548. # a value stored inside it
  549. type T = auto
  550. map(f, A -> T) is MatchedGenericType[T]
  551. # And it should provide a way to map one instance of
  552. # the Functor to a instance of a different type, given
  553. # a suitable `map` operation for the enclosed values
  554. import std/options
  555. echo Option[int] is Functor # prints true
  556. Concept derived values
  557. ----------------------
  558. All top level constants or types appearing within the concept body are
  559. accessible through the dot operator in procs where the concept was successfully
  560. matched to a concrete type:
  561. .. code-block:: nim
  562. type
  563. DateTime = concept t1, t2, type T
  564. const Min = T.MinDate
  565. T.Now is T
  566. t1 < t2 is bool
  567. type TimeSpan = typeof(t1 - t2)
  568. TimeSpan * int is TimeSpan
  569. TimeSpan + TimeSpan is TimeSpan
  570. t1 + TimeSpan is T
  571. proc eventsJitter(events: Enumerable[DateTime]): float =
  572. var
  573. # this variable will have the inferred TimeSpan type for
  574. # the concrete Date-like value the proc was called with:
  575. averageInterval: DateTime.TimeSpan
  576. deviation: float
  577. ...
  578. Concept refinement
  579. ------------------
  580. When the matched type within a concept is directly tested against a different
  581. concept, we say that the outer concept is a refinement of the inner concept and
  582. thus it is more-specific. When both concepts are matched in a call during
  583. overload resolution, Nim will assign a higher precedence to the most specific
  584. one. As an alternative way of defining concept refinements, you can use the
  585. object inheritance syntax involving the `of` keyword:
  586. .. code-block:: nim
  587. type
  588. Graph = concept g, type G of EquallyComparable, Copyable
  589. type
  590. VertexType = G.VertexType
  591. EdgeType = G.EdgeType
  592. VertexType is Copyable
  593. EdgeType is Copyable
  594. var
  595. v: VertexType
  596. e: EdgeType
  597. IncidendeGraph = concept of Graph
  598. # symbols such as variables and types from the refined
  599. # concept are automatically in scope:
  600. g.source(e) is VertexType
  601. g.target(e) is VertexType
  602. g.outgoingEdges(v) is Enumerable[EdgeType]
  603. BidirectionalGraph = concept g, type G
  604. # The following will also turn the concept into a refinement when it
  605. # comes to overload resolution, but it doesn't provide the convenient
  606. # symbol inheritance
  607. g is IncidendeGraph
  608. g.incomingEdges(G.VertexType) is Enumerable[G.EdgeType]
  609. proc f(g: IncidendeGraph)
  610. proc f(g: BidirectionalGraph) # this one will be preferred if we pass a type
  611. # matching the BidirectionalGraph concept
  612. ..
  613. Converter type classes
  614. ----------------------
  615. Concepts can also be used to convert a whole range of types to a single type or
  616. a small set of simpler types. This is achieved with a `return` statement within
  617. the concept body:
  618. .. code-block:: nim
  619. type
  620. Stringable = concept x
  621. $x is string
  622. return $x
  623. StringRefValue[CharType] = object
  624. base: ptr CharType
  625. len: int
  626. StringRef = concept x
  627. # the following would be an overloaded proc for cstring, string, seq and
  628. # other user-defined types, returning either a StringRefValue[char] or
  629. # StringRefValue[wchar]
  630. return makeStringRefValue(x)
  631. # the varargs param will here be converted to an array of StringRefValues
  632. # the proc will have only two instantiations for the two character types
  633. proc log(format: static string, varargs[StringRef])
  634. # this proc will allow char and wchar values to be mixed in
  635. # the same call at the cost of additional instantiations
  636. # the varargs param will be converted to a tuple
  637. proc log(format: static string, varargs[distinct StringRef])
  638. ..
  639. VTable types
  640. ------------
  641. Concepts allow Nim to define a great number of algorithms, using only
  642. static polymorphism and without erasing any type information or sacrificing
  643. any execution speed. But when polymorphic collections of objects are required,
  644. the user must use one of the provided type erasure techniques - either common
  645. base types or VTable types.
  646. VTable types are represented as "fat pointers" storing a reference to an
  647. object together with a reference to a table of procs implementing a set of
  648. required operations (the so called vtable).
  649. In contrast to other programming languages, the vtable in Nim is stored
  650. externally to the object, allowing you to create multiple different vtable
  651. views for the same object. Thus, the polymorphism in Nim is unbounded -
  652. any type can implement an unlimited number of protocols or interfaces not
  653. originally envisioned by the type's author.
  654. Any concept type can be turned into a VTable type by using the `vtref`
  655. or the `vtptr` compiler magics. Under the hood, these magics generate
  656. a converter type class, which converts the regular instances of the matching
  657. types to the corresponding VTable type.
  658. .. code-block:: nim
  659. type
  660. IntEnumerable = vtref Enumerable[int]
  661. MyObject = object
  662. enumerables: seq[IntEnumerable]
  663. streams: seq[OutputStream.vtref]
  664. proc addEnumerable(o: var MyObject, e: IntEnumerable) =
  665. o.enumerables.add e
  666. proc addStream(o: var MyObject, e: OutputStream.vtref) =
  667. o.streams.add e
  668. The procs that will be included in the vtable are derived from the concept
  669. body and include all proc calls for which all param types were specified as
  670. concrete types. All such calls should include exactly one param of the type
  671. matched against the concept (not necessarily in the first position), which
  672. will be considered the value bound to the vtable.
  673. Overloads will be created for all captured procs, accepting the vtable type
  674. in the position of the captured underlying object.
  675. Under these rules, it's possible to obtain a vtable type for a concept with
  676. unbound type parameters or one instantiated with metatypes (type classes),
  677. but it will include a smaller number of captured procs. A completely empty
  678. vtable will be reported as an error.
  679. The `vtref` magic produces types which can be bound to `ref` types and
  680. the `vtptr` magic produced types bound to `ptr` types.
  681. Type bound operations
  682. =====================
  683. There are 4 operations that are bound to a type:
  684. 1. Assignment
  685. 2. Moves
  686. 3. Destruction
  687. 4. Deep copying for communication between threads
  688. These operations can be *overridden* instead of *overloaded*. This means the
  689. implementation is automatically lifted to structured types. For instance if type
  690. `T` has an overridden assignment operator `=` this operator is also used
  691. for assignments of the type `seq[T]`. Since these operations are bound to a
  692. type they have to be bound to a nominal type for reasons of simplicity of
  693. implementation: This means an overridden `deepCopy` for `ref T` is really
  694. bound to `T` and not to `ref T`. This also means that one cannot override
  695. `deepCopy` for both `ptr T` and `ref T` at the same time; instead a
  696. helper distinct or object type has to be used for one pointer type.
  697. Assignments, moves and destruction are specified in
  698. the `destructors <destructors.html>`_ document.
  699. deepCopy
  700. --------
  701. `=deepCopy` is a builtin that is invoked whenever data is passed to
  702. a `spawn`'ed proc to ensure memory safety. The programmer can override its
  703. behaviour for a specific `ref` or `ptr` type `T`. (Later versions of the
  704. language may weaken this restriction.)
  705. The signature has to be:
  706. .. code-block:: nim
  707. proc `=deepCopy`(x: T): T
  708. This mechanism will be used by most data structures that support shared memory
  709. like channels to implement thread safe automatic memory management.
  710. The builtin `deepCopy` can even clone closures and their environments. See
  711. the documentation of `spawn <#parallel-amp-spawn-spawn-statement>`_ for details.
  712. Case statement macros
  713. =====================
  714. Macros named `case` can rewrite `case` statements for certain types in order to
  715. implement `pattern matching`:idx:. The following example implements a
  716. simplistic form of pattern matching for tuples, leveraging the existing
  717. equality operator for tuples (as provided in `system.==`):
  718. .. code-block:: nim
  719. :test: "nim c $1"
  720. {.experimental: "caseStmtMacros".}
  721. import std/macros
  722. macro `case`(n: tuple): untyped =
  723. result = newTree(nnkIfStmt)
  724. let selector = n[0]
  725. for i in 1 ..< n.len:
  726. let it = n[i]
  727. case it.kind
  728. of nnkElse, nnkElifBranch, nnkElifExpr, nnkElseExpr:
  729. result.add it
  730. of nnkOfBranch:
  731. for j in 0..it.len-2:
  732. let cond = newCall("==", selector, it[j])
  733. result.add newTree(nnkElifBranch, cond, it[^1])
  734. else:
  735. error "custom 'case' for tuple cannot handle this node", it
  736. case ("foo", 78)
  737. of ("foo", 78): echo "yes"
  738. of ("bar", 88): echo "no"
  739. else: discard
  740. Currently case statement macros must be enabled explicitly
  741. via `{.experimental: "caseStmtMacros".}`.
  742. `case` macros are subject to overload resolution. The type of the
  743. `case` statement's selector expression is matched against the type
  744. of the first argument of the `case` macro. Then the complete `case`
  745. statement is passed in place of the argument and the macro is evaluated.
  746. In other words, the macro needs to transform the full `case` statement
  747. but only the statement's selector expression is used to determine which
  748. macro to call.
  749. Term rewriting macros
  750. =====================
  751. Term rewriting macros are macros or templates that have not only
  752. a *name* but also a *pattern* that is searched for after the semantic checking
  753. phase of the compiler: This means they provide an easy way to enhance the
  754. compilation pipeline with user defined optimizations:
  755. .. code-block:: nim
  756. template optMul{`*`(a, 2)}(a: int): int = a+a
  757. let x = 3
  758. echo x * 2
  759. The compiler now rewrites `x * 2` as `x + x`. The code inside the
  760. curlies is the pattern to match against. The operators `*`, `**`,
  761. `|`, `~` have a special meaning in patterns if they are written in infix
  762. notation, so to match verbatim against `*` the ordinary function call syntax
  763. needs to be used.
  764. Term rewriting macro are applied recursively, up to a limit. This means that
  765. if the result of a term rewriting macro is eligible for another rewriting,
  766. the compiler will try to perform it, and so on, until no more optimizations
  767. are applicable. To avoid putting the compiler into an infinite loop, there is
  768. a hard limit on how many times a single term rewriting macro can be applied.
  769. Once this limit has been passed, the term rewriting macro will be ignored.
  770. Unfortunately optimizations are hard to get right and even the tiny example
  771. is **wrong**:
  772. .. code-block:: nim
  773. template optMul{`*`(a, 2)}(a: int): int = a+a
  774. proc f(): int =
  775. echo "side effect!"
  776. result = 55
  777. echo f() * 2
  778. We cannot duplicate 'a' if it denotes an expression that has a side effect!
  779. Fortunately Nim supports side effect analysis:
  780. .. code-block:: nim
  781. template optMul{`*`(a, 2)}(a: int{noSideEffect}): int = a+a
  782. proc f(): int =
  783. echo "side effect!"
  784. result = 55
  785. echo f() * 2 # not optimized ;-)
  786. You can make one overload matching with a constraint and one without, and the
  787. one with a constraint will have precedence, and so you can handle both cases
  788. differently.
  789. So what about `2 * a`? We should tell the compiler `*` is commutative. We
  790. cannot really do that however as the following code only swaps arguments
  791. blindly:
  792. .. code-block:: nim
  793. template mulIsCommutative{`*`(a, b)}(a, b: int): int = b*a
  794. What optimizers really need to do is a *canonicalization*:
  795. .. code-block:: nim
  796. template canonMul{`*`(a, b)}(a: int{lit}, b: int): int = b*a
  797. The `int{lit}` parameter pattern matches against an expression of
  798. type `int`, but only if it's a literal.
  799. Parameter constraints
  800. ---------------------
  801. The `parameter constraint`:idx: expression can use the operators `|` (or),
  802. `&` (and) and `~` (not) and the following predicates:
  803. =================== =====================================================
  804. Predicate Meaning
  805. =================== =====================================================
  806. `atom` The matching node has no children.
  807. `lit` The matching node is a literal like "abc", 12.
  808. `sym` The matching node must be a symbol (a bound
  809. identifier).
  810. `ident` The matching node must be an identifier (an unbound
  811. identifier).
  812. `call` The matching AST must be a call/apply expression.
  813. `lvalue` The matching AST must be an lvalue.
  814. `sideeffect` The matching AST must have a side effect.
  815. `nosideeffect` The matching AST must have no side effect.
  816. `param` A symbol which is a parameter.
  817. `genericparam` A symbol which is a generic parameter.
  818. `module` A symbol which is a module.
  819. `type` A symbol which is a type.
  820. `var` A symbol which is a variable.
  821. `let` A symbol which is a `let` variable.
  822. `const` A symbol which is a constant.
  823. `result` The special `result` variable.
  824. `proc` A symbol which is a proc.
  825. `method` A symbol which is a method.
  826. `iterator` A symbol which is an iterator.
  827. `converter` A symbol which is a converter.
  828. `macro` A symbol which is a macro.
  829. `template` A symbol which is a template.
  830. `field` A symbol which is a field in a tuple or an object.
  831. `enumfield` A symbol which is a field in an enumeration.
  832. `forvar` A for loop variable.
  833. `label` A label (used in `block` statements).
  834. `nk*` The matching AST must have the specified kind.
  835. (Example: `nkIfStmt` denotes an `if` statement.)
  836. `alias` States that the marked parameter needs to alias
  837. with *some* other parameter.
  838. `noalias` States that *every* other parameter must not alias
  839. with the marked parameter.
  840. =================== =====================================================
  841. Predicates that share their name with a keyword have to be escaped with
  842. backticks.
  843. The `alias` and `noalias` predicates refer not only to the matching AST,
  844. but also to every other bound parameter; syntactically they need to occur after
  845. the ordinary AST predicates:
  846. .. code-block:: nim
  847. template ex{a = b + c}(a: int{noalias}, b, c: int) =
  848. # this transformation is only valid if 'b' and 'c' do not alias 'a':
  849. a = b
  850. inc a, c
  851. Pattern operators
  852. -----------------
  853. The operators `*`, `**`, `|`, `~` have a special meaning in patterns
  854. if they are written in infix notation.
  855. The `|` operator
  856. ~~~~~~~~~~~~~~~~~~
  857. The `|` operator if used as infix operator creates an ordered choice:
  858. .. code-block:: nim
  859. template t{0|1}(): untyped = 3
  860. let a = 1
  861. # outputs 3:
  862. echo a
  863. The matching is performed after the compiler performed some optimizations like
  864. constant folding, so the following does not work:
  865. .. code-block:: nim
  866. template t{0|1}(): untyped = 3
  867. # outputs 1:
  868. echo 1
  869. The reason is that the compiler already transformed the 1 into "1" for
  870. the `echo` statement. However, a term rewriting macro should not change the
  871. semantics anyway. In fact they can be deactivated with the `--patterns:off`
  872. command line option or temporarily with the `patterns` pragma.
  873. The `{}` operator
  874. ~~~~~~~~~~~~~~~~~~~
  875. A pattern expression can be bound to a pattern parameter via the `expr{param}`
  876. notation:
  877. .. code-block:: nim
  878. template t{(0|1|2){x}}(x: untyped): untyped = x+1
  879. let a = 1
  880. # outputs 2:
  881. echo a
  882. The `~` operator
  883. ~~~~~~~~~~~~~~~~~~
  884. The `~` operator is the **not** operator in patterns:
  885. .. code-block:: nim
  886. template t{x = (~x){y} and (~x){z}}(x, y, z: bool) =
  887. x = y
  888. if x: x = z
  889. var
  890. a = false
  891. b = true
  892. c = false
  893. a = b and c
  894. echo a
  895. The `*` operator
  896. ~~~~~~~~~~~~~~~~~~
  897. The `*` operator can *flatten* a nested binary expression like `a & b & c`
  898. to `&(a, b, c)`:
  899. .. code-block:: nim
  900. var
  901. calls = 0
  902. proc `&&`(s: varargs[string]): string =
  903. result = s[0]
  904. for i in 1..len(s)-1: result.add s[i]
  905. inc calls
  906. template optConc{ `&&` * a }(a: string): untyped = &&a
  907. let space = " "
  908. echo "my" && (space & "awe" && "some " ) && "concat"
  909. # check that it's been optimized properly:
  910. doAssert calls == 1
  911. The second operator of `*` must be a parameter; it is used to gather all the
  912. arguments. The expression `"my" && (space & "awe" && "some " ) && "concat"`
  913. is passed to `optConc` in `a` as a special list (of kind `nkArgList`)
  914. which is flattened into a call expression; thus the invocation of `optConc`
  915. produces:
  916. .. code-block:: nim
  917. `&&`("my", space & "awe", "some ", "concat")
  918. The `**` operator
  919. ~~~~~~~~~~~~~~~~~~~
  920. The `**` is much like the `*` operator, except that it gathers not only
  921. all the arguments, but also the matched operators in reverse polish notation:
  922. .. code-block:: nim
  923. import std/macros
  924. type
  925. Matrix = object
  926. dummy: int
  927. proc `*`(a, b: Matrix): Matrix = discard
  928. proc `+`(a, b: Matrix): Matrix = discard
  929. proc `-`(a, b: Matrix): Matrix = discard
  930. proc `$`(a: Matrix): string = result = $a.dummy
  931. proc mat21(): Matrix =
  932. result.dummy = 21
  933. macro optM{ (`+`|`-`|`*`) ** a }(a: Matrix): untyped =
  934. echo treeRepr(a)
  935. result = newCall(bindSym"mat21")
  936. var x, y, z: Matrix
  937. echo x + y * z - x
  938. This passes the expression `x + y * z - x` to the `optM` macro as
  939. an `nnkArgList` node containing::
  940. Arglist
  941. Sym "x"
  942. Sym "y"
  943. Sym "z"
  944. Sym "*"
  945. Sym "+"
  946. Sym "x"
  947. Sym "-"
  948. (Which is the reverse polish notation of `x + y * z - x`.)
  949. Parameters
  950. ----------
  951. Parameters in a pattern are type checked in the matching process. If a
  952. parameter is of the type `varargs` it is treated specially and it can match
  953. 0 or more arguments in the AST to be matched against:
  954. .. code-block:: nim
  955. template optWrite{
  956. write(f, x)
  957. ((write|writeLine){w})(f, y)
  958. }(x, y: varargs[untyped], f: File, w: untyped) =
  959. w(f, x, y)
  960. Example: Partial evaluation
  961. ---------------------------
  962. The following example shows how some simple partial evaluation can be
  963. implemented with term rewriting:
  964. .. code-block:: nim
  965. proc p(x, y: int; cond: bool): int =
  966. result = if cond: x + y else: x - y
  967. template optP1{p(x, y, true)}(x, y: untyped): untyped = x + y
  968. template optP2{p(x, y, false)}(x, y: untyped): untyped = x - y
  969. Example: Hoisting
  970. -----------------
  971. The following example shows how some form of hoisting can be implemented:
  972. .. code-block:: nim
  973. import std/pegs
  974. template optPeg{peg(pattern)}(pattern: string{lit}): Peg =
  975. var gl {.global, gensym.} = peg(pattern)
  976. gl
  977. for i in 0 .. 3:
  978. echo match("(a b c)", peg"'(' @ ')'")
  979. echo match("W_HI_Le", peg"\y 'while'")
  980. The `optPeg` template optimizes the case of a peg constructor with a string
  981. literal, so that the pattern will only be parsed once at program startup and
  982. stored in a global `gl` which is then re-used. This optimization is called
  983. hoisting because it is comparable to classical loop hoisting.
  984. AST based overloading
  985. =====================
  986. Parameter constraints can also be used for ordinary routine parameters; these
  987. constraints affect ordinary overloading resolution then:
  988. .. code-block:: nim
  989. proc optLit(a: string{lit|`const`}) =
  990. echo "string literal"
  991. proc optLit(a: string) =
  992. echo "no string literal"
  993. const
  994. constant = "abc"
  995. var
  996. variable = "xyz"
  997. optLit("literal")
  998. optLit(constant)
  999. optLit(variable)
  1000. However, the constraints `alias` and `noalias` are not available in
  1001. ordinary routines.
  1002. Parallel & Spawn
  1003. ================
  1004. Nim has two flavors of parallelism:
  1005. 1) `Structured`:idx: parallelism via the `parallel` statement.
  1006. 2) `Unstructured`:idx: parallelism via the standalone `spawn` statement.
  1007. Nim has a builtin thread pool that can be used for CPU intensive tasks. For
  1008. IO intensive tasks the `async` and `await` features should be
  1009. used instead. Both parallel and spawn need the `threadpool <threadpool.html>`_
  1010. module to work.
  1011. Somewhat confusingly, `spawn` is also used in the `parallel` statement
  1012. with slightly different semantics. `spawn` always takes a call expression of
  1013. the form `f(a, ...)`. Let `T` be `f`'s return type. If `T` is `void`
  1014. then `spawn`'s return type is also `void` otherwise it is `FlowVar[T]`.
  1015. Within a `parallel` section sometimes the `FlowVar[T]` is eliminated
  1016. to `T`. This happens when `T` does not contain any GC'ed memory.
  1017. The compiler can ensure the location in `location = spawn f(...)` is not
  1018. read prematurely within a `parallel` section and so there is no need for
  1019. the overhead of an indirection via `FlowVar[T]` to ensure correctness.
  1020. **Note**: Currently exceptions are not propagated between `spawn`'ed tasks!
  1021. Spawn statement
  1022. ---------------
  1023. `spawn`:idx: can be used to pass a task to the thread pool:
  1024. .. code-block:: nim
  1025. import std/threadpool
  1026. proc processLine(line: string) =
  1027. discard "do some heavy lifting here"
  1028. for x in lines("myinput.txt"):
  1029. spawn processLine(x)
  1030. sync()
  1031. For reasons of type safety and implementation simplicity the expression
  1032. that `spawn` takes is restricted:
  1033. * It must be a call expression `f(a, ...)`.
  1034. * `f` must be `gcsafe`.
  1035. * `f` must not have the calling convention `closure`.
  1036. * `f`'s parameters may not be of type `var`.
  1037. This means one has to use raw `ptr`'s for data passing reminding the
  1038. programmer to be careful.
  1039. * `ref` parameters are deeply copied which is a subtle semantic change and
  1040. can cause performance problems but ensures memory safety. This deep copy
  1041. is performed via `system.deepCopy` and so can be overridden.
  1042. * For *safe* data exchange between `f` and the caller a global `TChannel`
  1043. needs to be used. However, since spawn can return a result, often no further
  1044. communication is required.
  1045. `spawn` executes the passed expression on the thread pool and returns
  1046. a `data flow variable`:idx: `FlowVar[T]` that can be read from. The reading
  1047. with the `^` operator is **blocking**. However, one can use `blockUntilAny` to
  1048. wait on multiple flow variables at the same time:
  1049. .. code-block:: nim
  1050. import std/threadpool, ...
  1051. # wait until 2 out of 3 servers received the update:
  1052. proc main =
  1053. var responses = newSeq[FlowVarBase](3)
  1054. for i in 0..2:
  1055. responses[i] = spawn tellServer(Update, "key", "value")
  1056. var index = blockUntilAny(responses)
  1057. assert index >= 0
  1058. responses.del(index)
  1059. discard blockUntilAny(responses)
  1060. Data flow variables ensure that no data races
  1061. are possible. Due to technical limitations not every type `T` is possible in
  1062. a data flow variable: `T` has to be of the type `ref`, `string`, `seq`
  1063. or of a type that doesn't contain a type that is garbage collected. This
  1064. restriction is not hard to work-around in practice.
  1065. Parallel statement
  1066. ------------------
  1067. Example:
  1068. .. code-block:: nim
  1069. :test: "nim c --threads:on $1"
  1070. # Compute PI in an inefficient way
  1071. import std/[strutils, math, threadpool]
  1072. {.experimental: "parallel".}
  1073. proc term(k: float): float = 4 * math.pow(-1, k) / (2*k + 1)
  1074. proc pi(n: int): float =
  1075. var ch = newSeq[float](n+1)
  1076. parallel:
  1077. for k in 0..ch.high:
  1078. ch[k] = spawn term(float(k))
  1079. for k in 0..ch.high:
  1080. result += ch[k]
  1081. echo formatFloat(pi(5000))
  1082. The parallel statement is the preferred mechanism to introduce parallelism in a
  1083. Nim program. A subset of the Nim language is valid within a `parallel`
  1084. section. This subset is checked during semantic analysis to be free of data
  1085. races. A sophisticated `disjoint checker`:idx: ensures that no data races are
  1086. possible even though shared memory is extensively supported!
  1087. The subset is in fact the full language with the following
  1088. restrictions / changes:
  1089. * `spawn` within a `parallel` section has special semantics.
  1090. * Every location of the form `a[i]` and `a[i..j]` and `dest` where
  1091. `dest` is part of the pattern `dest = spawn f(...)` has to be
  1092. provably disjoint. This is called the *disjoint check*.
  1093. * Every other complex location `loc` that is used in a spawned
  1094. proc (`spawn f(loc)`) has to be immutable for the duration of
  1095. the `parallel` section. This is called the *immutability check*. Currently
  1096. it is not specified what exactly "complex location" means. We need to make
  1097. this an optimization!
  1098. * Every array access has to be provably within bounds. This is called
  1099. the *bounds check*.
  1100. * Slices are optimized so that no copy is performed. This optimization is not
  1101. yet performed for ordinary slices outside of a `parallel` section.
  1102. Guards and locks
  1103. ================
  1104. Apart from `spawn` and `parallel` Nim also provides all the common low level
  1105. concurrency mechanisms like locks, atomic intrinsics or condition variables.
  1106. Nim significantly improves on the safety of these features via additional
  1107. pragmas:
  1108. 1) A `guard`:idx: annotation is introduced to prevent data races.
  1109. 2) Every access of a guarded memory location needs to happen in an
  1110. appropriate `locks`:idx: statement.
  1111. 3) Locks and routines can be annotated with `lock levels`:idx: to allow
  1112. potential deadlocks to be detected during semantic analysis.
  1113. Guards and the locks section
  1114. ----------------------------
  1115. Protecting global variables
  1116. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1117. Object fields and global variables can be annotated via a `guard` pragma:
  1118. .. code-block:: nim
  1119. var glock: TLock
  1120. var gdata {.guard: glock.}: int
  1121. The compiler then ensures that every access of `gdata` is within a `locks`
  1122. section:
  1123. .. code-block:: nim
  1124. proc invalid =
  1125. # invalid: unguarded access:
  1126. echo gdata
  1127. proc valid =
  1128. # valid access:
  1129. {.locks: [glock].}:
  1130. echo gdata
  1131. Top level accesses to `gdata` are always allowed so that it can be initialized
  1132. conveniently. It is *assumed* (but not enforced) that every top level statement
  1133. is executed before any concurrent action happens.
  1134. The `locks` section deliberately looks ugly because it has no runtime
  1135. semantics and should not be used directly! It should only be used in templates
  1136. that also implement some form of locking at runtime:
  1137. .. code-block:: nim
  1138. template lock(a: TLock; body: untyped) =
  1139. pthread_mutex_lock(a)
  1140. {.locks: [a].}:
  1141. try:
  1142. body
  1143. finally:
  1144. pthread_mutex_unlock(a)
  1145. The guard does not need to be of any particular type. It is flexible enough to
  1146. model low level lockfree mechanisms:
  1147. .. code-block:: nim
  1148. var dummyLock {.compileTime.}: int
  1149. var atomicCounter {.guard: dummyLock.}: int
  1150. template atomicRead(x): untyped =
  1151. {.locks: [dummyLock].}:
  1152. memoryReadBarrier()
  1153. x
  1154. echo atomicRead(atomicCounter)
  1155. The `locks` pragma takes a list of lock expressions `locks: [a, b, ...]`
  1156. in order to support *multi lock* statements. Why these are essential is
  1157. explained in the `lock levels <#guards-and-locks-lock-levels>`_ section.
  1158. Protecting general locations
  1159. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1160. The `guard` annotation can also be used to protect fields within an object.
  1161. The guard then needs to be another field within the same object or a
  1162. global variable.
  1163. Since objects can reside on the heap or on the stack this greatly enhances the
  1164. expressivity of the language:
  1165. .. code-block:: nim
  1166. type
  1167. ProtectedCounter = object
  1168. v {.guard: L.}: int
  1169. L: TLock
  1170. proc incCounters(counters: var openArray[ProtectedCounter]) =
  1171. for i in 0..counters.high:
  1172. lock counters[i].L:
  1173. inc counters[i].v
  1174. The access to field `x.v` is allowed since its guard `x.L` is active.
  1175. After template expansion, this amounts to:
  1176. .. code-block:: nim
  1177. proc incCounters(counters: var openArray[ProtectedCounter]) =
  1178. for i in 0..counters.high:
  1179. pthread_mutex_lock(counters[i].L)
  1180. {.locks: [counters[i].L].}:
  1181. try:
  1182. inc counters[i].v
  1183. finally:
  1184. pthread_mutex_unlock(counters[i].L)
  1185. There is an analysis that checks that `counters[i].L` is the lock that
  1186. corresponds to the protected location `counters[i].v`. This analysis is called
  1187. `path analysis`:idx: because it deals with paths to locations
  1188. like `obj.field[i].fieldB[j]`.
  1189. The path analysis is **currently unsound**, but that doesn't make it useless.
  1190. Two paths are considered equivalent if they are syntactically the same.
  1191. This means the following compiles (for now) even though it really should not:
  1192. .. code-block:: nim
  1193. {.locks: [a[i].L].}:
  1194. inc i
  1195. access a[i].v
  1196. Lock levels
  1197. -----------
  1198. Lock levels are used to enforce a global locking order in order to detect
  1199. potential deadlocks during semantic analysis. A lock level is an constant
  1200. integer in the range 0..1_000. Lock level 0 means that no lock is acquired at
  1201. all.
  1202. If a section of code holds a lock of level `M` than it can also acquire any
  1203. lock of level `N < M`. Another lock of level `M` cannot be acquired. Locks
  1204. of the same level can only be acquired *at the same time* within a
  1205. single `locks` section:
  1206. .. code-block:: nim
  1207. var a, b: TLock[2]
  1208. var x: TLock[1]
  1209. # invalid locking order: TLock[1] cannot be acquired before TLock[2]:
  1210. {.locks: [x].}:
  1211. {.locks: [a].}:
  1212. ...
  1213. # valid locking order: TLock[2] acquired before TLock[1]:
  1214. {.locks: [a].}:
  1215. {.locks: [x].}:
  1216. ...
  1217. # invalid locking order: TLock[2] acquired before TLock[2]:
  1218. {.locks: [a].}:
  1219. {.locks: [b].}:
  1220. ...
  1221. # valid locking order, locks of the same level acquired at the same time:
  1222. {.locks: [a, b].}:
  1223. ...
  1224. Here is how a typical multilock statement can be implemented in Nim. Note how
  1225. the runtime check is required to ensure a global ordering for two locks `a`
  1226. and `b` of the same lock level:
  1227. .. code-block:: nim
  1228. template multilock(a, b: ptr TLock; body: untyped) =
  1229. if cast[ByteAddress](a) < cast[ByteAddress](b):
  1230. pthread_mutex_lock(a)
  1231. pthread_mutex_lock(b)
  1232. else:
  1233. pthread_mutex_lock(b)
  1234. pthread_mutex_lock(a)
  1235. {.locks: [a, b].}:
  1236. try:
  1237. body
  1238. finally:
  1239. pthread_mutex_unlock(a)
  1240. pthread_mutex_unlock(b)
  1241. Whole routines can also be annotated with a `locks` pragma that takes a lock
  1242. level. This then means that the routine may acquire locks of up to this level.
  1243. This is essential so that procs can be called within a `locks` section:
  1244. .. code-block:: nim
  1245. proc p() {.locks: 3.} = discard
  1246. var a: TLock[4]
  1247. {.locks: [a].}:
  1248. # p's locklevel (3) is strictly less than a's (4) so the call is allowed:
  1249. p()
  1250. As usual `locks` is an inferred effect and there is a subtype
  1251. relation: `proc () {.locks: N.}` is a subtype of `proc () {.locks: M.}`
  1252. iff (M <= N).
  1253. The `locks` pragma can also take the special value `"unknown"`. This
  1254. is useful in the context of dynamic method dispatching. In the following
  1255. example, the compiler can infer a lock level of 0 for the `base` case.
  1256. However, one of the overloaded methods calls a procvar which is
  1257. potentially locking. Thus, the lock level of calling `g.testMethod`
  1258. cannot be inferred statically, leading to compiler warnings. By using
  1259. `{.locks: "unknown".}`, the base method can be marked explicitly as
  1260. having unknown lock level as well:
  1261. .. code-block:: nim
  1262. type SomeBase* = ref object of RootObj
  1263. type SomeDerived* = ref object of SomeBase
  1264. memberProc*: proc ()
  1265. method testMethod(g: SomeBase) {.base, locks: "unknown".} = discard
  1266. method testMethod(g: SomeDerived) =
  1267. if g.memberProc != nil:
  1268. g.memberProc()
  1269. noRewrite pragma
  1270. ----------------
  1271. Term rewriting macros and templates are currently greedy and
  1272. they will rewrite as long as there is a match.
  1273. There was no way to ensure some rewrite happens only once,
  1274. e.g. when rewriting term to same term plus extra content.
  1275. `noRewrite` pragma can actually prevent further rewriting on marked code,
  1276. e.g. with given example `echo("ab")` will be rewritten just once:
  1277. .. code-block:: nim
  1278. template pwnEcho{echo(x)}(x: untyped) =
  1279. {.noRewrite.}: echo("pwned!")
  1280. echo "ab"
  1281. `noRewrite` pragma can be useful to control term-rewriting macros recursion.
  1282. Aliasing restrictions in parameter passing
  1283. ==========================================
  1284. **Note**: The aliasing restrictions are currently not enforced by the
  1285. implementation and need to be fleshed out further.
  1286. "Aliasing" here means that the underlying storage locations overlap in memory
  1287. at runtime. An "output parameter" is a parameter of type `var T`,
  1288. an input parameter is any parameter that is not of type `var`.
  1289. 1. Two output parameters should never be aliased.
  1290. 2. An input and an output parameter should not be aliased.
  1291. 3. An output parameter should never be aliased with a global or thread local
  1292. variable referenced by the called proc.
  1293. 4. An input parameter should not be aliased with a global or thread local
  1294. variable updated by the called proc.
  1295. One problem with rules 3 and 4 is that they affect specific global or thread
  1296. local variables, but Nim's effect tracking only tracks "uses no global variable"
  1297. via `.noSideEffect`. The rules 3 and 4 can also be approximated by a different rule:
  1298. 5. A global or thread local variable (or a location derived from such a location)
  1299. can only passed to a parameter of a `.noSideEffect` proc.
  1300. Noalias annotation
  1301. ==================
  1302. Since version 1.4 of the Nim compiler, there is a `.noalias` annotation for variables
  1303. and parameters. It is mapped directly to C/C++'s `restrict` keyword and means that
  1304. the underlying pointer is pointing to a unique location in memory, no other aliases to
  1305. this location exist. It is *unchecked* that this alias restriction is followed, if the
  1306. restriction is violated, the backend optimizer is free to miscompile the code.
  1307. This is an **unsafe** language feature.
  1308. Ideally in later versions of the language, the restriction will be enforced at
  1309. compile time. (Which is also why the name `noalias` was choosen instead of a more
  1310. verbose name like `unsafeAssumeNoAlias`.)
  1311. Strict funcs
  1312. ============
  1313. Since version 1.4 a stricter definition of "side effect" is available. In addition
  1314. to the existing rule that a side effect is calling a function with side effects
  1315. the following rule is also enforced:
  1316. Any mutation to an object does count as a side effect if that object is reachable
  1317. via a parameter that is not declared as a `var` parameter.
  1318. For example:
  1319. .. code-block:: nim
  1320. {.experimental: "strictFuncs".}
  1321. type
  1322. Node = ref object
  1323. le, ri: Node
  1324. data: string
  1325. func len(n: Node): int =
  1326. # valid: len does not have side effects
  1327. var it = n
  1328. while it != nil:
  1329. inc result
  1330. it = it.ri
  1331. func mut(n: Node) =
  1332. let m = n # is the statement that connected the mutation to the parameter
  1333. m.data = "yeah" # the mutation is here
  1334. # Error: 'mut' can have side effects
  1335. # an object reachable from 'n' is potentially mutated
  1336. The algorithm behind this analysis is described in
  1337. the `view types section <#view-types-algorithm>`_.
  1338. View types
  1339. ==========
  1340. **Note**: `--experimental:views` is more effective
  1341. with `--experimental:strictFuncs`.
  1342. A view type is a type that is or contains one of the following types:
  1343. - `var T` (mutable view into `T`)
  1344. - `lent T` (immutable view into `T`)
  1345. - `openArray[T]` (pair of (pointer to array of `T`, size))
  1346. For example:
  1347. .. code-block:: nim
  1348. type
  1349. View1 = var int
  1350. View2 = openArray[byte]
  1351. View3 = lent string
  1352. View4 = Table[openArray[char], int]
  1353. Exceptions to this rule are types constructed via `ptr` or `proc`.
  1354. For example, the following types are **not** view types:
  1355. .. code-block:: nim
  1356. type
  1357. NotView1 = proc (x: openArray[int])
  1358. NotView2 = ptr openArray[char]
  1359. NotView3 = ptr array[4, var int]
  1360. A *mutable* view type is a type that is or contains a `var T` type.
  1361. An *immutable* view type is a view type that is not a mutable view type.
  1362. A *view* is a symbol (a let, var, const, etc.) that has a view type.
  1363. Since version 1.4 Nim allows view types to be used as local variables.
  1364. This feature needs to be enabled via `{.experimental: "views".}`.
  1365. A local variable of a view type *borrows* from the locations and
  1366. it is statically enforced that the view does not outlive the location
  1367. it was borrowed from.
  1368. For example:
  1369. .. code-block:: nim
  1370. {.experimental: "views".}
  1371. proc take(a: openArray[int]) =
  1372. echo a.len
  1373. proc main(s: seq[int]) =
  1374. var x: openArray[int] = s # 'x' is a view into 's'
  1375. # it is checked that 'x' does not outlive 's' and
  1376. # that 's' is not mutated.
  1377. for i in 0 .. high(x):
  1378. echo x[i]
  1379. take(x)
  1380. take(x.toOpenArray(0, 1)) # slicing remains possible
  1381. let y = x # create a view from a view
  1382. take y
  1383. # it is checked that 'y' does not outlive 'x' and
  1384. # that 'x' is not mutated as long as 'y' lives.
  1385. main(@[11, 22, 33])
  1386. A local variable of a view type can borrow from a location
  1387. derived from a parameter, another local variable, a global `const` or `let`
  1388. symbol or a thread-local `var` or `let`.
  1389. Let `p` the proc that is analysed for the correctness of the borrow operation.
  1390. Let `source` be one of:
  1391. - A formal parameter of `p`. Note that this does not cover parameters of
  1392. inner procs.
  1393. - The `result` symbol of `p`.
  1394. - A local `var` or `let` or `const` of `p`. Note that this does
  1395. not cover locals of inner procs.
  1396. - A thread-local `var` or `let`.
  1397. - A global `let` or `const`.
  1398. - A constant array/seq/object/tuple constructor.
  1399. Path expressions
  1400. ----------------
  1401. A location derived from `source` is then defined as a path expression that
  1402. has `source` as the owner. A path expression `e` is defined recursively:
  1403. - `source` itself is a path expression.
  1404. - Container access like `e[i]` is a path expression.
  1405. - Tuple access `e[0]` is a path expression.
  1406. - Object field access `e.field` is a path expression.
  1407. - `system.toOpenArray(e, ...)` is a path expression.
  1408. - Pointer dereference `e[]` is a path expression.
  1409. - An address `addr e`, `unsafeAddr e` is a path expression.
  1410. - A type conversion `T(e)` is a path expression.
  1411. - A cast expression `cast[T](e)` is a path expression.
  1412. - `f(e, ...)` is a path expression if `f`'s return type is a view type.
  1413. Because the view can only have been borrowed from `e`, we then know
  1414. that owner of `f(e, ...)` is `e`.
  1415. If a view type is used as a return type, the location must borrow from a location
  1416. that is derived from the first parameter that is passed to the proc.
  1417. See https://nim-lang.org/docs/manual.html#procedures-var-return-type for
  1418. details about how this is done for `var T`.
  1419. A mutable view can borrow from a mutable location, an immutable view can borrow
  1420. from both a mutable or an immutable location.
  1421. The *duration* of a borrow is the span of commands beginning from the assignment
  1422. to the view and ending with the last usage of the view.
  1423. For the duration of the borrow operation, no mutations to the borrowed locations
  1424. may be performed except via the potentially mutable view that borrowed from the
  1425. location. The borrowed location is said to be *sealed* during the borrow.
  1426. .. code-block:: nim
  1427. {.experimental: "views".}
  1428. type
  1429. Obj = object
  1430. field: string
  1431. proc dangerous(s: var seq[Obj]) =
  1432. let v: lent Obj = s[0] # seal 's'
  1433. s.setLen 0 # prevented at compile-time because 's' is sealed.
  1434. echo v.field
  1435. The scope of the view does not matter:
  1436. .. code-block:: nim
  1437. proc valid(s: var seq[Obj]) =
  1438. let v: lent Obj = s[0] # begin of borrow
  1439. echo v.field # end of borrow
  1440. s.setLen 0 # valid because 'v' isn't used afterwards
  1441. The analysis requires as much precision about mutations as is reasonably obtainable,
  1442. so it is more effective with the experimental `strict funcs <#strict-funcs>`_
  1443. feature. In other words `--experimental:views` works better
  1444. with `--experimental:strictFuncs`.
  1445. The analysis is currently control flow insensitive:
  1446. .. code-block:: nim
  1447. proc invalid(s: var seq[Obj]) =
  1448. let v: lent Obj = s[0]
  1449. if false:
  1450. s.setLen 0
  1451. echo v.field
  1452. In this example, the compiler assumes that `s.setLen 0` invalidates the
  1453. borrow operation of `v` even though a human being can easily see that it
  1454. will never do that at runtime.
  1455. Start of a borrow
  1456. -----------------
  1457. A borrow starts with one of the following:
  1458. - The assignment of a non-view-type to a view-type.
  1459. - The assignment of a location that is derived from a local parameter
  1460. to a view-type.
  1461. End of a borrow
  1462. ---------------
  1463. A borrow operation ends with the last usage of the view variable.
  1464. Reborrows
  1465. ---------
  1466. A view `v` can borrow from multiple different locations. However, the borrow
  1467. is always the full span of `v`'s lifetime and every location that is borrowed
  1468. from is sealed during `v`'s lifetime.
  1469. Algorithm
  1470. ---------
  1471. The following section is an outline of the algorithm that the current implementation
  1472. uses. The algorithm performs two traversals over the AST of the procedure or global
  1473. section of code that uses a view variable. No fixpoint iterations are performed, the
  1474. complexity of the analysis is O(N) where N is the number of nodes of the AST.
  1475. The first pass over the AST computes the lifetime of each local variable based on
  1476. a notion of an "abstract time", in the implementation it's a simple integer that is
  1477. incremented for every visited node.
  1478. In the second pass information about the underlying object "graphs" is computed.
  1479. Let `v` be a parameter or a local variable. Let `G(v)` be the graph
  1480. that `v` belongs to. A graph is defined by the set of variables that belong
  1481. to the graph. Initially for all `v`: `G(v) = {v}`. Every variable can only
  1482. be part of a single graph.
  1483. Assignments like `a = b` "connect" two variables, both variables end up in the
  1484. same graph `{a, b} = G(a) = G(b)`. Unfortunately, the pattern to look for is
  1485. much more complex than that and can involve multiple assignment targets
  1486. and sources::
  1487. f(x, y) = g(a, b)
  1488. connects `x` and `y` to `a` and `b`: `G(x) = G(y) = G(a) = G(b) = {x, y, a, b}`.
  1489. A type based alias analysis rules out some of these combinations, for example
  1490. a `string` value cannot possibly be connected to a `seq[int]`.
  1491. A pattern like `v[] = value` or `v.field = value` marks `G(v)` as mutated.
  1492. After the second pass a set of disjoint graphs was computed.
  1493. For strict functions it is then enforced that there is no graph that is both mutated
  1494. and has an element that is an immutable parameter (that is a parameter that is not
  1495. of type `var T`).
  1496. For borrow checking a different set of checks is performed. Let `v` be the view
  1497. and `b` the location that is borrowed from.
  1498. - The lifetime of `v` must not exceed `b`'s lifetime. Note: The lifetime of
  1499. a parameter is the complete proc body.
  1500. - If `v` is a mutable view and `v` is used to actually mutate the
  1501. borrowed location, then `b` has to be a mutable location.
  1502. Note: If it is not actually used for mutation, borrowing a mutable view from an
  1503. immutable location is allowed! This allows for many important idioms and will be
  1504. justified in an upcoming RFC.
  1505. - During `v`'s lifetime, `G(b)` can only be modified by `v` (and only if
  1506. `v` is a mutable view).
  1507. - If `v` is `result` then `b` has to be a location derived from the first
  1508. formal parameter or from a constant location.
  1509. - A view cannot be used for a read or a write access before it was assigned to.