manual_experimental.rst 54 KB

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