manual.rst 230 KB

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