manual.rst 237 KB

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