system.nim 162 KB

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