manual.rst 226 KB

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