system.nim 104 KB

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