system.nim 92 KB

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