system.nim 168 KB

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