manual.rst 251 KB

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