system.nim 104 KB

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