system.nim 107 KB

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