system.nim 167 KB

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