manual.rst 233 KB

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