manual_experimental.rst 52 KB

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