system.nim 94 KB

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