system.nim 168 KB

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