system.nim 99 KB

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