system.nim 165 KB

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