system.nim 94 KB

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