system.nim 107 KB

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