system.nim 93 KB

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