manual.rst 230 KB

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