system.nim 97 KB

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