manual.rst 244 KB

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