system.nim 152 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899
  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. ## Each module implicitly imports the System module; it must not be listed
  13. ## explicitly. Because of this there cannot be a user-defined module named
  14. ## ``system``.
  15. ##
  16. ## Module system
  17. ## =============
  18. ##
  19. # That lonesome header above is to prevent :idx: entries from being mentioned
  20. # in the global index as part of the previous header (Exception hierarchy).
  21. type
  22. int* {.magic: Int.} ## default integer type; bitwidth depends on
  23. ## architecture, but is always the same as a pointer
  24. int8* {.magic: Int8.} ## signed 8 bit integer type
  25. int16* {.magic: Int16.} ## signed 16 bit integer type
  26. int32* {.magic: Int32.} ## signed 32 bit integer type
  27. int64* {.magic: Int64.} ## signed 64 bit integer type
  28. uint* {.magic: UInt.} ## unsigned default integer type
  29. uint8* {.magic: UInt8.} ## unsigned 8 bit integer type
  30. uint16* {.magic: UInt16.} ## unsigned 16 bit integer type
  31. uint32* {.magic: UInt32.} ## unsigned 32 bit integer type
  32. uint64* {.magic: UInt64.} ## unsigned 64 bit integer type
  33. float* {.magic: Float.} ## default floating point type
  34. float32* {.magic: Float32.} ## 32 bit floating point type
  35. float64* {.magic: Float.} ## 64 bit floating point type
  36. # 'float64' is now an alias to 'float'; this solves many problems
  37. type # we need to start a new type section here, so that ``0`` can have a type
  38. bool* {.magic: Bool.} = enum ## built-in boolean type
  39. false = 0, true = 1
  40. type
  41. char* {.magic: Char.} ## built-in 8 bit character type (unsigned)
  42. string* {.magic: String.} ## built-in string type
  43. cstring* {.magic: Cstring.} ## built-in cstring (*compatible string*) type
  44. pointer* {.magic: Pointer.} ## built-in pointer type, use the ``addr``
  45. ## operator to get a pointer to a variable
  46. typedesc* {.magic: TypeDesc.} ## meta type to denote a type description
  47. const
  48. on* = true ## alias for ``true``
  49. off* = false ## alias for ``false``
  50. {.push warning[GcMem]: off, warning[Uninit]: off.}
  51. {.push hints: off.}
  52. proc `or` *(a, b: typedesc): typedesc {.magic: "TypeTrait", noSideEffect.}
  53. ## Constructs an `or` meta class
  54. proc `and` *(a, b: typedesc): typedesc {.magic: "TypeTrait", noSideEffect.}
  55. ## Constructs an `and` meta class
  56. proc `not` *(a: typedesc): typedesc {.magic: "TypeTrait", noSideEffect.}
  57. ## Constructs an `not` meta class
  58. type
  59. Ordinal* {.magic: Ordinal.}[T] ## Generic ordinal type. Includes integer,
  60. ## bool, character, and enumeration types
  61. ## as well as their subtypes. Note `uint`
  62. ## and `uint64` are not ordinal types for
  63. ## implementation reasons
  64. `ptr`* {.magic: Pointer.}[T] ## built-in generic untraced pointer type
  65. `ref`* {.magic: Pointer.}[T] ## built-in generic traced pointer type
  66. `nil` {.magic: "Nil".}
  67. expr* {.magic: Expr, deprecated.} ## meta type to denote an expression (for templates)
  68. ## **Deprecated** since version 0.15. Use ``untyped`` instead.
  69. stmt* {.magic: Stmt, deprecated.} ## meta type to denote a statement (for templates)
  70. ## **Deprecated** since version 0.15. Use ``typed`` instead.
  71. void* {.magic: "VoidType".} ## meta type to denote the absence of any type
  72. auto* {.magic: Expr.} ## meta type for automatic type determination
  73. any* = distinct auto ## meta type for any supported type
  74. untyped* {.magic: Expr.} ## meta type to denote an expression that
  75. ## is not resolved (for templates)
  76. typed* {.magic: Stmt.} ## meta type to denote an expression that
  77. ## is resolved (for templates)
  78. SomeSignedInt* = int|int8|int16|int32|int64
  79. ## type class matching all signed integer types
  80. SomeUnsignedInt* = uint|uint8|uint16|uint32|uint64
  81. ## type class matching all unsigned integer types
  82. SomeInteger* = SomeSignedInt|SomeUnsignedInt
  83. ## type class matching all integer types
  84. SomeOrdinal* = int|int8|int16|int32|int64|bool|enum|uint8|uint16|uint32
  85. ## type class matching all ordinal types; however this includes enums with
  86. ## holes.
  87. SomeReal* = float|float32|float64
  88. ## type class matching all floating point number types
  89. SomeNumber* = SomeInteger|SomeReal
  90. ## type class matching all number types
  91. proc defined*(x: untyped): bool {.magic: "Defined", noSideEffect, compileTime.}
  92. ## Special compile-time procedure that checks whether `x` is
  93. ## defined.
  94. ## `x` is an external symbol introduced through the compiler's
  95. ## `-d:x switch <nimc.html#compile-time-symbols>`_ to enable build time
  96. ## conditionals:
  97. ##
  98. ## .. code-block:: Nim
  99. ## when not defined(release):
  100. ## # Do here programmer friendly expensive sanity checks.
  101. ## # Put here the normal code
  102. when defined(nimalias):
  103. {.deprecated: [
  104. TSignedInt: SomeSignedInt,
  105. TUnsignedInt: SomeUnsignedInt,
  106. TInteger: SomeInteger,
  107. TReal: SomeReal,
  108. TNumber: SomeNumber,
  109. TOrdinal: SomeOrdinal].}
  110. proc declared*(x: untyped): bool {.magic: "Defined", noSideEffect, compileTime.}
  111. ## Special compile-time procedure that checks whether `x` is
  112. ## declared. `x` has to be an identifier or a qualified identifier.
  113. ## This can be used to check whether a library provides a certain
  114. ## feature or not:
  115. ##
  116. ## .. code-block:: Nim
  117. ## when not declared(strutils.toUpper):
  118. ## # provide our own toUpper proc here, because strutils is
  119. ## # missing it.
  120. when defined(useNimRtl):
  121. {.deadCodeElim: on.}
  122. proc definedInScope*(x: untyped): bool {.
  123. magic: "DefinedInScope", noSideEffect, deprecated, compileTime.}
  124. ## **Deprecated since version 0.9.6**: Use ``declaredInScope`` instead.
  125. proc declaredInScope*(x: untyped): bool {.
  126. magic: "DefinedInScope", noSideEffect, compileTime.}
  127. ## Special compile-time procedure that checks whether `x` is
  128. ## declared in the current scope. `x` has to be an identifier.
  129. proc `addr`*[T](x: var T): ptr T {.magic: "Addr", noSideEffect.} =
  130. ## Builtin 'addr' operator for taking the address of a memory location.
  131. ## Cannot be overloaded.
  132. ##
  133. ## .. code-block:: nim
  134. ## var
  135. ## buf: seq[char] = @['a','b','c']
  136. ## p: pointer = buf[1].addr
  137. ## echo cast[ptr char](p)[] # b
  138. discard
  139. proc unsafeAddr*[T](x: T): ptr T {.magic: "Addr", noSideEffect.} =
  140. ## Builtin 'addr' operator for taking the address of a memory
  141. ## location. This works even for ``let`` variables or parameters
  142. ## for better interop with C and so it is considered even more
  143. ## unsafe than the ordinary ``addr``. When you use it to write a
  144. ## wrapper for a C library, you should always check that the
  145. ## original library does never write to data behind the pointer that
  146. ## is returned from this procedure.
  147. ## Cannot be overloaded.
  148. discard
  149. proc `type`*(x: untyped): typeDesc {.magic: "TypeOf", noSideEffect, compileTime.} =
  150. ## Builtin 'type' operator for accessing the type of an expression.
  151. ## Cannot be overloaded.
  152. discard
  153. proc `not` *(x: bool): bool {.magic: "Not", noSideEffect.}
  154. ## Boolean not; returns true iff ``x == false``.
  155. proc `and`*(x, y: bool): bool {.magic: "And", noSideEffect.}
  156. ## Boolean ``and``; returns true iff ``x == y == true``.
  157. ## Evaluation is lazy: if ``x`` is false,
  158. ## ``y`` will not even be evaluated.
  159. proc `or`*(x, y: bool): bool {.magic: "Or", noSideEffect.}
  160. ## Boolean ``or``; returns true iff ``not (not x and not y)``.
  161. ## Evaluation is lazy: if ``x`` is true,
  162. ## ``y`` will not even be evaluated.
  163. proc `xor`*(x, y: bool): bool {.magic: "Xor", noSideEffect.}
  164. ## Boolean `exclusive or`; returns true iff ``x != y``.
  165. proc new*[T](a: var ref T) {.magic: "New", noSideEffect.}
  166. ## creates a new object of type ``T`` and returns a safe (traced)
  167. ## reference to it in ``a``.
  168. proc new*(T: typedesc): auto =
  169. ## creates a new object of type ``T`` and returns a safe (traced)
  170. ## reference to it as result value.
  171. ##
  172. ## When ``T`` is a ref type then the resulting type will be ``T``,
  173. ## otherwise it will be ``ref T``.
  174. when (T is ref):
  175. var r: T
  176. else:
  177. var r: ref T
  178. new(r)
  179. return r
  180. proc internalNew*[T](a: var ref T) {.magic: "New", noSideEffect.}
  181. ## leaked implementation detail. Do not use.
  182. proc new*[T](a: var ref T, finalizer: proc (x: ref T) {.nimcall.}) {.
  183. magic: "NewFinalize", noSideEffect.}
  184. ## creates a new object of type ``T`` and returns a safe (traced)
  185. ## reference to it in ``a``. When the garbage collector frees the object,
  186. ## `finalizer` is called. The `finalizer` may not keep a reference to the
  187. ## object pointed to by `x`. The `finalizer` cannot prevent the GC from
  188. ## freeing the object. Note: The `finalizer` refers to the type `T`, not to
  189. ## the object! This means that for each object of type `T` the finalizer
  190. ## will be called!
  191. proc reset*[T](obj: var T) {.magic: "Reset", noSideEffect.}
  192. ## resets an object `obj` to its initial (binary zero) value. This needs to
  193. ## be called before any possible `object branch transition`:idx:.
  194. type
  195. range*{.magic: "Range".}[T] ## Generic type to construct range types.
  196. array*{.magic: "Array".}[I, T] ## Generic type to construct
  197. ## fixed-length arrays.
  198. openArray*{.magic: "OpenArray".}[T] ## Generic type to construct open arrays.
  199. ## Open arrays are implemented as a
  200. ## pointer to the array data and a
  201. ## length field.
  202. varargs*{.magic: "Varargs".}[T] ## Generic type to construct a varargs type.
  203. seq*{.magic: "Seq".}[T] ## Generic type to construct sequences.
  204. set*{.magic: "Set".}[T] ## Generic type to construct bit sets.
  205. UncheckedArray* {.unchecked.}[T] = array[0, T]
  206. ## Array with no bounds checking
  207. proc high*[T: Ordinal](x: T): T {.magic: "High", noSideEffect.}
  208. ## returns the highest possible index of an array, a sequence, a string or
  209. ## the highest possible value of an ordinal value `x`. As a special
  210. ## semantic rule, `x` may also be a type identifier.
  211. ## ``high(int)`` is Nim's way of writing `INT_MAX`:idx: or `MAX_INT`:idx:.
  212. ##
  213. ## .. code-block:: nim
  214. ## var arr = [1,2,3,4,5,6,7]
  215. ## high(arr) #=> 6
  216. ## high(2) #=> 9223372036854775807
  217. ## high(int) #=> 9223372036854775807
  218. proc high*[T: Ordinal](x: typeDesc[T]): T {.magic: "High", noSideEffect.}
  219. proc high*[T](x: openArray[T]): int {.magic: "High", noSideEffect.}
  220. proc high*[I, T](x: array[I, T]): I {.magic: "High", noSideEffect.}
  221. proc high*[I, T](x: typeDesc[array[I, T]]): I {.magic: "High", noSideEffect.}
  222. proc high*(x: cstring): int {.magic: "High", noSideEffect.}
  223. proc high*(x: string): int {.magic: "High", noSideEffect.}
  224. proc low*[T: Ordinal](x: typeDesc[T]): T {.magic: "Low", noSideEffect.}
  225. proc low*[T](x: openArray[T]): int {.magic: "Low", noSideEffect.}
  226. proc low*[I, T](x: array[I, T]): I {.magic: "Low", noSideEffect.}
  227. proc low*[T](x: T): T {.magic: "Low", noSideEffect.}
  228. proc low*[I, T](x: typeDesc[array[I, T]]): I {.magic: "Low", noSideEffect.}
  229. proc low*(x: cstring): int {.magic: "Low", noSideEffect.}
  230. proc low*(x: string): int {.magic: "Low", noSideEffect.}
  231. ## returns the lowest possible index of an array, a sequence, a string or
  232. ## the lowest possible value of an ordinal value `x`. As a special
  233. ## semantic rule, `x` may also be a type identifier.
  234. ##
  235. ## .. code-block:: nim
  236. ## var arr = [1,2,3,4,5,6,7]
  237. ## low(arr) #=> 0
  238. ## low(2) #=> -9223372036854775808
  239. ## low(int) #=> -9223372036854775808
  240. when defined(nimArrIdx):
  241. # :array|openarray|string|seq|cstring|tuple
  242. proc `[]`*[I: Ordinal;T](a: T; i: I): T {.
  243. noSideEffect, magic: "ArrGet".}
  244. proc `[]=`*[I: Ordinal;T,S](a: T; i: I;
  245. x: S) {.noSideEffect, magic: "ArrPut".}
  246. proc `=`*[T](dest: var T; src: T) {.noSideEffect, magic: "Asgn".}
  247. type
  248. Slice*[T] = object ## builtin slice type
  249. a*, b*: T ## the bounds
  250. when defined(nimalias):
  251. {.deprecated: [TSlice: Slice].}
  252. proc `..`*[T](a, b: T): Slice[T] {.noSideEffect, inline, magic: "DotDot".} =
  253. ## `slice`:idx: operator that constructs an interval ``[a, b]``, both `a`
  254. ## and `b` are inclusive. Slices can also be used in the set constructor
  255. ## and in ordinal case statements, but then they are special-cased by the
  256. ## compiler.
  257. result.a = a
  258. result.b = b
  259. proc `..`*[T](b: T): Slice[T] {.noSideEffect, inline, magic: "DotDot".} =
  260. ## `slice`:idx: operator that constructs an interval ``[default(T), b]``
  261. result.b = b
  262. when not defined(niminheritable):
  263. {.pragma: inheritable.}
  264. when not defined(nimunion):
  265. {.pragma: unchecked.}
  266. # comparison operators:
  267. proc `==` *[Enum: enum](x, y: Enum): bool {.magic: "EqEnum", noSideEffect.}
  268. ## Checks whether values within the *same enum* have the same underlying value
  269. ##
  270. ## .. code-block:: nim
  271. ## type
  272. ## Enum1 = enum
  273. ## Field1 = 3, Field2
  274. ## Enum2 = enum
  275. ## Place1, Place2 = 3
  276. ## var
  277. ## e1 = Field1
  278. ## e2 = Enum1(Place2)
  279. ## echo (e1 == e2) # true
  280. ## echo (e1 == Place2) # raises error
  281. proc `==` *(x, y: pointer): bool {.magic: "EqRef", noSideEffect.}
  282. ## .. code-block:: nim
  283. ## var # this is a wildly dangerous example
  284. ## a = cast[pointer](0)
  285. ## b = cast[pointer](nil)
  286. ## echo (a == b) # true due to the special meaning of `nil`/0 as a pointer
  287. proc `==` *(x, y: string): bool {.magic: "EqStr", noSideEffect.}
  288. ## Checks for equality between two `string` variables
  289. proc `==` *(x, y: char): bool {.magic: "EqCh", noSideEffect.}
  290. ## Checks for equality between two `char` variables
  291. proc `==` *(x, y: bool): bool {.magic: "EqB", noSideEffect.}
  292. ## Checks for equality between two `bool` variables
  293. proc `==` *[T](x, y: set[T]): bool {.magic: "EqSet", noSideEffect.}
  294. ## Checks for equality between two variables of type `set`
  295. ##
  296. ## .. code-block:: nim
  297. ## var a = {1, 2, 2, 3} # duplication in sets is ignored
  298. ## var b = {1, 2, 3}
  299. ## echo (a == b) # true
  300. proc `==` *[T](x, y: ref T): bool {.magic: "EqRef", noSideEffect.}
  301. ## Checks that two `ref` variables refer to the same item
  302. proc `==` *[T](x, y: ptr T): bool {.magic: "EqRef", noSideEffect.}
  303. ## Checks that two `ptr` variables refer to the same item
  304. proc `==` *[T: proc](x, y: T): bool {.magic: "EqProc", noSideEffect.}
  305. ## Checks that two `proc` variables refer to the same procedure
  306. proc `<=` *[Enum: enum](x, y: Enum): bool {.magic: "LeEnum", noSideEffect.}
  307. proc `<=` *(x, y: string): bool {.magic: "LeStr", noSideEffect.}
  308. proc `<=` *(x, y: char): bool {.magic: "LeCh", noSideEffect.}
  309. proc `<=` *[T](x, y: set[T]): bool {.magic: "LeSet", noSideEffect.}
  310. proc `<=` *(x, y: bool): bool {.magic: "LeB", noSideEffect.}
  311. proc `<=` *[T](x, y: ref T): bool {.magic: "LePtr", noSideEffect.}
  312. proc `<=` *(x, y: pointer): bool {.magic: "LePtr", noSideEffect.}
  313. proc `<` *[Enum: enum](x, y: Enum): bool {.magic: "LtEnum", noSideEffect.}
  314. proc `<` *(x, y: string): bool {.magic: "LtStr", noSideEffect.}
  315. proc `<` *(x, y: char): bool {.magic: "LtCh", noSideEffect.}
  316. proc `<` *[T](x, y: set[T]): bool {.magic: "LtSet", noSideEffect.}
  317. proc `<` *(x, y: bool): bool {.magic: "LtB", noSideEffect.}
  318. proc `<` *[T](x, y: ref T): bool {.magic: "LtPtr", noSideEffect.}
  319. proc `<` *[T](x, y: ptr T): bool {.magic: "LtPtr", noSideEffect.}
  320. proc `<` *(x, y: pointer): bool {.magic: "LtPtr", noSideEffect.}
  321. template `!=` * (x, y: untyped): untyped =
  322. ## unequals operator. This is a shorthand for ``not (x == y)``.
  323. not (x == y)
  324. template `>=` * (x, y: untyped): untyped =
  325. ## "is greater or equals" operator. This is the same as ``y <= x``.
  326. y <= x
  327. template `>` * (x, y: untyped): untyped =
  328. ## "is greater" operator. This is the same as ``y < x``.
  329. y < x
  330. const
  331. appType* {.magic: "AppType"}: string = ""
  332. ## a string that describes the application type. Possible values:
  333. ## "console", "gui", "lib".
  334. include "system/inclrtl"
  335. const NoFakeVars* = defined(nimscript) ## true if the backend doesn't support \
  336. ## "fake variables" like 'var EBADF {.importc.}: cint'.
  337. when not defined(JS):
  338. type
  339. TGenericSeq {.compilerproc, pure, inheritable.} = object
  340. len, reserved: int
  341. when defined(gogc):
  342. elemSize: int
  343. PGenericSeq {.exportc.} = ptr TGenericSeq
  344. # len and space without counting the terminating zero:
  345. NimStringDesc {.compilerproc, final.} = object of TGenericSeq
  346. data: UncheckedArray[char]
  347. NimString = ptr NimStringDesc
  348. when not defined(JS) and not defined(nimscript):
  349. template space(s: PGenericSeq): int {.dirty.} =
  350. s.reserved and not seqShallowFlag
  351. include "system/hti"
  352. type
  353. byte* = uint8 ## this is an alias for ``uint8``, that is an unsigned
  354. ## int 8 bits wide.
  355. Natural* = range[0..high(int)]
  356. ## is an int type ranging from zero to the maximum value
  357. ## of an int. This type is often useful for documentation and debugging.
  358. Positive* = range[1..high(int)]
  359. ## is an int type ranging from one to the maximum value
  360. ## of an int. This type is often useful for documentation and debugging.
  361. RootObj* {.compilerProc, inheritable.} =
  362. object ## the root of Nim's object hierarchy. Objects should
  363. ## inherit from RootObj or one of its descendants. However,
  364. ## objects that have no ancestor are allowed.
  365. RootRef* = ref RootObj ## reference to RootObj
  366. RootEffect* {.compilerproc.} = object of RootObj ## \
  367. ## base effect class; each effect should
  368. ## inherit from `RootEffect` unless you know what
  369. ## you doing.
  370. TimeEffect* = object of RootEffect ## Time effect.
  371. IOEffect* = object of RootEffect ## IO effect.
  372. ReadIOEffect* = object of IOEffect ## Effect describing a read IO operation.
  373. WriteIOEffect* = object of IOEffect ## Effect describing a write IO operation.
  374. ExecIOEffect* = object of IOEffect ## Effect describing an executing IO operation.
  375. Exception* {.compilerproc.} = object of RootObj ## \
  376. ## Base exception class.
  377. ##
  378. ## Each exception has to inherit from `Exception`. See the full `exception
  379. ## hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  380. parent*: ref Exception ## parent exception (can be used as a stack)
  381. name*: cstring ## The exception's name is its Nim identifier.
  382. ## This field is filled automatically in the
  383. ## ``raise`` statement.
  384. msg* {.exportc: "message".}: string ## the exception's message. Not
  385. ## providing an exception message
  386. ## is bad style.
  387. trace: string
  388. up: ref Exception # used for stacking exceptions. Not exported!
  389. SystemError* = object of Exception ## \
  390. ## Abstract class for exceptions that the runtime system raises.
  391. ##
  392. ## See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  393. IOError* = object of SystemError ## \
  394. ## Raised if an IO error occurred.
  395. ##
  396. ## See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  397. EOFError* = object of IOError ## \
  398. ## Raised if an IO "end of file" error occurred.
  399. ##
  400. ## See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  401. OSError* = object of SystemError ## \
  402. ## Raised if an operating system service failed.
  403. ##
  404. ## See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  405. errorCode*: int32 ## OS-defined error code describing this error.
  406. LibraryError* = object of OSError ## \
  407. ## Raised if a dynamic library could not be loaded.
  408. ##
  409. ## See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  410. ResourceExhaustedError* = object of SystemError ## \
  411. ## Raised if a resource request could not be fulfilled.
  412. ##
  413. ## See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  414. ArithmeticError* = object of Exception ## \
  415. ## Raised if any kind of arithmetic error occurred.
  416. ##
  417. ## See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  418. DivByZeroError* = object of ArithmeticError ## \
  419. ## Raised for runtime integer divide-by-zero errors.
  420. ##
  421. ## See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  422. OverflowError* = object of ArithmeticError ## \
  423. ## Raised for runtime integer overflows.
  424. ##
  425. ## This happens for calculations whose results are too large to fit in the
  426. ## provided bits. See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  427. AccessViolationError* = object of Exception ## \
  428. ## Raised for invalid memory access errors
  429. ##
  430. ## See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  431. AssertionError* = object of Exception ## \
  432. ## Raised when assertion is proved wrong.
  433. ##
  434. ## Usually the result of using the `assert() template <#assert>`_. See the
  435. ## full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  436. ValueError* = object of Exception ## \
  437. ## Raised for string and object conversion errors.
  438. KeyError* = object of ValueError ## \
  439. ## Raised if a key cannot be found in a table.
  440. ##
  441. ## Mostly used by the `tables <tables.html>`_ module, it can also be raised
  442. ## by other collection modules like `sets <sets.html>`_ or `strtabs
  443. ## <strtabs.html>`_. See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  444. OutOfMemError* = object of SystemError ## \
  445. ## Raised for unsuccessful attempts to allocate memory.
  446. ##
  447. ## See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  448. IndexError* = object of Exception ## \
  449. ## Raised if an array index is out of bounds.
  450. ##
  451. ## See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  452. FieldError* = object of Exception ## \
  453. ## Raised if a record field is not accessible because its dicriminant's
  454. ## value does not fit.
  455. ##
  456. ## See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  457. RangeError* = object of Exception ## \
  458. ## Raised if a range check error occurred.
  459. ##
  460. ## See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  461. StackOverflowError* = object of SystemError ## \
  462. ## Raised if the hardware stack used for subroutine calls overflowed.
  463. ##
  464. ## See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  465. ReraiseError* = object of Exception ## \
  466. ## Raised if there is no exception to reraise.
  467. ##
  468. ## See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  469. ObjectAssignmentError* = object of Exception ## \
  470. ## Raised if an object gets assigned to its parent's object.
  471. ##
  472. ## See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  473. ObjectConversionError* = object of Exception ## \
  474. ## Raised if an object is converted to an incompatible object type.
  475. ## You can use ``of`` operator to check if conversion will succeed.
  476. ##
  477. ## See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  478. FloatingPointError* = object of Exception ## \
  479. ## Base class for floating point exceptions.
  480. ##
  481. ## See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  482. FloatInvalidOpError* = object of FloatingPointError ## \
  483. ## Raised by invalid operations according to IEEE.
  484. ##
  485. ## Raised by ``0.0/0.0``, for example. See the full `exception
  486. ## hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  487. FloatDivByZeroError* = object of FloatingPointError ## \
  488. ## Raised by division by zero.
  489. ##
  490. ## Divisor is zero and dividend is a finite nonzero number. See the full
  491. ## `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  492. FloatOverflowError* = object of FloatingPointError ## \
  493. ## Raised for overflows.
  494. ##
  495. ## The operation produced a result that exceeds the range of the exponent.
  496. ## See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  497. FloatUnderflowError* = object of FloatingPointError ## \
  498. ## Raised for underflows.
  499. ##
  500. ## The operation produced a result that is too small to be represented as a
  501. ## normal number. See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  502. FloatInexactError* = object of FloatingPointError ## \
  503. ## Raised for inexact results.
  504. ##
  505. ## The operation produced a result that cannot be represented with infinite
  506. ## precision -- for example: ``2.0 / 3.0, log(1.1)``
  507. ##
  508. ## **NOTE**: Nim currently does not detect these! See the full
  509. ## `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  510. DeadThreadError* = object of Exception ## \
  511. ## Raised if it is attempted to send a message to a dead thread.
  512. ##
  513. ## See the full `exception hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
  514. NilAccessError* = object of SystemError ## \
  515. ## Raised on dereferences of ``nil`` pointers.
  516. ##
  517. ## This is only raised if the ``segfaults.nim`` module was imported!
  518. {.deprecated: [TObject: RootObj, PObject: RootRef, TEffect: RootEffect,
  519. FTime: TimeEffect, FIO: IOEffect, FReadIO: ReadIOEffect,
  520. FWriteIO: WriteIOEffect, FExecIO: ExecIOEffect,
  521. E_Base: Exception, ESystem: SystemError, EIO: IOError,
  522. EOS: OSError, EInvalidLibrary: LibraryError,
  523. EResourceExhausted: ResourceExhaustedError,
  524. EArithmetic: ArithmeticError, EDivByZero: DivByZeroError,
  525. EOverflow: OverflowError, EAccessViolation: AccessViolationError,
  526. EAssertionFailed: AssertionError, EInvalidValue: ValueError,
  527. EInvalidKey: KeyError, EOutOfMemory: OutOfMemError,
  528. EInvalidIndex: IndexError, EInvalidField: FieldError,
  529. EOutOfRange: RangeError, EStackOverflow: StackOverflowError,
  530. ENoExceptionToReraise: ReraiseError,
  531. EInvalidObjectAssignment: ObjectAssignmentError,
  532. EInvalidObjectConversion: ObjectConversionError,
  533. EDeadThread: DeadThreadError,
  534. EFloatInexact: FloatInexactError,
  535. EFloatUnderflow: FloatUnderflowError,
  536. EFloatingPoint: FloatingPointError,
  537. EFloatInvalidOp: FloatInvalidOpError,
  538. EFloatDivByZero: FloatDivByZeroError,
  539. EFloatOverflow: FloatOverflowError,
  540. ESynch: Exception
  541. ].}
  542. proc unsafeNew*[T](a: var ref T, size: Natural) {.magic: "New", noSideEffect.}
  543. ## creates a new object of type ``T`` and returns a safe (traced)
  544. ## reference to it in ``a``. This is **unsafe** as it allocates an object
  545. ## of the passed ``size``. This should only be used for optimization
  546. ## purposes when you know what you're doing!
  547. proc sizeof*[T](x: T): int {.magic: "SizeOf", noSideEffect.}
  548. ## returns the size of ``x`` in bytes. Since this is a low-level proc,
  549. ## its usage is discouraged - using ``new`` for the most cases suffices
  550. ## that one never needs to know ``x``'s size. As a special semantic rule,
  551. ## ``x`` may also be a type identifier (``sizeof(int)`` is valid).
  552. ##
  553. ## Limitations: If used within nim VM context ``sizeof`` will only work
  554. ## for simple types.
  555. ##
  556. ## .. code-block:: nim
  557. ## sizeof('A') #=> 1
  558. ## sizeof(2) #=> 8
  559. when defined(nimtypedescfixed):
  560. proc sizeof*(x: typedesc): int {.magic: "SizeOf", noSideEffect.}
  561. proc `<`*[T](x: Ordinal[T]): T {.magic: "UnaryLt", noSideEffect.}
  562. ## unary ``<`` that can be used for nice looking excluding ranges:
  563. ##
  564. ## .. code-block:: nim
  565. ## for i in 0 .. <10: echo i #=> 0 1 2 3 4 5 6 7 8 9
  566. ##
  567. ## Semantically this is the same as ``pred``.
  568. proc succ*[T](x: Ordinal[T], y = 1): T {.magic: "Succ", noSideEffect.}
  569. ## returns the ``y``-th successor of the value ``x``. ``T`` has to be
  570. ## an ordinal type. If such a value does not exist, ``EOutOfRange`` is raised
  571. ## or a compile time error occurs.
  572. proc pred*[T](x: Ordinal[T], y = 1): T {.magic: "Pred", noSideEffect.}
  573. ## returns the ``y``-th predecessor of the value ``x``. ``T`` has to be
  574. ## an ordinal type. If such a value does not exist, ``EOutOfRange`` is raised
  575. ## or a compile time error occurs.
  576. proc inc*[T: Ordinal|uint|uint64](x: var T, y = 1) {.magic: "Inc", noSideEffect.}
  577. ## increments the ordinal ``x`` by ``y``. If such a value does not
  578. ## exist, ``EOutOfRange`` is raised or a compile time error occurs. This is a
  579. ## short notation for: ``x = succ(x, y)``.
  580. ##
  581. ## .. code-block:: nim
  582. ## var i = 2
  583. ## inc(i) #=> 3
  584. ## inc(i, 3) #=> 6
  585. proc dec*[T: Ordinal|uint|uint64](x: var T, y = 1) {.magic: "Dec", noSideEffect.}
  586. ## decrements the ordinal ``x`` by ``y``. If such a value does not
  587. ## exist, ``EOutOfRange`` is raised or a compile time error occurs. This is a
  588. ## short notation for: ``x = pred(x, y)``.
  589. ##
  590. ## .. code-block:: nim
  591. ## var i = 2
  592. ## dec(i) #=> 1
  593. ## dec(i, 3) #=> -2
  594. proc newSeq*[T](s: var seq[T], len: Natural) {.magic: "NewSeq", noSideEffect.}
  595. ## creates a new sequence of type ``seq[T]`` with length ``len``.
  596. ## This is equivalent to ``s = @[]; setlen(s, len)``, but more
  597. ## efficient since no reallocation is needed.
  598. ##
  599. ## Note that the sequence will be filled with zeroed entries, which can be a
  600. ## problem for sequences containing strings since their value will be
  601. ## ``nil``. After the creation of the sequence you should assign entries to
  602. ## the sequence instead of adding them. Example:
  603. ##
  604. ## .. code-block:: nim
  605. ## var inputStrings : seq[string]
  606. ## newSeq(inputStrings, 3)
  607. ## inputStrings[0] = "The fourth"
  608. ## inputStrings[1] = "assignment"
  609. ## inputStrings[2] = "would crash"
  610. ## #inputStrings[3] = "out of bounds"
  611. proc newSeq*[T](len = 0.Natural): seq[T] =
  612. ## creates a new sequence of type ``seq[T]`` with length ``len``.
  613. ##
  614. ## Note that the sequence will be filled with zeroed entries, which can be a
  615. ## problem for sequences containing strings since their value will be
  616. ## ``nil``. After the creation of the sequence you should assign entries to
  617. ## the sequence instead of adding them. Example:
  618. ##
  619. ## .. code-block:: nim
  620. ## var inputStrings = newSeq[string](3)
  621. ## inputStrings[0] = "The fourth"
  622. ## inputStrings[1] = "assignment"
  623. ## inputStrings[2] = "would crash"
  624. ## #inputStrings[3] = "out of bounds"
  625. newSeq(result, len)
  626. proc newSeqOfCap*[T](cap: Natural): seq[T] {.
  627. magic: "NewSeqOfCap", noSideEffect.} =
  628. ## creates a new sequence of type ``seq[T]`` with length 0 and capacity
  629. ## ``cap``.
  630. discard
  631. proc len*[TOpenArray: openArray|varargs](x: TOpenArray): int {.
  632. magic: "LengthOpenArray", noSideEffect.}
  633. proc len*(x: string): int {.magic: "LengthStr", noSideEffect.}
  634. proc len*(x: cstring): int {.magic: "LengthStr", noSideEffect.}
  635. proc len*(x: (type array)|array): int {.magic: "LengthArray", noSideEffect.}
  636. proc len*[T](x: seq[T]): int {.magic: "LengthSeq", noSideEffect.}
  637. ## returns the length of an array, an openarray, a sequence or a string.
  638. ## This is roughly the same as ``high(T)-low(T)+1``, but its resulting type is
  639. ## always an int.
  640. ##
  641. ## .. code-block:: nim
  642. ## var arr = [1,1,1,1,1]
  643. ## len(arr) #=> 5
  644. ## for i in 0..<arr.len:
  645. ## echo arr[i] #=> 1,1,1,1,1
  646. # set routines:
  647. proc incl*[T](x: var set[T], y: T) {.magic: "Incl", noSideEffect.}
  648. ## includes element ``y`` to the set ``x``. This is the same as
  649. ## ``x = x + {y}``, but it might be more efficient.
  650. ##
  651. ## .. code-block:: nim
  652. ## var a = initSet[int](4)
  653. ## a.incl(2) #=> {2}
  654. ## a.incl(3) #=> {2, 3}
  655. template incl*[T](s: var set[T], flags: set[T]) =
  656. ## includes the set of flags to the set ``x``.
  657. s = s + flags
  658. proc excl*[T](x: var set[T], y: T) {.magic: "Excl", noSideEffect.}
  659. ## excludes element ``y`` to the set ``x``. This is the same as
  660. ## ``x = x - {y}``, but it might be more efficient.
  661. ##
  662. ## .. code-block:: nim
  663. ## var b = {2,3,5,6,12,545}
  664. ## b.excl(5) #=> {2,3,6,12,545}
  665. template excl*[T](s: var set[T], flags: set[T]) =
  666. ## excludes the set of flags to ``x``.
  667. s = s - flags
  668. proc card*[T](x: set[T]): int {.magic: "Card", noSideEffect.}
  669. ## returns the cardinality of the set ``x``, i.e. the number of elements
  670. ## in the set.
  671. ##
  672. ## .. code-block:: nim
  673. ## var i = {1,2,3,4}
  674. ## card(i) #=> 4
  675. proc ord*[T](x: T): int {.magic: "Ord", noSideEffect.}
  676. ## returns the internal int value of an ordinal value ``x``.
  677. ##
  678. ## .. code-block:: nim
  679. ## ord('A') #=> 65
  680. proc chr*(u: range[0..255]): char {.magic: "Chr", noSideEffect.}
  681. ## converts an int in the range 0..255 to a character.
  682. ##
  683. ## .. code-block:: nim
  684. ## chr(65) #=> A
  685. # --------------------------------------------------------------------------
  686. # built-in operators
  687. when not defined(JS):
  688. proc ze*(x: int8): int {.magic: "Ze8ToI", noSideEffect.}
  689. ## zero extends a smaller integer type to ``int``. This treats `x` as
  690. ## unsigned.
  691. proc ze*(x: int16): int {.magic: "Ze16ToI", noSideEffect.}
  692. ## zero extends a smaller integer type to ``int``. This treats `x` as
  693. ## unsigned.
  694. proc ze64*(x: int8): int64 {.magic: "Ze8ToI64", noSideEffect.}
  695. ## zero extends a smaller integer type to ``int64``. This treats `x` as
  696. ## unsigned.
  697. proc ze64*(x: int16): int64 {.magic: "Ze16ToI64", noSideEffect.}
  698. ## zero extends a smaller integer type to ``int64``. This treats `x` as
  699. ## unsigned.
  700. proc ze64*(x: int32): int64 {.magic: "Ze32ToI64", noSideEffect.}
  701. ## zero extends a smaller integer type to ``int64``. This treats `x` as
  702. ## unsigned.
  703. proc ze64*(x: int): int64 {.magic: "ZeIToI64", noSideEffect.}
  704. ## zero extends a smaller integer type to ``int64``. This treats `x` as
  705. ## unsigned. Does nothing if the size of an ``int`` is the same as ``int64``.
  706. ## (This is the case on 64 bit processors.)
  707. proc toU8*(x: int): int8 {.magic: "ToU8", noSideEffect.}
  708. ## treats `x` as unsigned and converts it to a byte by taking the last 8 bits
  709. ## from `x`.
  710. proc toU16*(x: int): int16 {.magic: "ToU16", noSideEffect.}
  711. ## treats `x` as unsigned and converts it to an ``int16`` by taking the last
  712. ## 16 bits from `x`.
  713. proc toU32*(x: int64): int32 {.magic: "ToU32", noSideEffect.}
  714. ## treats `x` as unsigned and converts it to an ``int32`` by taking the
  715. ## last 32 bits from `x`.
  716. # integer calculations:
  717. proc `+` *(x: int): int {.magic: "UnaryPlusI", noSideEffect.}
  718. proc `+` *(x: int8): int8 {.magic: "UnaryPlusI", noSideEffect.}
  719. proc `+` *(x: int16): int16 {.magic: "UnaryPlusI", noSideEffect.}
  720. proc `+` *(x: int32): int32 {.magic: "UnaryPlusI", noSideEffect.}
  721. proc `+` *(x: int64): int64 {.magic: "UnaryPlusI", noSideEffect.}
  722. ## Unary `+` operator for an integer. Has no effect.
  723. proc `-` *(x: int): int {.magic: "UnaryMinusI", noSideEffect.}
  724. proc `-` *(x: int8): int8 {.magic: "UnaryMinusI", noSideEffect.}
  725. proc `-` *(x: int16): int16 {.magic: "UnaryMinusI", noSideEffect.}
  726. proc `-` *(x: int32): int32 {.magic: "UnaryMinusI", noSideEffect.}
  727. proc `-` *(x: int64): int64 {.magic: "UnaryMinusI64", noSideEffect.}
  728. ## Unary `-` operator for an integer. Negates `x`.
  729. proc `not` *(x: int): int {.magic: "BitnotI", noSideEffect.}
  730. proc `not` *(x: int8): int8 {.magic: "BitnotI", noSideEffect.}
  731. proc `not` *(x: int16): int16 {.magic: "BitnotI", noSideEffect.}
  732. proc `not` *(x: int32): int32 {.magic: "BitnotI", noSideEffect.}
  733. ## computes the `bitwise complement` of the integer `x`.
  734. when defined(nimnomagic64):
  735. proc `not` *(x: int64): int64 {.magic: "BitnotI", noSideEffect.}
  736. else:
  737. proc `not` *(x: int64): int64 {.magic: "BitnotI64", noSideEffect.}
  738. proc `+` *(x, y: int): int {.magic: "AddI", noSideEffect.}
  739. proc `+` *(x, y: int8): int8 {.magic: "AddI", noSideEffect.}
  740. proc `+` *(x, y: int16): int16 {.magic: "AddI", noSideEffect.}
  741. proc `+` *(x, y: int32): int32 {.magic: "AddI", noSideEffect.}
  742. ## Binary `+` operator for an integer.
  743. when defined(nimnomagic64):
  744. proc `+` *(x, y: int64): int64 {.magic: "AddI", noSideEffect.}
  745. else:
  746. proc `+` *(x, y: int64): int64 {.magic: "AddI64", noSideEffect.}
  747. proc `-` *(x, y: int): int {.magic: "SubI", noSideEffect.}
  748. proc `-` *(x, y: int8): int8 {.magic: "SubI", noSideEffect.}
  749. proc `-` *(x, y: int16): int16 {.magic: "SubI", noSideEffect.}
  750. proc `-` *(x, y: int32): int32 {.magic: "SubI", noSideEffect.}
  751. ## Binary `-` operator for an integer.
  752. when defined(nimnomagic64):
  753. proc `-` *(x, y: int64): int64 {.magic: "SubI", noSideEffect.}
  754. else:
  755. proc `-` *(x, y: int64): int64 {.magic: "SubI64", noSideEffect.}
  756. proc `*` *(x, y: int): int {.magic: "MulI", noSideEffect.}
  757. proc `*` *(x, y: int8): int8 {.magic: "MulI", noSideEffect.}
  758. proc `*` *(x, y: int16): int16 {.magic: "MulI", noSideEffect.}
  759. proc `*` *(x, y: int32): int32 {.magic: "MulI", noSideEffect.}
  760. ## Binary `*` operator for an integer.
  761. when defined(nimnomagic64):
  762. proc `*` *(x, y: int64): int64 {.magic: "MulI", noSideEffect.}
  763. else:
  764. proc `*` *(x, y: int64): int64 {.magic: "MulI64", noSideEffect.}
  765. proc `div` *(x, y: int): int {.magic: "DivI", noSideEffect.}
  766. proc `div` *(x, y: int8): int8 {.magic: "DivI", noSideEffect.}
  767. proc `div` *(x, y: int16): int16 {.magic: "DivI", noSideEffect.}
  768. proc `div` *(x, y: int32): int32 {.magic: "DivI", noSideEffect.}
  769. ## computes the integer division. This is roughly the same as
  770. ## ``floor(x/y)``.
  771. ##
  772. ## .. code-block:: Nim
  773. ## 1 div 2 == 0
  774. ## 2 div 2 == 1
  775. ## 3 div 2 == 1
  776. ## 7 div 5 == 1
  777. when defined(nimnomagic64):
  778. proc `div` *(x, y: int64): int64 {.magic: "DivI", noSideEffect.}
  779. else:
  780. proc `div` *(x, y: int64): int64 {.magic: "DivI64", noSideEffect.}
  781. proc `mod` *(x, y: int): int {.magic: "ModI", noSideEffect.}
  782. proc `mod` *(x, y: int8): int8 {.magic: "ModI", noSideEffect.}
  783. proc `mod` *(x, y: int16): int16 {.magic: "ModI", noSideEffect.}
  784. proc `mod` *(x, y: int32): int32 {.magic: "ModI", noSideEffect.}
  785. ## computes the integer modulo operation (remainder).
  786. ## This is the same as
  787. ## ``x - (x div y) * y``.
  788. ##
  789. ## .. code-block:: Nim
  790. ## (7 mod 5) == 2
  791. when defined(nimnomagic64):
  792. proc `mod` *(x, y: int64): int64 {.magic: "ModI", noSideEffect.}
  793. else:
  794. proc `mod` *(x, y: int64): int64 {.magic: "ModI64", noSideEffect.}
  795. when defined(nimNewShiftOps):
  796. proc `shr` *(x: int, y: SomeInteger): int {.magic: "ShrI", noSideEffect.}
  797. proc `shr` *(x: int8, y: SomeInteger): int8 {.magic: "ShrI", noSideEffect.}
  798. proc `shr` *(x: int16, y: SomeInteger): int16 {.magic: "ShrI", noSideEffect.}
  799. proc `shr` *(x: int32, y: SomeInteger): int32 {.magic: "ShrI", noSideEffect.}
  800. proc `shr` *(x: int64, y: SomeInteger): int64 {.magic: "ShrI", noSideEffect.}
  801. ## computes the `shift right` operation of `x` and `y`, filling
  802. ## vacant bit positions with zeros.
  803. ##
  804. ## .. code-block:: Nim
  805. ## 0b0001_0000'i8 shr 2 == 0b0000_0100'i8
  806. ## 0b1000_0000'i8 shr 8 == 0b0000_0000'i8
  807. ## 0b0000_0001'i8 shr 1 == 0b0000_0000'i8
  808. proc `shl` *(x: int, y: SomeInteger): int {.magic: "ShlI", noSideEffect.}
  809. proc `shl` *(x: int8, y: SomeInteger): int8 {.magic: "ShlI", noSideEffect.}
  810. proc `shl` *(x: int16, y: SomeInteger): int16 {.magic: "ShlI", noSideEffect.}
  811. proc `shl` *(x: int32, y: SomeInteger): int32 {.magic: "ShlI", noSideEffect.}
  812. proc `shl` *(x: int64, y: SomeInteger): int64 {.magic: "ShlI", noSideEffect.}
  813. ## computes the `shift left` operation of `x` and `y`.
  814. ##
  815. ## .. code-block:: Nim
  816. ## 1'i32 shl 4 == 0x0000_0010
  817. ## 1'i64 shl 4 == 0x0000_0000_0000_0010
  818. else:
  819. proc `shr` *(x, y: int): int {.magic: "ShrI", noSideEffect.}
  820. proc `shr` *(x, y: int8): int8 {.magic: "ShrI", noSideEffect.}
  821. proc `shr` *(x, y: int16): int16 {.magic: "ShrI", noSideEffect.}
  822. proc `shr` *(x, y: int32): int32 {.magic: "ShrI", noSideEffect.}
  823. proc `shr` *(x, y: int64): int64 {.magic: "ShrI", noSideEffect.}
  824. proc `shl` *(x, y: int): int {.magic: "ShlI", noSideEffect.}
  825. proc `shl` *(x, y: int8): int8 {.magic: "ShlI", noSideEffect.}
  826. proc `shl` *(x, y: int16): int16 {.magic: "ShlI", noSideEffect.}
  827. proc `shl` *(x, y: int32): int32 {.magic: "ShlI", noSideEffect.}
  828. proc `shl` *(x, y: int64): int64 {.magic: "ShlI", noSideEffect.}
  829. proc `and` *(x, y: int): int {.magic: "BitandI", noSideEffect.}
  830. proc `and` *(x, y: int8): int8 {.magic: "BitandI", noSideEffect.}
  831. proc `and` *(x, y: int16): int16 {.magic: "BitandI", noSideEffect.}
  832. proc `and` *(x, y: int32): int32 {.magic: "BitandI", noSideEffect.}
  833. proc `and` *(x, y: int64): int64 {.magic: "BitandI", noSideEffect.}
  834. ## computes the `bitwise and` of numbers `x` and `y`.
  835. ##
  836. ## .. code-block:: Nim
  837. ## (0xffff'i16 and 0x0010'i16) == 0x0010
  838. proc `or` *(x, y: int): int {.magic: "BitorI", noSideEffect.}
  839. proc `or` *(x, y: int8): int8 {.magic: "BitorI", noSideEffect.}
  840. proc `or` *(x, y: int16): int16 {.magic: "BitorI", noSideEffect.}
  841. proc `or` *(x, y: int32): int32 {.magic: "BitorI", noSideEffect.}
  842. proc `or` *(x, y: int64): int64 {.magic: "BitorI", noSideEffect.}
  843. ## computes the `bitwise or` of numbers `x` and `y`.
  844. ##
  845. ## .. code-block:: Nim
  846. ## (0x0005'i16 or 0x0010'i16) == 0x0015
  847. proc `xor` *(x, y: int): int {.magic: "BitxorI", noSideEffect.}
  848. proc `xor` *(x, y: int8): int8 {.magic: "BitxorI", noSideEffect.}
  849. proc `xor` *(x, y: int16): int16 {.magic: "BitxorI", noSideEffect.}
  850. proc `xor` *(x, y: int32): int32 {.magic: "BitxorI", noSideEffect.}
  851. proc `xor` *(x, y: int64): int64 {.magic: "BitxorI", noSideEffect.}
  852. ## computes the `bitwise xor` of numbers `x` and `y`.
  853. ##
  854. ## .. code-block:: Nim
  855. ## (0x1011'i16 xor 0x0101'i16) == 0x1110
  856. proc `==` *(x, y: int): bool {.magic: "EqI", noSideEffect.}
  857. proc `==` *(x, y: int8): bool {.magic: "EqI", noSideEffect.}
  858. proc `==` *(x, y: int16): bool {.magic: "EqI", noSideEffect.}
  859. proc `==` *(x, y: int32): bool {.magic: "EqI", noSideEffect.}
  860. proc `==` *(x, y: int64): bool {.magic: "EqI", noSideEffect.}
  861. ## Compares two integers for equality.
  862. proc `<=` *(x, y: int): bool {.magic: "LeI", noSideEffect.}
  863. proc `<=` *(x, y: int8): bool {.magic: "LeI", noSideEffect.}
  864. proc `<=` *(x, y: int16): bool {.magic: "LeI", noSideEffect.}
  865. proc `<=` *(x, y: int32): bool {.magic: "LeI", noSideEffect.}
  866. proc `<=` *(x, y: int64): bool {.magic: "LeI", noSideEffect.}
  867. ## Returns true iff `x` is less than or equal to `y`.
  868. proc `<` *(x, y: int): bool {.magic: "LtI", noSideEffect.}
  869. proc `<` *(x, y: int8): bool {.magic: "LtI", noSideEffect.}
  870. proc `<` *(x, y: int16): bool {.magic: "LtI", noSideEffect.}
  871. proc `<` *(x, y: int32): bool {.magic: "LtI", noSideEffect.}
  872. proc `<` *(x, y: int64): bool {.magic: "LtI", noSideEffect.}
  873. ## Returns true iff `x` is less than `y`.
  874. type
  875. IntMax32 = int|int8|int16|int32
  876. proc `+%` *(x, y: IntMax32): IntMax32 {.magic: "AddU", noSideEffect.}
  877. proc `+%` *(x, y: int64): int64 {.magic: "AddU", noSideEffect.}
  878. ## treats `x` and `y` as unsigned and adds them. The result is truncated to
  879. ## fit into the result. This implements modulo arithmetic. No overflow
  880. ## errors are possible.
  881. proc `-%` *(x, y: IntMax32): IntMax32 {.magic: "SubU", noSideEffect.}
  882. proc `-%` *(x, y: int64): int64 {.magic: "SubU", noSideEffect.}
  883. ## treats `x` and `y` as unsigned and subtracts them. The result is
  884. ## truncated to fit into the result. This implements modulo arithmetic.
  885. ## No overflow errors are possible.
  886. proc `*%` *(x, y: IntMax32): IntMax32 {.magic: "MulU", noSideEffect.}
  887. proc `*%` *(x, y: int64): int64 {.magic: "MulU", noSideEffect.}
  888. ## treats `x` and `y` as unsigned and multiplies them. The result is
  889. ## truncated to fit into the result. This implements modulo arithmetic.
  890. ## No overflow errors are possible.
  891. proc `/%` *(x, y: IntMax32): IntMax32 {.magic: "DivU", noSideEffect.}
  892. proc `/%` *(x, y: int64): int64 {.magic: "DivU", noSideEffect.}
  893. ## treats `x` and `y` as unsigned and divides them. The result is
  894. ## truncated to fit into the result. This implements modulo arithmetic.
  895. ## No overflow errors are possible.
  896. proc `%%` *(x, y: IntMax32): IntMax32 {.magic: "ModU", noSideEffect.}
  897. proc `%%` *(x, y: int64): int64 {.magic: "ModU", noSideEffect.}
  898. ## treats `x` and `y` as unsigned and compute the modulo of `x` and `y`.
  899. ## The result is truncated to fit into the result.
  900. ## This implements modulo arithmetic.
  901. ## No overflow errors are possible.
  902. proc `<=%` *(x, y: IntMax32): bool {.magic: "LeU", noSideEffect.}
  903. proc `<=%` *(x, y: int64): bool {.magic: "LeU64", noSideEffect.}
  904. ## treats `x` and `y` as unsigned and compares them.
  905. ## Returns true iff ``unsigned(x) <= unsigned(y)``.
  906. proc `<%` *(x, y: IntMax32): bool {.magic: "LtU", noSideEffect.}
  907. proc `<%` *(x, y: int64): bool {.magic: "LtU64", noSideEffect.}
  908. ## treats `x` and `y` as unsigned and compares them.
  909. ## Returns true iff ``unsigned(x) < unsigned(y)``.
  910. # unsigned integer operations:
  911. proc `not`*[T: SomeUnsignedInt](x: T): T {.magic: "BitnotI", noSideEffect.}
  912. ## computes the `bitwise complement` of the integer `x`.
  913. when defined(nimNewShiftOps):
  914. proc `shr`*[T: SomeUnsignedInt](x: T, y: SomeInteger): T {.magic: "ShrI", noSideEffect.}
  915. ## computes the `shift right` operation of `x` and `y`.
  916. proc `shl`*[T: SomeUnsignedInt](x: T, y: SomeInteger): T {.magic: "ShlI", noSideEffect.}
  917. ## computes the `shift left` operation of `x` and `y`.
  918. else:
  919. proc `shr`*[T: SomeUnsignedInt](x, y: T): T {.magic: "ShrI", noSideEffect.}
  920. ## computes the `shift right` operation of `x` and `y`.
  921. proc `shl`*[T: SomeUnsignedInt](x, y: T): T {.magic: "ShlI", noSideEffect.}
  922. ## computes the `shift left` operation of `x` and `y`.
  923. proc `and`*[T: SomeUnsignedInt](x, y: T): T {.magic: "BitandI", noSideEffect.}
  924. ## computes the `bitwise and` of numbers `x` and `y`.
  925. proc `or`*[T: SomeUnsignedInt](x, y: T): T {.magic: "BitorI", noSideEffect.}
  926. ## computes the `bitwise or` of numbers `x` and `y`.
  927. proc `xor`*[T: SomeUnsignedInt](x, y: T): T {.magic: "BitxorI", noSideEffect.}
  928. ## computes the `bitwise xor` of numbers `x` and `y`.
  929. proc `==`*[T: SomeUnsignedInt](x, y: T): bool {.magic: "EqI", noSideEffect.}
  930. ## Compares two unsigned integers for equality.
  931. proc `+`*[T: SomeUnsignedInt](x, y: T): T {.magic: "AddU", noSideEffect.}
  932. ## Binary `+` operator for unsigned integers.
  933. proc `-`*[T: SomeUnsignedInt](x, y: T): T {.magic: "SubU", noSideEffect.}
  934. ## Binary `-` operator for unsigned integers.
  935. proc `*`*[T: SomeUnsignedInt](x, y: T): T {.magic: "MulU", noSideEffect.}
  936. ## Binary `*` operator for unsigned integers.
  937. proc `div`*[T: SomeUnsignedInt](x, y: T): T {.magic: "DivU", noSideEffect.}
  938. ## computes the integer division. This is roughly the same as
  939. ## ``floor(x/y)``.
  940. ##
  941. ## .. code-block:: Nim
  942. ## (7 div 5) == 1
  943. proc `mod`*[T: SomeUnsignedInt](x, y: T): T {.magic: "ModU", noSideEffect.}
  944. ## computes the integer modulo operation (remainder).
  945. ## This is the same as
  946. ## ``x - (x div y) * y``.
  947. ##
  948. ## .. code-block:: Nim
  949. ## (7 mod 5) == 2
  950. proc `<=`*[T: SomeUnsignedInt](x, y: T): bool {.magic: "LeU", noSideEffect.}
  951. ## Returns true iff ``x <= y``.
  952. proc `<`*[T: SomeUnsignedInt](x, y: T): bool {.magic: "LtU", noSideEffect.}
  953. ## Returns true iff ``unsigned(x) < unsigned(y)``.
  954. # floating point operations:
  955. proc `+` *(x: float32): float32 {.magic: "UnaryPlusF64", noSideEffect.}
  956. proc `-` *(x: float32): float32 {.magic: "UnaryMinusF64", noSideEffect.}
  957. proc `+` *(x, y: float32): float32 {.magic: "AddF64", noSideEffect.}
  958. proc `-` *(x, y: float32): float32 {.magic: "SubF64", noSideEffect.}
  959. proc `*` *(x, y: float32): float32 {.magic: "MulF64", noSideEffect.}
  960. proc `/` *(x, y: float32): float32 {.magic: "DivF64", noSideEffect.}
  961. proc `+` *(x: float): float {.magic: "UnaryPlusF64", noSideEffect.}
  962. proc `-` *(x: float): float {.magic: "UnaryMinusF64", noSideEffect.}
  963. proc `+` *(x, y: float): float {.magic: "AddF64", noSideEffect.}
  964. proc `-` *(x, y: float): float {.magic: "SubF64", noSideEffect.}
  965. proc `*` *(x, y: float): float {.magic: "MulF64", noSideEffect.}
  966. proc `/` *(x, y: float): float {.magic: "DivF64", noSideEffect.}
  967. ## computes the floating point division
  968. proc `==` *(x, y: float32): bool {.magic: "EqF64", noSideEffect.}
  969. proc `<=` *(x, y: float32): bool {.magic: "LeF64", noSideEffect.}
  970. proc `<` *(x, y: float32): bool {.magic: "LtF64", noSideEffect.}
  971. proc `==` *(x, y: float): bool {.magic: "EqF64", noSideEffect.}
  972. proc `<=` *(x, y: float): bool {.magic: "LeF64", noSideEffect.}
  973. proc `<` *(x, y: float): bool {.magic: "LtF64", noSideEffect.}
  974. # set operators
  975. proc `*` *[T](x, y: set[T]): set[T] {.magic: "MulSet", noSideEffect.}
  976. ## This operator computes the intersection of two sets.
  977. proc `+` *[T](x, y: set[T]): set[T] {.magic: "PlusSet", noSideEffect.}
  978. ## This operator computes the union of two sets.
  979. proc `-` *[T](x, y: set[T]): set[T] {.magic: "MinusSet", noSideEffect.}
  980. ## This operator computes the difference of two sets.
  981. proc contains*[T](x: set[T], y: T): bool {.magic: "InSet", noSideEffect.}
  982. ## One should overload this proc if one wants to overload the ``in`` operator.
  983. ## The parameters are in reverse order! ``a in b`` is a template for
  984. ## ``contains(b, a)``.
  985. ## This is because the unification algorithm that Nim uses for overload
  986. ## resolution works from left to right.
  987. ## But for the ``in`` operator that would be the wrong direction for this
  988. ## piece of code:
  989. ##
  990. ## .. code-block:: Nim
  991. ## var s: set[range['a'..'z']] = {'a'..'c'}
  992. ## writeLine(stdout, 'b' in s)
  993. ##
  994. ## If ``in`` had been declared as ``[T](elem: T, s: set[T])`` then ``T`` would
  995. ## have been bound to ``char``. But ``s`` is not compatible to type
  996. ## ``set[char]``! The solution is to bind ``T`` to ``range['a'..'z']``. This
  997. ## is achieved by reversing the parameters for ``contains``; ``in`` then
  998. ## passes its arguments in reverse order.
  999. proc contains*[T](s: Slice[T], value: T): bool {.noSideEffect, inline.} =
  1000. ## Checks if `value` is within the range of `s`; returns true iff
  1001. ## `value >= s.a and value <= s.b`
  1002. ##
  1003. ## .. code-block:: Nim
  1004. ## assert((1..3).contains(1) == true)
  1005. ## assert((1..3).contains(2) == true)
  1006. ## assert((1..3).contains(4) == false)
  1007. result = s.a <= value and value <= s.b
  1008. template `in` * (x, y: untyped): untyped {.dirty.} = contains(y, x)
  1009. ## Sugar for contains
  1010. ##
  1011. ## .. code-block:: Nim
  1012. ## assert(1 in (1..3) == true)
  1013. ## assert(5 in (1..3) == false)
  1014. template `notin` * (x, y: untyped): untyped {.dirty.} = not contains(y, x)
  1015. ## Sugar for not containing
  1016. ##
  1017. ## .. code-block:: Nim
  1018. ## assert(1 notin (1..3) == false)
  1019. ## assert(5 notin (1..3) == true)
  1020. proc `is` *[T, S](x: T, y: S): bool {.magic: "Is", noSideEffect.}
  1021. ## Checks if T is of the same type as S
  1022. ##
  1023. ## .. code-block:: Nim
  1024. ## proc test[T](a: T): int =
  1025. ## when (T is int):
  1026. ## return a
  1027. ## else:
  1028. ## return 0
  1029. ##
  1030. ## assert(test[int](3) == 3)
  1031. ## assert(test[string]("xyz") == 0)
  1032. template `isnot` *(x, y: untyped): untyped = not (x is y)
  1033. ## Negated version of `is`. Equivalent to ``not(x is y)``.
  1034. proc `of` *[T, S](x: typeDesc[T], y: typeDesc[S]): bool {.magic: "Of", noSideEffect.}
  1035. proc `of` *[T, S](x: T, y: typeDesc[S]): bool {.magic: "Of", noSideEffect.}
  1036. proc `of` *[T, S](x: T, y: S): bool {.magic: "Of", noSideEffect.}
  1037. ## Checks if `x` has a type of `y`
  1038. ##
  1039. ## .. code-block:: Nim
  1040. ## assert(FloatingPointError of Exception)
  1041. ## assert(DivByZeroError of Exception)
  1042. proc cmp*[T](x, y: T): int {.procvar.} =
  1043. ## Generic compare proc. Returns a value < 0 iff x < y, a value > 0 iff x > y
  1044. ## and 0 iff x == y. This is useful for writing generic algorithms without
  1045. ## performance loss. This generic implementation uses the `==` and `<`
  1046. ## operators.
  1047. ##
  1048. ## .. code-block:: Nim
  1049. ## import algorithm
  1050. ## echo sorted(@[4,2,6,5,8,7], cmp[int])
  1051. if x == y: return 0
  1052. if x < y: return -1
  1053. return 1
  1054. proc cmp*(x, y: string): int {.noSideEffect, procvar.}
  1055. ## Compare proc for strings. More efficient than the generic version.
  1056. proc `@` * [IDX, T](a: array[IDX, T]): seq[T] {.
  1057. magic: "ArrToSeq", nosideeffect.}
  1058. ## turns an array into a sequence. This most often useful for constructing
  1059. ## sequences with the array constructor: ``@[1, 2, 3]`` has the type
  1060. ## ``seq[int]``, while ``[1, 2, 3]`` has the type ``array[0..2, int]``.
  1061. proc setLen*[T](s: var seq[T], newlen: Natural) {.
  1062. magic: "SetLengthSeq", noSideEffect.}
  1063. ## sets the length of `s` to `newlen`.
  1064. ## ``T`` may be any sequence type.
  1065. ## If the current length is greater than the new length,
  1066. ## ``s`` will be truncated. `s` cannot be nil! To initialize a sequence with
  1067. ## a size, use ``newSeq`` instead.
  1068. proc setLen*(s: var string, newlen: Natural) {.
  1069. magic: "SetLengthStr", noSideEffect.}
  1070. ## sets the length of `s` to `newlen`.
  1071. ## If the current length is greater than the new length,
  1072. ## ``s`` will be truncated. `s` cannot be nil! To initialize a string with
  1073. ## a size, use ``newString`` instead.
  1074. ##
  1075. ## .. code-block:: Nim
  1076. ## var myS = "Nim is great!!"
  1077. ## myS.setLen(3)
  1078. ## echo myS, " is fantastic!!"
  1079. proc newString*(len: Natural): string {.
  1080. magic: "NewString", importc: "mnewString", noSideEffect.}
  1081. ## returns a new string of length ``len`` but with uninitialized
  1082. ## content. One needs to fill the string character after character
  1083. ## with the index operator ``s[i]``. This procedure exists only for
  1084. ## optimization purposes; the same effect can be achieved with the
  1085. ## ``&`` operator or with ``add``.
  1086. proc newStringOfCap*(cap: Natural): string {.
  1087. magic: "NewStringOfCap", importc: "rawNewString", noSideEffect.}
  1088. ## returns a new string of length ``0`` but with capacity `cap`.This
  1089. ## procedure exists only for optimization purposes; the same effect can
  1090. ## be achieved with the ``&`` operator or with ``add``.
  1091. proc `&` * (x: string, y: char): string {.
  1092. magic: "ConStrStr", noSideEffect, merge.}
  1093. ## Concatenates `x` with `y`
  1094. ##
  1095. ## .. code-block:: Nim
  1096. ## assert("ab" & 'c' == "abc")
  1097. proc `&` * (x, y: char): string {.
  1098. magic: "ConStrStr", noSideEffect, merge.}
  1099. ## Concatenates `x` and `y` into a string
  1100. ##
  1101. ## .. code-block:: Nim
  1102. ## assert('a' & 'b' == "ab")
  1103. proc `&` * (x, y: string): string {.
  1104. magic: "ConStrStr", noSideEffect, merge.}
  1105. ## Concatenates `x` and `y`
  1106. ##
  1107. ## .. code-block:: Nim
  1108. ## assert("ab" & "cd" == "abcd")
  1109. proc `&` * (x: char, y: string): string {.
  1110. magic: "ConStrStr", noSideEffect, merge.}
  1111. ## Concatenates `x` with `y`
  1112. ##
  1113. ## .. code-block:: Nim
  1114. ## assert('a' & "bc" == "abc")
  1115. # implementation note: These must all have the same magic value "ConStrStr" so
  1116. # that the merge optimization works properly.
  1117. proc add*(x: var string, y: char) {.magic: "AppendStrCh", noSideEffect.}
  1118. ## Appends `y` to `x` in place
  1119. ##
  1120. ## .. code-block:: Nim
  1121. ## var tmp = ""
  1122. ## tmp.add('a')
  1123. ## tmp.add('b')
  1124. ## assert(tmp == "ab")
  1125. proc add*(x: var string, y: string) {.magic: "AppendStrStr", noSideEffect.}
  1126. ## Concatenates `x` and `y` in place
  1127. ##
  1128. ## .. code-block:: Nim
  1129. ## var tmp = ""
  1130. ## tmp.add("ab")
  1131. ## tmp.add("cd")
  1132. ## assert(tmp == "abcd")
  1133. type
  1134. Endianness* = enum ## is a type describing the endianness of a processor.
  1135. littleEndian, bigEndian
  1136. const
  1137. isMainModule* {.magic: "IsMainModule".}: bool = false
  1138. ## is true only when accessed in the main module. This works thanks to
  1139. ## compiler magic. It is useful to embed testing code in a module.
  1140. CompileDate* {.magic: "CompileDate"}: string = "0000-00-00"
  1141. ## is the date of compilation as a string of the form
  1142. ## ``YYYY-MM-DD``. This works thanks to compiler magic.
  1143. CompileTime* {.magic: "CompileTime"}: string = "00:00:00"
  1144. ## is the time of compilation as a string of the form
  1145. ## ``HH:MM:SS``. This works thanks to compiler magic.
  1146. cpuEndian* {.magic: "CpuEndian"}: Endianness = littleEndian
  1147. ## is the endianness of the target CPU. This is a valuable piece of
  1148. ## information for low-level code only. This works thanks to compiler
  1149. ## magic.
  1150. hostOS* {.magic: "HostOS".}: string = ""
  1151. ## a string that describes the host operating system. Possible values:
  1152. ## "windows", "macosx", "linux", "netbsd", "freebsd", "openbsd", "solaris",
  1153. ## "aix", "standalone".
  1154. hostCPU* {.magic: "HostCPU".}: string = ""
  1155. ## a string that describes the host CPU. Possible values:
  1156. ## "i386", "alpha", "powerpc", "powerpc64", "powerpc64el", "sparc",
  1157. ## "amd64", "mips", "mipsel", "arm", "arm64", "mips64", "mips64el".
  1158. seqShallowFlag = low(int)
  1159. {.push profiler: off.}
  1160. when defined(nimKnowsNimvm):
  1161. let nimvm* {.magic: "Nimvm".}: bool = false
  1162. ## may be used only in "when" expression.
  1163. ## It is true in Nim VM context and false otherwise
  1164. else:
  1165. const nimvm*: bool = false
  1166. {.pop.}
  1167. proc compileOption*(option: string): bool {.
  1168. magic: "CompileOption", noSideEffect.}
  1169. ## can be used to determine an on|off compile-time option. Example:
  1170. ##
  1171. ## .. code-block:: nim
  1172. ## when compileOption("floatchecks"):
  1173. ## echo "compiled with floating point NaN and Inf checks"
  1174. proc compileOption*(option, arg: string): bool {.
  1175. magic: "CompileOptionArg", noSideEffect.}
  1176. ## can be used to determine an enum compile-time option. Example:
  1177. ##
  1178. ## .. code-block:: nim
  1179. ## when compileOption("opt", "size") and compileOption("gc", "boehm"):
  1180. ## echo "compiled with optimization for size and uses Boehm's GC"
  1181. const
  1182. hasThreadSupport = compileOption("threads") and not defined(nimscript)
  1183. hasSharedHeap = defined(boehmgc) or defined(gogc) # don't share heaps; every thread has its own
  1184. taintMode = compileOption("taintmode")
  1185. nimEnableCovariance* = defined(nimEnableCovariance) # or true
  1186. when hasThreadSupport and defined(tcc) and not compileOption("tlsEmulation"):
  1187. # tcc doesn't support TLS
  1188. {.error: "``--tlsEmulation:on`` must be used when using threads with tcc backend".}
  1189. when defined(boehmgc):
  1190. when defined(windows):
  1191. const boehmLib = "boehmgc.dll"
  1192. elif defined(macosx):
  1193. const boehmLib = "libgc.dylib"
  1194. else:
  1195. const boehmLib = "libgc.so.1"
  1196. {.pragma: boehmGC, noconv, dynlib: boehmLib.}
  1197. when taintMode:
  1198. type TaintedString* = distinct string ## a distinct string type that
  1199. ## is `tainted`:idx:, see `taint mode
  1200. ## <manual.html#taint-mode>`_ for
  1201. ## details. It is an alias for
  1202. ## ``string`` if the taint mode is not
  1203. ## turned on.
  1204. proc len*(s: TaintedString): int {.borrow.}
  1205. else:
  1206. type TaintedString* = string ## a distinct string type that
  1207. ## is `tainted`:idx:, see `taint mode
  1208. ## <manual.html#taint-mode>`_ for
  1209. ## details. It is an alias for
  1210. ## ``string`` if the taint mode is not
  1211. ## turned on.
  1212. when defined(profiler):
  1213. proc nimProfile() {.compilerProc, noinline.}
  1214. when hasThreadSupport:
  1215. {.pragma: rtlThreadVar, threadvar.}
  1216. else:
  1217. {.pragma: rtlThreadVar.}
  1218. const
  1219. QuitSuccess* = 0
  1220. ## is the value that should be passed to `quit <#quit>`_ to indicate
  1221. ## success.
  1222. QuitFailure* = 1
  1223. ## is the value that should be passed to `quit <#quit>`_ to indicate
  1224. ## failure.
  1225. var programResult* {.exportc: "nim_program_result".}: int
  1226. ## modify this variable to specify the exit code of the program
  1227. ## under normal circumstances. When the program is terminated
  1228. ## prematurely using ``quit``, this value is ignored.
  1229. when defined(nimdoc):
  1230. proc quit*(errorcode: int = QuitSuccess) {.magic: "Exit", noreturn.}
  1231. ## Stops the program immediately with an exit code.
  1232. ##
  1233. ## Before stopping the program the "quit procedures" are called in the
  1234. ## opposite order they were added with `addQuitProc <#addQuitProc>`_.
  1235. ## ``quit`` never returns and ignores any exception that may have been raised
  1236. ## by the quit procedures. It does *not* call the garbage collector to free
  1237. ## all the memory, unless a quit procedure calls `GC_fullCollect
  1238. ## <#GC_fullCollect>`_.
  1239. ##
  1240. ## The proc ``quit(QuitSuccess)`` is called implicitly when your nim
  1241. ## program finishes without incident. A raised unhandled exception is
  1242. ## equivalent to calling ``quit(QuitFailure)``.
  1243. ##
  1244. ## Note that this is a *runtime* call and using ``quit`` inside a macro won't
  1245. ## have any compile time effect. If you need to stop the compiler inside a
  1246. ## macro, use the `error <manual.html#error-pragma>`_ or `fatal
  1247. ## <manual.html#fatal-pragma>`_ pragmas.
  1248. elif defined(genode):
  1249. proc quit*(errorcode: int = QuitSuccess) {.magic: "Exit", noreturn,
  1250. importcpp: "genodeEnv->parent().exit(@); Genode::sleep_forever()",
  1251. header: "<base/sleep.h>".}
  1252. else:
  1253. proc quit*(errorcode: int = QuitSuccess) {.
  1254. magic: "Exit", importc: "exit", header: "<stdlib.h>", noreturn.}
  1255. template sysAssert(cond: bool, msg: string) =
  1256. when defined(useSysAssert):
  1257. if not cond:
  1258. echo "[SYSASSERT] ", msg
  1259. quit 1
  1260. const hasAlloc = (hostOS != "standalone" or not defined(nogc)) and not defined(nimscript)
  1261. when not defined(JS) and not defined(nimscript) and hostOS != "standalone":
  1262. include "system/cgprocs"
  1263. when not defined(JS) and not defined(nimscript) and hasAlloc:
  1264. proc setStackBottom(theStackBottom: pointer) {.compilerRtl, noinline, benign.}
  1265. proc addChar(s: NimString, c: char): NimString {.compilerProc, benign.}
  1266. proc add *[T](x: var seq[T], y: T) {.magic: "AppendSeqElem", noSideEffect.}
  1267. proc add *[T](x: var seq[T], y: openArray[T]) {.noSideEffect.} =
  1268. ## Generic proc for adding a data item `y` to a container `x`.
  1269. ## For containers that have an order, `add` means *append*. New generic
  1270. ## containers should also call their adding proc `add` for consistency.
  1271. ## Generic code becomes much easier to write if the Nim naming scheme is
  1272. ## respected.
  1273. ##
  1274. ## .. code-block:: nim
  1275. ## var s: seq[string] = @["test2","test2"]
  1276. ## s.add("test") #=> @[test2, test2, test]
  1277. let xl = x.len
  1278. setLen(x, xl + y.len)
  1279. for i in 0..high(y): x[xl+i] = y[i]
  1280. proc shallowCopy*[T](x: var T, y: T) {.noSideEffect, magic: "ShallowCopy".}
  1281. ## use this instead of `=` for a `shallow copy`:idx:. The shallow copy
  1282. ## only changes the semantics for sequences and strings (and types which
  1283. ## contain those). Be careful with the changed semantics though! There
  1284. ## is a reason why the default assignment does a deep copy of sequences
  1285. ## and strings.
  1286. proc del*[T](x: var seq[T], i: Natural) {.noSideEffect.} =
  1287. ## deletes the item at index `i` by putting ``x[high(x)]`` into position `i`.
  1288. ## This is an O(1) operation.
  1289. ##
  1290. ## .. code-block:: nim
  1291. ## var i = @[1, 2, 3, 4, 5]
  1292. ## i.del(2) #=> @[1, 2, 5, 4]
  1293. let xl = x.len - 1
  1294. shallowCopy(x[i], x[xl])
  1295. setLen(x, xl)
  1296. proc delete*[T](x: var seq[T], i: Natural) {.noSideEffect.} =
  1297. ## deletes the item at index `i` by moving ``x[i+1..]`` by one position.
  1298. ## This is an O(n) operation.
  1299. ##
  1300. ## .. code-block:: nim
  1301. ## var i = @[1, 2, 3, 4, 5]
  1302. ## i.delete(2) #=> @[1, 2, 4, 5]
  1303. template defaultImpl =
  1304. let xl = x.len
  1305. for j in i..xl-2: shallowCopy(x[j], x[j+1])
  1306. setLen(x, xl-1)
  1307. when nimvm:
  1308. defaultImpl()
  1309. else:
  1310. when defined(js):
  1311. {.emit: "`x`[`x`_Idx].splice(`i`, 1);".}
  1312. else:
  1313. defaultImpl()
  1314. proc insert*[T](x: var seq[T], item: T, i = 0.Natural) {.noSideEffect.} =
  1315. ## inserts `item` into `x` at position `i`.
  1316. ##
  1317. ## .. code-block:: nim
  1318. ## var i = @[1, 2, 3, 4, 5]
  1319. ## i.insert(2, 4) #=> @[1, 2, 3, 4, 2, 5]
  1320. template defaultImpl =
  1321. let xl = x.len
  1322. setLen(x, xl+1)
  1323. var j = xl-1
  1324. while j >= i:
  1325. shallowCopy(x[j+1], x[j])
  1326. dec(j)
  1327. when nimvm:
  1328. defaultImpl()
  1329. else:
  1330. when defined(js):
  1331. var it : T
  1332. {.emit: "`x`[`x`_Idx].splice(`i`, 0, `it`);".}
  1333. else:
  1334. defaultImpl()
  1335. x[i] = item
  1336. proc repr*[T](x: T): string {.magic: "Repr", noSideEffect.}
  1337. ## takes any Nim variable and returns its string representation. It
  1338. ## works even for complex data graphs with cycles. This is a great
  1339. ## debugging tool.
  1340. ##
  1341. ## .. code-block:: nim
  1342. ## var s: seq[string] = @["test2", "test2"]
  1343. ## var i = @[1, 2, 3, 4, 5]
  1344. ## repr(s) #=> 0x1055eb050[0x1055ec050"test2", 0x1055ec078"test2"]
  1345. ## repr(i) #=> 0x1055ed050[1, 2, 3, 4, 5]
  1346. type
  1347. ByteAddress* = int
  1348. ## is the signed integer type that should be used for converting
  1349. ## pointers to integer addresses for readability.
  1350. BiggestInt* = int64
  1351. ## is an alias for the biggest signed integer type the Nim compiler
  1352. ## supports. Currently this is ``int64``, but it is platform-dependant
  1353. ## in general.
  1354. BiggestFloat* = float64
  1355. ## is an alias for the biggest floating point type the Nim
  1356. ## compiler supports. Currently this is ``float64``, but it is
  1357. ## platform-dependant in general.
  1358. when defined(JS):
  1359. type BiggestUInt* = uint32
  1360. ## is an alias for the biggest unsigned integer type the Nim compiler
  1361. ## supports. Currently this is ``uint32`` for JS and ``uint64`` for other
  1362. ## targets.
  1363. else:
  1364. type BiggestUInt* = uint64
  1365. ## is an alias for the biggest unsigned integer type the Nim compiler
  1366. ## supports. Currently this is ``uint32`` for JS and ``uint64`` for other
  1367. ## targets.
  1368. {.deprecated: [TAddress: ByteAddress].}
  1369. when defined(windows):
  1370. type
  1371. clong* {.importc: "long", nodecl.} = int32
  1372. ## This is the same as the type ``long`` in *C*.
  1373. culong* {.importc: "unsigned long", nodecl.} = uint32
  1374. ## This is the same as the type ``unsigned long`` in *C*.
  1375. else:
  1376. type
  1377. clong* {.importc: "long", nodecl.} = int
  1378. ## This is the same as the type ``long`` in *C*.
  1379. culong* {.importc: "unsigned long", nodecl.} = uint
  1380. ## This is the same as the type ``unsigned long`` in *C*.
  1381. type # these work for most platforms:
  1382. cchar* {.importc: "char", nodecl.} = char
  1383. ## This is the same as the type ``char`` in *C*.
  1384. cschar* {.importc: "signed char", nodecl.} = int8
  1385. ## This is the same as the type ``signed char`` in *C*.
  1386. cshort* {.importc: "short", nodecl.} = int16
  1387. ## This is the same as the type ``short`` in *C*.
  1388. cint* {.importc: "int", nodecl.} = int32
  1389. ## This is the same as the type ``int`` in *C*.
  1390. csize* {.importc: "size_t", nodecl.} = int
  1391. ## This is the same as the type ``size_t`` in *C*.
  1392. clonglong* {.importc: "long long", nodecl.} = int64
  1393. ## This is the same as the type ``long long`` in *C*.
  1394. cfloat* {.importc: "float", nodecl.} = float32
  1395. ## This is the same as the type ``float`` in *C*.
  1396. cdouble* {.importc: "double", nodecl.} = float64
  1397. ## This is the same as the type ``double`` in *C*.
  1398. clongdouble* {.importc: "long double", nodecl.} = BiggestFloat
  1399. ## This is the same as the type ``long double`` in *C*.
  1400. ## This C type is not supported by Nim's code generator.
  1401. cuchar* {.importc: "unsigned char", nodecl.} = char
  1402. ## This is the same as the type ``unsigned char`` in *C*.
  1403. cushort* {.importc: "unsigned short", nodecl.} = uint16
  1404. ## This is the same as the type ``unsigned short`` in *C*.
  1405. cuint* {.importc: "unsigned int", nodecl.} = uint32
  1406. ## This is the same as the type ``unsigned int`` in *C*.
  1407. culonglong* {.importc: "unsigned long long", nodecl.} = uint64
  1408. ## This is the same as the type ``unsigned long long`` in *C*.
  1409. cstringArray* {.importc: "char**", nodecl.} = ptr UncheckedArray[cstring]
  1410. ## This is binary compatible to the type ``char**`` in *C*. The array's
  1411. ## high value is large enough to disable bounds checking in practice.
  1412. ## Use `cstringArrayToSeq` to convert it into a ``seq[string]``.
  1413. PFloat32* = ptr float32 ## an alias for ``ptr float32``
  1414. PFloat64* = ptr float64 ## an alias for ``ptr float64``
  1415. PInt64* = ptr int64 ## an alias for ``ptr int64``
  1416. PInt32* = ptr int32 ## an alias for ``ptr int32``
  1417. proc toFloat*(i: int): float {.
  1418. magic: "ToFloat", noSideEffect, importc: "toFloat".}
  1419. ## converts an integer `i` into a ``float``. If the conversion
  1420. ## fails, `EInvalidValue` is raised. However, on most platforms the
  1421. ## conversion cannot fail.
  1422. proc toBiggestFloat*(i: BiggestInt): BiggestFloat {.
  1423. magic: "ToBiggestFloat", noSideEffect, importc: "toBiggestFloat".}
  1424. ## converts an biggestint `i` into a ``biggestfloat``. If the conversion
  1425. ## fails, `EInvalidValue` is raised. However, on most platforms the
  1426. ## conversion cannot fail.
  1427. proc toInt*(f: float): int {.
  1428. magic: "ToInt", noSideEffect, importc: "toInt".}
  1429. ## converts a floating point number `f` into an ``int``. Conversion
  1430. ## rounds `f` if it does not contain an integer value. If the conversion
  1431. ## fails (because `f` is infinite for example), `EInvalidValue` is raised.
  1432. proc toBiggestInt*(f: BiggestFloat): BiggestInt {.
  1433. magic: "ToBiggestInt", noSideEffect, importc: "toBiggestInt".}
  1434. ## converts a biggestfloat `f` into a ``biggestint``. Conversion
  1435. ## rounds `f` if it does not contain an integer value. If the conversion
  1436. ## fails (because `f` is infinite for example), `EInvalidValue` is raised.
  1437. proc addQuitProc*(QuitProc: proc() {.noconv.}) {.
  1438. importc: "atexit", header: "<stdlib.h>".}
  1439. ## Adds/registers a quit procedure.
  1440. ##
  1441. ## Each call to ``addQuitProc`` registers another quit procedure. Up to 30
  1442. ## procedures can be registered. They are executed on a last-in, first-out
  1443. ## basis (that is, the last function registered is the first to be executed).
  1444. ## ``addQuitProc`` raises an EOutOfIndex exception if ``QuitProc`` cannot be
  1445. ## registered.
  1446. # Support for addQuitProc() is done by Ansi C's facilities here.
  1447. # In case of an unhandled exeption the exit handlers should
  1448. # not be called explicitly! The user may decide to do this manually though.
  1449. proc copy*(s: string, first = 0): string {.
  1450. magic: "CopyStr", importc: "copyStr", noSideEffect, deprecated.}
  1451. proc copy*(s: string, first, last: int): string {.
  1452. magic: "CopyStrLast", importc: "copyStrLast", noSideEffect,
  1453. deprecated.}
  1454. ## copies a slice of `s` into a new string and returns this new
  1455. ## string. The bounds `first` and `last` denote the indices of
  1456. ## the first and last characters that shall be copied. If ``last``
  1457. ## is omitted, it is treated as ``high(s)``.
  1458. ## **Deprecated since version 0.8.12**: Use ``substr`` instead.
  1459. proc substr*(s: string, first = 0): string {.
  1460. magic: "CopyStr", importc: "copyStr", noSideEffect.}
  1461. proc substr*(s: string, first, last: int): string {.
  1462. magic: "CopyStrLast", importc: "copyStrLast", noSideEffect.}
  1463. ## copies a slice of `s` into a new string and returns this new
  1464. ## string. The bounds `first` and `last` denote the indices of
  1465. ## the first and last characters that shall be copied. If ``last``
  1466. ## is omitted, it is treated as ``high(s)``. If ``last >= s.len``, ``s.len``
  1467. ## is used instead: This means ``substr`` can also be used to `cut`:idx:
  1468. ## or `limit`:idx: a string's length.
  1469. when not defined(nimscript) and not defined(JS):
  1470. proc zeroMem*(p: pointer, size: Natural) {.inline, benign.}
  1471. ## overwrites the contents of the memory at ``p`` with the value 0.
  1472. ## Exactly ``size`` bytes will be overwritten. Like any procedure
  1473. ## dealing with raw memory this is *unsafe*.
  1474. proc copyMem*(dest, source: pointer, size: Natural) {.inline, benign,
  1475. tags: [], locks: 0.}
  1476. ## copies the contents from the memory at ``source`` to the memory
  1477. ## at ``dest``. Exactly ``size`` bytes will be copied. The memory
  1478. ## regions may not overlap. Like any procedure dealing with raw
  1479. ## memory this is *unsafe*.
  1480. proc moveMem*(dest, source: pointer, size: Natural) {.inline, benign,
  1481. tags: [], locks: 0.}
  1482. ## copies the contents from the memory at ``source`` to the memory
  1483. ## at ``dest``. Exactly ``size`` bytes will be copied. The memory
  1484. ## regions may overlap, ``moveMem`` handles this case appropriately
  1485. ## and is thus somewhat more safe than ``copyMem``. Like any procedure
  1486. ## dealing with raw memory this is still *unsafe*, though.
  1487. proc equalMem*(a, b: pointer, size: Natural): bool {.inline, noSideEffect, tags: [], locks: 0.}
  1488. ## compares the memory blocks ``a`` and ``b``. ``size`` bytes will
  1489. ## be compared. If the blocks are equal, true is returned, false
  1490. ## otherwise. Like any procedure dealing with raw memory this is
  1491. ## *unsafe*.
  1492. when not defined(nimscript):
  1493. when hasAlloc:
  1494. proc alloc*(size: Natural): pointer {.noconv, rtl, tags: [], benign.}
  1495. ## allocates a new memory block with at least ``size`` bytes. The
  1496. ## block has to be freed with ``realloc(block, 0)`` or
  1497. ## ``dealloc(block)``. The block is not initialized, so reading
  1498. ## from it before writing to it is undefined behaviour!
  1499. ## The allocated memory belongs to its allocating thread!
  1500. ## Use `allocShared` to allocate from a shared heap.
  1501. proc createU*(T: typedesc, size = 1.Positive): ptr T {.inline, benign.} =
  1502. ## allocates a new memory block with at least ``T.sizeof * size``
  1503. ## bytes. The block has to be freed with ``resize(block, 0)`` or
  1504. ## ``free(block)``. The block is not initialized, so reading
  1505. ## from it before writing to it is undefined behaviour!
  1506. ## The allocated memory belongs to its allocating thread!
  1507. ## Use `createSharedU` to allocate from a shared heap.
  1508. cast[ptr T](alloc(T.sizeof * size))
  1509. proc alloc0*(size: Natural): pointer {.noconv, rtl, tags: [], benign.}
  1510. ## allocates a new memory block with at least ``size`` bytes. The
  1511. ## block has to be freed with ``realloc(block, 0)`` or
  1512. ## ``dealloc(block)``. The block is initialized with all bytes
  1513. ## containing zero, so it is somewhat safer than ``alloc``.
  1514. ## The allocated memory belongs to its allocating thread!
  1515. ## Use `allocShared0` to allocate from a shared heap.
  1516. proc create*(T: typedesc, size = 1.Positive): ptr T {.inline, benign.} =
  1517. ## allocates a new memory block with at least ``T.sizeof * size``
  1518. ## bytes. The block has to be freed with ``resize(block, 0)`` or
  1519. ## ``free(block)``. The block is initialized with all bytes
  1520. ## containing zero, so it is somewhat safer than ``createU``.
  1521. ## The allocated memory belongs to its allocating thread!
  1522. ## Use `createShared` to allocate from a shared heap.
  1523. cast[ptr T](alloc0(sizeof(T) * size))
  1524. proc realloc*(p: pointer, newSize: Natural): pointer {.noconv, rtl, tags: [],
  1525. benign.}
  1526. ## grows or shrinks a given memory block. If p is **nil** then a new
  1527. ## memory block is returned. In either way the block has at least
  1528. ## ``newSize`` bytes. If ``newSize == 0`` and p is not **nil**
  1529. ## ``realloc`` calls ``dealloc(p)``. In other cases the block has to
  1530. ## be freed with ``dealloc``.
  1531. ## The allocated memory belongs to its allocating thread!
  1532. ## Use `reallocShared` to reallocate from a shared heap.
  1533. proc resize*[T](p: ptr T, newSize: Natural): ptr T {.inline, benign.} =
  1534. ## grows or shrinks a given memory block. If p is **nil** then a new
  1535. ## memory block is returned. In either way the block has at least
  1536. ## ``T.sizeof * newSize`` bytes. If ``newSize == 0`` and p is not
  1537. ## **nil** ``resize`` calls ``free(p)``. In other cases the block
  1538. ## has to be freed with ``free``. The allocated memory belongs to
  1539. ## its allocating thread!
  1540. ## Use `resizeShared` to reallocate from a shared heap.
  1541. cast[ptr T](realloc(p, T.sizeof * newSize))
  1542. proc dealloc*(p: pointer) {.noconv, rtl, tags: [], benign.}
  1543. ## frees the memory allocated with ``alloc``, ``alloc0`` or
  1544. ## ``realloc``. This procedure is dangerous! If one forgets to
  1545. ## free the memory a leak occurs; if one tries to access freed
  1546. ## memory (or just freeing it twice!) a core dump may happen
  1547. ## or other memory may be corrupted.
  1548. ## The freed memory must belong to its allocating thread!
  1549. ## Use `deallocShared` to deallocate from a shared heap.
  1550. proc allocShared*(size: Natural): pointer {.noconv, rtl, benign.}
  1551. ## allocates a new memory block on the shared heap with at
  1552. ## least ``size`` bytes. The block has to be freed with
  1553. ## ``reallocShared(block, 0)`` or ``deallocShared(block)``. The block
  1554. ## is not initialized, so reading from it before writing to it is
  1555. ## undefined behaviour!
  1556. proc createSharedU*(T: typedesc, size = 1.Positive): ptr T {.inline,
  1557. benign.} =
  1558. ## allocates a new memory block on the shared heap with at
  1559. ## least ``T.sizeof * size`` bytes. The block has to be freed with
  1560. ## ``resizeShared(block, 0)`` or ``freeShared(block)``. The block
  1561. ## is not initialized, so reading from it before writing to it is
  1562. ## undefined behaviour!
  1563. cast[ptr T](allocShared(T.sizeof * size))
  1564. proc allocShared0*(size: Natural): pointer {.noconv, rtl, benign.}
  1565. ## allocates a new memory block on the shared heap with at
  1566. ## least ``size`` bytes. The block has to be freed with
  1567. ## ``reallocShared(block, 0)`` or ``deallocShared(block)``.
  1568. ## The block is initialized with all bytes
  1569. ## containing zero, so it is somewhat safer than ``allocShared``.
  1570. proc createShared*(T: typedesc, size = 1.Positive): ptr T {.inline.} =
  1571. ## allocates a new memory block on the shared heap with at
  1572. ## least ``T.sizeof * size`` bytes. The block has to be freed with
  1573. ## ``resizeShared(block, 0)`` or ``freeShared(block)``.
  1574. ## The block is initialized with all bytes
  1575. ## containing zero, so it is somewhat safer than ``createSharedU``.
  1576. cast[ptr T](allocShared0(T.sizeof * size))
  1577. proc reallocShared*(p: pointer, newSize: Natural): pointer {.noconv, rtl,
  1578. benign.}
  1579. ## grows or shrinks a given memory block on the heap. If p is **nil**
  1580. ## then a new memory block is returned. In either way the block has at
  1581. ## least ``newSize`` bytes. If ``newSize == 0`` and p is not **nil**
  1582. ## ``reallocShared`` calls ``deallocShared(p)``. In other cases the
  1583. ## block has to be freed with ``deallocShared``.
  1584. proc resizeShared*[T](p: ptr T, newSize: Natural): ptr T {.inline.} =
  1585. ## grows or shrinks a given memory block on the heap. If p is **nil**
  1586. ## then a new memory block is returned. In either way the block has at
  1587. ## least ``T.sizeof * newSize`` bytes. If ``newSize == 0`` and p is
  1588. ## not **nil** ``resizeShared`` calls ``freeShared(p)``. In other
  1589. ## cases the block has to be freed with ``freeShared``.
  1590. cast[ptr T](reallocShared(p, T.sizeof * newSize))
  1591. proc deallocShared*(p: pointer) {.noconv, rtl, benign.}
  1592. ## frees the memory allocated with ``allocShared``, ``allocShared0`` or
  1593. ## ``reallocShared``. This procedure is dangerous! If one forgets to
  1594. ## free the memory a leak occurs; if one tries to access freed
  1595. ## memory (or just freeing it twice!) a core dump may happen
  1596. ## or other memory may be corrupted.
  1597. proc freeShared*[T](p: ptr T) {.inline, benign.} =
  1598. ## frees the memory allocated with ``createShared``, ``createSharedU`` or
  1599. ## ``resizeShared``. This procedure is dangerous! If one forgets to
  1600. ## free the memory a leak occurs; if one tries to access freed
  1601. ## memory (or just freeing it twice!) a core dump may happen
  1602. ## or other memory may be corrupted.
  1603. deallocShared(p)
  1604. proc swap*[T](a, b: var T) {.magic: "Swap", noSideEffect.}
  1605. ## swaps the values `a` and `b`. This is often more efficient than
  1606. ## ``tmp = a; a = b; b = tmp``. Particularly useful for sorting algorithms.
  1607. when not defined(js) and not defined(booting) and defined(nimTrMacros):
  1608. template swapRefsInArray*{swap(arr[a], arr[b])}(arr: openarray[ref], a, b: int) =
  1609. # Optimize swapping of array elements if they are refs. Default swap
  1610. # implementation will cause unsureAsgnRef to be emitted which causes
  1611. # unnecessary slow down in this case.
  1612. swap(cast[ptr pointer](addr arr[a])[], cast[ptr pointer](addr arr[b])[])
  1613. template `>=%` *(x, y: untyped): untyped = y <=% x
  1614. ## treats `x` and `y` as unsigned and compares them.
  1615. ## Returns true iff ``unsigned(x) >= unsigned(y)``.
  1616. template `>%` *(x, y: untyped): untyped = y <% x
  1617. ## treats `x` and `y` as unsigned and compares them.
  1618. ## Returns true iff ``unsigned(x) > unsigned(y)``.
  1619. proc `$`*(x: int): string {.magic: "IntToStr", noSideEffect.}
  1620. ## The stringify operator for an integer argument. Returns `x`
  1621. ## converted to a decimal string. ``$`` is Nim's general way of
  1622. ## spelling `toString`:idx:.
  1623. proc `$`*(x: int64): string {.magic: "Int64ToStr", noSideEffect.}
  1624. ## The stringify operator for an integer argument. Returns `x`
  1625. ## converted to a decimal string.
  1626. when not defined(nimscript):
  1627. when not defined(JS) and hasAlloc:
  1628. proc `$` *(x: uint64): string {.noSideEffect.}
  1629. ## The stringify operator for an unsigned integer argument. Returns `x`
  1630. ## converted to a decimal string.
  1631. proc `$` *(x: float): string {.magic: "FloatToStr", noSideEffect.}
  1632. ## The stringify operator for a float argument. Returns `x`
  1633. ## converted to a decimal string.
  1634. proc `$` *(x: bool): string {.magic: "BoolToStr", noSideEffect.}
  1635. ## The stringify operator for a boolean argument. Returns `x`
  1636. ## converted to the string "false" or "true".
  1637. proc `$` *(x: char): string {.magic: "CharToStr", noSideEffect.}
  1638. ## The stringify operator for a character argument. Returns `x`
  1639. ## converted to a string.
  1640. proc `$` *(x: cstring): string {.magic: "CStrToStr", noSideEffect.}
  1641. ## The stringify operator for a CString argument. Returns `x`
  1642. ## converted to a string.
  1643. proc `$` *(x: string): string {.magic: "StrToStr", noSideEffect.}
  1644. ## The stringify operator for a string argument. Returns `x`
  1645. ## as it is. This operator is useful for generic code, so
  1646. ## that ``$expr`` also works if ``expr`` is already a string.
  1647. proc `$` *[Enum: enum](x: Enum): string {.magic: "EnumToStr", noSideEffect.}
  1648. ## The stringify operator for an enumeration argument. This works for
  1649. ## any enumeration type thanks to compiler magic. If
  1650. ## a ``$`` operator for a concrete enumeration is provided, this is
  1651. ## used instead. (In other words: *Overwriting* is possible.)
  1652. # undocumented:
  1653. proc getRefcount*[T](x: ref T): int {.importc: "getRefcount", noSideEffect.}
  1654. proc getRefcount*(x: string): int {.importc: "getRefcount", noSideEffect.}
  1655. proc getRefcount*[T](x: seq[T]): int {.importc: "getRefcount", noSideEffect.}
  1656. ## retrieves the reference count of an heap-allocated object. The
  1657. ## value is implementation-dependent.
  1658. const
  1659. Inf* {.magic: "Inf".} = 1.0 / 0.0
  1660. ## contains the IEEE floating point value of positive infinity.
  1661. NegInf* {.magic: "NegInf".} = -Inf
  1662. ## contains the IEEE floating point value of negative infinity.
  1663. NaN* {.magic: "NaN".} = 0.0 / 0.0
  1664. ## contains an IEEE floating point value of *Not A Number*. Note
  1665. ## that you cannot compare a floating point value to this value
  1666. ## and expect a reasonable result - use the `classify` procedure
  1667. ## in the module ``math`` for checking for NaN.
  1668. NimMajor*: int = 0
  1669. ## is the major number of Nim's version.
  1670. NimMinor*: int = 17
  1671. ## is the minor number of Nim's version.
  1672. NimPatch*: int = 3
  1673. ## is the patch number of Nim's version.
  1674. NimVersion*: string = $NimMajor & "." & $NimMinor & "." & $NimPatch
  1675. ## is the version of Nim as a string.
  1676. # GC interface:
  1677. when not defined(nimscript) and hasAlloc:
  1678. proc getOccupiedMem*(): int {.rtl.}
  1679. ## returns the number of bytes that are owned by the process and hold data.
  1680. proc getFreeMem*(): int {.rtl.}
  1681. ## returns the number of bytes that are owned by the process, but do not
  1682. ## hold any meaningful data.
  1683. proc getTotalMem*(): int {.rtl.}
  1684. ## returns the number of bytes that are owned by the process.
  1685. when hasThreadSupport:
  1686. proc getOccupiedSharedMem*(): int {.rtl.}
  1687. ## returns the number of bytes that are owned by the process
  1688. ## on the shared heap and hold data. This is only available when
  1689. ## threads are enabled.
  1690. proc getFreeSharedMem*(): int {.rtl.}
  1691. ## returns the number of bytes that are owned by the
  1692. ## process on the shared heap, but do not hold any meaningful data.
  1693. ## This is only available when threads are enabled.
  1694. proc getTotalSharedMem*(): int {.rtl.}
  1695. ## returns the number of bytes on the shared heap that are owned by the
  1696. ## process. This is only available when threads are enabled.
  1697. when sizeof(int) <= 2:
  1698. type IntLikeForCount = int|int8|int16|char|bool|uint8|enum
  1699. else:
  1700. type IntLikeForCount = int|int8|int16|int32|char|bool|uint8|uint16|enum
  1701. iterator countdown*[T](a, b: T, step = 1): T {.inline.} =
  1702. ## Counts from ordinal value `a` down to `b` (inclusive) with the given
  1703. ## step count. `T` may be any ordinal type, `step` may only
  1704. ## be positive. **Note**: This fails to count to ``low(int)`` if T = int for
  1705. ## efficiency reasons.
  1706. when T is IntLikeForCount:
  1707. var res = int(a)
  1708. while res >= int(b):
  1709. yield T(res)
  1710. dec(res, step)
  1711. else:
  1712. var res = a
  1713. while res >= b:
  1714. yield res
  1715. dec(res, step)
  1716. iterator countup*[S, T](a: S, b: T, step = 1): T {.inline.} =
  1717. ## Counts from ordinal value `a` up to `b` (inclusive) with the given
  1718. ## step count. `S`, `T` may be any ordinal type, `step` may only
  1719. ## be positive. **Note**: This fails to count to ``high(int)`` if T = int for
  1720. ## efficiency reasons.
  1721. when T is IntLikeForCount:
  1722. var res = int(a)
  1723. while res <= int(b):
  1724. yield T(res)
  1725. inc(res, step)
  1726. else:
  1727. var res: T = T(a)
  1728. while res <= b:
  1729. yield res
  1730. inc(res, step)
  1731. iterator `..`*[S, T](a: S, b: T): T {.inline.} =
  1732. ## An alias for `countup`.
  1733. when T is IntLikeForCount:
  1734. var res = int(a)
  1735. while res <= int(b):
  1736. yield T(res)
  1737. inc(res)
  1738. else:
  1739. var res: T = T(a)
  1740. while res <= b:
  1741. yield res
  1742. inc(res)
  1743. iterator `||`*[S, T](a: S, b: T, annotation=""): T {.
  1744. inline, magic: "OmpParFor", sideEffect.} =
  1745. ## parallel loop iterator. Same as `..` but the loop may run in parallel.
  1746. ## `annotation` is an additional annotation for the code generator to use.
  1747. ## Note that the compiler maps that to
  1748. ## the ``#pragma omp parallel for`` construct of `OpenMP`:idx: and as
  1749. ## such isn't aware of the parallelism in your code! Be careful! Later
  1750. ## versions of ``||`` will get proper support by Nim's code generator
  1751. ## and GC.
  1752. discard
  1753. {.push stackTrace:off.}
  1754. proc min*(x, y: int): int {.magic: "MinI", noSideEffect.} =
  1755. if x <= y: x else: y
  1756. proc min*(x, y: int8): int8 {.magic: "MinI", noSideEffect.} =
  1757. if x <= y: x else: y
  1758. proc min*(x, y: int16): int16 {.magic: "MinI", noSideEffect.} =
  1759. if x <= y: x else: y
  1760. proc min*(x, y: int32): int32 {.magic: "MinI", noSideEffect.} =
  1761. if x <= y: x else: y
  1762. proc min*(x, y: int64): int64 {.magic: "MinI", noSideEffect.} =
  1763. ## The minimum value of two integers.
  1764. if x <= y: x else: y
  1765. proc min*[T](x: openArray[T]): T =
  1766. ## The minimum value of `x`. ``T`` needs to have a ``<`` operator.
  1767. result = x[0]
  1768. for i in 1..high(x):
  1769. if x[i] < result: result = x[i]
  1770. proc max*(x, y: int): int {.magic: "MaxI", noSideEffect.} =
  1771. if y <= x: x else: y
  1772. proc max*(x, y: int8): int8 {.magic: "MaxI", noSideEffect.} =
  1773. if y <= x: x else: y
  1774. proc max*(x, y: int16): int16 {.magic: "MaxI", noSideEffect.} =
  1775. if y <= x: x else: y
  1776. proc max*(x, y: int32): int32 {.magic: "MaxI", noSideEffect.} =
  1777. if y <= x: x else: y
  1778. proc max*(x, y: int64): int64 {.magic: "MaxI", noSideEffect.} =
  1779. ## The maximum value of two integers.
  1780. if y <= x: x else: y
  1781. proc max*[T](x: openArray[T]): T =
  1782. ## The maximum value of `x`. ``T`` needs to have a ``<`` operator.
  1783. result = x[0]
  1784. for i in 1..high(x):
  1785. if result < x[i]: result = x[i]
  1786. proc abs*(x: float): float {.magic: "AbsF64", noSideEffect.} =
  1787. if x < 0.0: -x else: x
  1788. proc min*(x, y: float): float {.magic: "MinF64", noSideEffect.} =
  1789. if x <= y: x else: y
  1790. proc max*(x, y: float): float {.magic: "MaxF64", noSideEffect.} =
  1791. if y <= x: x else: y
  1792. proc min*[T](x, y: T): T =
  1793. if x <= y: x else: y
  1794. proc max*[T](x, y: T): T =
  1795. if y <= x: x else: y
  1796. {.pop.}
  1797. proc clamp*[T](x, a, b: T): T =
  1798. ## limits the value ``x`` within the interval [a, b]
  1799. ##
  1800. ## .. code-block:: Nim
  1801. ## assert((1.4).clamp(0.0, 1.0) == 1.0)
  1802. ## assert((0.5).clamp(0.0, 1.0) == 0.5)
  1803. if x < a: return a
  1804. if x > b: return b
  1805. return x
  1806. proc len*[T: Ordinal](x: Slice[T]): int {.noSideEffect, inline.} =
  1807. ## length of ordinal slice, when x.b < x.a returns zero length
  1808. ##
  1809. ## .. code-block:: Nim
  1810. ## assert((0..5).len == 6)
  1811. ## assert((5..2).len == 0)
  1812. result = max(0, ord(x.b) - ord(x.a) + 1)
  1813. iterator items*[T](a: openArray[T]): T {.inline.} =
  1814. ## iterates over each item of `a`.
  1815. var i = 0
  1816. while i < len(a):
  1817. yield a[i]
  1818. inc(i)
  1819. iterator mitems*[T](a: var openArray[T]): var T {.inline.} =
  1820. ## iterates over each item of `a` so that you can modify the yielded value.
  1821. var i = 0
  1822. while i < len(a):
  1823. yield a[i]
  1824. inc(i)
  1825. iterator items*[IX, T](a: array[IX, T]): T {.inline.} =
  1826. ## iterates over each item of `a`.
  1827. var i = low(IX)
  1828. if i <= high(IX):
  1829. while true:
  1830. yield a[i]
  1831. if i >= high(IX): break
  1832. inc(i)
  1833. iterator mitems*[IX, T](a: var array[IX, T]): var T {.inline.} =
  1834. ## iterates over each item of `a` so that you can modify the yielded value.
  1835. var i = low(IX)
  1836. if i <= high(IX):
  1837. while true:
  1838. yield a[i]
  1839. if i >= high(IX): break
  1840. inc(i)
  1841. iterator items*[T](a: set[T]): T {.inline.} =
  1842. ## iterates over each element of `a`. `items` iterates only over the
  1843. ## elements that are really in the set (and not over the ones the set is
  1844. ## able to hold).
  1845. var i = low(T).int
  1846. while i <= high(T).int:
  1847. if T(i) in a: yield T(i)
  1848. inc(i)
  1849. iterator items*(a: cstring): char {.inline.} =
  1850. ## iterates over each item of `a`.
  1851. var i = 0
  1852. while a[i] != '\0':
  1853. yield a[i]
  1854. inc(i)
  1855. iterator mitems*(a: var cstring): var char {.inline.} =
  1856. ## iterates over each item of `a` so that you can modify the yielded value.
  1857. var i = 0
  1858. while a[i] != '\0':
  1859. yield a[i]
  1860. inc(i)
  1861. iterator items*(E: typedesc[enum]): E =
  1862. ## iterates over the values of the enum ``E``.
  1863. for v in low(E)..high(E):
  1864. yield v
  1865. iterator items*[T](s: Slice[T]): T =
  1866. ## iterates over the slice `s`, yielding each value between `s.a` and `s.b`
  1867. ## (inclusively).
  1868. for x in s.a..s.b:
  1869. yield x
  1870. iterator pairs*[T](a: openArray[T]): tuple[key: int, val: T] {.inline.} =
  1871. ## iterates over each item of `a`. Yields ``(index, a[index])`` pairs.
  1872. var i = 0
  1873. while i < len(a):
  1874. yield (i, a[i])
  1875. inc(i)
  1876. iterator mpairs*[T](a: var openArray[T]): tuple[key:int, val:var T]{.inline.} =
  1877. ## iterates over each item of `a`. Yields ``(index, a[index])`` pairs.
  1878. ## ``a[index]`` can be modified.
  1879. var i = 0
  1880. while i < len(a):
  1881. yield (i, a[i])
  1882. inc(i)
  1883. iterator pairs*[IX, T](a: array[IX, T]): tuple[key: IX, val: T] {.inline.} =
  1884. ## iterates over each item of `a`. Yields ``(index, a[index])`` pairs.
  1885. var i = low(IX)
  1886. if i <= high(IX):
  1887. while true:
  1888. yield (i, a[i])
  1889. if i >= high(IX): break
  1890. inc(i)
  1891. iterator mpairs*[IX, T](a:var array[IX, T]):tuple[key:IX,val:var T] {.inline.} =
  1892. ## iterates over each item of `a`. Yields ``(index, a[index])`` pairs.
  1893. ## ``a[index]`` can be modified.
  1894. var i = low(IX)
  1895. if i <= high(IX):
  1896. while true:
  1897. yield (i, a[i])
  1898. if i >= high(IX): break
  1899. inc(i)
  1900. iterator pairs*[T](a: seq[T]): tuple[key: int, val: T] {.inline.} =
  1901. ## iterates over each item of `a`. Yields ``(index, a[index])`` pairs.
  1902. var i = 0
  1903. while i < len(a):
  1904. yield (i, a[i])
  1905. inc(i)
  1906. iterator mpairs*[T](a: var seq[T]): tuple[key: int, val: var T] {.inline.} =
  1907. ## iterates over each item of `a`. Yields ``(index, a[index])`` pairs.
  1908. ## ``a[index]`` can be modified.
  1909. var i = 0
  1910. while i < len(a):
  1911. yield (i, a[i])
  1912. inc(i)
  1913. iterator pairs*(a: string): tuple[key: int, val: char] {.inline.} =
  1914. ## iterates over each item of `a`. Yields ``(index, a[index])`` pairs.
  1915. var i = 0
  1916. while i < len(a):
  1917. yield (i, a[i])
  1918. inc(i)
  1919. iterator mpairs*(a: var string): tuple[key: int, val: var char] {.inline.} =
  1920. ## iterates over each item of `a`. Yields ``(index, a[index])`` pairs.
  1921. ## ``a[index]`` can be modified.
  1922. var i = 0
  1923. while i < len(a):
  1924. yield (i, a[i])
  1925. inc(i)
  1926. iterator pairs*(a: cstring): tuple[key: int, val: char] {.inline.} =
  1927. ## iterates over each item of `a`. Yields ``(index, a[index])`` pairs.
  1928. var i = 0
  1929. while a[i] != '\0':
  1930. yield (i, a[i])
  1931. inc(i)
  1932. iterator mpairs*(a: var cstring): tuple[key: int, val: var char] {.inline.} =
  1933. ## iterates over each item of `a`. Yields ``(index, a[index])`` pairs.
  1934. ## ``a[index]`` can be modified.
  1935. var i = 0
  1936. while a[i] != '\0':
  1937. yield (i, a[i])
  1938. inc(i)
  1939. proc isNil*[T](x: seq[T]): bool {.noSideEffect, magic: "IsNil".}
  1940. proc isNil*[T](x: ref T): bool {.noSideEffect, magic: "IsNil".}
  1941. proc isNil*(x: string): bool {.noSideEffect, magic: "IsNil".}
  1942. proc isNil*[T](x: ptr T): bool {.noSideEffect, magic: "IsNil".}
  1943. proc isNil*(x: pointer): bool {.noSideEffect, magic: "IsNil".}
  1944. proc isNil*(x: cstring): bool {.noSideEffect, magic: "IsNil".}
  1945. proc isNil*[T: proc](x: T): bool {.noSideEffect, magic: "IsNil".}
  1946. ## Fast check whether `x` is nil. This is sometimes more efficient than
  1947. ## ``== nil``.
  1948. proc `==` *[I, T](x, y: array[I, T]): bool =
  1949. for f in low(x)..high(x):
  1950. if x[f] != y[f]:
  1951. return
  1952. result = true
  1953. proc `@`*[T](a: openArray[T]): seq[T] =
  1954. ## turns an openarray into a sequence. This is not as efficient as turning
  1955. ## a fixed length array into a sequence as it always copies every element
  1956. ## of `a`.
  1957. newSeq(result, a.len)
  1958. for i in 0..a.len-1: result[i] = a[i]
  1959. proc `&` *[T](x, y: seq[T]): seq[T] {.noSideEffect.} =
  1960. ## Concatenates two sequences.
  1961. ## Requires copying of the sequences.
  1962. ##
  1963. ## .. code-block:: Nim
  1964. ## assert(@[1, 2, 3, 4] & @[5, 6] == @[1, 2, 3, 4, 5, 6])
  1965. newSeq(result, x.len + y.len)
  1966. for i in 0..x.len-1:
  1967. result[i] = x[i]
  1968. for i in 0..y.len-1:
  1969. result[i+x.len] = y[i]
  1970. proc `&` *[T](x: seq[T], y: T): seq[T] {.noSideEffect.} =
  1971. ## Appends element y to the end of the sequence.
  1972. ## Requires copying of the sequence
  1973. ##
  1974. ## .. code-block:: Nim
  1975. ## assert(@[1, 2, 3] & 4 == @[1, 2, 3, 4])
  1976. newSeq(result, x.len + 1)
  1977. for i in 0..x.len-1:
  1978. result[i] = x[i]
  1979. result[x.len] = y
  1980. proc `&` *[T](x: T, y: seq[T]): seq[T] {.noSideEffect.} =
  1981. ## Prepends the element x to the beginning of the sequence.
  1982. ## Requires copying of the sequence
  1983. ##
  1984. ## .. code-block:: Nim
  1985. ## assert(1 & @[2, 3, 4] == @[1, 2, 3, 4])
  1986. newSeq(result, y.len + 1)
  1987. result[0] = x
  1988. for i in 0..y.len-1:
  1989. result[i+1] = y[i]
  1990. proc `==` *[T](x, y: seq[T]): bool {.noSideEffect.} =
  1991. ## Generic equals operator for sequences: relies on a equals operator for
  1992. ## the element type `T`.
  1993. when nimvm:
  1994. if x.isNil and y.isNil:
  1995. return true
  1996. else:
  1997. when not defined(JS) or defined(nimphp):
  1998. proc seqToPtr[T](x: seq[T]): pointer {.inline, nosideeffect.} =
  1999. result = cast[pointer](x)
  2000. else:
  2001. proc seqToPtr[T](x: seq[T]): pointer {.asmNoStackFrame, nosideeffect.} =
  2002. asm """return `x`"""
  2003. if seqToPtr(x) == seqToPtr(y):
  2004. return true
  2005. if x.isNil or y.isNil:
  2006. return false
  2007. if x.len != y.len:
  2008. return false
  2009. for i in 0..x.len-1:
  2010. if x[i] != y[i]:
  2011. return false
  2012. return true
  2013. proc find*[T, S](a: T, item: S): int {.inline.}=
  2014. ## Returns the first index of `item` in `a` or -1 if not found. This requires
  2015. ## appropriate `items` and `==` operations to work.
  2016. for i in items(a):
  2017. if i == item: return
  2018. inc(result)
  2019. result = -1
  2020. proc contains*[T](a: openArray[T], item: T): bool {.inline.}=
  2021. ## Returns true if `item` is in `a` or false if not found. This is a shortcut
  2022. ## for ``find(a, item) >= 0``.
  2023. return find(a, item) >= 0
  2024. proc pop*[T](s: var seq[T]): T {.inline, noSideEffect.} =
  2025. ## returns the last item of `s` and decreases ``s.len`` by one. This treats
  2026. ## `s` as a stack and implements the common *pop* operation.
  2027. var L = s.len-1
  2028. result = s[L]
  2029. setLen(s, L)
  2030. iterator fields*[T: tuple|object](x: T): RootObj {.
  2031. magic: "Fields", noSideEffect.}
  2032. ## iterates over every field of `x`. Warning: This really transforms
  2033. ## the 'for' and unrolls the loop. The current implementation also has a bug
  2034. ## that affects symbol binding in the loop body.
  2035. iterator fields*[S:tuple|object, T:tuple|object](x: S, y: T): tuple[a,b: untyped] {.
  2036. magic: "Fields", noSideEffect.}
  2037. ## iterates over every field of `x` and `y`.
  2038. ## Warning: This is really transforms the 'for' and unrolls the loop.
  2039. ## The current implementation also has a bug that affects symbol binding
  2040. ## in the loop body.
  2041. iterator fieldPairs*[T: tuple|object](x: T): RootObj {.
  2042. magic: "FieldPairs", noSideEffect.}
  2043. ## Iterates over every field of `x` returning their name and value.
  2044. ##
  2045. ## When you iterate over objects with different field types you have to use
  2046. ## the compile time ``when`` instead of a runtime ``if`` to select the code
  2047. ## you want to run for each type. To perform the comparison use the `is
  2048. ## operator <manual.html#is-operator>`_. Example:
  2049. ##
  2050. ## .. code-block:: Nim
  2051. ##
  2052. ## type
  2053. ## Custom = object
  2054. ## foo: string
  2055. ## bar: bool
  2056. ##
  2057. ## proc `$`(x: Custom): string =
  2058. ## result = "Custom:"
  2059. ## for name, value in x.fieldPairs:
  2060. ## when value is bool:
  2061. ## result.add("\n\t" & name & " is " & $value)
  2062. ## else:
  2063. ## if value.isNil:
  2064. ## result.add("\n\t" & name & " (nil)")
  2065. ## else:
  2066. ## result.add("\n\t" & name & " '" & value & "'")
  2067. ##
  2068. ## Another way to do the same without ``when`` is to leave the task of
  2069. ## picking the appropriate code to a secondary proc which you overload for
  2070. ## each field type and pass the `value` to.
  2071. ##
  2072. ## Warning: This really transforms the 'for' and unrolls the loop. The
  2073. ## current implementation also has a bug that affects symbol binding in the
  2074. ## loop body.
  2075. iterator fieldPairs*[S: tuple|object, T: tuple|object](x: S, y: T): tuple[
  2076. a, b: untyped] {.
  2077. magic: "FieldPairs", noSideEffect.}
  2078. ## iterates over every field of `x` and `y`.
  2079. ## Warning: This really transforms the 'for' and unrolls the loop.
  2080. ## The current implementation also has a bug that affects symbol binding
  2081. ## in the loop body.
  2082. proc `==`*[T: tuple|object](x, y: T): bool =
  2083. ## generic ``==`` operator for tuples that is lifted from the components
  2084. ## of `x` and `y`.
  2085. for a, b in fields(x, y):
  2086. if a != b: return false
  2087. return true
  2088. proc `<=`*[T: tuple](x, y: T): bool =
  2089. ## generic ``<=`` operator for tuples that is lifted from the components
  2090. ## of `x` and `y`. This implementation uses `cmp`.
  2091. for a, b in fields(x, y):
  2092. var c = cmp(a, b)
  2093. if c < 0: return true
  2094. if c > 0: return false
  2095. return true
  2096. proc `<`*[T: tuple](x, y: T): bool =
  2097. ## generic ``<`` operator for tuples that is lifted from the components
  2098. ## of `x` and `y`. This implementation uses `cmp`.
  2099. for a, b in fields(x, y):
  2100. var c = cmp(a, b)
  2101. if c < 0: return true
  2102. if c > 0: return false
  2103. return false
  2104. proc `$`*[T: tuple|object](x: T): string =
  2105. ## generic ``$`` operator for tuples that is lifted from the components
  2106. ## of `x`. Example:
  2107. ##
  2108. ## .. code-block:: nim
  2109. ## $(23, 45) == "(23, 45)"
  2110. ## $() == "()"
  2111. result = "("
  2112. var firstElement = true
  2113. for name, value in fieldPairs(x):
  2114. if not firstElement: result.add(", ")
  2115. result.add(name)
  2116. result.add(": ")
  2117. when compiles($value):
  2118. when compiles(value.isNil):
  2119. if value.isNil: result.add "nil"
  2120. else: result.add($value)
  2121. else:
  2122. result.add($value)
  2123. firstElement = false
  2124. else:
  2125. result.add("...")
  2126. result.add(")")
  2127. proc collectionToString[T: set | seq](x: T, b, e: string): string =
  2128. when x is seq:
  2129. if x.isNil: return "nil"
  2130. result = b
  2131. var firstElement = true
  2132. for value in items(x):
  2133. if not firstElement: result.add(", ")
  2134. when compiles(value.isNil):
  2135. if value.isNil: result.add "nil"
  2136. else: result.add($value)
  2137. else:
  2138. result.add($value)
  2139. firstElement = false
  2140. result.add(e)
  2141. proc `$`*[T](x: set[T]): string =
  2142. ## generic ``$`` operator for sets that is lifted from the components
  2143. ## of `x`. Example:
  2144. ##
  2145. ## .. code-block:: nim
  2146. ## ${23, 45} == "{23, 45}"
  2147. collectionToString(x, "{", "}")
  2148. proc `$`*[T](x: seq[T]): string =
  2149. ## generic ``$`` operator for seqs that is lifted from the components
  2150. ## of `x`. Example:
  2151. ##
  2152. ## .. code-block:: nim
  2153. ## $(@[23, 45]) == "@[23, 45]"
  2154. collectionToString(x, "@[", "]")
  2155. when false:
  2156. # causes bootstrapping to fail as we use array of chars and cstring should
  2157. # match better ...
  2158. proc `$`*[T, IDX](x: array[IDX, T]): string =
  2159. collectionToString(x, "[", "]")
  2160. # ----------------- GC interface ---------------------------------------------
  2161. when not defined(nimscript) and hasAlloc:
  2162. type
  2163. GC_Strategy* = enum ## the strategy the GC should use for the application
  2164. gcThroughput, ## optimize for throughput
  2165. gcResponsiveness, ## optimize for responsiveness (default)
  2166. gcOptimizeTime, ## optimize for speed
  2167. gcOptimizeSpace ## optimize for memory footprint
  2168. {.deprecated: [TGC_Strategy: GC_Strategy].}
  2169. when not defined(JS):
  2170. proc GC_disable*() {.rtl, inl, benign.}
  2171. ## disables the GC. If called n-times, n calls to `GC_enable` are needed to
  2172. ## reactivate the GC. Note that in most circumstances one should only disable
  2173. ## the mark and sweep phase with `GC_disableMarkAndSweep`.
  2174. proc GC_enable*() {.rtl, inl, benign.}
  2175. ## enables the GC again.
  2176. proc GC_fullCollect*() {.rtl, benign.}
  2177. ## forces a full garbage collection pass.
  2178. ## Ordinary code does not need to call this (and should not).
  2179. proc GC_setStrategy*(strategy: GC_Strategy) {.rtl, deprecated, benign.}
  2180. ## tells the GC the desired strategy for the application.
  2181. ## **Deprecated** since version 0.8.14. This has always been a nop.
  2182. proc GC_enableMarkAndSweep*() {.rtl, benign.}
  2183. proc GC_disableMarkAndSweep*() {.rtl, benign.}
  2184. ## the current implementation uses a reference counting garbage collector
  2185. ## with a seldomly run mark and sweep phase to free cycles. The mark and
  2186. ## sweep phase may take a long time and is not needed if the application
  2187. ## does not create cycles. Thus the mark and sweep phase can be deactivated
  2188. ## and activated separately from the rest of the GC.
  2189. proc GC_getStatistics*(): string {.rtl, benign.}
  2190. ## returns an informative string about the GC's activity. This may be useful
  2191. ## for tweaking.
  2192. proc GC_ref*[T](x: ref T) {.magic: "GCref", benign.}
  2193. proc GC_ref*[T](x: seq[T]) {.magic: "GCref", benign.}
  2194. proc GC_ref*(x: string) {.magic: "GCref", benign.}
  2195. ## marks the object `x` as referenced, so that it will not be freed until
  2196. ## it is unmarked via `GC_unref`. If called n-times for the same object `x`,
  2197. ## n calls to `GC_unref` are needed to unmark `x`.
  2198. proc GC_unref*[T](x: ref T) {.magic: "GCunref", benign.}
  2199. proc GC_unref*[T](x: seq[T]) {.magic: "GCunref", benign.}
  2200. proc GC_unref*(x: string) {.magic: "GCunref", benign.}
  2201. ## see the documentation of `GC_ref`.
  2202. else:
  2203. template GC_disable* =
  2204. {.warning: "GC_disable is a no-op in JavaScript".}
  2205. template GC_enable* =
  2206. {.warning: "GC_enable is a no-op in JavaScript".}
  2207. template GC_fullCollect* =
  2208. {.warning: "GC_fullCollect is a no-op in JavaScript".}
  2209. template GC_setStrategy* =
  2210. {.warning: "GC_setStrategy is a no-op in JavaScript".}
  2211. template GC_enableMarkAndSweep* =
  2212. {.warning: "GC_enableMarkAndSweep is a no-op in JavaScript".}
  2213. template GC_disableMarkAndSweep* =
  2214. {.warning: "GC_disableMarkAndSweep is a no-op in JavaScript".}
  2215. template GC_ref*[T](x: ref T) =
  2216. {.warning: "GC_ref is a no-op in JavaScript".}
  2217. template GC_ref*[T](x: seq[T]) =
  2218. {.warning: "GC_ref is a no-op in JavaScript".}
  2219. template GC_ref*(x: string) =
  2220. {.warning: "GC_ref is a no-op in JavaScript".}
  2221. template GC_unref*[T](x: ref T) =
  2222. {.warning: "GC_unref is a no-op in JavaScript".}
  2223. template GC_unref*[T](x: seq[T]) =
  2224. {.warning: "GC_unref is a no-op in JavaScript".}
  2225. template GC_unref*(x: string) =
  2226. {.warning: "GC_unref is a no-op in JavaScript".}
  2227. template GC_getStatistics*(): string =
  2228. {.warning: "GC_disableMarkAndSweep is a no-op in JavaScript".}
  2229. ""
  2230. template accumulateResult*(iter: untyped) =
  2231. ## helps to convert an iterator to a proc.
  2232. result = @[]
  2233. for x in iter: add(result, x)
  2234. # we have to compute this here before turning it off in except.nim anyway ...
  2235. const NimStackTrace = compileOption("stacktrace")
  2236. template coroutinesSupportedPlatform(): bool =
  2237. when defined(sparc) or defined(ELATE) or compileOption("gc", "v2") or
  2238. defined(boehmgc) or defined(gogc) or defined(nogc) or defined(gcRegions) or
  2239. defined(gcMarkAndSweep):
  2240. false
  2241. else:
  2242. true
  2243. when defined(nimCoroutines):
  2244. # Explicit opt-in.
  2245. when not coroutinesSupportedPlatform():
  2246. {.error: "Coroutines are not supported on this architecture and/or garbage collector.".}
  2247. const nimCoroutines* = true
  2248. elif defined(noNimCoroutines):
  2249. # Explicit opt-out.
  2250. const nimCoroutines* = false
  2251. else:
  2252. # Autodetect coroutine support.
  2253. const nimCoroutines* = false
  2254. {.push checks: off.}
  2255. # obviously we cannot generate checking operations here :-)
  2256. # because it would yield into an endless recursion
  2257. # however, stack-traces are available for most parts
  2258. # of the code
  2259. var
  2260. globalRaiseHook*: proc (e: ref Exception): bool {.nimcall, benign.}
  2261. ## with this hook you can influence exception handling on a global level.
  2262. ## If not nil, every 'raise' statement ends up calling this hook. Ordinary
  2263. ## application code should never set this hook! You better know what you
  2264. ## do when setting this. If ``globalRaiseHook`` returns false, the
  2265. ## exception is caught and does not propagate further through the call
  2266. ## stack.
  2267. localRaiseHook* {.threadvar.}: proc (e: ref Exception): bool {.nimcall, benign.}
  2268. ## with this hook you can influence exception handling on a
  2269. ## thread local level.
  2270. ## If not nil, every 'raise' statement ends up calling this hook. Ordinary
  2271. ## application code should never set this hook! You better know what you
  2272. ## do when setting this. If ``localRaiseHook`` returns false, the exception
  2273. ## is caught and does not propagate further through the call stack.
  2274. outOfMemHook*: proc () {.nimcall, tags: [], benign.}
  2275. ## set this variable to provide a procedure that should be called
  2276. ## in case of an `out of memory`:idx: event. The standard handler
  2277. ## writes an error message and terminates the program. `outOfMemHook` can
  2278. ## be used to raise an exception in case of OOM like so:
  2279. ##
  2280. ## .. code-block:: nim
  2281. ##
  2282. ## var gOutOfMem: ref EOutOfMemory
  2283. ## new(gOutOfMem) # need to be allocated *before* OOM really happened!
  2284. ## gOutOfMem.msg = "out of memory"
  2285. ##
  2286. ## proc handleOOM() =
  2287. ## raise gOutOfMem
  2288. ##
  2289. ## system.outOfMemHook = handleOOM
  2290. ##
  2291. ## If the handler does not raise an exception, ordinary control flow
  2292. ## continues and the program is terminated.
  2293. type
  2294. PFrame* = ptr TFrame ## represents a runtime frame of the call stack;
  2295. ## part of the debugger API.
  2296. TFrame* {.importc, nodecl, final.} = object ## the frame itself
  2297. prev*: PFrame ## previous frame; used for chaining the call stack
  2298. procname*: cstring ## name of the proc that is currently executing
  2299. line*: int ## line number of the proc that is currently executing
  2300. filename*: cstring ## filename of the proc that is currently executing
  2301. len*: int16 ## length of the inspectable slots
  2302. calldepth*: int16 ## used for max call depth checking
  2303. #{.deprecated: [TFrame: Frame].}
  2304. when defined(JS):
  2305. proc add*(x: var string, y: cstring) {.asmNoStackFrame.} =
  2306. when defined(nimphp):
  2307. asm """`x` .= `y`;"""
  2308. else:
  2309. asm """
  2310. var len = `x`[0].length-1;
  2311. for (var i = 0; i < `y`.length; ++i) {
  2312. `x`[0][len] = `y`.charCodeAt(i);
  2313. ++len;
  2314. }
  2315. `x`[0][len] = 0
  2316. """
  2317. proc add*(x: var cstring, y: cstring) {.magic: "AppendStrStr".}
  2318. elif hasAlloc:
  2319. {.push stack_trace:off, profiler:off.}
  2320. proc add*(x: var string, y: cstring) =
  2321. var i = 0
  2322. while y[i] != '\0':
  2323. add(x, y[i])
  2324. inc(i)
  2325. {.pop.}
  2326. when defined(nimvarargstyped):
  2327. proc echo*(x: varargs[typed, `$`]) {.magic: "Echo", tags: [WriteIOEffect],
  2328. benign, sideEffect.}
  2329. ## Writes and flushes the parameters to the standard output.
  2330. ##
  2331. ## Special built-in that takes a variable number of arguments. Each argument
  2332. ## is converted to a string via ``$``, so it works for user-defined
  2333. ## types that have an overloaded ``$`` operator.
  2334. ## It is roughly equivalent to ``writeLine(stdout, x); flushFile(stdout)``, but
  2335. ## available for the JavaScript target too.
  2336. ##
  2337. ## Unlike other IO operations this is guaranteed to be thread-safe as
  2338. ## ``echo`` is very often used for debugging convenience. If you want to use
  2339. ## ``echo`` inside a `proc without side effects
  2340. ## <manual.html#pragmas-nosideeffect-pragma>`_ you can use `debugEcho <#debugEcho>`_
  2341. ## instead.
  2342. proc debugEcho*(x: varargs[typed, `$`]) {.magic: "Echo", noSideEffect,
  2343. tags: [], raises: [].}
  2344. ## Same as `echo <#echo>`_, but as a special semantic rule, ``debugEcho``
  2345. ## pretends to be free of side effects, so that it can be used for debugging
  2346. ## routines marked as `noSideEffect <manual.html#pragmas-nosideeffect-pragma>`_.
  2347. else:
  2348. proc echo*(x: varargs[expr, `$`]) {.magic: "Echo", tags: [WriteIOEffect],
  2349. benign, sideEffect.}
  2350. proc debugEcho*(x: varargs[expr, `$`]) {.magic: "Echo", noSideEffect,
  2351. tags: [], raises: [].}
  2352. template newException*(exceptn: typedesc, message: string;
  2353. parentException: ref Exception = nil): untyped =
  2354. ## creates an exception object of type ``exceptn`` and sets its ``msg`` field
  2355. ## to `message`. Returns the new exception object.
  2356. var
  2357. e: ref exceptn
  2358. new(e)
  2359. e.msg = message
  2360. e.parent = parentException
  2361. e
  2362. when hostOS == "standalone":
  2363. include "$projectpath/panicoverride"
  2364. when not declared(sysFatal):
  2365. {.push profiler: off.}
  2366. when hostOS == "standalone":
  2367. proc sysFatal(exceptn: typedesc, message: string) {.inline.} =
  2368. panic(message)
  2369. proc sysFatal(exceptn: typedesc, message, arg: string) {.inline.} =
  2370. rawoutput(message)
  2371. panic(arg)
  2372. else:
  2373. proc sysFatal(exceptn: typedesc, message: string) {.inline, noReturn.} =
  2374. var e: ref exceptn
  2375. new(e)
  2376. e.msg = message
  2377. raise e
  2378. proc sysFatal(exceptn: typedesc, message, arg: string) {.inline, noReturn.} =
  2379. var e: ref exceptn
  2380. new(e)
  2381. e.msg = message & arg
  2382. raise e
  2383. {.pop.}
  2384. proc getTypeInfo*[T](x: T): pointer {.magic: "GetTypeInfo", benign.}
  2385. ## get type information for `x`. Ordinary code should not use this, but
  2386. ## the `typeinfo` module instead.
  2387. {.push stackTrace: off.}
  2388. proc abs*(x: int): int {.magic: "AbsI", noSideEffect.} =
  2389. if x < 0: -x else: x
  2390. proc abs*(x: int8): int8 {.magic: "AbsI", noSideEffect.} =
  2391. if x < 0: -x else: x
  2392. proc abs*(x: int16): int16 {.magic: "AbsI", noSideEffect.} =
  2393. if x < 0: -x else: x
  2394. proc abs*(x: int32): int32 {.magic: "AbsI", noSideEffect.} =
  2395. if x < 0: -x else: x
  2396. when defined(nimnomagic64):
  2397. proc abs*(x: int64): int64 {.magic: "AbsI", noSideEffect.} =
  2398. ## returns the absolute value of `x`. If `x` is ``low(x)`` (that
  2399. ## is -MININT for its type), an overflow exception is thrown (if overflow
  2400. ## checking is turned on).
  2401. if x < 0: -x else: x
  2402. else:
  2403. proc abs*(x: int64): int64 {.magic: "AbsI64", noSideEffect.} =
  2404. ## returns the absolute value of `x`. If `x` is ``low(x)`` (that
  2405. ## is -MININT for its type), an overflow exception is thrown (if overflow
  2406. ## checking is turned on).
  2407. if x < 0: -x else: x
  2408. {.pop.}
  2409. type
  2410. FileSeekPos* = enum ## Position relative to which seek should happen
  2411. # The values are ordered so that they match with stdio
  2412. # SEEK_SET, SEEK_CUR and SEEK_END respectively.
  2413. fspSet ## Seek to absolute value
  2414. fspCur ## Seek relative to current position
  2415. fspEnd ## Seek relative to end
  2416. when not defined(JS): #and not defined(nimscript):
  2417. {.push stack_trace: off, profiler:off.}
  2418. when hasAlloc:
  2419. when not defined(gcRegions):
  2420. proc initGC() {.gcsafe.}
  2421. when not defined(boehmgc) and not defined(useMalloc) and
  2422. not defined(gogc) and not defined(gcRegions):
  2423. proc initAllocator() {.inline.}
  2424. proc initStackBottom() {.inline, compilerproc.} =
  2425. # WARNING: This is very fragile! An array size of 8 does not work on my
  2426. # Linux 64bit system. -- That's because the stack direction is the other
  2427. # way round.
  2428. when declared(setStackBottom):
  2429. var locals {.volatile.}: pointer
  2430. locals = addr(locals)
  2431. setStackBottom(locals)
  2432. proc initStackBottomWith(locals: pointer) {.inline, compilerproc.} =
  2433. # We need to keep initStackBottom around for now to avoid
  2434. # bootstrapping problems.
  2435. when declared(setStackBottom):
  2436. setStackBottom(locals)
  2437. {.push profiler: off.}
  2438. var
  2439. strDesc = TNimType(size: sizeof(string), kind: tyString, flags: {ntfAcyclic})
  2440. {.pop.}
  2441. # ----------------- IO Part ------------------------------------------------
  2442. type
  2443. CFile {.importc: "FILE", header: "<stdio.h>",
  2444. final, incompletestruct.} = object
  2445. File* = ptr CFile ## The type representing a file handle.
  2446. FileMode* = enum ## The file mode when opening a file.
  2447. fmRead, ## Open the file for read access only.
  2448. fmWrite, ## Open the file for write access only.
  2449. ## If the file does not exist, it will be
  2450. ## created.
  2451. fmReadWrite, ## Open the file for read and write access.
  2452. ## If the file does not exist, it will be
  2453. ## created. Existing files will be cleared!
  2454. fmReadWriteExisting, ## Open the file for read and write access.
  2455. ## If the file does not exist, it will not be
  2456. ## created. The existing file will not be cleared.
  2457. fmAppend ## Open the file for writing only; append data
  2458. ## at the end.
  2459. FileHandle* = cint ## type that represents an OS file handle; this is
  2460. ## useful for low-level file access
  2461. {.deprecated: [TFile: File, TFileHandle: FileHandle, TFileMode: FileMode].}
  2462. include "system/ansi_c"
  2463. proc cmp(x, y: string): int =
  2464. when nimvm:
  2465. if x < y: result = -1
  2466. elif x > y: result = 1
  2467. else: result = 0
  2468. else:
  2469. result = int(c_strcmp(x, y))
  2470. when defined(nimscript):
  2471. proc readFile*(filename: string): string {.tags: [ReadIOEffect], benign.}
  2472. ## Opens a file named `filename` for reading, calls `readAll
  2473. ## <#readAll>`_ and closes the file afterwards. Returns the string.
  2474. ## Raises an IO exception in case of an error. If # you need to call
  2475. ## this inside a compile time macro you can use `staticRead
  2476. ## <#staticRead>`_.
  2477. proc writeFile*(filename, content: string) {.tags: [WriteIOEffect], benign.}
  2478. ## Opens a file named `filename` for writing. Then writes the
  2479. ## `content` completely to the file and closes the file afterwards.
  2480. ## Raises an IO exception in case of an error.
  2481. when not defined(nimscript) and hostOS != "standalone":
  2482. # text file handling:
  2483. var
  2484. stdin* {.importc: "stdin", header: "<stdio.h>".}: File
  2485. ## The standard input stream.
  2486. stdout* {.importc: "stdout", header: "<stdio.h>".}: File
  2487. ## The standard output stream.
  2488. stderr* {.importc: "stderr", header: "<stdio.h>".}: File
  2489. ## The standard error stream.
  2490. when defined(windows):
  2491. # work-around C's sucking abstraction:
  2492. # BUGFIX: stdin and stdout should be binary files!
  2493. proc c_setmode(handle, mode: cint) {.
  2494. importc: when defined(bcc): "setmode" else: "_setmode",
  2495. header: "<io.h>".}
  2496. var
  2497. O_BINARY {.importc: "O_BINARY", nodecl.}: cint
  2498. # we use binary mode on Windows:
  2499. c_setmode(c_fileno(stdin), O_BINARY)
  2500. c_setmode(c_fileno(stdout), O_BINARY)
  2501. c_setmode(c_fileno(stderr), O_BINARY)
  2502. when defined(endb):
  2503. proc endbStep()
  2504. when defined(useStdoutAsStdmsg):
  2505. template stdmsg*: File = stdout
  2506. else:
  2507. template stdmsg*: File = stderr
  2508. ## Template which expands to either stdout or stderr depending on
  2509. ## `useStdoutAsStdmsg` compile-time switch.
  2510. proc open*(f: var File, filename: string,
  2511. mode: FileMode = fmRead, bufSize: int = -1): bool {.tags: [],
  2512. benign.}
  2513. ## Opens a file named `filename` with given `mode`.
  2514. ##
  2515. ## Default mode is readonly. Returns true iff the file could be opened.
  2516. ## This throws no exception if the file could not be opened.
  2517. proc open*(f: var File, filehandle: FileHandle,
  2518. mode: FileMode = fmRead): bool {.tags: [], benign.}
  2519. ## Creates a ``File`` from a `filehandle` with given `mode`.
  2520. ##
  2521. ## Default mode is readonly. Returns true iff the file could be opened.
  2522. proc open*(filename: string,
  2523. mode: FileMode = fmRead, bufSize: int = -1): File =
  2524. ## Opens a file named `filename` with given `mode`.
  2525. ##
  2526. ## Default mode is readonly. Raises an ``IO`` exception if the file
  2527. ## could not be opened.
  2528. if not open(result, filename, mode, bufSize):
  2529. sysFatal(IOError, "cannot open: ", filename)
  2530. proc reopen*(f: File, filename: string, mode: FileMode = fmRead): bool {.
  2531. tags: [], benign.}
  2532. ## reopens the file `f` with given `filename` and `mode`. This
  2533. ## is often used to redirect the `stdin`, `stdout` or `stderr`
  2534. ## file variables.
  2535. ##
  2536. ## Default mode is readonly. Returns true iff the file could be reopened.
  2537. proc setStdIoUnbuffered*() {.tags: [], benign.}
  2538. ## Configures `stdin`, `stdout` and `stderr` to be unbuffered.
  2539. proc close*(f: File) {.tags: [], gcsafe.}
  2540. ## Closes the file.
  2541. proc endOfFile*(f: File): bool {.tags: [], benign.}
  2542. ## Returns true iff `f` is at the end.
  2543. proc readChar*(f: File): char {.tags: [ReadIOEffect], deprecated.}
  2544. ## Reads a single character from the stream `f`. **Deprecated** since
  2545. ## version 0.16.2. Use some variant of ``readBuffer`` instead.
  2546. proc flushFile*(f: File) {.tags: [WriteIOEffect].}
  2547. ## Flushes `f`'s buffer.
  2548. proc readAll*(file: File): TaintedString {.tags: [ReadIOEffect], benign.}
  2549. ## Reads all data from the stream `file`.
  2550. ##
  2551. ## Raises an IO exception in case of an error. It is an error if the
  2552. ## current file position is not at the beginning of the file.
  2553. proc readFile*(filename: string): TaintedString {.tags: [ReadIOEffect], benign.}
  2554. ## Opens a file named `filename` for reading.
  2555. ##
  2556. ## Then calls `readAll <#readAll>`_ and closes the file afterwards.
  2557. ## Returns the string. Raises an IO exception in case of an error. If
  2558. ## you need to call this inside a compile time macro you can use
  2559. ## `staticRead <#staticRead>`_.
  2560. proc writeFile*(filename, content: string) {.tags: [WriteIOEffect], benign.}
  2561. ## Opens a file named `filename` for writing. Then writes the
  2562. ## `content` completely to the file and closes the file afterwards.
  2563. ## Raises an IO exception in case of an error.
  2564. proc write*(f: File, r: float32) {.tags: [WriteIOEffect], benign.}
  2565. proc write*(f: File, i: int) {.tags: [WriteIOEffect], benign.}
  2566. proc write*(f: File, i: BiggestInt) {.tags: [WriteIOEffect], benign.}
  2567. proc write*(f: File, r: BiggestFloat) {.tags: [WriteIOEffect], benign.}
  2568. proc write*(f: File, s: string) {.tags: [WriteIOEffect], benign.}
  2569. proc write*(f: File, b: bool) {.tags: [WriteIOEffect], benign.}
  2570. proc write*(f: File, c: char) {.tags: [WriteIOEffect], benign.}
  2571. proc write*(f: File, c: cstring) {.tags: [WriteIOEffect], benign.}
  2572. proc write*(f: File, a: varargs[string, `$`]) {.tags: [WriteIOEffect], benign.}
  2573. ## Writes a value to the file `f`. May throw an IO exception.
  2574. proc readLine*(f: File): TaintedString {.tags: [ReadIOEffect], benign.}
  2575. ## reads a line of text from the file `f`. May throw an IO exception.
  2576. ## A line of text may be delimited by ``LF`` or ``CRLF``. The newline
  2577. ## character(s) are not part of the returned string.
  2578. proc readLine*(f: File, line: var TaintedString): bool {.tags: [ReadIOEffect],
  2579. benign.}
  2580. ## reads a line of text from the file `f` into `line`. `line` must not be
  2581. ## ``nil``! May throw an IO exception.
  2582. ## A line of text may be delimited by ``LF`` or ``CRLF``. The newline
  2583. ## character(s) are not part of the returned string. Returns ``false``
  2584. ## if the end of the file has been reached, ``true`` otherwise. If
  2585. ## ``false`` is returned `line` contains no new data.
  2586. proc writeLn*[Ty](f: File, x: varargs[Ty, `$`]) {.inline,
  2587. tags: [WriteIOEffect], benign, deprecated.}
  2588. ## **Deprecated since version 0.11.4:** Use **writeLine** instead.
  2589. proc writeLine*[Ty](f: File, x: varargs[Ty, `$`]) {.inline,
  2590. tags: [WriteIOEffect], benign.}
  2591. ## writes the values `x` to `f` and then writes "\\n".
  2592. ## May throw an IO exception.
  2593. proc getFileSize*(f: File): int64 {.tags: [ReadIOEffect], benign.}
  2594. ## retrieves the file size (in bytes) of `f`.
  2595. proc readBytes*(f: File, a: var openArray[int8|uint8], start, len: Natural): int {.
  2596. tags: [ReadIOEffect], benign.}
  2597. ## reads `len` bytes into the buffer `a` starting at ``a[start]``. Returns
  2598. ## the actual number of bytes that have been read which may be less than
  2599. ## `len` (if not as many bytes are remaining), but not greater.
  2600. proc readChars*(f: File, a: var openArray[char], start, len: Natural): int {.
  2601. tags: [ReadIOEffect], benign.}
  2602. ## reads `len` bytes into the buffer `a` starting at ``a[start]``. Returns
  2603. ## the actual number of bytes that have been read which may be less than
  2604. ## `len` (if not as many bytes are remaining), but not greater.
  2605. ##
  2606. ## **Warning:** The buffer `a` must be pre-allocated. This can be done
  2607. ## using, for example, ``newString``.
  2608. proc readBuffer*(f: File, buffer: pointer, len: Natural): int {.
  2609. tags: [ReadIOEffect], benign.}
  2610. ## reads `len` bytes into the buffer pointed to by `buffer`. Returns
  2611. ## the actual number of bytes that have been read which may be less than
  2612. ## `len` (if not as many bytes are remaining), but not greater.
  2613. proc writeBytes*(f: File, a: openArray[int8|uint8], start, len: Natural): int {.
  2614. tags: [WriteIOEffect], benign.}
  2615. ## writes the bytes of ``a[start..start+len-1]`` to the file `f`. Returns
  2616. ## the number of actual written bytes, which may be less than `len` in case
  2617. ## of an error.
  2618. proc writeChars*(f: File, a: openArray[char], start, len: Natural): int {.
  2619. tags: [WriteIOEffect], benign.}
  2620. ## writes the bytes of ``a[start..start+len-1]`` to the file `f`. Returns
  2621. ## the number of actual written bytes, which may be less than `len` in case
  2622. ## of an error.
  2623. proc writeBuffer*(f: File, buffer: pointer, len: Natural): int {.
  2624. tags: [WriteIOEffect], benign.}
  2625. ## writes the bytes of buffer pointed to by the parameter `buffer` to the
  2626. ## file `f`. Returns the number of actual written bytes, which may be less
  2627. ## than `len` in case of an error.
  2628. proc setFilePos*(f: File, pos: int64, relativeTo: FileSeekPos = fspSet) {.benign.}
  2629. ## sets the position of the file pointer that is used for read/write
  2630. ## operations. The file's first byte has the index zero.
  2631. proc getFilePos*(f: File): int64 {.benign.}
  2632. ## retrieves the current position of the file pointer that is used to
  2633. ## read from the file `f`. The file's first byte has the index zero.
  2634. proc getFileHandle*(f: File): FileHandle
  2635. ## returns the OS file handle of the file ``f``. This is only useful for
  2636. ## platform specific programming.
  2637. when not defined(nimfix):
  2638. {.deprecated: [fileHandle: getFileHandle].}
  2639. when declared(newSeq):
  2640. proc cstringArrayToSeq*(a: cstringArray, len: Natural): seq[string] =
  2641. ## converts a ``cstringArray`` to a ``seq[string]``. `a` is supposed to be
  2642. ## of length ``len``.
  2643. newSeq(result, len)
  2644. for i in 0..len-1: result[i] = $a[i]
  2645. proc cstringArrayToSeq*(a: cstringArray): seq[string] =
  2646. ## converts a ``cstringArray`` to a ``seq[string]``. `a` is supposed to be
  2647. ## terminated by ``nil``.
  2648. var L = 0
  2649. while a[L] != nil: inc(L)
  2650. result = cstringArrayToSeq(a, L)
  2651. # -------------------------------------------------------------------------
  2652. when declared(alloc0) and declared(dealloc):
  2653. proc allocCStringArray*(a: openArray[string]): cstringArray =
  2654. ## creates a NULL terminated cstringArray from `a`. The result has to
  2655. ## be freed with `deallocCStringArray` after it's not needed anymore.
  2656. result = cast[cstringArray](alloc0((a.len+1) * sizeof(cstring)))
  2657. let x = cast[ptr UncheckedArray[string]](a)
  2658. for i in 0 .. a.high:
  2659. result[i] = cast[cstring](alloc0(x[i].len+1))
  2660. copyMem(result[i], addr(x[i][0]), x[i].len)
  2661. proc deallocCStringArray*(a: cstringArray) =
  2662. ## frees a NULL terminated cstringArray.
  2663. var i = 0
  2664. while a[i] != nil:
  2665. dealloc(a[i])
  2666. inc(i)
  2667. dealloc(a)
  2668. when not defined(nimscript):
  2669. proc atomicInc*(memLoc: var int, x: int = 1): int {.inline,
  2670. discardable, benign.}
  2671. ## atomic increment of `memLoc`. Returns the value after the operation.
  2672. proc atomicDec*(memLoc: var int, x: int = 1): int {.inline,
  2673. discardable, benign.}
  2674. ## atomic decrement of `memLoc`. Returns the value after the operation.
  2675. include "system/atomics"
  2676. type
  2677. PSafePoint = ptr TSafePoint
  2678. TSafePoint {.compilerproc, final.} = object
  2679. prev: PSafePoint # points to next safe point ON THE STACK
  2680. status: int
  2681. context: C_JmpBuf
  2682. hasRaiseAction: bool
  2683. raiseAction: proc (e: ref Exception): bool {.closure.}
  2684. SafePoint = TSafePoint
  2685. # {.deprecated: [TSafePoint: SafePoint].}
  2686. when declared(initAllocator):
  2687. initAllocator()
  2688. when hasThreadSupport:
  2689. const insideRLocksModule = false
  2690. include "system/syslocks"
  2691. when hostOS != "standalone": include "system/threads"
  2692. elif not defined(nogc) and not defined(nimscript):
  2693. when not defined(useNimRtl) and not defined(createNimRtl): initStackBottom()
  2694. when declared(initGC): initGC()
  2695. when not defined(nimscript):
  2696. proc setControlCHook*(hook: proc () {.noconv.} not nil)
  2697. ## allows you to override the behaviour of your application when CTRL+C
  2698. ## is pressed. Only one such hook is supported.
  2699. proc writeStackTrace*() {.tags: [WriteIOEffect], gcsafe.}
  2700. ## writes the current stack trace to ``stderr``. This is only works
  2701. ## for debug builds.
  2702. when hostOS != "standalone":
  2703. proc getStackTrace*(): string {.gcsafe.}
  2704. ## gets the current stack trace. This only works for debug builds.
  2705. proc getStackTrace*(e: ref Exception): string {.gcsafe.}
  2706. ## gets the stack trace associated with `e`, which is the stack that
  2707. ## lead to the ``raise`` statement. This only works for debug builds.
  2708. {.push stack_trace: off, profiler:off.}
  2709. when defined(memtracker):
  2710. include "system/memtracker"
  2711. when not defined(nimscript):
  2712. proc zeroMem(p: pointer, size: Natural) =
  2713. c_memset(p, 0, size)
  2714. when declared(memTrackerOp):
  2715. memTrackerOp("zeroMem", p, size)
  2716. proc copyMem(dest, source: pointer, size: Natural) =
  2717. c_memcpy(dest, source, size)
  2718. when declared(memTrackerOp):
  2719. memTrackerOp("copyMem", dest, size)
  2720. proc moveMem(dest, source: pointer, size: Natural) =
  2721. c_memmove(dest, source, size)
  2722. when declared(memTrackerOp):
  2723. memTrackerOp("moveMem", dest, size)
  2724. proc equalMem(a, b: pointer, size: Natural): bool =
  2725. c_memcmp(a, b, size) == 0
  2726. when hostOS == "standalone":
  2727. include "system/embedded"
  2728. else:
  2729. include "system/excpt"
  2730. include "system/chcks"
  2731. # we cannot compile this with stack tracing on
  2732. # as it would recurse endlessly!
  2733. include "system/arithm"
  2734. {.pop.} # stack trace
  2735. {.pop.} # stack trace
  2736. when hostOS != "standalone" and not defined(nimscript):
  2737. include "system/dyncalls"
  2738. when not defined(nimscript):
  2739. include "system/sets"
  2740. when defined(gogc):
  2741. const GenericSeqSize = (3 * sizeof(int))
  2742. else:
  2743. const GenericSeqSize = (2 * sizeof(int))
  2744. proc getDiscriminant(aa: pointer, n: ptr TNimNode): int =
  2745. sysAssert(n.kind == nkCase, "getDiscriminant: node != nkCase")
  2746. var d: int
  2747. var a = cast[ByteAddress](aa)
  2748. case n.typ.size
  2749. of 1: d = ze(cast[ptr int8](a +% n.offset)[])
  2750. of 2: d = ze(cast[ptr int16](a +% n.offset)[])
  2751. of 4: d = int(cast[ptr int32](a +% n.offset)[])
  2752. else: sysAssert(false, "getDiscriminant: invalid n.typ.size")
  2753. return d
  2754. proc selectBranch(aa: pointer, n: ptr TNimNode): ptr TNimNode =
  2755. var discr = getDiscriminant(aa, n)
  2756. if discr <% n.len:
  2757. result = n.sons[discr]
  2758. if result == nil: result = n.sons[n.len]
  2759. # n.sons[n.len] contains the ``else`` part (but may be nil)
  2760. else:
  2761. result = n.sons[n.len]
  2762. {.push profiler:off.}
  2763. when hasAlloc: include "system/mmdisp"
  2764. {.pop.}
  2765. {.push stack_trace: off, profiler:off.}
  2766. when hasAlloc: include "system/sysstr"
  2767. {.pop.}
  2768. when hostOS != "standalone": include "system/sysio"
  2769. when hasThreadSupport:
  2770. when hostOS != "standalone": include "system/channels"
  2771. else:
  2772. include "system/sysio"
  2773. when not defined(nimscript) and hostOS != "standalone":
  2774. iterator lines*(filename: string): TaintedString {.tags: [ReadIOEffect].} =
  2775. ## Iterates over any line in the file named `filename`.
  2776. ##
  2777. ## If the file does not exist `EIO` is raised. The trailing newline
  2778. ## character(s) are removed from the iterated lines. Example:
  2779. ##
  2780. ## .. code-block:: nim
  2781. ## import strutils
  2782. ##
  2783. ## proc transformLetters(filename: string) =
  2784. ## var buffer = ""
  2785. ## for line in filename.lines:
  2786. ## buffer.add(line.replace("a", "0") & '\x0A')
  2787. ## writeFile(filename, buffer)
  2788. var f = open(filename, bufSize=8000)
  2789. defer: close(f)
  2790. var res = TaintedString(newStringOfCap(80))
  2791. while f.readLine(res): yield res
  2792. iterator lines*(f: File): TaintedString {.tags: [ReadIOEffect].} =
  2793. ## Iterate over any line in the file `f`.
  2794. ##
  2795. ## The trailing newline character(s) are removed from the iterated lines.
  2796. ## Example:
  2797. ##
  2798. ## .. code-block:: nim
  2799. ## proc countZeros(filename: File): tuple[lines, zeros: int] =
  2800. ## for line in filename.lines:
  2801. ## for letter in line:
  2802. ## if letter == '0':
  2803. ## result.zeros += 1
  2804. ## result.lines += 1
  2805. var res = TaintedString(newStringOfCap(80))
  2806. while f.readLine(res): yield res
  2807. when not defined(nimscript) and hasAlloc:
  2808. include "system/assign"
  2809. include "system/repr"
  2810. when hostOS != "standalone" and not defined(nimscript):
  2811. proc getCurrentException*(): ref Exception {.compilerRtl, inl, benign.} =
  2812. ## retrieves the current exception; if there is none, nil is returned.
  2813. result = currException
  2814. proc getCurrentExceptionMsg*(): string {.inline, benign.} =
  2815. ## retrieves the error message that was attached to the current
  2816. ## exception; if there is none, "" is returned.
  2817. var e = getCurrentException()
  2818. return if e == nil: "" else: e.msg
  2819. proc onRaise*(action: proc(e: ref Exception): bool{.closure.}) =
  2820. ## can be used in a ``try`` statement to setup a Lisp-like
  2821. ## `condition system`:idx:\: This prevents the 'raise' statement to
  2822. ## raise an exception but instead calls ``action``.
  2823. ## If ``action`` returns false, the exception has been handled and
  2824. ## does not propagate further through the call stack.
  2825. if not isNil(excHandler):
  2826. excHandler.hasRaiseAction = true
  2827. excHandler.raiseAction = action
  2828. proc setCurrentException*(exc: ref Exception) {.inline, benign.} =
  2829. ## sets the current exception.
  2830. ##
  2831. ## **Warning**: Only use this if you know what you are doing.
  2832. currException = exc
  2833. {.push stack_trace: off, profiler:off.}
  2834. when defined(endb) and not defined(nimscript):
  2835. include "system/debugger"
  2836. when defined(profiler) or defined(memProfiler):
  2837. include "system/profiler"
  2838. {.pop.} # stacktrace
  2839. when not defined(nimscript):
  2840. proc rawProc*[T: proc](x: T): pointer {.noSideEffect, inline.} =
  2841. ## retrieves the raw proc pointer of the closure `x`. This is
  2842. ## useful for interfacing closures with C.
  2843. {.emit: """
  2844. `result` = `x`.ClP_0;
  2845. """.}
  2846. proc rawEnv*[T: proc](x: T): pointer {.noSideEffect, inline.} =
  2847. ## retrieves the raw environment pointer of the closure `x`. This is
  2848. ## useful for interfacing closures with C.
  2849. {.emit: """
  2850. `result` = `x`.ClE_0;
  2851. """.}
  2852. proc finished*[T: proc](x: T): bool {.noSideEffect, inline.} =
  2853. ## can be used to determine if a first class iterator has finished.
  2854. {.emit: """
  2855. `result` = ((NI*) `x`.ClE_0)[1] < 0;
  2856. """.}
  2857. elif defined(JS):
  2858. # Stubs:
  2859. proc getOccupiedMem(): int = return -1
  2860. proc getFreeMem(): int = return -1
  2861. proc getTotalMem(): int = return -1
  2862. proc dealloc(p: pointer) = discard
  2863. proc alloc(size: Natural): pointer = discard
  2864. proc alloc0(size: Natural): pointer = discard
  2865. proc realloc(p: pointer, newsize: Natural): pointer = discard
  2866. proc allocShared(size: Natural): pointer = discard
  2867. proc allocShared0(size: Natural): pointer = discard
  2868. proc deallocShared(p: pointer) = discard
  2869. proc reallocShared(p: pointer, newsize: Natural): pointer = discard
  2870. when defined(JS):
  2871. include "system/jssys"
  2872. include "system/reprjs"
  2873. elif defined(nimscript):
  2874. proc cmp(x, y: string): int =
  2875. if x == y: return 0
  2876. if x < y: return -1
  2877. return 1
  2878. when defined(nimffi):
  2879. include "system/sysio"
  2880. proc quit*(errormsg: string, errorcode = QuitFailure) {.noReturn.} =
  2881. ## a shorthand for ``echo(errormsg); quit(errorcode)``.
  2882. echo(errormsg)
  2883. quit(errorcode)
  2884. {.pop.} # checks
  2885. {.pop.} # hints
  2886. when not defined(JS):
  2887. proc likely_proc(val: bool): bool {.importc: "likely", nodecl, nosideeffect.}
  2888. proc unlikely_proc(val: bool): bool {.importc: "unlikely", nodecl, nosideeffect.}
  2889. template likely*(val: bool): bool =
  2890. ## Hints the optimizer that `val` is likely going to be true.
  2891. ##
  2892. ## You can use this template to decorate a branch condition. On certain
  2893. ## platforms this can help the processor predict better which branch is
  2894. ## going to be run. Example:
  2895. ##
  2896. ## .. code-block:: nim
  2897. ## for value in inputValues:
  2898. ## if likely(value <= 100):
  2899. ## process(value)
  2900. ## else:
  2901. ## echo "Value too big!"
  2902. ##
  2903. ## On backends without branch prediction (JS and the nimscript VM), this
  2904. ## template will not affect code execution.
  2905. when nimvm:
  2906. val
  2907. else:
  2908. when defined(JS):
  2909. val
  2910. else:
  2911. likely_proc(val)
  2912. template unlikely*(val: bool): bool =
  2913. ## Hints the optimizer that `val` is likely going to be false.
  2914. ##
  2915. ## You can use this proc to decorate a branch condition. On certain
  2916. ## platforms this can help the processor predict better which branch is
  2917. ## going to be run. Example:
  2918. ##
  2919. ## .. code-block:: nim
  2920. ## for value in inputValues:
  2921. ## if unlikely(value > 100):
  2922. ## echo "Value too big!"
  2923. ## else:
  2924. ## process(value)
  2925. ##
  2926. ## On backends without branch prediction (JS and the nimscript VM), this
  2927. ## template will not affect code execution.
  2928. when nimvm:
  2929. val
  2930. else:
  2931. when defined(JS):
  2932. val
  2933. else:
  2934. unlikely_proc(val)
  2935. proc `/`*(x, y: int): float {.inline, noSideEffect.} =
  2936. ## integer division that results in a float.
  2937. result = toFloat(x) / toFloat(y)
  2938. template spliceImpl(s, a, L, b: untyped): untyped =
  2939. # make room for additional elements or cut:
  2940. var shift = b.len - max(0,L) # ignore negative slice size
  2941. var newLen = s.len + shift
  2942. if shift > 0:
  2943. # enlarge:
  2944. setLen(s, newLen)
  2945. for i in countdown(newLen-1, a+b.len): shallowCopy(s[i], s[i-shift])
  2946. else:
  2947. for i in countup(a+b.len, newLen-1): shallowCopy(s[i], s[i-shift])
  2948. # cut down:
  2949. setLen(s, newLen)
  2950. # fill the hole:
  2951. for i in 0 .. <b.len: s[a+i] = b[i]
  2952. when hasAlloc or defined(nimscript):
  2953. proc `[]`*(s: string, x: Slice[int]): string {.inline.} =
  2954. ## slice operation for strings.
  2955. ## returns the inclusive range [s[x.a], s[x.b]]:
  2956. ##
  2957. ## .. code-block:: nim
  2958. ## var s = "abcdef"
  2959. ## assert s[1..3] == "bcd"
  2960. result = s.substr(x.a, x.b)
  2961. proc `[]=`*(s: var string, x: Slice[int], b: string) =
  2962. ## slice assignment for strings. If
  2963. ## ``b.len`` is not exactly the number of elements that are referred to
  2964. ## by `x`, a `splice`:idx: is performed:
  2965. ##
  2966. ## .. code-block:: nim
  2967. ## var s = "abcdef"
  2968. ## s[1 .. ^2] = "xyz"
  2969. ## assert s == "axyzf"
  2970. var a = x.a
  2971. var L = x.b - a + 1
  2972. if L == b.len:
  2973. for i in 0 .. <L: s[i+a] = b[i]
  2974. else:
  2975. spliceImpl(s, a, L, b)
  2976. proc `[]`*[Idx, T](a: array[Idx, T], x: Slice[int]): seq[T] =
  2977. ## slice operation for arrays.
  2978. ## returns the inclusive range [a[x.a], a[x.b]]:
  2979. ##
  2980. ## .. code-block:: nim
  2981. ## var a = [1,2,3,4]
  2982. ## assert a[0..2] == @[1,2,3]
  2983. when low(a) < 0:
  2984. {.error: "Slicing for arrays with negative indices is unsupported.".}
  2985. var L = x.b - x.a + 1
  2986. result = newSeq[T](L)
  2987. for i in 0.. <L: result[i] = a[i + x.a]
  2988. proc `[]=`*[Idx, T](a: var array[Idx, T], x: Slice[int], b: openArray[T]) =
  2989. ## slice assignment for arrays.
  2990. when low(a) < 0:
  2991. {.error: "Slicing for arrays with negative indices is unsupported.".}
  2992. var L = x.b - x.a + 1
  2993. if L == b.len:
  2994. for i in 0 .. <L: a[i+x.a] = b[i]
  2995. else:
  2996. sysFatal(RangeError, "different lengths for slice assignment")
  2997. proc `[]`*[Idx, T](a: array[Idx, T], x: Slice[Idx]): seq[T] =
  2998. ## slice operation for arrays.
  2999. var L = ord(x.b) - ord(x.a) + 1
  3000. newSeq(result, L)
  3001. for i in 0.. <L:
  3002. result[i] = a[Idx(ord(x.a) + i)]
  3003. proc `[]=`*[Idx, T](a: var array[Idx, T], x: Slice[Idx], b: openArray[T]) =
  3004. ## slice assignment for arrays.
  3005. var L = ord(x.b) - ord(x.a) + 1
  3006. if L == b.len:
  3007. for i in 0 .. <L:
  3008. a[Idx(ord(x.a) + i)] = b[i]
  3009. else:
  3010. sysFatal(RangeError, "different lengths for slice assignment")
  3011. proc `[]`*[T](s: seq[T], x: Slice[int]): seq[T] =
  3012. ## slice operation for sequences.
  3013. ## returns the inclusive range [s[x.a], s[x.b]]:
  3014. ##
  3015. ## .. code-block:: nim
  3016. ## var s = @[1,2,3,4]
  3017. ## assert s[0..2] == @[1,2,3]
  3018. var a = x.a
  3019. var L = x.b - a + 1
  3020. newSeq(result, L)
  3021. for i in 0.. <L: result[i] = s[i + a]
  3022. proc `[]=`*[T](s: var seq[T], x: Slice[int], b: openArray[T]) =
  3023. ## slice assignment for sequences. If
  3024. ## ``b.len`` is not exactly the number of elements that are referred to
  3025. ## by `x`, a `splice`:idx: is performed.
  3026. var a = x.a
  3027. var L = x.b - a + 1
  3028. if L == b.len:
  3029. for i in 0 .. <L: s[i+a] = b[i]
  3030. else:
  3031. spliceImpl(s, a, L, b)
  3032. proc slurp*(filename: string): string {.magic: "Slurp".}
  3033. ## This is an alias for `staticRead <#staticRead>`_.
  3034. proc staticRead*(filename: string): string {.magic: "Slurp".}
  3035. ## Compile-time `readFile <#readFile>`_ proc for easy `resource`:idx:
  3036. ## embedding:
  3037. ##
  3038. ## .. code-block:: nim
  3039. ## const myResource = staticRead"mydatafile.bin"
  3040. ##
  3041. ## `slurp <#slurp>`_ is an alias for ``staticRead``.
  3042. proc gorge*(command: string, input = "", cache = ""): string {.
  3043. magic: "StaticExec".} = discard
  3044. ## This is an alias for `staticExec <#staticExec>`_.
  3045. proc staticExec*(command: string, input = "", cache = ""): string {.
  3046. magic: "StaticExec".} = discard
  3047. ## Executes an external process at compile-time.
  3048. ## if `input` is not an empty string, it will be passed as a standard input
  3049. ## to the executed program.
  3050. ##
  3051. ## .. code-block:: nim
  3052. ## const buildInfo = "Revision " & staticExec("git rev-parse HEAD") &
  3053. ## "\nCompiled on " & staticExec("uname -v")
  3054. ##
  3055. ## `gorge <#gorge>`_ is an alias for ``staticExec``. Note that you can use
  3056. ## this proc inside a pragma like `passC <nimc.html#passc-pragma>`_ or `passL
  3057. ## <nimc.html#passl-pragma>`_.
  3058. ##
  3059. ## If ``cache`` is not empty, the results of ``staticExec`` are cached within
  3060. ## the ``nimcache`` directory. Use ``--forceBuild`` to get rid of this caching
  3061. ## behaviour then. ``command & input & cache`` (the concatenated string) is
  3062. ## used to determine whether the entry in the cache is still valid. You can
  3063. ## use versioning information for ``cache``:
  3064. ##
  3065. ## .. code-block:: nim
  3066. ## const stateMachine = staticExec("dfaoptimizer", "input", "0.8.0")
  3067. proc gorgeEx*(command: string, input = "", cache = ""): tuple[output: string,
  3068. exitCode: int] =
  3069. ## Same as `gorge` but also returns the precious exit code.
  3070. discard
  3071. proc `+=`*[T: SomeOrdinal|uint|uint64](x: var T, y: T) {.
  3072. magic: "Inc", noSideEffect.}
  3073. ## Increments an ordinal
  3074. proc `-=`*[T: SomeOrdinal|uint|uint64](x: var T, y: T) {.
  3075. magic: "Dec", noSideEffect.}
  3076. ## Decrements an ordinal
  3077. proc `*=`*[T: SomeOrdinal|uint|uint64](x: var T, y: T) {.
  3078. inline, noSideEffect.} =
  3079. ## Binary `*=` operator for ordinals
  3080. x = x * y
  3081. proc `+=`*[T: float|float32|float64] (x: var T, y: T) {.
  3082. inline, noSideEffect.} =
  3083. ## Increments in place a floating point number
  3084. x = x + y
  3085. proc `-=`*[T: float|float32|float64] (x: var T, y: T) {.
  3086. inline, noSideEffect.} =
  3087. ## Decrements in place a floating point number
  3088. x = x - y
  3089. proc `*=`*[T: float|float32|float64] (x: var T, y: T) {.
  3090. inline, noSideEffect.} =
  3091. ## Multiplies in place a floating point number
  3092. x = x * y
  3093. proc `/=`*(x: var float64, y: float64) {.inline, noSideEffect.} =
  3094. ## Divides in place a floating point number
  3095. x = x / y
  3096. proc `/=`*[T: float|float32](x: var T, y: T) {.inline, noSideEffect.} =
  3097. ## Divides in place a floating point number
  3098. x = x / y
  3099. proc `&=`* (x: var string, y: string) {.magic: "AppendStrStr", noSideEffect.}
  3100. template `&=`*(x, y: typed) =
  3101. ## generic 'sink' operator for Nim. For files an alias for ``write``.
  3102. ## If not specialized further an alias for ``add``.
  3103. add(x, y)
  3104. when declared(File):
  3105. template `&=`*(f: File, x: typed) = write(f, x)
  3106. proc astToStr*[T](x: T): string {.magic: "AstToStr", noSideEffect.}
  3107. ## converts the AST of `x` into a string representation. This is very useful
  3108. ## for debugging.
  3109. proc instantiationInfo*(index = -1, fullPaths = false): tuple[
  3110. filename: string, line: int] {. magic: "InstantiationInfo", noSideEffect.}
  3111. ## provides access to the compiler's instantiation stack line information
  3112. ## of a template.
  3113. ##
  3114. ## While similar to the `caller info`:idx: of other languages, it is determined
  3115. ## at compile time.
  3116. ##
  3117. ## This proc is mostly useful for meta programming (eg. ``assert`` template)
  3118. ## to retrieve information about the current filename and line number.
  3119. ## Example:
  3120. ##
  3121. ## .. code-block:: nim
  3122. ## import strutils
  3123. ##
  3124. ## template testException(exception, code: expr): stmt =
  3125. ## try:
  3126. ## let pos = instantiationInfo()
  3127. ## discard(code)
  3128. ## echo "Test failure at $1:$2 with '$3'" % [pos.filename,
  3129. ## $pos.line, astToStr(code)]
  3130. ## assert false, "A test expecting failure succeeded?"
  3131. ## except exception:
  3132. ## discard
  3133. ##
  3134. ## proc tester(pos: int): int =
  3135. ## let
  3136. ## a = @[1, 2, 3]
  3137. ## result = a[pos]
  3138. ##
  3139. ## when isMainModule:
  3140. ## testException(IndexError, tester(30))
  3141. ## testException(IndexError, tester(1))
  3142. ## # --> Test failure at example.nim:20 with 'tester(1)'
  3143. template currentSourcePath*: string = instantiationInfo(-1, true).filename
  3144. ## returns the full file-system path of the current source
  3145. proc raiseAssert*(msg: string) {.noinline.} =
  3146. sysFatal(AssertionError, msg)
  3147. proc failedAssertImpl*(msg: string) {.raises: [], tags: [].} =
  3148. # trick the compiler to not list ``AssertionError`` when called
  3149. # by ``assert``.
  3150. type Hide = proc (msg: string) {.noinline, raises: [], noSideEffect,
  3151. tags: [].}
  3152. {.deprecated: [THide: Hide].}
  3153. Hide(raiseAssert)(msg)
  3154. template assert*(cond: bool, msg = "") =
  3155. ## Raises ``AssertionError`` with `msg` if `cond` is false. Note
  3156. ## that ``AssertionError`` is hidden from the effect system, so it doesn't
  3157. ## produce ``{.raises: [AssertionError].}``. This exception is only supposed
  3158. ## to be caught by unit testing frameworks.
  3159. ## The compiler may not generate any code at all for ``assert`` if it is
  3160. ## advised to do so through the ``-d:release`` or ``--assertions:off``
  3161. ## `command line switches <nimc.html#command-line-switches>`_.
  3162. bind instantiationInfo
  3163. mixin failedAssertImpl
  3164. when compileOption("assertions"):
  3165. {.line.}:
  3166. if not cond: failedAssertImpl(astToStr(cond) & ' ' & msg)
  3167. template doAssert*(cond: bool, msg = "") =
  3168. ## same as `assert` but is always turned on and not affected by the
  3169. ## ``--assertions`` command line switch.
  3170. bind instantiationInfo
  3171. {.line: instantiationInfo().}:
  3172. if not cond:
  3173. raiseAssert(astToStr(cond) & ' ' & msg)
  3174. iterator items*[T](a: seq[T]): T {.inline.} =
  3175. ## iterates over each item of `a`.
  3176. var i = 0
  3177. let L = len(a)
  3178. while i < L:
  3179. yield a[i]
  3180. inc(i)
  3181. assert(len(a) == L, "seq modified while iterating over it")
  3182. iterator mitems*[T](a: var seq[T]): var T {.inline.} =
  3183. ## iterates over each item of `a` so that you can modify the yielded value.
  3184. var i = 0
  3185. let L = len(a)
  3186. while i < L:
  3187. yield a[i]
  3188. inc(i)
  3189. assert(len(a) == L, "seq modified while iterating over it")
  3190. iterator items*(a: string): char {.inline.} =
  3191. ## iterates over each item of `a`.
  3192. var i = 0
  3193. let L = len(a)
  3194. while i < L:
  3195. yield a[i]
  3196. inc(i)
  3197. assert(len(a) == L, "string modified while iterating over it")
  3198. iterator mitems*(a: var string): var char {.inline.} =
  3199. ## iterates over each item of `a` so that you can modify the yielded value.
  3200. var i = 0
  3201. let L = len(a)
  3202. while i < L:
  3203. yield a[i]
  3204. inc(i)
  3205. assert(len(a) == L, "string modified while iterating over it")
  3206. when not defined(nimhygiene):
  3207. {.pragma: inject.}
  3208. template onFailedAssert*(msg, code: untyped): untyped {.dirty.} =
  3209. ## Sets an assertion failure handler that will intercept any assert
  3210. ## statements following `onFailedAssert` in the current module scope.
  3211. ##
  3212. ## .. code-block:: nim
  3213. ## # module-wide policy to change the failed assert
  3214. ## # exception type in order to include a lineinfo
  3215. ## onFailedAssert(msg):
  3216. ## var e = new(TMyError)
  3217. ## e.msg = msg
  3218. ## e.lineinfo = instantiationInfo(-2)
  3219. ## raise e
  3220. ##
  3221. template failedAssertImpl(msgIMPL: string): untyped {.dirty.} =
  3222. let msg = msgIMPL
  3223. code
  3224. proc shallow*[T](s: var seq[T]) {.noSideEffect, inline.} =
  3225. ## marks a sequence `s` as `shallow`:idx:. Subsequent assignments will not
  3226. ## perform deep copies of `s`. This is only useful for optimization
  3227. ## purposes.
  3228. when not defined(JS) and not defined(nimscript):
  3229. var s = cast[PGenericSeq](s)
  3230. s.reserved = s.reserved or seqShallowFlag
  3231. proc shallow*(s: var string) {.noSideEffect, inline.} =
  3232. ## marks a string `s` as `shallow`:idx:. Subsequent assignments will not
  3233. ## perform deep copies of `s`. This is only useful for optimization
  3234. ## purposes.
  3235. when not defined(JS) and not defined(nimscript):
  3236. var s = cast[PGenericSeq](s)
  3237. s.reserved = s.reserved or seqShallowFlag
  3238. type
  3239. NimNodeObj = object
  3240. NimNode* {.magic: "PNimrodNode".} = ref NimNodeObj
  3241. ## represents a Nim AST node. Macros operate on this type.
  3242. {.deprecated: [PNimrodNode: NimNode].}
  3243. when false:
  3244. template eval*(blk: stmt): stmt =
  3245. ## executes a block of code at compile time just as if it was a macro
  3246. ## optionally, the block can return an AST tree that will replace the
  3247. ## eval expression
  3248. macro payload: stmt {.gensym.} = blk
  3249. payload()
  3250. when hasAlloc:
  3251. proc insert*(x: var string, item: string, i = 0.Natural) {.noSideEffect.} =
  3252. ## inserts `item` into `x` at position `i`.
  3253. var xl = x.len
  3254. setLen(x, xl+item.len)
  3255. var j = xl-1
  3256. while j >= i:
  3257. shallowCopy(x[j+item.len], x[j])
  3258. dec(j)
  3259. j = 0
  3260. while j < item.len:
  3261. x[j+i] = item[j]
  3262. inc(j)
  3263. proc compiles*(x: untyped): bool {.magic: "Compiles", noSideEffect, compileTime.} =
  3264. ## Special compile-time procedure that checks whether `x` can be compiled
  3265. ## without any semantic error.
  3266. ## This can be used to check whether a type supports some operation:
  3267. ##
  3268. ## .. code-block:: Nim
  3269. ## when compiles(3 + 4):
  3270. ## echo "'+' for integers is available"
  3271. discard
  3272. when declared(initDebugger):
  3273. initDebugger()
  3274. when hasAlloc:
  3275. # XXX: make these the default (or implement the NilObject optimization)
  3276. proc safeAdd*[T](x: var seq[T], y: T) {.noSideEffect.} =
  3277. ## Adds ``y`` to ``x`` unless ``x`` is not yet initialized; in that case,
  3278. ## ``x`` becomes ``@[y]``
  3279. if x == nil: x = @[y]
  3280. else: x.add(y)
  3281. proc safeAdd*(x: var string, y: char) =
  3282. ## Adds ``y`` to ``x``. If ``x`` is ``nil`` it is initialized to ``""``
  3283. if x == nil: x = ""
  3284. x.add(y)
  3285. proc safeAdd*(x: var string, y: string) =
  3286. ## Adds ``y`` to ``x`` unless ``x`` is not yet initalized; in that
  3287. ## case, ``x`` becomes ``y``
  3288. if x == nil: x = y
  3289. else: x.add(y)
  3290. proc locals*(): RootObj {.magic: "Plugin", noSideEffect.} =
  3291. ## generates a tuple constructor expression listing all the local variables
  3292. ## in the current scope. This is quite fast as it does not rely
  3293. ## on any debug or runtime information. Note that in contrast to what
  3294. ## the official signature says, the return type is not ``RootObj`` but a
  3295. ## tuple of a structure that depends on the current scope. Example:
  3296. ##
  3297. ## .. code-block:: nim
  3298. ## proc testLocals() =
  3299. ## var
  3300. ## a = "something"
  3301. ## b = 4
  3302. ## c = locals()
  3303. ## d = "super!"
  3304. ##
  3305. ## b = 1
  3306. ## for name, value in fieldPairs(c):
  3307. ## echo "name ", name, " with value ", value
  3308. ## echo "B is ", b
  3309. ## # -> name a with value something
  3310. ## # -> name b with value 4
  3311. ## # -> B is 1
  3312. discard
  3313. when hasAlloc and not defined(nimscript) and not defined(JS):
  3314. proc deepCopy*[T](x: var T, y: T) {.noSideEffect, magic: "DeepCopy".} =
  3315. ## performs a deep copy of `y` and copies it into `x`.
  3316. ## This is also used by the code generator
  3317. ## for the implementation of ``spawn``.
  3318. discard
  3319. include "system/deepcopy"
  3320. proc procCall*(x: untyped) {.magic: "ProcCall", compileTime.} =
  3321. ## special magic to prohibit dynamic binding for `method`:idx: calls.
  3322. ## This is similar to `super`:idx: in ordinary OO languages.
  3323. ##
  3324. ## .. code-block:: nim
  3325. ## # 'someMethod' will be resolved fully statically:
  3326. ## procCall someMethod(a, b)
  3327. discard
  3328. proc `^`*[T](x: int; y: openArray[T]): int {.noSideEffect, magic: "Roof".}
  3329. proc `^`*(x: int): int {.noSideEffect, magic: "Roof".} =
  3330. ## builtin `roof`:idx: operator that can be used for convenient array access.
  3331. ## ``a[^x]`` is rewritten to ``a[a.len-x]``. However currently the ``a``
  3332. ## expression must not have side effects for this to compile. Note that since
  3333. ## this is a builtin, it automatically works for all kinds of
  3334. ## overloaded ``[]`` or ``[]=`` accessors.
  3335. discard
  3336. template `..^`*(a, b: untyped): untyped =
  3337. ## a shortcut for '.. ^' to avoid the common gotcha that a space between
  3338. ## '..' and '^' is required.
  3339. a .. ^b
  3340. template `..<`*(a, b: untyped): untyped {.dirty.} =
  3341. ## a shortcut for '.. <' to avoid the common gotcha that a space between
  3342. ## '..' and '<' is required.
  3343. a .. <b
  3344. iterator `..<`*[S,T](a: S, b: T): T =
  3345. var i = T(a)
  3346. while i < b:
  3347. yield i
  3348. inc i
  3349. proc xlen*(x: string): int {.magic: "XLenStr", noSideEffect.} = discard
  3350. proc xlen*[T](x: seq[T]): int {.magic: "XLenSeq", noSideEffect.} =
  3351. ## returns the length of a sequence or a string without testing for 'nil'.
  3352. ## This is an optimization that rarely makes sense.
  3353. discard
  3354. proc `==` *(x, y: cstring): bool {.magic: "EqCString", noSideEffect,
  3355. inline.} =
  3356. ## Checks for equality between two `cstring` variables.
  3357. proc strcmp(a, b: cstring): cint {.noSideEffect,
  3358. importc, header: "<string.h>".}
  3359. if pointer(x) == pointer(y): result = true
  3360. elif x.isNil or y.isNil: result = false
  3361. else: result = strcmp(x, y) == 0
  3362. template closureScope*(body: untyped): untyped =
  3363. ## Useful when creating a closure in a loop to capture local loop variables by
  3364. ## their current iteration values. Example:
  3365. ##
  3366. ## .. code-block:: nim
  3367. ## var myClosure : proc()
  3368. ## # without closureScope:
  3369. ## for i in 0 .. 5:
  3370. ## let j = i
  3371. ## if j == 3:
  3372. ## myClosure = proc() = echo j
  3373. ## myClosure() # outputs 5. `j` is changed after closure creation
  3374. ## # with closureScope:
  3375. ## for i in 0 .. 5:
  3376. ## closureScope: # Everything in this scope is locked after closure creation
  3377. ## let j = i
  3378. ## if j == 3:
  3379. ## myClosure = proc() = echo j
  3380. ## myClosure() # outputs 3
  3381. (proc() = body)()
  3382. {.pop.} #{.push warning[GcMem]: off, warning[Uninit]: off.}
  3383. when defined(nimconfig):
  3384. include "system/nimscript"
  3385. when defined(windows) and appType == "console" and defined(nimSetUtf8CodePage):
  3386. proc setConsoleOutputCP(codepage: cint): cint {.stdcall, dynlib: "kernel32",
  3387. importc: "SetConsoleOutputCP".}
  3388. discard setConsoleOutputCP(65001) # 65001 - utf-8 codepage