system.nim 153 KB

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