system.nim 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## The compiler depends on the System module to work properly and the System
  10. ## module depends on the compiler. Most of the routines listed here use
  11. ## special compiler magic.
  12. ##
  13. ## Each module implicitly imports the System module; it must not be listed
  14. ## explicitly. Because of this there cannot be a user-defined module named
  15. ## ``system``.
  16. ##
  17. ## System module
  18. ## =============
  19. ##
  20. ## .. include:: ./system_overview.rst
  21. type
  22. float* {.magic: Float.} ## Default floating point type.
  23. float32* {.magic: Float32.} ## 32 bit floating point type.
  24. float64* {.magic: Float.} ## 64 bit floating point type.
  25. # 'float64' is now an alias to 'float'; this solves many problems
  26. type
  27. char* {.magic: Char.} ## Built-in 8 bit character type (unsigned).
  28. string* {.magic: String.} ## Built-in string type.
  29. cstring* {.magic: Cstring.} ## Built-in cstring (*compatible string*) type.
  30. pointer* {.magic: Pointer.} ## Built-in pointer type, use the ``addr``
  31. ## operator to get a pointer to a variable.
  32. typedesc* {.magic: TypeDesc.} ## Meta type to denote a type description.
  33. type
  34. `ptr`*[T] {.magic: Pointer.} ## Built-in generic untraced pointer type.
  35. `ref`*[T] {.magic: Pointer.} ## Built-in generic traced pointer type.
  36. `nil` {.magic: "Nil".}
  37. void* {.magic: "VoidType".} ## Meta type to denote the absence of any type.
  38. auto* {.magic: Expr.} ## Meta type for automatic type determination.
  39. any* = distinct auto ## Meta type for any supported type.
  40. untyped* {.magic: Expr.} ## Meta type to denote an expression that
  41. ## is not resolved (for templates).
  42. typed* {.magic: Stmt.} ## Meta type to denote an expression that
  43. ## is resolved (for templates).
  44. include "system/basic_types"
  45. {.push warning[GcMem]: off, warning[Uninit]: off.}
  46. {.push hints: off.}
  47. proc `or`*(a, b: typedesc): typedesc {.magic: "TypeTrait", noSideEffect.}
  48. ## Constructs an `or` meta class.
  49. proc `and`*(a, b: typedesc): typedesc {.magic: "TypeTrait", noSideEffect.}
  50. ## Constructs an `and` meta class.
  51. proc `not`*(a: typedesc): typedesc {.magic: "TypeTrait", noSideEffect.}
  52. ## Constructs an `not` meta class.
  53. type
  54. SomeFloat* = float|float32|float64
  55. ## Type class matching all floating point number types.
  56. SomeNumber* = SomeInteger|SomeFloat
  57. ## Type class matching all number types.
  58. proc defined*(x: untyped): bool {.magic: "Defined", noSideEffect, compileTime.}
  59. ## Special compile-time procedure that checks whether `x` is
  60. ## defined.
  61. ##
  62. ## `x` is an external symbol introduced through the compiler's
  63. ## `-d:x switch <nimc.html#compiler-usage-compile-time-symbols>`_ to enable
  64. ## build time conditionals:
  65. ##
  66. ## .. code-block:: Nim
  67. ## when not defined(release):
  68. ## # Do here programmer friendly expensive sanity checks.
  69. ## # Put here the normal code
  70. when defined(nimHashOrdinalFixed):
  71. type
  72. Ordinal*[T] {.magic: Ordinal.} ## Generic ordinal type. Includes integer,
  73. ## bool, character, and enumeration types
  74. ## as well as their subtypes. See also
  75. ## `SomeOrdinal`.
  76. else:
  77. # bootstrap <= 0.20.0
  78. type
  79. OrdinalImpl[T] {.magic: Ordinal.}
  80. Ordinal* = OrdinalImpl | uint | uint64
  81. when defined(nimHasRunnableExamples):
  82. proc runnableExamples*(body: untyped) {.magic: "RunnableExamples".}
  83. ## A section you should use to mark `runnable example`:idx: code with.
  84. ##
  85. ## - In normal debug and release builds code within
  86. ## a ``runnableExamples`` section is ignored.
  87. ## - The documentation generator is aware of these examples and considers them
  88. ## part of the ``##`` doc comment. As the last step of documentation
  89. ## generation each runnableExample is put in its own file ``$file_examples$i.nim``,
  90. ## compiled and tested. The collected examples are
  91. ## put into their own module to ensure the examples do not refer to
  92. ## non-exported symbols.
  93. ##
  94. ## Usage:
  95. ##
  96. ## .. code-block:: Nim
  97. ## proc double*(x: int): int =
  98. ## ## This proc doubles a number.
  99. ## runnableExamples:
  100. ## ## at module scope
  101. ## assert double(5) == 10
  102. ## block: ## at block scope
  103. ## defer: echo "done"
  104. ##
  105. ## result = 2 * x
  106. else:
  107. template runnableExamples*(body: untyped) =
  108. discard
  109. proc declared*(x: untyped): bool {.magic: "Defined", noSideEffect, compileTime.}
  110. ## Special compile-time procedure that checks whether `x` is
  111. ## declared. `x` has to be an identifier or a qualified identifier.
  112. ##
  113. ## See also:
  114. ## * `declaredInScope <#declaredInScope,untyped>`_
  115. ##
  116. ## This can be used to check whether a library provides a certain
  117. ## feature or not:
  118. ##
  119. ## .. code-block:: Nim
  120. ## when not declared(strutils.toUpper):
  121. ## # provide our own toUpper proc here, because strutils is
  122. ## # missing it.
  123. proc declaredInScope*(x: untyped): bool {.
  124. magic: "DefinedInScope", noSideEffect, compileTime.}
  125. ## Special compile-time procedure that checks whether `x` is
  126. ## declared in the current scope. `x` has to be an identifier.
  127. proc `addr`*[T](x: var T): ptr T {.magic: "Addr", noSideEffect.} =
  128. ## Builtin `addr` operator for taking the address of a memory location.
  129. ## Cannot be overloaded.
  130. ##
  131. ## See also:
  132. ## * `unsafeAddr <#unsafeAddr,T>`_
  133. ##
  134. ## .. code-block:: Nim
  135. ## var
  136. ## buf: seq[char] = @['a','b','c']
  137. ## p = buf[1].addr
  138. ## echo p.repr # ref 0x7faa35c40059 --> 'b'
  139. ## echo p[] # b
  140. discard
  141. proc unsafeAddr*[T](x: T): ptr T {.magic: "Addr", noSideEffect.} =
  142. ## Builtin `addr` operator for taking the address of a memory
  143. ## location. This works even for ``let`` variables or parameters
  144. ## for better interop with C and so it is considered even more
  145. ## unsafe than the ordinary `addr <#addr,T>`_.
  146. ##
  147. ## **Note**: When you use it to write a wrapper for a C library, you should
  148. ## always check that the original library does never write to data behind the
  149. ## pointer that is returned from this procedure.
  150. ##
  151. ## Cannot be overloaded.
  152. discard
  153. when defined(nimNewTypedesc):
  154. type
  155. `static`*[T] {.magic: "Static".}
  156. ## Meta type representing all values that can be evaluated at compile-time.
  157. ##
  158. ## The type coercion ``static(x)`` can be used to force the compile-time
  159. ## evaluation of the given expression ``x``.
  160. `type`*[T] {.magic: "Type".}
  161. ## Meta type representing the type of all type values.
  162. ##
  163. ## The coercion ``type(x)`` can be used to obtain the type of the given
  164. ## expression ``x``.
  165. else:
  166. proc `type`*(x: untyped): typedesc {.magic: "TypeOf", noSideEffect, compileTime.} =
  167. ## Builtin `type` operator for accessing the type of an expression.
  168. ## Cannot be overloaded.
  169. discard
  170. when defined(nimHasTypeof):
  171. type
  172. TypeOfMode* = enum ## Possible modes of `typeof`.
  173. typeOfProc, ## Prefer the interpretation that means `x` is a proc call.
  174. typeOfIter ## Prefer the interpretation that means `x` is an iterator call.
  175. proc typeof*(x: untyped; mode = typeOfIter): typedesc {.
  176. magic: "TypeOf", noSideEffect, compileTime.} =
  177. ## Builtin `typeof` operation for accessing the type of an expression.
  178. ## Since version 0.20.0.
  179. discard
  180. const ThisIsSystem = true
  181. proc internalNew*[T](a: var ref T) {.magic: "New", noSideEffect.}
  182. ## Leaked implementation detail. Do not use.
  183. when true:
  184. proc new*[T](a: var ref T, finalizer: proc (x: ref T) {.nimcall.}) {.
  185. magic: "NewFinalize", noSideEffect.}
  186. ## Creates a new object of type ``T`` and returns a safe (traced)
  187. ## reference to it in ``a``.
  188. ##
  189. ## When the garbage collector frees the object, `finalizer` is called.
  190. ## The `finalizer` may not keep a reference to the
  191. ## object pointed to by `x`. The `finalizer` cannot prevent the GC from
  192. ## freeing the object.
  193. ##
  194. ## **Note**: The `finalizer` refers to the type `T`, not to the object!
  195. ## This means that for each object of type `T` the finalizer will be called!
  196. proc wasMoved*[T](obj: var T) {.magic: "WasMoved", noSideEffect.} =
  197. ## Resets an object `obj` to its initial (binary zero) value to signify
  198. ## it was "moved" and to signify its destructor should do nothing and
  199. ## ideally be optimized away.
  200. discard
  201. proc move*[T](x: var T): T {.magic: "Move", noSideEffect.} =
  202. result = x
  203. wasMoved(x)
  204. type
  205. range*[T]{.magic: "Range".} ## Generic type to construct range types.
  206. array*[I, T]{.magic: "Array".} ## Generic type to construct
  207. ## fixed-length arrays.
  208. openArray*[T]{.magic: "OpenArray".} ## Generic type to construct open arrays.
  209. ## Open arrays are implemented as a
  210. ## pointer to the array data and a
  211. ## length field.
  212. varargs*[T]{.magic: "Varargs".} ## Generic type to construct a varargs type.
  213. seq*[T]{.magic: "Seq".} ## Generic type to construct sequences.
  214. set*[T]{.magic: "Set".} ## Generic type to construct bit sets.
  215. when defined(nimUncheckedArrayTyp):
  216. type
  217. UncheckedArray*[T]{.magic: "UncheckedArray".}
  218. ## Array with no bounds checking.
  219. else:
  220. type
  221. UncheckedArray*[T]{.unchecked.} = array[0,T]
  222. ## Array with no bounds checking.
  223. type sink*[T]{.magic: "BuiltinType".}
  224. type lent*[T]{.magic: "BuiltinType".}
  225. proc high*[T: Ordinal|enum|range](x: T): T {.magic: "High", noSideEffect.}
  226. ## Returns the highest possible value of an ordinal value `x`.
  227. ##
  228. ## As a special semantic rule, `x` may also be a type identifier.
  229. ##
  230. ## See also:
  231. ## * `low(T) <#low,T>`_
  232. ##
  233. ## .. code-block:: Nim
  234. ## high(2) # => 9223372036854775807
  235. proc high*[T: Ordinal|enum|range](x: typedesc[T]): T {.magic: "High", noSideEffect.}
  236. ## Returns the highest possible value of an ordinal or enum type.
  237. ##
  238. ## ``high(int)`` is Nim's way of writing `INT_MAX`:idx: or `MAX_INT`:idx:.
  239. ##
  240. ## See also:
  241. ## * `low(typedesc) <#low,typedesc[T]>`_
  242. ##
  243. ## .. code-block:: Nim
  244. ## high(int) # => 9223372036854775807
  245. proc high*[T](x: openArray[T]): int {.magic: "High", noSideEffect.}
  246. ## Returns the highest possible index of a sequence `x`.
  247. ##
  248. ## See also:
  249. ## * `low(openArray) <#low,openArray[T]>`_
  250. ##
  251. ## .. code-block:: Nim
  252. ## var s = @[1, 2, 3, 4, 5, 6, 7]
  253. ## high(s) # => 6
  254. ## for i in low(s)..high(s):
  255. ## echo s[i]
  256. proc high*[I, T](x: array[I, T]): I {.magic: "High", noSideEffect.}
  257. ## Returns the highest possible index of an array `x`.
  258. ##
  259. ## See also:
  260. ## * `low(array) <#low,array[I,T]>`_
  261. ##
  262. ## .. code-block:: Nim
  263. ## var arr = [1, 2, 3, 4, 5, 6, 7]
  264. ## high(arr) # => 6
  265. ## for i in low(arr)..high(arr):
  266. ## echo arr[i]
  267. proc high*[I, T](x: typedesc[array[I, T]]): I {.magic: "High", noSideEffect.}
  268. ## Returns the highest possible index of an array type.
  269. ##
  270. ## See also:
  271. ## * `low(typedesc[array]) <#low,typedesc[array[I,T]]>`_
  272. ##
  273. ## .. code-block:: Nim
  274. ## high(array[7, int]) # => 6
  275. proc high*(x: cstring): int {.magic: "High", noSideEffect.}
  276. ## Returns the highest possible index of a compatible string `x`.
  277. ## This is sometimes an O(n) operation.
  278. ##
  279. ## See also:
  280. ## * `low(cstring) <#low,cstring>`_
  281. proc high*(x: string): int {.magic: "High", noSideEffect.}
  282. ## Returns the highest possible index of a string `x`.
  283. ##
  284. ## See also:
  285. ## * `low(string) <#low,string>`_
  286. ##
  287. ## .. code-block:: Nim
  288. ## var str = "Hello world!"
  289. ## high(str) # => 11
  290. proc low*[T: Ordinal|enum|range](x: T): T {.magic: "Low", noSideEffect.}
  291. ## Returns the lowest possible value of an ordinal value `x`. As a special
  292. ## semantic rule, `x` may also be a type identifier.
  293. ##
  294. ## See also:
  295. ## * `high(T) <#high,T>`_
  296. ##
  297. ## .. code-block:: Nim
  298. ## low(2) # => -9223372036854775808
  299. proc low*[T: Ordinal|enum|range](x: typedesc[T]): T {.magic: "Low", noSideEffect.}
  300. ## Returns the lowest possible value of an ordinal or enum type.
  301. ##
  302. ## ``low(int)`` is Nim's way of writing `INT_MIN`:idx: or `MIN_INT`:idx:.
  303. ##
  304. ## See also:
  305. ## * `high(typedesc) <#high,typedesc[T]>`_
  306. ##
  307. ## .. code-block:: Nim
  308. ## low(int) # => -9223372036854775808
  309. proc low*[T](x: openArray[T]): int {.magic: "Low", noSideEffect.}
  310. ## Returns the lowest possible index of a sequence `x`.
  311. ##
  312. ## See also:
  313. ## * `high(openArray) <#high,openArray[T]>`_
  314. ##
  315. ## .. code-block:: Nim
  316. ## var s = @[1, 2, 3, 4, 5, 6, 7]
  317. ## low(s) # => 0
  318. ## for i in low(s)..high(s):
  319. ## echo s[i]
  320. proc low*[I, T](x: array[I, T]): I {.magic: "Low", noSideEffect.}
  321. ## Returns the lowest possible index of an array `x`.
  322. ##
  323. ## See also:
  324. ## * `high(array) <#high,array[I,T]>`_
  325. ##
  326. ## .. code-block:: Nim
  327. ## var arr = [1, 2, 3, 4, 5, 6, 7]
  328. ## low(arr) # => 0
  329. ## for i in low(arr)..high(arr):
  330. ## echo arr[i]
  331. proc low*[I, T](x: typedesc[array[I, T]]): I {.magic: "Low", noSideEffect.}
  332. ## Returns the lowest possible index of an array type.
  333. ##
  334. ## See also:
  335. ## * `high(typedesc[array]) <#high,typedesc[array[I,T]]>`_
  336. ##
  337. ## .. code-block:: Nim
  338. ## low(array[7, int]) # => 0
  339. proc low*(x: cstring): int {.magic: "Low", noSideEffect.}
  340. ## Returns the lowest possible index of a compatible string `x`.
  341. ##
  342. ## See also:
  343. ## * `high(cstring) <#high,cstring>`_
  344. proc low*(x: string): int {.magic: "Low", noSideEffect.}
  345. ## Returns the lowest possible index of a string `x`.
  346. ##
  347. ## See also:
  348. ## * `high(string) <#high,string>`_
  349. ##
  350. ## .. code-block:: Nim
  351. ## var str = "Hello world!"
  352. ## low(str) # => 0
  353. proc shallowCopy*[T](x: var T, y: T) {.noSideEffect, magic: "ShallowCopy".}
  354. ## Use this instead of `=` for a `shallow copy`:idx:.
  355. ##
  356. ## The shallow copy only changes the semantics for sequences and strings
  357. ## (and types which contain those).
  358. ##
  359. ## Be careful with the changed semantics though!
  360. ## There is a reason why the default assignment does a deep copy of sequences
  361. ## and strings.
  362. when defined(nimArrIdx):
  363. # :array|openArray|string|seq|cstring|tuple
  364. proc `[]`*[I: Ordinal;T](a: T; i: I): T {.
  365. noSideEffect, magic: "ArrGet".}
  366. proc `[]=`*[I: Ordinal;T,S](a: T; i: I;
  367. x: sink S) {.noSideEffect, magic: "ArrPut".}
  368. proc `=`*[T](dest: var T; src: T) {.noSideEffect, magic: "Asgn".}
  369. proc arrGet[I: Ordinal;T](a: T; i: I): T {.
  370. noSideEffect, magic: "ArrGet".}
  371. proc arrPut[I: Ordinal;T,S](a: T; i: I;
  372. x: S) {.noSideEffect, magic: "ArrPut".}
  373. proc `=destroy`*[T](x: var T) {.inline, magic: "Destroy".} =
  374. ## Generic `destructor`:idx: implementation that can be overridden.
  375. discard
  376. proc `=sink`*[T](x: var T; y: T) {.inline, magic: "Asgn".} =
  377. ## Generic `sink`:idx: implementation that can be overridden.
  378. shallowCopy(x, y)
  379. type
  380. HSlice*[T, U] = object ## "Heterogeneous" slice type.
  381. a*: T ## The lower bound (inclusive).
  382. b*: U ## The upper bound (inclusive).
  383. Slice*[T] = HSlice[T, T] ## An alias for ``HSlice[T, T]``.
  384. proc `..`*[T, U](a: sink T, b: sink U): HSlice[T, U] {.noSideEffect, inline, magic: "DotDot".} =
  385. ## Binary `slice`:idx: operator that constructs an interval ``[a, b]``, both `a`
  386. ## and `b` are inclusive.
  387. ##
  388. ## Slices can also be used in the set constructor and in ordinal case
  389. ## statements, but then they are special-cased by the compiler.
  390. ##
  391. ## .. code-block:: Nim
  392. ## let a = [10, 20, 30, 40, 50]
  393. ## echo a[2 .. 3] # @[30, 40]
  394. result = HSlice[T, U](a: a, b: b)
  395. proc `..`*[T](b: sink T): HSlice[int, T] {.noSideEffect, inline, magic: "DotDot".} =
  396. ## Unary `slice`:idx: operator that constructs an interval ``[default(int), b]``.
  397. ##
  398. ## .. code-block:: Nim
  399. ## let a = [10, 20, 30, 40, 50]
  400. ## echo a[.. 2] # @[10, 20, 30]
  401. result = HSlice[int, T](a: 0, b: b)
  402. when not defined(niminheritable):
  403. {.pragma: inheritable.}
  404. when not defined(nimunion):
  405. {.pragma: unchecked.}
  406. when not defined(nimHasHotCodeReloading):
  407. {.pragma: nonReloadable.}
  408. when defined(hotCodeReloading):
  409. {.pragma: hcrInline, inline.}
  410. else:
  411. {.pragma: hcrInline.}
  412. {.push profiler: off.}
  413. let nimvm* {.magic: "Nimvm", compileTime.}: bool = false
  414. ## May be used only in `when` expression.
  415. ## It is true in Nim VM context and false otherwise.
  416. {.pop.}
  417. include "system/arithmetics"
  418. include "system/comparisons"
  419. const
  420. appType* {.magic: "AppType"}: string = ""
  421. ## A string that describes the application type. Possible values:
  422. ## `"console"`, `"gui"`, `"lib"`.
  423. include "system/inclrtl"
  424. const NoFakeVars* = defined(nimscript) ## `true` if the backend doesn't support \
  425. ## "fake variables" like `var EBADF {.importc.}: cint`.
  426. const notJSnotNims = not defined(js) and not defined(nimscript)
  427. when not defined(js) and not defined(nimSeqsV2):
  428. type
  429. TGenericSeq {.compilerproc, pure, inheritable.} = object
  430. len, reserved: int
  431. when defined(gogc):
  432. elemSize: int
  433. PGenericSeq {.exportc.} = ptr TGenericSeq
  434. # len and space without counting the terminating zero:
  435. NimStringDesc {.compilerproc, final.} = object of TGenericSeq
  436. data: UncheckedArray[char]
  437. NimString = ptr NimStringDesc
  438. when notJSnotNims and not defined(nimSeqsV2):
  439. template space(s: PGenericSeq): int {.dirty.} =
  440. s.reserved and not (seqShallowFlag or strlitFlag)
  441. when notJSnotNims and not defined(nimV2):
  442. include "system/hti"
  443. type
  444. byte* = uint8 ## This is an alias for ``uint8``, that is an unsigned
  445. ## integer, 8 bits wide.
  446. Natural* = range[0..high(int)]
  447. ## is an `int` type ranging from zero to the maximum value
  448. ## of an `int`. This type is often useful for documentation and debugging.
  449. Positive* = range[1..high(int)]
  450. ## is an `int` type ranging from one to the maximum value
  451. ## of an `int`. This type is often useful for documentation and debugging.
  452. RootObj* {.compilerproc, inheritable.} =
  453. object ## The root of Nim's object hierarchy.
  454. ##
  455. ## Objects should inherit from `RootObj` or one of its descendants.
  456. ## However, objects that have no ancestor are also allowed.
  457. RootRef* = ref RootObj ## Reference to `RootObj`.
  458. include "system/exceptions"
  459. when defined(js) or defined(nimdoc):
  460. type
  461. JsRoot* = ref object of RootObj
  462. ## Root type of the JavaScript object hierarchy
  463. proc unsafeNew*[T](a: var ref T, size: Natural) {.magic: "New", noSideEffect.}
  464. ## Creates a new object of type ``T`` and returns a safe (traced)
  465. ## reference to it in ``a``.
  466. ##
  467. ## This is **unsafe** as it allocates an object of the passed ``size``.
  468. ## This should only be used for optimization purposes when you know
  469. ## what you're doing!
  470. ##
  471. ## See also:
  472. ## * `new <#new,ref.T,proc(ref.T)>`_
  473. proc sizeof*[T](x: T): int {.magic: "SizeOf", noSideEffect.}
  474. ## Returns the size of ``x`` in bytes.
  475. ##
  476. ## Since this is a low-level proc,
  477. ## its usage is discouraged - using `new <#new,ref.T,proc(ref.T)>`_ for
  478. ## the most cases suffices that one never needs to know ``x``'s size.
  479. ##
  480. ## As a special semantic rule, ``x`` may also be a type identifier
  481. ## (``sizeof(int)`` is valid).
  482. ##
  483. ## Limitations: If used for types that are imported from C or C++,
  484. ## sizeof should fallback to the ``sizeof`` in the C compiler. The
  485. ## result isn't available for the Nim compiler and therefore can't
  486. ## be used inside of macros.
  487. ##
  488. ## .. code-block:: Nim
  489. ## sizeof('A') # => 1
  490. ## sizeof(2) # => 8
  491. when defined(nimHasalignOf):
  492. proc alignof*[T](x: T): int {.magic: "AlignOf", noSideEffect.}
  493. proc alignof*(x: typedesc): int {.magic: "AlignOf", noSideEffect.}
  494. proc offsetOfDotExpr(typeAccess: typed): int {.magic: "OffsetOf", noSideEffect, compileTime.}
  495. template offsetOf*[T](t: typedesc[T]; member: untyped): int =
  496. var tmp {.noinit.}: ptr T
  497. offsetOfDotExpr(tmp[].member)
  498. template offsetOf*[T](value: T; member: untyped): int =
  499. offsetOfDotExpr(value.member)
  500. #proc offsetOf*(memberaccess: typed): int {.magic: "OffsetOf", noSideEffect.}
  501. when defined(nimtypedescfixed):
  502. proc sizeof*(x: typedesc): int {.magic: "SizeOf", noSideEffect.}
  503. proc newSeq*[T](s: var seq[T], len: Natural) {.magic: "NewSeq", noSideEffect.}
  504. ## Creates a new sequence of type ``seq[T]`` with length ``len``.
  505. ##
  506. ## This is equivalent to ``s = @[]; setlen(s, len)``, but more
  507. ## efficient since no reallocation is needed.
  508. ##
  509. ## Note that the sequence will be filled with zeroed entries.
  510. ## After the creation of the sequence you should assign entries to
  511. ## the sequence instead of adding them. Example:
  512. ##
  513. ## .. code-block:: Nim
  514. ## var inputStrings : seq[string]
  515. ## newSeq(inputStrings, 3)
  516. ## assert len(inputStrings) == 3
  517. ## inputStrings[0] = "The fourth"
  518. ## inputStrings[1] = "assignment"
  519. ## inputStrings[2] = "would crash"
  520. ## #inputStrings[3] = "out of bounds"
  521. proc newSeq*[T](len = 0.Natural): seq[T] =
  522. ## Creates a new sequence of type ``seq[T]`` with length ``len``.
  523. ##
  524. ## Note that the sequence will be filled with zeroed entries.
  525. ## After the creation of the sequence you should assign entries to
  526. ## the sequence instead of adding them.
  527. ##
  528. ## See also:
  529. ## * `newSeqOfCap <#newSeqOfCap,Natural>`_
  530. ## * `newSeqUninitialized <#newSeqUninitialized,Natural>`_
  531. ##
  532. ## .. code-block:: Nim
  533. ## var inputStrings = newSeq[string](3)
  534. ## assert len(inputStrings) == 3
  535. ## inputStrings[0] = "The fourth"
  536. ## inputStrings[1] = "assignment"
  537. ## inputStrings[2] = "would crash"
  538. ## #inputStrings[3] = "out of bounds"
  539. newSeq(result, len)
  540. proc newSeqOfCap*[T](cap: Natural): seq[T] {.
  541. magic: "NewSeqOfCap", noSideEffect.} =
  542. ## Creates a new sequence of type ``seq[T]`` with length zero and capacity
  543. ## ``cap``.
  544. ##
  545. ## .. code-block:: Nim
  546. ## var x = newSeqOfCap[int](5)
  547. ## assert len(x) == 0
  548. ## x.add(10)
  549. ## assert len(x) == 1
  550. discard
  551. when not defined(js):
  552. proc newSeqUninitialized*[T: SomeNumber](len: Natural): seq[T] =
  553. ## Creates a new sequence of type ``seq[T]`` with length ``len``.
  554. ##
  555. ## Only available for numbers types. Note that the sequence will be
  556. ## uninitialized. After the creation of the sequence you should assign
  557. ## entries to the sequence instead of adding them.
  558. ##
  559. ## .. code-block:: Nim
  560. ## var x = newSeqUninitialized[int](3)
  561. ## assert len(x) == 3
  562. ## x[0] = 10
  563. result = newSeqOfCap[T](len)
  564. when defined(nimSeqsV2):
  565. cast[ptr int](addr result)[] = len
  566. else:
  567. var s = cast[PGenericSeq](result)
  568. s.len = len
  569. proc len*[TOpenArray: openArray|varargs](x: TOpenArray): int {.
  570. magic: "LengthOpenArray", noSideEffect.}
  571. ## Returns the length of an openArray.
  572. ##
  573. ## .. code-block:: Nim
  574. ## var s = [1, 1, 1, 1, 1]
  575. ## echo len(s) # => 5
  576. proc len*(x: string): int {.magic: "LengthStr", noSideEffect.}
  577. ## Returns the length of a string.
  578. ##
  579. ## .. code-block:: Nim
  580. ## var str = "Hello world!"
  581. ## echo len(str) # => 12
  582. proc len*(x: cstring): int {.magic: "LengthStr", noSideEffect.}
  583. ## Returns the length of a compatible string. This is sometimes
  584. ## an O(n) operation.
  585. ##
  586. ## .. code-block:: Nim
  587. ## var str: cstring = "Hello world!"
  588. ## len(str) # => 12
  589. proc len*(x: (type array)|array): int {.magic: "LengthArray", noSideEffect.}
  590. ## Returns the length of an array or an array type.
  591. ## This is roughly the same as ``high(T)-low(T)+1``.
  592. ##
  593. ## .. code-block:: Nim
  594. ## var arr = [1, 1, 1, 1, 1]
  595. ## echo len(arr) # => 5
  596. ## echo len(array[3..8, int]) # => 6
  597. proc len*[T](x: seq[T]): int {.magic: "LengthSeq", noSideEffect.}
  598. ## Returns the length of a sequence.
  599. ##
  600. ## .. code-block:: Nim
  601. ## var s = @[1, 1, 1, 1, 1]
  602. ## echo len(s) # => 5
  603. proc ord*[T: Ordinal|enum](x: T): int {.magic: "Ord", noSideEffect.}
  604. ## Returns the internal `int` value of an ordinal value ``x``.
  605. ##
  606. ## .. code-block:: Nim
  607. ## echo ord('A') # => 65
  608. ## echo ord('a') # => 97
  609. proc chr*(u: range[0..255]): char {.magic: "Chr", noSideEffect.}
  610. ## Converts an `int` in the range `0..255` to a character.
  611. ##
  612. ## .. code-block:: Nim
  613. ## echo chr(65) # => A
  614. ## echo chr(97) # => a
  615. # floating point operations:
  616. proc `+`*(x: float32): float32 {.magic: "UnaryPlusF64", noSideEffect.}
  617. proc `-`*(x: float32): float32 {.magic: "UnaryMinusF64", noSideEffect.}
  618. proc `+`*(x, y: float32): float32 {.magic: "AddF64", noSideEffect.}
  619. proc `-`*(x, y: float32): float32 {.magic: "SubF64", noSideEffect.}
  620. proc `*`*(x, y: float32): float32 {.magic: "MulF64", noSideEffect.}
  621. proc `/`*(x, y: float32): float32 {.magic: "DivF64", noSideEffect.}
  622. proc `+`*(x: float): float {.magic: "UnaryPlusF64", noSideEffect.}
  623. proc `-`*(x: float): float {.magic: "UnaryMinusF64", noSideEffect.}
  624. proc `+`*(x, y: float): float {.magic: "AddF64", noSideEffect.}
  625. proc `-`*(x, y: float): float {.magic: "SubF64", noSideEffect.}
  626. proc `*`*(x, y: float): float {.magic: "MulF64", noSideEffect.}
  627. proc `/`*(x, y: float): float {.magic: "DivF64", noSideEffect.}
  628. proc `==`*(x, y: float32): bool {.magic: "EqF64", noSideEffect.}
  629. proc `<=`*(x, y: float32): bool {.magic: "LeF64", noSideEffect.}
  630. proc `<` *(x, y: float32): bool {.magic: "LtF64", noSideEffect.}
  631. proc `==`*(x, y: float): bool {.magic: "EqF64", noSideEffect.}
  632. proc `<=`*(x, y: float): bool {.magic: "LeF64", noSideEffect.}
  633. proc `<`*(x, y: float): bool {.magic: "LtF64", noSideEffect.}
  634. include "system/setops"
  635. proc contains*[U, V, W](s: HSlice[U, V], value: W): bool {.noSideEffect, inline.} =
  636. ## Checks if `value` is within the range of `s`; returns true if
  637. ## `value >= s.a and value <= s.b`
  638. ##
  639. ## .. code-block:: Nim
  640. ## assert((1..3).contains(1) == true)
  641. ## assert((1..3).contains(2) == true)
  642. ## assert((1..3).contains(4) == false)
  643. result = s.a <= value and value <= s.b
  644. template `in`*(x, y: untyped): untyped {.dirty.} = contains(y, x)
  645. ## Sugar for `contains`.
  646. ##
  647. ## .. code-block:: Nim
  648. ## assert(1 in (1..3) == true)
  649. ## assert(5 in (1..3) == false)
  650. template `notin`*(x, y: untyped): untyped {.dirty.} = not contains(y, x)
  651. ## Sugar for `not contains`.
  652. ##
  653. ## .. code-block:: Nim
  654. ## assert(1 notin (1..3) == false)
  655. ## assert(5 notin (1..3) == true)
  656. proc `is`*[T, S](x: T, y: S): bool {.magic: "Is", noSideEffect.}
  657. ## Checks if `T` is of the same type as `S`.
  658. ##
  659. ## For a negated version, use `isnot <#isnot.t,untyped,untyped>`_.
  660. ##
  661. ## .. code-block:: Nim
  662. ## assert 42 is int
  663. ## assert @[1, 2] is seq
  664. ##
  665. ## proc test[T](a: T): int =
  666. ## when (T is int):
  667. ## return a
  668. ## else:
  669. ## return 0
  670. ##
  671. ## assert(test[int](3) == 3)
  672. ## assert(test[string]("xyz") == 0)
  673. template `isnot`*(x, y: untyped): untyped = not (x is y)
  674. ## Negated version of `is <#is,T,S>`_. Equivalent to ``not(x is y)``.
  675. ##
  676. ## .. code-block:: Nim
  677. ## assert 42 isnot float
  678. ## assert @[1, 2] isnot enum
  679. when (defined(nimOwnedEnabled) and not defined(nimscript)) or defined(nimFixedOwned):
  680. type owned*[T]{.magic: "BuiltinType".} ## type constructor to mark a ref/ptr or a closure as `owned`.
  681. else:
  682. template owned*(t: typedesc): typedesc = t
  683. when defined(nimOwnedEnabled) and not defined(nimscript):
  684. proc new*[T](a: var owned(ref T)) {.magic: "New", noSideEffect.}
  685. ## Creates a new object of type ``T`` and returns a safe (traced)
  686. ## reference to it in ``a``.
  687. proc new*(t: typedesc): auto =
  688. ## Creates a new object of type ``T`` and returns a safe (traced)
  689. ## reference to it as result value.
  690. ##
  691. ## When ``T`` is a ref type then the resulting type will be ``T``,
  692. ## otherwise it will be ``ref T``.
  693. when (t is ref):
  694. var r: owned t
  695. else:
  696. var r: owned(ref t)
  697. new(r)
  698. return r
  699. proc unown*[T](x: T): T {.magic: "Unown", noSideEffect.}
  700. ## Use the expression ``x`` ignoring its ownership attribute.
  701. # This is only required to make 0.20 compile with the 0.19 line.
  702. template `<//>`*(t: untyped): untyped = owned(t)
  703. else:
  704. template unown*(x: typed): untyped = x
  705. proc new*[T](a: var ref T) {.magic: "New", noSideEffect.}
  706. ## Creates a new object of type ``T`` and returns a safe (traced)
  707. ## reference to it in ``a``.
  708. proc new*(t: typedesc): auto =
  709. ## Creates a new object of type ``T`` and returns a safe (traced)
  710. ## reference to it as result value.
  711. ##
  712. ## When ``T`` is a ref type then the resulting type will be ``T``,
  713. ## otherwise it will be ``ref T``.
  714. when (t is ref):
  715. var r: t
  716. else:
  717. var r: ref t
  718. new(r)
  719. return r
  720. # This is only required to make 0.20 compile with the 0.19 line.
  721. template `<//>`*(t: untyped): untyped = t
  722. template disarm*(x: typed) =
  723. ## Useful for ``disarming`` dangling pointers explicitly for the
  724. ## --newruntime. Regardless of whether --newruntime is used or not
  725. ## this sets the pointer or callback ``x`` to ``nil``. This is an
  726. ## experimental API!
  727. x = nil
  728. proc `of`*[T, S](x: typedesc[T], y: typedesc[S]): bool {.magic: "Of", noSideEffect.}
  729. proc `of`*[T, S](x: T, y: typedesc[S]): bool {.magic: "Of", noSideEffect.}
  730. proc `of`*[T, S](x: T, y: S): bool {.magic: "Of", noSideEffect.}
  731. ## Checks if `x` has a type of `y`.
  732. ##
  733. ## .. code-block:: Nim
  734. ## assert(FloatingPointError of Exception)
  735. ## assert(DivByZeroError of Exception)
  736. proc cmp*[T](x, y: T): int {.procvar.} =
  737. ## Generic compare proc.
  738. ##
  739. ## Returns:
  740. ## * a value less than zero, if `x < y`
  741. ## * a value greater than zero, if `x > y`
  742. ## * zero, if `x == y`
  743. ##
  744. ## This is useful for writing generic algorithms without performance loss.
  745. ## This generic implementation uses the `==` and `<` operators.
  746. ##
  747. ## .. code-block:: Nim
  748. ## import algorithm
  749. ## echo sorted(@[4, 2, 6, 5, 8, 7], cmp[int])
  750. if x == y: return 0
  751. if x < y: return -1
  752. return 1
  753. proc cmp*(x, y: string): int {.noSideEffect, procvar.}
  754. ## Compare proc for strings. More efficient than the generic version.
  755. ##
  756. ## **Note**: The precise result values depend on the used C runtime library and
  757. ## can differ between operating systems!
  758. when defined(nimHasDefault):
  759. proc `@`* [IDX, T](a: sink array[IDX, T]): seq[T] {.
  760. magic: "ArrToSeq", noSideEffect.}
  761. ## Turns an array into a sequence.
  762. ##
  763. ## This most often useful for constructing
  764. ## sequences with the array constructor: ``@[1, 2, 3]`` has the type
  765. ## ``seq[int]``, while ``[1, 2, 3]`` has the type ``array[0..2, int]``.
  766. ##
  767. ## .. code-block:: Nim
  768. ## let
  769. ## a = [1, 3, 5]
  770. ## b = "foo"
  771. ##
  772. ## echo @a # => @[1, 3, 5]
  773. ## echo @b # => @['f', 'o', 'o']
  774. proc default*(T: typedesc): T {.magic: "Default", noSideEffect.}
  775. ## returns the default value of the type ``T``.
  776. proc reset*[T](obj: var T) {.noSideEffect.} =
  777. ## Resets an object `obj` to its default value.
  778. obj = default(typeof(obj))
  779. else:
  780. proc `@`* [IDX, T](a: array[IDX, T]): seq[T] {.
  781. magic: "ArrToSeq", noSideEffect.}
  782. when defined(nimV2):
  783. proc reset*[T](obj: var T) {.magic: "Destroy", noSideEffect.}
  784. else:
  785. proc reset*[T](obj: var T) {.magic: "Reset", noSideEffect.}
  786. proc setLen*[T](s: var seq[T], newlen: Natural) {.
  787. magic: "SetLengthSeq", noSideEffect.}
  788. ## Sets the length of seq `s` to `newlen`. ``T`` may be any sequence type.
  789. ##
  790. ## If the current length is greater than the new length,
  791. ## ``s`` will be truncated.
  792. ##
  793. ## .. code-block:: Nim
  794. ## var x = @[10, 20]
  795. ## x.setLen(5)
  796. ## x[4] = 50
  797. ## assert x == @[10, 20, 0, 0, 50]
  798. ## x.setLen(1)
  799. ## assert x == @[10]
  800. proc setLen*(s: var string, newlen: Natural) {.
  801. magic: "SetLengthStr", noSideEffect.}
  802. ## Sets the length of string `s` to `newlen`.
  803. ##
  804. ## If the current length is greater than the new length,
  805. ## ``s`` will be truncated.
  806. ##
  807. ## .. code-block:: Nim
  808. ## var myS = "Nim is great!!"
  809. ## myS.setLen(3) # myS <- "Nim"
  810. ## echo myS, " is fantastic!!"
  811. proc newString*(len: Natural): string {.
  812. magic: "NewString", importc: "mnewString", noSideEffect.}
  813. ## Returns a new string of length ``len`` but with uninitialized
  814. ## content. One needs to fill the string character after character
  815. ## with the index operator ``s[i]``.
  816. ##
  817. ## This procedure exists only for optimization purposes;
  818. ## the same effect can be achieved with the ``&`` operator or with ``add``.
  819. proc newStringOfCap*(cap: Natural): string {.
  820. magic: "NewStringOfCap", importc: "rawNewString", noSideEffect.}
  821. ## Returns a new string of length ``0`` but with capacity `cap`.
  822. ##
  823. ## This procedure exists only for optimization purposes; the same effect can
  824. ## be achieved with the ``&`` operator or with ``add``.
  825. proc `&`*(x: string, y: char): string {.
  826. magic: "ConStrStr", noSideEffect, merge.}
  827. ## Concatenates `x` with `y`.
  828. ##
  829. ## .. code-block:: Nim
  830. ## assert("ab" & 'c' == "abc")
  831. proc `&`*(x, y: char): string {.
  832. magic: "ConStrStr", noSideEffect, merge.}
  833. ## Concatenates characters `x` and `y` into a string.
  834. ##
  835. ## .. code-block:: Nim
  836. ## assert('a' & 'b' == "ab")
  837. proc `&`*(x, y: string): string {.
  838. magic: "ConStrStr", noSideEffect, merge.}
  839. ## Concatenates strings `x` and `y`.
  840. ##
  841. ## .. code-block:: Nim
  842. ## assert("ab" & "cd" == "abcd")
  843. proc `&`*(x: char, y: string): string {.
  844. magic: "ConStrStr", noSideEffect, merge.}
  845. ## Concatenates `x` with `y`.
  846. ##
  847. ## .. code-block:: Nim
  848. ## assert('a' & "bc" == "abc")
  849. # implementation note: These must all have the same magic value "ConStrStr" so
  850. # that the merge optimization works properly.
  851. proc add*(x: var string, y: char) {.magic: "AppendStrCh", noSideEffect.}
  852. ## Appends `y` to `x` in place.
  853. ##
  854. ## .. code-block:: Nim
  855. ## var tmp = ""
  856. ## tmp.add('a')
  857. ## tmp.add('b')
  858. ## assert(tmp == "ab")
  859. proc add*(x: var string, y: string) {.magic: "AppendStrStr", noSideEffect.}
  860. ## Concatenates `x` and `y` in place.
  861. ##
  862. ## .. code-block:: Nim
  863. ## var tmp = ""
  864. ## tmp.add("ab")
  865. ## tmp.add("cd")
  866. ## assert(tmp == "abcd")
  867. type
  868. Endianness* = enum ## Type describing the endianness of a processor.
  869. littleEndian, bigEndian
  870. const
  871. isMainModule* {.magic: "IsMainModule".}: bool = false
  872. ## True only when accessed in the main module. This works thanks to
  873. ## compiler magic. It is useful to embed testing code in a module.
  874. CompileDate* {.magic: "CompileDate"}: string = "0000-00-00"
  875. ## The date (in UTC) of compilation as a string of the form
  876. ## ``YYYY-MM-DD``. This works thanks to compiler magic.
  877. CompileTime* {.magic: "CompileTime"}: string = "00:00:00"
  878. ## The time (in UTC) of compilation as a string of the form
  879. ## ``HH:MM:SS``. This works thanks to compiler magic.
  880. cpuEndian* {.magic: "CpuEndian"}: Endianness = littleEndian
  881. ## The endianness of the target CPU. This is a valuable piece of
  882. ## information for low-level code only. This works thanks to compiler
  883. ## magic.
  884. hostOS* {.magic: "HostOS".}: string = ""
  885. ## A string that describes the host operating system.
  886. ##
  887. ## Possible values:
  888. ## `"windows"`, `"macosx"`, `"linux"`, `"netbsd"`, `"freebsd"`,
  889. ## `"openbsd"`, `"solaris"`, `"aix"`, `"haiku"`, `"standalone"`.
  890. hostCPU* {.magic: "HostCPU".}: string = ""
  891. ## A string that describes the host CPU.
  892. ##
  893. ## Possible values:
  894. ## `"i386"`, `"alpha"`, `"powerpc"`, `"powerpc64"`, `"powerpc64el"`,
  895. ## `"sparc"`, `"amd64"`, `"mips"`, `"mipsel"`, `"arm"`, `"arm64"`,
  896. ## `"mips64"`, `"mips64el"`, `"riscv64"`.
  897. seqShallowFlag = low(int)
  898. strlitFlag = 1 shl (sizeof(int)*8 - 2) # later versions of the codegen \
  899. # emit this flag
  900. # for string literals, it allows for some optimizations.
  901. proc compileOption*(option: string): bool {.
  902. magic: "CompileOption", noSideEffect.}
  903. ## Can be used to determine an `on|off` compile-time option. Example:
  904. ##
  905. ## .. code-block:: Nim
  906. ## when compileOption("floatchecks"):
  907. ## echo "compiled with floating point NaN and Inf checks"
  908. proc compileOption*(option, arg: string): bool {.
  909. magic: "CompileOptionArg", noSideEffect.}
  910. ## Can be used to determine an enum compile-time option. Example:
  911. ##
  912. ## .. code-block:: Nim
  913. ## when compileOption("opt", "size") and compileOption("gc", "boehm"):
  914. ## echo "compiled with optimization for size and uses Boehm's GC"
  915. const
  916. hasThreadSupport = compileOption("threads") and not defined(nimscript)
  917. hasSharedHeap = defined(boehmgc) or defined(gogc) # don't share heaps; every thread has its own
  918. taintMode = compileOption("taintmode")
  919. nimEnableCovariance* = defined(nimEnableCovariance) # or true
  920. when hasThreadSupport and defined(tcc) and not compileOption("tlsEmulation"):
  921. # tcc doesn't support TLS
  922. {.error: "``--tlsEmulation:on`` must be used when using threads with tcc backend".}
  923. when defined(boehmgc):
  924. when defined(windows):
  925. when sizeof(int) == 8:
  926. const boehmLib = "boehmgc64.dll"
  927. else:
  928. const boehmLib = "boehmgc.dll"
  929. elif defined(macosx):
  930. const boehmLib = "libgc.dylib"
  931. elif defined(openbsd):
  932. const boehmLib = "libgc.so.4.0"
  933. elif defined(freebsd):
  934. const boehmLib = "libgc-threaded.so.1"
  935. else:
  936. const boehmLib = "libgc.so.1"
  937. {.pragma: boehmGC, noconv, dynlib: boehmLib.}
  938. when taintMode:
  939. type TaintedString* = distinct string ## A distinct string type that
  940. ## is `tainted`:idx:, see `taint mode
  941. ## <manual_experimental.html#taint-mode>`_
  942. ## for details. It is an alias for
  943. ## ``string`` if the taint mode is not
  944. ## turned on.
  945. proc len*(s: TaintedString): int {.borrow.}
  946. else:
  947. type TaintedString* = string ## A distinct string type that
  948. ## is `tainted`:idx:, see `taint mode
  949. ## <manual_experimental.html#taint-mode>`_
  950. ## for details. It is an alias for
  951. ## ``string`` if the taint mode is not
  952. ## turned on.
  953. when defined(profiler) and not defined(nimscript):
  954. proc nimProfile() {.compilerproc, noinline.}
  955. when hasThreadSupport:
  956. {.pragma: rtlThreadVar, threadvar.}
  957. else:
  958. {.pragma: rtlThreadVar.}
  959. const
  960. QuitSuccess* = 0
  961. ## is the value that should be passed to `quit <#quit,int>`_ to indicate
  962. ## success.
  963. QuitFailure* = 1
  964. ## is the value that should be passed to `quit <#quit,int>`_ to indicate
  965. ## failure.
  966. when defined(js) and defined(nodejs) and not defined(nimscript):
  967. var programResult* {.importc: "process.exitCode".}: int
  968. programResult = 0
  969. elif hostOS != "standalone":
  970. var programResult* {.compilerproc, exportc: "nim_program_result".}: int
  971. ## deprecated, prefer ``quit``
  972. when defined(nimdoc):
  973. proc quit*(errorcode: int = QuitSuccess) {.magic: "Exit", noreturn.}
  974. ## Stops the program immediately with an exit code.
  975. ##
  976. ## Before stopping the program the "quit procedures" are called in the
  977. ## opposite order they were added with `addQuitProc <#addQuitProc,proc>`_.
  978. ## ``quit`` never returns and ignores any exception that may have been raised
  979. ## by the quit procedures. It does *not* call the garbage collector to free
  980. ## all the memory, unless a quit procedure calls `GC_fullCollect
  981. ## <#GC_fullCollect>`_.
  982. ##
  983. ## The proc ``quit(QuitSuccess)`` is called implicitly when your nim
  984. ## program finishes without incident for platforms where this is the
  985. ## expected behavior. A raised unhandled exception is
  986. ## equivalent to calling ``quit(QuitFailure)``.
  987. ##
  988. ## Note that this is a *runtime* call and using ``quit`` inside a macro won't
  989. ## have any compile time effect. If you need to stop the compiler inside a
  990. ## macro, use the `error <manual.html#pragmas-error-pragma>`_ or `fatal
  991. ## <manual.html#pragmas-fatal-pragma>`_ pragmas.
  992. elif defined(genode):
  993. include genode/env
  994. var systemEnv {.exportc: runtimeEnvSym.}: GenodeEnvPtr
  995. type GenodeEnv* = GenodeEnvPtr
  996. ## Opaque type representing Genode environment.
  997. proc quit*(env: GenodeEnv; errorcode: int) {.magic: "Exit", noreturn,
  998. importcpp: "#->parent().exit(@); Genode::sleep_forever()", header: "<base/sleep.h>".}
  999. proc quit*(errorcode: int = QuitSuccess) =
  1000. systemEnv.quit(errorcode)
  1001. elif defined(js) and defined(nodejs) and not defined(nimscript):
  1002. proc quit*(errorcode: int = QuitSuccess) {.magic: "Exit",
  1003. importc: "process.exit", noreturn.}
  1004. else:
  1005. proc quit*(errorcode: int = QuitSuccess) {.
  1006. magic: "Exit", importc: "exit", header: "<stdlib.h>", noreturn.}
  1007. template sysAssert(cond: bool, msg: string) =
  1008. when defined(useSysAssert):
  1009. if not cond:
  1010. cstderr.rawWrite "[SYSASSERT] "
  1011. cstderr.rawWrite msg
  1012. cstderr.rawWrite "\n"
  1013. quit 1
  1014. const hasAlloc = (hostOS != "standalone" or not defined(nogc)) and not defined(nimscript)
  1015. when notJSnotNims and hostOS != "standalone" and hostOS != "any":
  1016. include "system/cgprocs"
  1017. when notJSnotNims and hasAlloc and not defined(nimSeqsV2):
  1018. proc addChar(s: NimString, c: char): NimString {.compilerproc, benign.}
  1019. when defined(nimscript) or not defined(nimSeqsV2):
  1020. proc add*[T](x: var seq[T], y: T) {.magic: "AppendSeqElem", noSideEffect.}
  1021. ## Generic proc for adding a data item `y` to a container `x`.
  1022. ##
  1023. ## For containers that have an order, `add` means *append*. New generic
  1024. ## containers should also call their adding proc `add` for consistency.
  1025. ## Generic code becomes much easier to write if the Nim naming scheme is
  1026. ## respected.
  1027. proc add*[T](x: var seq[T], y: openArray[T]) {.noSideEffect.} =
  1028. ## Generic proc for adding a container `y` to a container `x`.
  1029. ##
  1030. ## For containers that have an order, `add` means *append*. New generic
  1031. ## containers should also call their adding proc `add` for consistency.
  1032. ## Generic code becomes much easier to write if the Nim naming scheme is
  1033. ## respected.
  1034. ##
  1035. ## See also:
  1036. ## * `& proc <#&,seq[T][T],seq[T][T]>`_
  1037. ##
  1038. ## .. code-block:: Nim
  1039. ## var s: seq[string] = @["test2","test2"]
  1040. ## s.add("test") # s <- @[test2, test2, test]
  1041. let xl = x.len
  1042. setLen(x, xl + y.len)
  1043. for i in 0..high(y): x[xl+i] = y[i]
  1044. when defined(nimSeqsV2):
  1045. template movingCopy(a, b) =
  1046. a = move(b)
  1047. else:
  1048. template movingCopy(a, b) =
  1049. shallowCopy(a, b)
  1050. proc del*[T](x: var seq[T], i: Natural) {.noSideEffect.} =
  1051. ## Deletes the item at index `i` by putting ``x[high(x)]`` into position `i`.
  1052. ##
  1053. ## This is an `O(1)` operation.
  1054. ##
  1055. ## See also:
  1056. ## * `delete <#delete,seq[T][T],Natural>`_ for preserving the order
  1057. ##
  1058. ## .. code-block:: Nim
  1059. ## var i = @[1, 2, 3, 4, 5]
  1060. ## i.del(2) # => @[1, 2, 5, 4]
  1061. let xl = x.len - 1
  1062. movingCopy(x[i], x[xl])
  1063. setLen(x, xl)
  1064. proc delete*[T](x: var seq[T], i: Natural) {.noSideEffect.} =
  1065. ## Deletes the item at index `i` by moving all ``x[i+1..]`` items by one position.
  1066. ##
  1067. ## This is an `O(n)` operation.
  1068. ##
  1069. ## See also:
  1070. ## * `del <#delete,seq[T][T],Natural>`_ for O(1) operation
  1071. ##
  1072. ## .. code-block:: Nim
  1073. ## var i = @[1, 2, 3, 4, 5]
  1074. ## i.delete(2) # => @[1, 2, 4, 5]
  1075. template defaultImpl =
  1076. let xl = x.len
  1077. for j in i.int..xl-2: movingCopy(x[j], x[j+1])
  1078. setLen(x, xl-1)
  1079. when nimvm:
  1080. defaultImpl()
  1081. else:
  1082. when defined(js):
  1083. {.emit: "`x`.splice(`i`, 1);".}
  1084. else:
  1085. defaultImpl()
  1086. proc insert*[T](x: var seq[T], item: sink T, i = 0.Natural) {.noSideEffect.} =
  1087. ## Inserts `item` into `x` at position `i`.
  1088. ##
  1089. ## .. code-block:: Nim
  1090. ## var i = @[1, 3, 5]
  1091. ## i.insert(99, 0) # i <- @[99, 1, 3, 5]
  1092. template defaultImpl =
  1093. let xl = x.len
  1094. setLen(x, xl+1)
  1095. var j = xl-1
  1096. while j >= i:
  1097. movingCopy(x[j+1], x[j])
  1098. dec(j)
  1099. when nimvm:
  1100. defaultImpl()
  1101. else:
  1102. when defined(js):
  1103. var it : T
  1104. {.emit: "`x` = `x` || []; `x`.splice(`i`, 0, `it`);".}
  1105. else:
  1106. defaultImpl()
  1107. x[i] = item
  1108. when not defined(nimV2):
  1109. proc repr*[T](x: T): string {.magic: "Repr", noSideEffect.}
  1110. ## Takes any Nim variable and returns its string representation.
  1111. ##
  1112. ## It works even for complex data graphs with cycles. This is a great
  1113. ## debugging tool.
  1114. ##
  1115. ## .. code-block:: Nim
  1116. ## var s: seq[string] = @["test2", "test2"]
  1117. ## var i = @[1, 2, 3, 4, 5]
  1118. ## echo repr(s) # => 0x1055eb050[0x1055ec050"test2", 0x1055ec078"test2"]
  1119. ## echo repr(i) # => 0x1055ed050[1, 2, 3, 4, 5]
  1120. type
  1121. ByteAddress* = int
  1122. ## is the signed integer type that should be used for converting
  1123. ## pointers to integer addresses for readability.
  1124. BiggestFloat* = float64
  1125. ## is an alias for the biggest floating point type the Nim
  1126. ## compiler supports. Currently this is ``float64``, but it is
  1127. ## platform-dependent in general.
  1128. when defined(js):
  1129. type BiggestUInt* = uint32
  1130. ## is an alias for the biggest unsigned integer type the Nim compiler
  1131. ## supports. Currently this is ``uint32`` for JS and ``uint64`` for other
  1132. ## targets.
  1133. else:
  1134. type BiggestUInt* = uint64
  1135. ## is an alias for the biggest unsigned integer type the Nim compiler
  1136. ## supports. Currently this is ``uint32`` for JS and ``uint64`` for other
  1137. ## targets.
  1138. when defined(windows):
  1139. type
  1140. clong* {.importc: "long", nodecl.} = int32
  1141. ## This is the same as the type ``long`` in *C*.
  1142. culong* {.importc: "unsigned long", nodecl.} = uint32
  1143. ## This is the same as the type ``unsigned long`` in *C*.
  1144. else:
  1145. type
  1146. clong* {.importc: "long", nodecl.} = int
  1147. ## This is the same as the type ``long`` in *C*.
  1148. culong* {.importc: "unsigned long", nodecl.} = uint
  1149. ## This is the same as the type ``unsigned long`` in *C*.
  1150. type # these work for most platforms:
  1151. cchar* {.importc: "char", nodecl.} = char
  1152. ## This is the same as the type ``char`` in *C*.
  1153. cschar* {.importc: "signed char", nodecl.} = int8
  1154. ## This is the same as the type ``signed char`` in *C*.
  1155. cshort* {.importc: "short", nodecl.} = int16
  1156. ## This is the same as the type ``short`` in *C*.
  1157. cint* {.importc: "int", nodecl.} = int32
  1158. ## This is the same as the type ``int`` in *C*.
  1159. csize* {.importc: "size_t", nodecl, deprecated: "use `csize_t` instead".} = int
  1160. ## This isn't the same as ``size_t`` in *C*. Don't use it.
  1161. csize_t* {.importc: "size_t", nodecl.} = uint
  1162. ## This is the same as the type ``size_t`` in *C*.
  1163. clonglong* {.importc: "long long", nodecl.} = int64
  1164. ## This is the same as the type ``long long`` in *C*.
  1165. cfloat* {.importc: "float", nodecl.} = float32
  1166. ## This is the same as the type ``float`` in *C*.
  1167. cdouble* {.importc: "double", nodecl.} = float64
  1168. ## This is the same as the type ``double`` in *C*.
  1169. clongdouble* {.importc: "long double", nodecl.} = BiggestFloat
  1170. ## This is the same as the type ``long double`` in *C*.
  1171. ## This C type is not supported by Nim's code generator.
  1172. cuchar* {.importc: "unsigned char", nodecl.} = char
  1173. ## This is the same as the type ``unsigned char`` in *C*.
  1174. cushort* {.importc: "unsigned short", nodecl.} = uint16
  1175. ## This is the same as the type ``unsigned short`` in *C*.
  1176. cuint* {.importc: "unsigned int", nodecl.} = uint32
  1177. ## This is the same as the type ``unsigned int`` in *C*.
  1178. culonglong* {.importc: "unsigned long long", nodecl.} = uint64
  1179. ## This is the same as the type ``unsigned long long`` in *C*.
  1180. cstringArray* {.importc: "char**", nodecl.} = ptr UncheckedArray[cstring]
  1181. ## This is binary compatible to the type ``char**`` in *C*. The array's
  1182. ## high value is large enough to disable bounds checking in practice.
  1183. ## Use `cstringArrayToSeq proc <#cstringArrayToSeq,cstringArray,Natural>`_
  1184. ## to convert it into a ``seq[string]``.
  1185. PFloat32* = ptr float32 ## An alias for ``ptr float32``.
  1186. PFloat64* = ptr float64 ## An alias for ``ptr float64``.
  1187. PInt64* = ptr int64 ## An alias for ``ptr int64``.
  1188. PInt32* = ptr int32 ## An alias for ``ptr int32``.
  1189. proc toFloat*(i: int): float {.noSideEffect, inline.} =
  1190. ## Converts an integer `i` into a ``float``.
  1191. ##
  1192. ## If the conversion fails, `ValueError` is raised.
  1193. ## However, on most platforms the conversion cannot fail.
  1194. ##
  1195. ## .. code-block:: Nim
  1196. ## let
  1197. ## a = 2
  1198. ## b = 3.7
  1199. ##
  1200. ## echo a.toFloat + b # => 5.7
  1201. float(i)
  1202. proc toBiggestFloat*(i: BiggestInt): BiggestFloat {.noSideEffect, inline.} =
  1203. ## Same as `toFloat <#toFloat,int>`_ but for ``BiggestInt`` to ``BiggestFloat``.
  1204. BiggestFloat(i)
  1205. proc toInt*(f: float): int {.noSideEffect.} =
  1206. ## Converts a floating point number `f` into an ``int``.
  1207. ##
  1208. ## Conversion rounds `f` half away from 0, see
  1209. ## `Round half away from zero
  1210. ## <https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero>`_.
  1211. ##
  1212. ## Note that some floating point numbers (e.g. infinity or even 1e19)
  1213. ## cannot be accurately converted.
  1214. ##
  1215. ## .. code-block:: Nim
  1216. ## doAssert toInt(0.49) == 0
  1217. ## doAssert toInt(0.5) == 1
  1218. ## doAssert toInt(-0.5) == -1 # rounding is symmetrical
  1219. if f >= 0: int(f+0.5) else: int(f-0.5)
  1220. proc toBiggestInt*(f: BiggestFloat): BiggestInt {.noSideEffect.} =
  1221. ## Same as `toInt <#toInt,float>`_ but for ``BiggestFloat`` to ``BiggestInt``.
  1222. if f >= 0: BiggestInt(f+0.5) else: BiggestInt(f-0.5)
  1223. proc addQuitProc*(quitProc: proc() {.noconv.}) {.
  1224. importc: "atexit", header: "<stdlib.h>".}
  1225. ## Adds/registers a quit procedure.
  1226. ##
  1227. ## Each call to ``addQuitProc`` registers another quit procedure. Up to 30
  1228. ## procedures can be registered. They are executed on a last-in, first-out
  1229. ## basis (that is, the last function registered is the first to be executed).
  1230. ## ``addQuitProc`` raises an EOutOfIndex exception if ``quitProc`` cannot be
  1231. ## registered.
  1232. # Support for addQuitProc() is done by Ansi C's facilities here.
  1233. # In case of an unhandled exception the exit handlers should
  1234. # not be called explicitly! The user may decide to do this manually though.
  1235. proc swap*[T](a, b: var T) {.magic: "Swap", noSideEffect.}
  1236. ## Swaps the values `a` and `b`.
  1237. ##
  1238. ## This is often more efficient than ``tmp = a; a = b; b = tmp``.
  1239. ## Particularly useful for sorting algorithms.
  1240. ##
  1241. ## .. code-block:: Nim
  1242. ## var
  1243. ## a = 5
  1244. ## b = 9
  1245. ##
  1246. ## swap(a, b)
  1247. ##
  1248. ## assert a == 9
  1249. ## assert b == 5
  1250. when not defined(js) and not defined(booting) and defined(nimTrMacros):
  1251. template swapRefsInArray*{swap(arr[a], arr[b])}(arr: openArray[ref], a, b: int) =
  1252. # Optimize swapping of array elements if they are refs. Default swap
  1253. # implementation will cause unsureAsgnRef to be emitted which causes
  1254. # unnecessary slow down in this case.
  1255. swap(cast[ptr pointer](addr arr[a])[], cast[ptr pointer](addr arr[b])[])
  1256. const
  1257. Inf* = 0x7FF0000000000000'f64
  1258. ## Contains the IEEE floating point value of positive infinity.
  1259. NegInf* = 0xFFF0000000000000'f64
  1260. ## Contains the IEEE floating point value of negative infinity.
  1261. NaN* = 0x7FF7FFFFFFFFFFFF'f64
  1262. ## Contains an IEEE floating point value of *Not A Number*.
  1263. ##
  1264. ## Note that you cannot compare a floating point value to this value
  1265. ## and expect a reasonable result - use the `classify` procedure
  1266. ## in the `math module <math.html>`_ for checking for NaN.
  1267. include "system/memalloc"
  1268. proc `|`*(a, b: typedesc): typedesc = discard
  1269. include "system/iterators_1"
  1270. {.push stackTrace: off.}
  1271. proc abs*(x: float64): float64 {.noSideEffect, inline.} =
  1272. if x < 0.0: -x else: x
  1273. proc abs*(x: float32): float32 {.noSideEffect, inline.} =
  1274. if x < 0.0: -x else: x
  1275. proc min*(x, y: float32): float32 {.noSideEffect, inline.} =
  1276. if x <= y or y != y: x else: y
  1277. proc min*(x, y: float64): float64 {.noSideEffect, inline.} =
  1278. if x <= y or y != y: x else: y
  1279. proc max*(x, y: float32): float32 {.noSideEffect, inline.} =
  1280. if y <= x or y != y: x else: y
  1281. proc max*(x, y: float64): float64 {.noSideEffect, inline.} =
  1282. if y <= x or y != y: x else: y
  1283. proc min*[T: not SomeFloat](x, y: T): T {.inline.} =
  1284. if x <= y: x else: y
  1285. proc max*[T: not SomeFloat](x, y: T): T {.inline.} =
  1286. if y <= x: x else: y
  1287. {.pop.} # stackTrace: off
  1288. proc high*(T: typedesc[SomeFloat]): T = Inf
  1289. proc low*(T: typedesc[SomeFloat]): T = NegInf
  1290. proc len*[U: Ordinal; V: Ordinal](x: HSlice[U, V]): int {.noSideEffect, inline.} =
  1291. ## Length of ordinal slice. When x.b < x.a returns zero length.
  1292. ##
  1293. ## .. code-block:: Nim
  1294. ## assert((0..5).len == 6)
  1295. ## assert((5..2).len == 0)
  1296. result = max(0, ord(x.b) - ord(x.a) + 1)
  1297. when defined(nimNoNilSeqs2):
  1298. when not compileOption("nilseqs"):
  1299. {.pragma: nilError, error.}
  1300. else:
  1301. {.pragma: nilError.}
  1302. else:
  1303. {.pragma: nilError.}
  1304. proc isNil*[T](x: seq[T]): bool {.noSideEffect, magic: "IsNil", nilError.}
  1305. ## Requires `--nilseqs:on` since 0.19.
  1306. ##
  1307. ## Seqs are no longer nil by default, but set and empty.
  1308. ## Check for zero length instead.
  1309. ##
  1310. ## See also:
  1311. ## * `isNil(string) <#isNil,string>`_
  1312. proc isNil*[T](x: ref T): bool {.noSideEffect, magic: "IsNil".}
  1313. proc isNil*(x: string): bool {.noSideEffect, magic: "IsNil", nilError.}
  1314. ## Requires `--nilseqs:on`.
  1315. ##
  1316. ## See also:
  1317. ## * `isNil(seq[T]) <#isNil,seq[T][T]>`_
  1318. proc isNil*[T](x: ptr T): bool {.noSideEffect, magic: "IsNil".}
  1319. proc isNil*(x: pointer): bool {.noSideEffect, magic: "IsNil".}
  1320. proc isNil*(x: cstring): bool {.noSideEffect, magic: "IsNil".}
  1321. proc isNil*[T: proc](x: T): bool {.noSideEffect, magic: "IsNil".}
  1322. ## Fast check whether `x` is nil. This is sometimes more efficient than
  1323. ## ``== nil``.
  1324. proc `@`*[T](a: openArray[T]): seq[T] =
  1325. ## Turns an *openArray* into a sequence.
  1326. ##
  1327. ## This is not as efficient as turning a fixed length array into a sequence
  1328. ## as it always copies every element of `a`.
  1329. newSeq(result, a.len)
  1330. for i in 0..a.len-1: result[i] = a[i]
  1331. when defined(nimSeqsV2):
  1332. proc `&`*[T](x, y: sink seq[T]): seq[T] {.noSideEffect.} =
  1333. ## Concatenates two sequences.
  1334. ##
  1335. ## Requires copying of the sequences.
  1336. ##
  1337. ## See also:
  1338. ## * `add(var seq[T], openArray[T]) <#add,seq[T][T],openArray[T]>`_
  1339. ##
  1340. ## .. code-block:: Nim
  1341. ## assert(@[1, 2, 3, 4] & @[5, 6] == @[1, 2, 3, 4, 5, 6])
  1342. newSeq(result, x.len + y.len)
  1343. for i in 0..x.len-1:
  1344. result[i] = move(x[i])
  1345. for i in 0..y.len-1:
  1346. result[i+x.len] = move(y[i])
  1347. proc `&`*[T](x: sink seq[T], y: sink T): seq[T] {.noSideEffect.} =
  1348. ## Appends element y to the end of the sequence.
  1349. ##
  1350. ## Requires copying of the sequence.
  1351. ##
  1352. ## See also:
  1353. ## * `add(var seq[T], T) <#add,seq[T][T],T>`_
  1354. ##
  1355. ## .. code-block:: Nim
  1356. ## assert(@[1, 2, 3] & 4 == @[1, 2, 3, 4])
  1357. newSeq(result, x.len + 1)
  1358. for i in 0..x.len-1:
  1359. result[i] = move(x[i])
  1360. result[x.len] = move(y)
  1361. proc `&`*[T](x: sink T, y: sink seq[T]): seq[T] {.noSideEffect.} =
  1362. ## Prepends the element x to the beginning of the sequence.
  1363. ##
  1364. ## Requires copying of the sequence.
  1365. ##
  1366. ## .. code-block:: Nim
  1367. ## assert(1 & @[2, 3, 4] == @[1, 2, 3, 4])
  1368. newSeq(result, y.len + 1)
  1369. result[0] = move(x)
  1370. for i in 0..y.len-1:
  1371. result[i+1] = move(y[i])
  1372. else:
  1373. proc `&`*[T](x, y: seq[T]): seq[T] {.noSideEffect.} =
  1374. ## Concatenates two sequences.
  1375. ##
  1376. ## Requires copying of the sequences.
  1377. ##
  1378. ## See also:
  1379. ## * `add(var seq[T], openArray[T]) <#add,seq[T][T],openArray[T]>`_
  1380. ##
  1381. ## .. code-block:: Nim
  1382. ## assert(@[1, 2, 3, 4] & @[5, 6] == @[1, 2, 3, 4, 5, 6])
  1383. newSeq(result, x.len + y.len)
  1384. for i in 0..x.len-1:
  1385. result[i] = x[i]
  1386. for i in 0..y.len-1:
  1387. result[i+x.len] = y[i]
  1388. proc `&`*[T](x: seq[T], y: T): seq[T] {.noSideEffect.} =
  1389. ## Appends element y to the end of the sequence.
  1390. ##
  1391. ## Requires copying of the sequence.
  1392. ##
  1393. ## See also:
  1394. ## * `add(var seq[T], T) <#add,seq[T][T],T>`_
  1395. ##
  1396. ## .. code-block:: Nim
  1397. ## assert(@[1, 2, 3] & 4 == @[1, 2, 3, 4])
  1398. newSeq(result, x.len + 1)
  1399. for i in 0..x.len-1:
  1400. result[i] = x[i]
  1401. result[x.len] = y
  1402. proc `&`*[T](x: T, y: seq[T]): seq[T] {.noSideEffect.} =
  1403. ## Prepends the element x to the beginning of the sequence.
  1404. ##
  1405. ## Requires copying of the sequence.
  1406. ##
  1407. ## .. code-block:: Nim
  1408. ## assert(1 & @[2, 3, 4] == @[1, 2, 3, 4])
  1409. newSeq(result, y.len + 1)
  1410. result[0] = x
  1411. for i in 0..y.len-1:
  1412. result[i+1] = y[i]
  1413. proc astToStr*[T](x: T): string {.magic: "AstToStr", noSideEffect.}
  1414. ## Converts the AST of `x` into a string representation. This is very useful
  1415. ## for debugging.
  1416. proc instantiationInfo*(index = -1, fullPaths = false): tuple[
  1417. filename: string, line: int, column: int] {.magic: "InstantiationInfo", noSideEffect.}
  1418. ## Provides access to the compiler's instantiation stack line information
  1419. ## of a template.
  1420. ##
  1421. ## While similar to the `caller info`:idx: of other languages, it is determined
  1422. ## at compile time.
  1423. ##
  1424. ## This proc is mostly useful for meta programming (eg. ``assert`` template)
  1425. ## to retrieve information about the current filename and line number.
  1426. ## Example:
  1427. ##
  1428. ## .. code-block:: nim
  1429. ## import strutils
  1430. ##
  1431. ## template testException(exception, code: untyped): typed =
  1432. ## try:
  1433. ## let pos = instantiationInfo()
  1434. ## discard(code)
  1435. ## echo "Test failure at $1:$2 with '$3'" % [pos.filename,
  1436. ## $pos.line, astToStr(code)]
  1437. ## assert false, "A test expecting failure succeeded?"
  1438. ## except exception:
  1439. ## discard
  1440. ##
  1441. ## proc tester(pos: int): int =
  1442. ## let
  1443. ## a = @[1, 2, 3]
  1444. ## result = a[pos]
  1445. ##
  1446. ## when isMainModule:
  1447. ## testException(IndexError, tester(30))
  1448. ## testException(IndexError, tester(1))
  1449. ## # --> Test failure at example.nim:20 with 'tester(1)'
  1450. proc compiles*(x: untyped): bool {.magic: "Compiles", noSideEffect, compileTime.} =
  1451. ## Special compile-time procedure that checks whether `x` can be compiled
  1452. ## without any semantic error.
  1453. ## This can be used to check whether a type supports some operation:
  1454. ##
  1455. ## .. code-block:: Nim
  1456. ## when compiles(3 + 4):
  1457. ## echo "'+' for integers is available"
  1458. discard
  1459. when notJSnotNims:
  1460. import "system/ansi_c"
  1461. import "system/memory"
  1462. {.push stackTrace: off.}
  1463. when not defined(js) and hasThreadSupport and hostOS != "standalone":
  1464. const insideRLocksModule = false
  1465. include "system/syslocks"
  1466. include "system/threadlocalstorage"
  1467. when not defined(js) and defined(nimV2):
  1468. type
  1469. TNimNode {.compilerproc.} = object # to keep the code generator simple
  1470. DestructorProc = proc (p: pointer) {.nimcall, benign, raises: [].}
  1471. TNimType {.compilerproc.} = object
  1472. destructor: pointer
  1473. size: int
  1474. name: cstring
  1475. traceImpl: pointer
  1476. disposeImpl: pointer
  1477. PNimType = ptr TNimType
  1478. when notJSnotNims and defined(nimSeqsV2):
  1479. include "system/strs_v2"
  1480. include "system/seqs_v2"
  1481. {.pop.}
  1482. when notJSnotNims:
  1483. proc writeStackTrace*() {.tags: [], gcsafe, raises: [].}
  1484. ## Writes the current stack trace to ``stderr``. This is only works
  1485. ## for debug builds. Since it's usually used for debugging, this
  1486. ## is proclaimed to have no IO effect!
  1487. when not declared(sysFatal):
  1488. include "system/fatal"
  1489. when notJSnotNims:
  1490. {.push stackTrace: off, profiler: off.}
  1491. proc atomicInc*(memLoc: var int, x: int = 1): int {.inline,
  1492. discardable, benign.}
  1493. ## Atomic increment of `memLoc`. Returns the value after the operation.
  1494. proc atomicDec*(memLoc: var int, x: int = 1): int {.inline,
  1495. discardable, benign.}
  1496. ## Atomic decrement of `memLoc`. Returns the value after the operation.
  1497. include "system/atomics"
  1498. {.pop.}
  1499. when defined(nimV2):
  1500. include system/refs_v2
  1501. import system/assertions
  1502. export assertions
  1503. import system/iterators
  1504. export iterators
  1505. proc find*[T, S](a: T, item: S): int {.inline.}=
  1506. ## Returns the first index of `item` in `a` or -1 if not found. This requires
  1507. ## appropriate `items` and `==` operations to work.
  1508. for i in items(a):
  1509. if i == item: return
  1510. inc(result)
  1511. result = -1
  1512. proc contains*[T](a: openArray[T], item: T): bool {.inline.}=
  1513. ## Returns true if `item` is in `a` or false if not found. This is a shortcut
  1514. ## for ``find(a, item) >= 0``.
  1515. ##
  1516. ## This allows the `in` operator: `a.contains(item)` is the same as
  1517. ## `item in a`.
  1518. ##
  1519. ## .. code-block:: Nim
  1520. ## var a = @[1, 3, 5]
  1521. ## assert a.contains(5)
  1522. ## assert 3 in a
  1523. ## assert 99 notin a
  1524. return find(a, item) >= 0
  1525. proc pop*[T](s: var seq[T]): T {.inline, noSideEffect.} =
  1526. ## Returns the last item of `s` and decreases ``s.len`` by one. This treats
  1527. ## `s` as a stack and implements the common *pop* operation.
  1528. runnableExamples:
  1529. var a = @[1, 3, 5, 7]
  1530. let b = pop(a)
  1531. assert b == 7
  1532. assert a == @[1, 3, 5]
  1533. var L = s.len-1
  1534. when defined(nimV2):
  1535. result = move s[L]
  1536. shrink(s, L)
  1537. else:
  1538. result = s[L]
  1539. setLen(s, L)
  1540. proc `==`*[T: tuple|object](x, y: T): bool =
  1541. ## Generic ``==`` operator for tuples that is lifted from the components.
  1542. ## of `x` and `y`.
  1543. for a, b in fields(x, y):
  1544. if a != b: return false
  1545. return true
  1546. proc `<=`*[T: tuple](x, y: T): bool =
  1547. ## Generic lexicographic ``<=`` operator for tuples that is lifted from the
  1548. ## components of `x` and `y`. This implementation uses `cmp`.
  1549. for a, b in fields(x, y):
  1550. var c = cmp(a, b)
  1551. if c < 0: return true
  1552. if c > 0: return false
  1553. return true
  1554. proc `<`*[T: tuple](x, y: T): bool =
  1555. ## Generic lexicographic ``<`` operator for tuples that is lifted from the
  1556. ## components of `x` and `y`. This implementation uses `cmp`.
  1557. for a, b in fields(x, y):
  1558. var c = cmp(a, b)
  1559. if c < 0: return true
  1560. if c > 0: return false
  1561. return false
  1562. include "system/gc_interface"
  1563. # we have to compute this here before turning it off in except.nim anyway ...
  1564. const NimStackTrace = compileOption("stacktrace")
  1565. template coroutinesSupportedPlatform(): bool =
  1566. when defined(sparc) or defined(ELATE) or compileOption("gc", "v2") or
  1567. defined(boehmgc) or defined(gogc) or defined(nogc) or defined(gcRegions) or
  1568. defined(gcMarkAndSweep):
  1569. false
  1570. else:
  1571. true
  1572. when defined(nimCoroutines):
  1573. # Explicit opt-in.
  1574. when not coroutinesSupportedPlatform():
  1575. {.error: "Coroutines are not supported on this architecture and/or garbage collector.".}
  1576. const nimCoroutines* = true
  1577. elif defined(noNimCoroutines):
  1578. # Explicit opt-out.
  1579. const nimCoroutines* = false
  1580. else:
  1581. # Autodetect coroutine support.
  1582. const nimCoroutines* = false
  1583. {.push checks: off.}
  1584. # obviously we cannot generate checking operations here :-)
  1585. # because it would yield into an endless recursion
  1586. # however, stack-traces are available for most parts
  1587. # of the code
  1588. var
  1589. globalRaiseHook*: proc (e: ref Exception): bool {.nimcall, benign.}
  1590. ## With this hook you can influence exception handling on a global level.
  1591. ## If not nil, every 'raise' statement ends up calling this hook.
  1592. ##
  1593. ## **Warning**: Ordinary application code should never set this hook!
  1594. ## You better know what you do when setting this.
  1595. ##
  1596. ## If ``globalRaiseHook`` returns false, the exception is caught and does
  1597. ## not propagate further through the call stack.
  1598. localRaiseHook* {.threadvar.}: proc (e: ref Exception): bool {.nimcall, benign.}
  1599. ## With this hook you can influence exception handling on a
  1600. ## thread local level.
  1601. ## If not nil, every 'raise' statement ends up calling this hook.
  1602. ##
  1603. ## **Warning**: Ordinary application code should never set this hook!
  1604. ## You better know what you do when setting this.
  1605. ##
  1606. ## If ``localRaiseHook`` returns false, the exception
  1607. ## is caught and does not propagate further through the call stack.
  1608. outOfMemHook*: proc () {.nimcall, tags: [], benign, raises: [].}
  1609. ## Set this variable to provide a procedure that should be called
  1610. ## in case of an `out of memory`:idx: event. The standard handler
  1611. ## writes an error message and terminates the program.
  1612. ##
  1613. ## `outOfMemHook` can be used to raise an exception in case of OOM like so:
  1614. ##
  1615. ## .. code-block:: Nim
  1616. ##
  1617. ## var gOutOfMem: ref EOutOfMemory
  1618. ## new(gOutOfMem) # need to be allocated *before* OOM really happened!
  1619. ## gOutOfMem.msg = "out of memory"
  1620. ##
  1621. ## proc handleOOM() =
  1622. ## raise gOutOfMem
  1623. ##
  1624. ## system.outOfMemHook = handleOOM
  1625. ##
  1626. ## If the handler does not raise an exception, ordinary control flow
  1627. ## continues and the program is terminated.
  1628. unhandledExceptionHook*: proc (e: ref Exception) {.nimcall, tags: [], benign, raises: [].}
  1629. ## Set this variable to provide a procedure that should be called
  1630. ## in case of an `unhandle exception` event. The standard handler
  1631. ## writes an error message and terminates the program, except when
  1632. ## using `--os:any`
  1633. type
  1634. PFrame* = ptr TFrame ## Represents a runtime frame of the call stack;
  1635. ## part of the debugger API.
  1636. TFrame* {.importc, nodecl, final.} = object ## The frame itself.
  1637. prev*: PFrame ## Previous frame; used for chaining the call stack.
  1638. procname*: cstring ## Name of the proc that is currently executing.
  1639. line*: int ## Line number of the proc that is currently executing.
  1640. filename*: cstring ## Filename of the proc that is currently executing.
  1641. len*: int16 ## Length of the inspectable slots.
  1642. calldepth*: int16 ## Used for max call depth checking.
  1643. when defined(js):
  1644. proc add*(x: var string, y: cstring) {.asmNoStackFrame.} =
  1645. asm """
  1646. if (`x` === null) { `x` = []; }
  1647. var off = `x`.length;
  1648. `x`.length += `y`.length;
  1649. for (var i = 0; i < `y`.length; ++i) {
  1650. `x`[off+i] = `y`.charCodeAt(i);
  1651. }
  1652. """
  1653. proc add*(x: var cstring, y: cstring) {.magic: "AppendStrStr".}
  1654. elif hasAlloc:
  1655. {.push stackTrace: off, profiler: off.}
  1656. proc add*(x: var string, y: cstring) =
  1657. var i = 0
  1658. if y != nil:
  1659. while y[i] != '\0':
  1660. add(x, y[i])
  1661. inc(i)
  1662. {.pop.}
  1663. when defined(nimvarargstyped):
  1664. proc echo*(x: varargs[typed, `$`]) {.magic: "Echo", tags: [WriteIOEffect],
  1665. benign, sideEffect.}
  1666. ## Writes and flushes the parameters to the standard output.
  1667. ##
  1668. ## Special built-in that takes a variable number of arguments. Each argument
  1669. ## is converted to a string via ``$``, so it works for user-defined
  1670. ## types that have an overloaded ``$`` operator.
  1671. ## It is roughly equivalent to ``writeLine(stdout, x); flushFile(stdout)``, but
  1672. ## available for the JavaScript target too.
  1673. ##
  1674. ## Unlike other IO operations this is guaranteed to be thread-safe as
  1675. ## ``echo`` is very often used for debugging convenience. If you want to use
  1676. ## ``echo`` inside a `proc without side effects
  1677. ## <manual.html#pragmas-nosideeffect-pragma>`_ you can use `debugEcho
  1678. ## <#debugEcho,varargs[typed,]>`_ instead.
  1679. proc debugEcho*(x: varargs[typed, `$`]) {.magic: "Echo", noSideEffect,
  1680. tags: [], raises: [].}
  1681. ## Same as `echo <#echo,varargs[typed,]>`_, but as a special semantic rule,
  1682. ## ``debugEcho`` pretends to be free of side effects, so that it can be used
  1683. ## for debugging routines marked as `noSideEffect
  1684. ## <manual.html#pragmas-nosideeffect-pragma>`_.
  1685. else:
  1686. proc echo*(x: varargs[untyped, `$`]) {.magic: "Echo", tags: [WriteIOEffect],
  1687. benign, sideEffect.}
  1688. proc debugEcho*(x: varargs[untyped, `$`]) {.magic: "Echo", noSideEffect,
  1689. tags: [], raises: [].}
  1690. template newException*(exceptn: typedesc, message: string;
  1691. parentException: ref Exception = nil): untyped =
  1692. ## Creates an exception object of type ``exceptn`` and sets its ``msg`` field
  1693. ## to `message`. Returns the new exception object.
  1694. when declared(owned):
  1695. var e: owned(ref exceptn)
  1696. else:
  1697. var e: ref exceptn
  1698. new(e)
  1699. e.msg = message
  1700. e.parent = parentException
  1701. e
  1702. when hostOS == "standalone" and defined(nogc):
  1703. proc nimToCStringConv(s: NimString): cstring {.compilerproc, inline.} =
  1704. if s == nil or s.len == 0: result = cstring""
  1705. else: result = cstring(addr s.data)
  1706. proc getTypeInfo*[T](x: T): pointer {.magic: "GetTypeInfo", benign.}
  1707. ## Get type information for `x`.
  1708. ##
  1709. ## Ordinary code should not use this, but the `typeinfo module
  1710. ## <typeinfo.html>`_ instead.
  1711. {.push stackTrace: off.}
  1712. proc abs*(x: int): int {.magic: "AbsI", noSideEffect.} =
  1713. if x < 0: -x else: x
  1714. proc abs*(x: int8): int8 {.magic: "AbsI", noSideEffect.} =
  1715. if x < 0: -x else: x
  1716. proc abs*(x: int16): int16 {.magic: "AbsI", noSideEffect.} =
  1717. if x < 0: -x else: x
  1718. proc abs*(x: int32): int32 {.magic: "AbsI", noSideEffect.} =
  1719. if x < 0: -x else: x
  1720. proc abs*(x: int64): int64 {.magic: "AbsI", noSideEffect.} =
  1721. ## Returns the absolute value of `x`.
  1722. ##
  1723. ## If `x` is ``low(x)`` (that is -MININT for its type),
  1724. ## an overflow exception is thrown (if overflow checking is turned on).
  1725. result = if x < 0: -x else: x
  1726. {.pop.}
  1727. when not defined(js):
  1728. proc likelyProc(val: bool): bool {.importc: "NIM_LIKELY", nodecl, noSideEffect.}
  1729. proc unlikelyProc(val: bool): bool {.importc: "NIM_UNLIKELY", nodecl, noSideEffect.}
  1730. template likely*(val: bool): bool =
  1731. ## Hints the optimizer that `val` is likely going to be true.
  1732. ##
  1733. ## You can use this template to decorate a branch condition. On certain
  1734. ## platforms this can help the processor predict better which branch is
  1735. ## going to be run. Example:
  1736. ##
  1737. ## .. code-block:: Nim
  1738. ## for value in inputValues:
  1739. ## if likely(value <= 100):
  1740. ## process(value)
  1741. ## else:
  1742. ## echo "Value too big!"
  1743. ##
  1744. ## On backends without branch prediction (JS and the nimscript VM), this
  1745. ## template will not affect code execution.
  1746. when nimvm:
  1747. val
  1748. else:
  1749. when defined(js):
  1750. val
  1751. else:
  1752. likelyProc(val)
  1753. template unlikely*(val: bool): bool =
  1754. ## Hints the optimizer that `val` is likely going to be false.
  1755. ##
  1756. ## You can use this proc to decorate a branch condition. On certain
  1757. ## platforms this can help the processor predict better which branch is
  1758. ## going to be run. Example:
  1759. ##
  1760. ## .. code-block:: Nim
  1761. ## for value in inputValues:
  1762. ## if unlikely(value > 100):
  1763. ## echo "Value too big!"
  1764. ## else:
  1765. ## process(value)
  1766. ##
  1767. ## On backends without branch prediction (JS and the nimscript VM), this
  1768. ## template will not affect code execution.
  1769. when nimvm:
  1770. val
  1771. else:
  1772. when defined(js):
  1773. val
  1774. else:
  1775. unlikelyProc(val)
  1776. import system/dollars
  1777. export dollars
  1778. const
  1779. NimMajor* {.intdefine.}: int = 1
  1780. ## is the major number of Nim's version.
  1781. NimMinor* {.intdefine.}: int = 1
  1782. ## is the minor number of Nim's version.
  1783. NimPatch* {.intdefine.}: int = 1
  1784. ## is the patch number of Nim's version.
  1785. NimVersion*: string = $NimMajor & "." & $NimMinor & "." & $NimPatch
  1786. ## is the version of Nim as a string.
  1787. type
  1788. FileSeekPos* = enum ## Position relative to which seek should happen.
  1789. # The values are ordered so that they match with stdio
  1790. # SEEK_SET, SEEK_CUR and SEEK_END respectively.
  1791. fspSet ## Seek to absolute value
  1792. fspCur ## Seek relative to current position
  1793. fspEnd ## Seek relative to end
  1794. when not defined(js):
  1795. {.push stackTrace: off, profiler: off.}
  1796. when hasAlloc:
  1797. when not defined(gcRegions) and not usesDestructors:
  1798. proc initGC() {.gcsafe.}
  1799. proc initStackBottom() {.inline, compilerproc.} =
  1800. # WARNING: This is very fragile! An array size of 8 does not work on my
  1801. # Linux 64bit system. -- That's because the stack direction is the other
  1802. # way around.
  1803. when declared(nimGC_setStackBottom):
  1804. var locals {.volatile.}: pointer
  1805. locals = addr(locals)
  1806. nimGC_setStackBottom(locals)
  1807. proc initStackBottomWith(locals: pointer) {.inline, compilerproc.} =
  1808. # We need to keep initStackBottom around for now to avoid
  1809. # bootstrapping problems.
  1810. when declared(nimGC_setStackBottom):
  1811. nimGC_setStackBottom(locals)
  1812. when not usesDestructors:
  1813. {.push profiler: off.}
  1814. var
  1815. strDesc = TNimType(size: sizeof(string), kind: tyString, flags: {ntfAcyclic})
  1816. {.pop.}
  1817. {.pop.}
  1818. when not defined(js):
  1819. # ugly hack, see the accompanying .pop for
  1820. # the mysterious error message
  1821. {.push stackTrace: off, profiler: off.}
  1822. when notJSnotNims:
  1823. proc zeroMem(p: pointer, size: Natural) =
  1824. nimZeroMem(p, size)
  1825. when declared(memTrackerOp):
  1826. memTrackerOp("zeroMem", p, size)
  1827. proc copyMem(dest, source: pointer, size: Natural) =
  1828. nimCopyMem(dest, source, size)
  1829. when declared(memTrackerOp):
  1830. memTrackerOp("copyMem", dest, size)
  1831. proc moveMem(dest, source: pointer, size: Natural) =
  1832. c_memmove(dest, source, csize_t(size))
  1833. when declared(memTrackerOp):
  1834. memTrackerOp("moveMem", dest, size)
  1835. proc equalMem(a, b: pointer, size: Natural): bool =
  1836. nimCmpMem(a, b, size) == 0
  1837. when not defined(js):
  1838. proc cmp(x, y: string): int =
  1839. when defined(nimscript):
  1840. if x < y: result = -1
  1841. elif x > y: result = 1
  1842. else: result = 0
  1843. else:
  1844. when nimvm:
  1845. if x < y: result = -1
  1846. elif x > y: result = 1
  1847. else: result = 0
  1848. else:
  1849. let minlen = min(x.len, y.len)
  1850. result = int(nimCmpMem(x.cstring, y.cstring, cast[csize_t](minlen)))
  1851. if result == 0:
  1852. result = x.len - y.len
  1853. when declared(newSeq):
  1854. proc cstringArrayToSeq*(a: cstringArray, len: Natural): seq[string] =
  1855. ## Converts a ``cstringArray`` to a ``seq[string]``. `a` is supposed to be
  1856. ## of length ``len``.
  1857. newSeq(result, len)
  1858. for i in 0..len-1: result[i] = $a[i]
  1859. proc cstringArrayToSeq*(a: cstringArray): seq[string] =
  1860. ## Converts a ``cstringArray`` to a ``seq[string]``. `a` is supposed to be
  1861. ## terminated by ``nil``.
  1862. var L = 0
  1863. while a[L] != nil: inc(L)
  1864. result = cstringArrayToSeq(a, L)
  1865. when not defined(js) and declared(alloc0) and declared(dealloc):
  1866. proc allocCStringArray*(a: openArray[string]): cstringArray =
  1867. ## Creates a NULL terminated cstringArray from `a`. The result has to
  1868. ## be freed with `deallocCStringArray` after it's not needed anymore.
  1869. result = cast[cstringArray](alloc0((a.len+1) * sizeof(cstring)))
  1870. let x = cast[ptr UncheckedArray[string]](a)
  1871. for i in 0 .. a.high:
  1872. result[i] = cast[cstring](alloc0(x[i].len+1))
  1873. copyMem(result[i], addr(x[i][0]), x[i].len)
  1874. proc deallocCStringArray*(a: cstringArray) =
  1875. ## Frees a NULL terminated cstringArray.
  1876. var i = 0
  1877. while a[i] != nil:
  1878. dealloc(a[i])
  1879. inc(i)
  1880. dealloc(a)
  1881. when notJSnotNims:
  1882. type
  1883. PSafePoint = ptr TSafePoint
  1884. TSafePoint {.compilerproc, final.} = object
  1885. prev: PSafePoint # points to next safe point ON THE STACK
  1886. status: int
  1887. context: C_JmpBuf
  1888. SafePoint = TSafePoint
  1889. when not defined(js):
  1890. when declared(initAllocator):
  1891. initAllocator()
  1892. when hasThreadSupport:
  1893. when hostOS != "standalone": include "system/threads"
  1894. elif not defined(nogc) and not defined(nimscript):
  1895. when not defined(useNimRtl) and not defined(createNimRtl): initStackBottom()
  1896. when declared(initGC): initGC()
  1897. when notJSnotNims:
  1898. proc setControlCHook*(hook: proc () {.noconv.})
  1899. ## Allows you to override the behaviour of your application when CTRL+C
  1900. ## is pressed. Only one such hook is supported.
  1901. when not defined(noSignalHandler) and not defined(useNimRtl):
  1902. proc unsetControlCHook*()
  1903. ## Reverts a call to setControlCHook.
  1904. when hostOS != "standalone":
  1905. proc getStackTrace*(): string {.gcsafe.}
  1906. ## Gets the current stack trace. This only works for debug builds.
  1907. proc getStackTrace*(e: ref Exception): string {.gcsafe.}
  1908. ## Gets the stack trace associated with `e`, which is the stack that
  1909. ## lead to the ``raise`` statement. This only works for debug builds.
  1910. {.push stackTrace: off, profiler: off.}
  1911. when defined(memtracker):
  1912. include "system/memtracker"
  1913. when hostOS == "standalone":
  1914. include "system/embedded"
  1915. else:
  1916. include "system/excpt"
  1917. include "system/chcks"
  1918. # we cannot compile this with stack tracing on
  1919. # as it would recurse endlessly!
  1920. include "system/arithm"
  1921. {.pop.}
  1922. when not defined(js):
  1923. # this is a hack: without this when statement, you would get:
  1924. # Error: system module needs: nimGCvisit
  1925. {.pop.} # stackTrace: off, profiler: off
  1926. when notJSnotNims:
  1927. when hostOS != "standalone" and hostOS != "any":
  1928. include "system/dyncalls"
  1929. include "system/sets"
  1930. when defined(gogc):
  1931. const GenericSeqSize = (3 * sizeof(int))
  1932. else:
  1933. const GenericSeqSize = (2 * sizeof(int))
  1934. when not defined(nimV2):
  1935. proc getDiscriminant(aa: pointer, n: ptr TNimNode): uint =
  1936. sysAssert(n.kind == nkCase, "getDiscriminant: node != nkCase")
  1937. var d: uint
  1938. var a = cast[uint](aa)
  1939. case n.typ.size
  1940. of 1: d = uint(cast[ptr uint8](a + uint(n.offset))[])
  1941. of 2: d = uint(cast[ptr uint16](a + uint(n.offset))[])
  1942. of 4: d = uint(cast[ptr uint32](a + uint(n.offset))[])
  1943. of 8: d = uint(cast[ptr uint64](a + uint(n.offset))[])
  1944. else: sysAssert(false, "getDiscriminant: invalid n.typ.size")
  1945. return d
  1946. proc selectBranch(aa: pointer, n: ptr TNimNode): ptr TNimNode =
  1947. var discr = getDiscriminant(aa, n)
  1948. if discr < cast[uint](n.len):
  1949. result = n.sons[discr]
  1950. if result == nil: result = n.sons[n.len]
  1951. # n.sons[n.len] contains the ``else`` part (but may be nil)
  1952. else:
  1953. result = n.sons[n.len]
  1954. when notJSnotNims and hasAlloc:
  1955. {.push profiler: off.}
  1956. include "system/mmdisp"
  1957. {.pop.}
  1958. {.push stackTrace: off, profiler: off.}
  1959. when not defined(nimSeqsV2):
  1960. include "system/sysstr"
  1961. {.pop.}
  1962. include "system/strmantle"
  1963. when not usesDestructors:
  1964. include "system/assign"
  1965. when not defined(nimV2):
  1966. include "system/repr"
  1967. when notJSnotNims and hasThreadSupport and hostOS != "standalone":
  1968. include "system/channels"
  1969. when notJSnotNims and hostOS != "standalone":
  1970. proc getCurrentException*(): ref Exception {.compilerRtl, inl, benign.} =
  1971. ## Retrieves the current exception; if there is none, `nil` is returned.
  1972. result = currException
  1973. proc nimBorrowCurrentException(): ref Exception {.compilerRtl, inl, benign, nodestroy.} =
  1974. # .nodestroy here so that we do not produce a write barrier as the
  1975. # C codegen only uses it in a borrowed way:
  1976. result = currException
  1977. proc getCurrentExceptionMsg*(): string {.inline, benign.} =
  1978. ## Retrieves the error message that was attached to the current
  1979. ## exception; if there is none, `""` is returned.
  1980. return if currException == nil: "" else: currException.msg
  1981. proc setCurrentException*(exc: ref Exception) {.inline, benign.} =
  1982. ## Sets the current exception.
  1983. ##
  1984. ## **Warning**: Only use this if you know what you are doing.
  1985. currException = exc
  1986. when notJSnotNims:
  1987. {.push stackTrace: off, profiler: off.}
  1988. when (defined(profiler) or defined(memProfiler)):
  1989. include "system/profiler"
  1990. {.pop.}
  1991. proc rawProc*[T: proc](x: T): pointer {.noSideEffect, inline.} =
  1992. ## Retrieves the raw proc pointer of the closure `x`. This is
  1993. ## useful for interfacing closures with C.
  1994. {.emit: """
  1995. `result` = `x`.ClP_0;
  1996. """.}
  1997. proc rawEnv*[T: proc](x: T): pointer {.noSideEffect, inline.} =
  1998. ## Retrieves the raw environment pointer of the closure `x`. This is
  1999. ## useful for interfacing closures with C.
  2000. {.emit: """
  2001. `result` = `x`.ClE_0;
  2002. """.}
  2003. proc finished*[T: proc](x: T): bool {.noSideEffect, inline.} =
  2004. ## can be used to determine if a first class iterator has finished.
  2005. {.emit: """
  2006. `result` = ((NI*) `x`.ClE_0)[1] < 0;
  2007. """.}
  2008. when defined(js):
  2009. when not defined(nimscript):
  2010. include "system/jssys"
  2011. include "system/reprjs"
  2012. else:
  2013. proc cmp(x, y: string): int =
  2014. if x == y: return 0
  2015. if x < y: return -1
  2016. return 1
  2017. when defined(js) or defined(nimscript):
  2018. proc addInt*(result: var string; x: int64) =
  2019. result.add $x
  2020. proc addFloat*(result: var string; x: float) =
  2021. result.add $x
  2022. proc quit*(errormsg: string, errorcode = QuitFailure) {.noreturn.} =
  2023. ## A shorthand for ``echo(errormsg); quit(errorcode)``.
  2024. when defined(nimscript) or defined(js) or (hostOS == "standalone"):
  2025. echo errormsg
  2026. else:
  2027. when nimvm:
  2028. echo errormsg
  2029. else:
  2030. cstderr.rawWrite(errormsg)
  2031. cstderr.rawWrite("\n")
  2032. quit(errorcode)
  2033. {.pop.} # checks: off
  2034. {.pop.} # hints: off
  2035. proc `/`*(x, y: int): float {.inline, noSideEffect.} =
  2036. ## Division of integers that results in a float.
  2037. ##
  2038. ## See also:
  2039. ## * `div <#div,int,int>`_
  2040. ## * `mod <#mod,int,int>`_
  2041. ##
  2042. ## .. code-block:: Nim
  2043. ## echo 7 / 5 # => 1.4
  2044. result = toFloat(x) / toFloat(y)
  2045. type
  2046. BackwardsIndex* = distinct int ## Type that is constructed by ``^`` for
  2047. ## reversed array accesses.
  2048. ## (See `^ template <#^.t,int>`_)
  2049. template `^`*(x: int): BackwardsIndex = BackwardsIndex(x)
  2050. ## Builtin `roof`:idx: operator that can be used for convenient array access.
  2051. ## ``a[^x]`` is a shortcut for ``a[a.len-x]``.
  2052. ##
  2053. ## .. code-block:: Nim
  2054. ## let
  2055. ## a = [1, 3, 5, 7, 9]
  2056. ## b = "abcdefgh"
  2057. ##
  2058. ## echo a[^1] # => 9
  2059. ## echo b[^2] # => g
  2060. template `..^`*(a, b: untyped): untyped =
  2061. ## A shortcut for `.. ^` to avoid the common gotcha that a space between
  2062. ## '..' and '^' is required.
  2063. a .. ^b
  2064. template `..<`*(a, b: untyped): untyped =
  2065. ## A shortcut for `a .. pred(b)`.
  2066. ##
  2067. ## .. code-block:: Nim
  2068. ## for i in 5 ..< 9:
  2069. ## echo i # => 5; 6; 7; 8
  2070. a .. (when b is BackwardsIndex: succ(b) else: pred(b))
  2071. template spliceImpl(s, a, L, b: untyped): untyped =
  2072. # make room for additional elements or cut:
  2073. var shift = b.len - max(0,L) # ignore negative slice size
  2074. var newLen = s.len + shift
  2075. if shift > 0:
  2076. # enlarge:
  2077. setLen(s, newLen)
  2078. for i in countdown(newLen-1, a+b.len): movingCopy(s[i], s[i-shift])
  2079. else:
  2080. for i in countup(a+b.len, newLen-1): movingCopy(s[i], s[i-shift])
  2081. # cut down:
  2082. setLen(s, newLen)
  2083. # fill the hole:
  2084. for i in 0 ..< b.len: s[a+i] = b[i]
  2085. template `^^`(s, i: untyped): untyped =
  2086. (when i is BackwardsIndex: s.len - int(i) else: int(i))
  2087. template `[]`*(s: string; i: int): char = arrGet(s, i)
  2088. template `[]=`*(s: string; i: int; val: char) = arrPut(s, i, val)
  2089. proc `[]`*[T, U](s: string, x: HSlice[T, U]): string {.inline.} =
  2090. ## Slice operation for strings.
  2091. ## Returns the inclusive range `[s[x.a], s[x.b]]`:
  2092. ##
  2093. ## .. code-block:: Nim
  2094. ## var s = "abcdef"
  2095. ## assert s[1..3] == "bcd"
  2096. let a = s ^^ x.a
  2097. let L = (s ^^ x.b) - a + 1
  2098. result = newString(L)
  2099. for i in 0 ..< L: result[i] = s[i + a]
  2100. proc `[]=`*[T, U](s: var string, x: HSlice[T, U], b: string) =
  2101. ## Slice assignment for strings.
  2102. ##
  2103. ## If ``b.len`` is not exactly the number of elements that are referred to
  2104. ## by `x`, a `splice`:idx: is performed:
  2105. ##
  2106. runnableExamples:
  2107. var s = "abcdefgh"
  2108. s[1 .. ^2] = "xyz"
  2109. assert s == "axyzh"
  2110. var a = s ^^ x.a
  2111. var L = (s ^^ x.b) - a + 1
  2112. if L == b.len:
  2113. for i in 0..<L: s[i+a] = b[i]
  2114. else:
  2115. spliceImpl(s, a, L, b)
  2116. proc `[]`*[Idx, T, U, V](a: array[Idx, T], x: HSlice[U, V]): seq[T] =
  2117. ## Slice operation for arrays.
  2118. ## Returns the inclusive range `[a[x.a], a[x.b]]`:
  2119. ##
  2120. ## .. code-block:: Nim
  2121. ## var a = [1, 2, 3, 4]
  2122. ## assert a[0..2] == @[1, 2, 3]
  2123. let xa = a ^^ x.a
  2124. let L = (a ^^ x.b) - xa + 1
  2125. result = newSeq[T](L)
  2126. for i in 0..<L: result[i] = a[Idx(i + xa)]
  2127. proc `[]=`*[Idx, T, U, V](a: var array[Idx, T], x: HSlice[U, V], b: openArray[T]) =
  2128. ## Slice assignment for arrays.
  2129. ##
  2130. ## .. code-block:: Nim
  2131. ## var a = [10, 20, 30, 40, 50]
  2132. ## a[1..2] = @[99, 88]
  2133. ## assert a == [10, 99, 88, 40, 50]
  2134. let xa = a ^^ x.a
  2135. let L = (a ^^ x.b) - xa + 1
  2136. if L == b.len:
  2137. for i in 0..<L: a[Idx(i + xa)] = b[i]
  2138. else:
  2139. sysFatal(RangeError, "different lengths for slice assignment")
  2140. proc `[]`*[T, U, V](s: openArray[T], x: HSlice[U, V]): seq[T] =
  2141. ## Slice operation for sequences.
  2142. ## Returns the inclusive range `[s[x.a], s[x.b]]`:
  2143. ##
  2144. ## .. code-block:: Nim
  2145. ## var s = @[1, 2, 3, 4]
  2146. ## assert s[0..2] == @[1, 2, 3]
  2147. let a = s ^^ x.a
  2148. let L = (s ^^ x.b) - a + 1
  2149. newSeq(result, L)
  2150. for i in 0 ..< L: result[i] = s[i + a]
  2151. proc `[]=`*[T, U, V](s: var seq[T], x: HSlice[U, V], b: openArray[T]) =
  2152. ## Slice assignment for sequences.
  2153. ##
  2154. ## If ``b.len`` is not exactly the number of elements that are referred to
  2155. ## by `x`, a `splice`:idx: is performed.
  2156. runnableExamples:
  2157. var s = @"abcdefgh"
  2158. s[1 .. ^2] = @"xyz"
  2159. assert s == @"axyzh"
  2160. let a = s ^^ x.a
  2161. let L = (s ^^ x.b) - a + 1
  2162. if L == b.len:
  2163. for i in 0 ..< L: s[i+a] = b[i]
  2164. else:
  2165. spliceImpl(s, a, L, b)
  2166. proc `[]`*[T](s: openArray[T]; i: BackwardsIndex): T {.inline.} =
  2167. system.`[]`(s, s.len - int(i))
  2168. proc `[]`*[Idx, T](a: array[Idx, T]; i: BackwardsIndex): T {.inline.} =
  2169. a[Idx(a.len - int(i) + int low(a))]
  2170. proc `[]`*(s: string; i: BackwardsIndex): char {.inline.} = s[s.len - int(i)]
  2171. proc `[]`*[T](s: var openArray[T]; i: BackwardsIndex): var T {.inline.} =
  2172. system.`[]`(s, s.len - int(i))
  2173. proc `[]`*[Idx, T](a: var array[Idx, T]; i: BackwardsIndex): var T {.inline.} =
  2174. a[Idx(a.len - int(i) + int low(a))]
  2175. proc `[]=`*[T](s: var openArray[T]; i: BackwardsIndex; x: T) {.inline.} =
  2176. system.`[]=`(s, s.len - int(i), x)
  2177. proc `[]=`*[Idx, T](a: var array[Idx, T]; i: BackwardsIndex; x: T) {.inline.} =
  2178. a[Idx(a.len - int(i) + int low(a))] = x
  2179. proc `[]=`*(s: var string; i: BackwardsIndex; x: char) {.inline.} =
  2180. s[s.len - int(i)] = x
  2181. proc slurp*(filename: string): string {.magic: "Slurp".}
  2182. ## This is an alias for `staticRead <#staticRead,string>`_.
  2183. proc staticRead*(filename: string): string {.magic: "Slurp".}
  2184. ## Compile-time `readFile <io.html#readFile,string>`_ proc for easy
  2185. ## `resource`:idx: embedding:
  2186. ##
  2187. ## The maximum file size limit that ``staticRead`` and ``slurp`` can read is
  2188. ## near or equal to the *free* memory of the device you are using to compile.
  2189. ##
  2190. ## .. code-block:: Nim
  2191. ## const myResource = staticRead"mydatafile.bin"
  2192. ##
  2193. ## `slurp <#slurp,string>`_ is an alias for ``staticRead``.
  2194. proc gorge*(command: string, input = "", cache = ""): string {.
  2195. magic: "StaticExec".} = discard
  2196. ## This is an alias for `staticExec <#staticExec,string,string,string>`_.
  2197. proc staticExec*(command: string, input = "", cache = ""): string {.
  2198. magic: "StaticExec".} = discard
  2199. ## Executes an external process at compile-time and returns its text output
  2200. ## (stdout + stderr).
  2201. ##
  2202. ## If `input` is not an empty string, it will be passed as a standard input
  2203. ## to the executed program.
  2204. ##
  2205. ## .. code-block:: Nim
  2206. ## const buildInfo = "Revision " & staticExec("git rev-parse HEAD") &
  2207. ## "\nCompiled on " & staticExec("uname -v")
  2208. ##
  2209. ## `gorge <#gorge,string,string,string>`_ is an alias for ``staticExec``.
  2210. ##
  2211. ## Note that you can use this proc inside a pragma like
  2212. ## `passc <manual.html#implementation-specific-pragmas-passc-pragma>`_ or
  2213. ## `passl <manual.html#implementation-specific-pragmas-passl-pragma>`_.
  2214. ##
  2215. ## If ``cache`` is not empty, the results of ``staticExec`` are cached within
  2216. ## the ``nimcache`` directory. Use ``--forceBuild`` to get rid of this caching
  2217. ## behaviour then. ``command & input & cache`` (the concatenated string) is
  2218. ## used to determine whether the entry in the cache is still valid. You can
  2219. ## use versioning information for ``cache``:
  2220. ##
  2221. ## .. code-block:: Nim
  2222. ## const stateMachine = staticExec("dfaoptimizer", "input", "0.8.0")
  2223. proc gorgeEx*(command: string, input = "", cache = ""): tuple[output: string,
  2224. exitCode: int] =
  2225. ## Similar to `gorge <#gorge,string,string,string>`_ but also returns the
  2226. ## precious exit code.
  2227. discard
  2228. proc `+=`*[T: float|float32|float64] (x: var T, y: T) {.
  2229. inline, noSideEffect.} =
  2230. ## Increments in place a floating point number.
  2231. x = x + y
  2232. proc `-=`*[T: float|float32|float64] (x: var T, y: T) {.
  2233. inline, noSideEffect.} =
  2234. ## Decrements in place a floating point number.
  2235. x = x - y
  2236. proc `*=`*[T: float|float32|float64] (x: var T, y: T) {.
  2237. inline, noSideEffect.} =
  2238. ## Multiplies in place a floating point number.
  2239. x = x * y
  2240. proc `/=`*(x: var float64, y: float64) {.inline, noSideEffect.} =
  2241. ## Divides in place a floating point number.
  2242. x = x / y
  2243. proc `/=`*[T: float|float32](x: var T, y: T) {.inline, noSideEffect.} =
  2244. ## Divides in place a floating point number.
  2245. x = x / y
  2246. proc `&=`*(x: var string, y: string) {.magic: "AppendStrStr", noSideEffect.}
  2247. ## Appends in place to a string.
  2248. ##
  2249. ## .. code-block:: Nim
  2250. ## var a = "abc"
  2251. ## a &= "de" # a <- "abcde"
  2252. template `&=`*(x, y: typed) =
  2253. ## Generic 'sink' operator for Nim.
  2254. ##
  2255. ## For files an alias for ``write``.
  2256. ## If not specialized further, an alias for ``add``.
  2257. add(x, y)
  2258. when declared(File):
  2259. template `&=`*(f: File, x: typed) = write(f, x)
  2260. template currentSourcePath*: string = instantiationInfo(-1, true).filename
  2261. ## Returns the full file-system path of the current source.
  2262. ##
  2263. ## To get the directory containing the current source, use it with
  2264. ## `os.parentDir() <os.html#parentDir%2Cstring>`_ as ``currentSourcePath.parentDir()``.
  2265. ##
  2266. ## The path returned by this template is set at compile time.
  2267. ##
  2268. ## See the docstring of `macros.getProjectPath() <macros.html#getProjectPath>`_
  2269. ## for an example to see the distinction between the ``currentSourcePath``
  2270. ## and ``getProjectPath``.
  2271. ##
  2272. ## See also:
  2273. ## * `getCurrentDir proc <os.html#getCurrentDir>`_
  2274. when compileOption("rangechecks"):
  2275. template rangeCheck*(cond) =
  2276. ## Helper for performing user-defined range checks.
  2277. ## Such checks will be performed only when the ``rangechecks``
  2278. ## compile-time option is enabled.
  2279. if not cond: sysFatal(RangeError, "range check failed")
  2280. else:
  2281. template rangeCheck*(cond) = discard
  2282. when not defined(nimhygiene):
  2283. {.pragma: inject.}
  2284. proc shallow*[T](s: var seq[T]) {.noSideEffect, inline.} =
  2285. ## Marks a sequence `s` as `shallow`:idx:. Subsequent assignments will not
  2286. ## perform deep copies of `s`.
  2287. ##
  2288. ## This is only useful for optimization purposes.
  2289. if s.len == 0: return
  2290. when not defined(js) and not defined(nimscript) and not defined(nimSeqsV2):
  2291. var s = cast[PGenericSeq](s)
  2292. s.reserved = s.reserved or seqShallowFlag
  2293. proc shallow*(s: var string) {.noSideEffect, inline.} =
  2294. ## Marks a string `s` as `shallow`:idx:. Subsequent assignments will not
  2295. ## perform deep copies of `s`.
  2296. ##
  2297. ## This is only useful for optimization purposes.
  2298. when not defined(js) and not defined(nimscript) and not defined(nimSeqsV2):
  2299. var s = cast[PGenericSeq](s)
  2300. if s == nil:
  2301. s = cast[PGenericSeq](newString(0))
  2302. # string literals cannot become 'shallow':
  2303. if (s.reserved and strlitFlag) == 0:
  2304. s.reserved = s.reserved or seqShallowFlag
  2305. type
  2306. NimNodeObj = object
  2307. NimNode* {.magic: "PNimrodNode".} = ref NimNodeObj
  2308. ## Represents a Nim AST node. Macros operate on this type.
  2309. when defined(nimV2):
  2310. import system/repr_v2
  2311. export repr_v2
  2312. macro lenVarargs*(x: varargs[untyped]): int {.since: (1, 1).} =
  2313. ## returns number of variadic arguments in `x`
  2314. proc lenVarargsImpl(x: NimNode): NimNode {.magic: "LengthOpenArray", noSideEffect.}
  2315. lenVarargsImpl(x)
  2316. when false:
  2317. template eval*(blk: typed): typed =
  2318. ## Executes a block of code at compile time just as if it was a macro.
  2319. ##
  2320. ## Optionally, the block can return an AST tree that will replace the
  2321. ## eval expression.
  2322. macro payload: typed {.gensym.} = blk
  2323. payload()
  2324. when hasAlloc or defined(nimscript):
  2325. proc insert*(x: var string, item: string, i = 0.Natural) {.noSideEffect.} =
  2326. ## Inserts `item` into `x` at position `i`.
  2327. ##
  2328. ## .. code-block:: Nim
  2329. ## var a = "abc"
  2330. ## a.insert("zz", 0) # a <- "zzabc"
  2331. var xl = x.len
  2332. setLen(x, xl+item.len)
  2333. var j = xl-1
  2334. while j >= i:
  2335. shallowCopy(x[j+item.len], x[j])
  2336. dec(j)
  2337. j = 0
  2338. while j < item.len:
  2339. x[j+i] = item[j]
  2340. inc(j)
  2341. when declared(initDebugger):
  2342. initDebugger()
  2343. proc addEscapedChar*(s: var string, c: char) {.noSideEffect, inline.} =
  2344. ## Adds a char to string `s` and applies the following escaping:
  2345. ##
  2346. ## * replaces any ``\`` by ``\\``
  2347. ## * replaces any ``'`` by ``\'``
  2348. ## * replaces any ``"`` by ``\"``
  2349. ## * replaces any ``\a`` by ``\\a``
  2350. ## * replaces any ``\b`` by ``\\b``
  2351. ## * replaces any ``\t`` by ``\\t``
  2352. ## * replaces any ``\n`` by ``\\n``
  2353. ## * replaces any ``\v`` by ``\\v``
  2354. ## * replaces any ``\f`` by ``\\f``
  2355. ## * replaces any ``\c`` by ``\\c``
  2356. ## * replaces any ``\e`` by ``\\e``
  2357. ## * replaces any other character not in the set ``{'\21..'\126'}
  2358. ## by ``\xHH`` where ``HH`` is its hexadecimal value.
  2359. ##
  2360. ## The procedure has been designed so that its output is usable for many
  2361. ## different common syntaxes.
  2362. ##
  2363. ## **Note**: This is **not correct** for producing Ansi C code!
  2364. case c
  2365. of '\a': s.add "\\a" # \x07
  2366. of '\b': s.add "\\b" # \x08
  2367. of '\t': s.add "\\t" # \x09
  2368. of '\L': s.add "\\n" # \x0A
  2369. of '\v': s.add "\\v" # \x0B
  2370. of '\f': s.add "\\f" # \x0C
  2371. of '\c': s.add "\\c" # \x0D
  2372. of '\e': s.add "\\e" # \x1B
  2373. of '\\': s.add("\\\\")
  2374. of '\'': s.add("\\'")
  2375. of '\"': s.add("\\\"")
  2376. of {'\32'..'\126'} - {'\\', '\'', '\"'}: s.add(c)
  2377. else:
  2378. s.add("\\x")
  2379. const HexChars = "0123456789ABCDEF"
  2380. let n = ord(c)
  2381. s.add(HexChars[int((n and 0xF0) shr 4)])
  2382. s.add(HexChars[int(n and 0xF)])
  2383. proc addQuoted*[T](s: var string, x: T) =
  2384. ## Appends `x` to string `s` in place, applying quoting and escaping
  2385. ## if `x` is a string or char.
  2386. ##
  2387. ## See `addEscapedChar <#addEscapedChar,string,char>`_
  2388. ## for the escaping scheme. When `x` is a string, characters in the
  2389. ## range ``{\128..\255}`` are never escaped so that multibyte UTF-8
  2390. ## characters are untouched (note that this behavior is different from
  2391. ## ``addEscapedChar``).
  2392. ##
  2393. ## The Nim standard library uses this function on the elements of
  2394. ## collections when producing a string representation of a collection.
  2395. ## It is recommended to use this function as well for user-side collections.
  2396. ## Users may overload `addQuoted` for custom (string-like) types if
  2397. ## they want to implement a customized element representation.
  2398. ##
  2399. ## .. code-block:: Nim
  2400. ## var tmp = ""
  2401. ## tmp.addQuoted(1)
  2402. ## tmp.add(", ")
  2403. ## tmp.addQuoted("string")
  2404. ## tmp.add(", ")
  2405. ## tmp.addQuoted('c')
  2406. ## assert(tmp == """1, "string", 'c'""")
  2407. when T is string or T is cstring:
  2408. s.add("\"")
  2409. for c in x:
  2410. # Only ASCII chars are escaped to avoid butchering
  2411. # multibyte UTF-8 characters.
  2412. if c <= 127.char:
  2413. s.addEscapedChar(c)
  2414. else:
  2415. s.add c
  2416. s.add("\"")
  2417. elif T is char:
  2418. s.add("'")
  2419. s.addEscapedChar(x)
  2420. s.add("'")
  2421. # prevent temporary string allocation
  2422. elif T is SomeSignedInt:
  2423. s.addInt(x)
  2424. elif T is SomeFloat:
  2425. s.addFloat(x)
  2426. elif compiles(s.add(x)):
  2427. s.add(x)
  2428. else:
  2429. s.add($x)
  2430. proc locals*(): RootObj {.magic: "Plugin", noSideEffect.} =
  2431. ## Generates a tuple constructor expression listing all the local variables
  2432. ## in the current scope.
  2433. ##
  2434. ## This is quite fast as it does not rely
  2435. ## on any debug or runtime information. Note that in contrast to what
  2436. ## the official signature says, the return type is *not* ``RootObj`` but a
  2437. ## tuple of a structure that depends on the current scope. Example:
  2438. ##
  2439. ## .. code-block:: Nim
  2440. ## proc testLocals() =
  2441. ## var
  2442. ## a = "something"
  2443. ## b = 4
  2444. ## c = locals()
  2445. ## d = "super!"
  2446. ##
  2447. ## b = 1
  2448. ## for name, value in fieldPairs(c):
  2449. ## echo "name ", name, " with value ", value
  2450. ## echo "B is ", b
  2451. ## # -> name a with value something
  2452. ## # -> name b with value 4
  2453. ## # -> B is 1
  2454. discard
  2455. when hasAlloc and notJSnotNims and not usesDestructors:
  2456. # XXX how to implement 'deepCopy' is an open problem.
  2457. proc deepCopy*[T](x: var T, y: T) {.noSideEffect, magic: "DeepCopy".} =
  2458. ## Performs a deep copy of `y` and copies it into `x`.
  2459. ##
  2460. ## This is also used by the code generator
  2461. ## for the implementation of ``spawn``.
  2462. discard
  2463. proc deepCopy*[T](y: T): T =
  2464. ## Convenience wrapper around `deepCopy` overload.
  2465. deepCopy(result, y)
  2466. include "system/deepcopy"
  2467. proc procCall*(x: untyped) {.magic: "ProcCall", compileTime.} =
  2468. ## Special magic to prohibit dynamic binding for `method`:idx: calls.
  2469. ## This is similar to `super`:idx: in ordinary OO languages.
  2470. ##
  2471. ## .. code-block:: Nim
  2472. ## # 'someMethod' will be resolved fully statically:
  2473. ## procCall someMethod(a, b)
  2474. discard
  2475. proc `==`*(x, y: cstring): bool {.magic: "EqCString", noSideEffect,
  2476. inline.} =
  2477. ## Checks for equality between two `cstring` variables.
  2478. proc strcmp(a, b: cstring): cint {.noSideEffect,
  2479. importc, header: "<string.h>".}
  2480. if pointer(x) == pointer(y): result = true
  2481. elif x.isNil or y.isNil: result = false
  2482. else: result = strcmp(x, y) == 0
  2483. when defined(nimNoNilSeqs2) and not compileOption("nilseqs"):
  2484. when defined(nimHasUserErrors):
  2485. # bug #9149; ensure that 'type(nil)' does not match *too* well by using 'type(nil) | type(nil)'.
  2486. # Eventually (in 0.20?) we will be able to remove this hack completely.
  2487. proc `==`*(x: string; y: type(nil) | type(nil)): bool {.
  2488. error: "'nil' is now invalid for 'string'; compile with --nilseqs:on for a migration period".} =
  2489. discard
  2490. proc `==`*(x: type(nil) | type(nil); y: string): bool {.
  2491. error: "'nil' is now invalid for 'string'; compile with --nilseqs:on for a migration period".} =
  2492. discard
  2493. else:
  2494. proc `==`*(x: string; y: type(nil) | type(nil)): bool {.error.} = discard
  2495. proc `==`*(x: type(nil) | type(nil); y: string): bool {.error.} = discard
  2496. template closureScope*(body: untyped): untyped =
  2497. ## Useful when creating a closure in a loop to capture local loop variables by
  2498. ## their current iteration values.
  2499. ##
  2500. ## Note: This template may not work in some cases, use
  2501. ## `capture <sugar.html#capture.m,openArray[typed],untyped>`_ instead.
  2502. ##
  2503. ## Example:
  2504. ##
  2505. ## .. code-block:: Nim
  2506. ## var myClosure : proc()
  2507. ## # without closureScope:
  2508. ## for i in 0 .. 5:
  2509. ## let j = i
  2510. ## if j == 3:
  2511. ## myClosure = proc() = echo j
  2512. ## myClosure() # outputs 5. `j` is changed after closure creation
  2513. ## # with closureScope:
  2514. ## for i in 0 .. 5:
  2515. ## closureScope: # Everything in this scope is locked after closure creation
  2516. ## let j = i
  2517. ## if j == 3:
  2518. ## myClosure = proc() = echo j
  2519. ## myClosure() # outputs 3
  2520. (proc() = body)()
  2521. template once*(body: untyped): untyped =
  2522. ## Executes a block of code only once (the first time the block is reached).
  2523. ##
  2524. ## .. code-block:: Nim
  2525. ##
  2526. ## proc draw(t: Triangle) =
  2527. ## once:
  2528. ## graphicsInit()
  2529. ## line(t.p1, t.p2)
  2530. ## line(t.p2, t.p3)
  2531. ## line(t.p3, t.p1)
  2532. ##
  2533. var alreadyExecuted {.global.} = false
  2534. if not alreadyExecuted:
  2535. alreadyExecuted = true
  2536. body
  2537. {.pop.} # warning[GcMem]: off, warning[Uninit]: off
  2538. proc substr*(s: string, first, last: int): string =
  2539. ## Copies a slice of `s` into a new string and returns this new
  2540. ## string.
  2541. ##
  2542. ## The bounds `first` and `last` denote the indices of
  2543. ## the first and last characters that shall be copied. If ``last``
  2544. ## is omitted, it is treated as ``high(s)``. If ``last >= s.len``, ``s.len``
  2545. ## is used instead: This means ``substr`` can also be used to `cut`:idx:
  2546. ## or `limit`:idx: a string's length.
  2547. runnableExamples:
  2548. let a = "abcdefgh"
  2549. assert a.substr(2, 5) == "cdef"
  2550. assert a.substr(2) == "cdefgh"
  2551. assert a.substr(5, 99) == "fgh"
  2552. let first = max(first, 0)
  2553. let L = max(min(last, high(s)) - first + 1, 0)
  2554. result = newString(L)
  2555. for i in 0 .. L-1:
  2556. result[i] = s[i+first]
  2557. proc substr*(s: string, first = 0): string =
  2558. result = substr(s, first, high(s))
  2559. when defined(nimconfig):
  2560. include "system/nimscript"
  2561. when not defined(js):
  2562. proc toOpenArray*[T](x: ptr UncheckedArray[T]; first, last: int): openArray[T] {.
  2563. magic: "Slice".}
  2564. when defined(nimToOpenArrayCString):
  2565. proc toOpenArray*(x: cstring; first, last: int): openArray[char] {.
  2566. magic: "Slice".}
  2567. proc toOpenArrayByte*(x: cstring; first, last: int): openArray[byte] {.
  2568. magic: "Slice".}
  2569. proc toOpenArray*[T](x: seq[T]; first, last: int): openArray[T] {.
  2570. magic: "Slice".}
  2571. proc toOpenArray*[T](x: openArray[T]; first, last: int): openArray[T] {.
  2572. magic: "Slice".}
  2573. proc toOpenArray*[I, T](x: array[I, T]; first, last: I): openArray[T] {.
  2574. magic: "Slice".}
  2575. proc toOpenArray*(x: string; first, last: int): openArray[char] {.
  2576. magic: "Slice".}
  2577. proc toOpenArrayByte*(x: string; first, last: int): openArray[byte] {.
  2578. magic: "Slice".}
  2579. proc toOpenArrayByte*(x: openArray[char]; first, last: int): openArray[byte] {.
  2580. magic: "Slice".}
  2581. proc toOpenArrayByte*(x: seq[char]; first, last: int): openArray[byte] {.
  2582. magic: "Slice".}
  2583. type
  2584. ForLoopStmt* {.compilerproc.} = object ## \
  2585. ## A special type that marks a macro as a `for-loop macro`:idx:.
  2586. ## See `"For Loop Macro" <manual.html#macros-for-loop-macro>`_.
  2587. when defined(genode):
  2588. var componentConstructHook*: proc (env: GenodeEnv) {.nimcall.}
  2589. ## Hook into the Genode component bootstrap process.
  2590. ##
  2591. ## This hook is called after all globals are initialized.
  2592. ## When this hook is set the component will not automatically exit,
  2593. ## call ``quit`` explicitly to do so. This is the only available method
  2594. ## of accessing the initial Genode environment.
  2595. proc nim_component_construct(env: GenodeEnv) {.exportc.} =
  2596. ## Procedure called during ``Component::construct`` by the loader.
  2597. if componentConstructHook.isNil:
  2598. env.quit(programResult)
  2599. # No native Genode application initialization,
  2600. # exit as would POSIX.
  2601. else:
  2602. componentConstructHook(env)
  2603. # Perform application initialization
  2604. # and return to thread entrypoint.
  2605. import system/widestrs
  2606. export widestrs
  2607. import system/io
  2608. export io
  2609. when not defined(createNimHcr):
  2610. include nimhcr