manual.rst 233 KB

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