manual.rst 244 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034
  1. ==========
  2. Nim Manual
  3. ==========
  4. :Authors: Andreas Rumpf, Zahary Karadjov
  5. :Version: |nimversion|
  6. .. default-role:: code
  7. .. include:: rstcommon.rst
  8. .. contents::
  9. "Complexity" seems to be a lot like "energy": you can transfer it from the
  10. end-user to one/some of the other players, but the total amount seems to remain
  11. pretty much constant for a given task. -- Ran
  12. About this document
  13. ===================
  14. **Note**: This document is a draft! Several of Nim's features may need more
  15. precise wording. This manual is constantly evolving into a proper specification.
  16. **Note**: The experimental features of Nim are
  17. covered `here <manual_experimental.html>`_.
  18. **Note**: Assignments, moves, and destruction are specified in
  19. the `destructors <destructors.html>`_ document.
  20. This document describes the lexis, the syntax, and the semantics of the Nim language.
  21. To learn how to compile Nim programs and generate documentation see
  22. the `Compiler User Guide <nimc.html>`_ and the `DocGen Tools Guide <docgen.html>`_.
  23. The language constructs are explained using an extended BNF, in which `(a)*`
  24. means 0 or more `a`'s, `a+` means 1 or more `a`'s, and `(a)?` means an
  25. optional *a*. Parentheses may be used to group elements.
  26. `&` is the lookahead operator; `&a` means that an `a` is expected but
  27. not consumed. It will be consumed in the following rule.
  28. The `|`, `/` symbols are used to mark alternatives and have the lowest
  29. precedence. `/` is the ordered choice that requires the parser to try the
  30. alternatives in the given order. `/` is often used to ensure the grammar
  31. is not ambiguous.
  32. Non-terminals start with a lowercase letter, abstract terminal symbols are in
  33. UPPERCASE. Verbatim terminal symbols (including keywords) are quoted
  34. with `'`. An example::
  35. ifStmt = 'if' expr ':' stmts ('elif' expr ':' stmts)* ('else' stmts)?
  36. The binary `^*` operator is used as a shorthand for 0 or more occurrences
  37. separated by its second argument; likewise `^+` means 1 or more
  38. occurrences: `a ^+ b` is short for `a (b a)*`
  39. and `a ^* b` is short for `(a (b a)*)?`. Example::
  40. arrayConstructor = '[' expr ^* ',' ']'
  41. Other parts of Nim, like scoping rules or runtime semantics, are
  42. described informally.
  43. Definitions
  44. ===========
  45. Nim code specifies a computation that acts on a memory consisting of
  46. components called `locations`:idx:. A variable is basically a name for a
  47. location. Each variable and location is of a certain `type`:idx:. The
  48. variable's type is called `static type`:idx:, the location's type is called
  49. `dynamic type`:idx:. If the static type is not the same as the dynamic type,
  50. it is a super-type or subtype of the dynamic type.
  51. An `identifier`:idx: is a symbol declared as a name for a variable, type,
  52. procedure, etc. The region of the program over which a declaration applies is
  53. called the `scope`:idx: of the declaration. Scopes can be nested. The meaning
  54. of an identifier is determined by the smallest enclosing scope in which the
  55. identifier is declared unless overloading resolution rules suggest otherwise.
  56. An expression specifies a computation that produces a value or location.
  57. Expressions that produce locations are called `l-values`:idx:. An l-value
  58. can denote either a location or the value the location contains, depending on
  59. the context.
  60. A Nim `program`:idx: consists of one or more text `source files`:idx: containing
  61. Nim code. It is processed by a Nim `compiler`:idx: into an `executable`:idx:.
  62. The nature of this executable depends on the compiler implementation; it may,
  63. for example, be a native binary or JavaScript source code.
  64. In a typical Nim program, most of the code is compiled into the executable.
  65. However, some of the code may be executed at
  66. `compile-time`:idx:. This can include constant expressions, macro definitions,
  67. and Nim procedures used by macro definitions. Most of the Nim language is
  68. supported at compile-time, but there are some restrictions -- see `Restrictions
  69. on Compile-Time Execution <#restrictions-on-compileminustime-execution>`_ for
  70. details. We use the term `runtime`:idx: to cover both compile-time execution
  71. and code execution in the executable.
  72. The compiler parses Nim source code into an internal data structure called the
  73. `abstract syntax tree`:idx: (`AST`:idx:). Then, before executing the code or
  74. compiling it into the executable, it transforms the AST through
  75. `semantic analysis`:idx:. This adds semantic information such as expression types,
  76. identifier meanings, and in some cases expression values. An error detected
  77. during semantic analysis is called a `static error`:idx:. Errors described in
  78. this manual are static errors when not otherwise specified.
  79. A `panic`:idx: is an error that the implementation detects
  80. and reports at runtime. The method for reporting such errors is via
  81. *raising exceptions* or *dying with a fatal error*. However, the implementation
  82. provides a means to disable these `runtime checks`:idx:. See the section
  83. pragmas_ for details.
  84. Whether a panic results in an exception or in a fatal error is
  85. implementation specific. Thus the following program is invalid; even though the
  86. code purports to catch the `IndexDefect` from an out-of-bounds array access, the
  87. compiler may instead choose to allow the program to die with a fatal error.
  88. .. code-block:: nim
  89. var a: array[0..1, char]
  90. let i = 5
  91. try:
  92. a[i] = 'N'
  93. except IndexDefect:
  94. echo "invalid index"
  95. The current implementation allows to switch between these different behaviors
  96. via `--panics:on|off`:option:. When panics are turned on, the program dies with a
  97. panic, if they are turned off the runtime errors are turned into
  98. exceptions. The benefit of `--panics:on`:option: is that it produces smaller binary
  99. code and the compiler has more freedom to optimize the code.
  100. An `unchecked runtime error`:idx: is an error that is not guaranteed to be
  101. detected and can cause the subsequent behavior of the computation to
  102. be arbitrary. Unchecked runtime errors cannot occur if only `safe`:idx:
  103. language features are used and if no runtime checks are disabled.
  104. A `constant expression`:idx: is an expression whose value can be computed during
  105. a semantic analysis of the code in which it appears. It is never an l-value and
  106. never has side effects. Constant expressions are not limited to the capabilities
  107. of semantic analysis, such as constant folding; they can use all Nim language
  108. features that are supported for compile-time execution. Since constant
  109. expressions can be used as an input to semantic analysis (such as for defining
  110. array bounds), this flexibility requires the compiler to interleave semantic
  111. analysis and compile-time code execution.
  112. It is mostly accurate to picture semantic analysis proceeding top to bottom and
  113. left to right in the source code, with compile-time code execution interleaved
  114. when necessary to compute values that are required for subsequent semantic
  115. analysis. We will see much later in this document that macro invocation not only
  116. requires this interleaving, but also creates a situation where semantic analysis
  117. does not entirely proceed top to bottom and left to right.
  118. Lexical Analysis
  119. ================
  120. Encoding
  121. --------
  122. All Nim source files are in the UTF-8 encoding (or its ASCII subset). Other
  123. encodings are not supported. Any of the standard platform line termination
  124. sequences can be used - the Unix form using ASCII LF (linefeed), the Windows
  125. form using the ASCII sequence CR LF (return followed by linefeed), or the old
  126. Macintosh form using the ASCII CR (return) character. All of these forms can be
  127. used equally, regardless of the platform.
  128. Indentation
  129. -----------
  130. Nim's standard grammar describes an `indentation sensitive`:idx: language.
  131. This means that all the control structures are recognized by indentation.
  132. Indentation consists only of spaces; tabulators are not allowed.
  133. The indentation handling is implemented as follows: The lexer annotates the
  134. following token with the preceding number of spaces; indentation is not
  135. a separate token. This trick allows parsing of Nim with only 1 token of
  136. lookahead.
  137. The parser uses a stack of indentation levels: the stack consists of integers
  138. counting the spaces. The indentation information is queried at strategic
  139. places in the parser but ignored otherwise: The pseudo-terminal `IND{>}`
  140. denotes an indentation that consists of more spaces than the entry at the top
  141. of the stack; `IND{=}` an indentation that has the same number of spaces. `DED`
  142. is another pseudo terminal that describes the *action* of popping a value
  143. from the stack, `IND{>}` then implies to push onto the stack.
  144. With this notation we can now easily define the core of the grammar: A block of
  145. statements (simplified example)::
  146. ifStmt = 'if' expr ':' stmt
  147. (IND{=} 'elif' expr ':' stmt)*
  148. (IND{=} 'else' ':' stmt)?
  149. simpleStmt = ifStmt / ...
  150. stmt = IND{>} stmt ^+ IND{=} DED # list of statements
  151. / simpleStmt # or a simple statement
  152. Comments
  153. --------
  154. Comments start anywhere outside a string or character literal with the
  155. hash character `#`.
  156. Comments consist of a concatenation of `comment pieces`:idx:. A comment piece
  157. starts with `#` and runs until the end of the line. The end of line characters
  158. belong to the piece. If the next line only consists of a comment piece with
  159. no other tokens between it and the preceding one, it does not start a new
  160. comment:
  161. .. code-block:: nim
  162. i = 0 # This is a single comment over multiple lines.
  163. # The lexer merges these two pieces.
  164. # The comment continues here.
  165. `Documentation comments`:idx: are comments that start with two `##`.
  166. Documentation comments are tokens; they are only allowed at certain places in
  167. the input file as they belong to the syntax tree.
  168. Multiline comments
  169. ------------------
  170. Starting with version 0.13.0 of the language Nim supports multiline comments.
  171. They look like:
  172. .. code-block:: nim
  173. #[Comment here.
  174. Multiple lines
  175. are not a problem.]#
  176. Multiline comments support nesting:
  177. .. code-block:: nim
  178. #[ #[ Multiline comment in already
  179. commented out code. ]#
  180. proc p[T](x: T) = discard
  181. ]#
  182. Multiline documentation comments also exist and support nesting too:
  183. .. code-block:: nim
  184. proc foo =
  185. ##[Long documentation comment
  186. here.
  187. ]##
  188. Identifiers & Keywords
  189. ----------------------
  190. Identifiers in Nim can be any string of letters, digits
  191. and underscores, with the following restrictions:
  192. * begins with a letter
  193. * does not end with an underscore `_`
  194. * two immediate following underscores `__` are not allowed:
  195. .. code-block::
  196. letter ::= 'A'..'Z' | 'a'..'z' | '\x80'..'\xff'
  197. digit ::= '0'..'9'
  198. IDENTIFIER ::= letter ( ['_'] (letter | digit) )*
  199. Currently, any Unicode character with an ordinal value > 127 (non-ASCII) is
  200. classified as a `letter` and may thus be part of an identifier but later
  201. versions of the language may assign some Unicode characters to belong to the
  202. operator characters instead.
  203. The following keywords are reserved and cannot be used as identifiers:
  204. .. code-block:: nim
  205. :file: keywords.txt
  206. Some keywords are unused; they are reserved for future developments of the
  207. language.
  208. Identifier equality
  209. -------------------
  210. Two identifiers are considered equal if the following algorithm returns true:
  211. .. code-block:: nim
  212. proc sameIdentifier(a, b: string): bool =
  213. a[0] == b[0] and
  214. a.replace("_", "").toLowerAscii == b.replace("_", "").toLowerAscii
  215. That means only the first letters are compared in a case-sensitive manner. Other
  216. letters are compared case-insensitively within the ASCII range and underscores are ignored.
  217. This rather unorthodox way to do identifier comparisons is called
  218. `partial case-insensitivity`:idx: and has some advantages over the conventional
  219. case sensitivity:
  220. It allows programmers to mostly use their own preferred
  221. spelling style, be it humpStyle or snake_style, and libraries written
  222. by different programmers cannot use incompatible conventions.
  223. A Nim-aware editor or IDE can show the identifiers as preferred.
  224. Another advantage is that it frees the programmer from remembering
  225. the exact spelling of an identifier. The exception with respect to the first
  226. letter allows common code like `var foo: Foo` to be parsed unambiguously.
  227. Note that this rule also applies to keywords, meaning that `notin` is
  228. the same as `notIn` and `not_in` (all-lowercase version (`notin`, `isnot`)
  229. is the preferred way of writing keywords).
  230. Historically, Nim was a fully `style-insensitive`:idx: language. This meant that
  231. it was not case-sensitive and underscores were ignored and there was not even a
  232. distinction between `foo` and `Foo`.
  233. Keywords as identifiers
  234. -----------------------
  235. If a keyword is enclosed in backticks it loses its keyword property and becomes an ordinary identifier.
  236. Examples
  237. .. code-block:: nim
  238. var `var` = "Hello Stropping"
  239. .. code-block:: nim
  240. type Obj = object
  241. `type`: int
  242. let `object` = Obj(`type`: 9)
  243. assert `object` is Obj
  244. assert `object`.`type` == 9
  245. var `var` = 42
  246. let `let` = 8
  247. assert `var` + `let` == 50
  248. const `assert` = true
  249. assert `assert`
  250. String literals
  251. ---------------
  252. Terminal symbol in the grammar: `STR_LIT`.
  253. String literals can be delimited by matching double quotes, and can
  254. contain the following `escape sequences`:idx:\ :
  255. ================== ===================================================
  256. Escape sequence Meaning
  257. ================== ===================================================
  258. ``\p`` platform specific newline: CRLF on Windows,
  259. LF on Unix
  260. ``\r``, ``\c`` `carriage return`:idx:
  261. ``\n``, ``\l`` `line feed`:idx: (often called `newline`:idx:)
  262. ``\f`` `form feed`:idx:
  263. ``\t`` `tabulator`:idx:
  264. ``\v`` `vertical tabulator`:idx:
  265. ``\\`` `backslash`:idx:
  266. ``\"`` `quotation mark`:idx:
  267. ``\'`` `apostrophe`:idx:
  268. ``\`` '0'..'9'+ `character with decimal value d`:idx:;
  269. all decimal digits directly
  270. following are used for the character
  271. ``\a`` `alert`:idx:
  272. ``\b`` `backspace`:idx:
  273. ``\e`` `escape`:idx: `[ESC]`:idx:
  274. ``\x`` HH `character with hex value HH`:idx:;
  275. exactly two hex digits are allowed
  276. ``\u`` HHHH `unicode codepoint with hex value HHHH`:idx:;
  277. exactly four hex digits are allowed
  278. ``\u`` {H+} `unicode codepoint`:idx:;
  279. all hex digits enclosed in `{}` are used for
  280. the codepoint
  281. ================== ===================================================
  282. Strings in Nim may contain any 8-bit value, even embedded zeros. However
  283. some operations may interpret the first binary zero as a terminator.
  284. Triple quoted string literals
  285. -----------------------------
  286. Terminal symbol in the grammar: `TRIPLESTR_LIT`.
  287. String literals can also be delimited by three double quotes `"""` ... `"""`.
  288. Literals in this form may run for several lines, may contain `"` and do not
  289. interpret any escape sequences.
  290. For convenience, when the opening `"""` is followed by a newline (there may
  291. be whitespace between the opening `"""` and the newline),
  292. the newline (and the preceding whitespace) is not included in the string. The
  293. ending of the string literal is defined by the pattern `"""[^"]`, so this:
  294. .. code-block:: nim
  295. """"long string within quotes""""
  296. Produces::
  297. "long string within quotes"
  298. Raw string literals
  299. -------------------
  300. Terminal symbol in the grammar: `RSTR_LIT`.
  301. There are also raw string literals that are preceded with the
  302. letter `r` (or `R`) and are delimited by matching double quotes (just
  303. like ordinary string literals) and do not interpret the escape sequences.
  304. This is especially convenient for regular expressions or Windows paths:
  305. .. code-block:: nim
  306. var f = openFile(r"C:\texts\text.txt") # a raw string, so ``\t`` is no tab
  307. To produce a single `"` within a raw string literal, it has to be doubled:
  308. .. code-block:: nim
  309. r"a""b"
  310. Produces::
  311. a"b
  312. `r""""` is not possible with this notation, because the three leading
  313. quotes introduce a triple quoted string literal. `r"""` is the same
  314. as `"""` since triple quoted string literals do not interpret escape
  315. sequences either.
  316. Generalized raw string literals
  317. -------------------------------
  318. Terminal symbols in the grammar: `GENERALIZED_STR_LIT`,
  319. `GENERALIZED_TRIPLESTR_LIT`.
  320. The construct `identifier"string literal"` (without whitespace between the
  321. identifier and the opening quotation mark) is a
  322. generalized raw string literal. It is a shortcut for the construct
  323. `identifier(r"string literal")`, so it denotes a routine call with a
  324. raw string literal as its only argument. Generalized raw string literals
  325. are especially convenient for embedding mini languages directly into Nim
  326. (for example regular expressions).
  327. The construct `identifier"""string literal"""` exists too. It is a shortcut
  328. for `identifier("""string literal""")`.
  329. Character literals
  330. ------------------
  331. Character literals are enclosed in single quotes `''` and can contain the
  332. same escape sequences as strings - with one exception: the platform
  333. dependent `newline`:idx: (``\p``)
  334. is not allowed as it may be wider than one character (it can be the pair
  335. CR/LF). Here are the valid `escape sequences`:idx: for character
  336. literals:
  337. ================== ===================================================
  338. Escape sequence Meaning
  339. ================== ===================================================
  340. ``\r``, ``\c`` `carriage return`:idx:
  341. ``\n``, ``\l`` `line feed`:idx:
  342. ``\f`` `form feed`:idx:
  343. ``\t`` `tabulator`:idx:
  344. ``\v`` `vertical tabulator`:idx:
  345. ``\\`` `backslash`:idx:
  346. ``\"`` `quotation mark`:idx:
  347. ``\'`` `apostrophe`:idx:
  348. ``\`` '0'..'9'+ `character with decimal value d`:idx:;
  349. all decimal digits directly
  350. following are used for the character
  351. ``\a`` `alert`:idx:
  352. ``\b`` `backspace`:idx:
  353. ``\e`` `escape`:idx: `[ESC]`:idx:
  354. ``\x`` HH `character with hex value HH`:idx:;
  355. exactly two hex digits are allowed
  356. ================== ===================================================
  357. A character is not a Unicode character but a single byte.
  358. Rationale: It enables the efficient support of `array[char, int]` or
  359. `set[char]`.
  360. The `Rune` type can represent any Unicode character.
  361. `Rune` is declared in the `unicode module <unicode.html>`_.
  362. A character literal that does not end in `'` is interpreted as `'` if there
  363. is a preceeding backtick token. There must be no whitespace between the preceeding
  364. backtick token and the character literal. This special case ensures that a declaration
  365. like ``proc `'customLiteral`(s: string)`` is valid. ``proc `'customLiteral`(s: string)``
  366. is the same as ``proc `'\''customLiteral`(s: string)``.
  367. See also `Custom Numeric Literals <#custom-numeric-literals>`_.
  368. Numeric Literals
  369. ----------------
  370. Numeric literals have the form::
  371. hexdigit = digit | 'A'..'F' | 'a'..'f'
  372. octdigit = '0'..'7'
  373. bindigit = '0'..'1'
  374. unary_minus = '-' # See the section about unary minus
  375. HEX_LIT = unary_minus? '0' ('x' | 'X' ) hexdigit ( ['_'] hexdigit )*
  376. DEC_LIT = unary_minus? digit ( ['_'] digit )*
  377. OCT_LIT = unary_minus? '0' 'o' octdigit ( ['_'] octdigit )*
  378. BIN_LIT = unary_minus? '0' ('b' | 'B' ) bindigit ( ['_'] bindigit )*
  379. INT_LIT = HEX_LIT
  380. | DEC_LIT
  381. | OCT_LIT
  382. | BIN_LIT
  383. INT8_LIT = INT_LIT ['\''] ('i' | 'I') '8'
  384. INT16_LIT = INT_LIT ['\''] ('i' | 'I') '16'
  385. INT32_LIT = INT_LIT ['\''] ('i' | 'I') '32'
  386. INT64_LIT = INT_LIT ['\''] ('i' | 'I') '64'
  387. UINT_LIT = INT_LIT ['\''] ('u' | 'U')
  388. UINT8_LIT = INT_LIT ['\''] ('u' | 'U') '8'
  389. UINT16_LIT = INT_LIT ['\''] ('u' | 'U') '16'
  390. UINT32_LIT = INT_LIT ['\''] ('u' | 'U') '32'
  391. UINT64_LIT = INT_LIT ['\''] ('u' | 'U') '64'
  392. exponent = ('e' | 'E' ) ['+' | '-'] digit ( ['_'] digit )*
  393. FLOAT_LIT = unary_minus? digit (['_'] digit)* (('.' digit (['_'] digit)* [exponent]) |exponent)
  394. FLOAT32_SUFFIX = ('f' | 'F') ['32']
  395. FLOAT32_LIT = HEX_LIT '\'' FLOAT32_SUFFIX
  396. | (FLOAT_LIT | DEC_LIT | OCT_LIT | BIN_LIT) ['\''] FLOAT32_SUFFIX
  397. FLOAT64_SUFFIX = ( ('f' | 'F') '64' ) | 'd' | 'D'
  398. FLOAT64_LIT = HEX_LIT '\'' FLOAT64_SUFFIX
  399. | (FLOAT_LIT | DEC_LIT | OCT_LIT | BIN_LIT) ['\''] FLOAT64_SUFFIX
  400. CUSTOM_NUMERIC_LIT = (FLOAT_LIT | INT_LIT) '\'' CUSTOM_NUMERIC_SUFFIX
  401. # CUSTOM_NUMERIC_SUFFIX is any Nim identifier that is not
  402. # a pre-defined type suffix.
  403. As can be seen in the productions, numeric literals can contain underscores
  404. for readability. Integer and floating-point literals may be given in decimal (no
  405. prefix), binary (prefix `0b`), octal (prefix `0o`), and hexadecimal
  406. (prefix `0x`) notation.
  407. The fact that the unary minus `-` in a number literal like `-1` is considered
  408. to be part of the literal is a late addition to the language. The rationale is that
  409. an expression `-128'i8` should be valid and without this special case, this would
  410. be impossible -- `128` is not a valid `int8` value, only `-128` is.
  411. For the `unary_minus` rule there are further restrictions that are not covered
  412. in the formal grammar. For `-` to be part of the number literal its immediately
  413. preceeding character has to be in the
  414. set `{' ', '\t', '\n', '\r', ',', ';', '(', '[', '{'}`. This set was designed to
  415. cover most cases in a natural manner.
  416. In the following examples, `-1` is a single token:
  417. .. code-block:: nim
  418. echo -1
  419. echo(-1)
  420. echo [-1]
  421. echo 3,-1
  422. "abc";-1
  423. In the following examples, `-1` is parsed as two separate tokens
  424. (as `-`:tok: `1`:tok:):
  425. .. code-block:: nim
  426. echo x-1
  427. echo (int)-1
  428. echo [a]-1
  429. "abc"-1
  430. The suffix starting with an apostrophe ('\'') is called a
  431. `type suffix`:idx:. Literals without a type suffix are of an integer type
  432. unless the literal contains a dot or `E|e` in which case it is of
  433. type `float`. This integer type is `int` if the literal is in the range
  434. `low(int32)..high(int32)`, otherwise it is `int64`.
  435. For notational convenience, the apostrophe of a type suffix
  436. is optional if it is not ambiguous (only hexadecimal floating-point literals
  437. with a type suffix can be ambiguous).
  438. The pre-defined type suffixes are:
  439. ================= =========================
  440. Type Suffix Resulting type of literal
  441. ================= =========================
  442. `'i8` int8
  443. `'i16` int16
  444. `'i32` int32
  445. `'i64` int64
  446. `'u` uint
  447. `'u8` uint8
  448. `'u16` uint16
  449. `'u32` uint32
  450. `'u64` uint64
  451. `'f` float32
  452. `'d` float64
  453. `'f32` float32
  454. `'f64` float64
  455. ================= =========================
  456. Floating-point literals may also be in binary, octal or hexadecimal
  457. notation:
  458. `0B0_10001110100_0000101001000111101011101111111011000101001101001001'f64`
  459. is approximately 1.72826e35 according to the IEEE floating-point standard.
  460. Literals must match the datatype, for example, `333'i8` is an invalid literal.
  461. Non-base-10 literals are used mainly for flags and bit pattern representations,
  462. therefore the checking is done on bit width and not on value range.
  463. Hence: 0b10000000'u8 == 0x80'u8 == 128, but, 0b10000000'i8 == 0x80'i8 == -1
  464. instead of causing an overflow error.
  465. Custom Numeric Literals
  466. ~~~~~~~~~~~~~~~~~~~~~~~
  467. If the suffix is not predefined, then the suffix is assumed to be a call
  468. to a proc, template, macro or other callable identifier that is passed the
  469. string containing the literal. The callable identifier needs to be declared
  470. with a special ``'`` prefix:
  471. .. code-block:: nim
  472. import strutils
  473. type u4 = distinct uint8 # a 4-bit unsigned integer aka "nibble"
  474. proc `'u4`(n: string): u4 =
  475. # The leading ' is required.
  476. result = (parseInt(n) and 0x0F).u4
  477. var x = 5'u4
  478. More formally, a custom numeric literal `123'custom` is transformed
  479. to r"123".`'custom` in the parsing step. There is no AST node kind that
  480. corresponds to this transformation. The transformation naturally handles
  481. the case that additional parameters are passed to the callee:
  482. .. code-block:: nim
  483. import strutils
  484. type u4 = distinct uint8 # a 4-bit unsigned integer aka "nibble"
  485. proc `'u4`(n: string; moreData: int): u4 =
  486. result = (parseInt(n) and 0x0F).u4
  487. var x = 5'u4(123)
  488. Custom numeric literals are covered by the grammar rule named `CUSTOM_NUMERIC_LIT`.
  489. A custom numeric literal is a single token.
  490. Operators
  491. ---------
  492. Nim allows user defined operators. An operator is any combination of the
  493. following characters::
  494. = + - * / < >
  495. @ $ ~ & % |
  496. ! ? ^ . : \
  497. (The grammar uses the terminal OPR to refer to operator symbols as
  498. defined here.)
  499. These keywords are also operators:
  500. `and or not xor shl shr div mod in notin is isnot of as from`.
  501. `.`:tok:, `=`:tok:, `:`:tok:, `::`:tok: are not available as general operators; they
  502. are used for other notational purposes.
  503. `*:` is as a special case treated as the two tokens `*`:tok: and `:`:tok:
  504. (to support `var v*: T`).
  505. The `not` keyword is always a unary operator, `a not b` is parsed
  506. as `a(not b)`, not as `(a) not (b)`.
  507. Other tokens
  508. ------------
  509. The following strings denote other tokens::
  510. ` ( ) { } [ ] , ; [. .] {. .} (. .) [:
  511. The `slice`:idx: operator `..`:tok: takes precedence over other tokens that
  512. contain a dot: `{..}` are the three tokens `{`:tok:, `..`:tok:, `}`:tok:
  513. and not the two tokens `{.`:tok:, `.}`:tok:.
  514. Unicode Operators
  515. -----------------
  516. Under the `--experimental:unicodeOperators` switch these Unicode operators are
  517. also parsed as operators::
  518. ∙ ∘ × ★ ⊗ ⊘ ⊙ ⊛ ⊠ ⊡ ∩ ∧ ⊓ # same priority as * (multiplication)
  519. ± ⊕ ⊖ ⊞ ⊟ ∪ ∨ ⊔ # same priority as + (addition)
  520. If enabled, Unicode operators can be combined with non-Unicode operator
  521. symbols. The usual precedence extensions then apply, for example, `⊠=` is an
  522. assignment like operator just like `*=` is.
  523. No Unicode normalization step is performed.
  524. **Note**: Due to parser limitations one **cannot** enable this feature via a
  525. pragma `{.experimental: "unicodeOperators".}` reliably.
  526. Syntax
  527. ======
  528. This section lists Nim's standard syntax. How the parser handles
  529. the indentation is already described in the `Lexical Analysis`_ section.
  530. Nim allows user-definable operators.
  531. Binary operators have 11 different levels of precedence.
  532. Associativity
  533. -------------
  534. Binary operators whose first character is `^` are right-associative, all
  535. other binary operators are left-associative.
  536. .. code-block:: nim
  537. proc `^/`(x, y: float): float =
  538. # a right-associative division operator
  539. result = x / y
  540. echo 12 ^/ 4 ^/ 8 # 24.0 (4 / 8 = 0.5, then 12 / 0.5 = 24.0)
  541. echo 12 / 4 / 8 # 0.375 (12 / 4 = 3.0, then 3 / 8 = 0.375)
  542. Precedence
  543. ----------
  544. Unary operators always bind stronger than any binary
  545. operator: `$a + b` is `($a) + b` and not `$(a + b)`.
  546. If a unary operator's first character is `@` it is a `sigil-like`:idx:
  547. operator which binds stronger than a `primarySuffix`: `@x.abc` is parsed
  548. as `(@x).abc` whereas `$x.abc` is parsed as `$(x.abc)`.
  549. For binary operators that are not keywords, the precedence is determined by the
  550. following rules:
  551. Operators ending in either `->`, `~>` or `=>` are called
  552. `arrow like`:idx:, and have the lowest precedence of all operators.
  553. If the operator ends with `=` and its first character is none of
  554. `<`, `>`, `!`, `=`, `~`, `?`, it is an *assignment operator* which
  555. has the second-lowest precedence.
  556. Otherwise, precedence is determined by the first character.
  557. ================ ======================================================= ================== ===============
  558. Precedence level Operators First character Terminal symbol
  559. ================ ======================================================= ================== ===============
  560. 10 (highest) `$ ^` OP10
  561. 9 `* / div mod shl shr %` `* % \ /` OP9
  562. 8 `+ -` `+ - ~ |` OP8
  563. 7 `&` `&` OP7
  564. 6 `..` `.` OP6
  565. 5 `== <= < >= > != in notin is isnot not of as from` `= < > !` OP5
  566. 4 `and` OP4
  567. 3 `or xor` OP3
  568. 2 `@ : ?` OP2
  569. 1 *assignment operator* (like `+=`, `*=`) OP1
  570. 0 (lowest) *arrow like operator* (like `->`, `=>`) OP0
  571. ================ ======================================================= ================== ===============
  572. Whether an operator is used as a prefix operator is also affected by preceding
  573. whitespace (this parsing change was introduced with version 0.13.0):
  574. .. code-block:: nim
  575. echo $foo
  576. # is parsed as
  577. echo($foo)
  578. Spacing also determines whether `(a, b)` is parsed as an argument list
  579. of a call or whether it is parsed as a tuple constructor:
  580. .. code-block:: nim
  581. echo(1, 2) # pass 1 and 2 to echo
  582. .. code-block:: nim
  583. echo (1, 2) # pass the tuple (1, 2) to echo
  584. Dot-like operators
  585. ------------------
  586. Terminal symbol in the grammar: `DOTLIKEOP`.
  587. Dot-like operators are operators starting with `.`, but not with `..`, for e.g. `.?`;
  588. they have the same precedence as `.`, so that `a.?b.c` is parsed as `(a.?b).c` instead of `a.?(b.c)`.
  589. Grammar
  590. -------
  591. The grammar's start symbol is `module`.
  592. .. include:: grammar.txt
  593. :literal:
  594. Order of evaluation
  595. ===================
  596. Order of evaluation is strictly left-to-right, inside-out as it is typical for most others
  597. imperative programming languages:
  598. .. code-block:: nim
  599. :test: "nim c $1"
  600. var s = ""
  601. proc p(arg: int): int =
  602. s.add $arg
  603. result = arg
  604. discard p(p(1) + p(2))
  605. doAssert s == "123"
  606. Assignments are not special, the left-hand-side expression is evaluated before the
  607. right-hand side:
  608. .. code-block:: nim
  609. :test: "nim c $1"
  610. var v = 0
  611. proc getI(): int =
  612. result = v
  613. inc v
  614. var a, b: array[0..2, int]
  615. proc someCopy(a: var int; b: int) = a = b
  616. a[getI()] = getI()
  617. doAssert a == [1, 0, 0]
  618. v = 0
  619. someCopy(b[getI()], getI())
  620. doAssert b == [1, 0, 0]
  621. Rationale: Consistency with overloaded assignment or assignment-like operations,
  622. `a = b` can be read as `performSomeCopy(a, b)`.
  623. However, the concept of "order of evaluation" is only applicable after the code
  624. was normalized: The normalization involves template expansions and argument
  625. reorderings that have been passed to named parameters:
  626. .. code-block:: nim
  627. :test: "nim c $1"
  628. var s = ""
  629. proc p(): int =
  630. s.add "p"
  631. result = 5
  632. proc q(): int =
  633. s.add "q"
  634. result = 3
  635. # Evaluation order is 'b' before 'a' due to template
  636. # expansion's semantics.
  637. template swapArgs(a, b): untyped =
  638. b + a
  639. doAssert swapArgs(p() + q(), q() - p()) == 6
  640. doAssert s == "qppq"
  641. # Evaluation order is not influenced by named parameters:
  642. proc construct(first, second: int) =
  643. discard
  644. # 'p' is evaluated before 'q'!
  645. construct(second = q(), first = p())
  646. doAssert s == "qppqpq"
  647. Rationale: This is far easier to implement than hypothetical alternatives.
  648. Constants and Constant Expressions
  649. ==================================
  650. A `constant`:idx: is a symbol that is bound to the value of a constant
  651. expression. Constant expressions are restricted to depend only on the following
  652. categories of values and operations, because these are either built into the
  653. language or declared and evaluated before semantic analysis of the constant
  654. expression:
  655. * literals
  656. * built-in operators
  657. * previously declared constants and compile-time variables
  658. * previously declared macros and templates
  659. * previously declared procedures that have no side effects beyond
  660. possibly modifying compile-time variables
  661. A constant expression can contain code blocks that may internally use all Nim
  662. features supported at compile time (as detailed in the next section below).
  663. Within such a code block, it is possible to declare variables and then later
  664. read and update them, or declare variables and pass them to procedures that
  665. modify them. However, the code in such a block must still adhere to the
  666. restrictions listed above for referencing values and operations outside the
  667. block.
  668. The ability to access and modify compile-time variables adds flexibility to
  669. constant expressions that may be surprising to those coming from other
  670. statically typed languages. For example, the following code echoes the beginning
  671. of the Fibonacci series **at compile-time**. (This is a demonstration of
  672. flexibility in defining constants, not a recommended style for solving this
  673. problem.)
  674. .. code-block:: nim
  675. :test: "nim c $1"
  676. import std/strformat
  677. var fibN {.compileTime.}: int
  678. var fibPrev {.compileTime.}: int
  679. var fibPrevPrev {.compileTime.}: int
  680. proc nextFib(): int =
  681. result = if fibN < 2:
  682. fibN
  683. else:
  684. fibPrevPrev + fibPrev
  685. inc(fibN)
  686. fibPrevPrev = fibPrev
  687. fibPrev = result
  688. const f0 = nextFib()
  689. const f1 = nextFib()
  690. const displayFib = block:
  691. const f2 = nextFib()
  692. var result = fmt"Fibonacci sequence: {f0}, {f1}, {f2}"
  693. for i in 3..12:
  694. add(result, fmt", {nextFib()}")
  695. result
  696. static:
  697. echo displayFib
  698. Restrictions on Compile-Time Execution
  699. ======================================
  700. Nim code that will be executed at compile time cannot use the following
  701. language features:
  702. * methods
  703. * closure iterators
  704. * the `cast` operator
  705. * reference (pointer) types
  706. * FFI
  707. The use of wrappers that use FFI and/or `cast` is also disallowed. Note that
  708. these wrappers include the ones in the standard libraries.
  709. Some or all of these restrictions are likely to be lifted over time.
  710. Types
  711. =====
  712. All expressions have a type that is known during semantic analysis. Nim
  713. is statically typed. One can declare new types, which is in essence defining
  714. an identifier that can be used to denote this custom type.
  715. These are the major type classes:
  716. * ordinal types (consist of integer, bool, character, enumeration
  717. (and subranges thereof) types)
  718. * floating-point types
  719. * string type
  720. * structured types
  721. * reference (pointer) type
  722. * procedural type
  723. * generic type
  724. Ordinal types
  725. -------------
  726. Ordinal types have the following characteristics:
  727. - Ordinal types are countable and ordered. This property allows the operation
  728. of functions such as `inc`, `ord`, and `dec` on ordinal types to
  729. be defined.
  730. - Ordinal types have a smallest possible value, accessible with `low(type)`.
  731. Trying to count further down than the smallest value produces a panic or
  732. a static error.
  733. - Ordinal types have a largest possible value, accessible with `high(type)`.
  734. Trying to count further up than the largest value produces a panic or
  735. a static error.
  736. Integers, bool, characters, and enumeration types (and subranges of these
  737. types) belong to ordinal types.
  738. A distinct type is an ordinal type if its base type is an ordinal type.
  739. Pre-defined integer types
  740. -------------------------
  741. These integer types are pre-defined:
  742. `int`
  743. the generic signed integer type; its size is platform-dependent and has the
  744. same size as a pointer. This type should be used in general. An integer
  745. literal that has no type suffix is of this type if it is in the range
  746. `low(int32)..high(int32)` otherwise the literal's type is `int64`.
  747. `int`\ XX
  748. additional signed integer types of XX bits use this naming scheme
  749. (example: int16 is a 16-bit wide integer).
  750. The current implementation supports `int8`, `int16`, `int32`, `int64`.
  751. Literals of these types have the suffix 'iXX.
  752. `uint`
  753. the generic `unsigned integer`:idx: type; its size is platform-dependent and
  754. has the same size as a pointer. An integer literal with the type
  755. suffix `'u` is of this type.
  756. `uint`\ XX
  757. additional unsigned integer types of XX bits use this naming scheme
  758. (example: uint16 is a 16-bit wide unsigned integer).
  759. The current implementation supports `uint8`, `uint16`, `uint32`,
  760. `uint64`. Literals of these types have the suffix 'uXX.
  761. Unsigned operations all wrap around; they cannot lead to over- or
  762. underflow errors.
  763. In addition to the usual arithmetic operators for signed and unsigned integers
  764. (`+ - *` etc.) there are also operators that formally work on *signed*
  765. integers but treat their arguments as *unsigned*: They are mostly provided
  766. for backwards compatibility with older versions of the language that lacked
  767. unsigned integer types. These unsigned operations for signed integers use
  768. the `%` suffix as convention:
  769. ====================== ======================================================
  770. operation meaning
  771. ====================== ======================================================
  772. `a +% b` unsigned integer addition
  773. `a -% b` unsigned integer subtraction
  774. `a *% b` unsigned integer multiplication
  775. `a /% b` unsigned integer division
  776. `a %% b` unsigned integer modulo operation
  777. `a <% b` treat `a` and `b` as unsigned and compare
  778. `a <=% b` treat `a` and `b` as unsigned and compare
  779. `ze(a)` extends the bits of `a` with zeros until it has the
  780. width of the `int` type
  781. `toU8(a)` treats `a` as unsigned and converts it to an
  782. unsigned integer of 8 bits (but still the
  783. `int8` type)
  784. `toU16(a)` treats `a` as unsigned and converts it to an
  785. unsigned integer of 16 bits (but still the
  786. `int16` type)
  787. `toU32(a)` treats `a` as unsigned and converts it to an
  788. unsigned integer of 32 bits (but still the
  789. `int32` type)
  790. ====================== ======================================================
  791. `Automatic type conversion`:idx: is performed in expressions where different
  792. kinds of integer types are used: the smaller type is converted to the larger.
  793. A `narrowing type conversion`:idx: converts a larger to a smaller type (for
  794. example `int32 -> int16`). A `widening type conversion`:idx: converts a
  795. smaller type to a larger type (for example `int16 -> int32`). In Nim only
  796. widening type conversions are *implicit*:
  797. .. code-block:: nim
  798. var myInt16 = 5i16
  799. var myInt: int
  800. myInt16 + 34 # of type `int16`
  801. myInt16 + myInt # of type `int`
  802. myInt16 + 2i32 # of type `int32`
  803. However, `int` literals are implicitly convertible to a smaller integer type
  804. if the literal's value fits this smaller type and such a conversion is less
  805. expensive than other implicit conversions, so `myInt16 + 34` produces
  806. an `int16` result.
  807. For further details, see `Convertible relation
  808. <#type-relations-convertible-relation>`_.
  809. Subrange types
  810. --------------
  811. A subrange type is a range of values from an ordinal or floating-point type (the base
  812. type). To define a subrange type, one must specify its limiting values -- the
  813. lowest and highest value of the type. For example:
  814. .. code-block:: nim
  815. type
  816. Subrange = range[0..5]
  817. PositiveFloat = range[0.0..Inf]
  818. Positive* = range[1..high(int)] # as defined in `system`
  819. `Subrange` is a subrange of an integer which can only hold the values 0
  820. to 5. `PositiveFloat` defines a subrange of all positive floating-point values.
  821. NaN does not belong to any subrange of floating-point types.
  822. Assigning any other value to a variable of type `Subrange` is a
  823. panic (or a static error if it can be determined during
  824. semantic analysis). Assignments from the base type to one of its subrange types
  825. (and vice versa) are allowed.
  826. A subrange type has the same size as its base type (`int` in the
  827. Subrange example).
  828. Pre-defined floating-point types
  829. --------------------------------
  830. The following floating-point types are pre-defined:
  831. `float`
  832. the generic floating-point type; its size used to be platform-dependent,
  833. but now it is always mapped to `float64`.
  834. This type should be used in general.
  835. `float`\ XX
  836. an implementation may define additional floating-point types of XX bits using
  837. this naming scheme (example: `float64` is a 64-bit wide float). The current
  838. implementation supports `float32` and `float64`. Literals of these types
  839. have the suffix 'fXX.
  840. Automatic type conversion in expressions with different kinds
  841. of floating-point types is performed: See `Convertible relation`_ for further
  842. details. Arithmetic performed on floating-point types follows the IEEE
  843. standard. Integer types are not converted to floating-point types automatically
  844. and vice versa.
  845. The IEEE standard defines five types of floating-point exceptions:
  846. * Invalid: operations with mathematically invalid operands,
  847. for example 0.0/0.0, sqrt(-1.0), and log(-37.8).
  848. * Division by zero: divisor is zero and dividend is a finite nonzero number,
  849. for example 1.0/0.0.
  850. * Overflow: operation produces a result that exceeds the range of the exponent,
  851. for example MAXDOUBLE+0.0000000000001e308.
  852. * Underflow: operation produces a result that is too small to be represented
  853. as a normal number, for example, MINDOUBLE * MINDOUBLE.
  854. * Inexact: operation produces a result that cannot be represented with infinite
  855. precision, for example, 2.0 / 3.0, log(1.1) and 0.1 in input.
  856. The IEEE exceptions are either ignored during execution or mapped to the
  857. Nim exceptions: `FloatInvalidOpDefect`:idx:, `FloatDivByZeroDefect`:idx:,
  858. `FloatOverflowDefect`:idx:, `FloatUnderflowDefect`:idx:,
  859. and `FloatInexactDefect`:idx:.
  860. These exceptions inherit from the `FloatingPointDefect`:idx: base class.
  861. Nim provides the pragmas `nanChecks`:idx: and `infChecks`:idx: to control
  862. whether the IEEE exceptions are ignored or trap a Nim exception:
  863. .. code-block:: nim
  864. {.nanChecks: on, infChecks: on.}
  865. var a = 1.0
  866. var b = 0.0
  867. echo b / b # raises FloatInvalidOpDefect
  868. echo a / b # raises FloatOverflowDefect
  869. In the current implementation `FloatDivByZeroDefect` and `FloatInexactDefect`
  870. are never raised. `FloatOverflowDefect` is raised instead of
  871. `FloatDivByZeroDefect`.
  872. There is also a `floatChecks`:idx: pragma that is a short-cut for the
  873. combination of `nanChecks` and `infChecks` pragmas. `floatChecks` are
  874. turned off as default.
  875. The only operations that are affected by the `floatChecks` pragma are
  876. the `+`, `-`, `*`, `/` operators for floating-point types.
  877. An implementation should always use the maximum precision available to evaluate
  878. floating-point values during semantic analysis; this means expressions like
  879. `0.09'f32 + 0.01'f32 == 0.09'f64 + 0.01'f64` that are evaluating during
  880. constant folding are true.
  881. Boolean type
  882. ------------
  883. The boolean type is named `bool`:idx: in Nim and can be one of the two
  884. pre-defined values `true` and `false`. Conditions in `while`,
  885. `if`, `elif`, `when`-statements need to be of type `bool`.
  886. This condition holds::
  887. ord(false) == 0 and ord(true) == 1
  888. The operators `not, and, or, xor, <, <=, >, >=, !=, ==` are defined
  889. for the bool type. The `and` and `or` operators perform short-cut
  890. evaluation. Example:
  891. .. code-block:: nim
  892. while p != nil and p.name != "xyz":
  893. # p.name is not evaluated if p == nil
  894. p = p.next
  895. The size of the bool type is one byte.
  896. Character type
  897. --------------
  898. The character type is named `char` in Nim. Its size is one byte.
  899. Thus it cannot represent a UTF-8 character, but a part of it.
  900. The `Rune` type is used for Unicode characters, it can represent any Unicode
  901. character. `Rune` is declared in the `unicode module <unicode.html>`_.
  902. Enumeration types
  903. -----------------
  904. Enumeration types define a new type whose values consist of the ones
  905. specified. The values are ordered. Example:
  906. .. code-block:: nim
  907. type
  908. Direction = enum
  909. north, east, south, west
  910. Now the following holds::
  911. ord(north) == 0
  912. ord(east) == 1
  913. ord(south) == 2
  914. ord(west) == 3
  915. # Also allowed:
  916. ord(Direction.west) == 3
  917. The implied order is: north < east < south < west. The comparison operators can be used
  918. with enumeration types. Instead of `north` etc, the enum value can also
  919. be qualified with the enum type that it resides in, `Direction.north`.
  920. For better interfacing to other programming languages, the fields of enum
  921. types can be assigned an explicit ordinal value. However, the ordinal values
  922. have to be in ascending order. A field whose ordinal value is not
  923. explicitly given is assigned the value of the previous field + 1.
  924. An explicit ordered enum can have *holes*:
  925. .. code-block:: nim
  926. type
  927. TokenType = enum
  928. a = 2, b = 4, c = 89 # holes are valid
  929. However, it is then not ordinal anymore, so it is impossible to use these
  930. enums as an index type for arrays. The procedures `inc`, `dec`, `succ`
  931. and `pred` are not available for them either.
  932. The compiler supports the built-in stringify operator `$` for enumerations.
  933. The stringify's result can be controlled by explicitly giving the string
  934. values to use:
  935. .. code-block:: nim
  936. type
  937. MyEnum = enum
  938. valueA = (0, "my value A"),
  939. valueB = "value B",
  940. valueC = 2,
  941. valueD = (3, "abc")
  942. As can be seen from the example, it is possible to both specify a field's
  943. ordinal value and its string value by using a tuple. It is also
  944. possible to only specify one of them.
  945. An enum can be marked with the `pure` pragma so that its fields are
  946. added to a special module-specific hidden scope that is only queried
  947. as the last attempt. Only non-ambiguous symbols are added to this scope.
  948. But one can always access these via type qualification written
  949. as `MyEnum.value`:
  950. .. code-block:: nim
  951. type
  952. MyEnum {.pure.} = enum
  953. valueA, valueB, valueC, valueD, amb
  954. OtherEnum {.pure.} = enum
  955. valueX, valueY, valueZ, amb
  956. echo valueA # MyEnum.valueA
  957. echo amb # Error: Unclear whether it's MyEnum.amb or OtherEnum.amb
  958. echo MyEnum.amb # OK.
  959. To implement bit fields with enums see `Bit fields <#set-type-bit-fields>`_
  960. Overloadable enum field names
  961. -----------------------------
  962. To be enabled via `{.experimental: "overloadableEnums".}`.
  963. Enum field names are overloadable much like routines. When an overloaded
  964. enum field is used, it produces a closed sym choice construct, here
  965. written as `(E|E)`.
  966. During overload resolution the right `E` is picked, if possible.
  967. For (array/object...) constructors the right `E` is picked, comparable to
  968. how `[byte(1), 2, 3]` works, one needs to use `[T.E, E2, E3]`. Ambiguous
  969. enum fields produce a static error:
  970. .. code-block:: nim
  971. :test: "nim c $1"
  972. {.experimental: "overloadableEnums".}
  973. type
  974. E1 = enum
  975. value1,
  976. value2
  977. E2 = enum
  978. value1,
  979. value2 = 4
  980. const
  981. Lookuptable = [
  982. E1.value1: "1",
  983. value2: "2"
  984. ]
  985. proc p(e: E1) =
  986. # disambiguation in 'case' statements:
  987. case e
  988. of value1: echo "A"
  989. of value2: echo "B"
  990. p value2
  991. String type
  992. -----------
  993. All string literals are of the type `string`. A string in Nim is very
  994. similar to a sequence of characters. However, strings in Nim are both
  995. zero-terminated and have a length field. One can retrieve the length with the
  996. builtin `len` procedure; the length never counts the terminating zero.
  997. The terminating zero cannot be accessed unless the string is converted
  998. to the `cstring` type first. The terminating zero assures that this
  999. conversion can be done in O(1) and without any allocations.
  1000. The assignment operator for strings always copies the string.
  1001. The `&` operator concatenates strings.
  1002. Most native Nim types support conversion to strings with the special `$` proc.
  1003. When calling the `echo` proc, for example, the built-in stringify operation
  1004. for the parameter is called:
  1005. .. code-block:: nim
  1006. echo 3 # calls `$` for `int`
  1007. Whenever a user creates a specialized object, implementation of this procedure
  1008. provides for `string` representation.
  1009. .. code-block:: nim
  1010. type
  1011. Person = object
  1012. name: string
  1013. age: int
  1014. proc `$`(p: Person): string = # `$` always returns a string
  1015. result = p.name & " is " &
  1016. $p.age & # we *need* the `$` in front of p.age which
  1017. # is natively an integer to convert it to
  1018. # a string
  1019. " years old."
  1020. While `$p.name` can also be used, the `$` operation on a string does
  1021. nothing. Note that we cannot rely on automatic conversion from an `int` to
  1022. a `string` like we can for the `echo` proc.
  1023. Strings are compared by their lexicographical order. All comparison operators
  1024. are available. Strings can be indexed like arrays (lower bound is 0). Unlike
  1025. arrays, they can be used in case statements:
  1026. .. code-block:: nim
  1027. case paramStr(i)
  1028. of "-v": incl(options, optVerbose)
  1029. of "-h", "-?": incl(options, optHelp)
  1030. else: write(stdout, "invalid command line option!\n")
  1031. Per convention, all strings are UTF-8 strings, but this is not enforced. For
  1032. example, when reading strings from binary files, they are merely a sequence of
  1033. bytes. The index operation `s[i]` means the i-th *char* of `s`, not the
  1034. i-th *unichar*. The iterator `runes` from the `unicode module
  1035. <unicode.html>`_ can be used for iteration over all Unicode characters.
  1036. cstring type
  1037. ------------
  1038. The `cstring` type meaning `compatible string` is the native representation
  1039. of a string for the compilation backend. For the C backend the `cstring` type
  1040. represents a pointer to a zero-terminated char array
  1041. compatible with the type `char*` in Ansi C. Its primary purpose lies in easy
  1042. interfacing with C. The index operation `s[i]` means the i-th *char* of
  1043. `s`; however no bounds checking for `cstring` is performed making the
  1044. index operation unsafe.
  1045. A Nim `string` is implicitly convertible
  1046. to `cstring` for convenience. If a Nim string is passed to a C-style
  1047. variadic proc, it is implicitly converted to `cstring` too:
  1048. .. code-block:: nim
  1049. proc printf(formatstr: cstring) {.importc: "printf", varargs,
  1050. header: "<stdio.h>".}
  1051. printf("This works %s", "as expected")
  1052. Even though the conversion is implicit, it is not *safe*: The garbage collector
  1053. does not consider a `cstring` to be a root and may collect the underlying
  1054. memory. For this reason, the implicit conversion will be removed in future
  1055. releases of the Nim compiler. Certain idioms like conversion of a `const` string
  1056. to `cstring` are safe and will remain to be allowed.
  1057. A `$` proc is defined for cstrings that returns a string. Thus to get a nim
  1058. string from a cstring:
  1059. .. code-block:: nim
  1060. var str: string = "Hello!"
  1061. var cstr: cstring = str
  1062. var newstr: string = $cstr
  1063. `cstring` literals shouldn't be modified.
  1064. .. code-block:: nim
  1065. var x = cstring"literals"
  1066. x[1] = 'A' # This is wrong!!!
  1067. If the `cstring` originates from a regular memory (not read-only memory),
  1068. it can be modified:
  1069. .. code-block:: nim
  1070. var x = "123456"
  1071. var s: cstring = x
  1072. s[0] = 'u' # This is ok
  1073. Structured types
  1074. ----------------
  1075. A variable of a structured type can hold multiple values at the same
  1076. time. Structured types can be nested to unlimited levels. Arrays, sequences,
  1077. tuples, objects, and sets belong to the structured types.
  1078. Array and sequence types
  1079. ------------------------
  1080. Arrays are a homogeneous type, meaning that each element in the array has the
  1081. same type. Arrays always have a fixed length specified as a constant expression
  1082. (except for open arrays). They can be indexed by any ordinal type.
  1083. A parameter `A` may be an *open array*, in which case it is indexed by
  1084. integers from 0 to `len(A)-1`. An array expression may be constructed by the
  1085. array constructor `[]`. The element type of this array expression is
  1086. inferred from the type of the first element. All other elements need to be
  1087. implicitly convertible to this type.
  1088. An array type can be defined using the `array[size, T]` syntax, or using
  1089. `array[lo..hi, T]` for arrays that start at an index other than zero.
  1090. Sequences are similar to arrays but of dynamic length which may change
  1091. during runtime (like strings). Sequences are implemented as growable arrays,
  1092. allocating pieces of memory as items are added. A sequence `S` is always
  1093. indexed by integers from 0 to `len(S)-1` and its bounds are checked.
  1094. Sequences can be constructed by the array constructor `[]` in conjunction
  1095. with the array to sequence operator `@`. Another way to allocate space for a
  1096. sequence is to call the built-in `newSeq` procedure.
  1097. A sequence may be passed to a parameter that is of type *open array*.
  1098. Example:
  1099. .. code-block:: nim
  1100. type
  1101. IntArray = array[0..5, int] # an array that is indexed with 0..5
  1102. IntSeq = seq[int] # a sequence of integers
  1103. var
  1104. x: IntArray
  1105. y: IntSeq
  1106. x = [1, 2, 3, 4, 5, 6] # [] is the array constructor
  1107. y = @[1, 2, 3, 4, 5, 6] # the @ turns the array into a sequence
  1108. let z = [1.0, 2, 3, 4] # the type of z is array[0..3, float]
  1109. The lower bound of an array or sequence may be received by the built-in proc
  1110. `low()`, the higher bound by `high()`. The length may be
  1111. received by `len()`. `low()` for a sequence or an open array always returns
  1112. 0, as this is the first valid index.
  1113. One can append elements to a sequence with the `add()` proc or the `&`
  1114. operator, and remove (and get) the last element of a sequence with the
  1115. `pop()` proc.
  1116. The notation `x[i]` can be used to access the i-th element of `x`.
  1117. Arrays are always bounds checked (statically or at runtime). These
  1118. checks can be disabled via pragmas or invoking the compiler with the
  1119. `--boundChecks:off`:option: command-line switch.
  1120. An array constructor can have explicit indexes for readability:
  1121. .. code-block:: nim
  1122. type
  1123. Values = enum
  1124. valA, valB, valC
  1125. const
  1126. lookupTable = [
  1127. valA: "A",
  1128. valB: "B",
  1129. valC: "C"
  1130. ]
  1131. If an index is left out, `succ(lastIndex)` is used as the index
  1132. value:
  1133. .. code-block:: nim
  1134. type
  1135. Values = enum
  1136. valA, valB, valC, valD, valE
  1137. const
  1138. lookupTable = [
  1139. valA: "A",
  1140. "B",
  1141. valC: "C",
  1142. "D", "e"
  1143. ]
  1144. Open arrays
  1145. -----------
  1146. Often fixed size arrays turn out to be too inflexible; procedures should
  1147. be able to deal with arrays of different sizes. The `openarray`:idx: type
  1148. allows this; it can only be used for parameters. Openarrays are always
  1149. indexed with an `int` starting at position 0. The `len`, `low`
  1150. and `high` operations are available for open arrays too. Any array with
  1151. a compatible base type can be passed to an openarray parameter, the index
  1152. type does not matter. In addition to arrays, sequences can also be passed
  1153. to an open array parameter.
  1154. The openarray type cannot be nested: multidimensional openarrays are not
  1155. supported because this is seldom needed and cannot be done efficiently.
  1156. .. code-block:: nim
  1157. proc testOpenArray(x: openArray[int]) = echo repr(x)
  1158. testOpenArray([1,2,3]) # array[]
  1159. testOpenArray(@[1,2,3]) # seq[]
  1160. Varargs
  1161. -------
  1162. A `varargs` parameter is an openarray parameter that additionally
  1163. allows to pass a variable number of arguments to a procedure. The compiler
  1164. converts the list of arguments to an array implicitly:
  1165. .. code-block:: nim
  1166. proc myWriteln(f: File, a: varargs[string]) =
  1167. for s in items(a):
  1168. write(f, s)
  1169. write(f, "\n")
  1170. myWriteln(stdout, "abc", "def", "xyz")
  1171. # is transformed to:
  1172. myWriteln(stdout, ["abc", "def", "xyz"])
  1173. This transformation is only done if the varargs parameter is the
  1174. last parameter in the procedure header. It is also possible to perform
  1175. type conversions in this context:
  1176. .. code-block:: nim
  1177. proc myWriteln(f: File, a: varargs[string, `$`]) =
  1178. for s in items(a):
  1179. write(f, s)
  1180. write(f, "\n")
  1181. myWriteln(stdout, 123, "abc", 4.0)
  1182. # is transformed to:
  1183. myWriteln(stdout, [$123, $"def", $4.0])
  1184. In this example `$` is applied to any argument that is passed to the
  1185. parameter `a`. (Note that `$` applied to strings is a nop.)
  1186. Note that an explicit array constructor passed to a `varargs` parameter is
  1187. not wrapped in another implicit array construction:
  1188. .. code-block:: nim
  1189. proc takeV[T](a: varargs[T]) = discard
  1190. takeV([123, 2, 1]) # takeV's T is "int", not "array of int"
  1191. `varargs[typed]` is treated specially: It matches a variable list of arguments
  1192. of arbitrary type but *always* constructs an implicit array. This is required
  1193. so that the builtin `echo` proc does what is expected:
  1194. .. code-block:: nim
  1195. proc echo*(x: varargs[typed, `$`]) {...}
  1196. echo @[1, 2, 3]
  1197. # prints "@[1, 2, 3]" and not "123"
  1198. Unchecked arrays
  1199. ----------------
  1200. The `UncheckedArray[T]` type is a special kind of `array` where its bounds
  1201. are not checked. This is often useful to implement customized flexibly sized
  1202. arrays. Additionally, an unchecked array is translated into a C array of
  1203. undetermined size:
  1204. .. code-block:: nim
  1205. type
  1206. MySeq = object
  1207. len, cap: int
  1208. data: UncheckedArray[int]
  1209. Produces roughly this C code:
  1210. .. code-block:: C
  1211. typedef struct {
  1212. NI len;
  1213. NI cap;
  1214. NI data[];
  1215. } MySeq;
  1216. The base type of the unchecked array may not contain any GC'ed memory but this
  1217. is currently not checked.
  1218. **Future directions**: GC'ed memory should be allowed in unchecked arrays and
  1219. there should be an explicit annotation of how the GC is to determine the
  1220. runtime size of the array.
  1221. Tuples and object types
  1222. -----------------------
  1223. A variable of a tuple or object type is a heterogeneous storage
  1224. container.
  1225. A tuple or object defines various named *fields* of a type. A tuple also
  1226. defines a lexicographic *order* of the fields. Tuples are meant to be
  1227. heterogeneous storage types with few abstractions. The `()` syntax
  1228. can be used to construct tuples. The order of the fields in the constructor
  1229. must match the order of the tuple's definition. Different tuple-types are
  1230. *equivalent* if they specify the same fields of the same type in the same
  1231. order. The *names* of the fields also have to be the same.
  1232. The assignment operator for tuples copies each component.
  1233. The default assignment operator for objects copies each component. Overloading
  1234. of the assignment operator is described `here
  1235. <manual_experimental.html#type-bound-operations>`_.
  1236. .. code-block:: nim
  1237. type
  1238. Person = tuple[name: string, age: int] # type representing a person:
  1239. # it consists of a name and an age.
  1240. var person: Person
  1241. person = (name: "Peter", age: 30)
  1242. assert person.name == "Peter"
  1243. # the same, but less readable:
  1244. person = ("Peter", 30)
  1245. assert person[0] == "Peter"
  1246. assert Person is (string, int)
  1247. assert (string, int) is Person
  1248. assert Person isnot tuple[other: string, age: int] # `other` is a different identifier
  1249. A tuple with one unnamed field can be constructed with the parentheses and a
  1250. trailing comma:
  1251. .. code-block:: nim
  1252. proc echoUnaryTuple(a: (int,)) =
  1253. echo a[0]
  1254. echoUnaryTuple (1,)
  1255. In fact, a trailing comma is allowed for every tuple construction.
  1256. The implementation aligns the fields for the best access performance. The alignment
  1257. is compatible with the way the C compiler does it.
  1258. For consistency with `object` declarations, tuples in a `type` section
  1259. can also be defined with indentation instead of `[]`:
  1260. .. code-block:: nim
  1261. type
  1262. Person = tuple # type representing a person
  1263. name: string # a person consists of a name
  1264. age: Natural # and an age
  1265. Objects provide many features that tuples do not. Objects provide inheritance
  1266. and the ability to hide fields from other modules. Objects with inheritance
  1267. enabled have information about their type at runtime so that the `of` operator
  1268. can be used to determine the object's type. The `of` operator is similar to
  1269. the `instanceof` operator in Java.
  1270. .. code-block:: nim
  1271. type
  1272. Person = object of RootObj
  1273. name*: string # the * means that `name` is accessible from other modules
  1274. age: int # no * means that the field is hidden
  1275. Student = ref object of Person # a student is a person
  1276. id: int # with an id field
  1277. var
  1278. student: Student
  1279. person: Person
  1280. assert(student of Student) # is true
  1281. assert(student of Person) # also true
  1282. Object fields that should be visible from outside the defining module have to
  1283. be marked by `*`. In contrast to tuples, different object types are
  1284. never *equivalent*, they are nominal types whereas tuples are structural.
  1285. Objects that have no ancestor are implicitly `final` and thus have no hidden
  1286. type information. One can use the `inheritable` pragma to
  1287. introduce new object roots apart from `system.RootObj`.
  1288. .. code-block:: nim
  1289. type
  1290. Person = object # example of a final object
  1291. name*: string
  1292. age: int
  1293. Student = ref object of Person # Error: inheritance only works with non-final objects
  1294. id: int
  1295. Object construction
  1296. -------------------
  1297. Objects can also be created with an `object construction expression`:idx: that
  1298. has the syntax `T(fieldA: valueA, fieldB: valueB, ...)` where `T` is
  1299. an `object` type or a `ref object` type:
  1300. .. code-block:: nim
  1301. type
  1302. Student = object
  1303. name: string
  1304. age: int
  1305. PStudent = ref Student
  1306. var a1 = Student(name: "Anton", age: 5)
  1307. var a2 = PStudent(name: "Anton", age: 5)
  1308. # this also works directly:
  1309. var a3 = (ref Student)(name: "Anton", age: 5)
  1310. # not all fields need to be mentioned, and they can be mentioned out of order:
  1311. var a4 = Student(age: 5)
  1312. Note that, unlike tuples, objects require the field names along with their values.
  1313. For a `ref object` type `system.new` is invoked implicitly.
  1314. Object variants
  1315. ---------------
  1316. Often an object hierarchy is an overkill in certain situations where simple variant
  1317. types are needed. Object variants are tagged unions discriminated via an
  1318. enumerated type used for runtime type flexibility, mirroring the concepts of
  1319. *sum types* and *algebraic data types (ADTs)* as found in other languages.
  1320. An example:
  1321. .. code-block:: nim
  1322. # This is an example of how an abstract syntax tree could be modelled in Nim
  1323. type
  1324. NodeKind = enum # the different node types
  1325. nkInt, # a leaf with an integer value
  1326. nkFloat, # a leaf with a float value
  1327. nkString, # a leaf with a string value
  1328. nkAdd, # an addition
  1329. nkSub, # a subtraction
  1330. nkIf # an if statement
  1331. Node = ref NodeObj
  1332. NodeObj = object
  1333. case kind: NodeKind # the `kind` field is the discriminator
  1334. of nkInt: intVal: int
  1335. of nkFloat: floatVal: float
  1336. of nkString: strVal: string
  1337. of nkAdd, nkSub:
  1338. leftOp, rightOp: Node
  1339. of nkIf:
  1340. condition, thenPart, elsePart: Node
  1341. # create a new case object:
  1342. var n = Node(kind: nkIf, condition: nil)
  1343. # accessing n.thenPart is valid because the `nkIf` branch is active:
  1344. n.thenPart = Node(kind: nkFloat, floatVal: 2.0)
  1345. # the following statement raises an `FieldDefect` exception, because
  1346. # n.kind's value does not fit and the `nkString` branch is not active:
  1347. n.strVal = ""
  1348. # invalid: would change the active object branch:
  1349. n.kind = nkInt
  1350. var x = Node(kind: nkAdd, leftOp: Node(kind: nkInt, intVal: 4),
  1351. rightOp: Node(kind: nkInt, intVal: 2))
  1352. # valid: does not change the active object branch:
  1353. x.kind = nkSub
  1354. As can be seen from the example, an advantage to an object hierarchy is that
  1355. no casting between different object types is needed. Yet, access to invalid
  1356. object fields raises an exception.
  1357. The syntax of `case` in an object declaration follows closely the syntax of
  1358. the `case` statement: The branches in a `case` section may be indented too.
  1359. In the example, the `kind` field is called the `discriminator`:idx:\: For
  1360. safety, its address cannot be taken and assignments to it are restricted: The
  1361. new value must not lead to a change of the active object branch. Also, when the
  1362. fields of a particular branch are specified during object construction, the
  1363. corresponding discriminator value must be specified as a constant expression.
  1364. Instead of changing the active object branch, replace the old object in memory
  1365. with a new one completely:
  1366. .. code-block:: nim
  1367. var x = Node(kind: nkAdd, leftOp: Node(kind: nkInt, intVal: 4),
  1368. rightOp: Node(kind: nkInt, intVal: 2))
  1369. # change the node's contents:
  1370. x[] = NodeObj(kind: nkString, strVal: "abc")
  1371. Starting with version 0.20 `system.reset` cannot be used anymore to support
  1372. object branch changes as this never was completely memory safe.
  1373. As a special rule, the discriminator kind can also be bounded using a `case`
  1374. statement. If possible values of the discriminator variable in a
  1375. `case` statement branch are a subset of discriminator values for the selected
  1376. object branch, the initialization is considered valid. This analysis only works
  1377. for immutable discriminators of an ordinal type and disregards `elif`
  1378. branches. For discriminator values with a `range` type, the compiler
  1379. checks if the entire range of possible values for the discriminator value is
  1380. valid for the chosen object branch.
  1381. A small example:
  1382. .. code-block:: nim
  1383. let unknownKind = nkSub
  1384. # invalid: unsafe initialization because the kind field is not statically known:
  1385. var y = Node(kind: unknownKind, strVal: "y")
  1386. var z = Node()
  1387. case unknownKind
  1388. of nkAdd, nkSub:
  1389. # valid: possible values of this branch are a subset of nkAdd/nkSub object branch:
  1390. z = Node(kind: unknownKind, leftOp: Node(), rightOp: Node())
  1391. else:
  1392. echo "ignoring: ", unknownKind
  1393. # also valid, since unknownKindBounded can only contain the values nkAdd or nkSub
  1394. let unknownKindBounded = range[nkAdd..nkSub](unknownKind)
  1395. z = Node(kind: unknownKindBounded, leftOp: Node(), rightOp: Node())
  1396. cast uncheckedAssign
  1397. --------------------
  1398. Some restrictions for case objects can be disabled via a `{.cast(unsafeAssign).}` section:
  1399. .. code-block:: nim
  1400. :test: "nim c $1"
  1401. type
  1402. TokenKind* = enum
  1403. strLit, intLit
  1404. Token = object
  1405. case kind*: TokenKind
  1406. of strLit:
  1407. s*: string
  1408. of intLit:
  1409. i*: int64
  1410. proc passToVar(x: var TokenKind) = discard
  1411. var t = Token(kind: strLit, s: "abc")
  1412. {.cast(uncheckedAssign).}:
  1413. # inside the 'cast' section it is allowed to pass 't.kind' to a 'var T' parameter:
  1414. passToVar(t.kind)
  1415. # inside the 'cast' section it is allowed to set field 's' even though the
  1416. # constructed 'kind' field has an unknown value:
  1417. t = Token(kind: t.kind, s: "abc")
  1418. # inside the 'cast' section it is allowed to assign to the 't.kind' field directly:
  1419. t.kind = intLit
  1420. Set type
  1421. --------
  1422. .. include:: sets_fragment.txt
  1423. Reference and pointer types
  1424. ---------------------------
  1425. References (similar to pointers in other programming languages) are a
  1426. way to introduce many-to-one relationships. This means different references can
  1427. point to and modify the same location in memory (also called `aliasing`:idx:).
  1428. Nim distinguishes between `traced`:idx: and `untraced`:idx: references.
  1429. Untraced references are also called *pointers*. Traced references point to
  1430. objects of a garbage-collected heap, untraced references point to
  1431. manually allocated objects or objects somewhere else in memory. Thus
  1432. untraced references are *unsafe*. However, for certain low-level operations
  1433. (accessing the hardware) untraced references are unavoidable.
  1434. Traced references are declared with the **ref** keyword, untraced references
  1435. are declared with the **ptr** keyword. In general, a `ptr T` is implicitly
  1436. convertible to the `pointer` type.
  1437. An empty subscript `[]` notation can be used to de-refer a reference,
  1438. the `addr` procedure returns the address of an item. An address is always
  1439. an untraced reference.
  1440. Thus the usage of `addr` is an *unsafe* feature.
  1441. The `.` (access a tuple/object field operator)
  1442. and `[]` (array/string/sequence index operator) operators perform implicit
  1443. dereferencing operations for reference types:
  1444. .. code-block:: nim
  1445. type
  1446. Node = ref NodeObj
  1447. NodeObj = object
  1448. le, ri: Node
  1449. data: int
  1450. var
  1451. n: Node
  1452. new(n)
  1453. n.data = 9
  1454. # no need to write n[].data; in fact n[].data is highly discouraged!
  1455. Automatic dereferencing can be performed for the first argument of a routine
  1456. call, but this is an experimental feature and is described `here
  1457. <manual_experimental.html#automatic-dereferencing>`_.
  1458. In order to simplify structural type checking, recursive tuples are not valid:
  1459. .. code-block:: nim
  1460. # invalid recursion
  1461. type MyTuple = tuple[a: ref MyTuple]
  1462. Likewise `T = ref T` is an invalid type.
  1463. As a syntactical extension, `object` types can be anonymous if
  1464. declared in a type section via the `ref object` or `ptr object` notations.
  1465. This feature is useful if an object should only gain reference semantics:
  1466. .. code-block:: nim
  1467. type
  1468. Node = ref object
  1469. le, ri: Node
  1470. data: int
  1471. To allocate a new traced object, the built-in procedure `new` has to be used.
  1472. To deal with untraced memory, the procedures `alloc`, `dealloc` and
  1473. `realloc` can be used. The documentation of the `system <system.html>`_ module
  1474. contains further information.
  1475. Nil
  1476. ---
  1477. If a reference points to *nothing*, it has the value `nil`. `nil` is the
  1478. default value for all `ref` and `ptr` types. The `nil` value can also be
  1479. used like any other literal value. For example, it can be used in an assignment
  1480. like `myRef = nil`.
  1481. Dereferencing `nil` is an unrecoverable fatal runtime error (and not a panic).
  1482. A successful dereferencing operation `p[]` implies that `p` is not nil. This
  1483. can be exploited by the implementation to optimize code like:
  1484. .. code-block:: nim
  1485. p[].field = 3
  1486. if p != nil:
  1487. # if p were nil, `p[]` would have caused a crash already,
  1488. # so we know `p` is always not nil here.
  1489. action()
  1490. Into:
  1491. .. code-block:: nim
  1492. p[].field = 3
  1493. action()
  1494. *Note*: This is not comparable to C's "undefined behavior" for
  1495. dereferencing NULL pointers.
  1496. Mixing GC'ed memory with `ptr`
  1497. --------------------------------
  1498. Special care has to be taken if an untraced object contains traced objects like
  1499. traced references, strings, or sequences: in order to free everything properly,
  1500. the built-in procedure `reset` has to be called before freeing the untraced
  1501. memory manually:
  1502. .. code-block:: nim
  1503. type
  1504. Data = tuple[x, y: int, s: string]
  1505. # allocate memory for Data on the heap:
  1506. var d = cast[ptr Data](alloc0(sizeof(Data)))
  1507. # create a new string on the garbage collected heap:
  1508. d.s = "abc"
  1509. # tell the GC that the string is not needed anymore:
  1510. reset(d.s)
  1511. # free the memory:
  1512. dealloc(d)
  1513. Without the `reset` call the memory allocated for the `d.s` string would
  1514. never be freed. The example also demonstrates two important features for
  1515. low-level programming: the `sizeof` proc returns the size of a type or value
  1516. in bytes. The `cast` operator can circumvent the type system: the compiler
  1517. is forced to treat the result of the `alloc0` call (which returns an untyped
  1518. pointer) as if it would have the type `ptr Data`. Casting should only be
  1519. done if it is unavoidable: it breaks type safety and bugs can lead to
  1520. mysterious crashes.
  1521. **Note**: The example only works because the memory is initialized to zero
  1522. (`alloc0` instead of `alloc` does this): `d.s` is thus initialized to
  1523. binary zero which the string assignment can handle. One needs to know low-level
  1524. details like this when mixing garbage-collected data with unmanaged memory.
  1525. .. XXX finalizers for traced objects
  1526. Procedural type
  1527. ---------------
  1528. A procedural type is internally a pointer to a procedure. `nil` is
  1529. an allowed value for a variable of a procedural type.
  1530. Examples:
  1531. .. code-block:: nim
  1532. proc printItem(x: int) = ...
  1533. proc forEach(c: proc (x: int) {.cdecl.}) =
  1534. ...
  1535. forEach(printItem) # this will NOT compile because calling conventions differ
  1536. .. code-block:: nim
  1537. type
  1538. OnMouseMove = proc (x, y: int) {.closure.}
  1539. proc onMouseMove(mouseX, mouseY: int) =
  1540. # has default calling convention
  1541. echo "x: ", mouseX, " y: ", mouseY
  1542. proc setOnMouseMove(mouseMoveEvent: OnMouseMove) = discard
  1543. # ok, 'onMouseMove' has the default calling convention, which is compatible
  1544. # to 'closure':
  1545. setOnMouseMove(onMouseMove)
  1546. A subtle issue with procedural types is that the calling convention of the
  1547. procedure influences the type compatibility: procedural types are only
  1548. compatible if they have the same calling convention. As a special extension,
  1549. a procedure of the calling convention `nimcall` can be passed to a parameter
  1550. that expects a proc of the calling convention `closure`.
  1551. Nim supports these `calling conventions`:idx:\:
  1552. `nimcall`:idx:
  1553. is the default convention used for a Nim **proc**. It is the
  1554. same as `fastcall`, but only for C compilers that support `fastcall`.
  1555. `closure`:idx:
  1556. is the default calling convention for a **procedural type** that lacks
  1557. any pragma annotations. It indicates that the procedure has a hidden
  1558. implicit parameter (an *environment*). Proc vars that have the calling
  1559. convention `closure` take up two machine words: One for the proc pointer
  1560. and another one for the pointer to implicitly passed environment.
  1561. `stdcall`:idx:
  1562. This is the stdcall convention as specified by Microsoft. The generated C
  1563. procedure is declared with the `__stdcall` keyword.
  1564. `cdecl`:idx:
  1565. The cdecl convention means that a procedure shall use the same convention
  1566. as the C compiler. Under Windows the generated C procedure is declared with
  1567. the `__cdecl` keyword.
  1568. `safecall`:idx:
  1569. This is the safecall convention as specified by Microsoft. The generated C
  1570. procedure is declared with the `__safecall` keyword. The word *safe*
  1571. refers to the fact that all hardware registers shall be pushed to the
  1572. hardware stack.
  1573. `inline`:idx:
  1574. The inline convention means the caller should not call the procedure,
  1575. but inline its code directly. Note that Nim does not inline, but leaves
  1576. this to the C compiler; it generates `__inline` procedures. This is
  1577. only a hint for the compiler: it may completely ignore it and
  1578. it may inline procedures that are not marked as `inline`.
  1579. `fastcall`:idx:
  1580. Fastcall means different things to different C compilers. One gets whatever
  1581. the C `__fastcall` means.
  1582. `thiscall`:idx:
  1583. This is the thiscall calling convention as specified by Microsoft, used on
  1584. C++ class member functions on the x86 architecture.
  1585. `syscall`:idx:
  1586. The syscall convention is the same as `__syscall`:c: in C. It is used for
  1587. interrupts.
  1588. `noconv`:idx:
  1589. The generated C code will not have any explicit calling convention and thus
  1590. use the C compiler's default calling convention. This is needed because
  1591. Nim's default calling convention for procedures is `fastcall` to
  1592. improve speed.
  1593. Most calling conventions exist only for the Windows 32-bit platform.
  1594. The default calling convention is `nimcall`, unless it is an inner proc (a
  1595. proc inside of a proc). For an inner proc an analysis is performed whether it
  1596. accesses its environment. If it does so, it has the calling convention
  1597. `closure`, otherwise it has the calling convention `nimcall`.
  1598. Distinct type
  1599. -------------
  1600. A `distinct` type is a new type derived from a `base type`:idx: that is
  1601. incompatible with its base type. In particular, it is an essential property
  1602. of a distinct type that it **does not** imply a subtype relation between it
  1603. and its base type. Explicit type conversions from a distinct type to its
  1604. base type and vice versa are allowed. See also `distinctBase` to get the
  1605. reverse operation.
  1606. A distinct type is an ordinal type if its base type is an ordinal type.
  1607. Modeling currencies
  1608. ~~~~~~~~~~~~~~~~~~~~
  1609. A distinct type can be used to model different physical `units`:idx: with a
  1610. numerical base type, for example. The following example models currencies.
  1611. Different currencies should not be mixed in monetary calculations. Distinct
  1612. types are a perfect tool to model different currencies:
  1613. .. code-block:: nim
  1614. type
  1615. Dollar = distinct int
  1616. Euro = distinct int
  1617. var
  1618. d: Dollar
  1619. e: Euro
  1620. echo d + 12
  1621. # Error: cannot add a number with no unit and a `Dollar`
  1622. Unfortunately, `d + 12.Dollar` is not allowed either,
  1623. because `+` is defined for `int` (among others), not for `Dollar`. So
  1624. a `+` for dollars needs to be defined:
  1625. .. code-block::
  1626. proc `+` (x, y: Dollar): Dollar =
  1627. result = Dollar(int(x) + int(y))
  1628. It does not make sense to multiply a dollar with a dollar, but with a
  1629. number without unit; and the same holds for division:
  1630. .. code-block::
  1631. proc `*` (x: Dollar, y: int): Dollar =
  1632. result = Dollar(int(x) * y)
  1633. proc `*` (x: int, y: Dollar): Dollar =
  1634. result = Dollar(x * int(y))
  1635. proc `div` ...
  1636. This quickly gets tedious. The implementations are trivial and the compiler
  1637. should not generate all this code only to optimize it away later - after all
  1638. `+` for dollars should produce the same binary code as `+` for ints.
  1639. The pragma `borrow`:idx: has been designed to solve this problem; in principle,
  1640. it generates the above trivial implementations:
  1641. .. code-block:: nim
  1642. proc `*` (x: Dollar, y: int): Dollar {.borrow.}
  1643. proc `*` (x: int, y: Dollar): Dollar {.borrow.}
  1644. proc `div` (x: Dollar, y: int): Dollar {.borrow.}
  1645. The `borrow` pragma makes the compiler use the same implementation as
  1646. the proc that deals with the distinct type's base type, so no code is
  1647. generated.
  1648. But it seems all this boilerplate code needs to be repeated for the `Euro`
  1649. currency. This can be solved with templates_.
  1650. .. code-block:: nim
  1651. :test: "nim c $1"
  1652. template additive(typ: typedesc) =
  1653. proc `+` *(x, y: typ): typ {.borrow.}
  1654. proc `-` *(x, y: typ): typ {.borrow.}
  1655. # unary operators:
  1656. proc `+` *(x: typ): typ {.borrow.}
  1657. proc `-` *(x: typ): typ {.borrow.}
  1658. template multiplicative(typ, base: typedesc) =
  1659. proc `*` *(x: typ, y: base): typ {.borrow.}
  1660. proc `*` *(x: base, y: typ): typ {.borrow.}
  1661. proc `div` *(x: typ, y: base): typ {.borrow.}
  1662. proc `mod` *(x: typ, y: base): typ {.borrow.}
  1663. template comparable(typ: typedesc) =
  1664. proc `<` * (x, y: typ): bool {.borrow.}
  1665. proc `<=` * (x, y: typ): bool {.borrow.}
  1666. proc `==` * (x, y: typ): bool {.borrow.}
  1667. template defineCurrency(typ, base: untyped) =
  1668. type
  1669. typ* = distinct base
  1670. additive(typ)
  1671. multiplicative(typ, base)
  1672. comparable(typ)
  1673. defineCurrency(Dollar, int)
  1674. defineCurrency(Euro, int)
  1675. The borrow pragma can also be used to annotate the distinct type to allow
  1676. certain builtin operations to be lifted:
  1677. .. code-block:: nim
  1678. type
  1679. Foo = object
  1680. a, b: int
  1681. s: string
  1682. Bar {.borrow: `.`.} = distinct Foo
  1683. var bb: ref Bar
  1684. new bb
  1685. # field access now valid
  1686. bb.a = 90
  1687. bb.s = "abc"
  1688. Currently, only the dot accessor can be borrowed in this way.
  1689. Avoiding SQL injection attacks
  1690. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1691. An SQL statement that is passed from Nim to an SQL database might be
  1692. modeled as a string. However, using string templates and filling in the
  1693. values is vulnerable to the famous `SQL injection attack`:idx:\:
  1694. .. code-block:: nim
  1695. import std/strutils
  1696. proc query(db: DbHandle, statement: string) = ...
  1697. var
  1698. username: string
  1699. db.query("SELECT FROM users WHERE name = '$1'" % username)
  1700. # Horrible security hole, but the compiler does not mind!
  1701. This can be avoided by distinguishing strings that contain SQL from strings
  1702. that don't. Distinct types provide a means to introduce a new string type
  1703. `SQL` that is incompatible with `string`:
  1704. .. code-block:: nim
  1705. type
  1706. SQL = distinct string
  1707. proc query(db: DbHandle, statement: SQL) = ...
  1708. var
  1709. username: string
  1710. db.query("SELECT FROM users WHERE name = '$1'" % username)
  1711. # Static error: `query` expects an SQL string!
  1712. It is an essential property of abstract types that they **do not** imply a
  1713. subtype relation between the abstract type and its base type. Explicit type
  1714. conversions from `string` to `SQL` are allowed:
  1715. .. code-block:: nim
  1716. import std/[strutils, sequtils]
  1717. proc properQuote(s: string): SQL =
  1718. # quotes a string properly for an SQL statement
  1719. return SQL(s)
  1720. proc `%` (frmt: SQL, values: openarray[string]): SQL =
  1721. # quote each argument:
  1722. let v = values.mapIt(properQuote(it))
  1723. # we need a temporary type for the type conversion :-(
  1724. type StrSeq = seq[string]
  1725. # call strutils.`%`:
  1726. result = SQL(string(frmt) % StrSeq(v))
  1727. db.query("SELECT FROM users WHERE name = '$1'".SQL % [username])
  1728. Now we have compile-time checking against SQL injection attacks. Since
  1729. `"".SQL` is transformed to `SQL("")` no new syntax is needed for nice
  1730. looking `SQL` string literals. The hypothetical `SQL` type actually
  1731. exists in the library as the `SqlQuery type <db_common.html#SqlQuery>`_ of
  1732. modules like `db_sqlite <db_sqlite.html>`_.
  1733. Auto type
  1734. ---------
  1735. The `auto` type can only be used for return types and parameters. For return
  1736. types it causes the compiler to infer the type from the routine body:
  1737. .. code-block:: nim
  1738. proc returnsInt(): auto = 1984
  1739. For parameters it currently creates implicitly generic routines:
  1740. .. code-block:: nim
  1741. proc foo(a, b: auto) = discard
  1742. Is the same as:
  1743. .. code-block:: nim
  1744. proc foo[T1, T2](a: T1, b: T2) = discard
  1745. However, later versions of the language might change this to mean "infer the
  1746. parameters' types from the body". Then the above `foo` would be rejected as
  1747. the parameters' types can not be inferred from an empty `discard` statement.
  1748. Type relations
  1749. ==============
  1750. The following section defines several relations on types that are needed to
  1751. describe the type checking done by the compiler.
  1752. Type equality
  1753. -------------
  1754. Nim uses structural type equivalence for most types. Only for objects,
  1755. enumerations and distinct types and for generic types name equivalence is used.
  1756. Subtype relation
  1757. ----------------
  1758. If object `a` inherits from `b`, `a` is a subtype of `b`.
  1759. This subtype relation is extended to the types `var`, `ref`, `ptr`.
  1760. If `A` is a subtype of `B` and `A` and `B` are `object` types then:
  1761. - `var A` is a subtype of `var B`
  1762. - `ref A` is a subtype of `ref B`
  1763. - `ptr A` is a subtype of `ptr B`.
  1764. **Note**: In later versions of the language the subtype relation might
  1765. be changed to *require* the pointer indirection in order to prevent
  1766. "object slicing".
  1767. Convertible relation
  1768. --------------------
  1769. A type `a` is **implicitly** convertible to type `b` iff the following
  1770. algorithm returns true:
  1771. .. code-block:: nim
  1772. proc isImplicitlyConvertible(a, b: PType): bool =
  1773. if isSubtype(a, b):
  1774. return true
  1775. if isIntLiteral(a):
  1776. return b in {int8, int16, int32, int64, int, uint, uint8, uint16,
  1777. uint32, uint64, float32, float64}
  1778. case a.kind
  1779. of int: result = b in {int32, int64}
  1780. of int8: result = b in {int16, int32, int64, int}
  1781. of int16: result = b in {int32, int64, int}
  1782. of int32: result = b in {int64, int}
  1783. of uint: result = b in {uint32, uint64}
  1784. of uint8: result = b in {uint16, uint32, uint64}
  1785. of uint16: result = b in {uint32, uint64}
  1786. of uint32: result = b in {uint64}
  1787. of float32: result = b in {float64}
  1788. of float64: result = b in {float32}
  1789. of seq:
  1790. result = b == openArray and typeEquals(a.baseType, b.baseType)
  1791. of array:
  1792. result = b == openArray and typeEquals(a.baseType, b.baseType)
  1793. if a.baseType == char and a.indexType.rangeA == 0:
  1794. result = b == cstring
  1795. of cstring, ptr:
  1796. result = b == pointer
  1797. of string:
  1798. result = b == cstring
  1799. of proc:
  1800. result = typeEquals(a, b) or compatibleParametersAndEffects(a, b)
  1801. We used the predicate `typeEquals(a, b)` for the "type equality" property
  1802. and the predicate `isSubtype(a, b)` for the "subtype relation".
  1803. `compatibleParametersAndEffects(a, b)` is currently not specified.
  1804. Implicit conversions are also performed for Nim's `range` type
  1805. constructor.
  1806. Let `a0`, `b0` of type `T`.
  1807. Let `A = range[a0..b0]` be the argument's type, `F` the formal
  1808. parameter's type. Then an implicit conversion from `A` to `F`
  1809. exists if `a0 >= low(F) and b0 <= high(F)` and both `T` and `F`
  1810. are signed integers or if both are unsigned integers.
  1811. A type `a` is **explicitly** convertible to type `b` iff the following
  1812. algorithm returns true:
  1813. .. code-block:: nim
  1814. proc isIntegralType(t: PType): bool =
  1815. result = isOrdinal(t) or t.kind in {float, float32, float64}
  1816. proc isExplicitlyConvertible(a, b: PType): bool =
  1817. result = false
  1818. if isImplicitlyConvertible(a, b): return true
  1819. if typeEquals(a, b): return true
  1820. if a == distinct and typeEquals(a.baseType, b): return true
  1821. if b == distinct and typeEquals(b.baseType, a): return true
  1822. if isIntegralType(a) and isIntegralType(b): return true
  1823. if isSubtype(a, b) or isSubtype(b, a): return true
  1824. The convertible relation can be relaxed by a user-defined type
  1825. `converter`:idx:.
  1826. .. code-block:: nim
  1827. converter toInt(x: char): int = result = ord(x)
  1828. var
  1829. x: int
  1830. chr: char = 'a'
  1831. # implicit conversion magic happens here
  1832. x = chr
  1833. echo x # => 97
  1834. # one can use the explicit form too
  1835. x = chr.toInt
  1836. echo x # => 97
  1837. The type conversion `T(a)` is an L-value if `a` is an L-value and
  1838. `typeEqualsOrDistinct(T, typeof(a))` holds.
  1839. Assignment compatibility
  1840. ------------------------
  1841. An expression `b` can be assigned to an expression `a` iff `a` is an
  1842. `l-value` and `isImplicitlyConvertible(b.typ, a.typ)` holds.
  1843. Overload resolution
  1844. ===================
  1845. In a call `p(args)` the routine `p` that matches best is selected. If
  1846. multiple routines match equally well, the ambiguity is reported during
  1847. semantic analysis.
  1848. Every arg in args needs to match. There are multiple different categories how an
  1849. argument can match. Let `f` be the formal parameter's type and `a` the type
  1850. of the argument.
  1851. 1. Exact match: `a` and `f` are of the same type.
  1852. 2. Literal match: `a` is an integer literal of value `v`
  1853. and `f` is a signed or unsigned integer type and `v` is in `f`'s
  1854. range. Or: `a` is a floating-point literal of value `v`
  1855. and `f` is a floating-point type and `v` is in `f`'s
  1856. range.
  1857. 3. Generic match: `f` is a generic type and `a` matches, for
  1858. instance `a` is `int` and `f` is a generic (constrained) parameter
  1859. type (like in `[T]` or `[T: int|char]`).
  1860. 4. Subrange or subtype match: `a` is a `range[T]` and `T`
  1861. matches `f` exactly. Or: `a` is a subtype of `f`.
  1862. 5. Integral conversion match: `a` is convertible to `f` and `f` and `a`
  1863. is some integer or floating-point type.
  1864. 6. Conversion match: `a` is convertible to `f`, possibly via a user
  1865. defined `converter`.
  1866. These matching categories have a priority: An exact match is better than a
  1867. literal match and that is better than a generic match etc. In the following,
  1868. `count(p, m)` counts the number of matches of the matching category `m`
  1869. for the routine `p`.
  1870. A routine `p` matches better than a routine `q` if the following
  1871. algorithm returns true::
  1872. for each matching category m in ["exact match", "literal match",
  1873. "generic match", "subtype match",
  1874. "integral match", "conversion match"]:
  1875. if count(p, m) > count(q, m): return true
  1876. elif count(p, m) == count(q, m):
  1877. discard "continue with next category m"
  1878. else:
  1879. return false
  1880. return "ambiguous"
  1881. Some examples:
  1882. .. code-block:: nim
  1883. proc takesInt(x: int) = echo "int"
  1884. proc takesInt[T](x: T) = echo "T"
  1885. proc takesInt(x: int16) = echo "int16"
  1886. takesInt(4) # "int"
  1887. var x: int32
  1888. takesInt(x) # "T"
  1889. var y: int16
  1890. takesInt(y) # "int16"
  1891. var z: range[0..4] = 0
  1892. takesInt(z) # "T"
  1893. If this algorithm returns "ambiguous" further disambiguation is performed:
  1894. If the argument `a` matches both the parameter type `f` of `p`
  1895. and `g` of `q` via a subtyping relation, the inheritance depth is taken
  1896. into account:
  1897. .. code-block:: nim
  1898. type
  1899. A = object of RootObj
  1900. B = object of A
  1901. C = object of B
  1902. proc p(obj: A) =
  1903. echo "A"
  1904. proc p(obj: B) =
  1905. echo "B"
  1906. var c = C()
  1907. # not ambiguous, calls 'B', not 'A' since B is a subtype of A
  1908. # but not vice versa:
  1909. p(c)
  1910. proc pp(obj: A, obj2: B) = echo "A B"
  1911. proc pp(obj: B, obj2: A) = echo "B A"
  1912. # but this is ambiguous:
  1913. pp(c, c)
  1914. Likewise, for generic matches, the most specialized generic type (that still
  1915. matches) is preferred:
  1916. .. code-block:: nim
  1917. proc gen[T](x: ref ref T) = echo "ref ref T"
  1918. proc gen[T](x: ref T) = echo "ref T"
  1919. proc gen[T](x: T) = echo "T"
  1920. var ri: ref int
  1921. gen(ri) # "ref T"
  1922. Overloading based on 'var T'
  1923. --------------------------------------
  1924. If the formal parameter `f` is of type `var T`
  1925. in addition to the ordinary type checking,
  1926. the argument is checked to be an `l-value`:idx:.
  1927. `var T` matches better than just `T` then.
  1928. .. code-block:: nim
  1929. proc sayHi(x: int): string =
  1930. # matches a non-var int
  1931. result = $x
  1932. proc sayHi(x: var int): string =
  1933. # matches a var int
  1934. result = $(x + 10)
  1935. proc sayHello(x: int) =
  1936. var m = x # a mutable version of x
  1937. echo sayHi(x) # matches the non-var version of sayHi
  1938. echo sayHi(m) # matches the var version of sayHi
  1939. sayHello(3) # 3
  1940. # 13
  1941. Lazy type resolution for untyped
  1942. --------------------------------
  1943. **Note**: An `unresolved`:idx: expression is an expression for which no symbol
  1944. lookups and no type checking have been performed.
  1945. Since templates and macros that are not declared as `immediate` participate
  1946. in overloading resolution, it's essential to have a way to pass unresolved
  1947. expressions to a template or macro. This is what the meta-type `untyped`
  1948. accomplishes:
  1949. .. code-block:: nim
  1950. template rem(x: untyped) = discard
  1951. rem unresolvedExpression(undeclaredIdentifier)
  1952. A parameter of type `untyped` always matches any argument (as long as there is
  1953. any argument passed to it).
  1954. But one has to watch out because other overloads might trigger the
  1955. argument's resolution:
  1956. .. code-block:: nim
  1957. template rem(x: untyped) = discard
  1958. proc rem[T](x: T) = discard
  1959. # undeclared identifier: 'unresolvedExpression'
  1960. rem unresolvedExpression(undeclaredIdentifier)
  1961. `untyped` and `varargs[untyped]` are the only metatype that are lazy in this sense, the other
  1962. metatypes `typed` and `typedesc` are not lazy.
  1963. Varargs matching
  1964. ----------------
  1965. See `Varargs <#types-varargs>`_.
  1966. iterable
  1967. --------
  1968. A called `iterator` yielding type `T` can be passed to a template or macro via
  1969. a parameter typed as `untyped` (for unresolved expressions) or the type class
  1970. `iterable` or `iterable[T]` (after type checking and overload resolution).
  1971. .. code-block:: nim
  1972. iterator iota(n: int): int =
  1973. for i in 0..<n: yield i
  1974. template toSeq2[T](a: iterable[T]): seq[T] =
  1975. var ret: seq[T]
  1976. assert a.typeof is T
  1977. for ai in a: ret.add ai
  1978. ret
  1979. assert iota(3).toSeq2 == @[0, 1, 2]
  1980. assert toSeq2(5..7) == @[5, 6, 7]
  1981. assert not compiles(toSeq2(@[1,2])) # seq[int] is not an iterable
  1982. assert toSeq2(items(@[1,2])) == @[1, 2] # but items(@[1,2]) is
  1983. Overload disambiguation
  1984. =======================
  1985. For routine calls "overload resolution" is performed. There is a weaker form of
  1986. overload resolution called *overload disambiguation* that is performed when an
  1987. overloaded symbol is used in a context where there is additional type information
  1988. available. Let `p` be an overloaded symbol. These contexts are:
  1989. - In a function call `q(..., p, ...)` when the corresponding formal parameter
  1990. of `q` is a `proc` type. If `q` itself is overloaded then the cartesian product
  1991. of every interpretation of `q` and `p` must be considered.
  1992. - In an object constructor `Obj(..., field: p, ...)` when `field` is a `proc`
  1993. type. Analogous rules exist for array/set/tuple constructors.
  1994. - In a declaration like `x: T = p` when `T` is a `proc` type.
  1995. As usual, ambiguous matches produce a compile-time error.
  1996. Statements and expressions
  1997. ==========================
  1998. Nim uses the common statement/expression paradigm: Statements do not
  1999. produce a value in contrast to expressions. However, some expressions are
  2000. statements.
  2001. Statements are separated into `simple statements`:idx: and
  2002. `complex statements`:idx:.
  2003. Simple statements are statements that cannot contain other statements like
  2004. assignments, calls, or the `return` statement; complex statements can
  2005. contain other statements. To avoid the `dangling else problem`:idx:, complex
  2006. statements always have to be indented. The details can be found in the grammar.
  2007. Statement list expression
  2008. -------------------------
  2009. Statements can also occur in an expression context that looks
  2010. like `(stmt1; stmt2; ...; ex)`. This is called
  2011. a statement list expression or `(;)`. The type
  2012. of `(stmt1; stmt2; ...; ex)` is the type of `ex`. All the other statements
  2013. must be of type `void`. (One can use `discard` to produce a `void` type.)
  2014. `(;)` does not introduce a new scope.
  2015. Discard statement
  2016. -----------------
  2017. Example:
  2018. .. code-block:: nim
  2019. proc p(x, y: int): int =
  2020. result = x + y
  2021. discard p(3, 4) # discard the return value of `p`
  2022. The `discard` statement evaluates its expression for side-effects and
  2023. throws the expression's resulting value away, and should only be used
  2024. when ignoring this value is known not to cause problems.
  2025. Ignoring the return value of a procedure without using a discard statement is
  2026. a static error.
  2027. The return value can be ignored implicitly if the called proc/iterator has
  2028. been declared with the `discardable`:idx: pragma:
  2029. .. code-block:: nim
  2030. proc p(x, y: int): int {.discardable.} =
  2031. result = x + y
  2032. p(3, 4) # now valid
  2033. however the discardable pragma does not work on templates as templates substitute the AST in place. For example:
  2034. .. code-block:: nim
  2035. {.push discardable .}
  2036. template example(): string = "https://nim-lang.org"
  2037. {.pop.}
  2038. example()
  2039. This template will resolve into "https://nim-lang.org" which is a string literal and since {.discardable.} doesn't apply to literals, the compiler will error.
  2040. An empty `discard` statement is often used as a null statement:
  2041. .. code-block:: nim
  2042. proc classify(s: string) =
  2043. case s[0]
  2044. of SymChars, '_': echo "an identifier"
  2045. of '0'..'9': echo "a number"
  2046. else: discard
  2047. Void context
  2048. ------------
  2049. In a list of statements, every expression except the last one needs to have the
  2050. type `void`. In addition to this rule an assignment to the builtin `result`
  2051. symbol also triggers a mandatory `void` context for the subsequent expressions:
  2052. .. code-block:: nim
  2053. proc invalid*(): string =
  2054. result = "foo"
  2055. "invalid" # Error: value of type 'string' has to be discarded
  2056. .. code-block:: nim
  2057. proc valid*(): string =
  2058. let x = 317
  2059. "valid"
  2060. Var statement
  2061. -------------
  2062. Var statements declare new local and global variables and
  2063. initialize them. A comma-separated list of variables can be used to specify
  2064. variables of the same type:
  2065. .. code-block:: nim
  2066. var
  2067. a: int = 0
  2068. x, y, z: int
  2069. If an initializer is given, the type can be omitted: the variable is then of the
  2070. same type as the initializing expression. Variables are always initialized
  2071. with a default value if there is no initializing expression. The default
  2072. value depends on the type and is always a zero in binary.
  2073. ============================ ==============================================
  2074. Type default value
  2075. ============================ ==============================================
  2076. any integer type 0
  2077. any float 0.0
  2078. char '\\0'
  2079. bool false
  2080. ref or pointer type nil
  2081. procedural type nil
  2082. sequence `@[]`
  2083. string `""`
  2084. tuple[x: A, y: B, ...] (default(A), default(B), ...)
  2085. (analogous for objects)
  2086. array[0..., T] [default(T), ...]
  2087. range[T] default(T); this may be out of the valid range
  2088. T = enum cast[T]\(0); this may be an invalid value
  2089. ============================ ==============================================
  2090. The implicit initialization can be avoided for optimization reasons with the
  2091. `noinit`:idx: pragma:
  2092. .. code-block:: nim
  2093. var
  2094. a {.noInit.}: array[0..1023, char]
  2095. If a proc is annotated with the `noinit` pragma, this refers to its implicit
  2096. `result` variable:
  2097. .. code-block:: nim
  2098. proc returnUndefinedValue: int {.noinit.} = discard
  2099. The implicit initialization can also be prevented by the `requiresInit`:idx:
  2100. type pragma. The compiler requires an explicit initialization for the object
  2101. and all of its fields. However, it does a `control flow analysis`:idx: to prove
  2102. the variable has been initialized and does not rely on syntactic properties:
  2103. .. code-block:: nim
  2104. type
  2105. MyObject = object {.requiresInit.}
  2106. proc p() =
  2107. # the following is valid:
  2108. var x: MyObject
  2109. if someCondition():
  2110. x = a()
  2111. else:
  2112. x = a()
  2113. # use x
  2114. `requiresInit` pragma can also be applyied to `distinct` types.
  2115. Given the following distinct type definitions:
  2116. .. code-block:: nim
  2117. type
  2118. DistinctObject {.requiresInit, borrow: `.`.} = distinct MyObject
  2119. DistinctString {.requiresInit.} = distinct string
  2120. The following code blocks will fail to compile:
  2121. .. code-block:: nim
  2122. var foo: DistinctFoo
  2123. foo.x = "test"
  2124. doAssert foo.x == "test"
  2125. .. code-block:: nim
  2126. var s: DistinctString
  2127. s = "test"
  2128. doAssert s == "test"
  2129. But these ones will compile successfully:
  2130. .. code-block:: nim
  2131. let foo = DistinctFoo(Foo(x: "test"))
  2132. doAssert foo.x == "test"
  2133. .. code-block:: nim
  2134. let s = "test"
  2135. doAssert s == "test"
  2136. Let statement
  2137. -------------
  2138. A `let` statement declares new local and global `single assignment`:idx:
  2139. variables and binds a value to them. The syntax is the same as that of the `var`
  2140. statement, except that the keyword `var` is replaced by the keyword `let`.
  2141. Let variables are not l-values and can thus not be passed to `var` parameters
  2142. nor can their address be taken. They cannot be assigned new values.
  2143. For let variables, the same pragmas are available as for ordinary variables.
  2144. As `let` statements are immutable after creation they need to define a value
  2145. when they are declared. The only exception to this is if the `{.importc.}`
  2146. pragma (or any of the other `importX` pragmas) is applied, in this case the
  2147. value is expected to come from native code, typically a C/C++ `const`.
  2148. Tuple unpacking
  2149. ---------------
  2150. In a `var` or `let` statement tuple unpacking can be performed. The special
  2151. identifier `_` can be used to ignore some parts of the tuple:
  2152. .. code-block:: nim
  2153. proc returnsTuple(): (int, int, int) = (4, 2, 3)
  2154. let (x, _, z) = returnsTuple()
  2155. Const section
  2156. -------------
  2157. A const section declares constants whose values are constant expressions:
  2158. .. code-block::
  2159. import std/[strutils]
  2160. const
  2161. roundPi = 3.1415
  2162. constEval = contains("abc", 'b') # computed at compile time!
  2163. Once declared, a constant's symbol can be used as a constant expression.
  2164. See `Constants and Constant Expressions <#constants-and-constant-expressions>`_
  2165. for details.
  2166. Static statement/expression
  2167. ---------------------------
  2168. A static statement/expression explicitly requires compile-time execution.
  2169. Even some code that has side effects is permitted in a static block:
  2170. .. code-block::
  2171. static:
  2172. echo "echo at compile time"
  2173. `static` can also be used like a routine.
  2174. .. code-block:: nim
  2175. proc getNum(a: int): int = a
  2176. # Below calls "echo getNum(123)" at compile time.
  2177. static:
  2178. echo getNum(123)
  2179. # Below call evaluates the "getNum(123)" at compile time, but its
  2180. # result gets used at run time.
  2181. echo static(getNum(123))
  2182. There are limitations on what Nim code can be executed at compile time;
  2183. see `Restrictions on Compile-Time Execution
  2184. <#restrictions-on-compileminustime-execution>`_ for details.
  2185. It's a static error if the compiler cannot execute the block at compile
  2186. time.
  2187. If statement
  2188. ------------
  2189. Example:
  2190. .. code-block:: nim
  2191. var name = readLine(stdin)
  2192. if name == "Andreas":
  2193. echo "What a nice name!"
  2194. elif name == "":
  2195. echo "Don't you have a name?"
  2196. else:
  2197. echo "Boring name..."
  2198. The `if` statement is a simple way to make a branch in the control flow:
  2199. The expression after the keyword `if` is evaluated, if it is true
  2200. the corresponding statements after the `:` are executed. Otherwise
  2201. the expression after the `elif` is evaluated (if there is an
  2202. `elif` branch), if it is true the corresponding statements after
  2203. the `:` are executed. This goes on until the last `elif`. If all
  2204. conditions fail, the `else` part is executed. If there is no `else`
  2205. part, execution continues with the next statement.
  2206. In `if` statements, new scopes begin immediately after
  2207. the `if`/`elif`/`else` keywords and ends after the
  2208. corresponding *then* block.
  2209. For visualization purposes the scopes have been enclosed
  2210. in `{| |}` in the following example:
  2211. .. code-block:: nim
  2212. if {| (let m = input =~ re"(\w+)=\w+"; m.isMatch):
  2213. echo "key ", m[0], " value ", m[1] |}
  2214. elif {| (let m = input =~ re""; m.isMatch):
  2215. echo "new m in this scope" |}
  2216. else: {|
  2217. echo "m not declared here" |}
  2218. Case statement
  2219. --------------
  2220. Example:
  2221. .. code-block:: nim
  2222. let line = readline(stdin)
  2223. case line
  2224. of "delete-everything", "restart-computer":
  2225. echo "permission denied"
  2226. of "go-for-a-walk": echo "please yourself"
  2227. elif line.len == 0: echo "empty" # optional, must come after `of` branches
  2228. else: echo "unknown command" # ditto
  2229. # indentation of the branches is also allowed; and so is an optional colon
  2230. # after the selecting expression:
  2231. case readline(stdin):
  2232. of "delete-everything", "restart-computer":
  2233. echo "permission denied"
  2234. of "go-for-a-walk": echo "please yourself"
  2235. else: echo "unknown command"
  2236. The `case` statement is similar to the `if` statement, but it represents
  2237. a multi-branch selection. The expression after the keyword `case` is
  2238. evaluated and if its value is in a *slicelist* the corresponding statements
  2239. (after the `of` keyword) are executed. If the value is not in any
  2240. given *slicelist*, trailing `elif` and `else` parts are executed using same
  2241. semantics as for `if` statement, and `elif` is handled just like `else: if`.
  2242. If there are no `else` or `elif` parts and not
  2243. all possible values that `expr` can hold occur in a *slicelist*, a static error occurs.
  2244. This holds only for expressions of ordinal types.
  2245. "All possible values" of `expr` are determined by `expr`'s type.
  2246. To suppress the static error an `else: discard` should be used.
  2247. For non-ordinal types, it is not possible to list every possible value and so
  2248. these always require an `else` part.
  2249. An exception to this rule is for the `string` type, which currently doesn't
  2250. require a trailing `else` or `elif` branch; it's unspecified whether this will
  2251. keep working in future versions.
  2252. Because case statements are checked for exhaustiveness during semantic analysis,
  2253. the value in every `of` branch must be a constant expression.
  2254. This restriction also allows the compiler to generate more performant code.
  2255. As a special semantic extension, an expression in an `of` branch of a case
  2256. statement may evaluate to a set or array constructor; the set or array is then
  2257. expanded into a list of its elements:
  2258. .. code-block:: nim
  2259. const
  2260. SymChars: set[char] = {'a'..'z', 'A'..'Z', '\x80'..'\xFF'}
  2261. proc classify(s: string) =
  2262. case s[0]
  2263. of SymChars, '_': echo "an identifier"
  2264. of '0'..'9': echo "a number"
  2265. else: echo "other"
  2266. # is equivalent to:
  2267. proc classify(s: string) =
  2268. case s[0]
  2269. of 'a'..'z', 'A'..'Z', '\x80'..'\xFF', '_': echo "an identifier"
  2270. of '0'..'9': echo "a number"
  2271. else: echo "other"
  2272. The `case` statement doesn't produce an l-value, so the following example
  2273. won't work:
  2274. .. code-block:: nim
  2275. type
  2276. Foo = ref object
  2277. x: seq[string]
  2278. proc get_x(x: Foo): var seq[string] =
  2279. # doesn't work
  2280. case true
  2281. of true:
  2282. x.x
  2283. else:
  2284. x.x
  2285. var foo = Foo(x: @[])
  2286. foo.get_x().add("asd")
  2287. This can be fixed by explicitly using `result` or `return`:
  2288. .. code-block:: nim
  2289. proc get_x(x: Foo): var seq[string] =
  2290. case true
  2291. of true:
  2292. result = x.x
  2293. else:
  2294. result = x.x
  2295. When statement
  2296. --------------
  2297. Example:
  2298. .. code-block:: nim
  2299. when sizeof(int) == 2:
  2300. echo "running on a 16 bit system!"
  2301. elif sizeof(int) == 4:
  2302. echo "running on a 32 bit system!"
  2303. elif sizeof(int) == 8:
  2304. echo "running on a 64 bit system!"
  2305. else:
  2306. echo "cannot happen!"
  2307. The `when` statement is almost identical to the `if` statement with some
  2308. exceptions:
  2309. * Each condition (`expr`) has to be a constant expression (of type `bool`).
  2310. * The statements do not open a new scope.
  2311. * The statements that belong to the expression that evaluated to true are
  2312. translated by the compiler, the other statements are not checked for
  2313. semantics! However, each condition is checked for semantics.
  2314. The `when` statement enables conditional compilation techniques. As
  2315. a special syntactic extension, the `when` construct is also available
  2316. within `object` definitions.
  2317. When nimvm statement
  2318. --------------------
  2319. `nimvm` is a special symbol that may be used as the expression of a
  2320. `when nimvm` statement to differentiate the execution path between
  2321. compile-time and the executable.
  2322. Example:
  2323. .. code-block:: nim
  2324. proc someProcThatMayRunInCompileTime(): bool =
  2325. when nimvm:
  2326. # This branch is taken at compile time.
  2327. result = true
  2328. else:
  2329. # This branch is taken in the executable.
  2330. result = false
  2331. const ctValue = someProcThatMayRunInCompileTime()
  2332. let rtValue = someProcThatMayRunInCompileTime()
  2333. assert(ctValue == true)
  2334. assert(rtValue == false)
  2335. A `when nimvm` statement must meet the following requirements:
  2336. * Its expression must always be `nimvm`. More complex expressions are not
  2337. allowed.
  2338. * It must not contain `elif` branches.
  2339. * It must contain an `else` branch.
  2340. * Code in branches must not affect semantics of the code that follows the
  2341. `when nimvm` statement. E.g. it must not define symbols that are used in
  2342. the following code.
  2343. Return statement
  2344. ----------------
  2345. Example:
  2346. .. code-block:: nim
  2347. return 40+2
  2348. The `return` statement ends the execution of the current procedure.
  2349. It is only allowed in procedures. If there is an `expr`, this is syntactic
  2350. sugar for:
  2351. .. code-block:: nim
  2352. result = expr
  2353. return result
  2354. `return` without an expression is a short notation for `return result` if
  2355. the proc has a return type. The `result`:idx: variable is always the return
  2356. value of the procedure. It is automatically declared by the compiler. As all
  2357. variables, `result` is initialized to (binary) zero:
  2358. .. code-block:: nim
  2359. proc returnZero(): int =
  2360. # implicitly returns 0
  2361. Yield statement
  2362. ---------------
  2363. Example:
  2364. .. code-block:: nim
  2365. yield (1, 2, 3)
  2366. The `yield` statement is used instead of the `return` statement in
  2367. iterators. It is only valid in iterators. Execution is returned to the body
  2368. of the for loop that called the iterator. Yield does not end the iteration
  2369. process, but the execution is passed back to the iterator if the next iteration
  2370. starts. See the section about iterators (`Iterators and the for statement`_)
  2371. for further information.
  2372. Block statement
  2373. ---------------
  2374. Example:
  2375. .. code-block:: nim
  2376. var found = false
  2377. block myblock:
  2378. for i in 0..3:
  2379. for j in 0..3:
  2380. if a[j][i] == 7:
  2381. found = true
  2382. break myblock # leave the block, in this case both for-loops
  2383. echo found
  2384. The block statement is a means to group statements to a (named) `block`.
  2385. Inside the block, the `break` statement is allowed to leave the block
  2386. immediately. A `break` statement can contain a name of a surrounding
  2387. block to specify which block is to be left.
  2388. Break statement
  2389. ---------------
  2390. Example:
  2391. .. code-block:: nim
  2392. break
  2393. The `break` statement is used to leave a block immediately. If `symbol`
  2394. is given, it is the name of the enclosing block that is to be left. If it is
  2395. absent, the innermost block is left.
  2396. While statement
  2397. ---------------
  2398. Example:
  2399. .. code-block:: nim
  2400. echo "Please tell me your password:"
  2401. var pw = readLine(stdin)
  2402. while pw != "12345":
  2403. echo "Wrong password! Next try:"
  2404. pw = readLine(stdin)
  2405. The `while` statement is executed until the `expr` evaluates to false.
  2406. Endless loops are no error. `while` statements open an `implicit block`
  2407. so that they can be left with a `break` statement.
  2408. Continue statement
  2409. ------------------
  2410. A `continue` statement leads to the immediate next iteration of the
  2411. surrounding loop construct. It is only allowed within a loop. A continue
  2412. statement is syntactic sugar for a nested block:
  2413. .. code-block:: nim
  2414. while expr1:
  2415. stmt1
  2416. continue
  2417. stmt2
  2418. Is equivalent to:
  2419. .. code-block:: nim
  2420. while expr1:
  2421. block myBlockName:
  2422. stmt1
  2423. break myBlockName
  2424. stmt2
  2425. Assembler statement
  2426. -------------------
  2427. The direct embedding of assembler code into Nim code is supported
  2428. by the unsafe `asm` statement. Identifiers in the assembler code that refer to
  2429. Nim identifiers shall be enclosed in a special character which can be
  2430. specified in the statement's pragmas. The default special character is `'\`'`:
  2431. .. code-block:: nim
  2432. {.push stackTrace:off.}
  2433. proc addInt(a, b: int): int =
  2434. # a in eax, and b in edx
  2435. asm """
  2436. mov eax, `a`
  2437. add eax, `b`
  2438. jno theEnd
  2439. call `raiseOverflow`
  2440. theEnd:
  2441. """
  2442. {.pop.}
  2443. If the GNU assembler is used, quotes and newlines are inserted automatically:
  2444. .. code-block:: nim
  2445. proc addInt(a, b: int): int =
  2446. asm """
  2447. addl %%ecx, %%eax
  2448. jno 1
  2449. call `raiseOverflow`
  2450. 1:
  2451. :"=a"(`result`)
  2452. :"a"(`a`), "c"(`b`)
  2453. """
  2454. Instead of:
  2455. .. code-block:: nim
  2456. proc addInt(a, b: int): int =
  2457. asm """
  2458. "addl %%ecx, %%eax\n"
  2459. "jno 1\n"
  2460. "call `raiseOverflow`\n"
  2461. "1: \n"
  2462. :"=a"(`result`)
  2463. :"a"(`a`), "c"(`b`)
  2464. """
  2465. Using statement
  2466. ---------------
  2467. The `using` statement provides syntactic convenience in modules where
  2468. the same parameter names and types are used over and over. Instead of:
  2469. .. code-block:: nim
  2470. proc foo(c: Context; n: Node) = ...
  2471. proc bar(c: Context; n: Node, counter: int) = ...
  2472. proc baz(c: Context; n: Node) = ...
  2473. One can tell the compiler about the convention that a parameter of
  2474. name `c` should default to type `Context`, `n` should default to
  2475. `Node` etc.:
  2476. .. code-block:: nim
  2477. using
  2478. c: Context
  2479. n: Node
  2480. counter: int
  2481. proc foo(c, n) = ...
  2482. proc bar(c, n, counter) = ...
  2483. proc baz(c, n) = ...
  2484. proc mixedMode(c, n; x, y: int) =
  2485. # 'c' is inferred to be of the type 'Context'
  2486. # 'n' is inferred to be of the type 'Node'
  2487. # But 'x' and 'y' are of type 'int'.
  2488. The `using` section uses the same indentation based grouping syntax as
  2489. a `var` or `let` section.
  2490. Note that `using` is not applied for `template` since the untyped template
  2491. parameters default to the type `system.untyped`.
  2492. Mixing parameters that should use the `using` declaration with parameters
  2493. that are explicitly typed is possible and requires a semicolon between them.
  2494. If expression
  2495. -------------
  2496. An `if` expression is almost like an if statement, but it is an expression.
  2497. This feature is similar to *ternary operators* in other languages.
  2498. Example:
  2499. .. code-block:: nim
  2500. var y = if x > 8: 9 else: 10
  2501. An if expression always results in a value, so the `else` part is
  2502. required. `Elif` parts are also allowed.
  2503. When expression
  2504. ---------------
  2505. Just like an `if` expression, but corresponding to the `when` statement.
  2506. Case expression
  2507. ---------------
  2508. The `case` expression is again very similar to the case statement:
  2509. .. code-block:: nim
  2510. var favoriteFood = case animal
  2511. of "dog": "bones"
  2512. of "cat": "mice"
  2513. elif animal.endsWith"whale": "plankton"
  2514. else:
  2515. echo "I'm not sure what to serve, but everybody loves ice cream"
  2516. "ice cream"
  2517. As seen in the above example, the case expression can also introduce side
  2518. effects. When multiple statements are given for a branch, Nim will use
  2519. the last expression as the result value.
  2520. Block expression
  2521. ----------------
  2522. A `block` expression is almost like a block statement, but it is an expression
  2523. that uses the last expression under the block as the value.
  2524. It is similar to the statement list expression, but the statement list expression
  2525. does not open a new block scope.
  2526. .. code-block:: nim
  2527. let a = block:
  2528. var fib = @[0, 1]
  2529. for i in 0..10:
  2530. fib.add fib[^1] + fib[^2]
  2531. fib
  2532. Table constructor
  2533. -----------------
  2534. A table constructor is syntactic sugar for an array constructor:
  2535. .. code-block:: nim
  2536. {"key1": "value1", "key2", "key3": "value2"}
  2537. # is the same as:
  2538. [("key1", "value1"), ("key2", "value2"), ("key3", "value2")]
  2539. The empty table can be written `{:}` (in contrast to the empty set
  2540. which is `{}`) which is thus another way to write the empty array
  2541. constructor `[]`. This slightly unusual way of supporting tables
  2542. has lots of advantages:
  2543. * The order of the (key,value)-pairs is preserved, thus it is easy to
  2544. support ordered dicts with for example `{key: val}.newOrderedTable`.
  2545. * A table literal can be put into a `const` section and the compiler
  2546. can easily put it into the executable's data section just like it can
  2547. for arrays and the generated data section requires a minimal amount
  2548. of memory.
  2549. * Every table implementation is treated equally syntactically.
  2550. * Apart from the minimal syntactic sugar, the language core does not need to
  2551. know about tables.
  2552. Type conversions
  2553. ----------------
  2554. Syntactically a *type conversion* is like a procedure call, but a
  2555. type name replaces the procedure name. A type conversion is always
  2556. safe in the sense that a failure to convert a type to another
  2557. results in an exception (if it cannot be determined statically).
  2558. Ordinary procs are often preferred over type conversions in Nim: For instance,
  2559. `$` is the `toString` operator by convention and `toFloat` and `toInt`
  2560. can be used to convert from floating-point to integer or vice versa.
  2561. Type conversion can also be used to disambiguate overloaded routines:
  2562. .. code-block:: nim
  2563. proc p(x: int) = echo "int"
  2564. proc p(x: string) = echo "string"
  2565. let procVar = (proc(x: string))(p)
  2566. procVar("a")
  2567. Since operations on unsigned numbers wrap around and are unchecked so are
  2568. type conversions to unsigned integers and between unsigned integers. The
  2569. rationale for this is mostly better interoperability with the C Programming
  2570. language when algorithms are ported from C to Nim.
  2571. Exception: Values that are converted to an unsigned type at compile time
  2572. are checked so that code like `byte(-1)` does not compile.
  2573. **Note**: Historically the operations
  2574. were unchecked and the conversions were sometimes checked but starting with
  2575. the revision 1.0.4 of this document and the language implementation the
  2576. conversions too are now *always unchecked*.
  2577. Type casts
  2578. ----------
  2579. *Type casts* are a crude mechanism to interpret the bit pattern of an expression
  2580. as if it would be of another type. Type casts are only needed for low-level
  2581. programming and are inherently unsafe.
  2582. .. code-block:: nim
  2583. cast[int](x)
  2584. The target type of a cast must be a concrete type, for instance, a target type
  2585. that is a type class (which is non-concrete) would be invalid:
  2586. .. code-block:: nim
  2587. type Foo = int or float
  2588. var x = cast[Foo](1) # Error: cannot cast to a non concrete type: 'Foo'
  2589. Type casts should not be confused with *type conversions,* as mentioned in the
  2590. prior section. Unlike type conversions, a type cast cannot change the underlying
  2591. bit pattern of the data being casted (aside from that the size of the target type
  2592. may differ from the source type). Casting resembles *type punning* in other
  2593. languages or C++'s `reinterpret_cast`:cpp: and `bit_cast`:cpp: features.
  2594. The addr operator
  2595. -----------------
  2596. The `addr` operator returns the address of an l-value. If the type of the
  2597. location is `T`, the `addr` operator result is of the type `ptr T`. An
  2598. address is always an untraced reference. Taking the address of an object that
  2599. resides on the stack is **unsafe**, as the pointer may live longer than the
  2600. object on the stack and can thus reference a non-existing object. One can get
  2601. the address of variables, but one can't use it on variables declared through
  2602. `let` statements:
  2603. .. code-block:: nim
  2604. let t1 = "Hello"
  2605. var
  2606. t2 = t1
  2607. t3 : pointer = addr(t2)
  2608. echo repr(addr(t2))
  2609. # --> ref 0x7fff6b71b670 --> 0x10bb81050"Hello"
  2610. echo cast[ptr string](t3)[]
  2611. # --> Hello
  2612. # The following line doesn't compile:
  2613. echo repr(addr(t1))
  2614. # Error: expression has no address
  2615. The unsafeAddr operator
  2616. -----------------------
  2617. For easier interoperability with other compiled languages such as C, retrieving
  2618. the address of a `let` variable, a parameter, or a `for` loop variable can
  2619. be accomplished by using the `unsafeAddr` operation:
  2620. .. code-block:: nim
  2621. let myArray = [1, 2, 3]
  2622. foreignProcThatTakesAnAddr(unsafeAddr myArray)
  2623. Procedures
  2624. ==========
  2625. What most programming languages call `methods`:idx: or `functions`:idx: are
  2626. called `procedures`:idx: in Nim. A procedure
  2627. declaration consists of an identifier, zero or more formal parameters, a return
  2628. value type and a block of code. Formal parameters are declared as a list of
  2629. identifiers separated by either comma or semicolon. A parameter is given a type
  2630. by `: typename`. The type applies to all parameters immediately before it,
  2631. until either the beginning of the parameter list, a semicolon separator, or an
  2632. already typed parameter, is reached. The semicolon can be used to make
  2633. separation of types and subsequent identifiers more distinct.
  2634. .. code-block:: nim
  2635. # Using only commas
  2636. proc foo(a, b: int, c, d: bool): int
  2637. # Using semicolon for visual distinction
  2638. proc foo(a, b: int; c, d: bool): int
  2639. # Will fail: a is untyped since ';' stops type propagation.
  2640. proc foo(a; b: int; c, d: bool): int
  2641. A parameter may be declared with a default value which is used if the caller
  2642. does not provide a value for the argument. The value will be reevaluated
  2643. every time the function is called.
  2644. .. code-block:: nim
  2645. # b is optional with 47 as its default value.
  2646. proc foo(a: int, b: int = 47): int
  2647. Just as the comma propagates the types from right to left until the
  2648. first parameter or until a semicolon is hit, it also propagates the
  2649. default value starting from the parameter declared with it.
  2650. .. code-block:: nim
  2651. # Both a and b are optional with 47 as their default values.
  2652. proc foo(a, b: int = 47): int
  2653. Parameters can be declared mutable and so allow the proc to modify those
  2654. arguments, by using the type modifier `var`.
  2655. .. code-block:: nim
  2656. # "returning" a value to the caller through the 2nd argument
  2657. # Notice that the function uses no actual return value at all (ie void)
  2658. proc foo(inp: int, outp: var int) =
  2659. outp = inp + 47
  2660. If the proc declaration has no body, it is a `forward`:idx: declaration. If the
  2661. proc returns a value, the procedure body can access an implicitly declared
  2662. variable named `result`:idx: that represents the return value. Procs can be
  2663. overloaded. The overloading resolution algorithm determines which proc is the
  2664. best match for the arguments. Example:
  2665. .. code-block:: nim
  2666. proc toLower(c: char): char = # toLower for characters
  2667. if c in {'A'..'Z'}:
  2668. result = chr(ord(c) + (ord('a') - ord('A')))
  2669. else:
  2670. result = c
  2671. proc toLower(s: string): string = # toLower for strings
  2672. result = newString(len(s))
  2673. for i in 0..len(s) - 1:
  2674. result[i] = toLower(s[i]) # calls toLower for characters; no recursion!
  2675. Calling a procedure can be done in many different ways:
  2676. .. code-block:: nim
  2677. proc callme(x, y: int, s: string = "", c: char, b: bool = false) = ...
  2678. # call with positional arguments # parameter bindings:
  2679. callme(0, 1, "abc", '\t', true) # (x=0, y=1, s="abc", c='\t', b=true)
  2680. # call with named and positional arguments:
  2681. callme(y=1, x=0, "abd", '\t') # (x=0, y=1, s="abd", c='\t', b=false)
  2682. # call with named arguments (order is not relevant):
  2683. callme(c='\t', y=1, x=0) # (x=0, y=1, s="", c='\t', b=false)
  2684. # call as a command statement: no () needed:
  2685. callme 0, 1, "abc", '\t' # (x=0, y=1, s="abc", c='\t', b=false)
  2686. A procedure may call itself recursively.
  2687. `Operators`:idx: are procedures with a special operator symbol as identifier:
  2688. .. code-block:: nim
  2689. proc `$` (x: int): string =
  2690. # converts an integer to a string; this is a prefix operator.
  2691. result = intToStr(x)
  2692. Operators with one parameter are prefix operators, operators with two
  2693. parameters are infix operators. (However, the parser distinguishes these from
  2694. the operator's position within an expression.) There is no way to declare
  2695. postfix operators: all postfix operators are built-in and handled by the
  2696. grammar explicitly.
  2697. Any operator can be called like an ordinary proc with the \`opr\`
  2698. notation. (Thus an operator can have more than two parameters):
  2699. .. code-block:: nim
  2700. proc `*+` (a, b, c: int): int =
  2701. # Multiply and add
  2702. result = a * b + c
  2703. assert `*+`(3, 4, 6) == `+`(`*`(a, b), c)
  2704. Export marker
  2705. -------------
  2706. If a declared symbol is marked with an `asterisk`:idx: it is exported from the
  2707. current module:
  2708. .. code-block:: nim
  2709. proc exportedEcho*(s: string) = echo s
  2710. proc `*`*(a: string; b: int): string =
  2711. result = newStringOfCap(a.len * b)
  2712. for i in 1..b: result.add a
  2713. var exportedVar*: int
  2714. const exportedConst* = 78
  2715. type
  2716. ExportedType* = object
  2717. exportedField*: int
  2718. Method call syntax
  2719. ------------------
  2720. For object-oriented programming, the syntax `obj.methodName(args)` can be used
  2721. instead of `methodName(obj, args)`. The parentheses can be omitted if
  2722. there are no remaining arguments: `obj.len` (instead of `len(obj)`).
  2723. This method call syntax is not restricted to objects, it can be used
  2724. to supply any type of first argument for procedures:
  2725. .. code-block:: nim
  2726. echo "abc".len # is the same as echo len "abc"
  2727. echo "abc".toUpper()
  2728. echo {'a', 'b', 'c'}.card
  2729. stdout.writeLine("Hallo") # the same as writeLine(stdout, "Hallo")
  2730. Another way to look at the method call syntax is that it provides the missing
  2731. postfix notation.
  2732. The method call syntax conflicts with explicit generic instantiations:
  2733. `p[T](x)` cannot be written as `x.p[T]` because `x.p[T]` is always
  2734. parsed as `(x.p)[T]`.
  2735. See also: `Limitations of the method call syntax
  2736. <#templates-limitations-of-the-method-call-syntax>`_.
  2737. The `[: ]` notation has been designed to mitigate this issue: `x.p[:T]`
  2738. is rewritten by the parser to `p[T](x)`, `x.p[:T](y)` is rewritten to
  2739. `p[T](x, y)`. Note that `[: ]` has no AST representation, the rewrite
  2740. is performed directly in the parsing step.
  2741. Properties
  2742. ----------
  2743. Nim has no need for *get-properties*: Ordinary get-procedures that are called
  2744. with the *method call syntax* achieve the same. But setting a value is
  2745. different; for this, a special setter syntax is needed:
  2746. .. code-block:: nim
  2747. # Module asocket
  2748. type
  2749. Socket* = ref object of RootObj
  2750. host: int # cannot be accessed from the outside of the module
  2751. proc `host=`*(s: var Socket, value: int) {.inline.} =
  2752. ## setter of hostAddr.
  2753. ## This accesses the 'host' field and is not a recursive call to
  2754. ## `host=` because the builtin dot access is preferred if it is
  2755. ## available:
  2756. s.host = value
  2757. proc host*(s: Socket): int {.inline.} =
  2758. ## getter of hostAddr
  2759. ## This accesses the 'host' field and is not a recursive call to
  2760. ## `host` because the builtin dot access is preferred if it is
  2761. ## available:
  2762. s.host
  2763. .. code-block:: nim
  2764. # module B
  2765. import asocket
  2766. var s: Socket
  2767. new s
  2768. s.host = 34 # same as `host=`(s, 34)
  2769. A proc defined as `f=` (with the trailing `=`) is called
  2770. a `setter`:idx:. A setter can be called explicitly via the common
  2771. backticks notation:
  2772. .. code-block:: nim
  2773. proc `f=`(x: MyObject; value: string) =
  2774. discard
  2775. `f=`(myObject, "value")
  2776. `f=` can be called implicitly in the pattern
  2777. `x.f = value` if and only if the type of `x` does not have a field
  2778. named `f` or if `f` is not visible in the current module. These rules
  2779. ensure that object fields and accessors can have the same name. Within the
  2780. module `x.f` is then always interpreted as field access and outside the
  2781. module it is interpreted as an accessor proc call.
  2782. Command invocation syntax
  2783. -------------------------
  2784. Routines can be invoked without the `()` if the call is syntactically
  2785. a statement. This command invocation syntax also works for
  2786. expressions, but then only a single argument may follow. This restriction
  2787. means `echo f 1, f 2` is parsed as `echo(f(1), f(2))` and not as
  2788. `echo(f(1, f(2)))`. The method call syntax may be used to provide one
  2789. more argument in this case:
  2790. .. code-block:: nim
  2791. proc optarg(x: int, y: int = 0): int = x + y
  2792. proc singlearg(x: int): int = 20*x
  2793. echo optarg 1, " ", singlearg 2 # prints "1 40"
  2794. let fail = optarg 1, optarg 8 # Wrong. Too many arguments for a command call
  2795. let x = optarg(1, optarg 8) # traditional procedure call with 2 arguments
  2796. let y = 1.optarg optarg 8 # same thing as above, w/o the parenthesis
  2797. assert x == y
  2798. The command invocation syntax also can't have complex expressions as arguments.
  2799. For example: (`anonymous procs <#procedures-anonymous-procs>`_), `if`,
  2800. `case` or `try`. Function calls with no arguments still need () to
  2801. distinguish between a call and the function itself as a first-class value.
  2802. Closures
  2803. --------
  2804. Procedures can appear at the top level in a module as well as inside other
  2805. scopes, in which case they are called nested procs. A nested proc can access
  2806. local variables from its enclosing scope and if it does so it becomes a
  2807. closure. Any captured variables are stored in a hidden additional argument
  2808. to the closure (its environment) and they are accessed by reference by both
  2809. the closure and its enclosing scope (i.e. any modifications made to them are
  2810. visible in both places). The closure environment may be allocated on the heap
  2811. or on the stack if the compiler determines that this would be safe.
  2812. Creating closures in loops
  2813. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  2814. Since closures capture local variables by reference it is often not wanted
  2815. behavior inside loop bodies. See `closureScope
  2816. <system.html#closureScope.t,untyped>`_ and `capture
  2817. <sugar.html#capture.m,varargs[typed],untyped>`_ for details on how to change this behavior.
  2818. Anonymous Procs
  2819. ---------------
  2820. Unnamed procedures can be used as lambda expressions to pass into other
  2821. procedures:
  2822. .. code-block:: nim
  2823. var cities = @["Frankfurt", "Tokyo", "New York", "Kyiv"]
  2824. cities.sort(proc (x,y: string): int =
  2825. cmp(x.len, y.len))
  2826. Procs as expressions can appear both as nested procs and inside top-level
  2827. executable code. The `sugar <sugar.html>`_ module contains the `=>` macro
  2828. which enables a more succinct syntax for anonymous procedures resembling
  2829. lambdas as they are in languages like JavaScript, C#, etc.
  2830. Func
  2831. ----
  2832. The `func` keyword introduces a shortcut for a `noSideEffect`:idx: proc.
  2833. .. code-block:: nim
  2834. func binarySearch[T](a: openArray[T]; elem: T): int
  2835. Is short for:
  2836. .. code-block:: nim
  2837. proc binarySearch[T](a: openArray[T]; elem: T): int {.noSideEffect.}
  2838. Routines
  2839. --------
  2840. A routine is a symbol of kind: `proc`, `func`, `method`, `iterator`, `macro`, `template`, `converter`.
  2841. Type bound operators
  2842. --------------------
  2843. A type bound operator is a `proc` or `func` whose name starts with `=` but isn't an operator
  2844. (i.e. containing only symbols, such as `==`). These are unrelated to setters
  2845. (see `properties <manual.html#procedures-properties>`_), which instead end in `=`.
  2846. A type bound operator declared for a type applies to the type regardless of whether
  2847. the operator is in scope (including if it is private).
  2848. .. code-block:: nim
  2849. # foo.nim:
  2850. var witness* = 0
  2851. type Foo[T] = object
  2852. proc initFoo*(T: typedesc): Foo[T] = discard
  2853. proc `=destroy`[T](x: var Foo[T]) = witness.inc # type bound operator
  2854. # main.nim:
  2855. import foo
  2856. block:
  2857. var a = initFoo(int)
  2858. doAssert witness == 0
  2859. doAssert witness == 1
  2860. block:
  2861. var a = initFoo(int)
  2862. doAssert witness == 1
  2863. `=destroy`(a) # can be called explicitly, even without being in scope
  2864. doAssert witness == 2
  2865. # will still be called upon exiting scope
  2866. doAssert witness == 3
  2867. Type bound operators are:
  2868. `=destroy`, `=copy`, `=sink`, `=trace`, `=deepcopy`.
  2869. For more details on some of those procs, see
  2870. `Lifetime-tracking hooks <destructors.html#lifetimeminustracking-hooks>`_.
  2871. Nonoverloadable builtins
  2872. ------------------------
  2873. The following built-in procs cannot be overloaded for reasons of implementation
  2874. simplicity (they require specialized semantic checking)::
  2875. declared, defined, definedInScope, compiles, sizeof,
  2876. is, shallowCopy, getAst, astToStr, spawn, procCall
  2877. Thus they act more like keywords than like ordinary identifiers; unlike a
  2878. keyword however, a redefinition may `shadow`:idx: the definition in
  2879. the system_ module. From this list the following should not be written in dot
  2880. notation `x.f` since `x` cannot be type-checked before it gets passed
  2881. to `f`::
  2882. declared, defined, definedInScope, compiles, getAst, astToStr
  2883. Var parameters
  2884. --------------
  2885. The type of a parameter may be prefixed with the `var` keyword:
  2886. .. code-block:: nim
  2887. proc divmod(a, b: int; res, remainder: var int) =
  2888. res = a div b
  2889. remainder = a mod b
  2890. var
  2891. x, y: int
  2892. divmod(8, 5, x, y) # modifies x and y
  2893. assert x == 1
  2894. assert y == 3
  2895. In the example, `res` and `remainder` are `var parameters`.
  2896. Var parameters can be modified by the procedure and the changes are
  2897. visible to the caller. The argument passed to a var parameter has to be
  2898. an l-value. Var parameters are implemented as hidden pointers. The
  2899. above example is equivalent to:
  2900. .. code-block:: nim
  2901. proc divmod(a, b: int; res, remainder: ptr int) =
  2902. res[] = a div b
  2903. remainder[] = a mod b
  2904. var
  2905. x, y: int
  2906. divmod(8, 5, addr(x), addr(y))
  2907. assert x == 1
  2908. assert y == 3
  2909. In the examples, var parameters or pointers are used to provide two
  2910. return values. This can be done in a cleaner way by returning a tuple:
  2911. .. code-block:: nim
  2912. proc divmod(a, b: int): tuple[res, remainder: int] =
  2913. (a div b, a mod b)
  2914. var t = divmod(8, 5)
  2915. assert t.res == 1
  2916. assert t.remainder == 3
  2917. One can use `tuple unpacking`:idx: to access the tuple's fields:
  2918. .. code-block:: nim
  2919. var (x, y) = divmod(8, 5) # tuple unpacking
  2920. assert x == 1
  2921. assert y == 3
  2922. **Note**: `var` parameters are never necessary for efficient parameter
  2923. passing. Since non-var parameters cannot be modified the compiler is always
  2924. free to pass arguments by reference if it considers it can speed up execution.
  2925. Var return type
  2926. ---------------
  2927. A proc, converter, or iterator may return a `var` type which means that the
  2928. returned value is an l-value and can be modified by the caller:
  2929. .. code-block:: nim
  2930. var g = 0
  2931. proc writeAccessToG(): var int =
  2932. result = g
  2933. writeAccessToG() = 6
  2934. assert g == 6
  2935. It is a static error if the implicitly introduced pointer could be
  2936. used to access a location beyond its lifetime:
  2937. .. code-block:: nim
  2938. proc writeAccessToG(): var int =
  2939. var g = 0
  2940. result = g # Error!
  2941. For iterators, a component of a tuple return type can have a `var` type too:
  2942. .. code-block:: nim
  2943. iterator mpairs(a: var seq[string]): tuple[key: int, val: var string] =
  2944. for i in 0..a.high:
  2945. yield (i, a[i])
  2946. In the standard library every name of a routine that returns a `var` type
  2947. starts with the prefix `m` per convention.
  2948. .. include:: manual/var_t_return.rst
  2949. Future directions
  2950. ~~~~~~~~~~~~~~~~~
  2951. Later versions of Nim can be more precise about the borrowing rule with
  2952. a syntax like:
  2953. .. code-block:: nim
  2954. proc foo(other: Y; container: var X): var T from container
  2955. Here `var T from container` explicitly exposes that the
  2956. location is derived from the second parameter (called
  2957. 'container' in this case). The syntax `var T from p` specifies a type
  2958. `varTy[T, 2]` which is incompatible with `varTy[T, 1]`.
  2959. NRVO
  2960. ----
  2961. **Note**: This section describes the current implementation. This part
  2962. of the language specification will be changed.
  2963. See https://github.com/nim-lang/RFCs/issues/230 for more information.
  2964. The return value is represented inside the body of a routine as the special
  2965. `result`:idx: variable. This allows for a mechanism much like C++'s
  2966. "named return value optimization" (`NRVO`:idx:). NRVO means that the stores
  2967. to `result` inside `p` directly affect the destination `dest`
  2968. in `let/var dest = p(args)` (definition of `dest`) and also in `dest = p(args)`
  2969. (assignment to `dest`). This is achieved by rewriting `dest = p(args)`
  2970. to `p'(args, dest)` where `p'` is a variation of `p` that returns `void` and
  2971. receives a hidden mutable parameter representing `result`.
  2972. Informally:
  2973. .. code-block:: nim
  2974. proc p(): BigT = ...
  2975. var x = p()
  2976. x = p()
  2977. # is roughly turned into:
  2978. proc p(result: var BigT) = ...
  2979. var x; p(x)
  2980. p(x)
  2981. Let `T`'s be `p`'s return type. NRVO applies for `T`
  2982. if `sizeof(T) >= N` (where `N` is implementation dependent),
  2983. in other words, it applies for "big" structures.
  2984. If `p` can raise an exception, NRVO applies regardless. This can produce
  2985. observable differences in behavior:
  2986. .. code-block:: nim
  2987. type
  2988. BigT = array[16, int]
  2989. proc p(raiseAt: int): BigT =
  2990. for i in 0..high(result):
  2991. if i == raiseAt: raise newException(ValueError, "interception")
  2992. result[i] = i
  2993. proc main =
  2994. var x: BigT
  2995. try:
  2996. x = p(8)
  2997. except ValueError:
  2998. doAssert x == [0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0]
  2999. main()
  3000. However, the current implementation produces a warning in these cases.
  3001. There are different ways to deal with this warning:
  3002. 1. Disable the warning via `{.push warning[ObservableStores]: off.}` ... `{.pop.}`.
  3003. Then one may need to ensure that `p` only raises *before* any stores to `result`
  3004. happen.
  3005. 2. One can use a temporary helper variable, for example instead of `x = p(8)`
  3006. use `let tmp = p(8); x = tmp`.
  3007. Overloading of the subscript operator
  3008. -------------------------------------
  3009. The `[]` subscript operator for arrays/openarrays/sequences can be overloaded.
  3010. Methods
  3011. =============
  3012. Procedures always use static dispatch. Methods use dynamic
  3013. dispatch. For dynamic dispatch to work on an object it should be a reference
  3014. type.
  3015. .. code-block:: nim
  3016. type
  3017. Expression = ref object of RootObj ## abstract base class for an expression
  3018. Literal = ref object of Expression
  3019. x: int
  3020. PlusExpr = ref object of Expression
  3021. a, b: Expression
  3022. method eval(e: Expression): int {.base.} =
  3023. # override this base method
  3024. raise newException(CatchableError, "Method without implementation override")
  3025. method eval(e: Literal): int = return e.x
  3026. method eval(e: PlusExpr): int =
  3027. # watch out: relies on dynamic binding
  3028. result = eval(e.a) + eval(e.b)
  3029. proc newLit(x: int): Literal =
  3030. new(result)
  3031. result.x = x
  3032. proc newPlus(a, b: Expression): PlusExpr =
  3033. new(result)
  3034. result.a = a
  3035. result.b = b
  3036. echo eval(newPlus(newPlus(newLit(1), newLit(2)), newLit(4)))
  3037. In the example the constructors `newLit` and `newPlus` are procs
  3038. because they should use static binding, but `eval` is a method because it
  3039. requires dynamic binding.
  3040. As can be seen in the example, base methods have to be annotated with
  3041. the `base`:idx: pragma. The `base` pragma also acts as a reminder for the
  3042. programmer that a base method `m` is used as the foundation to determine all
  3043. the effects that a call to `m` might cause.
  3044. **Note**: Compile-time execution is not (yet) supported for methods.
  3045. **Note**: Starting from Nim 0.20, generic methods are deprecated.
  3046. Multi-methods
  3047. --------------
  3048. **Note:** Starting from Nim 0.20, to use multi-methods one must explicitly pass
  3049. `--multimethods:on`:option: when compiling.
  3050. In a multi-method, all parameters that have an object type are used for the
  3051. dispatching:
  3052. .. code-block:: nim
  3053. :test: "nim c --multiMethods:on $1"
  3054. type
  3055. Thing = ref object of RootObj
  3056. Unit = ref object of Thing
  3057. x: int
  3058. method collide(a, b: Thing) {.inline.} =
  3059. quit "to override!"
  3060. method collide(a: Thing, b: Unit) {.inline.} =
  3061. echo "1"
  3062. method collide(a: Unit, b: Thing) {.inline.} =
  3063. echo "2"
  3064. var a, b: Unit
  3065. new a
  3066. new b
  3067. collide(a, b) # output: 2
  3068. Inhibit dynamic method resolution via procCall
  3069. -----------------------------------------------
  3070. Dynamic method resolution can be inhibited via the builtin `system.procCall`:idx:.
  3071. This is somewhat comparable to the `super`:idx: keyword that traditional OOP
  3072. languages offer.
  3073. .. code-block:: nim
  3074. :test: "nim c $1"
  3075. type
  3076. Thing = ref object of RootObj
  3077. Unit = ref object of Thing
  3078. x: int
  3079. method m(a: Thing) {.base.} =
  3080. echo "base"
  3081. method m(a: Unit) =
  3082. # Call the base method:
  3083. procCall m(Thing(a))
  3084. echo "1"
  3085. Iterators and the for statement
  3086. ===============================
  3087. The `for`:idx: statement is an abstract mechanism to iterate over the elements
  3088. of a container. It relies on an `iterator`:idx: to do so. Like `while`
  3089. statements, `for` statements open an `implicit block`:idx: so that they
  3090. can be left with a `break` statement.
  3091. The `for` loop declares iteration variables - their scope reaches until the
  3092. end of the loop body. The iteration variables' types are inferred by the
  3093. return type of the iterator.
  3094. An iterator is similar to a procedure, except that it can be called in the
  3095. context of a `for` loop. Iterators provide a way to specify the iteration over
  3096. an abstract type. The `yield` statement in the called iterator plays a key
  3097. role in the execution of a `for` loop. Whenever a `yield` statement is
  3098. reached, the data is bound to the `for` loop variables and control continues
  3099. in the body of the `for` loop. The iterator's local variables and execution
  3100. state are automatically saved between calls. Example:
  3101. .. code-block:: nim
  3102. # this definition exists in the system module
  3103. iterator items*(a: string): char {.inline.} =
  3104. var i = 0
  3105. while i < len(a):
  3106. yield a[i]
  3107. inc(i)
  3108. for ch in items("hello world"): # `ch` is an iteration variable
  3109. echo ch
  3110. The compiler generates code as if the programmer would have written this:
  3111. .. code-block:: nim
  3112. var i = 0
  3113. while i < len(a):
  3114. var ch = a[i]
  3115. echo ch
  3116. inc(i)
  3117. If the iterator yields a tuple, there can be as many iteration variables
  3118. as there are components in the tuple. The i'th iteration variable's type is
  3119. the type of the i'th component. In other words, implicit tuple unpacking in a
  3120. for loop context is supported.
  3121. Implicit items/pairs invocations
  3122. --------------------------------
  3123. If the for loop expression `e` does not denote an iterator and the for loop
  3124. has exactly 1 variable, the for loop expression is rewritten to `items(e)`;
  3125. ie. an `items` iterator is implicitly invoked:
  3126. .. code-block:: nim
  3127. for x in [1,2,3]: echo x
  3128. If the for loop has exactly 2 variables, a `pairs` iterator is implicitly
  3129. invoked.
  3130. Symbol lookup of the identifiers `items`/`pairs` is performed after
  3131. the rewriting step, so that all overloads of `items`/`pairs` are taken
  3132. into account.
  3133. First-class iterators
  3134. ---------------------
  3135. There are 2 kinds of iterators in Nim: *inline* and *closure* iterators.
  3136. An `inline iterator`:idx: is an iterator that's always inlined by the compiler
  3137. leading to zero overhead for the abstraction, but may result in a heavy
  3138. increase in code size.
  3139. Caution: the body of a for loop over an inline iterator is inlined into
  3140. each `yield` statement appearing in the iterator code,
  3141. so ideally the code should be refactored to contain a single yield when possible
  3142. to avoid code bloat.
  3143. Inline iterators are second class citizens;
  3144. They can be passed as parameters only to other inlining code facilities like
  3145. templates, macros, and other inline iterators.
  3146. In contrast to that, a `closure iterator`:idx: can be passed around more freely:
  3147. .. code-block:: nim
  3148. iterator count0(): int {.closure.} =
  3149. yield 0
  3150. iterator count2(): int {.closure.} =
  3151. var x = 1
  3152. yield x
  3153. inc x
  3154. yield x
  3155. proc invoke(iter: iterator(): int {.closure.}) =
  3156. for x in iter(): echo x
  3157. invoke(count0)
  3158. invoke(count2)
  3159. Closure iterators and inline iterators have some restrictions:
  3160. 1. For now, a closure iterator cannot be executed at compile time.
  3161. 2. `return` is allowed in a closure iterator but not in an inline iterator
  3162. (but rarely useful) and ends the iteration.
  3163. 3. Neither inline nor closure iterators can be (directly)* recursive.
  3164. 4. Neither inline nor closure iterators have the special `result` variable.
  3165. 5. Closure iterators are not supported by the JS backend.
  3166. (*) Closure iterators can be co-recursive with a factory proc which results
  3167. in similar syntax to a recursive iterator. More details follow.
  3168. Iterators that are neither marked `{.closure.}` nor `{.inline.}` explicitly
  3169. default to being inline, but this may change in future versions of the
  3170. implementation.
  3171. The `iterator` type is always of the calling convention `closure`
  3172. implicitly; the following example shows how to use iterators to implement
  3173. a `collaborative tasking`:idx: system:
  3174. .. code-block:: nim
  3175. # simple tasking:
  3176. type
  3177. Task = iterator (ticker: int)
  3178. iterator a1(ticker: int) {.closure.} =
  3179. echo "a1: A"
  3180. yield
  3181. echo "a1: B"
  3182. yield
  3183. echo "a1: C"
  3184. yield
  3185. echo "a1: D"
  3186. iterator a2(ticker: int) {.closure.} =
  3187. echo "a2: A"
  3188. yield
  3189. echo "a2: B"
  3190. yield
  3191. echo "a2: C"
  3192. proc runTasks(t: varargs[Task]) =
  3193. var ticker = 0
  3194. while true:
  3195. let x = t[ticker mod t.len]
  3196. if finished(x): break
  3197. x(ticker)
  3198. inc ticker
  3199. runTasks(a1, a2)
  3200. The builtin `system.finished` can be used to determine if an iterator has
  3201. finished its operation; no exception is raised on an attempt to invoke an
  3202. iterator that has already finished its work.
  3203. Note that `system.finished` is error prone to use because it only returns
  3204. `true` one iteration after the iterator has finished:
  3205. .. code-block:: nim
  3206. iterator mycount(a, b: int): int {.closure.} =
  3207. var x = a
  3208. while x <= b:
  3209. yield x
  3210. inc x
  3211. var c = mycount # instantiate the iterator
  3212. while not finished(c):
  3213. echo c(1, 3)
  3214. # Produces
  3215. 1
  3216. 2
  3217. 3
  3218. 0
  3219. Instead this code has to be used:
  3220. .. code-block:: nim
  3221. var c = mycount # instantiate the iterator
  3222. while true:
  3223. let value = c(1, 3)
  3224. if finished(c): break # and discard 'value'!
  3225. echo value
  3226. It helps to think that the iterator actually returns a
  3227. pair `(value, done)` and `finished` is used to access the hidden `done`
  3228. field.
  3229. Closure iterators are *resumable functions* and so one has to provide the
  3230. arguments to every call. To get around this limitation one can capture
  3231. parameters of an outer factory proc:
  3232. .. code-block:: nim
  3233. proc mycount(a, b: int): iterator (): int =
  3234. result = iterator (): int =
  3235. var x = a
  3236. while x <= b:
  3237. yield x
  3238. inc x
  3239. let foo = mycount(1, 4)
  3240. for f in foo():
  3241. echo f
  3242. The call can be made more like an inline iterator with a for loop macro:
  3243. .. code-block:: nim
  3244. import std/macros
  3245. macro toItr(x: ForLoopStmt): untyped =
  3246. let expr = x[0]
  3247. let call = x[1][1] # Get foo out of toItr(foo)
  3248. let body = x[2]
  3249. result = quote do:
  3250. block:
  3251. let itr = `call`
  3252. for `expr` in itr():
  3253. `body`
  3254. for f in toItr(mycount(1, 4)): # using early `proc mycount`
  3255. echo f
  3256. Because of full backend function call aparatus involvment, closure iterator
  3257. invocation is typically higher cost than inline iterators. Adornment by
  3258. a macro wrapper at the call site like this is a possibly useful reminder.
  3259. The factory `proc`, as an ordinary procedure, can be recursive. The
  3260. above macro allows such recursion to look much like a recursive iterator
  3261. would. For example:
  3262. .. code-block:: nim
  3263. proc recCountDown(n: int): iterator(): int =
  3264. result = iterator(): int =
  3265. if n > 0:
  3266. yield n
  3267. for e in toItr(recCountDown(n - 1)):
  3268. yield e
  3269. for i in toItr(recCountDown(6)): # Emits: 6 5 4 3 2 1
  3270. echo i
  3271. See also see `iterable <#overloading-resolution-iterable>`_ for passing iterators to templates and macros.
  3272. Converters
  3273. ==========
  3274. A converter is like an ordinary proc except that it enhances
  3275. the "implicitly convertible" type relation (see `Convertible relation`_):
  3276. .. code-block:: nim
  3277. # bad style ahead: Nim is not C.
  3278. converter toBool(x: int): bool = x != 0
  3279. if 4:
  3280. echo "compiles"
  3281. A converter can also be explicitly invoked for improved readability. Note that
  3282. implicit converter chaining is not supported: If there is a converter from
  3283. type A to type B and from type B to type C the implicit conversion from A to C
  3284. is not provided.
  3285. Type sections
  3286. =============
  3287. Example:
  3288. .. code-block:: nim
  3289. type # example demonstrating mutually recursive types
  3290. Node = ref object # an object managed by the garbage collector (ref)
  3291. le, ri: Node # left and right subtrees
  3292. sym: ref Sym # leaves contain a reference to a Sym
  3293. Sym = object # a symbol
  3294. name: string # the symbol's name
  3295. line: int # the line the symbol was declared in
  3296. code: Node # the symbol's abstract syntax tree
  3297. A type section begins with the `type` keyword. It contains multiple
  3298. type definitions. A type definition binds a type to a name. Type definitions
  3299. can be recursive or even mutually recursive. Mutually recursive types are only
  3300. possible within a single `type` section. Nominal types like `objects`
  3301. or `enums` can only be defined in a `type` section.
  3302. Exception handling
  3303. ==================
  3304. Try statement
  3305. -------------
  3306. Example:
  3307. .. code-block:: nim
  3308. # read the first two lines of a text file that should contain numbers
  3309. # and tries to add them
  3310. var
  3311. f: File
  3312. if open(f, "numbers.txt"):
  3313. try:
  3314. var a = readLine(f)
  3315. var b = readLine(f)
  3316. echo "sum: " & $(parseInt(a) + parseInt(b))
  3317. except OverflowDefect:
  3318. echo "overflow!"
  3319. except ValueError, IOError:
  3320. echo "catch multiple exceptions!"
  3321. except:
  3322. echo "Unknown exception!"
  3323. finally:
  3324. close(f)
  3325. The statements after the `try` are executed in sequential order unless
  3326. an exception `e` is raised. If the exception type of `e` matches any
  3327. listed in an `except` clause, the corresponding statements are executed.
  3328. The statements following the `except` clauses are called
  3329. `exception handlers`:idx:.
  3330. The empty `except`:idx: clause is executed if there is an exception that is
  3331. not listed otherwise. It is similar to an `else` clause in `if` statements.
  3332. If there is a `finally`:idx: clause, it is always executed after the
  3333. exception handlers.
  3334. The exception is *consumed* in an exception handler. However, an
  3335. exception handler may raise another exception. If the exception is not
  3336. handled, it is propagated through the call stack. This means that often
  3337. the rest of the procedure - that is not within a `finally` clause -
  3338. is not executed (if an exception occurs).
  3339. Try expression
  3340. --------------
  3341. Try can also be used as an expression; the type of the `try` branch then
  3342. needs to fit the types of `except` branches, but the type of the `finally`
  3343. branch always has to be `void`:
  3344. .. code-block:: nim
  3345. from std/strutils import parseInt
  3346. let x = try: parseInt("133a")
  3347. except: -1
  3348. finally: echo "hi"
  3349. To prevent confusing code there is a parsing limitation; if the `try`
  3350. follows a `(` it has to be written as a one liner:
  3351. .. code-block:: nim
  3352. let x = (try: parseInt("133a") except: -1)
  3353. Except clauses
  3354. --------------
  3355. Within an `except` clause it is possible to access the current exception
  3356. using the following syntax:
  3357. .. code-block:: nim
  3358. try:
  3359. # ...
  3360. except IOError as e:
  3361. # Now use "e"
  3362. echo "I/O error: " & e.msg
  3363. Alternatively, it is possible to use `getCurrentException` to retrieve the
  3364. exception that has been raised:
  3365. .. code-block:: nim
  3366. try:
  3367. # ...
  3368. except IOError:
  3369. let e = getCurrentException()
  3370. # Now use "e"
  3371. Note that `getCurrentException` always returns a `ref Exception`
  3372. type. If a variable of the proper type is needed (in the example
  3373. above, `IOError`), one must convert it explicitly:
  3374. .. code-block:: nim
  3375. try:
  3376. # ...
  3377. except IOError:
  3378. let e = (ref IOError)(getCurrentException())
  3379. # "e" is now of the proper type
  3380. However, this is seldom needed. The most common case is to extract an
  3381. error message from `e`, and for such situations, it is enough to use
  3382. `getCurrentExceptionMsg`:
  3383. .. code-block:: nim
  3384. try:
  3385. # ...
  3386. except:
  3387. echo getCurrentExceptionMsg()
  3388. Custom exceptions
  3389. -----------------
  3390. It is possible to create custom exceptions. A custom exception is a custom type:
  3391. .. code-block:: nim
  3392. type
  3393. LoadError* = object of Exception
  3394. Ending the custom exception's name with `Error` is recommended.
  3395. Custom exceptions can be raised just like any other exception, e.g.:
  3396. .. code-block:: nim
  3397. raise newException(LoadError, "Failed to load data")
  3398. Defer statement
  3399. ---------------
  3400. Instead of a `try finally` statement a `defer` statement can be used, which
  3401. avoids lexical nesting and offers more flexibility in terms of scoping as shown
  3402. below.
  3403. Any statements following the `defer` in the current block will be considered
  3404. to be in an implicit try block:
  3405. .. code-block:: nim
  3406. :test: "nim c $1"
  3407. proc main =
  3408. var f = open("numbers.txt", fmWrite)
  3409. defer: close(f)
  3410. f.write "abc"
  3411. f.write "def"
  3412. Is rewritten to:
  3413. .. code-block:: nim
  3414. :test: "nim c $1"
  3415. proc main =
  3416. var f = open("numbers.txt")
  3417. try:
  3418. f.write "abc"
  3419. f.write "def"
  3420. finally:
  3421. close(f)
  3422. When `defer` is at the outermost scope of a template/macro, its scope extends
  3423. to the block where the template is called from:
  3424. .. code-block:: nim
  3425. :test: "nim c $1"
  3426. template safeOpenDefer(f, path) =
  3427. var f = open(path, fmWrite)
  3428. defer: close(f)
  3429. template safeOpenFinally(f, path, body) =
  3430. var f = open(path, fmWrite)
  3431. try: body # without `defer`, `body` must be specified as parameter
  3432. finally: close(f)
  3433. block:
  3434. safeOpenDefer(f, "/tmp/z01.txt")
  3435. f.write "abc"
  3436. block:
  3437. safeOpenFinally(f, "/tmp/z01.txt"):
  3438. f.write "abc" # adds a lexical scope
  3439. block:
  3440. var f = open("/tmp/z01.txt", fmWrite)
  3441. try:
  3442. f.write "abc" # adds a lexical scope
  3443. finally: close(f)
  3444. Top-level `defer` statements are not supported
  3445. since it's unclear what such a statement should refer to.
  3446. Raise statement
  3447. ---------------
  3448. Example:
  3449. .. code-block:: nim
  3450. raise newException(IOError, "IO failed")
  3451. Apart from built-in operations like array indexing, memory allocation, etc.
  3452. the `raise` statement is the only way to raise an exception.
  3453. .. XXX document this better!
  3454. If no exception name is given, the current exception is `re-raised`:idx:. The
  3455. `ReraiseDefect`:idx: exception is raised if there is no exception to
  3456. re-raise. It follows that the `raise` statement *always* raises an
  3457. exception.
  3458. Exception hierarchy
  3459. -------------------
  3460. The exception tree is defined in the `system <system.html>`_ module.
  3461. Every exception inherits from `system.Exception`. Exceptions that indicate
  3462. programming bugs inherit from `system.Defect` (which is a subtype of `Exception`)
  3463. and are strictly speaking not catchable as they can also be mapped to an operation
  3464. that terminates the whole process. If panics are turned into exceptions, these
  3465. exceptions inherit from `Defect`.
  3466. Exceptions that indicate any other runtime error that can be caught inherit from
  3467. `system.CatchableError` (which is a subtype of `Exception`).
  3468. Imported exceptions
  3469. -------------------
  3470. It is possible to raise/catch imported C++ exceptions. Types imported using
  3471. `importcpp` can be raised or caught. Exceptions are raised by value and
  3472. caught by reference. Example:
  3473. .. code-block:: nim
  3474. :test: "nim cpp -r $1"
  3475. type
  3476. CStdException {.importcpp: "std::exception", header: "<exception>", inheritable.} = object
  3477. ## does not inherit from `RootObj`, so we use `inheritable` instead
  3478. CRuntimeError {.requiresInit, importcpp: "std::runtime_error", header: "<stdexcept>".} = object of CStdException
  3479. ## `CRuntimeError` has no default constructor => `requiresInit`
  3480. proc what(s: CStdException): cstring {.importcpp: "((char *)#.what())".}
  3481. proc initRuntimeError(a: cstring): CRuntimeError {.importcpp: "std::runtime_error(@)", constructor.}
  3482. proc initStdException(): CStdException {.importcpp: "std::exception()", constructor.}
  3483. proc fn() =
  3484. let a = initRuntimeError("foo")
  3485. doAssert $a.what == "foo"
  3486. var b: cstring
  3487. try: raise initRuntimeError("foo2")
  3488. except CStdException as e:
  3489. doAssert e is CStdException
  3490. b = e.what()
  3491. doAssert $b == "foo2"
  3492. try: raise initStdException()
  3493. except CStdException: discard
  3494. try: raise initRuntimeError("foo3")
  3495. except CRuntimeError as e:
  3496. b = e.what()
  3497. except CStdException:
  3498. doAssert false
  3499. doAssert $b == "foo3"
  3500. fn()
  3501. **Note:** `getCurrentException()` and `getCurrentExceptionMsg()` are not available
  3502. for imported exceptions from C++. One needs to use the `except ImportedException as x:` syntax
  3503. and rely on functionality of the `x` object to get exception details.
  3504. Effect system
  3505. =============
  3506. **Note**: The rules for effect tracking changed with the release of version
  3507. 1.6 of the Nim compiler. This section describes the new rules that are activated
  3508. via `--experimental:strictEffects`.
  3509. Exception tracking
  3510. ------------------
  3511. Nim supports exception tracking. The `raises`:idx: pragma can be used
  3512. to explicitly define which exceptions a proc/iterator/method/converter is
  3513. allowed to raise. The compiler verifies this:
  3514. .. code-block:: nim
  3515. :test: "nim c $1"
  3516. proc p(what: bool) {.raises: [IOError, OSError].} =
  3517. if what: raise newException(IOError, "IO")
  3518. else: raise newException(OSError, "OS")
  3519. An empty `raises` list (`raises: []`) means that no exception may be raised:
  3520. .. code-block:: nim
  3521. proc p(): bool {.raises: [].} =
  3522. try:
  3523. unsafeCall()
  3524. result = true
  3525. except:
  3526. result = false
  3527. A `raises` list can also be attached to a proc type. This affects type
  3528. compatibility:
  3529. .. code-block:: nim
  3530. :test: "nim c $1"
  3531. :status: 1
  3532. type
  3533. Callback = proc (s: string) {.raises: [IOError].}
  3534. var
  3535. c: Callback
  3536. proc p(x: string) =
  3537. raise newException(OSError, "OS")
  3538. c = p # type error
  3539. For a routine `p`, the compiler uses inference rules to determine the set of
  3540. possibly raised exceptions; the algorithm operates on `p`'s call graph:
  3541. 1. Every indirect call via some proc type `T` is assumed to
  3542. raise `system.Exception` (the base type of the exception hierarchy) and
  3543. thus any exception unless `T` has an explicit `raises` list.
  3544. However, if the call is of the form `f(...)` where `f` is a parameter of
  3545. the currently analyzed routine it is ignored that is marked as `.effectsOf: f`.
  3546. The call is optimistically assumed to have no effect.
  3547. Rule 2 compensates for this case.
  3548. 2. Every expression `e` of some proc type within a call that is passed to parameter
  3549. marked as `.effectsOf` is assumed to be called indirectly and thus
  3550. its raises list is added to `p`'s raises list.
  3551. 3. Every call to a proc `q` which has an unknown body (due to a forward
  3552. declaration) is assumed to
  3553. raise `system.Exception` unless `q` has an explicit `raises` list.
  3554. Procs that are `importc`'ed are assumed to have `.raises: []`, unless explicitly
  3555. declared otherwise.
  3556. 4. Every call to a method `m` is assumed to
  3557. raise `system.Exception` unless `m` has an explicit `raises` list.
  3558. 5. For every other call, the analysis can determine an exact `raises` list.
  3559. 6. For determining a `raises` list, the `raise` and `try` statements
  3560. of `p` are taken into consideration.
  3561. Exceptions inheriting from `system.Defect` are not tracked with
  3562. the `.raises: []` exception tracking mechanism. This is more consistent with the
  3563. built-in operations. The following code is valid:
  3564. .. code-block:: nim
  3565. proc mydiv(a, b): int {.raises: [].} =
  3566. a div b # can raise an DivByZeroDefect
  3567. And so is:
  3568. .. code-block:: nim
  3569. proc mydiv(a, b): int {.raises: [].} =
  3570. if b == 0: raise newException(DivByZeroDefect, "division by zero")
  3571. else: result = a div b
  3572. The reason for this is that `DivByZeroDefect` inherits from `Defect` and
  3573. with `--panics:on`:option: Defects become unrecoverable errors.
  3574. (Since version 1.4 of the language.)
  3575. EffectsOf annotation
  3576. --------------------
  3577. Rules 1-2 of the exception tracking inference rules (see the previous section)
  3578. ensure the following works:
  3579. .. code-block:: nim
  3580. proc weDontRaiseButMaybeTheCallback(callback: proc()) {.raises: [], effectsOf: callback.} =
  3581. callback()
  3582. proc doRaise() {.raises: [IOError].} =
  3583. raise newException(IOError, "IO")
  3584. proc use() {.raises: [].} =
  3585. # doesn't compile! Can raise IOError!
  3586. weDontRaiseButMaybeTheCallback(doRaise)
  3587. As can be seen from the example, a parameter of type `proc (...)` can be
  3588. annotated as `.effectsOf`. Such a parameter allows for effect polymorphism:
  3589. The proc `weDontRaiseButMaybeTheCallback` raises the exceptions
  3590. that `callback` raises.
  3591. So in many cases a callback does not cause the compiler to be overly
  3592. conservative in its effect analysis:
  3593. .. code-block:: nim
  3594. :test: "nim c $1"
  3595. :status: 1
  3596. {.push warningAsError[Effect]: on.}
  3597. {.experimental: "strictEffects".}
  3598. import algorithm
  3599. type
  3600. MyInt = distinct int
  3601. var toSort = @[MyInt 1, MyInt 2, MyInt 3]
  3602. proc cmpN(a, b: MyInt): int =
  3603. cmp(a.int, b.int)
  3604. proc harmless {.raises: [].} =
  3605. toSort.sort cmpN
  3606. proc cmpE(a, b: MyInt): int {.raises: [Exception].} =
  3607. cmp(a.int, b.int)
  3608. proc harmfull {.raises: [].} =
  3609. # does not compile, `sort` can now raise Exception
  3610. toSort.sort cmpE
  3611. Tag tracking
  3612. ------------
  3613. Exception tracking is part of Nim's `effect system`:idx:. Raising an exception
  3614. is an *effect*. Other effects can also be defined. A user defined effect is a
  3615. means to *tag* a routine and to perform checks against this tag:
  3616. .. code-block:: nim
  3617. :test: "nim c --warningAsError:Effect:on $1"
  3618. :status: 1
  3619. type IO = object ## input/output effect
  3620. proc readLine(): string {.tags: [IO].} = discard
  3621. proc no_IO_please() {.tags: [].} =
  3622. # the compiler prevents this:
  3623. let x = readLine()
  3624. A tag has to be a type name. A `tags` list - like a `raises` list - can
  3625. also be attached to a proc type. This affects type compatibility.
  3626. The inference for tag tracking is analogous to the inference for
  3627. exception tracking.
  3628. Side effects
  3629. ------------
  3630. The `noSideEffect` pragma is used to mark a proc/iterator that can have only
  3631. side effects through parameters. This means that the proc/iterator only changes locations that are
  3632. reachable from its parameters and the return value only depends on the
  3633. parameters. If none of its parameters have the type `var`, `ref`, `ptr`, `cstring`, or `proc`,
  3634. then no locations are modified.
  3635. In other words, a routine has no side effects if it does not access a threadlocal
  3636. or global variable and it does not call any routine that has a side effect.
  3637. It is a static error to mark a proc/iterator to have no side effect if the compiler cannot verify this.
  3638. As a special semantic rule, the built-in `debugEcho
  3639. <system.html#debugEcho,varargs[typed,]>`_ pretends to be free of side effects
  3640. so that it can be used for debugging routines marked as `noSideEffect`.
  3641. `func` is syntactic sugar for a proc with no side effects:
  3642. .. code-block:: nim
  3643. func `+` (x, y: int): int
  3644. To override the compiler's side effect analysis a `{.noSideEffect.}`
  3645. `cast` pragma block can be used:
  3646. .. code-block:: nim
  3647. func f() =
  3648. {.cast(noSideEffect).}:
  3649. echo "test"
  3650. **Side effects are usually inferred. The inference for side effects is
  3651. analogous to the inference for exception tracking.**
  3652. GC safety effect
  3653. ----------------
  3654. We call a proc `p` `GC safe`:idx: when it doesn't access any global variable
  3655. that contains GC'ed memory (`string`, `seq`, `ref` or a closure) either
  3656. directly or indirectly through a call to a GC unsafe proc.
  3657. **The GC safety property is usually inferred. The inference for GC safety is
  3658. analogous to the inference for exception tracking.**
  3659. The `gcsafe`:idx: annotation can be used to mark a proc to be gcsafe,
  3660. otherwise this property is inferred by the compiler. Note that `noSideEffect`
  3661. implies `gcsafe`.
  3662. Routines that are imported from C are always assumed to be `gcsafe`.
  3663. To override the compiler's gcsafety analysis a `{.cast(gcsafe).}` pragma block can
  3664. be used:
  3665. .. code-block:: nim
  3666. var
  3667. someGlobal: string = "some string here"
  3668. perThread {.threadvar.}: string
  3669. proc setPerThread() =
  3670. {.cast(gcsafe).}:
  3671. deepCopy(perThread, someGlobal)
  3672. See also:
  3673. - `Shared heap memory management <gc.html>`_.
  3674. Effects pragma
  3675. --------------
  3676. The `effects` pragma has been designed to assist the programmer with the
  3677. effects analysis. It is a statement that makes the compiler output all inferred
  3678. effects up to the `effects`'s position:
  3679. .. code-block:: nim
  3680. proc p(what: bool) =
  3681. if what:
  3682. raise newException(IOError, "IO")
  3683. {.effects.}
  3684. else:
  3685. raise newException(OSError, "OS")
  3686. The compiler produces a hint message that `IOError` can be raised. `OSError`
  3687. is not listed as it cannot be raised in the branch the `effects` pragma
  3688. appears in.
  3689. Generics
  3690. ========
  3691. Generics are Nim's means to parametrize procs, iterators or types with
  3692. `type parameters`:idx:. Depending on the context, the brackets are used either to
  3693. introduce type parameters or to instantiate a generic proc, iterator, or type.
  3694. The following example shows how a generic binary tree can be modeled:
  3695. .. code-block:: nim
  3696. :test: "nim c $1"
  3697. type
  3698. BinaryTree*[T] = ref object # BinaryTree is a generic type with
  3699. # generic param `T`
  3700. le, ri: BinaryTree[T] # left and right subtrees; may be nil
  3701. data: T # the data stored in a node
  3702. proc newNode*[T](data: T): BinaryTree[T] =
  3703. # constructor for a node
  3704. result = BinaryTree[T](le: nil, ri: nil, data: data)
  3705. proc add*[T](root: var BinaryTree[T], n: BinaryTree[T]) =
  3706. # insert a node into the tree
  3707. if root == nil:
  3708. root = n
  3709. else:
  3710. var it = root
  3711. while it != nil:
  3712. # compare the data items; uses the generic `cmp` proc
  3713. # that works for any type that has a `==` and `<` operator
  3714. var c = cmp(it.data, n.data)
  3715. if c < 0:
  3716. if it.le == nil:
  3717. it.le = n
  3718. return
  3719. it = it.le
  3720. else:
  3721. if it.ri == nil:
  3722. it.ri = n
  3723. return
  3724. it = it.ri
  3725. proc add*[T](root: var BinaryTree[T], data: T) =
  3726. # convenience proc:
  3727. add(root, newNode(data))
  3728. iterator preorder*[T](root: BinaryTree[T]): T =
  3729. # Preorder traversal of a binary tree.
  3730. # This uses an explicit stack (which is more efficient than
  3731. # a recursive iterator factory).
  3732. var stack: seq[BinaryTree[T]] = @[root]
  3733. while stack.len > 0:
  3734. var n = stack.pop()
  3735. while n != nil:
  3736. yield n.data
  3737. add(stack, n.ri) # push right subtree onto the stack
  3738. n = n.le # and follow the left pointer
  3739. var
  3740. root: BinaryTree[string] # instantiate a BinaryTree with `string`
  3741. add(root, newNode("hello")) # instantiates `newNode` and `add`
  3742. add(root, "world") # instantiates the second `add` proc
  3743. for str in preorder(root):
  3744. stdout.writeLine(str)
  3745. The `T` is called a `generic type parameter`:idx: or
  3746. a `type variable`:idx:.
  3747. Is operator
  3748. -----------
  3749. The `is` operator is evaluated during semantic analysis to check for type
  3750. equivalence. It is therefore very useful for type specialization within generic
  3751. code:
  3752. .. code-block:: nim
  3753. type
  3754. Table[Key, Value] = object
  3755. keys: seq[Key]
  3756. values: seq[Value]
  3757. when not (Key is string): # empty value for strings used for optimization
  3758. deletedKeys: seq[bool]
  3759. Type Classes
  3760. ------------
  3761. A type class is a special pseudo-type that can be used to match against
  3762. types in the context of overload resolution or the `is` operator.
  3763. Nim supports the following built-in type classes:
  3764. ================== ===================================================
  3765. type class matches
  3766. ================== ===================================================
  3767. `object` any object type
  3768. `tuple` any tuple type
  3769. `enum` any enumeration
  3770. `proc` any proc type
  3771. `ref` any `ref` type
  3772. `ptr` any `ptr` type
  3773. `var` any `var` type
  3774. `distinct` any distinct type
  3775. `array` any array type
  3776. `set` any set type
  3777. `seq` any seq type
  3778. `auto` any type
  3779. ================== ===================================================
  3780. Furthermore, every generic type automatically creates a type class of the same
  3781. name that will match any instantiation of the generic type.
  3782. Type classes can be combined using the standard boolean operators to form
  3783. more complex type classes:
  3784. .. code-block:: nim
  3785. # create a type class that will match all tuple and object types
  3786. type RecordType = tuple or object
  3787. proc printFields[T: RecordType](rec: T) =
  3788. for key, value in fieldPairs(rec):
  3789. echo key, " = ", value
  3790. Type constraints on generic parameters can be grouped with `,` and propagation
  3791. stops with `;`, similarly to parameters for macros and templates:
  3792. .. code-block:: nim
  3793. proc fn1[T; U, V: SomeFloat]() = discard # T is unconstrained
  3794. template fn2(t; u, v: SomeFloat) = discard # t is unconstrained
  3795. Whilst the syntax of type classes appears to resemble that of ADTs/algebraic data
  3796. types in ML-like languages, it should be understood that type classes are static
  3797. constraints to be enforced at type instantiations. Type classes are not really
  3798. types in themselves but are instead a system of providing generic "checks" that
  3799. ultimately *resolve* to some singular type. Type classes do not allow for
  3800. runtime type dynamism, unlike object variants or methods.
  3801. As an example, the following would not compile:
  3802. .. code-block:: nim
  3803. type TypeClass = int | string
  3804. var foo: TypeClass = 2 # foo's type is resolved to an int here
  3805. foo = "this will fail" # error here, because foo is an int
  3806. Nim allows for type classes and regular types to be specified
  3807. as `type constraints`:idx: of the generic type parameter:
  3808. .. code-block:: nim
  3809. proc onlyIntOrString[T: int|string](x, y: T) = discard
  3810. onlyIntOrString(450, 616) # valid
  3811. onlyIntOrString(5.0, 0.0) # type mismatch
  3812. onlyIntOrString("xy", 50) # invalid as 'T' cannot be both at the same time
  3813. Implicit generics
  3814. -----------------
  3815. A type class can be used directly as the parameter's type.
  3816. .. code-block:: nim
  3817. # create a type class that will match all tuple and object types
  3818. type RecordType = tuple or object
  3819. proc printFields(rec: RecordType) =
  3820. for key, value in fieldPairs(rec):
  3821. echo key, " = ", value
  3822. Procedures utilizing type classes in such a manner are considered to be
  3823. `implicitly generic`:idx:. They will be instantiated once for each unique
  3824. combination of param types used within the program.
  3825. By default, during overload resolution, each named type class will bind to
  3826. exactly one concrete type. We call such type classes `bind once`:idx: types.
  3827. Here is an example taken directly from the system module to illustrate this:
  3828. .. code-block:: nim
  3829. proc `==`*(x, y: tuple): bool =
  3830. ## requires `x` and `y` to be of the same tuple type
  3831. ## generic `==` operator for tuples that is lifted from the components
  3832. ## of `x` and `y`.
  3833. result = true
  3834. for a, b in fields(x, y):
  3835. if a != b: result = false
  3836. Alternatively, the `distinct` type modifier can be applied to the type class
  3837. to allow each param matching the type class to bind to a different type. Such
  3838. type classes are called `bind many`:idx: types.
  3839. Procs written with the implicitly generic style will often need to refer to the
  3840. type parameters of the matched generic type. They can be easily accessed using
  3841. the dot syntax:
  3842. .. code-block:: nim
  3843. type Matrix[T, Rows, Columns] = object
  3844. ...
  3845. proc `[]`(m: Matrix, row, col: int): Matrix.T =
  3846. m.data[col * high(Matrix.Columns) + row]
  3847. Here are more examples that illustrate implicit generics:
  3848. .. code-block:: nim
  3849. proc p(t: Table; k: Table.Key): Table.Value
  3850. # is roughly the same as:
  3851. proc p[Key, Value](t: Table[Key, Value]; k: Key): Value
  3852. .. code-block:: nim
  3853. proc p(a: Table, b: Table)
  3854. # is roughly the same as:
  3855. proc p[Key, Value](a, b: Table[Key, Value])
  3856. .. code-block:: nim
  3857. proc p(a: Table, b: distinct Table)
  3858. # is roughly the same as:
  3859. proc p[Key, Value, KeyB, ValueB](a: Table[Key, Value], b: Table[KeyB, ValueB])
  3860. `typedesc` used as a parameter type also introduces an implicit
  3861. generic. `typedesc` has its own set of rules:
  3862. .. code-block:: nim
  3863. proc p(a: typedesc)
  3864. # is roughly the same as:
  3865. proc p[T](a: typedesc[T])
  3866. `typedesc` is a "bind many" type class:
  3867. .. code-block:: nim
  3868. proc p(a, b: typedesc)
  3869. # is roughly the same as:
  3870. proc p[T, T2](a: typedesc[T], b: typedesc[T2])
  3871. A parameter of type `typedesc` is itself usable as a type. If it is used
  3872. as a type, it's the underlying type. (In other words, one level
  3873. of "typedesc"-ness is stripped off:
  3874. .. code-block:: nim
  3875. proc p(a: typedesc; b: a) = discard
  3876. # is roughly the same as:
  3877. proc p[T](a: typedesc[T]; b: T) = discard
  3878. # hence this is a valid call:
  3879. p(int, 4)
  3880. # as parameter 'a' requires a type, but 'b' requires a value.
  3881. Generic inference restrictions
  3882. ------------------------------
  3883. The types `var T` and `typedesc[T]` cannot be inferred in a generic
  3884. instantiation. The following is not allowed:
  3885. .. code-block:: nim
  3886. :test: "nim c $1"
  3887. :status: 1
  3888. proc g[T](f: proc(x: T); x: T) =
  3889. f(x)
  3890. proc c(y: int) = echo y
  3891. proc v(y: var int) =
  3892. y += 100
  3893. var i: int
  3894. # allowed: infers 'T' to be of type 'int'
  3895. g(c, 42)
  3896. # not valid: 'T' is not inferred to be of type 'var int'
  3897. g(v, i)
  3898. # also not allowed: explicit instantiation via 'var int'
  3899. g[var int](v, i)
  3900. Symbol lookup in generics
  3901. -------------------------
  3902. Open and Closed symbols
  3903. ~~~~~~~~~~~~~~~~~~~~~~~
  3904. The symbol binding rules in generics are slightly subtle: There are "open" and
  3905. "closed" symbols. A "closed" symbol cannot be re-bound in the instantiation
  3906. context, an "open" symbol can. Per default, overloaded symbols are open
  3907. and every other symbol is closed.
  3908. Open symbols are looked up in two different contexts: Both the context
  3909. at definition and the context at instantiation are considered:
  3910. .. code-block:: nim
  3911. :test: "nim c $1"
  3912. type
  3913. Index = distinct int
  3914. proc `==` (a, b: Index): bool {.borrow.}
  3915. var a = (0, 0.Index)
  3916. var b = (0, 0.Index)
  3917. echo a == b # works!
  3918. In the example, the generic `==` for tuples (as defined in the system module)
  3919. uses the `==` operators of the tuple's components. However, the `==` for
  3920. the `Index` type is defined *after* the `==` for tuples; yet the example
  3921. compiles as the instantiation takes the currently defined symbols into account
  3922. too.
  3923. Mixin statement
  3924. ---------------
  3925. A symbol can be forced to be open by a `mixin`:idx: declaration:
  3926. .. code-block:: nim
  3927. :test: "nim c $1"
  3928. proc create*[T](): ref T =
  3929. # there is no overloaded 'init' here, so we need to state that it's an
  3930. # open symbol explicitly:
  3931. mixin init
  3932. new result
  3933. init result
  3934. `mixin` statements only make sense in templates and generics.
  3935. Bind statement
  3936. --------------
  3937. The `bind` statement is the counterpart to the `mixin` statement. It
  3938. can be used to explicitly declare identifiers that should be bound early (i.e.
  3939. the identifiers should be looked up in the scope of the template/generic
  3940. definition):
  3941. .. code-block:: nim
  3942. # Module A
  3943. var
  3944. lastId = 0
  3945. template genId*: untyped =
  3946. bind lastId
  3947. inc(lastId)
  3948. lastId
  3949. .. code-block:: nim
  3950. # Module B
  3951. import A
  3952. echo genId()
  3953. But a `bind` is rarely useful because symbol binding from the definition
  3954. scope is the default.
  3955. `bind` statements only make sense in templates and generics.
  3956. Delegating bind statements
  3957. --------------------------
  3958. The following example outlines a problem that can arise when generic
  3959. instantiations cross multiple different modules:
  3960. .. code-block:: nim
  3961. # module A
  3962. proc genericA*[T](x: T) =
  3963. mixin init
  3964. init(x)
  3965. .. code-block:: nim
  3966. import C
  3967. # module B
  3968. proc genericB*[T](x: T) =
  3969. # Without the `bind init` statement C's init proc is
  3970. # not available when `genericB` is instantiated:
  3971. bind init
  3972. genericA(x)
  3973. .. code-block:: nim
  3974. # module C
  3975. type O = object
  3976. proc init*(x: var O) = discard
  3977. .. code-block:: nim
  3978. # module main
  3979. import B, C
  3980. genericB O()
  3981. In module B has an `init` proc from module C in its scope that is not
  3982. taken into account when `genericB` is instantiated which leads to the
  3983. instantiation of `genericA`. The solution is to `forward`:idx: these
  3984. symbols by a `bind` statement inside `genericB`.
  3985. Templates
  3986. =========
  3987. A template is a simple form of a macro: It is a simple substitution
  3988. mechanism that operates on Nim's abstract syntax trees. It is processed in
  3989. the semantic pass of the compiler.
  3990. The syntax to *invoke* a template is the same as calling a procedure.
  3991. Example:
  3992. .. code-block:: nim
  3993. template `!=` (a, b: untyped): untyped =
  3994. # this definition exists in the System module
  3995. not (a == b)
  3996. assert(5 != 6) # the compiler rewrites that to: assert(not (5 == 6))
  3997. The `!=`, `>`, `>=`, `in`, `notin`, `isnot` operators are in fact
  3998. templates:
  3999. | `a > b` is transformed into `b < a`.
  4000. | `a in b` is transformed into `contains(b, a)`.
  4001. | `notin` and `isnot` have the obvious meanings.
  4002. The "types" of templates can be the symbols `untyped`,
  4003. `typed` or `typedesc`. These are "meta types", they can only be used in certain
  4004. contexts. Regular types can be used too; this implies that `typed` expressions
  4005. are expected.
  4006. Typed vs untyped parameters
  4007. ---------------------------
  4008. An `untyped` parameter means that symbol lookups and type resolution is not
  4009. performed before the expression is passed to the template. This means that
  4010. *undeclared* identifiers, for example, can be passed to the template:
  4011. .. code-block:: nim
  4012. :test: "nim c $1"
  4013. template declareInt(x: untyped) =
  4014. var x: int
  4015. declareInt(x) # valid
  4016. x = 3
  4017. .. code-block:: nim
  4018. :test: "nim c $1"
  4019. :status: 1
  4020. template declareInt(x: typed) =
  4021. var x: int
  4022. declareInt(x) # invalid, because x has not been declared and so it has no type
  4023. A template where every parameter is `untyped` is called an `immediate`:idx:
  4024. template. For historical reasons, templates can be explicitly annotated with
  4025. an `immediate` pragma and then these templates do not take part in
  4026. overloading resolution and the parameters' types are *ignored* by the
  4027. compiler. Explicit immediate templates are now deprecated.
  4028. **Note**: For historical reasons, `stmt` was an alias for `typed` and
  4029. `expr` was an alias for `untyped`, but they are removed.
  4030. Passing a code block to a template
  4031. ----------------------------------
  4032. One can pass a block of statements as the last argument to a template
  4033. following the special `:` syntax:
  4034. .. code-block:: nim
  4035. :test: "nim c $1"
  4036. template withFile(f, fn, mode, actions: untyped): untyped =
  4037. var f: File
  4038. if open(f, fn, mode):
  4039. try:
  4040. actions
  4041. finally:
  4042. close(f)
  4043. else:
  4044. quit("cannot open: " & fn)
  4045. withFile(txt, "ttempl3.txt", fmWrite): # special colon
  4046. txt.writeLine("line 1")
  4047. txt.writeLine("line 2")
  4048. In the example, the two `writeLine` statements are bound to the `actions`
  4049. parameter.
  4050. Usually, to pass a block of code to a template, the parameter that accepts
  4051. the block needs to be of type `untyped`. Because symbol lookups are then
  4052. delayed until template instantiation time:
  4053. .. code-block:: nim
  4054. :test: "nim c $1"
  4055. :status: 1
  4056. template t(body: typed) =
  4057. proc p = echo "hey"
  4058. block:
  4059. body
  4060. t:
  4061. p() # fails with 'undeclared identifier: p'
  4062. The above code fails with the error message that `p` is not declared.
  4063. The reason for this is that the `p()` body is type-checked before getting
  4064. passed to the `body` parameter and type checking in Nim implies symbol lookups.
  4065. The same code works with `untyped` as the passed body is not required to be
  4066. type-checked:
  4067. .. code-block:: nim
  4068. :test: "nim c $1"
  4069. template t(body: untyped) =
  4070. proc p = echo "hey"
  4071. block:
  4072. body
  4073. t:
  4074. p() # compiles
  4075. Varargs of untyped
  4076. ------------------
  4077. In addition to the `untyped` meta-type that prevents type checking, there is
  4078. also `varargs[untyped]` so that not even the number of parameters is fixed:
  4079. .. code-block:: nim
  4080. :test: "nim c $1"
  4081. template hideIdentifiers(x: varargs[untyped]) = discard
  4082. hideIdentifiers(undeclared1, undeclared2)
  4083. However, since a template cannot iterate over varargs, this feature is
  4084. generally much more useful for macros.
  4085. Symbol binding in templates
  4086. ---------------------------
  4087. A template is a `hygienic`:idx: macro and so opens a new scope. Most symbols are
  4088. bound from the definition scope of the template:
  4089. .. code-block:: nim
  4090. # Module A
  4091. var
  4092. lastId = 0
  4093. template genId*: untyped =
  4094. inc(lastId)
  4095. lastId
  4096. .. code-block:: nim
  4097. # Module B
  4098. import A
  4099. echo genId() # Works as 'lastId' has been bound in 'genId's defining scope
  4100. As in generics, symbol binding can be influenced via `mixin` or `bind`
  4101. statements.
  4102. Identifier construction
  4103. -----------------------
  4104. In templates, identifiers can be constructed with the backticks notation:
  4105. .. code-block:: nim
  4106. :test: "nim c $1"
  4107. template typedef(name: untyped, typ: typedesc) =
  4108. type
  4109. `T name`* {.inject.} = typ
  4110. `P name`* {.inject.} = ref `T name`
  4111. typedef(myint, int)
  4112. var x: PMyInt
  4113. In the example, `name` is instantiated with `myint`, so \`T name\` becomes
  4114. `Tmyint`.
  4115. Lookup rules for template parameters
  4116. ------------------------------------
  4117. A parameter `p` in a template is even substituted in the expression `x.p`.
  4118. Thus, template arguments can be used as field names and a global symbol can be
  4119. shadowed by the same argument name even when fully qualified:
  4120. .. code-block:: nim
  4121. # module 'm'
  4122. type
  4123. Lev = enum
  4124. levA, levB
  4125. var abclev = levB
  4126. template tstLev(abclev: Lev) =
  4127. echo abclev, " ", m.abclev
  4128. tstLev(levA)
  4129. # produces: 'levA levA'
  4130. But the global symbol can properly be captured by a `bind` statement:
  4131. .. code-block:: nim
  4132. # module 'm'
  4133. type
  4134. Lev = enum
  4135. levA, levB
  4136. var abclev = levB
  4137. template tstLev(abclev: Lev) =
  4138. bind m.abclev
  4139. echo abclev, " ", m.abclev
  4140. tstLev(levA)
  4141. # produces: 'levA levB'
  4142. Hygiene in templates
  4143. --------------------
  4144. Per default, templates are `hygienic`:idx:\: Local identifiers declared in a
  4145. template cannot be accessed in the instantiation context:
  4146. .. code-block:: nim
  4147. :test: "nim c $1"
  4148. template newException*(exceptn: typedesc, message: string): untyped =
  4149. var
  4150. e: ref exceptn # e is implicitly gensym'ed here
  4151. new(e)
  4152. e.msg = message
  4153. e
  4154. # so this works:
  4155. let e = "message"
  4156. raise newException(IoError, e)
  4157. Whether a symbol that is declared in a template is exposed to the instantiation
  4158. scope is controlled by the `inject`:idx: and `gensym`:idx: pragmas:
  4159. `gensym`'ed symbols are not exposed but `inject`'ed symbols are.
  4160. The default for symbols of entity `type`, `var`, `let` and `const`
  4161. is `gensym` and for `proc`, `iterator`, `converter`, `template`,
  4162. `macro` is `inject`. However, if the name of the entity is passed as a
  4163. template parameter, it is an `inject`'ed symbol:
  4164. .. code-block:: nim
  4165. template withFile(f, fn, mode: untyped, actions: untyped): untyped =
  4166. block:
  4167. var f: File # since 'f' is a template param, it's injected implicitly
  4168. ...
  4169. withFile(txt, "ttempl3.txt", fmWrite):
  4170. txt.writeLine("line 1")
  4171. txt.writeLine("line 2")
  4172. The `inject` and `gensym` pragmas are second class annotations; they have
  4173. no semantics outside of a template definition and cannot be abstracted over:
  4174. .. code-block:: nim
  4175. {.pragma myInject: inject.}
  4176. template t() =
  4177. var x {.myInject.}: int # does NOT work
  4178. To get rid of hygiene in templates, one can use the `dirty`:idx: pragma for
  4179. a template. `inject` and `gensym` have no effect in `dirty` templates.
  4180. `gensym`'ed symbols cannot be used as `field` in the `x.field` syntax.
  4181. Nor can they be used in the `ObjectConstruction(field: value)`
  4182. and `namedParameterCall(field = value)` syntactic constructs.
  4183. The reason for this is that code like
  4184. .. code-block:: nim
  4185. :test: "nim c $1"
  4186. type
  4187. T = object
  4188. f: int
  4189. template tmp(x: T) =
  4190. let f = 34
  4191. echo x.f, T(f: 4)
  4192. should work as expected.
  4193. However, this means that the method call syntax is not available for
  4194. `gensym`'ed symbols:
  4195. .. code-block:: nim
  4196. :test: "nim c $1"
  4197. :status: 1
  4198. template tmp(x) =
  4199. type
  4200. T {.gensym.} = int
  4201. echo x.T # invalid: instead use: 'echo T(x)'.
  4202. tmp(12)
  4203. **Note**: The Nim compiler prior to version 1 was more lenient about this
  4204. requirement. Use the `--useVersion:0.19`:option: switch for a transition period.
  4205. Limitations of the method call syntax
  4206. -------------------------------------
  4207. The expression `x` in `x.f` needs to be semantically checked (that means
  4208. symbol lookup and type checking) before it can be decided that it needs to be
  4209. rewritten to `f(x)`. Therefore the dot syntax has some limitations when it
  4210. is used to invoke templates/macros:
  4211. .. code-block:: nim
  4212. :test: "nim c $1"
  4213. :status: 1
  4214. template declareVar(name: untyped) =
  4215. const name {.inject.} = 45
  4216. # Doesn't compile:
  4217. unknownIdentifier.declareVar
  4218. It is also not possible to use fully qualified identifiers with module
  4219. symbol in method call syntax. The order in which the dot operator
  4220. binds to symbols prohibits this.
  4221. .. code-block:: nim
  4222. :test: "nim c $1"
  4223. :status: 1
  4224. import std/sequtils
  4225. var myItems = @[1,3,3,7]
  4226. let N1 = count(myItems, 3) # OK
  4227. let N2 = sequtils.count(myItems, 3) # fully qualified, OK
  4228. let N3 = myItems.count(3) # OK
  4229. let N4 = myItems.sequtils.count(3) # illegal, `myItems.sequtils` can't be resolved
  4230. This means that when for some reason a procedure needs a
  4231. disambiguation through the module name, the call needs to be
  4232. written in function call syntax.
  4233. Macros
  4234. ======
  4235. A macro is a special function that is executed at compile time.
  4236. Normally, the input for a macro is an abstract syntax
  4237. tree (AST) of the code that is passed to it. The macro can then do
  4238. transformations on it and return the transformed AST. This can be used to
  4239. add custom language features and implement `domain-specific languages`:idx:.
  4240. Macro invocation is a case where semantic analysis does **not** entirely proceed
  4241. top to bottom and left to right. Instead, semantic analysis happens at least
  4242. twice:
  4243. * Semantic analysis recognizes and resolves the macro invocation.
  4244. * The compiler executes the macro body (which may invoke other procs).
  4245. * It replaces the AST of the macro invocation with the AST returned by the macro.
  4246. * It repeats semantic analysis of that region of the code.
  4247. * If the AST returned by the macro contains other macro invocations,
  4248. this process iterates.
  4249. While macros enable advanced compile-time code transformations, they
  4250. cannot change Nim's syntax.
  4251. Debug Example
  4252. -------------
  4253. The following example implements a powerful `debug` command that accepts a
  4254. variable number of arguments:
  4255. .. code-block:: nim
  4256. :test: "nim c $1"
  4257. # to work with Nim syntax trees, we need an API that is defined in the
  4258. # `macros` module:
  4259. import std/macros
  4260. macro debug(args: varargs[untyped]): untyped =
  4261. # `args` is a collection of `NimNode` values that each contain the
  4262. # AST for an argument of the macro. A macro always has to
  4263. # return a `NimNode`. A node of kind `nnkStmtList` is suitable for
  4264. # this use case.
  4265. result = nnkStmtList.newTree()
  4266. # iterate over any argument that is passed to this macro:
  4267. for n in args:
  4268. # add a call to the statement list that writes the expression;
  4269. # `toStrLit` converts an AST to its string representation:
  4270. result.add newCall("write", newIdentNode("stdout"), newLit(n.repr))
  4271. # add a call to the statement list that writes ": "
  4272. result.add newCall("write", newIdentNode("stdout"), newLit(": "))
  4273. # add a call to the statement list that writes the expressions value:
  4274. result.add newCall("writeLine", newIdentNode("stdout"), n)
  4275. var
  4276. a: array[0..10, int]
  4277. x = "some string"
  4278. a[0] = 42
  4279. a[1] = 45
  4280. debug(a[0], a[1], x)
  4281. The macro call expands to:
  4282. .. code-block:: nim
  4283. write(stdout, "a[0]")
  4284. write(stdout, ": ")
  4285. writeLine(stdout, a[0])
  4286. write(stdout, "a[1]")
  4287. write(stdout, ": ")
  4288. writeLine(stdout, a[1])
  4289. write(stdout, "x")
  4290. write(stdout, ": ")
  4291. writeLine(stdout, x)
  4292. Arguments that are passed to a `varargs` parameter are wrapped in an array
  4293. constructor expression. This is why `debug` iterates over all of `args`'s
  4294. children.
  4295. BindSym
  4296. -------
  4297. The above `debug` macro relies on the fact that `write`, `writeLine` and
  4298. `stdout` are declared in the system module and are thus visible in the
  4299. instantiating context. There is a way to use bound identifiers
  4300. (aka `symbols`:idx:) instead of using unbound identifiers. The `bindSym`
  4301. builtin can be used for that:
  4302. .. code-block:: nim
  4303. :test: "nim c $1"
  4304. import std/macros
  4305. macro debug(n: varargs[typed]): untyped =
  4306. result = newNimNode(nnkStmtList, n)
  4307. for x in n:
  4308. # we can bind symbols in scope via 'bindSym':
  4309. add(result, newCall(bindSym"write", bindSym"stdout", toStrLit(x)))
  4310. add(result, newCall(bindSym"write", bindSym"stdout", newStrLitNode(": ")))
  4311. add(result, newCall(bindSym"writeLine", bindSym"stdout", x))
  4312. var
  4313. a: array[0..10, int]
  4314. x = "some string"
  4315. a[0] = 42
  4316. a[1] = 45
  4317. debug(a[0], a[1], x)
  4318. The macro call expands to:
  4319. .. code-block:: nim
  4320. write(stdout, "a[0]")
  4321. write(stdout, ": ")
  4322. writeLine(stdout, a[0])
  4323. write(stdout, "a[1]")
  4324. write(stdout, ": ")
  4325. writeLine(stdout, a[1])
  4326. write(stdout, "x")
  4327. write(stdout, ": ")
  4328. writeLine(stdout, x)
  4329. However, the symbols `write`, `writeLine` and `stdout` are already bound
  4330. and are not looked up again. As the example shows, `bindSym` does work with
  4331. overloaded symbols implicitly.
  4332. Case-Of Macro
  4333. -------------
  4334. In Nim, it is possible to have a macro with the syntax of a *case-of*
  4335. expression just with the difference that all *of-branches* are passed to
  4336. and processed by the macro implementation. It is then up the macro
  4337. implementation to transform the *of-branches* into a valid Nim
  4338. statement. The following example should show how this feature could be
  4339. used for a lexical analyzer.
  4340. .. code-block:: nim
  4341. import std/macros
  4342. macro case_token(args: varargs[untyped]): untyped =
  4343. echo args.treeRepr
  4344. # creates a lexical analyzer from regular expressions
  4345. # ... (implementation is an exercise for the reader ;-)
  4346. discard
  4347. case_token: # this colon tells the parser it is a macro statement
  4348. of r"[A-Za-z_]+[A-Za-z_0-9]*":
  4349. return tkIdentifier
  4350. of r"0-9+":
  4351. return tkInteger
  4352. of r"[\+\-\*\?]+":
  4353. return tkOperator
  4354. else:
  4355. return tkUnknown
  4356. **Style note**: For code readability, it is best to use the least powerful
  4357. programming construct that still suffices. So the "check list" is:
  4358. (1) Use an ordinary proc/iterator, if possible.
  4359. (2) Else: Use a generic proc/iterator, if possible.
  4360. (3) Else: Use a template, if possible.
  4361. (4) Else: Use a macro.
  4362. For loop macro
  4363. --------------
  4364. A macro that takes as its only input parameter an expression of the special
  4365. type `system.ForLoopStmt` can rewrite the entirety of a `for` loop:
  4366. .. code-block:: nim
  4367. :test: "nim c $1"
  4368. import std/macros
  4369. macro example(loop: ForLoopStmt) =
  4370. result = newTree(nnkForStmt) # Create a new For loop.
  4371. result.add loop[^3] # This is "item".
  4372. result.add loop[^2][^1] # This is "[1, 2, 3]".
  4373. result.add newCall(bindSym"echo", loop[0])
  4374. for item in example([1, 2, 3]): discard
  4375. Expands to:
  4376. .. code-block:: nim
  4377. for item in items([1, 2, 3]):
  4378. echo item
  4379. Another example:
  4380. .. code-block:: nim
  4381. :test: "nim c $1"
  4382. import std/macros
  4383. macro enumerate(x: ForLoopStmt): untyped =
  4384. expectKind x, nnkForStmt
  4385. # check if the starting count is specified:
  4386. var countStart = if x[^2].len == 2: newLit(0) else: x[^2][1]
  4387. result = newStmtList()
  4388. # we strip off the first for loop variable and use it as an integer counter:
  4389. result.add newVarStmt(x[0], countStart)
  4390. var body = x[^1]
  4391. if body.kind != nnkStmtList:
  4392. body = newTree(nnkStmtList, body)
  4393. body.add newCall(bindSym"inc", x[0])
  4394. var newFor = newTree(nnkForStmt)
  4395. for i in 1..x.len-3:
  4396. newFor.add x[i]
  4397. # transform enumerate(X) to 'X'
  4398. newFor.add x[^2][^1]
  4399. newFor.add body
  4400. result.add newFor
  4401. # now wrap the whole macro in a block to create a new scope
  4402. result = quote do:
  4403. block: `result`
  4404. for a, b in enumerate(items([1, 2, 3])):
  4405. echo a, " ", b
  4406. # without wrapping the macro in a block, we'd need to choose different
  4407. # names for `a` and `b` here to avoid redefinition errors
  4408. for a, b in enumerate(10, [1, 2, 3, 5]):
  4409. echo a, " ", b
  4410. Special Types
  4411. =============
  4412. static[T]
  4413. ---------
  4414. As their name suggests, static parameters must be constant expressions:
  4415. .. code-block:: nim
  4416. proc precompiledRegex(pattern: static string): RegEx =
  4417. var res {.global.} = re(pattern)
  4418. return res
  4419. precompiledRegex("/d+") # Replaces the call with a precompiled
  4420. # regex, stored in a global variable
  4421. precompiledRegex(paramStr(1)) # Error, command-line options
  4422. # are not constant expressions
  4423. For the purposes of code generation, all static params are treated as
  4424. generic params - the proc will be compiled separately for each unique
  4425. supplied value (or combination of values).
  4426. Static params can also appear in the signatures of generic types:
  4427. .. code-block:: nim
  4428. type
  4429. Matrix[M,N: static int; T: Number] = array[0..(M*N - 1), T]
  4430. # Note how `Number` is just a type constraint here, while
  4431. # `static int` requires us to supply an int value
  4432. AffineTransform2D[T] = Matrix[3, 3, T]
  4433. AffineTransform3D[T] = Matrix[4, 4, T]
  4434. var m1: AffineTransform3D[float] # OK
  4435. var m2: AffineTransform2D[string] # Error, `string` is not a `Number`
  4436. Please note that `static T` is just a syntactic convenience for the underlying
  4437. generic type `static[T]`. The type param can be omitted to obtain the type
  4438. class of all constant expressions. A more specific type class can be created by
  4439. instantiating `static` with another type class.
  4440. One can force an expression to be evaluated at compile time as a constant
  4441. expression by coercing it to a corresponding `static` type:
  4442. .. code-block:: nim
  4443. import std/math
  4444. echo static(fac(5)), " ", static[bool](16.isPowerOfTwo)
  4445. The compiler will report any failure to evaluate the expression or a
  4446. possible type mismatch error.
  4447. typedesc[T]
  4448. -----------
  4449. In many contexts, Nim treats the names of types as regular
  4450. values. These values exist only during the compilation phase, but since
  4451. all values must have a type, `typedesc` is considered their special type.
  4452. `typedesc` acts as a generic type. For instance, the type of the symbol
  4453. `int` is `typedesc[int]`. Just like with regular generic types, when the
  4454. generic param is omitted, `typedesc` denotes the type class of all types.
  4455. As a syntactic convenience, one can also use `typedesc` as a modifier.
  4456. Procs featuring `typedesc` params are considered implicitly generic.
  4457. They will be instantiated for each unique combination of supplied types,
  4458. and within the body of the proc, the name of each param will refer to
  4459. the bound concrete type:
  4460. .. code-block:: nim
  4461. proc new(T: typedesc): ref T =
  4462. echo "allocating ", T.name
  4463. new(result)
  4464. var n = Node.new
  4465. var tree = new(BinaryTree[int])
  4466. When multiple type params are present, they will bind freely to different
  4467. types. To force a bind-once behavior, one can use an explicit generic param:
  4468. .. code-block:: nim
  4469. proc acceptOnlyTypePairs[T, U](A, B: typedesc[T]; C, D: typedesc[U])
  4470. Once bound, type params can appear in the rest of the proc signature:
  4471. .. code-block:: nim
  4472. :test: "nim c $1"
  4473. template declareVariableWithType(T: typedesc, value: T) =
  4474. var x: T = value
  4475. declareVariableWithType int, 42
  4476. Overload resolution can be further influenced by constraining the set
  4477. of types that will match the type param. This works in practice by
  4478. attaching attributes to types via templates. The constraint can be a
  4479. concrete type or a type class.
  4480. .. code-block:: nim
  4481. :test: "nim c $1"
  4482. template maxval(T: typedesc[int]): int = high(int)
  4483. template maxval(T: typedesc[float]): float = Inf
  4484. var i = int.maxval
  4485. var f = float.maxval
  4486. when false:
  4487. var s = string.maxval # error, maxval is not implemented for string
  4488. template isNumber(t: typedesc[object]): string = "Don't think so."
  4489. template isNumber(t: typedesc[SomeInteger]): string = "Yes!"
  4490. template isNumber(t: typedesc[SomeFloat]): string = "Maybe, could be NaN."
  4491. echo "is int a number? ", isNumber(int)
  4492. echo "is float a number? ", isNumber(float)
  4493. echo "is RootObj a number? ", isNumber(RootObj)
  4494. Passing `typedesc` is almost identical, just with the difference that
  4495. the macro is not instantiated generically. The type expression is
  4496. simply passed as a `NimNode` to the macro, like everything else.
  4497. .. code-block:: nim
  4498. import std/macros
  4499. macro forwardType(arg: typedesc): typedesc =
  4500. # `arg` is of type `NimNode`
  4501. let tmp: NimNode = arg
  4502. result = tmp
  4503. var tmp: forwardType(int)
  4504. typeof operator
  4505. ---------------
  4506. **Note**: `typeof(x)` can for historical reasons also be written as
  4507. `type(x)` but `type(x)` is discouraged.
  4508. One can obtain the type of a given expression by constructing a `typeof`
  4509. value from it (in many other languages this is known as the `typeof`:idx:
  4510. operator):
  4511. .. code-block:: nim
  4512. var x = 0
  4513. var y: typeof(x) # y has type int
  4514. If `typeof` is used to determine the result type of a proc/iterator/converter
  4515. call `c(X)` (where `X` stands for a possibly empty list of arguments), the
  4516. interpretation, where `c` is an iterator, is preferred over the
  4517. other interpretations, but this behavior can be changed by
  4518. passing `typeOfProc` as the second argument to `typeof`:
  4519. .. code-block:: nim
  4520. :test: "nim c $1"
  4521. iterator split(s: string): string = discard
  4522. proc split(s: string): seq[string] = discard
  4523. # since an iterator is the preferred interpretation, `y` has the type `string`:
  4524. assert typeof("a b c".split) is string
  4525. assert typeof("a b c".split, typeOfProc) is seq[string]
  4526. Modules
  4527. =======
  4528. Nim supports splitting a program into pieces by a module concept.
  4529. Each module needs to be in its own file and has its own `namespace`:idx:.
  4530. Modules enable `information hiding`:idx: and `separate compilation`:idx:.
  4531. A module may gain access to symbols of another module by the `import`:idx:
  4532. statement. `Recursive module dependencies`:idx: are allowed, but are slightly
  4533. subtle. Only top-level symbols that are marked with an asterisk (`*`) are
  4534. exported. A valid module name can only be a valid Nim identifier (and thus its
  4535. filename is ``identifier.nim``).
  4536. The algorithm for compiling modules is:
  4537. - Compile the whole module as usual, following import statements recursively.
  4538. - If there is a cycle, only import the already parsed symbols (that are
  4539. exported); if an unknown identifier occurs then abort.
  4540. This is best illustrated by an example:
  4541. .. code-block:: nim
  4542. # Module A
  4543. type
  4544. T1* = int # Module A exports the type `T1`
  4545. import B # the compiler starts parsing B
  4546. proc main() =
  4547. var i = p(3) # works because B has been parsed completely here
  4548. main()
  4549. .. code-block:: nim
  4550. # Module B
  4551. import A # A is not parsed here! Only the already known symbols
  4552. # of A are imported.
  4553. proc p*(x: A.T1): A.T1 =
  4554. # this works because the compiler has already
  4555. # added T1 to A's interface symbol table
  4556. result = x + 1
  4557. Import statement
  4558. ----------------
  4559. After the `import` statement, a list of module names can follow or a single
  4560. module name followed by an `except` list to prevent some symbols from being
  4561. imported:
  4562. .. code-block:: nim
  4563. :test: "nim c $1"
  4564. :status: 1
  4565. import std/strutils except `%`, toUpperAscii
  4566. # doesn't work then:
  4567. echo "$1" % "abc".toUpperAscii
  4568. It is not checked that the `except` list is really exported from the module.
  4569. This feature allows us to compile against an older version of the module that
  4570. does not export these identifiers.
  4571. The `import` statement is only allowed at the top level.
  4572. Include statement
  4573. -----------------
  4574. The `include` statement does something fundamentally different than
  4575. importing a module: it merely includes the contents of a file. The `include`
  4576. statement is useful to split up a large module into several files:
  4577. .. code-block:: nim
  4578. include fileA, fileB, fileC
  4579. The `include` statement can be used outside of the top level, as such:
  4580. .. code-block:: nim
  4581. # Module A
  4582. echo "Hello World!"
  4583. .. code-block:: nim
  4584. # Module B
  4585. proc main() =
  4586. include A
  4587. main() # => Hello World!
  4588. Module names in imports
  4589. -----------------------
  4590. A module alias can be introduced via the `as` keyword:
  4591. .. code-block:: nim
  4592. import std/strutils as su, std/sequtils as qu
  4593. echo su.format("$1", "lalelu")
  4594. The original module name is then not accessible. The notations
  4595. `path/to/module` or `"path/to/module"` can be used to refer to a module
  4596. in subdirectories:
  4597. .. code-block:: nim
  4598. import lib/pure/os, "lib/pure/times"
  4599. Note that the module name is still `strutils` and not `lib/pure/strutils`
  4600. and so one **cannot** do:
  4601. .. code-block:: nim
  4602. import lib/pure/strutils
  4603. echo lib/pure/strutils.toUpperAscii("abc")
  4604. Likewise, the following does not make sense as the name is `strutils` already:
  4605. .. code-block:: nim
  4606. import lib/pure/strutils as strutils
  4607. Collective imports from a directory
  4608. -----------------------------------
  4609. The syntax `import dir / [moduleA, moduleB]` can be used to import multiple modules
  4610. from the same directory.
  4611. Path names are syntactically either Nim identifiers or string literals. If the path
  4612. name is not a valid Nim identifier it needs to be a string literal:
  4613. .. code-block:: nim
  4614. import "gfx/3d/somemodule" # in quotes because '3d' is not a valid Nim identifier
  4615. Pseudo import/include paths
  4616. ---------------------------
  4617. A directory can also be a so-called "pseudo directory". They can be used to
  4618. avoid ambiguity when there are multiple modules with the same path.
  4619. There are two pseudo directories:
  4620. 1. `std`: The `std` pseudo directory is the abstract location of Nim's standard
  4621. library. For example, the syntax `import std / strutils` is used to unambiguously
  4622. refer to the standard library's `strutils` module.
  4623. 2. `pkg`: The `pkg` pseudo directory is used to unambiguously refer to a Nimble
  4624. package. However, for technical details that lie outside the scope of this document,
  4625. its semantics are: *Use the search path to look for module name but ignore the standard
  4626. library locations*. In other words, it is the opposite of `std`.
  4627. It is recommended and preferred but not currently enforced that all stdlib module imports include the std/ "pseudo directory" as part of the import name.
  4628. From import statement
  4629. ---------------------
  4630. After the `from` statement, a module name follows followed by
  4631. an `import` to list the symbols one likes to use without explicit
  4632. full qualification:
  4633. .. code-block:: nim
  4634. :test: "nim c $1"
  4635. from std/strutils import `%`
  4636. echo "$1" % "abc"
  4637. # always possible: full qualification:
  4638. echo strutils.replace("abc", "a", "z")
  4639. It's also possible to use `from module import nil` if one wants to import
  4640. the module but wants to enforce fully qualified access to every symbol
  4641. in `module`.
  4642. Export statement
  4643. ----------------
  4644. An `export` statement can be used for symbol forwarding so that client
  4645. modules don't need to import a module's dependencies:
  4646. .. code-block:: nim
  4647. # module B
  4648. type MyObject* = object
  4649. .. code-block:: nim
  4650. # module A
  4651. import B
  4652. export B.MyObject
  4653. proc `$`*(x: MyObject): string = "my object"
  4654. .. code-block:: nim
  4655. # module C
  4656. import A
  4657. # B.MyObject has been imported implicitly here:
  4658. var x: MyObject
  4659. echo $x
  4660. When the exported symbol is another module, all of its definitions will
  4661. be forwarded. One can use an `except` list to exclude some of the symbols.
  4662. Notice that when exporting, one needs to specify only the module name:
  4663. .. code-block:: nim
  4664. import foo/bar/baz
  4665. export baz
  4666. Scope rules
  4667. -----------
  4668. Identifiers are valid from the point of their declaration until the end of
  4669. the block in which the declaration occurred. The range where the identifier
  4670. is known is the scope of the identifier. The exact scope of an
  4671. identifier depends on the way it was declared.
  4672. Block scope
  4673. ~~~~~~~~~~~
  4674. The *scope* of a variable declared in the declaration part of a block
  4675. is valid from the point of declaration until the end of the block. If a
  4676. block contains a second block, in which the identifier is redeclared,
  4677. then inside this block, the second declaration will be valid. Upon
  4678. leaving the inner block, the first declaration is valid again. An
  4679. identifier cannot be redefined in the same block, except if valid for
  4680. procedure or iterator overloading purposes.
  4681. Tuple or object scope
  4682. ~~~~~~~~~~~~~~~~~~~~~
  4683. The field identifiers inside a tuple or object definition are valid in the
  4684. following places:
  4685. * To the end of the tuple/object definition.
  4686. * Field designators of a variable of the given tuple/object type.
  4687. * In all descendant types of the object type.
  4688. Module scope
  4689. ~~~~~~~~~~~~
  4690. All identifiers of a module are valid from the point of declaration until
  4691. the end of the module. Identifiers from indirectly dependent modules are *not*
  4692. available. The `system`:idx: module is automatically imported in every module.
  4693. If a module imports an identifier by two different modules, each occurrence of
  4694. the identifier has to be qualified unless it is an overloaded procedure or
  4695. iterator in which case the overloading resolution takes place:
  4696. .. code-block:: nim
  4697. # Module A
  4698. var x*: string
  4699. .. code-block:: nim
  4700. # Module B
  4701. var x*: int
  4702. .. code-block:: nim
  4703. # Module C
  4704. import A, B
  4705. write(stdout, x) # error: x is ambiguous
  4706. write(stdout, A.x) # no error: qualifier used
  4707. var x = 4
  4708. write(stdout, x) # not ambiguous: uses the module C's x
  4709. Compiler Messages
  4710. =================
  4711. The Nim compiler emits different kinds of messages: `hint`:idx:,
  4712. `warning`:idx:, and `error`:idx: messages. An *error* message is emitted if
  4713. the compiler encounters any static error.
  4714. Pragmas
  4715. =======
  4716. Pragmas are Nim's method to give the compiler additional information /
  4717. commands without introducing a massive number of new keywords. Pragmas are
  4718. processed on the fly during semantic checking. Pragmas are enclosed in the
  4719. special `{.` and `.}` curly brackets. Pragmas are also often used as a
  4720. first implementation to play with a language feature before a nicer syntax
  4721. to access the feature becomes available.
  4722. deprecated pragma
  4723. -----------------
  4724. The deprecated pragma is used to mark a symbol as deprecated:
  4725. .. code-block:: nim
  4726. proc p() {.deprecated.}
  4727. var x {.deprecated.}: char
  4728. This pragma can also take in an optional warning string to relay to developers.
  4729. .. code-block:: nim
  4730. proc thing(x: bool) {.deprecated: "use thong instead".}
  4731. compileTime pragma
  4732. ------------------
  4733. The `compileTime` pragma is used to mark a proc or variable to be used only
  4734. during compile-time execution. No code will be generated for it. Compile-time
  4735. procs are useful as helpers for macros. Since version 0.12.0 of the language, a
  4736. proc that uses `system.NimNode` within its parameter types is implicitly
  4737. declared `compileTime`:
  4738. .. code-block:: nim
  4739. proc astHelper(n: NimNode): NimNode =
  4740. result = n
  4741. Is the same as:
  4742. .. code-block:: nim
  4743. proc astHelper(n: NimNode): NimNode {.compileTime.} =
  4744. result = n
  4745. `compileTime` variables are available at runtime too. This simplifies certain
  4746. idioms where variables are filled at compile-time (for example, lookup tables)
  4747. but accessed at runtime:
  4748. .. code-block:: nim
  4749. :test: "nim c -r $1"
  4750. import std/macros
  4751. var nameToProc {.compileTime.}: seq[(string, proc (): string {.nimcall.})]
  4752. macro registerProc(p: untyped): untyped =
  4753. result = newTree(nnkStmtList, p)
  4754. let procName = p[0]
  4755. let procNameAsStr = $p[0]
  4756. result.add quote do:
  4757. nameToProc.add((`procNameAsStr`, `procName`))
  4758. proc foo: string {.registerProc.} = "foo"
  4759. proc bar: string {.registerProc.} = "bar"
  4760. proc baz: string {.registerProc.} = "baz"
  4761. doAssert nameToProc[2][1]() == "baz"
  4762. noReturn pragma
  4763. ---------------
  4764. The `noreturn` pragma is used to mark a proc that never returns.
  4765. acyclic pragma
  4766. --------------
  4767. The `acyclic` pragma can be used for object types to mark them as acyclic
  4768. even though they seem to be cyclic. This is an **optimization** for the garbage
  4769. collector to not consider objects of this type as part of a cycle:
  4770. .. code-block:: nim
  4771. type
  4772. Node = ref NodeObj
  4773. NodeObj {.acyclic.} = object
  4774. left, right: Node
  4775. data: string
  4776. Or if we directly use a ref object:
  4777. .. code-block:: nim
  4778. type
  4779. Node {.acyclic.} = ref object
  4780. left, right: Node
  4781. data: string
  4782. In the example, a tree structure is declared with the `Node` type. Note that
  4783. the type definition is recursive and the GC has to assume that objects of
  4784. this type may form a cyclic graph. The `acyclic` pragma passes the
  4785. information that this cannot happen to the GC. If the programmer uses the
  4786. `acyclic` pragma for data types that are in reality cyclic, this may result
  4787. in memory leaks, but memory safety is preserved.
  4788. final pragma
  4789. ------------
  4790. The `final` pragma can be used for an object type to specify that it
  4791. cannot be inherited from. Note that inheritance is only available for
  4792. objects that inherit from an existing object (via the `object of SuperType`
  4793. syntax) or that have been marked as `inheritable`.
  4794. shallow pragma
  4795. --------------
  4796. The `shallow` pragma affects the semantics of a type: The compiler is
  4797. allowed to make a shallow copy. This can cause serious semantic issues and
  4798. break memory safety! However, it can speed up assignments considerably,
  4799. because the semantics of Nim require deep copying of sequences and strings.
  4800. This can be expensive, especially if sequences are used to build a tree
  4801. structure:
  4802. .. code-block:: nim
  4803. type
  4804. NodeKind = enum nkLeaf, nkInner
  4805. Node {.shallow.} = object
  4806. case kind: NodeKind
  4807. of nkLeaf:
  4808. strVal: string
  4809. of nkInner:
  4810. children: seq[Node]
  4811. pure pragma
  4812. -----------
  4813. An object type can be marked with the `pure` pragma so that its type field
  4814. which is used for runtime type identification is omitted. This used to be
  4815. necessary for binary compatibility with other compiled languages.
  4816. An enum type can be marked as `pure`. Then access of its fields always
  4817. requires full qualification.
  4818. asmNoStackFrame pragma
  4819. ----------------------
  4820. A proc can be marked with the `asmNoStackFrame` pragma to tell the compiler
  4821. it should not generate a stack frame for the proc. There are also no exit
  4822. statements like `return result;` generated and the generated C function is
  4823. declared as `__declspec(naked)`:c: or `__attribute__((naked))`:c: (depending on
  4824. the used C compiler).
  4825. **Note**: This pragma should only be used by procs which consist solely of
  4826. assembler statements.
  4827. error pragma
  4828. ------------
  4829. The `error` pragma is used to make the compiler output an error message
  4830. with the given content. The compilation does not necessarily abort after an error
  4831. though.
  4832. The `error` pragma can also be used to
  4833. annotate a symbol (like an iterator or proc). The *usage* of the symbol then
  4834. triggers a static error. This is especially useful to rule out that some
  4835. operation is valid due to overloading and type conversions:
  4836. .. code-block:: nim
  4837. ## check that underlying int values are compared and not the pointers:
  4838. proc `==`(x, y: ptr int): bool {.error.}
  4839. fatal pragma
  4840. ------------
  4841. The `fatal` pragma is used to make the compiler output an error message
  4842. with the given content. In contrast to the `error` pragma, the compilation
  4843. is guaranteed to be aborted by this pragma. Example:
  4844. .. code-block:: nim
  4845. when not defined(objc):
  4846. {.fatal: "Compile this program with the objc command!".}
  4847. warning pragma
  4848. --------------
  4849. The `warning` pragma is used to make the compiler output a warning message
  4850. with the given content. Compilation continues after the warning.
  4851. hint pragma
  4852. -----------
  4853. The `hint` pragma is used to make the compiler output a hint message with
  4854. the given content. Compilation continues after the hint.
  4855. line pragma
  4856. -----------
  4857. The `line` pragma can be used to affect line information of the annotated
  4858. statement, as seen in stack backtraces:
  4859. .. code-block:: nim
  4860. template myassert*(cond: untyped, msg = "") =
  4861. if not cond:
  4862. # change run-time line information of the 'raise' statement:
  4863. {.line: instantiationInfo().}:
  4864. raise newException(EAssertionFailed, msg)
  4865. If the `line` pragma is used with a parameter, the parameter needs be a
  4866. `tuple[filename: string, line: int]`. If it is used without a parameter,
  4867. `system.InstantiationInfo()` is used.
  4868. linearScanEnd pragma
  4869. --------------------
  4870. The `linearScanEnd` pragma can be used to tell the compiler how to
  4871. compile a Nim `case`:idx: statement. Syntactically it has to be used as a
  4872. statement:
  4873. .. code-block:: nim
  4874. case myInt
  4875. of 0:
  4876. echo "most common case"
  4877. of 1:
  4878. {.linearScanEnd.}
  4879. echo "second most common case"
  4880. of 2: echo "unlikely: use branch table"
  4881. else: echo "unlikely too: use branch table for ", myInt
  4882. In the example, the case branches `0` and `1` are much more common than
  4883. the other cases. Therefore the generated assembler code should test for these
  4884. values first so that the CPU's branch predictor has a good chance to succeed
  4885. (avoiding an expensive CPU pipeline stall). The other cases might be put into a
  4886. jump table for O(1) overhead but at the cost of a (very likely) pipeline
  4887. stall.
  4888. The `linearScanEnd` pragma should be put into the last branch that should be
  4889. tested against via linear scanning. If put into the last branch of the
  4890. whole `case` statement, the whole `case` statement uses linear scanning.
  4891. computedGoto pragma
  4892. -------------------
  4893. The `computedGoto` pragma can be used to tell the compiler how to
  4894. compile a Nim `case`:idx: in a `while true` statement.
  4895. Syntactically it has to be used as a statement inside the loop:
  4896. .. code-block:: nim
  4897. type
  4898. MyEnum = enum
  4899. enumA, enumB, enumC, enumD, enumE
  4900. proc vm() =
  4901. var instructions: array[0..100, MyEnum]
  4902. instructions[2] = enumC
  4903. instructions[3] = enumD
  4904. instructions[4] = enumA
  4905. instructions[5] = enumD
  4906. instructions[6] = enumC
  4907. instructions[7] = enumA
  4908. instructions[8] = enumB
  4909. instructions[12] = enumE
  4910. var pc = 0
  4911. while true:
  4912. {.computedGoto.}
  4913. let instr = instructions[pc]
  4914. case instr
  4915. of enumA:
  4916. echo "yeah A"
  4917. of enumC, enumD:
  4918. echo "yeah CD"
  4919. of enumB:
  4920. echo "yeah B"
  4921. of enumE:
  4922. break
  4923. inc(pc)
  4924. vm()
  4925. As the example shows, `computedGoto` is mostly useful for interpreters. If
  4926. the underlying backend (C compiler) does not support the computed goto
  4927. extension the pragma is simply ignored.
  4928. immediate pragma
  4929. ----------------
  4930. The immediate pragma is obsolete. See `Typed vs untyped parameters
  4931. <#templates-typed-vs-untyped-parameters>`_.
  4932. compilation option pragmas
  4933. --------------------------
  4934. The listed pragmas here can be used to override the code generation options
  4935. for a proc/method/converter.
  4936. The implementation currently provides the following possible options (various
  4937. others may be added later).
  4938. =============== =============== ============================================
  4939. pragma allowed values description
  4940. =============== =============== ============================================
  4941. checks on|off Turns the code generation for all runtime
  4942. checks on or off.
  4943. boundChecks on|off Turns the code generation for array bound
  4944. checks on or off.
  4945. overflowChecks on|off Turns the code generation for over- or
  4946. underflow checks on or off.
  4947. nilChecks on|off Turns the code generation for nil pointer
  4948. checks on or off.
  4949. assertions on|off Turns the code generation for assertions
  4950. on or off.
  4951. warnings on|off Turns the warning messages of the compiler
  4952. on or off.
  4953. hints on|off Turns the hint messages of the compiler
  4954. on or off.
  4955. optimization none|speed|size Optimize the code for speed or size, or
  4956. disable optimization.
  4957. patterns on|off Turns the term rewriting templates/macros
  4958. on or off.
  4959. callconv cdecl|... Specifies the default calling convention for
  4960. all procedures (and procedure types) that
  4961. follow.
  4962. =============== =============== ============================================
  4963. Example:
  4964. .. code-block:: nim
  4965. {.checks: off, optimization: speed.}
  4966. # compile without runtime checks and optimize for speed
  4967. push and pop pragmas
  4968. --------------------
  4969. The `push/pop`:idx: pragmas are very similar to the option directive,
  4970. but are used to override the settings temporarily. Example:
  4971. .. code-block:: nim
  4972. {.push checks: off.}
  4973. # compile this section without runtime checks as it is
  4974. # speed critical
  4975. # ... some code ...
  4976. {.pop.} # restore old settings
  4977. `push/pop`:idx: can switch on/off some standard library pragmas, example:
  4978. .. code-block:: nim
  4979. {.push inline.}
  4980. proc thisIsInlined(): int = 42
  4981. func willBeInlined(): float = 42.0
  4982. {.pop.}
  4983. proc notInlined(): int = 9
  4984. {.push discardable, boundChecks: off, compileTime, noSideEffect, experimental.}
  4985. template example(): string = "https://nim-lang.org"
  4986. {.pop.}
  4987. {.push deprecated, hint[LineTooLong]: off, used, stackTrace: off.}
  4988. proc sample(): bool = true
  4989. {.pop.}
  4990. For third party pragmas, it depends on its implementation but uses the same syntax.
  4991. register pragma
  4992. ---------------
  4993. The `register` pragma is for variables only. It declares the variable as
  4994. `register`, giving the compiler a hint that the variable should be placed
  4995. in a hardware register for faster access. C compilers usually ignore this
  4996. though and for good reasons: Often they do a better job without it anyway.
  4997. However, in highly specific cases (a dispatch loop of a bytecode interpreter
  4998. for example) it may provide benefits.
  4999. global pragma
  5000. -------------
  5001. The `global` pragma can be applied to a variable within a proc to instruct
  5002. the compiler to store it in a global location and initialize it once at program
  5003. startup.
  5004. .. code-block:: nim
  5005. proc isHexNumber(s: string): bool =
  5006. var pattern {.global.} = re"[0-9a-fA-F]+"
  5007. result = s.match(pattern)
  5008. When used within a generic proc, a separate unique global variable will be
  5009. created for each instantiation of the proc. The order of initialization of
  5010. the created global variables within a module is not defined, but all of them
  5011. will be initialized after any top-level variables in their originating module
  5012. and before any variable in a module that imports it.
  5013. Disabling certain messages
  5014. --------------------------
  5015. Nim generates some warnings and hints ("line too long") that may annoy the
  5016. user. A mechanism for disabling certain messages is provided: Each hint
  5017. and warning message contains a symbol in brackets. This is the message's
  5018. identifier that can be used to enable or disable it:
  5019. .. code-block:: Nim
  5020. {.hint[LineTooLong]: off.} # turn off the hint about too long lines
  5021. This is often better than disabling all warnings at once.
  5022. used pragma
  5023. -----------
  5024. Nim produces a warning for symbols that are not exported and not used either.
  5025. The `used` pragma can be attached to a symbol to suppress this warning. This
  5026. is particularly useful when the symbol was generated by a macro:
  5027. .. code-block:: nim
  5028. template implementArithOps(T) =
  5029. proc echoAdd(a, b: T) {.used.} =
  5030. echo a + b
  5031. proc echoSub(a, b: T) {.used.} =
  5032. echo a - b
  5033. # no warning produced for the unused 'echoSub'
  5034. implementArithOps(int)
  5035. echoAdd 3, 5
  5036. `used` can also be used as a top-level statement to mark a module as "used".
  5037. This prevents the "Unused import" warning:
  5038. .. code-block:: nim
  5039. # module: debughelper.nim
  5040. when defined(nimHasUsed):
  5041. # 'import debughelper' is so useful for debugging
  5042. # that Nim shouldn't produce a warning for that import,
  5043. # even if currently unused:
  5044. {.used.}
  5045. experimental pragma
  5046. -------------------
  5047. The `experimental` pragma enables experimental language features. Depending
  5048. on the concrete feature, this means that the feature is either considered
  5049. too unstable for an otherwise stable release or that the future of the feature
  5050. is uncertain (it may be removed at any time).
  5051. Example:
  5052. .. code-block:: nim
  5053. import std/threadpool
  5054. {.experimental: "parallel".}
  5055. proc threadedEcho(s: string, i: int) =
  5056. echo(s, " ", $i)
  5057. proc useParallel() =
  5058. parallel:
  5059. for i in 0..4:
  5060. spawn threadedEcho("echo in parallel", i)
  5061. useParallel()
  5062. As a top-level statement, the experimental pragma enables a feature for the
  5063. rest of the module it's enabled in. This is problematic for macro and generic
  5064. instantiations that cross a module scope. Currently, these usages have to be
  5065. put into a `.push/pop` environment:
  5066. .. code-block:: nim
  5067. # client.nim
  5068. proc useParallel*[T](unused: T) =
  5069. # use a generic T here to show the problem.
  5070. {.push experimental: "parallel".}
  5071. parallel:
  5072. for i in 0..4:
  5073. echo "echo in parallel"
  5074. {.pop.}
  5075. .. code-block:: nim
  5076. import client
  5077. useParallel(1)
  5078. Implementation Specific Pragmas
  5079. ===============================
  5080. This section describes additional pragmas that the current Nim implementation
  5081. supports but which should not be seen as part of the language specification.
  5082. Bitsize pragma
  5083. --------------
  5084. The `bitsize` pragma is for object field members. It declares the field as
  5085. a bitfield in C/C++.
  5086. .. code-block:: Nim
  5087. type
  5088. mybitfield = object
  5089. flag {.bitsize:1.}: cuint
  5090. generates:
  5091. .. code-block:: C
  5092. struct mybitfield {
  5093. unsigned int flag:1;
  5094. };
  5095. Align pragma
  5096. ------------
  5097. The `align`:idx: pragma is for variables and object field members. It
  5098. modifies the alignment requirement of the entity being declared. The
  5099. argument must be a constant power of 2. Valid non-zero
  5100. alignments that are weaker than other align pragmas on the same
  5101. declaration are ignored. Alignments that are weaker than the
  5102. alignment requirement of the type are ignored.
  5103. .. code-block:: Nim
  5104. type
  5105. sseType = object
  5106. sseData {.align(16).}: array[4, float32]
  5107. # every object will be aligned to 128-byte boundary
  5108. Data = object
  5109. x: char
  5110. cacheline {.align(128).}: array[128, char] # over-aligned array of char,
  5111. proc main() =
  5112. echo "sizeof(Data) = ", sizeof(Data), " (1 byte + 127 bytes padding + 128-byte array)"
  5113. # output: sizeof(Data) = 256 (1 byte + 127 bytes padding + 128-byte array)
  5114. echo "alignment of sseType is ", alignof(sseType)
  5115. # output: alignment of sseType is 16
  5116. var d {.align(2048).}: Data # this instance of data is aligned even stricter
  5117. main()
  5118. This pragma has no effect on the JS backend.
  5119. Volatile pragma
  5120. ---------------
  5121. The `volatile` pragma is for variables only. It declares the variable as
  5122. `volatile`:c:, whatever that means in C/C++ (its semantics are not well defined
  5123. in C/C++).
  5124. **Note**: This pragma will not exist for the LLVM backend.
  5125. nodecl pragma
  5126. -------------
  5127. The `nodecl` pragma can be applied to almost any symbol (variable, proc,
  5128. type, etc.) and is sometimes useful for interoperability with C:
  5129. It tells Nim that it should not generate a declaration for the symbol in
  5130. the C code. For example:
  5131. .. code-block:: Nim
  5132. var
  5133. EACCES {.importc, nodecl.}: cint # pretend EACCES was a variable, as
  5134. # Nim does not know its value
  5135. However, the `header` pragma is often the better alternative.
  5136. **Note**: This will not work for the LLVM backend.
  5137. Header pragma
  5138. -------------
  5139. The `header` pragma is very similar to the `nodecl` pragma: It can be
  5140. applied to almost any symbol and specifies that it should not be declared
  5141. and instead, the generated code should contain an `#include`:c:\:
  5142. .. code-block:: Nim
  5143. type
  5144. PFile {.importc: "FILE*", header: "<stdio.h>".} = distinct pointer
  5145. # import C's FILE* type; Nim will treat it as a new pointer type
  5146. The `header` pragma always expects a string constant. The string constant
  5147. contains the header file: As usual for C, a system header file is enclosed
  5148. in angle brackets: `<>`:c:. If no angle brackets are given, Nim
  5149. encloses the header file in `""`:c: in the generated C code.
  5150. **Note**: This will not work for the LLVM backend.
  5151. IncompleteStruct pragma
  5152. -----------------------
  5153. The `incompleteStruct` pragma tells the compiler to not use the
  5154. underlying C `struct`:c: in a `sizeof` expression:
  5155. .. code-block:: Nim
  5156. type
  5157. DIR* {.importc: "DIR", header: "<dirent.h>",
  5158. pure, incompleteStruct.} = object
  5159. Compile pragma
  5160. --------------
  5161. The `compile` pragma can be used to compile and link a C/C++ source file
  5162. with the project:
  5163. .. code-block:: Nim
  5164. {.compile: "myfile.cpp".}
  5165. **Note**: Nim computes a SHA1 checksum and only recompiles the file if it
  5166. has changed. One can use the `-f`:option: command-line option to force
  5167. the recompilation of the file.
  5168. Since 1.4 the `compile` pragma is also available with this syntax:
  5169. .. code-block:: Nim
  5170. {.compile("myfile.cpp", "--custom flags here").}
  5171. As can be seen in the example, this new variant allows for custom flags
  5172. that are passed to the C compiler when the file is recompiled.
  5173. Link pragma
  5174. -----------
  5175. The `link` pragma can be used to link an additional file with the project:
  5176. .. code-block:: Nim
  5177. {.link: "myfile.o".}
  5178. PassC pragma
  5179. ------------
  5180. The `passc` pragma can be used to pass additional parameters to the C
  5181. compiler like one would using the command-line switch `--passc`:option:\:
  5182. .. code-block:: Nim
  5183. {.passc: "-Wall -Werror".}
  5184. Note that one can use `gorge` from the `system module <system.html>`_ to
  5185. embed parameters from an external command that will be executed
  5186. during semantic analysis:
  5187. .. code-block:: Nim
  5188. {.passc: gorge("pkg-config --cflags sdl").}
  5189. LocalPassc pragma
  5190. -----------------
  5191. The `localPassc` pragma can be used to pass additional parameters to the C
  5192. compiler, but only for the C/C++ file that is produced from the Nim module
  5193. the pragma resides in:
  5194. .. code-block:: Nim
  5195. # Module A.nim
  5196. # Produces: A.nim.cpp
  5197. {.localPassc: "-Wall -Werror".} # Passed when compiling A.nim.cpp
  5198. PassL pragma
  5199. ------------
  5200. The `passL` pragma can be used to pass additional parameters to the linker
  5201. like one would be using the command-line switch `--passL`:option:\:
  5202. .. code-block:: Nim
  5203. {.passL: "-lSDLmain -lSDL".}
  5204. Note that one can use `gorge` from the `system module <system.html>`_ to
  5205. embed parameters from an external command that will be executed
  5206. during semantic analysis:
  5207. .. code-block:: Nim
  5208. {.passL: gorge("pkg-config --libs sdl").}
  5209. Emit pragma
  5210. -----------
  5211. The `emit` pragma can be used to directly affect the output of the
  5212. compiler's code generator. The code is then unportable to other code
  5213. generators/backends. Its usage is highly discouraged! However, it can be
  5214. extremely useful for interfacing with `C++`:idx: or `Objective C`:idx: code.
  5215. Example:
  5216. .. code-block:: Nim
  5217. {.emit: """
  5218. static int cvariable = 420;
  5219. """.}
  5220. {.push stackTrace:off.}
  5221. proc embedsC() =
  5222. var nimVar = 89
  5223. # access Nim symbols within an emit section outside of string literals:
  5224. {.emit: ["""fprintf(stdout, "%d\n", cvariable + (int)""", nimVar, ");"].}
  5225. {.pop.}
  5226. embedsC()
  5227. ``nimbase.h`` defines `NIM_EXTERNC`:c: C macro that can be used for
  5228. `extern "C"`:cpp: code to work with both `nim c`:cmd: and `nim cpp`:cmd:, e.g.:
  5229. .. code-block:: Nim
  5230. proc foobar() {.importc:"$1".}
  5231. {.emit: """
  5232. #include <stdio.h>
  5233. NIM_EXTERNC
  5234. void fun(){}
  5235. """.}
  5236. .. note:: For backward compatibility, if the argument to the `emit` statement
  5237. is a single string literal, Nim symbols can be referred to via backticks.
  5238. This usage is however deprecated.
  5239. For a top-level emit statement, the section where in the generated C/C++ file
  5240. the code should be emitted can be influenced via the prefixes
  5241. `/*TYPESECTION*/`:c: or `/*VARSECTION*/`:c: or `/*INCLUDESECTION*/`:c:\:
  5242. .. code-block:: Nim
  5243. {.emit: """/*TYPESECTION*/
  5244. struct Vector3 {
  5245. public:
  5246. Vector3(): x(5) {}
  5247. Vector3(float x_): x(x_) {}
  5248. float x;
  5249. };
  5250. """.}
  5251. type Vector3 {.importcpp: "Vector3", nodecl} = object
  5252. x: cfloat
  5253. proc constructVector3(a: cfloat): Vector3 {.importcpp: "Vector3(@)", nodecl}
  5254. ImportCpp pragma
  5255. ----------------
  5256. **Note**: `c2nim <https://github.com/nim-lang/c2nim/blob/master/doc/c2nim.rst>`_ can parse a large subset of C++ and knows
  5257. about the `importcpp` pragma pattern language. It is not necessary
  5258. to know all the details described here.
  5259. Similar to the `importc pragma for C
  5260. <#foreign-function-interface-importc-pragma>`_, the
  5261. `importcpp` pragma can be used to import `C++`:idx: methods or C++ symbols
  5262. in general. The generated code then uses the C++ method calling
  5263. syntax: `obj->method(arg)`:cpp:. In combination with the `header` and `emit`
  5264. pragmas this allows *sloppy* interfacing with libraries written in C++:
  5265. .. code-block:: Nim
  5266. # Horrible example of how to interface with a C++ engine ... ;-)
  5267. {.link: "/usr/lib/libIrrlicht.so".}
  5268. {.emit: """
  5269. using namespace irr;
  5270. using namespace core;
  5271. using namespace scene;
  5272. using namespace video;
  5273. using namespace io;
  5274. using namespace gui;
  5275. """.}
  5276. const
  5277. irr = "<irrlicht/irrlicht.h>"
  5278. type
  5279. IrrlichtDeviceObj {.header: irr,
  5280. importcpp: "IrrlichtDevice".} = object
  5281. IrrlichtDevice = ptr IrrlichtDeviceObj
  5282. proc createDevice(): IrrlichtDevice {.
  5283. header: irr, importcpp: "createDevice(@)".}
  5284. proc run(device: IrrlichtDevice): bool {.
  5285. header: irr, importcpp: "#.run(@)".}
  5286. The compiler needs to be told to generate C++ (command `cpp`:option:) for
  5287. this to work. The conditional symbol `cpp` is defined when the compiler
  5288. emits C++ code.
  5289. Namespaces
  5290. ~~~~~~~~~~
  5291. The *sloppy interfacing* example uses `.emit` to produce `using namespace`:cpp:
  5292. declarations. It is usually much better to instead refer to the imported name
  5293. via the `namespace::identifier`:cpp: notation:
  5294. .. code-block:: nim
  5295. type
  5296. IrrlichtDeviceObj {.header: irr,
  5297. importcpp: "irr::IrrlichtDevice".} = object
  5298. Importcpp for enums
  5299. ~~~~~~~~~~~~~~~~~~~
  5300. When `importcpp` is applied to an enum type the numerical enum values are
  5301. annotated with the C++ enum type, like in this example:
  5302. `((TheCppEnum)(3))`:cpp:.
  5303. (This turned out to be the simplest way to implement it.)
  5304. Importcpp for procs
  5305. ~~~~~~~~~~~~~~~~~~~
  5306. Note that the `importcpp` variant for procs uses a somewhat cryptic pattern
  5307. language for maximum flexibility:
  5308. - A hash ``#`` symbol is replaced by the first or next argument.
  5309. - A dot following the hash ``#.`` indicates that the call should use C++'s dot
  5310. or arrow notation.
  5311. - An at symbol ``@`` is replaced by the remaining arguments,
  5312. separated by commas.
  5313. For example:
  5314. .. code-block:: nim
  5315. proc cppMethod(this: CppObj, a, b, c: cint) {.importcpp: "#.CppMethod(@)".}
  5316. var x: ptr CppObj
  5317. cppMethod(x[], 1, 2, 3)
  5318. Produces:
  5319. .. code-block:: C
  5320. x->CppMethod(1, 2, 3)
  5321. As a special rule to keep backward compatibility with older versions of the
  5322. `importcpp` pragma, if there is no special pattern
  5323. character (any of ``# ' @``) at all, C++'s
  5324. dot or arrow notation is assumed, so the above example can also be written as:
  5325. .. code-block:: nim
  5326. proc cppMethod(this: CppObj, a, b, c: cint) {.importcpp: "CppMethod".}
  5327. Note that the pattern language naturally also covers C++'s operator overloading
  5328. capabilities:
  5329. .. code-block:: nim
  5330. proc vectorAddition(a, b: Vec3): Vec3 {.importcpp: "# + #".}
  5331. proc dictLookup(a: Dict, k: Key): Value {.importcpp: "#[#]".}
  5332. - An apostrophe ``'`` followed by an integer ``i`` in the range 0..9
  5333. is replaced by the i'th parameter *type*. The 0th position is the result
  5334. type. This can be used to pass types to C++ function templates. Between
  5335. the ``'`` and the digit, an asterisk can be used to get to the base type
  5336. of the type. (So it "takes away a star" from the type; `T*`:c: becomes `T`.)
  5337. Two stars can be used to get to the element type of the element type etc.
  5338. For example:
  5339. .. code-block:: nim
  5340. type Input {.importcpp: "System::Input".} = object
  5341. proc getSubsystem*[T](): ptr T {.importcpp: "SystemManager::getSubsystem<'*0>()", nodecl.}
  5342. let x: ptr Input = getSubsystem[Input]()
  5343. Produces:
  5344. .. code-block:: C
  5345. x = SystemManager::getSubsystem<System::Input>()
  5346. - ``#@`` is a special case to support a `cnew` operation. It is required so
  5347. that the call expression is inlined directly, without going through a
  5348. temporary location. This is only required to circumvent a limitation of the
  5349. current code generator.
  5350. For example C++'s `new`:cpp: operator can be "imported" like this:
  5351. .. code-block:: nim
  5352. proc cnew*[T](x: T): ptr T {.importcpp: "(new '*0#@)", nodecl.}
  5353. # constructor of 'Foo':
  5354. proc constructFoo(a, b: cint): Foo {.importcpp: "Foo(@)".}
  5355. let x = cnew constructFoo(3, 4)
  5356. Produces:
  5357. .. code-block:: C
  5358. x = new Foo(3, 4)
  5359. However, depending on the use case `new Foo`:cpp: can also be wrapped like this
  5360. instead:
  5361. .. code-block:: nim
  5362. proc newFoo(a, b: cint): ptr Foo {.importcpp: "new Foo(@)".}
  5363. let x = newFoo(3, 4)
  5364. Wrapping constructors
  5365. ~~~~~~~~~~~~~~~~~~~~~
  5366. Sometimes a C++ class has a private copy constructor and so code like
  5367. `Class c = Class(1,2);`:cpp: must not be generated but instead
  5368. `Class c(1,2);`:cpp:.
  5369. For this purpose the Nim proc that wraps a C++ constructor needs to be
  5370. annotated with the `constructor`:idx: pragma. This pragma also helps to generate
  5371. faster C++ code since construction then doesn't invoke the copy constructor:
  5372. .. code-block:: nim
  5373. # a better constructor of 'Foo':
  5374. proc constructFoo(a, b: cint): Foo {.importcpp: "Foo(@)", constructor.}
  5375. Wrapping destructors
  5376. ~~~~~~~~~~~~~~~~~~~~
  5377. Since Nim generates C++ directly, any destructor is called implicitly by the
  5378. C++ compiler at the scope exits. This means that often one can get away with
  5379. not wrapping the destructor at all! However, when it needs to be invoked
  5380. explicitly, it needs to be wrapped. The pattern language provides
  5381. everything that is required:
  5382. .. code-block:: nim
  5383. proc destroyFoo(this: var Foo) {.importcpp: "#.~Foo()".}
  5384. Importcpp for objects
  5385. ~~~~~~~~~~~~~~~~~~~~~
  5386. Generic `importcpp`'ed objects are mapped to C++ templates. This means that
  5387. one can import C++'s templates rather easily without the need for a pattern
  5388. language for object types:
  5389. .. code-block:: nim
  5390. :test: "nim cpp $1"
  5391. type
  5392. StdMap[K, V] {.importcpp: "std::map", header: "<map>".} = object
  5393. proc `[]=`[K, V](this: var StdMap[K, V]; key: K; val: V) {.
  5394. importcpp: "#[#] = #", header: "<map>".}
  5395. var x: StdMap[cint, cdouble]
  5396. x[6] = 91.4
  5397. Produces:
  5398. .. code-block:: C
  5399. std::map<int, double> x;
  5400. x[6] = 91.4;
  5401. - If more precise control is needed, the apostrophe `'` can be used in the
  5402. supplied pattern to denote the concrete type parameters of the generic type.
  5403. See the usage of the apostrophe operator in proc patterns for more details.
  5404. .. code-block:: nim
  5405. type
  5406. VectorIterator {.importcpp: "std::vector<'0>::iterator".} [T] = object
  5407. var x: VectorIterator[cint]
  5408. Produces:
  5409. .. code-block:: C
  5410. std::vector<int>::iterator x;
  5411. ImportJs pragma
  5412. ---------------
  5413. Similar to the `importcpp pragma for C++ <#implementation-specific-pragmas-importcpp-pragma>`_,
  5414. the `importjs` pragma can be used to import Javascript methods or
  5415. symbols in general. The generated code then uses the Javascript method
  5416. calling syntax: ``obj.method(arg)``.
  5417. ImportObjC pragma
  5418. -----------------
  5419. Similar to the `importc pragma for C
  5420. <#foreign-function-interface-importc-pragma>`_, the `importobjc` pragma can
  5421. be used to import `Objective C`:idx: methods. The generated code then uses the
  5422. Objective C method calling syntax: ``[obj method param1: arg]``.
  5423. In addition with the `header` and `emit` pragmas this
  5424. allows *sloppy* interfacing with libraries written in Objective C:
  5425. .. code-block:: Nim
  5426. # horrible example of how to interface with GNUStep ...
  5427. {.passL: "-lobjc".}
  5428. {.emit: """
  5429. #include <objc/Object.h>
  5430. @interface Greeter:Object
  5431. {
  5432. }
  5433. - (void)greet:(long)x y:(long)dummy;
  5434. @end
  5435. #include <stdio.h>
  5436. @implementation Greeter
  5437. - (void)greet:(long)x y:(long)dummy
  5438. {
  5439. printf("Hello, World!\n");
  5440. }
  5441. @end
  5442. #include <stdlib.h>
  5443. """.}
  5444. type
  5445. Id {.importc: "id", header: "<objc/Object.h>", final.} = distinct int
  5446. proc newGreeter: Id {.importobjc: "Greeter new", nodecl.}
  5447. proc greet(self: Id, x, y: int) {.importobjc: "greet", nodecl.}
  5448. proc free(self: Id) {.importobjc: "free", nodecl.}
  5449. var g = newGreeter()
  5450. g.greet(12, 34)
  5451. g.free()
  5452. The compiler needs to be told to generate Objective C (command `objc`:option:) for
  5453. this to work. The conditional symbol ``objc`` is defined when the compiler
  5454. emits Objective C code.
  5455. CodegenDecl pragma
  5456. ------------------
  5457. The `codegenDecl` pragma can be used to directly influence Nim's code
  5458. generator. It receives a format string that determines how the variable
  5459. or proc is declared in the generated code.
  5460. For variables, $1 in the format string represents the type of the variable
  5461. and $2 is the name of the variable.
  5462. The following Nim code:
  5463. .. code-block:: nim
  5464. var
  5465. a {.codegenDecl: "$# progmem $#".}: int
  5466. will generate this C code:
  5467. .. code-block:: c
  5468. int progmem a
  5469. For procedures, $1 is the return type of the procedure, $2 is the name of
  5470. the procedure, and $3 is the parameter list.
  5471. The following nim code:
  5472. .. code-block:: nim
  5473. proc myinterrupt() {.codegenDecl: "__interrupt $# $#$#".} =
  5474. echo "realistic interrupt handler"
  5475. will generate this code:
  5476. .. code-block:: c
  5477. __interrupt void myinterrupt()
  5478. `cppNonPod` pragma
  5479. ------------------
  5480. The `.cppNonPod` pragma should be used for non-POD `importcpp` types so that they
  5481. work properly (in particular regarding constructor and destructor) for
  5482. `.threadvar` variables. This requires `--tlsEmulation:off`:option:.
  5483. .. code-block:: nim
  5484. type Foo {.cppNonPod, importcpp, header: "funs.h".} = object
  5485. x: cint
  5486. proc main()=
  5487. var a {.threadvar.}: Foo
  5488. compile-time define pragmas
  5489. ---------------------------
  5490. The pragmas listed here can be used to optionally accept values from
  5491. the `-d/--define`:option: option at compile time.
  5492. The implementation currently provides the following possible options (various
  5493. others may be added later).
  5494. ================= ============================================
  5495. pragma description
  5496. ================= ============================================
  5497. `intdefine`:idx: Reads in a build-time define as an integer
  5498. `strdefine`:idx: Reads in a build-time define as a string
  5499. `booldefine`:idx: Reads in a build-time define as a bool
  5500. ================= ============================================
  5501. .. code-block:: nim
  5502. const FooBar {.intdefine.}: int = 5
  5503. echo FooBar
  5504. .. code:: cmd
  5505. nim c -d:FooBar=42 foobar.nim
  5506. In the above example, providing the `-d`:option: flag causes the symbol
  5507. `FooBar` to be overwritten at compile-time, printing out 42. If the
  5508. `-d:FooBar=42`:option: were to be omitted, the default value of 5 would be
  5509. used. To see if a value was provided, `defined(FooBar)` can be used.
  5510. The syntax `-d:flag`:option: is actually just a shortcut for
  5511. `-d:flag=true`:option:.
  5512. User-defined pragmas
  5513. ====================
  5514. pragma pragma
  5515. -------------
  5516. The `pragma` pragma can be used to declare user-defined pragmas. This is
  5517. useful because Nim's templates and macros do not affect pragmas.
  5518. User-defined pragmas are in a different module-wide scope than all other symbols.
  5519. They cannot be imported from a module.
  5520. Example:
  5521. .. code-block:: nim
  5522. when appType == "lib":
  5523. {.pragma: rtl, exportc, dynlib, cdecl.}
  5524. else:
  5525. {.pragma: rtl, importc, dynlib: "client.dll", cdecl.}
  5526. proc p*(a, b: int): int {.rtl.} =
  5527. result = a+b
  5528. In the example, a new pragma named `rtl` is introduced that either imports
  5529. a symbol from a dynamic library or exports the symbol for dynamic library
  5530. generation.
  5531. Custom annotations
  5532. ------------------
  5533. It is possible to define custom typed pragmas. Custom pragmas do not affect
  5534. code generation directly, but their presence can be detected by macros.
  5535. Custom pragmas are defined using templates annotated with pragma `pragma`:
  5536. .. code-block:: nim
  5537. template dbTable(name: string, table_space: string = "") {.pragma.}
  5538. template dbKey(name: string = "", primary_key: bool = false) {.pragma.}
  5539. template dbForeignKey(t: typedesc) {.pragma.}
  5540. template dbIgnore {.pragma.}
  5541. Consider this stylized example of a possible Object Relation Mapping (ORM)
  5542. implementation:
  5543. .. code-block:: nim
  5544. const tblspace {.strdefine.} = "dev" # switch for dev, test and prod environments
  5545. type
  5546. User {.dbTable("users", tblspace).} = object
  5547. id {.dbKey(primary_key = true).}: int
  5548. name {.dbKey"full_name".}: string
  5549. is_cached {.dbIgnore.}: bool
  5550. age: int
  5551. UserProfile {.dbTable("profiles", tblspace).} = object
  5552. id {.dbKey(primary_key = true).}: int
  5553. user_id {.dbForeignKey: User.}: int
  5554. read_access: bool
  5555. write_access: bool
  5556. admin_acess: bool
  5557. In this example, custom pragmas are used to describe how Nim objects are
  5558. mapped to the schema of the relational database. Custom pragmas can have
  5559. zero or more arguments. In order to pass multiple arguments use one of
  5560. template call syntaxes. All arguments are typed and follow standard
  5561. overload resolution rules for templates. Therefore, it is possible to have
  5562. default values for arguments, pass by name, varargs, etc.
  5563. Custom pragmas can be used in all locations where ordinary pragmas can be
  5564. specified. It is possible to annotate procs, templates, type and variable
  5565. definitions, statements, etc.
  5566. The macros module includes helpers which can be used to simplify custom pragma
  5567. access `hasCustomPragma`, `getCustomPragmaVal`. Please consult the
  5568. `macros <macros.html>`_ module documentation for details. These macros are not
  5569. magic, everything they do can also be achieved by walking the AST of the object
  5570. representation.
  5571. More examples with custom pragmas:
  5572. - Better serialization/deserialization control:
  5573. .. code-block:: nim
  5574. type MyObj = object
  5575. a {.dontSerialize.}: int
  5576. b {.defaultDeserialize: 5.}: int
  5577. c {.serializationKey: "_c".}: string
  5578. - Adopting type for gui inspector in a game engine:
  5579. .. code-block:: nim
  5580. type MyComponent = object
  5581. position {.editable, animatable.}: Vector3
  5582. alpha {.editRange: [0.0..1.0], animatable.}: float32
  5583. Macro pragmas
  5584. -------------
  5585. All macros and templates can also be used as pragmas. They can be attached
  5586. to routines (procs, iterators, etc), type names, or type expressions. The
  5587. compiler will perform the following simple syntactic transformations:
  5588. .. code-block:: nim
  5589. template command(name: string, def: untyped) = discard
  5590. proc p() {.command("print").} = discard
  5591. This is translated to:
  5592. .. code-block:: nim
  5593. command("print"):
  5594. proc p() = discard
  5595. ------
  5596. .. code-block:: nim
  5597. type
  5598. AsyncEventHandler = proc (x: Event) {.async.}
  5599. This is translated to:
  5600. .. code-block:: nim
  5601. type
  5602. AsyncEventHandler = async(proc (x: Event))
  5603. ------
  5604. .. code-block:: nim
  5605. type
  5606. MyObject {.schema: "schema.protobuf".} = object
  5607. This is translated to a call to the `schema` macro with a `nnkTypeDef`
  5608. AST node capturing both the left-hand side and right-hand side of the
  5609. definition. The macro can return a potentially modified `nnkTypeDef` tree
  5610. which will replace the original row in the type section.
  5611. When multiple macro pragmas are applied to the same definition, the
  5612. compiler will apply them consequently from left to right. Each macro
  5613. will receive as input the output of the previous one.
  5614. Foreign function interface
  5615. ==========================
  5616. Nim's `FFI`:idx: (foreign function interface) is extensive and only the
  5617. parts that scale to other future backends (like the LLVM/JavaScript backends)
  5618. are documented here.
  5619. Importc pragma
  5620. --------------
  5621. The `importc` pragma provides a means to import a proc or a variable
  5622. from C. The optional argument is a string containing the C identifier. If
  5623. the argument is missing, the C name is the Nim identifier *exactly as
  5624. spelled*:
  5625. .. code-block::
  5626. proc printf(formatstr: cstring) {.header: "<stdio.h>", importc: "printf", varargs.}
  5627. When `importc` is applied to a `let` statement it can omit its value which
  5628. will then be expected to come from C. This can be used to import a C `const`:c:\:
  5629. .. code-block::
  5630. {.emit: "const int cconst = 42;".}
  5631. let cconst {.importc, nodecl.}: cint
  5632. assert cconst == 42
  5633. Note that this pragma has been abused in the past to also work in the
  5634. JS backend for JS objects and functions. Other backends do provide
  5635. the same feature under the same name. Also, when the target language
  5636. is not set to C, other pragmas are available:
  5637. * `importcpp <manual.html#implementation-specific-pragmas-importcpp-pragma>`_
  5638. * `importobjc <manual.html#implementation-specific-pragmas-importobjc-pragma>`_
  5639. * `importjs <manual.html#implementation-specific-pragmas-importjs-pragma>`_
  5640. .. code-block:: Nim
  5641. proc p(s: cstring) {.importc: "prefix$1".}
  5642. In the example, the external name of `p` is set to `prefixp`. Only ``$1``
  5643. is available and a literal dollar sign must be written as ``$$``.
  5644. Exportc pragma
  5645. --------------
  5646. The `exportc` pragma provides a means to export a type, a variable, or a
  5647. procedure to C. Enums and constants can't be exported. The optional argument
  5648. is a string containing the C identifier. If the argument is missing, the C
  5649. name is the Nim identifier *exactly as spelled*:
  5650. .. code-block:: Nim
  5651. proc callme(formatstr: cstring) {.exportc: "callMe", varargs.}
  5652. Note that this pragma is somewhat of a misnomer: Other backends do provide
  5653. the same feature under the same name.
  5654. The string literal passed to `exportc` can be a format string:
  5655. .. code-block:: Nim
  5656. proc p(s: string) {.exportc: "prefix$1".} =
  5657. echo s
  5658. In the example, the external name of `p` is set to `prefixp`. Only ``$1``
  5659. is available and a literal dollar sign must be written as ``$$``.
  5660. If the symbol should also be exported to a dynamic library, the `dynlib`
  5661. pragma should be used in addition to the `exportc` pragma. See
  5662. `Dynlib pragma for export <#foreign-function-interface-dynlib-pragma-for-export>`_.
  5663. Extern pragma
  5664. -------------
  5665. Like `exportc` or `importc`, the `extern` pragma affects name
  5666. mangling. The string literal passed to `extern` can be a format string:
  5667. .. code-block:: Nim
  5668. proc p(s: string) {.extern: "prefix$1".} =
  5669. echo s
  5670. In the example, the external name of `p` is set to `prefixp`. Only ``$1``
  5671. is available and a literal dollar sign must be written as ``$$``.
  5672. Bycopy pragma
  5673. -------------
  5674. The `bycopy` pragma can be applied to an object or tuple type and
  5675. instructs the compiler to pass the type by value to procs:
  5676. .. code-block:: nim
  5677. type
  5678. Vector {.bycopy.} = object
  5679. x, y, z: float
  5680. Byref pragma
  5681. ------------
  5682. The `byref` pragma can be applied to an object or tuple type and instructs
  5683. the compiler to pass the type by reference (hidden pointer) to procs.
  5684. Varargs pragma
  5685. --------------
  5686. The `varargs` pragma can be applied to procedures only (and procedure
  5687. types). It tells Nim that the proc can take a variable number of parameters
  5688. after the last specified parameter. Nim string values will be converted to C
  5689. strings automatically:
  5690. .. code-block:: Nim
  5691. proc printf(formatstr: cstring) {.nodecl, varargs.}
  5692. printf("hallo %s", "world") # "world" will be passed as C string
  5693. Union pragma
  5694. ------------
  5695. The `union` pragma can be applied to any `object` type. It means all
  5696. of the object's fields are overlaid in memory. This produces a `union`:c:
  5697. instead of a `struct`:c: in the generated C/C++ code. The object declaration
  5698. then must not use inheritance or any GC'ed memory but this is currently not
  5699. checked.
  5700. **Future directions**: GC'ed memory should be allowed in unions and the GC
  5701. should scan unions conservatively.
  5702. Packed pragma
  5703. -------------
  5704. The `packed` pragma can be applied to any `object` type. It ensures
  5705. that the fields of an object are packed back-to-back in memory. It is useful
  5706. to store packets or messages from/to network or hardware drivers, and for
  5707. interoperability with C. Combining packed pragma with inheritance is not
  5708. defined, and it should not be used with GC'ed memory (ref's).
  5709. **Future directions**: Using GC'ed memory in packed pragma will result in
  5710. a static error. Usage with inheritance should be defined and documented.
  5711. Dynlib pragma for import
  5712. ------------------------
  5713. With the `dynlib` pragma, a procedure or a variable can be imported from
  5714. a dynamic library (``.dll`` files for Windows, ``lib*.so`` files for UNIX).
  5715. The non-optional argument has to be the name of the dynamic library:
  5716. .. code-block:: Nim
  5717. proc gtk_image_new(): PGtkWidget
  5718. {.cdecl, dynlib: "libgtk-x11-2.0.so", importc.}
  5719. In general, importing a dynamic library does not require any special linker
  5720. options or linking with import libraries. This also implies that no *devel*
  5721. packages need to be installed.
  5722. The `dynlib` import mechanism supports a versioning scheme:
  5723. .. code-block:: nim
  5724. proc Tcl_Eval(interp: pTcl_Interp, script: cstring): int {.cdecl,
  5725. importc, dynlib: "libtcl(|8.5|8.4|8.3).so.(1|0)".}
  5726. At runtime, the dynamic library is searched for (in this order)::
  5727. libtcl.so.1
  5728. libtcl.so.0
  5729. libtcl8.5.so.1
  5730. libtcl8.5.so.0
  5731. libtcl8.4.so.1
  5732. libtcl8.4.so.0
  5733. libtcl8.3.so.1
  5734. libtcl8.3.so.0
  5735. The `dynlib` pragma supports not only constant strings as an argument but also
  5736. string expressions in general:
  5737. .. code-block:: nim
  5738. import std/os
  5739. proc getDllName: string =
  5740. result = "mylib.dll"
  5741. if fileExists(result): return
  5742. result = "mylib2.dll"
  5743. if fileExists(result): return
  5744. quit("could not load dynamic library")
  5745. proc myImport(s: cstring) {.cdecl, importc, dynlib: getDllName().}
  5746. **Note**: Patterns like ``libtcl(|8.5|8.4).so`` are only supported in constant
  5747. strings, because they are precompiled.
  5748. **Note**: Passing variables to the `dynlib` pragma will fail at runtime
  5749. because of order of initialization problems.
  5750. **Note**: A `dynlib` import can be overridden with
  5751. the `--dynlibOverride:name`:option: command-line option. The
  5752. `Compiler User Guide <nimc.html>`_ contains further information.
  5753. Dynlib pragma for export
  5754. ------------------------
  5755. With the `dynlib` pragma, a procedure can also be exported to
  5756. a dynamic library. The pragma then has no argument and has to be used in
  5757. conjunction with the `exportc` pragma:
  5758. .. code-block:: Nim
  5759. proc exportme(): int {.cdecl, exportc, dynlib.}
  5760. This is only useful if the program is compiled as a dynamic library via the
  5761. `--app:lib`:option: command-line option.
  5762. Threads
  5763. =======
  5764. To enable thread support the `--threads:on`:option: command-line switch needs to
  5765. be used. The system_ module then contains several threading primitives.
  5766. See the `channels <channels_builtin.html>`_ modules
  5767. for the low-level thread API. There are also high-level parallelism constructs
  5768. available. See `spawn <manual_experimental.html#parallel-amp-spawn>`_ for
  5769. further details.
  5770. Nim's memory model for threads is quite different than that of other common
  5771. programming languages (C, Pascal, Java): Each thread has its own (garbage
  5772. collected) heap, and sharing of memory is restricted to global variables. This
  5773. helps to prevent race conditions. GC efficiency is improved quite a lot,
  5774. because the GC never has to stop other threads and see what they reference.
  5775. The only way to create a thread is via `spawn` or
  5776. `createThread`. The invoked proc must not use `var` parameters nor must
  5777. any of its parameters contain a `ref` or `closure` type. This enforces
  5778. the *no heap sharing restriction*.
  5779. Thread pragma
  5780. -------------
  5781. A proc that is executed as a new thread of execution should be marked by the
  5782. `thread` pragma for reasons of readability. The compiler checks for
  5783. violations of the `no heap sharing restriction`:idx:\: This restriction implies
  5784. that it is invalid to construct a data structure that consists of memory
  5785. allocated from different (thread-local) heaps.
  5786. A thread proc is passed to `createThread` or `spawn` and invoked
  5787. indirectly; so the `thread` pragma implies `procvar`.
  5788. Threadvar pragma
  5789. ----------------
  5790. A variable can be marked with the `threadvar` pragma, which makes it a
  5791. `thread-local`:idx: variable; Additionally, this implies all the effects
  5792. of the `global` pragma.
  5793. .. code-block:: nim
  5794. var checkpoints* {.threadvar.}: seq[string]
  5795. Due to implementation restrictions, thread-local variables cannot be
  5796. initialized within the `var` section. (Every thread-local variable needs to
  5797. be replicated at thread creation.)
  5798. Threads and exceptions
  5799. ----------------------
  5800. The interaction between threads and exceptions is simple: A *handled* exception
  5801. in one thread cannot affect any other thread. However, an *unhandled* exception
  5802. in one thread terminates the whole *process*.