manual.rst 241 KB

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