system.nim 98 KB

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