system.nim 93 KB

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