system.nim 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078
  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. ## No trailing newline is inserted (so `echo` won't add an empty newline).
  1162. ## Use `-d:nimLegacyReprWithNewline` to revert to old behavior where newlines
  1163. ## were added in some cases.
  1164. ##
  1165. ## It works even for complex data graphs with cycles. This is a great
  1166. ## debugging tool.
  1167. ##
  1168. ## .. code-block:: Nim
  1169. ## var s: seq[string] = @["test2", "test2"]
  1170. ## var i = @[1, 2, 3, 4, 5]
  1171. ## echo repr(s) # => 0x1055eb050[0x1055ec050"test2", 0x1055ec078"test2"]
  1172. ## echo repr(i) # => 0x1055ed050[1, 2, 3, 4, 5]
  1173. type
  1174. ByteAddress* = int
  1175. ## is the signed integer type that should be used for converting
  1176. ## pointers to integer addresses for readability.
  1177. BiggestFloat* = float64
  1178. ## is an alias for the biggest floating point type the Nim
  1179. ## compiler supports. Currently this is ``float64``, but it is
  1180. ## platform-dependent in general.
  1181. when defined(js):
  1182. type BiggestUInt* = uint32
  1183. ## is an alias for the biggest unsigned integer type the Nim compiler
  1184. ## supports. Currently this is ``uint32`` for JS and ``uint64`` for other
  1185. ## targets.
  1186. else:
  1187. type BiggestUInt* = uint64
  1188. ## is an alias for the biggest unsigned integer type the Nim compiler
  1189. ## supports. Currently this is ``uint32`` for JS and ``uint64`` for other
  1190. ## targets.
  1191. when defined(windows):
  1192. type
  1193. clong* {.importc: "long", nodecl.} = int32
  1194. ## This is the same as the type ``long`` in *C*.
  1195. culong* {.importc: "unsigned long", nodecl.} = uint32
  1196. ## This is the same as the type ``unsigned long`` in *C*.
  1197. else:
  1198. type
  1199. clong* {.importc: "long", nodecl.} = int
  1200. ## This is the same as the type ``long`` in *C*.
  1201. culong* {.importc: "unsigned long", nodecl.} = uint
  1202. ## This is the same as the type ``unsigned long`` in *C*.
  1203. type # these work for most platforms:
  1204. cchar* {.importc: "char", nodecl.} = char
  1205. ## This is the same as the type ``char`` in *C*.
  1206. cschar* {.importc: "signed char", nodecl.} = int8
  1207. ## This is the same as the type ``signed char`` in *C*.
  1208. cshort* {.importc: "short", nodecl.} = int16
  1209. ## This is the same as the type ``short`` in *C*.
  1210. cint* {.importc: "int", nodecl.} = int32
  1211. ## This is the same as the type ``int`` in *C*.
  1212. csize* {.importc: "size_t", nodecl, deprecated: "use `csize_t` instead".} = int
  1213. ## This isn't the same as ``size_t`` in *C*. Don't use it.
  1214. csize_t* {.importc: "size_t", nodecl.} = uint
  1215. ## This is the same as the type ``size_t`` in *C*.
  1216. clonglong* {.importc: "long long", nodecl.} = int64
  1217. ## This is the same as the type ``long long`` in *C*.
  1218. cfloat* {.importc: "float", nodecl.} = float32
  1219. ## This is the same as the type ``float`` in *C*.
  1220. cdouble* {.importc: "double", nodecl.} = float64
  1221. ## This is the same as the type ``double`` in *C*.
  1222. clongdouble* {.importc: "long double", nodecl.} = BiggestFloat
  1223. ## This is the same as the type ``long double`` in *C*.
  1224. ## This C type is not supported by Nim's code generator.
  1225. cuchar* {.importc: "unsigned char", nodecl.} = char
  1226. ## This is the same as the type ``unsigned char`` in *C*.
  1227. cushort* {.importc: "unsigned short", nodecl.} = uint16
  1228. ## This is the same as the type ``unsigned short`` in *C*.
  1229. cuint* {.importc: "unsigned int", nodecl.} = uint32
  1230. ## This is the same as the type ``unsigned int`` in *C*.
  1231. culonglong* {.importc: "unsigned long long", nodecl.} = uint64
  1232. ## This is the same as the type ``unsigned long long`` in *C*.
  1233. cstringArray* {.importc: "char**", nodecl.} = ptr UncheckedArray[cstring]
  1234. ## This is binary compatible to the type ``char**`` in *C*. The array's
  1235. ## high value is large enough to disable bounds checking in practice.
  1236. ## Use `cstringArrayToSeq proc <#cstringArrayToSeq,cstringArray,Natural>`_
  1237. ## to convert it into a ``seq[string]``.
  1238. PFloat32* = ptr float32 ## An alias for ``ptr float32``.
  1239. PFloat64* = ptr float64 ## An alias for ``ptr float64``.
  1240. PInt64* = ptr int64 ## An alias for ``ptr int64``.
  1241. PInt32* = ptr int32 ## An alias for ``ptr int32``.
  1242. proc toFloat*(i: int): float {.noSideEffect, inline.} =
  1243. ## Converts an integer `i` into a ``float``.
  1244. ##
  1245. ## If the conversion fails, `ValueError` is raised.
  1246. ## However, on most platforms the conversion cannot fail.
  1247. ##
  1248. ## .. code-block:: Nim
  1249. ## let
  1250. ## a = 2
  1251. ## b = 3.7
  1252. ##
  1253. ## echo a.toFloat + b # => 5.7
  1254. float(i)
  1255. proc toBiggestFloat*(i: BiggestInt): BiggestFloat {.noSideEffect, inline.} =
  1256. ## Same as `toFloat <#toFloat,int>`_ but for ``BiggestInt`` to ``BiggestFloat``.
  1257. BiggestFloat(i)
  1258. proc toInt*(f: float): int {.noSideEffect.} =
  1259. ## Converts a floating point number `f` into an ``int``.
  1260. ##
  1261. ## Conversion rounds `f` half away from 0, see
  1262. ## `Round half away from zero
  1263. ## <https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero>`_.
  1264. ##
  1265. ## Note that some floating point numbers (e.g. infinity or even 1e19)
  1266. ## cannot be accurately converted.
  1267. ##
  1268. ## .. code-block:: Nim
  1269. ## doAssert toInt(0.49) == 0
  1270. ## doAssert toInt(0.5) == 1
  1271. ## doAssert toInt(-0.5) == -1 # rounding is symmetrical
  1272. if f >= 0: int(f+0.5) else: int(f-0.5)
  1273. proc toBiggestInt*(f: BiggestFloat): BiggestInt {.noSideEffect.} =
  1274. ## Same as `toInt <#toInt,float>`_ but for ``BiggestFloat`` to ``BiggestInt``.
  1275. if f >= 0: BiggestInt(f+0.5) else: BiggestInt(f-0.5)
  1276. proc addQuitProc*(quitProc: proc() {.noconv.}) {.
  1277. importc: "atexit", header: "<stdlib.h>", deprecated: "use exitprocs.addExitProc".}
  1278. ## Adds/registers a quit procedure.
  1279. ##
  1280. ## Each call to ``addQuitProc`` registers another quit procedure. Up to 30
  1281. ## procedures can be registered. They are executed on a last-in, first-out
  1282. ## basis (that is, the last function registered is the first to be executed).
  1283. ## ``addQuitProc`` raises an EOutOfIndex exception if ``quitProc`` cannot be
  1284. ## registered.
  1285. # Support for addQuitProc() is done by Ansi C's facilities here.
  1286. # In case of an unhandled exception the exit handlers should
  1287. # not be called explicitly! The user may decide to do this manually though.
  1288. proc swap*[T](a, b: var T) {.magic: "Swap", noSideEffect.}
  1289. ## Swaps the values `a` and `b`.
  1290. ##
  1291. ## This is often more efficient than ``tmp = a; a = b; b = tmp``.
  1292. ## Particularly useful for sorting algorithms.
  1293. ##
  1294. ## .. code-block:: Nim
  1295. ## var
  1296. ## a = 5
  1297. ## b = 9
  1298. ##
  1299. ## swap(a, b)
  1300. ##
  1301. ## assert a == 9
  1302. ## assert b == 5
  1303. when not defined(js) and not defined(booting) and defined(nimTrMacros):
  1304. template swapRefsInArray*{swap(arr[a], arr[b])}(arr: openArray[ref], a, b: int) =
  1305. # Optimize swapping of array elements if they are refs. Default swap
  1306. # implementation will cause unsureAsgnRef to be emitted which causes
  1307. # unnecessary slow down in this case.
  1308. swap(cast[ptr pointer](addr arr[a])[], cast[ptr pointer](addr arr[b])[])
  1309. const
  1310. Inf* = 0x7FF0000000000000'f64
  1311. ## Contains the IEEE floating point value of positive infinity.
  1312. NegInf* = 0xFFF0000000000000'f64
  1313. ## Contains the IEEE floating point value of negative infinity.
  1314. NaN* = 0x7FF7FFFFFFFFFFFF'f64
  1315. ## Contains an IEEE floating point value of *Not A Number*.
  1316. ##
  1317. ## Note that you cannot compare a floating point value to this value
  1318. ## and expect a reasonable result - use the `classify` procedure
  1319. ## in the `math module <math.html>`_ for checking for NaN.
  1320. include "system/memalloc"
  1321. proc `|`*(a, b: typedesc): typedesc = discard
  1322. include "system/iterators_1"
  1323. {.push stackTrace: off.}
  1324. proc abs*(x: float64): float64 {.noSideEffect, inline.} =
  1325. if x < 0.0: -x else: x
  1326. proc abs*(x: float32): float32 {.noSideEffect, inline.} =
  1327. if x < 0.0: -x else: x
  1328. proc min*(x, y: float32): float32 {.noSideEffect, inline.} =
  1329. if x <= y or y != y: x else: y
  1330. proc min*(x, y: float64): float64 {.noSideEffect, inline.} =
  1331. if x <= y or y != y: x else: y
  1332. proc max*(x, y: float32): float32 {.noSideEffect, inline.} =
  1333. if y <= x or y != y: x else: y
  1334. proc max*(x, y: float64): float64 {.noSideEffect, inline.} =
  1335. if y <= x or y != y: x else: y
  1336. proc min*[T: not SomeFloat](x, y: T): T {.inline.} =
  1337. if x <= y: x else: y
  1338. proc max*[T: not SomeFloat](x, y: T): T {.inline.} =
  1339. if y <= x: x else: y
  1340. {.pop.} # stackTrace: off
  1341. proc high*(T: typedesc[SomeFloat]): T = Inf
  1342. proc low*(T: typedesc[SomeFloat]): T = NegInf
  1343. proc len*[U: Ordinal; V: Ordinal](x: HSlice[U, V]): int {.noSideEffect, inline.} =
  1344. ## Length of ordinal slice. When x.b < x.a returns zero length.
  1345. ##
  1346. ## .. code-block:: Nim
  1347. ## assert((0..5).len == 6)
  1348. ## assert((5..2).len == 0)
  1349. result = max(0, ord(x.b) - ord(x.a) + 1)
  1350. when defined(nimNoNilSeqs2):
  1351. when not compileOption("nilseqs"):
  1352. {.pragma: nilError, error.}
  1353. else:
  1354. {.pragma: nilError.}
  1355. else:
  1356. {.pragma: nilError.}
  1357. proc isNil*[T](x: seq[T]): bool {.noSideEffect, magic: "IsNil", nilError.}
  1358. ## Requires `--nilseqs:on` since 0.19.
  1359. ##
  1360. ## Seqs are no longer nil by default, but set and empty.
  1361. ## Check for zero length instead.
  1362. ##
  1363. ## See also:
  1364. ## * `isNil(string) <#isNil,string>`_
  1365. proc isNil*[T](x: ref T): bool {.noSideEffect, magic: "IsNil".}
  1366. proc isNil*(x: string): bool {.noSideEffect, magic: "IsNil", nilError.}
  1367. ## Requires `--nilseqs:on`.
  1368. ##
  1369. ## See also:
  1370. ## * `isNil(seq[T]) <#isNil,seq[T][T]>`_
  1371. proc isNil*[T](x: ptr T): bool {.noSideEffect, magic: "IsNil".}
  1372. proc isNil*(x: pointer): bool {.noSideEffect, magic: "IsNil".}
  1373. proc isNil*(x: cstring): bool {.noSideEffect, magic: "IsNil".}
  1374. proc isNil*[T: proc](x: T): bool {.noSideEffect, magic: "IsNil".}
  1375. ## Fast check whether `x` is nil. This is sometimes more efficient than
  1376. ## ``== nil``.
  1377. proc `@`*[T](a: openArray[T]): seq[T] =
  1378. ## Turns an *openArray* into a sequence.
  1379. ##
  1380. ## This is not as efficient as turning a fixed length array into a sequence
  1381. ## as it always copies every element of `a`.
  1382. newSeq(result, a.len)
  1383. for i in 0..a.len-1: result[i] = a[i]
  1384. when defined(nimSeqsV2):
  1385. proc `&`*[T](x, y: sink seq[T]): seq[T] {.noSideEffect.} =
  1386. ## Concatenates two sequences.
  1387. ##
  1388. ## Requires copying of the sequences.
  1389. ##
  1390. ## See also:
  1391. ## * `add(var seq[T], openArray[T]) <#add,seq[T][T],openArray[T]>`_
  1392. ##
  1393. ## .. code-block:: Nim
  1394. ## assert(@[1, 2, 3, 4] & @[5, 6] == @[1, 2, 3, 4, 5, 6])
  1395. newSeq(result, x.len + y.len)
  1396. for i in 0..x.len-1:
  1397. result[i] = move(x[i])
  1398. for i in 0..y.len-1:
  1399. result[i+x.len] = move(y[i])
  1400. proc `&`*[T](x: sink seq[T], y: sink T): seq[T] {.noSideEffect.} =
  1401. ## Appends element y to the end of the sequence.
  1402. ##
  1403. ## Requires copying of the sequence.
  1404. ##
  1405. ## See also:
  1406. ## * `add(var seq[T], T) <#add,seq[T][T],T>`_
  1407. ##
  1408. ## .. code-block:: Nim
  1409. ## assert(@[1, 2, 3] & 4 == @[1, 2, 3, 4])
  1410. newSeq(result, x.len + 1)
  1411. for i in 0..x.len-1:
  1412. result[i] = move(x[i])
  1413. result[x.len] = move(y)
  1414. proc `&`*[T](x: sink T, y: sink seq[T]): seq[T] {.noSideEffect.} =
  1415. ## Prepends the element x to the beginning of the sequence.
  1416. ##
  1417. ## Requires copying of the sequence.
  1418. ##
  1419. ## .. code-block:: Nim
  1420. ## assert(1 & @[2, 3, 4] == @[1, 2, 3, 4])
  1421. newSeq(result, y.len + 1)
  1422. result[0] = move(x)
  1423. for i in 0..y.len-1:
  1424. result[i+1] = move(y[i])
  1425. else:
  1426. proc `&`*[T](x, y: seq[T]): seq[T] {.noSideEffect.} =
  1427. ## Concatenates two sequences.
  1428. ##
  1429. ## Requires copying of the sequences.
  1430. ##
  1431. ## See also:
  1432. ## * `add(var seq[T], openArray[T]) <#add,seq[T][T],openArray[T]>`_
  1433. ##
  1434. ## .. code-block:: Nim
  1435. ## assert(@[1, 2, 3, 4] & @[5, 6] == @[1, 2, 3, 4, 5, 6])
  1436. newSeq(result, x.len + y.len)
  1437. for i in 0..x.len-1:
  1438. result[i] = x[i]
  1439. for i in 0..y.len-1:
  1440. result[i+x.len] = y[i]
  1441. proc `&`*[T](x: seq[T], y: T): seq[T] {.noSideEffect.} =
  1442. ## Appends element y to the end of the sequence.
  1443. ##
  1444. ## Requires copying of the sequence.
  1445. ##
  1446. ## See also:
  1447. ## * `add(var seq[T], T) <#add,seq[T][T],T>`_
  1448. ##
  1449. ## .. code-block:: Nim
  1450. ## assert(@[1, 2, 3] & 4 == @[1, 2, 3, 4])
  1451. newSeq(result, x.len + 1)
  1452. for i in 0..x.len-1:
  1453. result[i] = x[i]
  1454. result[x.len] = y
  1455. proc `&`*[T](x: T, y: seq[T]): seq[T] {.noSideEffect.} =
  1456. ## Prepends the element x to the beginning of the sequence.
  1457. ##
  1458. ## Requires copying of the sequence.
  1459. ##
  1460. ## .. code-block:: Nim
  1461. ## assert(1 & @[2, 3, 4] == @[1, 2, 3, 4])
  1462. newSeq(result, y.len + 1)
  1463. result[0] = x
  1464. for i in 0..y.len-1:
  1465. result[i+1] = y[i]
  1466. proc astToStr*[T](x: T): string {.magic: "AstToStr", noSideEffect.}
  1467. ## Converts the AST of `x` into a string representation. This is very useful
  1468. ## for debugging.
  1469. proc instantiationInfo*(index = -1, fullPaths = false): tuple[
  1470. filename: string, line: int, column: int] {.magic: "InstantiationInfo", noSideEffect.}
  1471. ## Provides access to the compiler's instantiation stack line information
  1472. ## of a template.
  1473. ##
  1474. ## While similar to the `caller info`:idx: of other languages, it is determined
  1475. ## at compile time.
  1476. ##
  1477. ## This proc is mostly useful for meta programming (eg. ``assert`` template)
  1478. ## to retrieve information about the current filename and line number.
  1479. ## Example:
  1480. ##
  1481. ## .. code-block:: nim
  1482. ## import strutils
  1483. ##
  1484. ## template testException(exception, code: untyped): typed =
  1485. ## try:
  1486. ## let pos = instantiationInfo()
  1487. ## discard(code)
  1488. ## echo "Test failure at $1:$2 with '$3'" % [pos.filename,
  1489. ## $pos.line, astToStr(code)]
  1490. ## assert false, "A test expecting failure succeeded?"
  1491. ## except exception:
  1492. ## discard
  1493. ##
  1494. ## proc tester(pos: int): int =
  1495. ## let
  1496. ## a = @[1, 2, 3]
  1497. ## result = a[pos]
  1498. ##
  1499. ## when isMainModule:
  1500. ## testException(IndexDefect, tester(30))
  1501. ## testException(IndexDefect, tester(1))
  1502. ## # --> Test failure at example.nim:20 with 'tester(1)'
  1503. proc compiles*(x: untyped): bool {.magic: "Compiles", noSideEffect, compileTime.} =
  1504. ## Special compile-time procedure that checks whether `x` can be compiled
  1505. ## without any semantic error.
  1506. ## This can be used to check whether a type supports some operation:
  1507. ##
  1508. ## .. code-block:: Nim
  1509. ## when compiles(3 + 4):
  1510. ## echo "'+' for integers is available"
  1511. discard
  1512. when notJSnotNims:
  1513. import "system/ansi_c"
  1514. import "system/memory"
  1515. {.push stackTrace: off.}
  1516. when not defined(js) and hasThreadSupport and hostOS != "standalone":
  1517. const insideRLocksModule = false
  1518. include "system/syslocks"
  1519. include "system/threadlocalstorage"
  1520. when not defined(js) and defined(nimV2):
  1521. type
  1522. DestructorProc = proc (p: pointer) {.nimcall, benign, raises: [].}
  1523. TNimTypeV2 {.compilerproc.} = object
  1524. destructor: pointer
  1525. size: int
  1526. align: int
  1527. name: cstring
  1528. traceImpl: pointer
  1529. disposeImpl: pointer
  1530. typeInfoV1: pointer # for backwards compat, usually nil
  1531. PNimTypeV2 = ptr TNimTypeV2
  1532. when notJSnotNims and defined(nimSeqsV2):
  1533. include "system/strs_v2"
  1534. include "system/seqs_v2"
  1535. {.pop.}
  1536. when notJSnotNims:
  1537. proc writeStackTrace*() {.tags: [], gcsafe, raises: [].}
  1538. ## Writes the current stack trace to ``stderr``. This is only works
  1539. ## for debug builds. Since it's usually used for debugging, this
  1540. ## is proclaimed to have no IO effect!
  1541. when not declared(sysFatal):
  1542. include "system/fatal"
  1543. when notJSnotNims:
  1544. {.push stackTrace: off, profiler: off.}
  1545. proc atomicInc*(memLoc: var int, x: int = 1): int {.inline,
  1546. discardable, benign.}
  1547. ## Atomic increment of `memLoc`. Returns the value after the operation.
  1548. proc atomicDec*(memLoc: var int, x: int = 1): int {.inline,
  1549. discardable, benign.}
  1550. ## Atomic decrement of `memLoc`. Returns the value after the operation.
  1551. include "system/atomics"
  1552. {.pop.}
  1553. when defined(nimV2):
  1554. include system/arc
  1555. import system/assertions
  1556. export assertions
  1557. import system/iterators
  1558. export iterators
  1559. proc find*[T, S](a: T, item: S): int {.inline.}=
  1560. ## Returns the first index of `item` in `a` or -1 if not found. This requires
  1561. ## appropriate `items` and `==` operations to work.
  1562. result = 0
  1563. for i in items(a):
  1564. if i == item: return
  1565. inc(result)
  1566. result = -1
  1567. proc contains*[T](a: openArray[T], item: T): bool {.inline.}=
  1568. ## Returns true if `item` is in `a` or false if not found. This is a shortcut
  1569. ## for ``find(a, item) >= 0``.
  1570. ##
  1571. ## This allows the `in` operator: `a.contains(item)` is the same as
  1572. ## `item in a`.
  1573. ##
  1574. ## .. code-block:: Nim
  1575. ## var a = @[1, 3, 5]
  1576. ## assert a.contains(5)
  1577. ## assert 3 in a
  1578. ## assert 99 notin a
  1579. return find(a, item) >= 0
  1580. proc pop*[T](s: var seq[T]): T {.inline, noSideEffect.} =
  1581. ## Returns the last item of `s` and decreases ``s.len`` by one. This treats
  1582. ## `s` as a stack and implements the common *pop* operation.
  1583. runnableExamples:
  1584. var a = @[1, 3, 5, 7]
  1585. let b = pop(a)
  1586. assert b == 7
  1587. assert a == @[1, 3, 5]
  1588. var L = s.len-1
  1589. when defined(nimV2):
  1590. result = move s[L]
  1591. shrink(s, L)
  1592. else:
  1593. result = s[L]
  1594. setLen(s, L)
  1595. proc `==`*[T: tuple|object](x, y: T): bool =
  1596. ## Generic ``==`` operator for tuples that is lifted from the components.
  1597. ## of `x` and `y`.
  1598. for a, b in fields(x, y):
  1599. if a != b: return false
  1600. return true
  1601. proc `<=`*[T: tuple](x, y: T): bool =
  1602. ## Generic lexicographic ``<=`` operator for tuples that is lifted from the
  1603. ## components of `x` and `y`. This implementation uses `cmp`.
  1604. for a, b in fields(x, y):
  1605. var c = cmp(a, b)
  1606. if c < 0: return true
  1607. if c > 0: return false
  1608. return true
  1609. proc `<`*[T: tuple](x, y: T): bool =
  1610. ## Generic lexicographic ``<`` operator for tuples that is lifted from the
  1611. ## components of `x` and `y`. This implementation uses `cmp`.
  1612. for a, b in fields(x, y):
  1613. var c = cmp(a, b)
  1614. if c < 0: return true
  1615. if c > 0: return false
  1616. return false
  1617. include "system/gc_interface"
  1618. # we have to compute this here before turning it off in except.nim anyway ...
  1619. const NimStackTrace = compileOption("stacktrace")
  1620. template coroutinesSupportedPlatform(): bool =
  1621. when defined(sparc) or defined(ELATE) or compileOption("gc", "v2") or
  1622. defined(boehmgc) or defined(gogc) or defined(nogc) or defined(gcRegions) or
  1623. defined(gcMarkAndSweep):
  1624. false
  1625. else:
  1626. true
  1627. when defined(nimCoroutines):
  1628. # Explicit opt-in.
  1629. when not coroutinesSupportedPlatform():
  1630. {.error: "Coroutines are not supported on this architecture and/or garbage collector.".}
  1631. const nimCoroutines* = true
  1632. elif defined(noNimCoroutines):
  1633. # Explicit opt-out.
  1634. const nimCoroutines* = false
  1635. else:
  1636. # Autodetect coroutine support.
  1637. const nimCoroutines* = false
  1638. {.push checks: off.}
  1639. # obviously we cannot generate checking operations here :-)
  1640. # because it would yield into an endless recursion
  1641. # however, stack-traces are available for most parts
  1642. # of the code
  1643. var
  1644. globalRaiseHook*: proc (e: ref Exception): bool {.nimcall, benign.}
  1645. ## With this hook you can influence exception handling on a global level.
  1646. ## If not nil, every 'raise' statement ends up calling this hook.
  1647. ##
  1648. ## **Warning**: Ordinary application code should never set this hook!
  1649. ## You better know what you do when setting this.
  1650. ##
  1651. ## If ``globalRaiseHook`` returns false, the exception is caught and does
  1652. ## not propagate further through the call stack.
  1653. localRaiseHook* {.threadvar.}: proc (e: ref Exception): bool {.nimcall, benign.}
  1654. ## With this hook you can influence exception handling on a
  1655. ## thread local level.
  1656. ## If not nil, every 'raise' statement ends up calling this hook.
  1657. ##
  1658. ## **Warning**: Ordinary application code should never set this hook!
  1659. ## You better know what you do when setting this.
  1660. ##
  1661. ## If ``localRaiseHook`` returns false, the exception
  1662. ## is caught and does not propagate further through the call stack.
  1663. outOfMemHook*: proc () {.nimcall, tags: [], benign, raises: [].}
  1664. ## Set this variable to provide a procedure that should be called
  1665. ## in case of an `out of memory`:idx: event. The standard handler
  1666. ## writes an error message and terminates the program.
  1667. ##
  1668. ## `outOfMemHook` can be used to raise an exception in case of OOM like so:
  1669. ##
  1670. ## .. code-block:: Nim
  1671. ##
  1672. ## var gOutOfMem: ref EOutOfMemory
  1673. ## new(gOutOfMem) # need to be allocated *before* OOM really happened!
  1674. ## gOutOfMem.msg = "out of memory"
  1675. ##
  1676. ## proc handleOOM() =
  1677. ## raise gOutOfMem
  1678. ##
  1679. ## system.outOfMemHook = handleOOM
  1680. ##
  1681. ## If the handler does not raise an exception, ordinary control flow
  1682. ## continues and the program is terminated.
  1683. unhandledExceptionHook*: proc (e: ref Exception) {.nimcall, tags: [], benign, raises: [].}
  1684. ## Set this variable to provide a procedure that should be called
  1685. ## in case of an `unhandle exception` event. The standard handler
  1686. ## writes an error message and terminates the program, except when
  1687. ## using `--os:any`
  1688. type
  1689. PFrame* = ptr TFrame ## Represents a runtime frame of the call stack;
  1690. ## part of the debugger API.
  1691. # keep in sync with nimbase.h `struct TFrame_`
  1692. TFrame* {.importc, nodecl, final.} = object ## The frame itself.
  1693. prev*: PFrame ## Previous frame; used for chaining the call stack.
  1694. procname*: cstring ## Name of the proc that is currently executing.
  1695. line*: int ## Line number of the proc that is currently executing.
  1696. filename*: cstring ## Filename of the proc that is currently executing.
  1697. len*: int16 ## Length of the inspectable slots.
  1698. calldepth*: int16 ## Used for max call depth checking.
  1699. when NimStackTraceMsgs:
  1700. frameMsgLen*: int ## end position in frameMsgBuf for this frame.
  1701. when defined(js):
  1702. proc add*(x: var string, y: cstring) {.asmNoStackFrame.} =
  1703. asm """
  1704. if (`x` === null) { `x` = []; }
  1705. var off = `x`.length;
  1706. `x`.length += `y`.length;
  1707. for (var i = 0; i < `y`.length; ++i) {
  1708. `x`[off+i] = `y`.charCodeAt(i);
  1709. }
  1710. """
  1711. proc add*(x: var cstring, y: cstring) {.magic: "AppendStrStr".}
  1712. elif hasAlloc:
  1713. {.push stackTrace: off, profiler: off.}
  1714. proc add*(x: var string, y: cstring) =
  1715. var i = 0
  1716. if y != nil:
  1717. while y[i] != '\0':
  1718. add(x, y[i])
  1719. inc(i)
  1720. {.pop.}
  1721. when defined(nimvarargstyped):
  1722. proc echo*(x: varargs[typed, `$`]) {.magic: "Echo", tags: [WriteIOEffect],
  1723. benign, sideEffect.}
  1724. ## Writes and flushes the parameters to the standard output.
  1725. ##
  1726. ## Special built-in that takes a variable number of arguments. Each argument
  1727. ## is converted to a string via ``$``, so it works for user-defined
  1728. ## types that have an overloaded ``$`` operator.
  1729. ## It is roughly equivalent to ``writeLine(stdout, x); flushFile(stdout)``, but
  1730. ## available for the JavaScript target too.
  1731. ##
  1732. ## Unlike other IO operations this is guaranteed to be thread-safe as
  1733. ## ``echo`` is very often used for debugging convenience. If you want to use
  1734. ## ``echo`` inside a `proc without side effects
  1735. ## <manual.html#pragmas-nosideeffect-pragma>`_ you can use `debugEcho
  1736. ## <#debugEcho,varargs[typed,]>`_ instead.
  1737. proc debugEcho*(x: varargs[typed, `$`]) {.magic: "Echo", noSideEffect,
  1738. tags: [], raises: [].}
  1739. ## Same as `echo <#echo,varargs[typed,]>`_, but as a special semantic rule,
  1740. ## ``debugEcho`` pretends to be free of side effects, so that it can be used
  1741. ## for debugging routines marked as `noSideEffect
  1742. ## <manual.html#pragmas-nosideeffect-pragma>`_.
  1743. else:
  1744. proc echo*(x: varargs[untyped, `$`]) {.magic: "Echo", tags: [WriteIOEffect],
  1745. benign, sideEffect.}
  1746. proc debugEcho*(x: varargs[untyped, `$`]) {.magic: "Echo", noSideEffect,
  1747. tags: [], raises: [].}
  1748. template newException*(exceptn: typedesc, message: string;
  1749. parentException: ref Exception = nil): untyped =
  1750. ## Creates an exception object of type ``exceptn`` and sets its ``msg`` field
  1751. ## to `message`. Returns the new exception object.
  1752. (ref exceptn)(msg: message, parent: parentException)
  1753. when hostOS == "standalone" and defined(nogc):
  1754. proc nimToCStringConv(s: NimString): cstring {.compilerproc, inline.} =
  1755. if s == nil or s.len == 0: result = cstring""
  1756. else: result = cstring(addr s.data)
  1757. proc getTypeInfo*[T](x: T): pointer {.magic: "GetTypeInfo", benign.}
  1758. ## Get type information for `x`.
  1759. ##
  1760. ## Ordinary code should not use this, but the `typeinfo module
  1761. ## <typeinfo.html>`_ instead.
  1762. {.push stackTrace: off.}
  1763. proc abs*(x: int): int {.magic: "AbsI", noSideEffect.} =
  1764. if x < 0: -x else: x
  1765. proc abs*(x: int8): int8 {.magic: "AbsI", noSideEffect.} =
  1766. if x < 0: -x else: x
  1767. proc abs*(x: int16): int16 {.magic: "AbsI", noSideEffect.} =
  1768. if x < 0: -x else: x
  1769. proc abs*(x: int32): int32 {.magic: "AbsI", noSideEffect.} =
  1770. if x < 0: -x else: x
  1771. proc abs*(x: int64): int64 {.magic: "AbsI", noSideEffect.} =
  1772. ## Returns the absolute value of `x`.
  1773. ##
  1774. ## If `x` is ``low(x)`` (that is -MININT for its type),
  1775. ## an overflow exception is thrown (if overflow checking is turned on).
  1776. result = if x < 0: -x else: x
  1777. {.pop.}
  1778. when not defined(js):
  1779. proc likelyProc(val: bool): bool {.importc: "NIM_LIKELY", nodecl, noSideEffect.}
  1780. proc unlikelyProc(val: bool): bool {.importc: "NIM_UNLIKELY", nodecl, noSideEffect.}
  1781. template likely*(val: bool): bool =
  1782. ## Hints the optimizer that `val` is likely going to be true.
  1783. ##
  1784. ## You can use this template to decorate a branch condition. On certain
  1785. ## platforms this can help the processor predict better which branch is
  1786. ## going to be run. Example:
  1787. ##
  1788. ## .. code-block:: Nim
  1789. ## for value in inputValues:
  1790. ## if likely(value <= 100):
  1791. ## process(value)
  1792. ## else:
  1793. ## echo "Value too big!"
  1794. ##
  1795. ## On backends without branch prediction (JS and the nimscript VM), this
  1796. ## template will not affect code execution.
  1797. when nimvm:
  1798. val
  1799. else:
  1800. when defined(js):
  1801. val
  1802. else:
  1803. likelyProc(val)
  1804. template unlikely*(val: bool): bool =
  1805. ## Hints the optimizer that `val` is likely going to be false.
  1806. ##
  1807. ## You can use this proc to decorate a branch condition. On certain
  1808. ## platforms this can help the processor predict better which branch is
  1809. ## going to be run. Example:
  1810. ##
  1811. ## .. code-block:: Nim
  1812. ## for value in inputValues:
  1813. ## if unlikely(value > 100):
  1814. ## echo "Value too big!"
  1815. ## else:
  1816. ## process(value)
  1817. ##
  1818. ## On backends without branch prediction (JS and the nimscript VM), this
  1819. ## template will not affect code execution.
  1820. when nimvm:
  1821. val
  1822. else:
  1823. when defined(js):
  1824. val
  1825. else:
  1826. unlikelyProc(val)
  1827. const
  1828. NimMajor* {.intdefine.}: int = 1
  1829. ## is the major number of Nim's version. Example:
  1830. ##
  1831. ## .. code-block:: Nim
  1832. ## when (NimMajor, NimMinor, NimPatch) >= (1, 3, 1): discard
  1833. # see also std/private/since
  1834. NimMinor* {.intdefine.}: int = 5
  1835. ## is the minor number of Nim's version.
  1836. ## Odd for devel, even for releases.
  1837. NimPatch* {.intdefine.}: int = 1
  1838. ## is the patch number of Nim's version.
  1839. ## Odd for devel, even for releases.
  1840. import system/dollars
  1841. export dollars
  1842. const
  1843. NimVersion*: string = $NimMajor & "." & $NimMinor & "." & $NimPatch
  1844. ## is the version of Nim as a string.
  1845. type
  1846. FileSeekPos* = enum ## Position relative to which seek should happen.
  1847. # The values are ordered so that they match with stdio
  1848. # SEEK_SET, SEEK_CUR and SEEK_END respectively.
  1849. fspSet ## Seek to absolute value
  1850. fspCur ## Seek relative to current position
  1851. fspEnd ## Seek relative to end
  1852. when not defined(js):
  1853. {.push stackTrace: off, profiler: off.}
  1854. when hasAlloc:
  1855. when not defined(gcRegions) and not usesDestructors:
  1856. proc initGC() {.gcsafe, raises: [].}
  1857. proc initStackBottom() {.inline, compilerproc.} =
  1858. # WARNING: This is very fragile! An array size of 8 does not work on my
  1859. # Linux 64bit system. -- That's because the stack direction is the other
  1860. # way around.
  1861. when declared(nimGC_setStackBottom):
  1862. var locals {.volatile, noinit.}: pointer
  1863. locals = addr(locals)
  1864. nimGC_setStackBottom(locals)
  1865. proc initStackBottomWith(locals: pointer) {.inline, compilerproc.} =
  1866. # We need to keep initStackBottom around for now to avoid
  1867. # bootstrapping problems.
  1868. when declared(nimGC_setStackBottom):
  1869. nimGC_setStackBottom(locals)
  1870. when not usesDestructors:
  1871. {.push profiler: off.}
  1872. var
  1873. strDesc = TNimType(size: sizeof(string), kind: tyString, flags: {ntfAcyclic})
  1874. {.pop.}
  1875. {.pop.}
  1876. when not defined(js):
  1877. # ugly hack, see the accompanying .pop for
  1878. # the mysterious error message
  1879. {.push stackTrace: off, profiler: off.}
  1880. when notJSnotNims:
  1881. proc zeroMem(p: pointer, size: Natural) =
  1882. nimZeroMem(p, size)
  1883. when declared(memTrackerOp):
  1884. memTrackerOp("zeroMem", p, size)
  1885. proc copyMem(dest, source: pointer, size: Natural) =
  1886. nimCopyMem(dest, source, size)
  1887. when declared(memTrackerOp):
  1888. memTrackerOp("copyMem", dest, size)
  1889. proc moveMem(dest, source: pointer, size: Natural) =
  1890. c_memmove(dest, source, csize_t(size))
  1891. when declared(memTrackerOp):
  1892. memTrackerOp("moveMem", dest, size)
  1893. proc equalMem(a, b: pointer, size: Natural): bool =
  1894. nimCmpMem(a, b, size) == 0
  1895. when not defined(js):
  1896. proc cmp(x, y: string): int =
  1897. when nimvm:
  1898. if x < y: result = -1
  1899. elif x > y: result = 1
  1900. else: result = 0
  1901. else:
  1902. when not defined(nimscript): # avoid semantic checking
  1903. let minlen = min(x.len, y.len)
  1904. result = int(nimCmpMem(x.cstring, y.cstring, cast[csize_t](minlen)))
  1905. if result == 0:
  1906. result = x.len - y.len
  1907. when declared(newSeq):
  1908. proc cstringArrayToSeq*(a: cstringArray, len: Natural): seq[string] =
  1909. ## Converts a ``cstringArray`` to a ``seq[string]``. `a` is supposed to be
  1910. ## of length ``len``.
  1911. newSeq(result, len)
  1912. for i in 0..len-1: result[i] = $a[i]
  1913. proc cstringArrayToSeq*(a: cstringArray): seq[string] =
  1914. ## Converts a ``cstringArray`` to a ``seq[string]``. `a` is supposed to be
  1915. ## terminated by ``nil``.
  1916. var L = 0
  1917. while a[L] != nil: inc(L)
  1918. result = cstringArrayToSeq(a, L)
  1919. when not defined(js) and declared(alloc0) and declared(dealloc):
  1920. proc allocCStringArray*(a: openArray[string]): cstringArray =
  1921. ## Creates a NULL terminated cstringArray from `a`. The result has to
  1922. ## be freed with `deallocCStringArray` after it's not needed anymore.
  1923. result = cast[cstringArray](alloc0((a.len+1) * sizeof(cstring)))
  1924. let x = cast[ptr UncheckedArray[string]](a)
  1925. for i in 0 .. a.high:
  1926. result[i] = cast[cstring](alloc0(x[i].len+1))
  1927. copyMem(result[i], addr(x[i][0]), x[i].len)
  1928. proc deallocCStringArray*(a: cstringArray) =
  1929. ## Frees a NULL terminated cstringArray.
  1930. var i = 0
  1931. while a[i] != nil:
  1932. dealloc(a[i])
  1933. inc(i)
  1934. dealloc(a)
  1935. when notJSnotNims:
  1936. type
  1937. PSafePoint = ptr TSafePoint
  1938. TSafePoint {.compilerproc, final.} = object
  1939. prev: PSafePoint # points to next safe point ON THE STACK
  1940. status: int
  1941. context: C_JmpBuf
  1942. SafePoint = TSafePoint
  1943. when not defined(js):
  1944. when declared(initAllocator):
  1945. initAllocator()
  1946. when hasThreadSupport:
  1947. when hostOS != "standalone": include "system/threads"
  1948. elif not defined(nogc) and not defined(nimscript):
  1949. when not defined(useNimRtl) and not defined(createNimRtl): initStackBottom()
  1950. when declared(initGC): initGC()
  1951. when notJSnotNims:
  1952. proc setControlCHook*(hook: proc () {.noconv.})
  1953. ## Allows you to override the behaviour of your application when CTRL+C
  1954. ## is pressed. Only one such hook is supported.
  1955. when not defined(noSignalHandler) and not defined(useNimRtl):
  1956. proc unsetControlCHook*()
  1957. ## Reverts a call to setControlCHook.
  1958. when hostOS != "standalone":
  1959. proc getStackTrace*(): string {.gcsafe.}
  1960. ## Gets the current stack trace. This only works for debug builds.
  1961. proc getStackTrace*(e: ref Exception): string {.gcsafe.}
  1962. ## Gets the stack trace associated with `e`, which is the stack that
  1963. ## lead to the ``raise`` statement. This only works for debug builds.
  1964. {.push stackTrace: off, profiler: off.}
  1965. when defined(memtracker):
  1966. include "system/memtracker"
  1967. when hostOS == "standalone":
  1968. include "system/embedded"
  1969. else:
  1970. include "system/excpt"
  1971. include "system/chcks"
  1972. # we cannot compile this with stack tracing on
  1973. # as it would recurse endlessly!
  1974. when defined(nimNewIntegerOps):
  1975. include "system/integerops"
  1976. else:
  1977. include "system/arithm"
  1978. {.pop.}
  1979. when not defined(js):
  1980. # this is a hack: without this when statement, you would get:
  1981. # Error: system module needs: nimGCvisit
  1982. {.pop.} # stackTrace: off, profiler: off
  1983. when notJSnotNims:
  1984. when hostOS != "standalone" and hostOS != "any":
  1985. include "system/dyncalls"
  1986. include "system/sets"
  1987. when defined(gogc):
  1988. const GenericSeqSize = (3 * sizeof(int))
  1989. else:
  1990. const GenericSeqSize = (2 * sizeof(int))
  1991. proc getDiscriminant(aa: pointer, n: ptr TNimNode): uint =
  1992. sysAssert(n.kind == nkCase, "getDiscriminant: node != nkCase")
  1993. var d: uint
  1994. var a = cast[uint](aa)
  1995. case n.typ.size
  1996. of 1: d = uint(cast[ptr uint8](a + uint(n.offset))[])
  1997. of 2: d = uint(cast[ptr uint16](a + uint(n.offset))[])
  1998. of 4: d = uint(cast[ptr uint32](a + uint(n.offset))[])
  1999. of 8: d = uint(cast[ptr uint64](a + uint(n.offset))[])
  2000. else:
  2001. d = 0'u
  2002. sysAssert(false, "getDiscriminant: invalid n.typ.size")
  2003. return d
  2004. proc selectBranch(aa: pointer, n: ptr TNimNode): ptr TNimNode =
  2005. var discr = getDiscriminant(aa, n)
  2006. if discr < cast[uint](n.len):
  2007. result = n.sons[discr]
  2008. if result == nil: result = n.sons[n.len]
  2009. # n.sons[n.len] contains the ``else`` part (but may be nil)
  2010. else:
  2011. result = n.sons[n.len]
  2012. when notJSnotNims and hasAlloc:
  2013. {.push profiler: off.}
  2014. include "system/mmdisp"
  2015. {.pop.}
  2016. {.push stackTrace: off, profiler: off.}
  2017. when not defined(nimSeqsV2):
  2018. include "system/sysstr"
  2019. {.pop.}
  2020. include "system/strmantle"
  2021. include "system/assign"
  2022. when not defined(nimV2):
  2023. include "system/repr"
  2024. when notJSnotNims and hasThreadSupport and hostOS != "standalone":
  2025. include "system/channels"
  2026. when notJSnotNims and hostOS != "standalone":
  2027. proc getCurrentException*(): ref Exception {.compilerRtl, inl, benign.} =
  2028. ## Retrieves the current exception; if there is none, `nil` is returned.
  2029. result = currException
  2030. proc nimBorrowCurrentException(): ref Exception {.compilerRtl, inl, benign, nodestroy.} =
  2031. # .nodestroy here so that we do not produce a write barrier as the
  2032. # C codegen only uses it in a borrowed way:
  2033. result = currException
  2034. proc getCurrentExceptionMsg*(): string {.inline, benign.} =
  2035. ## Retrieves the error message that was attached to the current
  2036. ## exception; if there is none, `""` is returned.
  2037. return if currException == nil: "" else: currException.msg
  2038. proc setCurrentException*(exc: ref Exception) {.inline, benign.} =
  2039. ## Sets the current exception.
  2040. ##
  2041. ## **Warning**: Only use this if you know what you are doing.
  2042. currException = exc
  2043. elif defined(nimscript):
  2044. proc getCurrentException*(): ref Exception {.compilerRtl.} = discard
  2045. when notJSnotNims:
  2046. {.push stackTrace: off, profiler: off.}
  2047. when (defined(profiler) or defined(memProfiler)):
  2048. include "system/profiler"
  2049. {.pop.}
  2050. proc rawProc*[T: proc](x: T): pointer {.noSideEffect, inline.} =
  2051. ## Retrieves the raw proc pointer of the closure `x`. This is
  2052. ## useful for interfacing closures with C.
  2053. {.emit: """
  2054. `result` = `x`.ClP_0;
  2055. """.}
  2056. proc rawEnv*[T: proc](x: T): pointer {.noSideEffect, inline.} =
  2057. ## Retrieves the raw environment pointer of the closure `x`. This is
  2058. ## useful for interfacing closures with C.
  2059. {.emit: """
  2060. `result` = `x`.ClE_0;
  2061. """.}
  2062. proc finished*[T: proc](x: T): bool {.noSideEffect, inline.} =
  2063. ## can be used to determine if a first class iterator has finished.
  2064. {.emit: """
  2065. `result` = ((NI*) `x`.ClE_0)[1] < 0;
  2066. """.}
  2067. when defined(js):
  2068. when not defined(nimscript):
  2069. include "system/jssys"
  2070. include "system/reprjs"
  2071. else:
  2072. proc cmp(x, y: string): int =
  2073. if x == y: return 0
  2074. if x < y: return -1
  2075. return 1
  2076. when defined(js) or defined(nimscript):
  2077. proc addInt*(result: var string; x: int64) =
  2078. result.add $x
  2079. proc addFloat*(result: var string; x: float) =
  2080. result.add $x
  2081. proc quit*(errormsg: string, errorcode = QuitFailure) {.noreturn.} =
  2082. ## A shorthand for ``echo(errormsg); quit(errorcode)``.
  2083. when defined(nimscript) or defined(js) or (hostOS == "standalone"):
  2084. echo errormsg
  2085. else:
  2086. when nimvm:
  2087. echo errormsg
  2088. else:
  2089. cstderr.rawWrite(errormsg)
  2090. cstderr.rawWrite("\n")
  2091. quit(errorcode)
  2092. {.pop.} # checks: off
  2093. {.pop.} # hints: off
  2094. proc `/`*(x, y: int): float {.inline, noSideEffect.} =
  2095. ## Division of integers that results in a float.
  2096. ##
  2097. ## See also:
  2098. ## * `div <#div,int,int>`_
  2099. ## * `mod <#mod,int,int>`_
  2100. ##
  2101. ## .. code-block:: Nim
  2102. ## echo 7 / 5 # => 1.4
  2103. result = toFloat(x) / toFloat(y)
  2104. type
  2105. BackwardsIndex* = distinct int ## Type that is constructed by ``^`` for
  2106. ## reversed array accesses.
  2107. ## (See `^ template <#^.t,int>`_)
  2108. template `^`*(x: int): BackwardsIndex = BackwardsIndex(x)
  2109. ## Builtin `roof`:idx: operator that can be used for convenient array access.
  2110. ## ``a[^x]`` is a shortcut for ``a[a.len-x]``.
  2111. ##
  2112. ## .. code-block:: Nim
  2113. ## let
  2114. ## a = [1, 3, 5, 7, 9]
  2115. ## b = "abcdefgh"
  2116. ##
  2117. ## echo a[^1] # => 9
  2118. ## echo b[^2] # => g
  2119. template `..^`*(a, b: untyped): untyped =
  2120. ## A shortcut for `.. ^` to avoid the common gotcha that a space between
  2121. ## '..' and '^' is required.
  2122. a .. ^b
  2123. template `..<`*(a, b: untyped): untyped =
  2124. ## A shortcut for `a .. pred(b)`.
  2125. ##
  2126. ## .. code-block:: Nim
  2127. ## for i in 5 ..< 9:
  2128. ## echo i # => 5; 6; 7; 8
  2129. a .. (when b is BackwardsIndex: succ(b) else: pred(b))
  2130. template spliceImpl(s, a, L, b: untyped): untyped =
  2131. # make room for additional elements or cut:
  2132. var shift = b.len - max(0,L) # ignore negative slice size
  2133. var newLen = s.len + shift
  2134. if shift > 0:
  2135. # enlarge:
  2136. setLen(s, newLen)
  2137. for i in countdown(newLen-1, a+b.len): movingCopy(s[i], s[i-shift])
  2138. else:
  2139. for i in countup(a+b.len, newLen-1): movingCopy(s[i], s[i-shift])
  2140. # cut down:
  2141. setLen(s, newLen)
  2142. # fill the hole:
  2143. for i in 0 ..< b.len: s[a+i] = b[i]
  2144. template `^^`(s, i: untyped): untyped =
  2145. (when i is BackwardsIndex: s.len - int(i) else: int(i))
  2146. template `[]`*(s: string; i: int): char = arrGet(s, i)
  2147. template `[]=`*(s: string; i: int; val: char) = arrPut(s, i, val)
  2148. proc `[]`*[T, U](s: string, x: HSlice[T, U]): string {.inline.} =
  2149. ## Slice operation for strings.
  2150. ## Returns the inclusive range `[s[x.a], s[x.b]]`:
  2151. ##
  2152. ## .. code-block:: Nim
  2153. ## var s = "abcdef"
  2154. ## assert s[1..3] == "bcd"
  2155. let a = s ^^ x.a
  2156. let L = (s ^^ x.b) - a + 1
  2157. result = newString(L)
  2158. for i in 0 ..< L: result[i] = s[i + a]
  2159. proc `[]=`*[T, U](s: var string, x: HSlice[T, U], b: string) =
  2160. ## Slice assignment for strings.
  2161. ##
  2162. ## If ``b.len`` is not exactly the number of elements that are referred to
  2163. ## by `x`, a `splice`:idx: is performed:
  2164. ##
  2165. runnableExamples:
  2166. var s = "abcdefgh"
  2167. s[1 .. ^2] = "xyz"
  2168. assert s == "axyzh"
  2169. var a = s ^^ x.a
  2170. var L = (s ^^ x.b) - a + 1
  2171. if L == b.len:
  2172. for i in 0..<L: s[i+a] = b[i]
  2173. else:
  2174. spliceImpl(s, a, L, b)
  2175. proc `[]`*[Idx, T, U, V](a: array[Idx, T], x: HSlice[U, V]): seq[T] =
  2176. ## Slice operation for arrays.
  2177. ## Returns the inclusive range `[a[x.a], a[x.b]]`:
  2178. ##
  2179. ## .. code-block:: Nim
  2180. ## var a = [1, 2, 3, 4]
  2181. ## assert a[0..2] == @[1, 2, 3]
  2182. let xa = a ^^ x.a
  2183. let L = (a ^^ x.b) - xa + 1
  2184. result = newSeq[T](L)
  2185. for i in 0..<L: result[i] = a[Idx(i + xa)]
  2186. proc `[]=`*[Idx, T, U, V](a: var array[Idx, T], x: HSlice[U, V], b: openArray[T]) =
  2187. ## Slice assignment for arrays.
  2188. ##
  2189. ## .. code-block:: Nim
  2190. ## var a = [10, 20, 30, 40, 50]
  2191. ## a[1..2] = @[99, 88]
  2192. ## assert a == [10, 99, 88, 40, 50]
  2193. let xa = a ^^ x.a
  2194. let L = (a ^^ x.b) - xa + 1
  2195. if L == b.len:
  2196. for i in 0..<L: a[Idx(i + xa)] = b[i]
  2197. else:
  2198. sysFatal(RangeDefect, "different lengths for slice assignment")
  2199. proc `[]`*[T, U, V](s: openArray[T], x: HSlice[U, V]): seq[T] =
  2200. ## Slice operation for sequences.
  2201. ## Returns the inclusive range `[s[x.a], s[x.b]]`:
  2202. ##
  2203. ## .. code-block:: Nim
  2204. ## var s = @[1, 2, 3, 4]
  2205. ## assert s[0..2] == @[1, 2, 3]
  2206. let a = s ^^ x.a
  2207. let L = (s ^^ x.b) - a + 1
  2208. newSeq(result, L)
  2209. for i in 0 ..< L: result[i] = s[i + a]
  2210. proc `[]=`*[T, U, V](s: var seq[T], x: HSlice[U, V], b: openArray[T]) =
  2211. ## Slice assignment for sequences.
  2212. ##
  2213. ## If ``b.len`` is not exactly the number of elements that are referred to
  2214. ## by `x`, a `splice`:idx: is performed.
  2215. runnableExamples:
  2216. var s = @"abcdefgh"
  2217. s[1 .. ^2] = @"xyz"
  2218. assert s == @"axyzh"
  2219. let a = s ^^ x.a
  2220. let L = (s ^^ x.b) - a + 1
  2221. if L == b.len:
  2222. for i in 0 ..< L: s[i+a] = b[i]
  2223. else:
  2224. spliceImpl(s, a, L, b)
  2225. proc `[]`*[T](s: openArray[T]; i: BackwardsIndex): T {.inline.} =
  2226. system.`[]`(s, s.len - int(i))
  2227. proc `[]`*[Idx, T](a: array[Idx, T]; i: BackwardsIndex): T {.inline.} =
  2228. a[Idx(a.len - int(i) + int low(a))]
  2229. proc `[]`*(s: string; i: BackwardsIndex): char {.inline.} = s[s.len - int(i)]
  2230. proc `[]`*[T](s: var openArray[T]; i: BackwardsIndex): var T {.inline.} =
  2231. system.`[]`(s, s.len - int(i))
  2232. proc `[]`*[Idx, T](a: var array[Idx, T]; i: BackwardsIndex): var T {.inline.} =
  2233. a[Idx(a.len - int(i) + int low(a))]
  2234. proc `[]`*(s: var string; i: BackwardsIndex): var char {.inline.} = s[s.len - int(i)]
  2235. proc `[]=`*[T](s: var openArray[T]; i: BackwardsIndex; x: T) {.inline.} =
  2236. system.`[]=`(s, s.len - int(i), x)
  2237. proc `[]=`*[Idx, T](a: var array[Idx, T]; i: BackwardsIndex; x: T) {.inline.} =
  2238. a[Idx(a.len - int(i) + int low(a))] = x
  2239. proc `[]=`*(s: var string; i: BackwardsIndex; x: char) {.inline.} =
  2240. s[s.len - int(i)] = x
  2241. proc slurp*(filename: string): string {.magic: "Slurp".}
  2242. ## This is an alias for `staticRead <#staticRead,string>`_.
  2243. proc staticRead*(filename: string): string {.magic: "Slurp".}
  2244. ## Compile-time `readFile <io.html#readFile,string>`_ proc for easy
  2245. ## `resource`:idx: embedding:
  2246. ##
  2247. ## The maximum file size limit that ``staticRead`` and ``slurp`` can read is
  2248. ## near or equal to the *free* memory of the device you are using to compile.
  2249. ##
  2250. ## .. code-block:: Nim
  2251. ## const myResource = staticRead"mydatafile.bin"
  2252. ##
  2253. ## `slurp <#slurp,string>`_ is an alias for ``staticRead``.
  2254. proc gorge*(command: string, input = "", cache = ""): string {.
  2255. magic: "StaticExec".} = discard
  2256. ## This is an alias for `staticExec <#staticExec,string,string,string>`_.
  2257. proc staticExec*(command: string, input = "", cache = ""): string {.
  2258. magic: "StaticExec".} = discard
  2259. ## Executes an external process at compile-time and returns its text output
  2260. ## (stdout + stderr).
  2261. ##
  2262. ## If `input` is not an empty string, it will be passed as a standard input
  2263. ## to the executed program.
  2264. ##
  2265. ## .. code-block:: Nim
  2266. ## const buildInfo = "Revision " & staticExec("git rev-parse HEAD") &
  2267. ## "\nCompiled on " & staticExec("uname -v")
  2268. ##
  2269. ## `gorge <#gorge,string,string,string>`_ is an alias for ``staticExec``.
  2270. ##
  2271. ## Note that you can use this proc inside a pragma like
  2272. ## `passc <manual.html#implementation-specific-pragmas-passc-pragma>`_ or
  2273. ## `passl <manual.html#implementation-specific-pragmas-passl-pragma>`_.
  2274. ##
  2275. ## If ``cache`` is not empty, the results of ``staticExec`` are cached within
  2276. ## the ``nimcache`` directory. Use ``--forceBuild`` to get rid of this caching
  2277. ## behaviour then. ``command & input & cache`` (the concatenated string) is
  2278. ## used to determine whether the entry in the cache is still valid. You can
  2279. ## use versioning information for ``cache``:
  2280. ##
  2281. ## .. code-block:: Nim
  2282. ## const stateMachine = staticExec("dfaoptimizer", "input", "0.8.0")
  2283. proc gorgeEx*(command: string, input = "", cache = ""): tuple[output: string,
  2284. exitCode: int] =
  2285. ## Similar to `gorge <#gorge,string,string,string>`_ but also returns the
  2286. ## precious exit code.
  2287. discard
  2288. proc `+=`*[T: float|float32|float64] (x: var T, y: T) {.
  2289. inline, noSideEffect.} =
  2290. ## Increments in place a floating point number.
  2291. x = x + y
  2292. proc `-=`*[T: float|float32|float64] (x: var T, y: T) {.
  2293. inline, noSideEffect.} =
  2294. ## Decrements in place a floating point number.
  2295. x = x - y
  2296. proc `*=`*[T: float|float32|float64] (x: var T, y: T) {.
  2297. inline, noSideEffect.} =
  2298. ## Multiplies in place a floating point number.
  2299. x = x * y
  2300. proc `/=`*(x: var float64, y: float64) {.inline, noSideEffect.} =
  2301. ## Divides in place a floating point number.
  2302. x = x / y
  2303. proc `/=`*[T: float|float32](x: var T, y: T) {.inline, noSideEffect.} =
  2304. ## Divides in place a floating point number.
  2305. x = x / y
  2306. proc `&=`*(x: var string, y: string) {.magic: "AppendStrStr", noSideEffect.}
  2307. ## Appends in place to a string.
  2308. ##
  2309. ## .. code-block:: Nim
  2310. ## var a = "abc"
  2311. ## a &= "de" # a <- "abcde"
  2312. template `&=`*(x, y: typed) =
  2313. ## Generic 'sink' operator for Nim.
  2314. ##
  2315. ## For files an alias for ``write``.
  2316. ## If not specialized further, an alias for ``add``.
  2317. add(x, y)
  2318. when declared(File):
  2319. template `&=`*(f: File, x: typed) = write(f, x)
  2320. template currentSourcePath*: string = instantiationInfo(-1, true).filename
  2321. ## Returns the full file-system path of the current source.
  2322. ##
  2323. ## To get the directory containing the current source, use it with
  2324. ## `os.parentDir() <os.html#parentDir%2Cstring>`_ as ``currentSourcePath.parentDir()``.
  2325. ##
  2326. ## The path returned by this template is set at compile time.
  2327. ##
  2328. ## See the docstring of `macros.getProjectPath() <macros.html#getProjectPath>`_
  2329. ## for an example to see the distinction between the ``currentSourcePath``
  2330. ## and ``getProjectPath``.
  2331. ##
  2332. ## See also:
  2333. ## * `getCurrentDir proc <os.html#getCurrentDir>`_
  2334. when compileOption("rangechecks"):
  2335. template rangeCheck*(cond) =
  2336. ## Helper for performing user-defined range checks.
  2337. ## Such checks will be performed only when the ``rangechecks``
  2338. ## compile-time option is enabled.
  2339. if not cond: sysFatal(RangeDefect, "range check failed")
  2340. else:
  2341. template rangeCheck*(cond) = discard
  2342. when not defined(nimhygiene):
  2343. {.pragma: inject.}
  2344. proc shallow*[T](s: var seq[T]) {.noSideEffect, inline.} =
  2345. ## Marks a sequence `s` as `shallow`:idx:. Subsequent assignments will not
  2346. ## perform deep copies of `s`.
  2347. ##
  2348. ## This is only useful for optimization purposes.
  2349. if s.len == 0: return
  2350. when not defined(js) and not defined(nimscript) and not defined(nimSeqsV2):
  2351. var s = cast[PGenericSeq](s)
  2352. s.reserved = s.reserved or seqShallowFlag
  2353. proc shallow*(s: var string) {.noSideEffect, inline.} =
  2354. ## Marks a string `s` as `shallow`:idx:. Subsequent assignments will not
  2355. ## perform deep copies of `s`.
  2356. ##
  2357. ## This is only useful for optimization purposes.
  2358. when not defined(js) and not defined(nimscript) and not defined(nimSeqsV2):
  2359. var s = cast[PGenericSeq](s)
  2360. if s == nil:
  2361. s = cast[PGenericSeq](newString(0))
  2362. # string literals cannot become 'shallow':
  2363. if (s.reserved and strlitFlag) == 0:
  2364. s.reserved = s.reserved or seqShallowFlag
  2365. type
  2366. NimNodeObj = object
  2367. NimNode* {.magic: "PNimrodNode".} = ref NimNodeObj
  2368. ## Represents a Nim AST node. Macros operate on this type.
  2369. when defined(nimV2):
  2370. import system/repr_v2
  2371. export repr_v2
  2372. macro varargsLen*(x: varargs[untyped]): int {.since: (1, 1).} =
  2373. ## returns number of variadic arguments in `x`
  2374. proc varargsLenImpl(x: NimNode): NimNode {.magic: "LengthOpenArray", noSideEffect.}
  2375. varargsLenImpl(x)
  2376. when false:
  2377. template eval*(blk: typed): typed =
  2378. ## Executes a block of code at compile time just as if it was a macro.
  2379. ##
  2380. ## Optionally, the block can return an AST tree that will replace the
  2381. ## eval expression.
  2382. macro payload: typed {.gensym.} = blk
  2383. payload()
  2384. when hasAlloc or defined(nimscript):
  2385. proc insert*(x: var string, item: string, i = 0.Natural) {.noSideEffect.} =
  2386. ## Inserts `item` into `x` at position `i`.
  2387. ##
  2388. ## .. code-block:: Nim
  2389. ## var a = "abc"
  2390. ## a.insert("zz", 0) # a <- "zzabc"
  2391. var xl = x.len
  2392. setLen(x, xl+item.len)
  2393. var j = xl-1
  2394. while j >= i:
  2395. shallowCopy(x[j+item.len], x[j])
  2396. dec(j)
  2397. j = 0
  2398. while j < item.len:
  2399. x[j+i] = item[j]
  2400. inc(j)
  2401. when declared(initDebugger):
  2402. initDebugger()
  2403. proc addEscapedChar*(s: var string, c: char) {.noSideEffect, inline.} =
  2404. ## Adds a char to string `s` and applies the following escaping:
  2405. ##
  2406. ## * replaces any ``\`` by ``\\``
  2407. ## * replaces any ``'`` by ``\'``
  2408. ## * replaces any ``"`` by ``\"``
  2409. ## * replaces any ``\a`` by ``\\a``
  2410. ## * replaces any ``\b`` by ``\\b``
  2411. ## * replaces any ``\t`` by ``\\t``
  2412. ## * replaces any ``\n`` by ``\\n``
  2413. ## * replaces any ``\v`` by ``\\v``
  2414. ## * replaces any ``\f`` by ``\\f``
  2415. ## * replaces any ``\c`` by ``\\c``
  2416. ## * replaces any ``\e`` by ``\\e``
  2417. ## * replaces any other character not in the set ``{'\21..'\126'}
  2418. ## by ``\xHH`` where ``HH`` is its hexadecimal value.
  2419. ##
  2420. ## The procedure has been designed so that its output is usable for many
  2421. ## different common syntaxes.
  2422. ##
  2423. ## **Note**: This is **not correct** for producing Ansi C code!
  2424. case c
  2425. of '\a': s.add "\\a" # \x07
  2426. of '\b': s.add "\\b" # \x08
  2427. of '\t': s.add "\\t" # \x09
  2428. of '\L': s.add "\\n" # \x0A
  2429. of '\v': s.add "\\v" # \x0B
  2430. of '\f': s.add "\\f" # \x0C
  2431. of '\c': s.add "\\c" # \x0D
  2432. of '\e': s.add "\\e" # \x1B
  2433. of '\\': s.add("\\\\")
  2434. of '\'': s.add("\\'")
  2435. of '\"': s.add("\\\"")
  2436. of {'\32'..'\126'} - {'\\', '\'', '\"'}: s.add(c)
  2437. else:
  2438. s.add("\\x")
  2439. const HexChars = "0123456789ABCDEF"
  2440. let n = ord(c)
  2441. s.add(HexChars[int((n and 0xF0) shr 4)])
  2442. s.add(HexChars[int(n and 0xF)])
  2443. proc addQuoted*[T](s: var string, x: T) =
  2444. ## Appends `x` to string `s` in place, applying quoting and escaping
  2445. ## if `x` is a string or char.
  2446. ##
  2447. ## See `addEscapedChar <#addEscapedChar,string,char>`_
  2448. ## for the escaping scheme. When `x` is a string, characters in the
  2449. ## range ``{\128..\255}`` are never escaped so that multibyte UTF-8
  2450. ## characters are untouched (note that this behavior is different from
  2451. ## ``addEscapedChar``).
  2452. ##
  2453. ## The Nim standard library uses this function on the elements of
  2454. ## collections when producing a string representation of a collection.
  2455. ## It is recommended to use this function as well for user-side collections.
  2456. ## Users may overload `addQuoted` for custom (string-like) types if
  2457. ## they want to implement a customized element representation.
  2458. ##
  2459. ## .. code-block:: Nim
  2460. ## var tmp = ""
  2461. ## tmp.addQuoted(1)
  2462. ## tmp.add(", ")
  2463. ## tmp.addQuoted("string")
  2464. ## tmp.add(", ")
  2465. ## tmp.addQuoted('c')
  2466. ## assert(tmp == """1, "string", 'c'""")
  2467. when T is string or T is cstring:
  2468. s.add("\"")
  2469. for c in x:
  2470. # Only ASCII chars are escaped to avoid butchering
  2471. # multibyte UTF-8 characters.
  2472. if c <= 127.char:
  2473. s.addEscapedChar(c)
  2474. else:
  2475. s.add c
  2476. s.add("\"")
  2477. elif T is char:
  2478. s.add("'")
  2479. s.addEscapedChar(x)
  2480. s.add("'")
  2481. # prevent temporary string allocation
  2482. elif T is SomeSignedInt:
  2483. s.addInt(x)
  2484. elif T is SomeFloat:
  2485. s.addFloat(x)
  2486. elif compiles(s.add(x)):
  2487. s.add(x)
  2488. else:
  2489. s.add($x)
  2490. proc locals*(): RootObj {.magic: "Plugin", noSideEffect.} =
  2491. ## Generates a tuple constructor expression listing all the local variables
  2492. ## in the current scope.
  2493. ##
  2494. ## This is quite fast as it does not rely
  2495. ## on any debug or runtime information. Note that in contrast to what
  2496. ## the official signature says, the return type is *not* ``RootObj`` but a
  2497. ## tuple of a structure that depends on the current scope. Example:
  2498. ##
  2499. ## .. code-block:: Nim
  2500. ## proc testLocals() =
  2501. ## var
  2502. ## a = "something"
  2503. ## b = 4
  2504. ## c = locals()
  2505. ## d = "super!"
  2506. ##
  2507. ## b = 1
  2508. ## for name, value in fieldPairs(c):
  2509. ## echo "name ", name, " with value ", value
  2510. ## echo "B is ", b
  2511. ## # -> name a with value something
  2512. ## # -> name b with value 4
  2513. ## # -> B is 1
  2514. discard
  2515. when hasAlloc and notJSnotNims:
  2516. # XXX how to implement 'deepCopy' is an open problem.
  2517. proc deepCopy*[T](x: var T, y: T) {.noSideEffect, magic: "DeepCopy".} =
  2518. ## Performs a deep copy of `y` and copies it into `x`.
  2519. ##
  2520. ## This is also used by the code generator
  2521. ## for the implementation of ``spawn``.
  2522. ##
  2523. ## For ``--gc:arc`` or ``--gc:orc`` deepcopy support has to be enabled
  2524. ## via ``--deepcopy:on``.
  2525. discard
  2526. proc deepCopy*[T](y: T): T =
  2527. ## Convenience wrapper around `deepCopy` overload.
  2528. deepCopy(result, y)
  2529. include "system/deepcopy"
  2530. proc procCall*(x: untyped) {.magic: "ProcCall", compileTime.} =
  2531. ## Special magic to prohibit dynamic binding for `method`:idx: calls.
  2532. ## This is similar to `super`:idx: in ordinary OO languages.
  2533. ##
  2534. ## .. code-block:: Nim
  2535. ## # 'someMethod' will be resolved fully statically:
  2536. ## procCall someMethod(a, b)
  2537. discard
  2538. proc `==`*(x, y: cstring): bool {.magic: "EqCString", noSideEffect,
  2539. inline.} =
  2540. ## Checks for equality between two `cstring` variables.
  2541. proc strcmp(a, b: cstring): cint {.noSideEffect,
  2542. importc, header: "<string.h>".}
  2543. if pointer(x) == pointer(y): result = true
  2544. elif x.isNil or y.isNil: result = false
  2545. else: result = strcmp(x, y) == 0
  2546. when defined(nimNoNilSeqs2) and not compileOption("nilseqs"):
  2547. when defined(nimHasUserErrors):
  2548. # bug #9149; ensure that 'type(nil)' does not match *too* well by using 'type(nil) | type(nil)'.
  2549. # Eventually (in 0.20?) we will be able to remove this hack completely.
  2550. proc `==`*(x: string; y: type(nil) | type(nil)): bool {.
  2551. error: "'nil' is now invalid for 'string'; compile with --nilseqs:on for a migration period".} =
  2552. discard
  2553. proc `==`*(x: type(nil) | type(nil); y: string): bool {.
  2554. error: "'nil' is now invalid for 'string'; compile with --nilseqs:on for a migration period".} =
  2555. discard
  2556. else:
  2557. proc `==`*(x: string; y: type(nil) | type(nil)): bool {.error.} = discard
  2558. proc `==`*(x: type(nil) | type(nil); y: string): bool {.error.} = discard
  2559. template closureScope*(body: untyped): untyped =
  2560. ## Useful when creating a closure in a loop to capture local loop variables by
  2561. ## their current iteration values.
  2562. ##
  2563. ## Note: This template may not work in some cases, use
  2564. ## `capture <sugar.html#capture.m,openArray[typed],untyped>`_ instead.
  2565. ##
  2566. ## Example:
  2567. ##
  2568. ## .. code-block:: Nim
  2569. ## var myClosure : proc()
  2570. ## # without closureScope:
  2571. ## for i in 0 .. 5:
  2572. ## let j = i
  2573. ## if j == 3:
  2574. ## myClosure = proc() = echo j
  2575. ## myClosure() # outputs 5. `j` is changed after closure creation
  2576. ## # with closureScope:
  2577. ## for i in 0 .. 5:
  2578. ## closureScope: # Everything in this scope is locked after closure creation
  2579. ## let j = i
  2580. ## if j == 3:
  2581. ## myClosure = proc() = echo j
  2582. ## myClosure() # outputs 3
  2583. (proc() = body)()
  2584. template once*(body: untyped): untyped =
  2585. ## Executes a block of code only once (the first time the block is reached).
  2586. ##
  2587. ## .. code-block:: Nim
  2588. ##
  2589. ## proc draw(t: Triangle) =
  2590. ## once:
  2591. ## graphicsInit()
  2592. ## line(t.p1, t.p2)
  2593. ## line(t.p2, t.p3)
  2594. ## line(t.p3, t.p1)
  2595. ##
  2596. var alreadyExecuted {.global.} = false
  2597. if not alreadyExecuted:
  2598. alreadyExecuted = true
  2599. body
  2600. {.pop.} # warning[GcMem]: off, warning[Uninit]: off
  2601. proc substr*(s: string, first, last: int): string =
  2602. ## Copies a slice of `s` into a new string and returns this new
  2603. ## string.
  2604. ##
  2605. ## The bounds `first` and `last` denote the indices of
  2606. ## the first and last characters that shall be copied. If ``last``
  2607. ## is omitted, it is treated as ``high(s)``. If ``last >= s.len``, ``s.len``
  2608. ## is used instead: This means ``substr`` can also be used to `cut`:idx:
  2609. ## or `limit`:idx: a string's length.
  2610. runnableExamples:
  2611. let a = "abcdefgh"
  2612. assert a.substr(2, 5) == "cdef"
  2613. assert a.substr(2) == "cdefgh"
  2614. assert a.substr(5, 99) == "fgh"
  2615. let first = max(first, 0)
  2616. let L = max(min(last, high(s)) - first + 1, 0)
  2617. result = newString(L)
  2618. for i in 0 .. L-1:
  2619. result[i] = s[i+first]
  2620. proc substr*(s: string, first = 0): string =
  2621. result = substr(s, first, high(s))
  2622. when defined(nimconfig):
  2623. include "system/nimscript"
  2624. when not defined(js):
  2625. proc toOpenArray*[T](x: ptr UncheckedArray[T]; first, last: int): openArray[T] {.
  2626. magic: "Slice".}
  2627. when defined(nimToOpenArrayCString):
  2628. proc toOpenArray*(x: cstring; first, last: int): openArray[char] {.
  2629. magic: "Slice".}
  2630. proc toOpenArrayByte*(x: cstring; first, last: int): openArray[byte] {.
  2631. magic: "Slice".}
  2632. proc toOpenArray*[T](x: seq[T]; first, last: int): openArray[T] {.
  2633. magic: "Slice".}
  2634. proc toOpenArray*[T](x: openArray[T]; first, last: int): openArray[T] {.
  2635. magic: "Slice".}
  2636. proc toOpenArray*[I, T](x: array[I, T]; first, last: I): openArray[T] {.
  2637. magic: "Slice".}
  2638. proc toOpenArray*(x: string; first, last: int): openArray[char] {.
  2639. magic: "Slice".}
  2640. proc toOpenArrayByte*(x: string; first, last: int): openArray[byte] {.
  2641. magic: "Slice".}
  2642. proc toOpenArrayByte*(x: openArray[char]; first, last: int): openArray[byte] {.
  2643. magic: "Slice".}
  2644. proc toOpenArrayByte*(x: seq[char]; first, last: int): openArray[byte] {.
  2645. magic: "Slice".}
  2646. type
  2647. ForLoopStmt* {.compilerproc.} = object ## \
  2648. ## A special type that marks a macro as a `for-loop macro`:idx:.
  2649. ## See `"For Loop Macro" <manual.html#macros-for-loop-macro>`_.
  2650. when defined(genode):
  2651. var componentConstructHook*: proc (env: GenodeEnv) {.nimcall.}
  2652. ## Hook into the Genode component bootstrap process.
  2653. ##
  2654. ## This hook is called after all globals are initialized.
  2655. ## When this hook is set the component will not automatically exit,
  2656. ## call ``quit`` explicitly to do so. This is the only available method
  2657. ## of accessing the initial Genode environment.
  2658. proc nim_component_construct(env: GenodeEnv) {.exportc.} =
  2659. ## Procedure called during ``Component::construct`` by the loader.
  2660. if componentConstructHook.isNil:
  2661. env.quit(programResult)
  2662. # No native Genode application initialization,
  2663. # exit as would POSIX.
  2664. else:
  2665. componentConstructHook(env)
  2666. # Perform application initialization
  2667. # and return to thread entrypoint.
  2668. import system/widestrs
  2669. export widestrs
  2670. import system/io
  2671. export io
  2672. when not defined(createNimHcr) and not defined(nimscript):
  2673. include nimhcr