parser.cpp 185 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439
  1. #include "parser_pos.cpp"
  2. gb_internal u64 ast_file_vet_flags(AstFile *f) {
  3. if (f != nullptr && f->vet_flags_set) {
  4. return f->vet_flags;
  5. }
  6. return build_context.vet_flags;
  7. }
  8. gb_internal bool ast_file_vet_style(AstFile *f) {
  9. return (ast_file_vet_flags(f) & VetFlag_Style) != 0;
  10. }
  11. gb_internal bool file_allow_newline(AstFile *f) {
  12. bool is_strict = build_context.strict_style || ast_file_vet_style(f);
  13. return !is_strict;
  14. }
  15. gb_internal Token token_end_of_line(AstFile *f, Token tok) {
  16. u8 const *start = f->tokenizer.start + tok.pos.offset;
  17. u8 const *s = start;
  18. while (*s && *s != '\n' && s < f->tokenizer.end) {
  19. s += 1;
  20. }
  21. tok.pos.column += cast(i32)(s - start) - 1;
  22. return tok;
  23. }
  24. gb_internal gbString get_file_line_as_string(TokenPos const &pos, i32 *offset_) {
  25. AstFile *file = thread_safe_get_ast_file_from_id(pos.file_id);
  26. if (file == nullptr) {
  27. return nullptr;
  28. }
  29. isize offset = pos.offset;
  30. u8 *start = file->tokenizer.start;
  31. u8 *end = file->tokenizer.end;
  32. if (start == end) {
  33. return nullptr;
  34. }
  35. isize len = end-start;
  36. if (len < offset) {
  37. return nullptr;
  38. }
  39. u8 *pos_offset = start+offset;
  40. u8 *line_start = pos_offset;
  41. u8 *line_end = pos_offset;
  42. while (line_start >= start) {
  43. if (*line_start == '\n') {
  44. line_start += 1;
  45. break;
  46. }
  47. line_start -= 1;
  48. }
  49. while (line_end < end) {
  50. if (*line_end == '\n') {
  51. break;
  52. }
  53. line_end += 1;
  54. }
  55. String the_line = make_string(line_start, line_end-line_start);
  56. the_line = string_trim_whitespace(the_line);
  57. if (offset_) *offset_ = cast(i32)(pos_offset - the_line.text);
  58. return gb_string_make_length(heap_allocator(), the_line.text, the_line.len);
  59. }
  60. gb_internal isize ast_node_size(AstKind kind) {
  61. return align_formula_isize(gb_size_of(AstCommonStuff) + ast_variant_sizes[kind], gb_align_of(void *));
  62. }
  63. gb_global std::atomic<isize> global_total_node_memory_allocated;
  64. // NOTE(bill): And this below is why is I/we need a new language! Discriminated unions are a pain in C/C++
  65. gb_internal Ast *alloc_ast_node(AstFile *f, AstKind kind) {
  66. isize size = ast_node_size(kind);
  67. Ast *node = cast(Ast *)arena_alloc(&global_thread_local_ast_arena, size, 16);
  68. node->kind = kind;
  69. node->file_id = f ? f->id : 0;
  70. global_total_node_memory_allocated.fetch_add(size);
  71. return node;
  72. }
  73. gb_internal Ast *clone_ast(Ast *node, AstFile *f = nullptr);
  74. gb_internal Array<Ast *> clone_ast_array(Array<Ast *> const &array, AstFile *f) {
  75. Array<Ast *> result = {};
  76. if (array.count > 0) {
  77. result = array_make<Ast *>(ast_allocator(nullptr), array.count);
  78. for_array(i, array) {
  79. result[i] = clone_ast(array[i], f);
  80. }
  81. }
  82. return result;
  83. }
  84. gb_internal Slice<Ast *> clone_ast_array(Slice<Ast *> const &array, AstFile *f) {
  85. Slice<Ast *> result = {};
  86. if (array.count > 0) {
  87. result = slice_clone(ast_allocator(nullptr), array);
  88. for_array(i, array) {
  89. result[i] = clone_ast(array[i], f);
  90. }
  91. }
  92. return result;
  93. }
  94. gb_internal Ast *clone_ast(Ast *node, AstFile *f) {
  95. if (node == nullptr) {
  96. return nullptr;
  97. }
  98. if (f == nullptr) {
  99. f = node->thread_safe_file();
  100. }
  101. Ast *n = alloc_ast_node(f, node->kind);
  102. gb_memmove(n, node, ast_node_size(node->kind));
  103. switch (n->kind) {
  104. default: GB_PANIC("Unhandled Ast %.*s", LIT(ast_strings[n->kind])); break;
  105. case Ast_Invalid: break;
  106. case Ast_Ident:
  107. n->Ident.entity = nullptr;
  108. break;
  109. case Ast_Implicit: break;
  110. case Ast_Uninit: break;
  111. case Ast_BasicLit: break;
  112. case Ast_BasicDirective: break;
  113. case Ast_PolyType:
  114. n->PolyType.type = clone_ast(n->PolyType.type, f);
  115. n->PolyType.specialization = clone_ast(n->PolyType.specialization, f);
  116. break;
  117. case Ast_Ellipsis:
  118. n->Ellipsis.expr = clone_ast(n->Ellipsis.expr, f);
  119. break;
  120. case Ast_ProcGroup:
  121. n->ProcGroup.args = clone_ast_array(n->ProcGroup.args, f);
  122. break;
  123. case Ast_ProcLit:
  124. n->ProcLit.type = clone_ast(n->ProcLit.type, f);
  125. n->ProcLit.body = clone_ast(n->ProcLit.body, f);
  126. n->ProcLit.where_clauses = clone_ast_array(n->ProcLit.where_clauses, f);
  127. break;
  128. case Ast_CompoundLit:
  129. n->CompoundLit.type = clone_ast(n->CompoundLit.type, f);
  130. n->CompoundLit.elems = clone_ast_array(n->CompoundLit.elems, f);
  131. break;
  132. case Ast_BadExpr: break;
  133. case Ast_TagExpr:
  134. n->TagExpr.expr = clone_ast(n->TagExpr.expr, f);
  135. break;
  136. case Ast_UnaryExpr:
  137. n->UnaryExpr.expr = clone_ast(n->UnaryExpr.expr, f);
  138. break;
  139. case Ast_BinaryExpr:
  140. n->BinaryExpr.left = clone_ast(n->BinaryExpr.left, f);
  141. n->BinaryExpr.right = clone_ast(n->BinaryExpr.right, f);
  142. break;
  143. case Ast_ParenExpr:
  144. n->ParenExpr.expr = clone_ast(n->ParenExpr.expr, f);
  145. break;
  146. case Ast_SelectorExpr:
  147. n->SelectorExpr.expr = clone_ast(n->SelectorExpr.expr, f);
  148. n->SelectorExpr.selector = clone_ast(n->SelectorExpr.selector, f);
  149. break;
  150. case Ast_ImplicitSelectorExpr:
  151. n->ImplicitSelectorExpr.selector = clone_ast(n->ImplicitSelectorExpr.selector, f);
  152. break;
  153. case Ast_SelectorCallExpr:
  154. n->SelectorCallExpr.expr = clone_ast(n->SelectorCallExpr.expr, f);
  155. n->SelectorCallExpr.call = clone_ast(n->SelectorCallExpr.call, f);
  156. break;
  157. case Ast_IndexExpr:
  158. n->IndexExpr.expr = clone_ast(n->IndexExpr.expr, f);
  159. n->IndexExpr.index = clone_ast(n->IndexExpr.index, f);
  160. break;
  161. case Ast_MatrixIndexExpr:
  162. n->MatrixIndexExpr.expr = clone_ast(n->MatrixIndexExpr.expr, f);
  163. n->MatrixIndexExpr.row_index = clone_ast(n->MatrixIndexExpr.row_index, f);
  164. n->MatrixIndexExpr.column_index = clone_ast(n->MatrixIndexExpr.column_index, f);
  165. break;
  166. case Ast_DerefExpr:
  167. n->DerefExpr.expr = clone_ast(n->DerefExpr.expr, f);
  168. break;
  169. case Ast_SliceExpr:
  170. n->SliceExpr.expr = clone_ast(n->SliceExpr.expr, f);
  171. n->SliceExpr.low = clone_ast(n->SliceExpr.low, f);
  172. n->SliceExpr.high = clone_ast(n->SliceExpr.high, f);
  173. break;
  174. case Ast_CallExpr:
  175. n->CallExpr.proc = clone_ast(n->CallExpr.proc, f);
  176. n->CallExpr.args = clone_ast_array(n->CallExpr.args, f);
  177. break;
  178. case Ast_FieldValue:
  179. n->FieldValue.field = clone_ast(n->FieldValue.field, f);
  180. n->FieldValue.value = clone_ast(n->FieldValue.value, f);
  181. break;
  182. case Ast_EnumFieldValue:
  183. n->EnumFieldValue.name = clone_ast(n->EnumFieldValue.name, f);
  184. n->EnumFieldValue.value = clone_ast(n->EnumFieldValue.value, f);
  185. break;
  186. case Ast_TernaryIfExpr:
  187. n->TernaryIfExpr.x = clone_ast(n->TernaryIfExpr.x, f);
  188. n->TernaryIfExpr.cond = clone_ast(n->TernaryIfExpr.cond, f);
  189. n->TernaryIfExpr.y = clone_ast(n->TernaryIfExpr.y, f);
  190. break;
  191. case Ast_TernaryWhenExpr:
  192. n->TernaryWhenExpr.x = clone_ast(n->TernaryWhenExpr.x, f);
  193. n->TernaryWhenExpr.cond = clone_ast(n->TernaryWhenExpr.cond, f);
  194. n->TernaryWhenExpr.y = clone_ast(n->TernaryWhenExpr.y, f);
  195. break;
  196. case Ast_OrElseExpr:
  197. n->OrElseExpr.x = clone_ast(n->OrElseExpr.x, f);
  198. n->OrElseExpr.y = clone_ast(n->OrElseExpr.y, f);
  199. break;
  200. case Ast_OrReturnExpr:
  201. n->OrReturnExpr.expr = clone_ast(n->OrReturnExpr.expr, f);
  202. break;
  203. case Ast_OrBranchExpr:
  204. n->OrBranchExpr.label = clone_ast(n->OrBranchExpr.label, f);
  205. n->OrBranchExpr.expr = clone_ast(n->OrBranchExpr.expr, f);
  206. break;
  207. case Ast_TypeAssertion:
  208. n->TypeAssertion.expr = clone_ast(n->TypeAssertion.expr, f);
  209. n->TypeAssertion.type = clone_ast(n->TypeAssertion.type, f);
  210. break;
  211. case Ast_TypeCast:
  212. n->TypeCast.type = clone_ast(n->TypeCast.type, f);
  213. n->TypeCast.expr = clone_ast(n->TypeCast.expr, f);
  214. break;
  215. case Ast_AutoCast:
  216. n->AutoCast.expr = clone_ast(n->AutoCast.expr, f);
  217. break;
  218. case Ast_InlineAsmExpr:
  219. n->InlineAsmExpr.param_types = clone_ast_array(n->InlineAsmExpr.param_types, f);
  220. n->InlineAsmExpr.return_type = clone_ast(n->InlineAsmExpr.return_type, f);
  221. n->InlineAsmExpr.asm_string = clone_ast(n->InlineAsmExpr.asm_string, f);
  222. n->InlineAsmExpr.constraints_string = clone_ast(n->InlineAsmExpr.constraints_string, f);
  223. break;
  224. case Ast_BadStmt: break;
  225. case Ast_EmptyStmt: break;
  226. case Ast_ExprStmt:
  227. n->ExprStmt.expr = clone_ast(n->ExprStmt.expr, f);
  228. break;
  229. case Ast_AssignStmt:
  230. n->AssignStmt.lhs = clone_ast_array(n->AssignStmt.lhs, f);
  231. n->AssignStmt.rhs = clone_ast_array(n->AssignStmt.rhs, f);
  232. break;
  233. case Ast_BlockStmt:
  234. n->BlockStmt.label = clone_ast(n->BlockStmt.label, f);
  235. n->BlockStmt.stmts = clone_ast_array(n->BlockStmt.stmts, f);
  236. break;
  237. case Ast_IfStmt:
  238. n->IfStmt.label = clone_ast(n->IfStmt.label, f);
  239. n->IfStmt.init = clone_ast(n->IfStmt.init, f);
  240. n->IfStmt.cond = clone_ast(n->IfStmt.cond, f);
  241. n->IfStmt.body = clone_ast(n->IfStmt.body, f);
  242. n->IfStmt.else_stmt = clone_ast(n->IfStmt.else_stmt, f);
  243. break;
  244. case Ast_WhenStmt:
  245. n->WhenStmt.cond = clone_ast(n->WhenStmt.cond, f);
  246. n->WhenStmt.body = clone_ast(n->WhenStmt.body, f);
  247. n->WhenStmt.else_stmt = clone_ast(n->WhenStmt.else_stmt, f);
  248. break;
  249. case Ast_ReturnStmt:
  250. n->ReturnStmt.results = clone_ast_array(n->ReturnStmt.results, f);
  251. break;
  252. case Ast_ForStmt:
  253. n->ForStmt.label = clone_ast(n->ForStmt.label, f);
  254. n->ForStmt.init = clone_ast(n->ForStmt.init, f);
  255. n->ForStmt.cond = clone_ast(n->ForStmt.cond, f);
  256. n->ForStmt.post = clone_ast(n->ForStmt.post, f);
  257. n->ForStmt.body = clone_ast(n->ForStmt.body, f);
  258. break;
  259. case Ast_RangeStmt:
  260. n->RangeStmt.label = clone_ast(n->RangeStmt.label, f);
  261. n->RangeStmt.vals = clone_ast_array(n->RangeStmt.vals, f);
  262. n->RangeStmt.expr = clone_ast(n->RangeStmt.expr, f);
  263. n->RangeStmt.body = clone_ast(n->RangeStmt.body, f);
  264. break;
  265. case Ast_UnrollRangeStmt:
  266. n->UnrollRangeStmt.val0 = clone_ast(n->UnrollRangeStmt.val0, f);
  267. n->UnrollRangeStmt.val1 = clone_ast(n->UnrollRangeStmt.val1, f);
  268. n->UnrollRangeStmt.expr = clone_ast(n->UnrollRangeStmt.expr, f);
  269. n->UnrollRangeStmt.body = clone_ast(n->UnrollRangeStmt.body, f);
  270. break;
  271. case Ast_CaseClause:
  272. n->CaseClause.list = clone_ast_array(n->CaseClause.list, f);
  273. n->CaseClause.stmts = clone_ast_array(n->CaseClause.stmts, f);
  274. n->CaseClause.implicit_entity = nullptr;
  275. break;
  276. case Ast_SwitchStmt:
  277. n->SwitchStmt.label = clone_ast(n->SwitchStmt.label, f);
  278. n->SwitchStmt.init = clone_ast(n->SwitchStmt.init, f);
  279. n->SwitchStmt.tag = clone_ast(n->SwitchStmt.tag, f);
  280. n->SwitchStmt.body = clone_ast(n->SwitchStmt.body, f);
  281. break;
  282. case Ast_TypeSwitchStmt:
  283. n->TypeSwitchStmt.label = clone_ast(n->TypeSwitchStmt.label, f);
  284. n->TypeSwitchStmt.tag = clone_ast(n->TypeSwitchStmt.tag, f);
  285. n->TypeSwitchStmt.body = clone_ast(n->TypeSwitchStmt.body, f);
  286. break;
  287. case Ast_DeferStmt:
  288. n->DeferStmt.stmt = clone_ast(n->DeferStmt.stmt, f);
  289. break;
  290. case Ast_BranchStmt:
  291. n->BranchStmt.label = clone_ast(n->BranchStmt.label, f);
  292. break;
  293. case Ast_UsingStmt:
  294. n->UsingStmt.list = clone_ast_array(n->UsingStmt.list, f);
  295. break;
  296. case Ast_BadDecl: break;
  297. case Ast_ForeignBlockDecl:
  298. n->ForeignBlockDecl.foreign_library = clone_ast(n->ForeignBlockDecl.foreign_library, f);
  299. n->ForeignBlockDecl.body = clone_ast(n->ForeignBlockDecl.body, f);
  300. n->ForeignBlockDecl.attributes = clone_ast_array(n->ForeignBlockDecl.attributes, f);
  301. break;
  302. case Ast_Label:
  303. n->Label.name = clone_ast(n->Label.name, f);
  304. break;
  305. case Ast_ValueDecl:
  306. n->ValueDecl.names = clone_ast_array(n->ValueDecl.names, f);
  307. n->ValueDecl.type = clone_ast(n->ValueDecl.type, f);
  308. n->ValueDecl.values = clone_ast_array(n->ValueDecl.values, f);
  309. n->ValueDecl.attributes = clone_ast_array(n->ValueDecl.attributes, f);
  310. break;
  311. case Ast_Attribute:
  312. n->Attribute.elems = clone_ast_array(n->Attribute.elems, f);
  313. break;
  314. case Ast_Field:
  315. n->Field.names = clone_ast_array(n->Field.names, f);
  316. n->Field.type = clone_ast(n->Field.type, f);
  317. break;
  318. case Ast_BitFieldField:
  319. n->BitFieldField.name = clone_ast(n->BitFieldField.name, f);
  320. n->BitFieldField.type = clone_ast(n->BitFieldField.type, f);
  321. n->BitFieldField.bit_size = clone_ast(n->BitFieldField.bit_size, f);
  322. break;
  323. case Ast_FieldList:
  324. n->FieldList.list = clone_ast_array(n->FieldList.list, f);
  325. break;
  326. case Ast_TypeidType:
  327. n->TypeidType.specialization = clone_ast(n->TypeidType.specialization, f);
  328. break;
  329. case Ast_HelperType:
  330. n->HelperType.type = clone_ast(n->HelperType.type, f);
  331. break;
  332. case Ast_DistinctType:
  333. n->DistinctType.type = clone_ast(n->DistinctType.type, f);
  334. break;
  335. case Ast_ProcType:
  336. n->ProcType.params = clone_ast(n->ProcType.params, f);
  337. n->ProcType.results = clone_ast(n->ProcType.results, f);
  338. break;
  339. case Ast_RelativeType:
  340. n->RelativeType.tag = clone_ast(n->RelativeType.tag, f);
  341. n->RelativeType.type = clone_ast(n->RelativeType.type, f);
  342. break;
  343. case Ast_PointerType:
  344. n->PointerType.type = clone_ast(n->PointerType.type, f);
  345. n->PointerType.tag = clone_ast(n->PointerType.tag, f);
  346. break;
  347. case Ast_MultiPointerType:
  348. n->MultiPointerType.type = clone_ast(n->MultiPointerType.type, f);
  349. break;
  350. case Ast_ArrayType:
  351. n->ArrayType.count = clone_ast(n->ArrayType.count, f);
  352. n->ArrayType.elem = clone_ast(n->ArrayType.elem, f);
  353. n->ArrayType.tag = clone_ast(n->ArrayType.tag, f);
  354. break;
  355. case Ast_DynamicArrayType:
  356. n->DynamicArrayType.elem = clone_ast(n->DynamicArrayType.elem, f);
  357. break;
  358. case Ast_StructType:
  359. n->StructType.fields = clone_ast_array(n->StructType.fields, f);
  360. n->StructType.polymorphic_params = clone_ast(n->StructType.polymorphic_params, f);
  361. n->StructType.align = clone_ast(n->StructType.align, f);
  362. n->StructType.field_align = clone_ast(n->StructType.field_align, f);
  363. n->StructType.where_clauses = clone_ast_array(n->StructType.where_clauses, f);
  364. break;
  365. case Ast_UnionType:
  366. n->UnionType.variants = clone_ast_array(n->UnionType.variants, f);
  367. n->UnionType.polymorphic_params = clone_ast(n->UnionType.polymorphic_params, f);
  368. n->UnionType.where_clauses = clone_ast_array(n->UnionType.where_clauses, f);
  369. break;
  370. case Ast_EnumType:
  371. n->EnumType.base_type = clone_ast(n->EnumType.base_type, f);
  372. n->EnumType.fields = clone_ast_array(n->EnumType.fields, f);
  373. break;
  374. case Ast_BitSetType:
  375. n->BitSetType.elem = clone_ast(n->BitSetType.elem, f);
  376. n->BitSetType.underlying = clone_ast(n->BitSetType.underlying, f);
  377. break;
  378. case Ast_BitFieldType:
  379. n->BitFieldType.backing_type = clone_ast(n->BitFieldType.backing_type, f);
  380. n->BitFieldType.fields = clone_ast_array(n->BitFieldType.fields, f);
  381. break;
  382. case Ast_MapType:
  383. n->MapType.count = clone_ast(n->MapType.count, f);
  384. n->MapType.key = clone_ast(n->MapType.key, f);
  385. n->MapType.value = clone_ast(n->MapType.value, f);
  386. break;
  387. case Ast_MatrixType:
  388. n->MatrixType.row_count = clone_ast(n->MatrixType.row_count, f);
  389. n->MatrixType.column_count = clone_ast(n->MatrixType.column_count, f);
  390. n->MatrixType.elem = clone_ast(n->MatrixType.elem, f);
  391. break;
  392. }
  393. return n;
  394. }
  395. gb_internal void error(Ast *node, char const *fmt, ...) {
  396. Token token = {};
  397. TokenPos end_pos = {};
  398. if (node != nullptr) {
  399. token = ast_token(node);
  400. end_pos = ast_end_pos(node);
  401. }
  402. va_list va;
  403. va_start(va, fmt);
  404. error_va(token.pos, end_pos, fmt, va);
  405. va_end(va);
  406. if (node != nullptr && node->file_id != 0) {
  407. AstFile *f = node->thread_safe_file();
  408. f->error_count += 1;
  409. }
  410. }
  411. gb_internal void syntax_error_with_verbose(Ast *node, char const *fmt, ...) {
  412. Token token = {};
  413. TokenPos end_pos = {};
  414. if (node != nullptr) {
  415. token = ast_token(node);
  416. end_pos = ast_end_pos(node);
  417. }
  418. va_list va;
  419. va_start(va, fmt);
  420. syntax_error_with_verbose_va(token.pos, end_pos, fmt, va);
  421. va_end(va);
  422. if (node != nullptr && node->file_id != 0) {
  423. AstFile *f = node->thread_safe_file();
  424. f->error_count += 1;
  425. }
  426. }
  427. gb_internal void error_no_newline(Ast *node, char const *fmt, ...) {
  428. Token token = {};
  429. if (node != nullptr) {
  430. token = ast_token(node);
  431. }
  432. va_list va;
  433. va_start(va, fmt);
  434. error_no_newline_va(token.pos, fmt, va);
  435. va_end(va);
  436. if (node != nullptr && node->file_id != 0) {
  437. AstFile *f = node->thread_safe_file();
  438. f->error_count += 1;
  439. }
  440. }
  441. gb_internal void warning(Ast *node, char const *fmt, ...) {
  442. Token token = {};
  443. TokenPos end_pos = {};
  444. if (node != nullptr) {
  445. token = ast_token(node);
  446. end_pos = ast_end_pos(node);
  447. }
  448. va_list va;
  449. va_start(va, fmt);
  450. warning_va(token.pos, end_pos, fmt, va);
  451. va_end(va);
  452. }
  453. gb_internal void syntax_error(Ast *node, char const *fmt, ...) {
  454. Token token = {};
  455. TokenPos end_pos = {};
  456. if (node != nullptr) {
  457. token = ast_token(node);
  458. end_pos = ast_end_pos(node);
  459. }
  460. va_list va;
  461. va_start(va, fmt);
  462. syntax_error_va(token.pos, end_pos, fmt, va);
  463. va_end(va);
  464. if (node != nullptr && node->file_id != 0) {
  465. AstFile *f = node->thread_safe_file();
  466. f->error_count += 1;
  467. }
  468. }
  469. gb_internal bool ast_node_expect(Ast *node, AstKind kind) {
  470. if (node->kind != kind) {
  471. syntax_error(node, "Expected %.*s, got %.*s", LIT(ast_strings[kind]), LIT(ast_strings[node->kind]));
  472. return false;
  473. }
  474. return true;
  475. }
  476. gb_internal bool ast_node_expect2(Ast *node, AstKind kind0, AstKind kind1) {
  477. if (node->kind != kind0 && node->kind != kind1) {
  478. syntax_error(node, "Expected %.*s or %.*s, got %.*s", LIT(ast_strings[kind0]), LIT(ast_strings[kind1]), LIT(ast_strings[node->kind]));
  479. return false;
  480. }
  481. return true;
  482. }
  483. gb_internal Ast *ast_bad_expr(AstFile *f, Token begin, Token end) {
  484. Ast *result = alloc_ast_node(f, Ast_BadExpr);
  485. result->BadExpr.begin = begin;
  486. result->BadExpr.end = end;
  487. return result;
  488. }
  489. gb_internal Ast *ast_tag_expr(AstFile *f, Token token, Token name, Ast *expr) {
  490. Ast *result = alloc_ast_node(f, Ast_TagExpr);
  491. result->TagExpr.token = token;
  492. result->TagExpr.name = name;
  493. result->TagExpr.expr = expr;
  494. return result;
  495. }
  496. gb_internal Ast *ast_unary_expr(AstFile *f, Token op, Ast *expr) {
  497. Ast *result = alloc_ast_node(f, Ast_UnaryExpr);
  498. if (expr) switch (expr->kind) {
  499. case Ast_OrReturnExpr:
  500. syntax_error_with_verbose(expr, "'or_return' within an unary expression not wrapped in parentheses (...)");
  501. break;
  502. case Ast_OrBranchExpr:
  503. syntax_error_with_verbose(expr, "'or_%.*s' within an unary expression not wrapped in parentheses (...)", LIT(expr->OrBranchExpr.token.string));
  504. break;
  505. }
  506. result->UnaryExpr.op = op;
  507. result->UnaryExpr.expr = expr;
  508. return result;
  509. }
  510. gb_internal Ast *ast_binary_expr(AstFile *f, Token op, Ast *left, Ast *right) {
  511. Ast *result = alloc_ast_node(f, Ast_BinaryExpr);
  512. if (left == nullptr) {
  513. syntax_error(op, "No lhs expression for binary expression '%.*s'", LIT(op.string));
  514. left = ast_bad_expr(f, op, op);
  515. }
  516. if (right == nullptr) {
  517. syntax_error(op, "No rhs expression for binary expression '%.*s'", LIT(op.string));
  518. right = ast_bad_expr(f, op, op);
  519. }
  520. if (left) switch (left->kind) {
  521. case Ast_OrReturnExpr:
  522. syntax_error_with_verbose(left, "'or_return' within a binary expression not wrapped in parentheses (...)");
  523. break;
  524. case Ast_OrBranchExpr:
  525. syntax_error_with_verbose(left, "'or_%.*s' within a binary expression not wrapped in parentheses (...)", LIT(left->OrBranchExpr.token.string));
  526. break;
  527. }
  528. if (right) switch (right->kind) {
  529. case Ast_OrReturnExpr:
  530. syntax_error_with_verbose(right, "'or_return' within a binary expression not wrapped in parentheses (...)");
  531. break;
  532. case Ast_OrBranchExpr:
  533. syntax_error_with_verbose(right, "'or_%.*s' within a binary expression not wrapped in parentheses (...)", LIT(right->OrBranchExpr.token.string));
  534. break;
  535. }
  536. result->BinaryExpr.op = op;
  537. result->BinaryExpr.left = left;
  538. result->BinaryExpr.right = right;
  539. return result;
  540. }
  541. gb_internal Ast *ast_paren_expr(AstFile *f, Ast *expr, Token open, Token close) {
  542. Ast *result = alloc_ast_node(f, Ast_ParenExpr);
  543. result->ParenExpr.expr = expr;
  544. result->ParenExpr.open = open;
  545. result->ParenExpr.close = close;
  546. return result;
  547. }
  548. gb_internal Ast *ast_call_expr(AstFile *f, Ast *proc, Array<Ast *> const &args, Token open, Token close, Token ellipsis) {
  549. Ast *result = alloc_ast_node(f, Ast_CallExpr);
  550. result->CallExpr.proc = proc;
  551. result->CallExpr.args = slice_from_array(args);
  552. result->CallExpr.open = open;
  553. result->CallExpr.close = close;
  554. result->CallExpr.ellipsis = ellipsis;
  555. return result;
  556. }
  557. gb_internal Ast *ast_selector_expr(AstFile *f, Token token, Ast *expr, Ast *selector) {
  558. Ast *result = alloc_ast_node(f, Ast_SelectorExpr);
  559. result->SelectorExpr.token = token;
  560. result->SelectorExpr.expr = expr;
  561. result->SelectorExpr.selector = selector;
  562. return result;
  563. }
  564. gb_internal Ast *ast_implicit_selector_expr(AstFile *f, Token token, Ast *selector) {
  565. Ast *result = alloc_ast_node(f, Ast_ImplicitSelectorExpr);
  566. result->ImplicitSelectorExpr.token = token;
  567. result->ImplicitSelectorExpr.selector = selector;
  568. return result;
  569. }
  570. gb_internal Ast *ast_selector_call_expr(AstFile *f, Token token, Ast *expr, Ast *call) {
  571. Ast *result = alloc_ast_node(f, Ast_SelectorCallExpr);
  572. result->SelectorCallExpr.token = token;
  573. result->SelectorCallExpr.expr = expr;
  574. result->SelectorCallExpr.call = call;
  575. return result;
  576. }
  577. gb_internal Ast *ast_index_expr(AstFile *f, Ast *expr, Ast *index, Token open, Token close) {
  578. Ast *result = alloc_ast_node(f, Ast_IndexExpr);
  579. result->IndexExpr.expr = expr;
  580. result->IndexExpr.index = index;
  581. result->IndexExpr.open = open;
  582. result->IndexExpr.close = close;
  583. return result;
  584. }
  585. gb_internal Ast *ast_slice_expr(AstFile *f, Ast *expr, Token open, Token close, Token interval, Ast *low, Ast *high) {
  586. Ast *result = alloc_ast_node(f, Ast_SliceExpr);
  587. result->SliceExpr.expr = expr;
  588. result->SliceExpr.open = open;
  589. result->SliceExpr.close = close;
  590. result->SliceExpr.interval = interval;
  591. result->SliceExpr.low = low;
  592. result->SliceExpr.high = high;
  593. return result;
  594. }
  595. gb_internal Ast *ast_deref_expr(AstFile *f, Ast *expr, Token op) {
  596. Ast *result = alloc_ast_node(f, Ast_DerefExpr);
  597. result->DerefExpr.expr = expr;
  598. result->DerefExpr.op = op;
  599. return result;
  600. }
  601. gb_internal Ast *ast_matrix_index_expr(AstFile *f, Ast *expr, Token open, Token close, Token interval, Ast *row, Ast *column) {
  602. Ast *result = alloc_ast_node(f, Ast_MatrixIndexExpr);
  603. result->MatrixIndexExpr.expr = expr;
  604. result->MatrixIndexExpr.row_index = row;
  605. result->MatrixIndexExpr.column_index = column;
  606. result->MatrixIndexExpr.open = open;
  607. result->MatrixIndexExpr.close = close;
  608. return result;
  609. }
  610. gb_internal Ast *ast_ident(AstFile *f, Token token) {
  611. Ast *result = alloc_ast_node(f, Ast_Ident);
  612. result->Ident.token = token;
  613. return result;
  614. }
  615. gb_internal Ast *ast_implicit(AstFile *f, Token token) {
  616. Ast *result = alloc_ast_node(f, Ast_Implicit);
  617. result->Implicit = token;
  618. return result;
  619. }
  620. gb_internal Ast *ast_uninit(AstFile *f, Token token) {
  621. Ast *result = alloc_ast_node(f, Ast_Uninit);
  622. result->Uninit = token;
  623. return result;
  624. }
  625. gb_internal ExactValue exact_value_from_token(AstFile *f, Token const &token) {
  626. String s = token.string;
  627. switch (token.kind) {
  628. case Token_Rune:
  629. if (!unquote_string(ast_allocator(f), &s, 0)) {
  630. syntax_error(token, "Invalid rune literal");
  631. }
  632. break;
  633. case Token_String:
  634. if (!unquote_string(ast_allocator(f), &s, 0, s.text[0] == '`')) {
  635. syntax_error(token, "Invalid string literal");
  636. }
  637. break;
  638. }
  639. ExactValue value = exact_value_from_basic_literal(token.kind, s);
  640. if (value.kind == ExactValue_Invalid) {
  641. syntax_error(token, "Invalid token literal");
  642. }
  643. return value;
  644. }
  645. gb_internal String string_value_from_token(AstFile *f, Token const &token) {
  646. ExactValue value = exact_value_from_token(f, token);
  647. String str = {};
  648. if (value.kind == ExactValue_String) {
  649. str = value.value_string;
  650. }
  651. return str;
  652. }
  653. gb_internal Ast *ast_basic_lit(AstFile *f, Token basic_lit) {
  654. Ast *result = alloc_ast_node(f, Ast_BasicLit);
  655. result->BasicLit.token = basic_lit;
  656. result->tav.mode = Addressing_Constant;
  657. result->tav.value = exact_value_from_token(f, basic_lit);
  658. return result;
  659. }
  660. gb_internal Ast *ast_basic_directive(AstFile *f, Token token, Token name) {
  661. Ast *result = alloc_ast_node(f, Ast_BasicDirective);
  662. result->BasicDirective.token = token;
  663. result->BasicDirective.name = name;
  664. return result;
  665. }
  666. gb_internal Ast *ast_ellipsis(AstFile *f, Token token, Ast *expr) {
  667. Ast *result = alloc_ast_node(f, Ast_Ellipsis);
  668. result->Ellipsis.token = token;
  669. result->Ellipsis.expr = expr;
  670. return result;
  671. }
  672. gb_internal Ast *ast_proc_group(AstFile *f, Token token, Token open, Token close, Array<Ast *> const &args) {
  673. Ast *result = alloc_ast_node(f, Ast_ProcGroup);
  674. result->ProcGroup.token = token;
  675. result->ProcGroup.open = open;
  676. result->ProcGroup.close = close;
  677. result->ProcGroup.args = slice_from_array(args);
  678. return result;
  679. }
  680. gb_internal Ast *ast_proc_lit(AstFile *f, Ast *type, Ast *body, u64 tags, Token where_token, Array<Ast *> const &where_clauses) {
  681. Ast *result = alloc_ast_node(f, Ast_ProcLit);
  682. result->ProcLit.type = type;
  683. result->ProcLit.body = body;
  684. result->ProcLit.tags = tags;
  685. result->ProcLit.where_token = where_token;
  686. result->ProcLit.where_clauses = slice_from_array(where_clauses);
  687. return result;
  688. }
  689. gb_internal Ast *ast_field_value(AstFile *f, Ast *field, Ast *value, Token eq) {
  690. Ast *result = alloc_ast_node(f, Ast_FieldValue);
  691. result->FieldValue.field = field;
  692. result->FieldValue.value = value;
  693. result->FieldValue.eq = eq;
  694. return result;
  695. }
  696. gb_internal Ast *ast_enum_field_value(AstFile *f, Ast *name, Ast *value, CommentGroup *docs, CommentGroup *comment) {
  697. Ast *result = alloc_ast_node(f, Ast_EnumFieldValue);
  698. result->EnumFieldValue.name = name;
  699. result->EnumFieldValue.value = value;
  700. result->EnumFieldValue.docs = docs;
  701. result->EnumFieldValue.comment = comment;
  702. return result;
  703. }
  704. gb_internal Ast *ast_compound_lit(AstFile *f, Ast *type, Array<Ast *> const &elems, Token open, Token close) {
  705. Ast *result = alloc_ast_node(f, Ast_CompoundLit);
  706. result->CompoundLit.type = type;
  707. result->CompoundLit.elems = slice_from_array(elems);
  708. result->CompoundLit.open = open;
  709. result->CompoundLit.close = close;
  710. return result;
  711. }
  712. gb_internal Ast *ast_ternary_if_expr(AstFile *f, Ast *x, Ast *cond, Ast *y) {
  713. Ast *result = alloc_ast_node(f, Ast_TernaryIfExpr);
  714. result->TernaryIfExpr.x = x;
  715. result->TernaryIfExpr.cond = cond;
  716. result->TernaryIfExpr.y = y;
  717. return result;
  718. }
  719. gb_internal Ast *ast_ternary_when_expr(AstFile *f, Ast *x, Ast *cond, Ast *y) {
  720. Ast *result = alloc_ast_node(f, Ast_TernaryWhenExpr);
  721. result->TernaryWhenExpr.x = x;
  722. result->TernaryWhenExpr.cond = cond;
  723. result->TernaryWhenExpr.y = y;
  724. return result;
  725. }
  726. gb_internal Ast *ast_or_else_expr(AstFile *f, Ast *x, Token const &token, Ast *y) {
  727. Ast *result = alloc_ast_node(f, Ast_OrElseExpr);
  728. result->OrElseExpr.x = x;
  729. result->OrElseExpr.token = token;
  730. result->OrElseExpr.y = y;
  731. return result;
  732. }
  733. gb_internal Ast *ast_or_return_expr(AstFile *f, Ast *expr, Token const &token) {
  734. Ast *result = alloc_ast_node(f, Ast_OrReturnExpr);
  735. result->OrReturnExpr.expr = expr;
  736. result->OrReturnExpr.token = token;
  737. return result;
  738. }
  739. gb_internal Ast *ast_or_branch_expr(AstFile *f, Ast *expr, Token const &token, Ast *label) {
  740. Ast *result = alloc_ast_node(f, Ast_OrBranchExpr);
  741. result->OrBranchExpr.expr = expr;
  742. result->OrBranchExpr.token = token;
  743. result->OrBranchExpr.label = label;
  744. return result;
  745. }
  746. gb_internal Ast *ast_type_assertion(AstFile *f, Ast *expr, Token dot, Ast *type) {
  747. Ast *result = alloc_ast_node(f, Ast_TypeAssertion);
  748. result->TypeAssertion.expr = expr;
  749. result->TypeAssertion.dot = dot;
  750. result->TypeAssertion.type = type;
  751. return result;
  752. }
  753. gb_internal Ast *ast_type_cast(AstFile *f, Token token, Ast *type, Ast *expr) {
  754. Ast *result = alloc_ast_node(f, Ast_TypeCast);
  755. result->TypeCast.token = token;
  756. result->TypeCast.type = type;
  757. result->TypeCast.expr = expr;
  758. return result;
  759. }
  760. gb_internal Ast *ast_auto_cast(AstFile *f, Token token, Ast *expr) {
  761. Ast *result = alloc_ast_node(f, Ast_AutoCast);
  762. result->AutoCast.token = token;
  763. result->AutoCast.expr = expr;
  764. return result;
  765. }
  766. gb_internal Ast *ast_inline_asm_expr(AstFile *f, Token token, Token open, Token close,
  767. Array<Ast *> const &param_types,
  768. Ast *return_type,
  769. Ast *asm_string,
  770. Ast *constraints_string,
  771. bool has_side_effects,
  772. bool is_align_stack,
  773. InlineAsmDialectKind dialect) {
  774. Ast *result = alloc_ast_node(f, Ast_InlineAsmExpr);
  775. result->InlineAsmExpr.token = token;
  776. result->InlineAsmExpr.open = open;
  777. result->InlineAsmExpr.close = close;
  778. result->InlineAsmExpr.param_types = slice_from_array(param_types);
  779. result->InlineAsmExpr.return_type = return_type;
  780. result->InlineAsmExpr.asm_string = asm_string;
  781. result->InlineAsmExpr.constraints_string = constraints_string;
  782. result->InlineAsmExpr.has_side_effects = has_side_effects;
  783. result->InlineAsmExpr.is_align_stack = is_align_stack;
  784. result->InlineAsmExpr.dialect = dialect;
  785. return result;
  786. }
  787. gb_internal Ast *ast_bad_stmt(AstFile *f, Token begin, Token end) {
  788. Ast *result = alloc_ast_node(f, Ast_BadStmt);
  789. result->BadStmt.begin = begin;
  790. result->BadStmt.end = end;
  791. return result;
  792. }
  793. gb_internal Ast *ast_empty_stmt(AstFile *f, Token token) {
  794. Ast *result = alloc_ast_node(f, Ast_EmptyStmt);
  795. result->EmptyStmt.token = token;
  796. return result;
  797. }
  798. gb_internal Ast *ast_expr_stmt(AstFile *f, Ast *expr) {
  799. Ast *result = alloc_ast_node(f, Ast_ExprStmt);
  800. result->ExprStmt.expr = expr;
  801. return result;
  802. }
  803. gb_internal Ast *ast_assign_stmt(AstFile *f, Token op, Array<Ast *> const &lhs, Array<Ast *> const &rhs) {
  804. Ast *result = alloc_ast_node(f, Ast_AssignStmt);
  805. result->AssignStmt.op = op;
  806. result->AssignStmt.lhs = slice_from_array(lhs);
  807. result->AssignStmt.rhs = slice_from_array(rhs);
  808. return result;
  809. }
  810. gb_internal Ast *ast_block_stmt(AstFile *f, Array<Ast *> const &stmts, Token open, Token close) {
  811. Ast *result = alloc_ast_node(f, Ast_BlockStmt);
  812. result->BlockStmt.stmts = slice_from_array(stmts);
  813. result->BlockStmt.open = open;
  814. result->BlockStmt.close = close;
  815. return result;
  816. }
  817. gb_internal Ast *ast_if_stmt(AstFile *f, Token token, Ast *init, Ast *cond, Ast *body, Ast *else_stmt) {
  818. Ast *result = alloc_ast_node(f, Ast_IfStmt);
  819. result->IfStmt.token = token;
  820. result->IfStmt.init = init;
  821. result->IfStmt.cond = cond;
  822. result->IfStmt.body = body;
  823. result->IfStmt.else_stmt = else_stmt;
  824. return result;
  825. }
  826. gb_internal Ast *ast_when_stmt(AstFile *f, Token token, Ast *cond, Ast *body, Ast *else_stmt) {
  827. Ast *result = alloc_ast_node(f, Ast_WhenStmt);
  828. result->WhenStmt.token = token;
  829. result->WhenStmt.cond = cond;
  830. result->WhenStmt.body = body;
  831. result->WhenStmt.else_stmt = else_stmt;
  832. return result;
  833. }
  834. gb_internal Ast *ast_return_stmt(AstFile *f, Token token, Array<Ast *> const &results) {
  835. Ast *result = alloc_ast_node(f, Ast_ReturnStmt);
  836. result->ReturnStmt.token = token;
  837. result->ReturnStmt.results = slice_from_array(results);
  838. return result;
  839. }
  840. gb_internal Ast *ast_for_stmt(AstFile *f, Token token, Ast *init, Ast *cond, Ast *post, Ast *body) {
  841. Ast *result = alloc_ast_node(f, Ast_ForStmt);
  842. result->ForStmt.token = token;
  843. result->ForStmt.init = init;
  844. result->ForStmt.cond = cond;
  845. result->ForStmt.post = post;
  846. result->ForStmt.body = body;
  847. return result;
  848. }
  849. gb_internal Ast *ast_range_stmt(AstFile *f, Token token, Slice<Ast *> vals, Token in_token, Ast *expr, Ast *body) {
  850. Ast *result = alloc_ast_node(f, Ast_RangeStmt);
  851. result->RangeStmt.token = token;
  852. result->RangeStmt.vals = vals;
  853. result->RangeStmt.in_token = in_token;
  854. result->RangeStmt.expr = expr;
  855. result->RangeStmt.body = body;
  856. return result;
  857. }
  858. gb_internal Ast *ast_unroll_range_stmt(AstFile *f, Token unroll_token, Token for_token, Ast *val0, Ast *val1, Token in_token, Ast *expr, Ast *body) {
  859. Ast *result = alloc_ast_node(f, Ast_UnrollRangeStmt);
  860. result->UnrollRangeStmt.unroll_token = unroll_token;
  861. result->UnrollRangeStmt.for_token = for_token;
  862. result->UnrollRangeStmt.val0 = val0;
  863. result->UnrollRangeStmt.val1 = val1;
  864. result->UnrollRangeStmt.in_token = in_token;
  865. result->UnrollRangeStmt.expr = expr;
  866. result->UnrollRangeStmt.body = body;
  867. return result;
  868. }
  869. gb_internal Ast *ast_switch_stmt(AstFile *f, Token token, Ast *init, Ast *tag, Ast *body) {
  870. Ast *result = alloc_ast_node(f, Ast_SwitchStmt);
  871. result->SwitchStmt.token = token;
  872. result->SwitchStmt.init = init;
  873. result->SwitchStmt.tag = tag;
  874. result->SwitchStmt.body = body;
  875. result->SwitchStmt.partial = false;
  876. return result;
  877. }
  878. gb_internal Ast *ast_type_switch_stmt(AstFile *f, Token token, Ast *tag, Ast *body) {
  879. Ast *result = alloc_ast_node(f, Ast_TypeSwitchStmt);
  880. result->TypeSwitchStmt.token = token;
  881. result->TypeSwitchStmt.tag = tag;
  882. result->TypeSwitchStmt.body = body;
  883. result->TypeSwitchStmt.partial = false;
  884. return result;
  885. }
  886. gb_internal Ast *ast_case_clause(AstFile *f, Token token, Array<Ast *> const &list, Array<Ast *> const &stmts) {
  887. Ast *result = alloc_ast_node(f, Ast_CaseClause);
  888. result->CaseClause.token = token;
  889. result->CaseClause.list = slice_from_array(list);
  890. result->CaseClause.stmts = slice_from_array(stmts);
  891. return result;
  892. }
  893. gb_internal Ast *ast_defer_stmt(AstFile *f, Token token, Ast *stmt) {
  894. Ast *result = alloc_ast_node(f, Ast_DeferStmt);
  895. result->DeferStmt.token = token;
  896. result->DeferStmt.stmt = stmt;
  897. return result;
  898. }
  899. gb_internal Ast *ast_branch_stmt(AstFile *f, Token token, Ast *label) {
  900. Ast *result = alloc_ast_node(f, Ast_BranchStmt);
  901. result->BranchStmt.token = token;
  902. result->BranchStmt.label = label;
  903. return result;
  904. }
  905. gb_internal Ast *ast_using_stmt(AstFile *f, Token token, Array<Ast *> const &list) {
  906. Ast *result = alloc_ast_node(f, Ast_UsingStmt);
  907. result->UsingStmt.token = token;
  908. result->UsingStmt.list = slice_from_array(list);
  909. return result;
  910. }
  911. gb_internal Ast *ast_bad_decl(AstFile *f, Token begin, Token end) {
  912. Ast *result = alloc_ast_node(f, Ast_BadDecl);
  913. result->BadDecl.begin = begin;
  914. result->BadDecl.end = end;
  915. return result;
  916. }
  917. gb_internal Ast *ast_field(AstFile *f, Array<Ast *> const &names, Ast *type, Ast *default_value, u32 flags, Token tag,
  918. CommentGroup *docs, CommentGroup *comment) {
  919. Ast *result = alloc_ast_node(f, Ast_Field);
  920. result->Field.names = slice_from_array(names);
  921. result->Field.type = type;
  922. result->Field.default_value = default_value;
  923. result->Field.flags = flags;
  924. result->Field.tag = tag;
  925. result->Field.docs = docs;
  926. result->Field.comment = comment;
  927. return result;
  928. }
  929. gb_internal Ast *ast_bit_field_field(AstFile *f, Ast *name, Ast *type, Ast *bit_size, Token tag,
  930. CommentGroup *docs, CommentGroup *comment) {
  931. Ast *result = alloc_ast_node(f, Ast_BitFieldField);
  932. result->BitFieldField.name = name;
  933. result->BitFieldField.type = type;
  934. result->BitFieldField.bit_size = bit_size;
  935. result->BitFieldField.tag = tag;
  936. result->BitFieldField.docs = docs;
  937. result->BitFieldField.comment = comment;
  938. return result;
  939. }
  940. gb_internal Ast *ast_field_list(AstFile *f, Token token, Array<Ast *> const &list) {
  941. Ast *result = alloc_ast_node(f, Ast_FieldList);
  942. result->FieldList.token = token;
  943. result->FieldList.list = slice_from_array(list);
  944. return result;
  945. }
  946. gb_internal Ast *ast_typeid_type(AstFile *f, Token token, Ast *specialization) {
  947. Ast *result = alloc_ast_node(f, Ast_TypeidType);
  948. result->TypeidType.token = token;
  949. result->TypeidType.specialization = specialization;
  950. return result;
  951. }
  952. gb_internal Ast *ast_helper_type(AstFile *f, Token token, Ast *type) {
  953. Ast *result = alloc_ast_node(f, Ast_HelperType);
  954. result->HelperType.token = token;
  955. result->HelperType.type = type;
  956. return result;
  957. }
  958. gb_internal Ast *ast_distinct_type(AstFile *f, Token token, Ast *type) {
  959. Ast *result = alloc_ast_node(f, Ast_DistinctType);
  960. result->DistinctType.token = token;
  961. result->DistinctType.type = type;
  962. return result;
  963. }
  964. gb_internal Ast *ast_poly_type(AstFile *f, Token token, Ast *type, Ast *specialization) {
  965. Ast *result = alloc_ast_node(f, Ast_PolyType);
  966. result->PolyType.token = token;
  967. result->PolyType.type = type;
  968. result->PolyType.specialization = specialization;
  969. return result;
  970. }
  971. gb_internal Ast *ast_proc_type(AstFile *f, Token token, Ast *params, Ast *results, u64 tags, ProcCallingConvention calling_convention, bool generic, bool diverging) {
  972. Ast *result = alloc_ast_node(f, Ast_ProcType);
  973. result->ProcType.token = token;
  974. result->ProcType.params = params;
  975. result->ProcType.results = results;
  976. result->ProcType.tags = tags;
  977. result->ProcType.calling_convention = calling_convention;
  978. result->ProcType.generic = generic;
  979. result->ProcType.diverging = diverging;
  980. return result;
  981. }
  982. gb_internal Ast *ast_relative_type(AstFile *f, Ast *tag, Ast *type) {
  983. Ast *result = alloc_ast_node(f, Ast_RelativeType);
  984. result->RelativeType.tag = tag;
  985. result->RelativeType.type = type;
  986. return result;
  987. }
  988. gb_internal Ast *ast_pointer_type(AstFile *f, Token token, Ast *type) {
  989. Ast *result = alloc_ast_node(f, Ast_PointerType);
  990. result->PointerType.token = token;
  991. result->PointerType.type = type;
  992. return result;
  993. }
  994. gb_internal Ast *ast_multi_pointer_type(AstFile *f, Token token, Ast *type) {
  995. Ast *result = alloc_ast_node(f, Ast_MultiPointerType);
  996. result->MultiPointerType.token = token;
  997. result->MultiPointerType.type = type;
  998. return result;
  999. }
  1000. gb_internal Ast *ast_array_type(AstFile *f, Token token, Ast *count, Ast *elem) {
  1001. Ast *result = alloc_ast_node(f, Ast_ArrayType);
  1002. result->ArrayType.token = token;
  1003. result->ArrayType.count = count;
  1004. result->ArrayType.elem = elem;
  1005. return result;
  1006. }
  1007. gb_internal Ast *ast_dynamic_array_type(AstFile *f, Token token, Ast *elem) {
  1008. Ast *result = alloc_ast_node(f, Ast_DynamicArrayType);
  1009. result->DynamicArrayType.token = token;
  1010. result->DynamicArrayType.elem = elem;
  1011. return result;
  1012. }
  1013. gb_internal Ast *ast_struct_type(AstFile *f, Token token, Slice<Ast *> fields, isize field_count,
  1014. Ast *polymorphic_params, bool is_packed, bool is_raw_union, bool is_no_copy,
  1015. Ast *align, Ast *field_align,
  1016. Token where_token, Array<Ast *> const &where_clauses) {
  1017. Ast *result = alloc_ast_node(f, Ast_StructType);
  1018. result->StructType.token = token;
  1019. result->StructType.fields = fields;
  1020. result->StructType.field_count = field_count;
  1021. result->StructType.polymorphic_params = polymorphic_params;
  1022. result->StructType.is_packed = is_packed;
  1023. result->StructType.is_raw_union = is_raw_union;
  1024. result->StructType.is_no_copy = is_no_copy;
  1025. result->StructType.align = align;
  1026. result->StructType.field_align = field_align;
  1027. result->StructType.where_token = where_token;
  1028. result->StructType.where_clauses = slice_from_array(where_clauses);
  1029. return result;
  1030. }
  1031. gb_internal Ast *ast_union_type(AstFile *f, Token token, Array<Ast *> const &variants, Ast *polymorphic_params, Ast *align, UnionTypeKind kind,
  1032. Token where_token, Array<Ast *> const &where_clauses) {
  1033. Ast *result = alloc_ast_node(f, Ast_UnionType);
  1034. result->UnionType.token = token;
  1035. result->UnionType.variants = slice_from_array(variants);
  1036. result->UnionType.polymorphic_params = polymorphic_params;
  1037. result->UnionType.align = align;
  1038. result->UnionType.kind = kind;
  1039. result->UnionType.where_token = where_token;
  1040. result->UnionType.where_clauses = slice_from_array(where_clauses);
  1041. return result;
  1042. }
  1043. gb_internal Ast *ast_enum_type(AstFile *f, Token token, Ast *base_type, Array<Ast *> const &fields) {
  1044. Ast *result = alloc_ast_node(f, Ast_EnumType);
  1045. result->EnumType.token = token;
  1046. result->EnumType.base_type = base_type;
  1047. result->EnumType.fields = slice_from_array(fields);
  1048. return result;
  1049. }
  1050. gb_internal Ast *ast_bit_set_type(AstFile *f, Token token, Ast *elem, Ast *underlying) {
  1051. Ast *result = alloc_ast_node(f, Ast_BitSetType);
  1052. result->BitSetType.token = token;
  1053. result->BitSetType.elem = elem;
  1054. result->BitSetType.underlying = underlying;
  1055. return result;
  1056. }
  1057. gb_internal Ast *ast_bit_field_type(AstFile *f, Token token, Ast *backing_type, Token open, Array<Ast *> const &fields, Token close) {
  1058. Ast *result = alloc_ast_node(f, Ast_BitFieldType);
  1059. result->BitFieldType.token = token;
  1060. result->BitFieldType.backing_type = backing_type;
  1061. result->BitFieldType.open = open;
  1062. result->BitFieldType.fields = slice_from_array(fields);
  1063. result->BitFieldType.close = close;
  1064. return result;
  1065. }
  1066. gb_internal Ast *ast_map_type(AstFile *f, Token token, Ast *key, Ast *value) {
  1067. Ast *result = alloc_ast_node(f, Ast_MapType);
  1068. result->MapType.token = token;
  1069. result->MapType.key = key;
  1070. result->MapType.value = value;
  1071. return result;
  1072. }
  1073. gb_internal Ast *ast_matrix_type(AstFile *f, Token token, Ast *row_count, Ast *column_count, Ast *elem) {
  1074. Ast *result = alloc_ast_node(f, Ast_MatrixType);
  1075. result->MatrixType.token = token;
  1076. result->MatrixType.row_count = row_count;
  1077. result->MatrixType.column_count = column_count;
  1078. result->MatrixType.elem = elem;
  1079. return result;
  1080. }
  1081. gb_internal Ast *ast_foreign_block_decl(AstFile *f, Token token, Ast *foreign_library, Ast *body,
  1082. CommentGroup *docs) {
  1083. Ast *result = alloc_ast_node(f, Ast_ForeignBlockDecl);
  1084. result->ForeignBlockDecl.token = token;
  1085. result->ForeignBlockDecl.foreign_library = foreign_library;
  1086. result->ForeignBlockDecl.body = body;
  1087. result->ForeignBlockDecl.docs = docs;
  1088. result->ForeignBlockDecl.attributes.allocator = ast_allocator(f);
  1089. return result;
  1090. }
  1091. gb_internal Ast *ast_label_decl(AstFile *f, Token token, Ast *name) {
  1092. Ast *result = alloc_ast_node(f, Ast_Label);
  1093. result->Label.token = token;
  1094. result->Label.name = name;
  1095. return result;
  1096. }
  1097. gb_internal Ast *ast_value_decl(AstFile *f, Array<Ast *> const &names, Ast *type, Array<Ast *> const &values, bool is_mutable,
  1098. CommentGroup *docs, CommentGroup *comment) {
  1099. Ast *result = alloc_ast_node(f, Ast_ValueDecl);
  1100. result->ValueDecl.names = slice_from_array(names);
  1101. result->ValueDecl.type = type;
  1102. result->ValueDecl.values = slice_from_array(values);
  1103. result->ValueDecl.is_mutable = is_mutable;
  1104. result->ValueDecl.docs = docs;
  1105. result->ValueDecl.comment = comment;
  1106. result->ValueDecl.attributes.allocator = ast_allocator(f);
  1107. return result;
  1108. }
  1109. gb_internal Ast *ast_package_decl(AstFile *f, Token token, Token name, CommentGroup *docs, CommentGroup *comment) {
  1110. Ast *result = alloc_ast_node(f, Ast_PackageDecl);
  1111. result->PackageDecl.token = token;
  1112. result->PackageDecl.name = name;
  1113. result->PackageDecl.docs = docs;
  1114. result->PackageDecl.comment = comment;
  1115. return result;
  1116. }
  1117. gb_internal Ast *ast_import_decl(AstFile *f, Token token, Token relpath, Token import_name,
  1118. CommentGroup *docs, CommentGroup *comment) {
  1119. Ast *result = alloc_ast_node(f, Ast_ImportDecl);
  1120. result->ImportDecl.token = token;
  1121. result->ImportDecl.relpath = relpath;
  1122. result->ImportDecl.import_name = import_name;
  1123. result->ImportDecl.docs = docs;
  1124. result->ImportDecl.comment = comment;
  1125. result->ImportDecl.attributes.allocator = ast_allocator(f);
  1126. return result;
  1127. }
  1128. gb_internal Ast *ast_foreign_import_decl(AstFile *f, Token token, Array<Token> filepaths, Token library_name,
  1129. CommentGroup *docs, CommentGroup *comment) {
  1130. Ast *result = alloc_ast_node(f, Ast_ForeignImportDecl);
  1131. result->ForeignImportDecl.token = token;
  1132. result->ForeignImportDecl.filepaths = slice_from_array(filepaths);
  1133. result->ForeignImportDecl.library_name = library_name;
  1134. result->ForeignImportDecl.docs = docs;
  1135. result->ForeignImportDecl.comment = comment;
  1136. result->ForeignImportDecl.attributes.allocator = ast_allocator(f);
  1137. return result;
  1138. }
  1139. gb_internal Ast *ast_attribute(AstFile *f, Token token, Token open, Token close, Array<Ast *> const &elems) {
  1140. Ast *result = alloc_ast_node(f, Ast_Attribute);
  1141. result->Attribute.token = token;
  1142. result->Attribute.open = open;
  1143. result->Attribute.elems = slice_from_array(elems);
  1144. result->Attribute.close = close;
  1145. return result;
  1146. }
  1147. gb_internal bool next_token0(AstFile *f) {
  1148. if (f->curr_token_index+1 < f->tokens.count) {
  1149. f->curr_token = f->tokens[++f->curr_token_index];
  1150. return true;
  1151. }
  1152. syntax_error(f->curr_token, "Token is EOF");
  1153. return false;
  1154. }
  1155. gb_internal Token consume_comment(AstFile *f, isize *end_line_) {
  1156. Token tok = f->curr_token;
  1157. GB_ASSERT(tok.kind == Token_Comment);
  1158. isize end_line = tok.pos.line;
  1159. if (tok.string[1] == '*') {
  1160. for (isize i = 2; i < tok.string.len; i++) {
  1161. if (tok.string[i] == '\n') {
  1162. end_line++;
  1163. }
  1164. }
  1165. }
  1166. if (end_line_) *end_line_ = end_line;
  1167. next_token0(f);
  1168. if (f->curr_token.pos.line > tok.pos.line || tok.kind == Token_EOF) {
  1169. end_line++;
  1170. }
  1171. return tok;
  1172. }
  1173. gb_internal CommentGroup *consume_comment_group(AstFile *f, isize n, isize *end_line_) {
  1174. Array<Token> list = {};
  1175. list.allocator = ast_allocator(f);
  1176. isize end_line = f->curr_token.pos.line;
  1177. if (f->curr_token_index == 1 &&
  1178. f->prev_token.kind == Token_Comment &&
  1179. f->prev_token.pos.line+1 == f->curr_token.pos.line) {
  1180. // NOTE(bill): Special logic for the first comment in the file
  1181. array_add(&list, f->prev_token);
  1182. }
  1183. while (f->curr_token.kind == Token_Comment &&
  1184. f->curr_token.pos.line <= end_line+n) {
  1185. array_add(&list, consume_comment(f, &end_line));
  1186. }
  1187. if (end_line_) *end_line_ = end_line;
  1188. CommentGroup *comments = nullptr;
  1189. if (list.count > 0) {
  1190. comments = gb_alloc_item(permanent_allocator(), CommentGroup);
  1191. comments->list = slice_from_array(list);
  1192. array_add(&f->comments, comments);
  1193. }
  1194. return comments;
  1195. }
  1196. gb_internal void consume_comment_groups(AstFile *f, Token prev) {
  1197. if (f->curr_token.kind == Token_Comment) {
  1198. CommentGroup *comment = nullptr;
  1199. isize end_line = 0;
  1200. if (f->curr_token.pos.line == prev.pos.line) {
  1201. comment = consume_comment_group(f, 0, &end_line);
  1202. if (f->curr_token.pos.line != end_line || f->curr_token.kind == Token_EOF) {
  1203. f->line_comment = comment;
  1204. }
  1205. }
  1206. end_line = -1;
  1207. while (f->curr_token.kind == Token_Comment) {
  1208. comment = consume_comment_group(f, 1, &end_line);
  1209. }
  1210. if (end_line+1 == f->curr_token.pos.line || end_line < 0) {
  1211. f->lead_comment = comment;
  1212. }
  1213. GB_ASSERT(f->curr_token.kind != Token_Comment);
  1214. }
  1215. }
  1216. gb_internal gb_inline bool ignore_newlines(AstFile *f) {
  1217. return f->expr_level > 0;
  1218. }
  1219. gb_internal Token advance_token(AstFile *f) {
  1220. f->lead_comment = nullptr;
  1221. f->line_comment = nullptr;
  1222. f->prev_token_index = f->curr_token_index;
  1223. Token prev = f->prev_token = f->curr_token;
  1224. bool ok = next_token0(f);
  1225. if (ok) {
  1226. switch (f->curr_token.kind) {
  1227. case Token_Comment:
  1228. consume_comment_groups(f, prev);
  1229. break;
  1230. case Token_Semicolon:
  1231. if (ignore_newlines(f) && f->curr_token.string == "\n") {
  1232. advance_token(f);
  1233. }
  1234. break;
  1235. }
  1236. }
  1237. return prev;
  1238. }
  1239. gb_internal Token peek_token(AstFile *f) {
  1240. for (isize i = f->curr_token_index+1; i < f->tokens.count; i++) {
  1241. Token tok = f->tokens[i];
  1242. if (tok.kind == Token_Comment) {
  1243. continue;
  1244. }
  1245. return tok;
  1246. }
  1247. return {};
  1248. }
  1249. gb_internal Token peek_token_n(AstFile *f, isize n) {
  1250. Token found = {};
  1251. for (isize i = f->curr_token_index+1; i < f->tokens.count; i++) {
  1252. Token tok = f->tokens[i];
  1253. if (tok.kind == Token_Comment) {
  1254. continue;
  1255. }
  1256. found = tok;
  1257. if (n-- == 0) {
  1258. return found;
  1259. }
  1260. }
  1261. return {};
  1262. }
  1263. gb_internal bool skip_possible_newline(AstFile *f) {
  1264. if (token_is_newline(f->curr_token)) {
  1265. advance_token(f);
  1266. return true;
  1267. }
  1268. return false;
  1269. }
  1270. gb_internal bool skip_possible_newline_for_literal(AstFile *f) {
  1271. Token curr = f->curr_token;
  1272. if (token_is_newline(curr)) {
  1273. Token next = peek_token(f);
  1274. if (curr.pos.line+1 >= next.pos.line) {
  1275. switch (next.kind) {
  1276. case Token_OpenBrace:
  1277. case Token_else:
  1278. case Token_where:
  1279. advance_token(f);
  1280. return true;
  1281. }
  1282. }
  1283. }
  1284. return false;
  1285. }
  1286. gb_internal String token_to_string(Token const &tok) {
  1287. String p = token_strings[tok.kind];
  1288. if (token_is_newline(tok)) {
  1289. p = str_lit("newline");
  1290. }
  1291. return p;
  1292. }
  1293. gb_internal Token expect_token(AstFile *f, TokenKind kind) {
  1294. Token prev = f->curr_token;
  1295. if (prev.kind != kind) {
  1296. String c = token_strings[kind];
  1297. String p = token_to_string(prev);
  1298. begin_error_block();
  1299. syntax_error(f->curr_token, "Expected '%.*s', got '%.*s'", LIT(c), LIT(p));
  1300. if (kind == Token_Ident) switch (prev.kind) {
  1301. case Token_context:
  1302. error_line("\tSuggestion: '%.*s' is a keyword, would 'ctx' suffice?\n", LIT(prev.string));
  1303. break;
  1304. case Token_package:
  1305. error_line("\tSuggestion: '%.*s' is a keyword, would 'pkg' suffice?\n", LIT(prev.string));
  1306. break;
  1307. default:
  1308. if (token_is_keyword(prev.kind)) {
  1309. error_line("\tNote: '%.*s' is a keyword\n", LIT(prev.string));
  1310. }
  1311. break;
  1312. }
  1313. end_error_block();
  1314. if (prev.kind == Token_EOF) {
  1315. exit_with_errors();
  1316. }
  1317. }
  1318. advance_token(f);
  1319. return prev;
  1320. }
  1321. gb_internal Token expect_token_after(AstFile *f, TokenKind kind, char const *msg) {
  1322. Token prev = f->prev_token;
  1323. Token curr = f->curr_token;
  1324. if (curr.kind != kind) {
  1325. String p = token_to_string(curr);
  1326. Token token = f->curr_token;
  1327. if (token_is_newline(curr)) {
  1328. token = curr;
  1329. token.pos.column -= 1;
  1330. skip_possible_newline(f);
  1331. }
  1332. syntax_error(token, "Expected '%.*s' after %s, got '%.*s'",
  1333. LIT(token_strings[kind]),
  1334. msg,
  1335. LIT(p));
  1336. }
  1337. advance_token(f);
  1338. if (ast_file_vet_style(f) &&
  1339. prev.kind == Token_Comma &&
  1340. prev.pos.line == curr.pos.line) {
  1341. syntax_error(prev, "No need for a trailing comma followed by a %.*s on the same line", LIT(token_strings[kind]));
  1342. }
  1343. return curr;
  1344. }
  1345. gb_internal bool is_token_range(TokenKind kind) {
  1346. switch (kind) {
  1347. case Token_Ellipsis:
  1348. case Token_RangeFull:
  1349. case Token_RangeHalf:
  1350. return true;
  1351. }
  1352. return false;
  1353. }
  1354. gb_internal bool is_token_range(Token tok) {
  1355. return is_token_range(tok.kind);
  1356. }
  1357. gb_internal Token expect_operator(AstFile *f) {
  1358. Token prev = f->curr_token;
  1359. if ((prev.kind == Token_in || prev.kind == Token_not_in) && (f->expr_level >= 0 || f->allow_in_expr)) {
  1360. // okay
  1361. } else if (prev.kind == Token_if || prev.kind == Token_when) {
  1362. // okay
  1363. } else if (prev.kind == Token_or_else || prev.kind == Token_or_return ||
  1364. prev.kind == Token_or_break || prev.kind == Token_or_continue) {
  1365. // okay
  1366. } else if (!gb_is_between(prev.kind, Token__OperatorBegin+1, Token__OperatorEnd-1)) {
  1367. String p = token_to_string(prev);
  1368. syntax_error(prev, "Expected an operator, got '%.*s'",
  1369. LIT(p));
  1370. } else if (!f->allow_range && is_token_range(prev)) {
  1371. String p = token_to_string(prev);
  1372. syntax_error(prev, "Expected an non-range operator, got '%.*s'",
  1373. LIT(p));
  1374. }
  1375. if (prev.kind == Token_Ellipsis) {
  1376. syntax_warning(prev, "'..' for ranges has now been deprecated, prefer '..='");
  1377. f->tokens[f->curr_token_index].flags |= TokenFlag_Replace;
  1378. }
  1379. advance_token(f);
  1380. return prev;
  1381. }
  1382. gb_internal bool allow_token(AstFile *f, TokenKind kind) {
  1383. Token prev = f->curr_token;
  1384. if (prev.kind == kind) {
  1385. advance_token(f);
  1386. return true;
  1387. }
  1388. return false;
  1389. }
  1390. gb_internal Token expect_closing_brace_of_field_list(AstFile *f) {
  1391. Token token = f->curr_token;
  1392. if (allow_token(f, Token_CloseBrace)) {
  1393. return token;
  1394. }
  1395. bool ok = true;
  1396. if (f->allow_newline) {
  1397. ok = !skip_possible_newline(f);
  1398. }
  1399. if (ok && allow_token(f, Token_Semicolon)) {
  1400. String p = token_to_string(token);
  1401. syntax_error(token_end_of_line(f, f->prev_token), "Expected a comma, got a %.*s", LIT(p));
  1402. }
  1403. return expect_token(f, Token_CloseBrace);
  1404. }
  1405. gb_internal bool is_blank_ident(String str) {
  1406. if (str.len == 1) {
  1407. return str[0] == '_';
  1408. }
  1409. return false;
  1410. }
  1411. gb_internal bool is_blank_ident(Token token) {
  1412. if (token.kind == Token_Ident) {
  1413. return is_blank_ident(token.string);
  1414. }
  1415. return false;
  1416. }
  1417. gb_internal bool is_blank_ident(Ast *node) {
  1418. if (node->kind == Ast_Ident) {
  1419. ast_node(i, Ident, node);
  1420. return is_blank_ident(i->token.string);
  1421. }
  1422. return false;
  1423. }
  1424. // NOTE(bill): Go to next statement to prevent numerous error messages popping up
  1425. gb_internal void fix_advance_to_next_stmt(AstFile *f) {
  1426. for (;;) {
  1427. Token t = f->curr_token;
  1428. switch (t.kind) {
  1429. case Token_EOF:
  1430. case Token_Semicolon:
  1431. return;
  1432. case Token_package:
  1433. case Token_foreign:
  1434. case Token_import:
  1435. case Token_if:
  1436. case Token_for:
  1437. case Token_when:
  1438. case Token_return:
  1439. case Token_switch:
  1440. case Token_defer:
  1441. case Token_using:
  1442. case Token_break:
  1443. case Token_continue:
  1444. case Token_fallthrough:
  1445. case Token_Hash:
  1446. {
  1447. if (t.pos == f->fix_prev_pos &&
  1448. f->fix_count < PARSER_MAX_FIX_COUNT) {
  1449. f->fix_count++;
  1450. return;
  1451. }
  1452. if (f->fix_prev_pos < t.pos) {
  1453. f->fix_prev_pos = t.pos;
  1454. f->fix_count = 0; // NOTE(bill): Reset
  1455. return;
  1456. }
  1457. // NOTE(bill): Reaching here means there is a parsing bug
  1458. } break;
  1459. }
  1460. advance_token(f);
  1461. }
  1462. }
  1463. gb_internal Token expect_closing(AstFile *f, TokenKind kind, String const &context) {
  1464. if (f->curr_token.kind != kind &&
  1465. f->curr_token.kind == Token_Semicolon &&
  1466. (f->curr_token.string == "\n" || f->curr_token.kind == Token_EOF)) {
  1467. if (f->allow_newline) {
  1468. Token tok = f->prev_token;
  1469. tok.pos.column += cast(i32)tok.string.len;
  1470. syntax_error(tok, "Missing ',' before newline in %.*s", LIT(context));
  1471. }
  1472. advance_token(f);
  1473. }
  1474. return expect_token(f, kind);
  1475. }
  1476. gb_internal void assign_removal_flag_to_semicolon(AstFile *f) {
  1477. // NOTE(bill): this is used for rewriting files to strip unneeded semicolons
  1478. Token *prev_token = &f->tokens[f->prev_token_index];
  1479. Token *curr_token = &f->tokens[f->curr_token_index];
  1480. GB_ASSERT(prev_token->kind == Token_Semicolon);
  1481. if (prev_token->string != ";") {
  1482. return;
  1483. }
  1484. bool ok = false;
  1485. if (curr_token->pos.line > prev_token->pos.line) {
  1486. ok = true;
  1487. } else if (curr_token->pos.line == prev_token->pos.line) {
  1488. switch (curr_token->kind) {
  1489. case Token_CloseBrace:
  1490. case Token_CloseParen:
  1491. case Token_EOF:
  1492. ok = true;
  1493. break;
  1494. }
  1495. }
  1496. if (!ok) {
  1497. return;
  1498. }
  1499. if (build_context.strict_style || (ast_file_vet_flags(f) & VetFlag_Semicolon)) {
  1500. syntax_error(*prev_token, "Found unneeded semicolon");
  1501. }
  1502. prev_token->flags |= TokenFlag_Remove;
  1503. }
  1504. gb_internal void expect_semicolon(AstFile *f) {
  1505. Token prev_token = {};
  1506. if (allow_token(f, Token_Semicolon)) {
  1507. assign_removal_flag_to_semicolon(f);
  1508. return;
  1509. }
  1510. switch (f->curr_token.kind) {
  1511. case Token_CloseBrace:
  1512. case Token_CloseParen:
  1513. if (f->curr_token.pos.line == f->prev_token.pos.line) {
  1514. return;
  1515. }
  1516. break;
  1517. }
  1518. prev_token = f->prev_token;
  1519. if (prev_token.kind == Token_Semicolon) {
  1520. assign_removal_flag_to_semicolon(f);
  1521. return;
  1522. }
  1523. if (f->curr_token.kind == Token_EOF) {
  1524. return;
  1525. }
  1526. switch (f->curr_token.kind) {
  1527. case Token_EOF:
  1528. return;
  1529. }
  1530. if (f->curr_token.pos.line == f->prev_token.pos.line) {
  1531. String p = token_to_string(f->curr_token);
  1532. prev_token.pos = token_pos_end(prev_token);
  1533. syntax_error(prev_token, "Expected ';', got %.*s", LIT(p));
  1534. fix_advance_to_next_stmt(f);
  1535. }
  1536. }
  1537. gb_internal Ast * parse_expr(AstFile *f, bool lhs);
  1538. gb_internal Ast * parse_proc_type(AstFile *f, Token proc_token);
  1539. gb_internal Array<Ast *> parse_stmt_list(AstFile *f);
  1540. gb_internal Ast * parse_stmt(AstFile *f);
  1541. gb_internal Ast * parse_body(AstFile *f);
  1542. gb_internal Ast * parse_do_body(AstFile *f, Token const &token, char const *msg);
  1543. gb_internal Ast * parse_block_stmt(AstFile *f, b32 is_when);
  1544. gb_internal Ast *parse_ident(AstFile *f, bool allow_poly_names=false) {
  1545. Token token = f->curr_token;
  1546. if (token.kind == Token_Ident) {
  1547. advance_token(f);
  1548. } else if (allow_poly_names && token.kind == Token_Dollar) {
  1549. Token dollar = expect_token(f, Token_Dollar);
  1550. Ast *name = ast_ident(f, expect_token(f, Token_Ident));
  1551. if (is_blank_ident(name)) {
  1552. syntax_error(name, "Invalid polymorphic type definition with a blank identifier");
  1553. }
  1554. return ast_poly_type(f, dollar, name, nullptr);
  1555. } else {
  1556. token.string = str_lit("_");
  1557. expect_token(f, Token_Ident);
  1558. }
  1559. return ast_ident(f, token);
  1560. }
  1561. gb_internal Ast *parse_tag_expr(AstFile *f, Ast *expression) {
  1562. Token token = expect_token(f, Token_Hash);
  1563. Token name = expect_token(f, Token_Ident);
  1564. return ast_tag_expr(f, token, name, expression);
  1565. }
  1566. gb_internal Ast *unparen_expr(Ast *node) {
  1567. for (;;) {
  1568. if (node == nullptr) {
  1569. return nullptr;
  1570. }
  1571. if (node->kind != Ast_ParenExpr) {
  1572. return node;
  1573. }
  1574. node = node->ParenExpr.expr;
  1575. }
  1576. }
  1577. gb_internal Ast *unselector_expr(Ast *node) {
  1578. node = unparen_expr(node);
  1579. if (node == nullptr) {
  1580. return nullptr;
  1581. }
  1582. while (node->kind == Ast_SelectorExpr) {
  1583. node = node->SelectorExpr.selector;
  1584. }
  1585. return node;
  1586. }
  1587. gb_internal Ast *strip_or_return_expr(Ast *node) {
  1588. for (;;) {
  1589. if (node == nullptr) {
  1590. return node;
  1591. }
  1592. if (node->kind == Ast_OrReturnExpr) {
  1593. node = node->OrReturnExpr.expr;
  1594. } else if (node->kind == Ast_OrBranchExpr) {
  1595. node = node->OrBranchExpr.expr;
  1596. } else if (node->kind == Ast_ParenExpr) {
  1597. node = node->ParenExpr.expr;
  1598. } else {
  1599. return node;
  1600. }
  1601. }
  1602. }
  1603. gb_internal Ast *parse_value(AstFile *f);
  1604. gb_internal Array<Ast *> parse_element_list(AstFile *f) {
  1605. auto elems = array_make<Ast *>(ast_allocator(f));
  1606. while (f->curr_token.kind != Token_CloseBrace &&
  1607. f->curr_token.kind != Token_EOF) {
  1608. Ast *elem = parse_value(f);
  1609. if (f->curr_token.kind == Token_Eq) {
  1610. Token eq = expect_token(f, Token_Eq);
  1611. Ast *value = parse_value(f);
  1612. elem = ast_field_value(f, elem, value, eq);
  1613. }
  1614. array_add(&elems, elem);
  1615. if (!allow_field_separator(f)) {
  1616. break;
  1617. }
  1618. }
  1619. return elems;
  1620. }
  1621. gb_internal CommentGroup *consume_line_comment(AstFile *f) {
  1622. CommentGroup *comment = f->line_comment;
  1623. if (f->line_comment == f->lead_comment) {
  1624. f->lead_comment = nullptr;
  1625. }
  1626. f->line_comment = nullptr;
  1627. return comment;
  1628. }
  1629. gb_internal Array<Ast *> parse_enum_field_list(AstFile *f) {
  1630. auto elems = array_make<Ast *>(ast_allocator(f));
  1631. while (f->curr_token.kind != Token_CloseBrace &&
  1632. f->curr_token.kind != Token_EOF) {
  1633. CommentGroup *docs = f->lead_comment;
  1634. CommentGroup *comment = nullptr;
  1635. Ast *name = parse_value(f);
  1636. Ast *value = nullptr;
  1637. if (f->curr_token.kind == Token_Eq) {
  1638. Token eq = expect_token(f, Token_Eq);
  1639. value = parse_value(f);
  1640. }
  1641. comment = consume_line_comment(f);
  1642. Ast *elem = ast_enum_field_value(f, name, value, docs, comment);
  1643. array_add(&elems, elem);
  1644. if (!allow_field_separator(f)) {
  1645. break;
  1646. }
  1647. if (!elem->EnumFieldValue.comment) {
  1648. elem->EnumFieldValue.comment = consume_line_comment(f);
  1649. }
  1650. }
  1651. return elems;
  1652. }
  1653. gb_internal Ast *parse_literal_value(AstFile *f, Ast *type) {
  1654. Array<Ast *> elems = {};
  1655. Token open = expect_token(f, Token_OpenBrace);
  1656. isize expr_level = f->expr_level;
  1657. f->expr_level = 0;
  1658. if (f->curr_token.kind != Token_CloseBrace) {
  1659. elems = parse_element_list(f);
  1660. }
  1661. f->expr_level = expr_level;
  1662. Token close = expect_closing(f, Token_CloseBrace, str_lit("compound literal"));
  1663. return ast_compound_lit(f, type, elems, open, close);
  1664. }
  1665. gb_internal Ast *parse_value(AstFile *f) {
  1666. if (f->curr_token.kind == Token_OpenBrace) {
  1667. return parse_literal_value(f, nullptr);
  1668. }
  1669. Ast *value;
  1670. bool prev_allow_range = f->allow_range;
  1671. f->allow_range = true;
  1672. value = parse_expr(f, false);
  1673. f->allow_range = prev_allow_range;
  1674. return value;
  1675. }
  1676. gb_internal Ast *parse_type_or_ident(AstFile *f);
  1677. gb_internal void check_proc_add_tag(AstFile *f, Ast *tag_expr, u64 *tags, ProcTag tag, String const &tag_name) {
  1678. if (*tags & tag) {
  1679. syntax_error(tag_expr, "Procedure tag already used: %.*s", LIT(tag_name));
  1680. }
  1681. *tags |= tag;
  1682. }
  1683. gb_internal bool is_foreign_name_valid(String const &name) {
  1684. if (name.len == 0) {
  1685. return false;
  1686. }
  1687. isize offset = 0;
  1688. while (offset < name.len) {
  1689. Rune rune;
  1690. isize remaining = name.len - offset;
  1691. isize width = utf8_decode(name.text+offset, remaining, &rune);
  1692. if (rune == GB_RUNE_INVALID && width == 1) {
  1693. return false;
  1694. } else if (rune == GB_RUNE_BOM && remaining > 0) {
  1695. return false;
  1696. }
  1697. if (offset == 0) {
  1698. switch (rune) {
  1699. case '-':
  1700. case '$':
  1701. case '.':
  1702. case '_':
  1703. break;
  1704. default:
  1705. if (!gb_char_is_alpha(cast(char)rune))
  1706. return false;
  1707. break;
  1708. }
  1709. } else {
  1710. switch (rune) {
  1711. case '-':
  1712. case '$':
  1713. case '.':
  1714. case '_':
  1715. break;
  1716. default:
  1717. if (!gb_char_is_alphanumeric(cast(char)rune)) {
  1718. return false;
  1719. }
  1720. break;
  1721. }
  1722. }
  1723. offset += width;
  1724. }
  1725. return true;
  1726. }
  1727. gb_internal void parse_proc_tags(AstFile *f, u64 *tags) {
  1728. GB_ASSERT(tags != nullptr);
  1729. while (f->curr_token.kind == Token_Hash) {
  1730. Ast *tag_expr = parse_tag_expr(f, nullptr);
  1731. ast_node(te, TagExpr, tag_expr);
  1732. String tag_name = te->name.string;
  1733. #define ELSE_IF_ADD_TAG(name) \
  1734. else if (tag_name == #name) { \
  1735. check_proc_add_tag(f, tag_expr, tags, ProcTag_##name, tag_name); \
  1736. }
  1737. if (false) {}
  1738. ELSE_IF_ADD_TAG(optional_ok)
  1739. ELSE_IF_ADD_TAG(optional_allocator_error)
  1740. ELSE_IF_ADD_TAG(require_results)
  1741. ELSE_IF_ADD_TAG(bounds_check)
  1742. ELSE_IF_ADD_TAG(no_bounds_check)
  1743. ELSE_IF_ADD_TAG(type_assert)
  1744. ELSE_IF_ADD_TAG(no_type_assert)
  1745. else {
  1746. syntax_error(tag_expr, "Unknown procedure type tag #%.*s", LIT(tag_name));
  1747. }
  1748. #undef ELSE_IF_ADD_TAG
  1749. }
  1750. if ((*tags & ProcTag_bounds_check) && (*tags & ProcTag_no_bounds_check)) {
  1751. syntax_error(f->curr_token, "You cannot apply both #bounds_check and #no_bounds_check to a procedure");
  1752. }
  1753. if ((*tags & ProcTag_type_assert) && (*tags & ProcTag_no_type_assert)) {
  1754. syntax_error(f->curr_token, "You cannot apply both #type_assert and #no_type_assert to a procedure");
  1755. }
  1756. }
  1757. gb_internal Array<Ast *> parse_lhs_expr_list (AstFile *f);
  1758. gb_internal Array<Ast *> parse_rhs_expr_list (AstFile *f);
  1759. gb_internal Ast * parse_simple_stmt (AstFile *f, u32 flags);
  1760. gb_internal Ast * parse_type (AstFile *f);
  1761. gb_internal Ast * parse_call_expr (AstFile *f, Ast *operand);
  1762. gb_internal Ast * parse_struct_field_list(AstFile *f, isize *name_count_);
  1763. gb_internal Ast *parse_field_list(AstFile *f, isize *name_count_, u32 allowed_flags, TokenKind follow, bool allow_default_parameters, bool allow_typeid_token);
  1764. gb_internal Ast *parse_unary_expr(AstFile *f, bool lhs);
  1765. gb_internal Ast *convert_stmt_to_expr(AstFile *f, Ast *statement, String const &kind) {
  1766. if (statement == nullptr) {
  1767. return nullptr;
  1768. }
  1769. if (statement->kind == Ast_ExprStmt) {
  1770. return statement->ExprStmt.expr;
  1771. }
  1772. syntax_error(f->curr_token, "Expected '%.*s', found a simple statement.", LIT(kind));
  1773. Token end = f->curr_token;
  1774. if (f->tokens.count < f->curr_token_index) {
  1775. end = f->tokens[f->curr_token_index+1];
  1776. }
  1777. return ast_bad_expr(f, f->curr_token, end);
  1778. }
  1779. gb_internal Ast *convert_stmt_to_body(AstFile *f, Ast *stmt) {
  1780. if (stmt->kind == Ast_BlockStmt) {
  1781. syntax_error(stmt, "Expected a normal statement rather than a block statement");
  1782. return stmt;
  1783. }
  1784. if (stmt->kind == Ast_EmptyStmt) {
  1785. syntax_error(stmt, "Expected a non-empty statement");
  1786. }
  1787. GB_ASSERT(is_ast_stmt(stmt) || is_ast_decl(stmt));
  1788. Token open = ast_token(stmt);
  1789. Token close = ast_token(stmt);
  1790. auto stmts = array_make<Ast *>(ast_allocator(f), 0, 1);
  1791. array_add(&stmts, stmt);
  1792. return ast_block_stmt(f, stmts, open, close);
  1793. }
  1794. gb_internal void check_polymorphic_params_for_type(AstFile *f, Ast *polymorphic_params, Token token) {
  1795. if (polymorphic_params == nullptr) {
  1796. return;
  1797. }
  1798. if (polymorphic_params->kind != Ast_FieldList) {
  1799. return;
  1800. }
  1801. ast_node(fl, FieldList, polymorphic_params);
  1802. for (Ast *field : fl->list) {
  1803. if (field->kind != Ast_Field) {
  1804. continue;
  1805. }
  1806. for (Ast *name : field->Field.names) {
  1807. if (name->kind != field->Field.names[0]->kind) {
  1808. syntax_error(name, "Mixture of polymorphic names using both $ and not for %.*s parameters", LIT(token.string));
  1809. return;
  1810. }
  1811. }
  1812. }
  1813. }
  1814. gb_internal bool ast_on_same_line(Token const &x, Ast *yp) {
  1815. Token y = ast_token(yp);
  1816. return x.pos.line == y.pos.line;
  1817. }
  1818. gb_internal Ast *parse_force_inlining_operand(AstFile *f, Token token) {
  1819. Ast *expr = parse_unary_expr(f, false);
  1820. Ast *e = strip_or_return_expr(expr);
  1821. if (e->kind != Ast_ProcLit && e->kind != Ast_CallExpr) {
  1822. syntax_error(expr, "%.*s must be followed by a procedure literal or call, got %.*s", LIT(token.string), LIT(ast_strings[expr->kind]));
  1823. return ast_bad_expr(f, token, f->curr_token);
  1824. }
  1825. ProcInlining pi = ProcInlining_none;
  1826. if (token.kind == Token_Ident) {
  1827. if (token.string == "force_inline") {
  1828. pi = ProcInlining_inline;
  1829. } else if (token.string == "force_no_inline") {
  1830. pi = ProcInlining_no_inline;
  1831. }
  1832. }
  1833. if (pi != ProcInlining_none) {
  1834. if (e->kind == Ast_ProcLit) {
  1835. if (expr->ProcLit.inlining != ProcInlining_none &&
  1836. expr->ProcLit.inlining != pi) {
  1837. syntax_error(expr, "Cannot apply both '#force_inline' and '#force_no_inline' to a procedure literal");
  1838. }
  1839. expr->ProcLit.inlining = pi;
  1840. } else if (e->kind == Ast_CallExpr) {
  1841. if (expr->CallExpr.inlining != ProcInlining_none &&
  1842. expr->CallExpr.inlining != pi) {
  1843. syntax_error(expr, "Cannot apply both '#force_inline' and '#force_no_inline' to a procedure call");
  1844. }
  1845. expr->CallExpr.inlining = pi;
  1846. }
  1847. }
  1848. return expr;
  1849. }
  1850. gb_internal Ast *parse_check_directive_for_statement(Ast *s, Token const &tag_token, u16 state_flag) {
  1851. String name = tag_token.string;
  1852. if (s == nullptr) {
  1853. syntax_error(tag_token, "Invalid operand for #%.*s", LIT(name));
  1854. return nullptr;
  1855. }
  1856. if (s != nullptr && s->kind == Ast_EmptyStmt) {
  1857. if (s->EmptyStmt.token.string == "\n") {
  1858. syntax_error(tag_token, "#%.*s cannot be followed by a newline", LIT(name));
  1859. } else {
  1860. syntax_error(tag_token, "#%.*s cannot be applied to an empty statement ';'", LIT(name));
  1861. }
  1862. }
  1863. if (s->state_flags & state_flag) {
  1864. syntax_error(tag_token, "#%.*s has been applied multiple times", LIT(name));
  1865. }
  1866. s->state_flags |= state_flag;
  1867. switch (state_flag) {
  1868. case StateFlag_bounds_check:
  1869. if ((s->state_flags & StateFlag_no_bounds_check) != 0) {
  1870. syntax_error(tag_token, "#bounds_check and #no_bounds_check cannot be applied together");
  1871. }
  1872. break;
  1873. case StateFlag_no_bounds_check:
  1874. if ((s->state_flags & StateFlag_bounds_check) != 0) {
  1875. syntax_error(tag_token, "#bounds_check and #no_bounds_check cannot be applied together");
  1876. }
  1877. break;
  1878. case StateFlag_type_assert:
  1879. if ((s->state_flags & StateFlag_no_type_assert) != 0) {
  1880. syntax_error(tag_token, "#type_assert and #no_type_assert cannot be applied together");
  1881. }
  1882. break;
  1883. case StateFlag_no_type_assert:
  1884. if ((s->state_flags & StateFlag_type_assert) != 0) {
  1885. syntax_error(tag_token, "#type_assert and #no_type_assert cannot be applied together");
  1886. }
  1887. break;
  1888. }
  1889. switch (state_flag) {
  1890. case StateFlag_bounds_check:
  1891. case StateFlag_no_bounds_check:
  1892. case StateFlag_type_assert:
  1893. case StateFlag_no_type_assert:
  1894. switch (s->kind) {
  1895. case Ast_BlockStmt:
  1896. case Ast_IfStmt:
  1897. case Ast_WhenStmt:
  1898. case Ast_ForStmt:
  1899. case Ast_RangeStmt:
  1900. case Ast_UnrollRangeStmt:
  1901. case Ast_SwitchStmt:
  1902. case Ast_TypeSwitchStmt:
  1903. case Ast_ReturnStmt:
  1904. case Ast_DeferStmt:
  1905. case Ast_AssignStmt:
  1906. // Okay
  1907. break;
  1908. case Ast_ValueDecl:
  1909. if (!s->ValueDecl.is_mutable) {
  1910. syntax_error(tag_token, "#%.*s may only be applied to a variable declaration, and not a constant value declaration", LIT(name));
  1911. }
  1912. break;
  1913. default:
  1914. syntax_error(tag_token, "#%.*s may only be applied to the following statements: '{}', 'if', 'when', 'for', 'switch', 'return', 'defer', assignment, variable declaration", LIT(name));
  1915. break;
  1916. }
  1917. break;
  1918. }
  1919. return s;
  1920. }
  1921. gb_internal Array<Ast *> parse_union_variant_list(AstFile *f) {
  1922. auto variants = array_make<Ast *>(ast_allocator(f));
  1923. while (f->curr_token.kind != Token_CloseBrace &&
  1924. f->curr_token.kind != Token_EOF) {
  1925. Ast *type = parse_type(f);
  1926. if (type->kind != Ast_BadExpr) {
  1927. array_add(&variants, type);
  1928. }
  1929. if (!allow_field_separator(f)) {
  1930. break;
  1931. }
  1932. }
  1933. return variants;
  1934. }
  1935. gb_internal void parser_check_polymorphic_record_parameters(AstFile *f, Ast *polymorphic_params) {
  1936. if (polymorphic_params == nullptr) {
  1937. return;
  1938. }
  1939. if (polymorphic_params->kind != Ast_FieldList) {
  1940. return;
  1941. }
  1942. enum {Unknown, Dollar, Bare} prefix = Unknown;
  1943. gb_unused(prefix);
  1944. for (Ast *field : polymorphic_params->FieldList.list) {
  1945. if (field == nullptr || field->kind != Ast_Field) {
  1946. continue;
  1947. }
  1948. for (Ast *name : field->Field.names) {
  1949. if (name == nullptr) {
  1950. continue;
  1951. }
  1952. bool error = false;
  1953. if (name->kind == Ast_Ident) {
  1954. switch (prefix) {
  1955. case Unknown: prefix = Bare; break;
  1956. case Dollar: error = true; break;
  1957. case Bare: break;
  1958. }
  1959. } else if (name->kind == Ast_PolyType) {
  1960. switch (prefix) {
  1961. case Unknown: prefix = Dollar; break;
  1962. case Dollar: break;
  1963. case Bare: error = true; break;
  1964. }
  1965. }
  1966. if (error) {
  1967. syntax_error(name, "Mixture of polymorphic $ names and normal identifiers are not allowed within record parameters");
  1968. }
  1969. }
  1970. }
  1971. }
  1972. gb_internal Ast *parse_operand(AstFile *f, bool lhs) {
  1973. Ast *operand = nullptr; // Operand
  1974. switch (f->curr_token.kind) {
  1975. case Token_Ident:
  1976. return parse_ident(f);
  1977. case Token_Uninit:
  1978. return ast_uninit(f, expect_token(f, Token_Uninit));
  1979. case Token_context:
  1980. return ast_implicit(f, expect_token(f, Token_context));
  1981. case Token_Integer:
  1982. case Token_Float:
  1983. case Token_Imag:
  1984. case Token_Rune:
  1985. return ast_basic_lit(f, advance_token(f));
  1986. case Token_String:
  1987. return ast_basic_lit(f, advance_token(f));
  1988. case Token_OpenBrace:
  1989. if (!lhs) return parse_literal_value(f, nullptr);
  1990. break;
  1991. case Token_OpenParen: {
  1992. bool allow_newline;
  1993. isize prev_expr_level;
  1994. Token open, close;
  1995. // NOTE(bill): Skip the Paren Expression
  1996. open = expect_token(f, Token_OpenParen);
  1997. if (f->prev_token.kind == Token_CloseParen) {
  1998. close = expect_token(f, Token_CloseParen);
  1999. syntax_error(open, "Invalid parentheses expression with no inside expression");
  2000. return ast_bad_expr(f, open, close);
  2001. }
  2002. prev_expr_level = f->expr_level;
  2003. allow_newline = f->allow_newline;
  2004. if (f->expr_level < 0) {
  2005. f->allow_newline = false;
  2006. }
  2007. // NOTE(bill): enforce it to >0
  2008. f->expr_level = gb_max(f->expr_level, 0)+1;
  2009. operand = parse_expr(f, false);
  2010. f->allow_newline = allow_newline;
  2011. f->expr_level = prev_expr_level;
  2012. close = expect_token(f, Token_CloseParen);
  2013. return ast_paren_expr(f, operand, open, close);
  2014. }
  2015. case Token_distinct: {
  2016. Token token = expect_token(f, Token_distinct);
  2017. Ast *type = parse_type(f);
  2018. return ast_distinct_type(f, token, type);
  2019. }
  2020. case Token_Hash: {
  2021. Token token = expect_token(f, Token_Hash);
  2022. Token name = expect_token(f, Token_Ident);
  2023. if (name.string == "type") {
  2024. return ast_helper_type(f, token, parse_type(f));
  2025. } else if ( name.string == "simd") {
  2026. Ast *tag = ast_basic_directive(f, token, name);
  2027. Ast *original_type = parse_type(f);
  2028. Ast *type = unparen_expr(original_type);
  2029. switch (type->kind) {
  2030. case Ast_ArrayType: type->ArrayType.tag = tag; break;
  2031. default:
  2032. syntax_error(type, "Expected a fixed array type after #%.*s, got %.*s", LIT(name.string), LIT(ast_strings[type->kind]));
  2033. break;
  2034. }
  2035. return original_type;
  2036. } else if (name.string == "soa") {
  2037. Ast *tag = ast_basic_directive(f, token, name);
  2038. Ast *original_type = parse_type(f);
  2039. Ast *type = unparen_expr(original_type);
  2040. switch (type->kind) {
  2041. case Ast_ArrayType: type->ArrayType.tag = tag; break;
  2042. case Ast_DynamicArrayType: type->DynamicArrayType.tag = tag; break;
  2043. case Ast_PointerType: type->PointerType.tag = tag; break;
  2044. default:
  2045. syntax_error(type, "Expected an array or pointer type after #%.*s, got %.*s", LIT(name.string), LIT(ast_strings[type->kind]));
  2046. break;
  2047. }
  2048. return original_type;
  2049. } else if (name.string == "row_major" ||
  2050. name.string == "column_major") {
  2051. Ast *original_type = parse_type(f);
  2052. Ast *type = unparen_expr(original_type);
  2053. switch (type->kind) {
  2054. case Ast_MatrixType:
  2055. type->MatrixType.is_row_major = (name.string == "row_major");
  2056. break;
  2057. default:
  2058. syntax_error(type, "Expected a matrix type after #%.*s, got %.*s", LIT(name.string), LIT(ast_strings[type->kind]));
  2059. break;
  2060. }
  2061. return original_type;
  2062. } else if (name.string == "partial") {
  2063. Ast *tag = ast_basic_directive(f, token, name);
  2064. Ast *original_expr = parse_expr(f, lhs);
  2065. Ast *expr = unparen_expr(original_expr);
  2066. if (expr == nullptr) {
  2067. syntax_error(name, "Expected a compound literal after #%.*s", LIT(name.string));
  2068. return ast_bad_expr(f, token, name);
  2069. }
  2070. switch (expr->kind) {
  2071. case Ast_CompoundLit:
  2072. expr->CompoundLit.tag = tag;
  2073. break;
  2074. default:
  2075. syntax_error(expr, "Expected a compound literal after #%.*s, got %.*s", LIT(name.string), LIT(ast_strings[expr->kind]));
  2076. break;
  2077. }
  2078. return original_expr;
  2079. } else if (name.string == "sparse") {
  2080. Ast *tag = ast_basic_directive(f, token, name);
  2081. Ast *original_type = parse_type(f);
  2082. Ast *type = unparen_expr(original_type);
  2083. switch (type->kind) {
  2084. case Ast_ArrayType: type->ArrayType.tag = tag; break;
  2085. default:
  2086. syntax_error(type, "Expected an enumerated array type after #%.*s, got %.*s", LIT(name.string), LIT(ast_strings[type->kind]));
  2087. break;
  2088. }
  2089. return original_type;
  2090. } else if (name.string == "bounds_check") {
  2091. Ast *operand = parse_expr(f, lhs);
  2092. return parse_check_directive_for_statement(operand, name, StateFlag_bounds_check);
  2093. } else if (name.string == "no_bounds_check") {
  2094. Ast *operand = parse_expr(f, lhs);
  2095. return parse_check_directive_for_statement(operand, name, StateFlag_no_bounds_check);
  2096. } else if (name.string == "type_assert") {
  2097. Ast *operand = parse_expr(f, lhs);
  2098. return parse_check_directive_for_statement(operand, name, StateFlag_type_assert);
  2099. } else if (name.string == "no_type_assert") {
  2100. Ast *operand = parse_expr(f, lhs);
  2101. return parse_check_directive_for_statement(operand, name, StateFlag_no_type_assert);
  2102. } else if (name.string == "relative") {
  2103. Ast *tag = ast_basic_directive(f, token, name);
  2104. if (f->curr_token.kind != Token_OpenParen) {
  2105. syntax_error(tag, "expected #relative(<integer type>) <type>");
  2106. } else {
  2107. tag = parse_call_expr(f, tag);
  2108. }
  2109. Ast *type = parse_type(f);
  2110. return ast_relative_type(f, tag, type);
  2111. } else if (name.string == "force_inline" ||
  2112. name.string == "force_no_inline") {
  2113. return parse_force_inlining_operand(f, name);
  2114. }
  2115. return ast_basic_directive(f, token, name);
  2116. }
  2117. // Parse Procedure Type or Literal or Group
  2118. case Token_proc: {
  2119. Token token = expect_token(f, Token_proc);
  2120. if (f->curr_token.kind == Token_OpenBrace) { // ProcGroup
  2121. Token open = expect_token(f, Token_OpenBrace);
  2122. auto args = array_make<Ast *>(ast_allocator(f));
  2123. while (f->curr_token.kind != Token_CloseBrace &&
  2124. f->curr_token.kind != Token_EOF) {
  2125. Ast *elem = parse_expr(f, false);
  2126. array_add(&args, elem);
  2127. if (!allow_field_separator(f)) {
  2128. break;
  2129. }
  2130. }
  2131. Token close = expect_token(f, Token_CloseBrace);
  2132. if (args.count == 0) {
  2133. syntax_error(token, "Expected a least 1 argument in a procedure group");
  2134. }
  2135. return ast_proc_group(f, token, open, close, args);
  2136. }
  2137. Ast *type = parse_proc_type(f, token);
  2138. Token where_token = {};
  2139. Array<Ast *> where_clauses = {};
  2140. u64 tags = 0;
  2141. skip_possible_newline_for_literal(f);
  2142. if (f->curr_token.kind == Token_where) {
  2143. where_token = expect_token(f, Token_where);
  2144. isize prev_level = f->expr_level;
  2145. f->expr_level = -1;
  2146. where_clauses = parse_rhs_expr_list(f);
  2147. f->expr_level = prev_level;
  2148. }
  2149. parse_proc_tags(f, &tags);
  2150. if ((tags & ProcTag_require_results) != 0) {
  2151. syntax_error(f->curr_token, "#require_results has now been replaced as an attribute @(require_results) on the declaration");
  2152. tags &= ~ProcTag_require_results;
  2153. }
  2154. GB_ASSERT(type->kind == Ast_ProcType);
  2155. type->ProcType.tags = tags;
  2156. if (f->allow_type && f->expr_level < 0) {
  2157. if (tags != 0) {
  2158. syntax_error(token, "A procedure type cannot have suffix tags");
  2159. }
  2160. if (where_token.kind != Token_Invalid) {
  2161. syntax_error(where_token, "'where' clauses are not allowed on procedure types");
  2162. }
  2163. return type;
  2164. }
  2165. skip_possible_newline_for_literal(f);
  2166. if (allow_token(f, Token_Uninit)) {
  2167. if (where_token.kind != Token_Invalid) {
  2168. syntax_error(where_token, "'where' clauses are not allowed on procedure literals without a defined body (replaced with ---)");
  2169. }
  2170. return ast_proc_lit(f, type, nullptr, tags, where_token, where_clauses);
  2171. } else if (f->curr_token.kind == Token_OpenBrace) {
  2172. Ast *curr_proc = f->curr_proc;
  2173. Ast *body = nullptr;
  2174. f->curr_proc = type;
  2175. body = parse_body(f);
  2176. f->curr_proc = curr_proc;
  2177. // Apply the tags directly to the body rather than the type
  2178. if (tags & ProcTag_no_bounds_check) {
  2179. body->state_flags |= StateFlag_no_bounds_check;
  2180. }
  2181. if (tags & ProcTag_bounds_check) {
  2182. body->state_flags |= StateFlag_bounds_check;
  2183. }
  2184. if (tags & ProcTag_no_type_assert) {
  2185. body->state_flags |= StateFlag_no_type_assert;
  2186. }
  2187. if (tags & ProcTag_type_assert) {
  2188. body->state_flags |= StateFlag_type_assert;
  2189. }
  2190. return ast_proc_lit(f, type, body, tags, where_token, where_clauses);
  2191. } else if (allow_token(f, Token_do)) {
  2192. Ast *curr_proc = f->curr_proc;
  2193. Ast *body = nullptr;
  2194. f->curr_proc = type;
  2195. body = convert_stmt_to_body(f, parse_stmt(f));
  2196. f->curr_proc = curr_proc;
  2197. syntax_error(body, "'do' for procedure bodies is not allowed, prefer {}");
  2198. return ast_proc_lit(f, type, body, tags, where_token, where_clauses);
  2199. }
  2200. if (tags != 0) {
  2201. syntax_error(token, "A procedure type cannot have suffix tags");
  2202. }
  2203. if (where_token.kind != Token_Invalid) {
  2204. syntax_error(where_token, "'where' clauses are not allowed on procedure types");
  2205. }
  2206. return type;
  2207. }
  2208. // Check for Types
  2209. case Token_Dollar: {
  2210. Token token = expect_token(f, Token_Dollar);
  2211. Ast *type = parse_ident(f);
  2212. if (is_blank_ident(type)) {
  2213. syntax_error(type, "Invalid polymorphic type definition with a blank identifier");
  2214. }
  2215. Ast *specialization = nullptr;
  2216. if (allow_token(f, Token_Quo)) {
  2217. specialization = parse_type(f);
  2218. }
  2219. return ast_poly_type(f, token, type, specialization);
  2220. } break;
  2221. case Token_typeid: {
  2222. Token token = expect_token(f, Token_typeid);
  2223. return ast_typeid_type(f, token, nullptr);
  2224. } break;
  2225. case Token_Pointer: {
  2226. Token token = expect_token(f, Token_Pointer);
  2227. Ast *elem = parse_type(f);
  2228. return ast_pointer_type(f, token, elem);
  2229. } break;
  2230. case Token_Mul:
  2231. return parse_unary_expr(f, true);
  2232. case Token_OpenBracket: {
  2233. Token token = expect_token(f, Token_OpenBracket);
  2234. Ast *count_expr = nullptr;
  2235. if (f->curr_token.kind == Token_Pointer) {
  2236. expect_token(f, Token_Pointer);
  2237. expect_token(f, Token_CloseBracket);
  2238. return ast_multi_pointer_type(f, token, parse_type(f));
  2239. } else if (f->curr_token.kind == Token_Question) {
  2240. count_expr = ast_unary_expr(f, expect_token(f, Token_Question), nullptr);
  2241. } else if (allow_token(f, Token_dynamic)) {
  2242. expect_token(f, Token_CloseBracket);
  2243. return ast_dynamic_array_type(f, token, parse_type(f));
  2244. } else if (f->curr_token.kind != Token_CloseBracket) {
  2245. f->expr_level++;
  2246. count_expr = parse_expr(f, false);
  2247. f->expr_level--;
  2248. }
  2249. expect_token(f, Token_CloseBracket);
  2250. return ast_array_type(f, token, count_expr, parse_type(f));
  2251. } break;
  2252. case Token_map: {
  2253. Token token = expect_token(f, Token_map);
  2254. Ast *key = nullptr;
  2255. Ast *value = nullptr;
  2256. Token open, close;
  2257. open = expect_token_after(f, Token_OpenBracket, "map");
  2258. key = parse_expr(f, true);
  2259. close = expect_token(f, Token_CloseBracket);
  2260. value = parse_type(f);
  2261. return ast_map_type(f, token, key, value);
  2262. } break;
  2263. case Token_matrix: {
  2264. Token token = expect_token(f, Token_matrix);
  2265. Ast *row_count = nullptr;
  2266. Ast *column_count = nullptr;
  2267. Ast *type = nullptr;
  2268. Token open, close;
  2269. open = expect_token_after(f, Token_OpenBracket, "matrix");
  2270. row_count = parse_expr(f, true);
  2271. expect_token(f, Token_Comma);
  2272. column_count = parse_expr(f, true);
  2273. close = expect_token(f, Token_CloseBracket);
  2274. type = parse_type(f);
  2275. return ast_matrix_type(f, token, row_count, column_count, type);
  2276. } break;
  2277. case Token_bit_field: {
  2278. Token token = expect_token(f, Token_bit_field);
  2279. isize prev_level;
  2280. prev_level = f->expr_level;
  2281. f->expr_level = -1;
  2282. Ast *backing_type = parse_type_or_ident(f);
  2283. if (backing_type == nullptr) {
  2284. Token token = advance_token(f);
  2285. syntax_error(token, "Expected a backing type for a 'bit_field'");
  2286. backing_type = ast_bad_expr(f, token, f->curr_token);
  2287. }
  2288. skip_possible_newline_for_literal(f);
  2289. Token open = expect_token_after(f, Token_OpenBrace, "bit_field");
  2290. auto fields = array_make<Ast *>(ast_allocator(f), 0, 0);
  2291. while (f->curr_token.kind != Token_CloseBrace &&
  2292. f->curr_token.kind != Token_EOF) {
  2293. CommentGroup *docs = nullptr;
  2294. CommentGroup *comment = nullptr;
  2295. Ast *name = parse_ident(f);
  2296. bool err_once = false;
  2297. while (allow_token(f, Token_Comma)) {
  2298. Ast *dummy_name = parse_ident(f);
  2299. if (!err_once) {
  2300. error(dummy_name, "'bit_field' fields do not support multiple names per field");
  2301. err_once = true;
  2302. }
  2303. }
  2304. expect_token(f, Token_Colon);
  2305. Ast *type = parse_type(f);
  2306. expect_token(f, Token_Or);
  2307. Ast *bit_size = parse_expr(f, true);
  2308. Token tag = {};
  2309. if (f->curr_token.kind == Token_String) {
  2310. tag = expect_token(f, Token_String);
  2311. }
  2312. Ast *bf_field = ast_bit_field_field(f, name, type, bit_size, tag, docs, comment);
  2313. array_add(&fields, bf_field);
  2314. if (!allow_field_separator(f)) {
  2315. break;
  2316. }
  2317. }
  2318. Token close = expect_closing_brace_of_field_list(f);
  2319. f->expr_level = prev_level;
  2320. return ast_bit_field_type(f, token, backing_type, open, fields, close);
  2321. }
  2322. case Token_struct: {
  2323. Token token = expect_token(f, Token_struct);
  2324. Ast *polymorphic_params = nullptr;
  2325. bool is_packed = false;
  2326. bool is_raw_union = false;
  2327. bool no_copy = false;
  2328. Ast *align = nullptr;
  2329. Ast *field_align = nullptr;
  2330. if (allow_token(f, Token_OpenParen)) {
  2331. isize param_count = 0;
  2332. polymorphic_params = parse_field_list(f, &param_count, 0, Token_CloseParen, true, true);
  2333. if (param_count == 0) {
  2334. syntax_error(polymorphic_params, "Expected at least 1 polymorphic parameter");
  2335. polymorphic_params = nullptr;
  2336. }
  2337. expect_token_after(f, Token_CloseParen, "parameter list");
  2338. check_polymorphic_params_for_type(f, polymorphic_params, token);
  2339. }
  2340. isize prev_level;
  2341. prev_level = f->expr_level;
  2342. f->expr_level = -1;
  2343. while (allow_token(f, Token_Hash)) {
  2344. Token tag = expect_token_after(f, Token_Ident, "#");
  2345. if (tag.string == "packed") {
  2346. if (is_packed) {
  2347. syntax_error(tag, "Duplicate struct tag '#%.*s'", LIT(tag.string));
  2348. }
  2349. is_packed = true;
  2350. } else if (tag.string == "align") {
  2351. if (align) {
  2352. syntax_error(tag, "Duplicate struct tag '#%.*s'", LIT(tag.string));
  2353. }
  2354. align = parse_expr(f, true);
  2355. if (align && align->kind != Ast_ParenExpr) {
  2356. ERROR_BLOCK();
  2357. gbString s = expr_to_string(align);
  2358. syntax_warning(tag, "#align requires parentheses around the expression");
  2359. error_line("\tSuggestion: #align(%s)", s);
  2360. gb_string_free(s);
  2361. }
  2362. } else if (tag.string == "field_align") {
  2363. if (field_align) {
  2364. syntax_error(tag, "Duplicate struct tag '#%.*s'", LIT(tag.string));
  2365. }
  2366. field_align = parse_expr(f, true);
  2367. if (field_align && field_align->kind != Ast_ParenExpr) {
  2368. ERROR_BLOCK();
  2369. gbString s = expr_to_string(field_align);
  2370. syntax_warning(tag, "#field_align requires parentheses around the expression");
  2371. error_line("\tSuggestion: #field_align(%s)", s);
  2372. gb_string_free(s);
  2373. }
  2374. } else if (tag.string == "raw_union") {
  2375. if (is_raw_union) {
  2376. syntax_error(tag, "Duplicate struct tag '#%.*s'", LIT(tag.string));
  2377. }
  2378. is_raw_union = true;
  2379. } else if (tag.string == "no_copy") {
  2380. if (no_copy) {
  2381. syntax_error(tag, "Duplicate struct tag '#%.*s'", LIT(tag.string));
  2382. }
  2383. no_copy = true;
  2384. } else {
  2385. syntax_error(tag, "Invalid struct tag '#%.*s'", LIT(tag.string));
  2386. }
  2387. }
  2388. f->expr_level = prev_level;
  2389. if (is_raw_union && is_packed) {
  2390. is_packed = false;
  2391. syntax_error(token, "'#raw_union' cannot also be '#packed'");
  2392. }
  2393. Token where_token = {};
  2394. Array<Ast *> where_clauses = {};
  2395. skip_possible_newline_for_literal(f);
  2396. if (f->curr_token.kind == Token_where) {
  2397. where_token = expect_token(f, Token_where);
  2398. prev_level = f->expr_level;
  2399. f->expr_level = -1;
  2400. where_clauses = parse_rhs_expr_list(f);
  2401. f->expr_level = prev_level;
  2402. }
  2403. skip_possible_newline_for_literal(f);
  2404. Token open = expect_token_after(f, Token_OpenBrace, "struct");
  2405. isize name_count = 0;
  2406. Ast *fields = parse_struct_field_list(f, &name_count);
  2407. Token close = expect_closing_brace_of_field_list(f);
  2408. Slice<Ast *> decls = {};
  2409. if (fields != nullptr) {
  2410. GB_ASSERT(fields->kind == Ast_FieldList);
  2411. decls = fields->FieldList.list;
  2412. }
  2413. parser_check_polymorphic_record_parameters(f, polymorphic_params);
  2414. return ast_struct_type(f, token, decls, name_count, polymorphic_params, is_packed, is_raw_union, no_copy, align, field_align, where_token, where_clauses);
  2415. } break;
  2416. case Token_union: {
  2417. Token token = expect_token(f, Token_union);
  2418. Ast *polymorphic_params = nullptr;
  2419. Ast *align = nullptr;
  2420. bool no_nil = false;
  2421. bool maybe = false;
  2422. bool shared_nil = false;
  2423. UnionTypeKind union_kind = UnionType_Normal;
  2424. Token start_token = f->curr_token;
  2425. if (allow_token(f, Token_OpenParen)) {
  2426. isize param_count = 0;
  2427. polymorphic_params = parse_field_list(f, &param_count, 0, Token_CloseParen, true, true);
  2428. if (param_count == 0) {
  2429. syntax_error(polymorphic_params, "Expected at least 1 polymorphic parametric");
  2430. polymorphic_params = nullptr;
  2431. }
  2432. expect_token_after(f, Token_CloseParen, "parameter list");
  2433. check_polymorphic_params_for_type(f, polymorphic_params, token);
  2434. }
  2435. while (allow_token(f, Token_Hash)) {
  2436. Token tag = expect_token_after(f, Token_Ident, "#");
  2437. if (tag.string == "align") {
  2438. if (align) {
  2439. syntax_error(tag, "Duplicate union tag '#%.*s'", LIT(tag.string));
  2440. }
  2441. align = parse_expr(f, true);
  2442. if (align && align->kind != Ast_ParenExpr) {
  2443. ERROR_BLOCK();
  2444. gbString s = expr_to_string(align);
  2445. syntax_warning(tag, "#align requires parentheses around the expression");
  2446. error_line("\tSuggestion: #align(%s)", s);
  2447. gb_string_free(s);
  2448. }
  2449. } else if (tag.string == "no_nil") {
  2450. if (no_nil) {
  2451. syntax_error(tag, "Duplicate union tag '#%.*s'", LIT(tag.string));
  2452. }
  2453. no_nil = true;
  2454. } else if (tag.string == "shared_nil") {
  2455. if (shared_nil) {
  2456. syntax_error(tag, "Duplicate union tag '#%.*s'", LIT(tag.string));
  2457. }
  2458. shared_nil = true;
  2459. } else if (tag.string == "maybe") {
  2460. if (maybe) {
  2461. syntax_error(tag, "Duplicate union tag '#%.*s'", LIT(tag.string));
  2462. }
  2463. maybe = true;
  2464. }else {
  2465. syntax_error(tag, "Invalid union tag '#%.*s'", LIT(tag.string));
  2466. }
  2467. }
  2468. if (no_nil && shared_nil) {
  2469. syntax_error(f->curr_token, "#shared_nil and #no_nil cannot be applied together");
  2470. }
  2471. if (maybe) {
  2472. syntax_error(f->curr_token, "#maybe functionality has now been merged with standard 'union' functionality");
  2473. }
  2474. if (no_nil) {
  2475. union_kind = UnionType_no_nil;
  2476. } else if (shared_nil) {
  2477. union_kind = UnionType_shared_nil;
  2478. }
  2479. skip_possible_newline_for_literal(f);
  2480. Token where_token = {};
  2481. Array<Ast *> where_clauses = {};
  2482. if (f->curr_token.kind == Token_where) {
  2483. where_token = expect_token(f, Token_where);
  2484. isize prev_level = f->expr_level;
  2485. f->expr_level = -1;
  2486. where_clauses = parse_rhs_expr_list(f);
  2487. f->expr_level = prev_level;
  2488. }
  2489. skip_possible_newline_for_literal(f);
  2490. Token open = expect_token_after(f, Token_OpenBrace, "union");
  2491. auto variants = parse_union_variant_list(f);
  2492. Token close = expect_closing_brace_of_field_list(f);
  2493. parser_check_polymorphic_record_parameters(f, polymorphic_params);
  2494. return ast_union_type(f, token, variants, polymorphic_params, align, union_kind, where_token, where_clauses);
  2495. } break;
  2496. case Token_enum: {
  2497. Token token = expect_token(f, Token_enum);
  2498. Ast *base_type = nullptr;
  2499. if (f->curr_token.kind != Token_OpenBrace) {
  2500. base_type = parse_type(f);
  2501. }
  2502. skip_possible_newline_for_literal(f);
  2503. Token open = expect_token(f, Token_OpenBrace);
  2504. Array<Ast *> values = parse_enum_field_list(f);
  2505. Token close = expect_closing_brace_of_field_list(f);
  2506. return ast_enum_type(f, token, base_type, values);
  2507. } break;
  2508. case Token_bit_set: {
  2509. Token token = expect_token(f, Token_bit_set);
  2510. expect_token(f, Token_OpenBracket);
  2511. Ast *elem = nullptr;
  2512. Ast *underlying = nullptr;
  2513. bool prev_allow_range = f->allow_range;
  2514. f->allow_range = true;
  2515. elem = parse_expr(f, true);
  2516. f->allow_range = prev_allow_range;
  2517. if (elem == nullptr) {
  2518. syntax_error(token, "Expected a type or range, got nothing");
  2519. }
  2520. if (allow_token(f, Token_Semicolon)) {
  2521. underlying = parse_type(f);
  2522. } else if (allow_token(f, Token_Comma)) {
  2523. String p = token_to_string(f->prev_token);
  2524. syntax_error(token_end_of_line(f, f->prev_token), "Expected a semicolon, got a %.*s", LIT(p));
  2525. underlying = parse_type(f);
  2526. }
  2527. expect_token(f, Token_CloseBracket);
  2528. return ast_bit_set_type(f, token, elem, underlying);
  2529. }
  2530. case Token_asm: {
  2531. Token token = expect_token(f, Token_asm);
  2532. Array<Ast *> param_types = {};
  2533. Ast *return_type = nullptr;
  2534. if (allow_token(f, Token_OpenParen)) {
  2535. param_types = array_make<Ast *>(ast_allocator(f));
  2536. while (f->curr_token.kind != Token_CloseParen && f->curr_token.kind != Token_EOF) {
  2537. Ast *t = parse_type(f);
  2538. array_add(&param_types, t);
  2539. if (f->curr_token.kind != Token_Comma ||
  2540. f->curr_token.kind == Token_EOF) {
  2541. break;
  2542. }
  2543. advance_token(f);
  2544. }
  2545. expect_token(f, Token_CloseParen);
  2546. if (allow_token(f, Token_ArrowRight)) {
  2547. return_type = parse_type(f);
  2548. }
  2549. }
  2550. bool has_side_effects = false;
  2551. bool is_align_stack = false;
  2552. InlineAsmDialectKind dialect = InlineAsmDialect_Default;
  2553. while (f->curr_token.kind == Token_Hash) {
  2554. advance_token(f);
  2555. if (f->curr_token.kind == Token_Ident) {
  2556. Token token = advance_token(f);
  2557. String name = token.string;
  2558. if (name == "side_effects") {
  2559. if (has_side_effects) {
  2560. syntax_error(token, "Duplicate directive on inline asm expression: '#side_effects'");
  2561. }
  2562. has_side_effects = true;
  2563. } else if (name == "align_stack") {
  2564. if (is_align_stack) {
  2565. syntax_error(token, "Duplicate directive on inline asm expression: '#align_stack'");
  2566. }
  2567. is_align_stack = true;
  2568. } else if (name == "att") {
  2569. if (dialect == InlineAsmDialect_ATT) {
  2570. syntax_error(token, "Duplicate directive on inline asm expression: '#att'");
  2571. } else if (dialect != InlineAsmDialect_Default) {
  2572. syntax_error(token, "Conflicting asm dialects");
  2573. } else {
  2574. dialect = InlineAsmDialect_ATT;
  2575. }
  2576. } else if (name == "intel") {
  2577. if (dialect == InlineAsmDialect_Intel) {
  2578. syntax_error(token, "Duplicate directive on inline asm expression: '#intel'");
  2579. } else if (dialect != InlineAsmDialect_Default) {
  2580. syntax_error(token, "Conflicting asm dialects");
  2581. } else {
  2582. dialect = InlineAsmDialect_Intel;
  2583. }
  2584. }
  2585. } else {
  2586. syntax_error(f->curr_token, "Expected an identifier after hash");
  2587. }
  2588. }
  2589. skip_possible_newline_for_literal(f);
  2590. Token open = expect_token(f, Token_OpenBrace);
  2591. Ast *asm_string = parse_expr(f, false);
  2592. expect_token(f, Token_Comma);
  2593. Ast *constraints_string = parse_expr(f, false);
  2594. allow_token(f, Token_Comma);
  2595. Token close = expect_closing_brace_of_field_list(f);
  2596. return ast_inline_asm_expr(f, token, open, close, param_types, return_type, asm_string, constraints_string, has_side_effects, is_align_stack, dialect);
  2597. }
  2598. }
  2599. return nullptr;
  2600. }
  2601. gb_internal bool is_literal_type(Ast *node) {
  2602. node = unparen_expr(node);
  2603. switch (node->kind) {
  2604. case Ast_BadExpr:
  2605. case Ast_Ident:
  2606. case Ast_SelectorExpr:
  2607. case Ast_ArrayType:
  2608. case Ast_StructType:
  2609. case Ast_UnionType:
  2610. case Ast_EnumType:
  2611. case Ast_DynamicArrayType:
  2612. case Ast_MapType:
  2613. case Ast_BitSetType:
  2614. case Ast_MatrixType:
  2615. case Ast_CallExpr:
  2616. return true;
  2617. case Ast_MultiPointerType:
  2618. // For better error messages
  2619. return true;
  2620. }
  2621. return false;
  2622. }
  2623. gb_internal Ast *parse_call_expr(AstFile *f, Ast *operand) {
  2624. auto args = array_make<Ast *>(ast_allocator(f));
  2625. Token open_paren, close_paren;
  2626. Token ellipsis = {};
  2627. isize prev_expr_level = f->expr_level;
  2628. bool prev_allow_newline = f->allow_newline;
  2629. f->expr_level = 0;
  2630. f->allow_newline = file_allow_newline(f);
  2631. open_paren = expect_token(f, Token_OpenParen);
  2632. bool seen_ellipsis = false;
  2633. while (f->curr_token.kind != Token_CloseParen &&
  2634. f->curr_token.kind != Token_EOF) {
  2635. if (f->curr_token.kind == Token_Comma) {
  2636. syntax_error(f->curr_token, "Expected an expression not ,");
  2637. } else if (f->curr_token.kind == Token_Eq) {
  2638. syntax_error(f->curr_token, "Expected an expression not =");
  2639. }
  2640. bool prefix_ellipsis = false;
  2641. if (f->curr_token.kind == Token_Ellipsis) {
  2642. prefix_ellipsis = true;
  2643. ellipsis = expect_token(f, Token_Ellipsis);
  2644. }
  2645. Ast *arg = parse_expr(f, false);
  2646. if (f->curr_token.kind == Token_Eq) {
  2647. Token eq = expect_token(f, Token_Eq);
  2648. if (prefix_ellipsis) {
  2649. syntax_error(ellipsis, "'..' must be applied to value rather than the field name");
  2650. }
  2651. Ast *value = parse_value(f);
  2652. arg = ast_field_value(f, arg, value, eq);
  2653. } else if (seen_ellipsis) {
  2654. syntax_error(arg, "Positional arguments are not allowed after '..'");
  2655. }
  2656. array_add(&args, arg);
  2657. if (ellipsis.pos.line != 0) {
  2658. seen_ellipsis = true;
  2659. }
  2660. if (!allow_field_separator(f)) {
  2661. break;
  2662. }
  2663. }
  2664. f->allow_newline = prev_allow_newline;
  2665. f->expr_level = prev_expr_level;
  2666. close_paren = expect_closing(f, Token_CloseParen, str_lit("argument list"));
  2667. Ast *call = ast_call_expr(f, operand, args, open_paren, close_paren, ellipsis);
  2668. Ast *o = unparen_expr(operand);
  2669. if (o->kind == Ast_SelectorExpr && o->SelectorExpr.token.kind == Token_ArrowRight) {
  2670. return ast_selector_call_expr(f, o->SelectorExpr.token, o, call);
  2671. }
  2672. return call;
  2673. }
  2674. gb_internal void parse_check_or_return(Ast *operand, char const *msg) {
  2675. if (operand == nullptr) {
  2676. return;
  2677. }
  2678. switch (operand->kind) {
  2679. case Ast_OrReturnExpr:
  2680. syntax_error_with_verbose(operand, "'or_return' use within %s is not wrapped in parentheses (...)", msg);
  2681. break;
  2682. case Ast_OrBranchExpr:
  2683. syntax_error_with_verbose(operand, "'or_%.*s' use within %s is not wrapped in parentheses (...)", msg, LIT(operand->OrBranchExpr.token.string));
  2684. break;
  2685. }
  2686. }
  2687. gb_internal Ast *parse_atom_expr(AstFile *f, Ast *operand, bool lhs) {
  2688. if (operand == nullptr) {
  2689. if (f->allow_type) return nullptr;
  2690. Token begin = f->curr_token;
  2691. syntax_error(begin, "Expected an operand");
  2692. fix_advance_to_next_stmt(f);
  2693. operand = ast_bad_expr(f, begin, f->curr_token);
  2694. }
  2695. bool loop = true;
  2696. while (loop) {
  2697. switch (f->curr_token.kind) {
  2698. case Token_OpenParen:
  2699. parse_check_or_return(operand, "call expression");
  2700. operand = parse_call_expr(f, operand);
  2701. break;
  2702. case Token_Period: {
  2703. Token token = advance_token(f);
  2704. switch (f->curr_token.kind) {
  2705. case Token_Ident:
  2706. parse_check_or_return(operand, "selector expression");
  2707. operand = ast_selector_expr(f, token, operand, parse_ident(f));
  2708. break;
  2709. case Token_OpenParen: {
  2710. parse_check_or_return(operand, "type assertion");
  2711. Token open = expect_token(f, Token_OpenParen);
  2712. Ast *type = parse_type(f);
  2713. Token close = expect_token(f, Token_CloseParen);
  2714. operand = ast_type_assertion(f, operand, token, type);
  2715. } break;
  2716. case Token_Question: {
  2717. parse_check_or_return(operand, ".? based type assertion");
  2718. Token question = expect_token(f, Token_Question);
  2719. Ast *type = ast_unary_expr(f, question, nullptr);
  2720. operand = ast_type_assertion(f, operand, token, type);
  2721. } break;
  2722. default:
  2723. syntax_error(f->curr_token, "Expected a selector");
  2724. advance_token(f);
  2725. operand = ast_bad_expr(f, ast_token(operand), f->curr_token);
  2726. // operand = ast_selector_expr(f, f->curr_token, operand, nullptr);
  2727. break;
  2728. }
  2729. } break;
  2730. case Token_ArrowRight: {
  2731. parse_check_or_return(operand, "-> based call expression");
  2732. Token token = advance_token(f);
  2733. operand = ast_selector_expr(f, token, operand, parse_ident(f));
  2734. // Ast *call = parse_call_expr(f, sel);
  2735. // operand = ast_selector_call_expr(f, token, sel, call);
  2736. break;
  2737. }
  2738. case Token_OpenBracket: {
  2739. bool prev_allow_range = f->allow_range;
  2740. f->allow_range = false;
  2741. Token open = {}, close = {}, interval = {};
  2742. Ast *indices[2] = {};
  2743. bool is_interval = false;
  2744. f->expr_level++;
  2745. open = expect_token(f, Token_OpenBracket);
  2746. switch (f->curr_token.kind) {
  2747. case Token_Ellipsis:
  2748. case Token_RangeFull:
  2749. case Token_RangeHalf:
  2750. // NOTE(bill): Do not err yet
  2751. case Token_Colon:
  2752. break;
  2753. default:
  2754. indices[0] = parse_expr(f, false);
  2755. break;
  2756. }
  2757. switch (f->curr_token.kind) {
  2758. case Token_Ellipsis:
  2759. case Token_RangeFull:
  2760. case Token_RangeHalf:
  2761. syntax_error(f->curr_token, "Expected a colon, not a range");
  2762. /* fallthrough */
  2763. case Token_Comma: // matrix index
  2764. case Token_Colon:
  2765. interval = advance_token(f);
  2766. is_interval = true;
  2767. if (f->curr_token.kind != Token_CloseBracket &&
  2768. f->curr_token.kind != Token_EOF) {
  2769. indices[1] = parse_expr(f, false);
  2770. }
  2771. break;
  2772. }
  2773. f->expr_level--;
  2774. close = expect_token(f, Token_CloseBracket);
  2775. if (is_interval) {
  2776. if (interval.kind == Token_Comma) {
  2777. if (indices[0] == nullptr || indices[1] == nullptr) {
  2778. syntax_error(open, "Matrix index expressions require both row and column indices");
  2779. }
  2780. parse_check_or_return(operand, "matrix index expression");
  2781. operand = ast_matrix_index_expr(f, operand, open, close, interval, indices[0], indices[1]);
  2782. } else {
  2783. parse_check_or_return(operand, "slice expression");
  2784. operand = ast_slice_expr(f, operand, open, close, interval, indices[0], indices[1]);
  2785. }
  2786. } else {
  2787. parse_check_or_return(operand, "index expression");
  2788. operand = ast_index_expr(f, operand, indices[0], open, close);
  2789. }
  2790. f->allow_range = prev_allow_range;
  2791. } break;
  2792. case Token_Pointer: // Deference
  2793. parse_check_or_return(operand, "dereference");
  2794. operand = ast_deref_expr(f, operand, expect_token(f, Token_Pointer));
  2795. break;
  2796. case Token_or_return:
  2797. operand = ast_or_return_expr(f, operand, expect_token(f, Token_or_return));
  2798. break;
  2799. case Token_or_break:
  2800. case Token_or_continue:
  2801. {
  2802. Token token = advance_token(f);
  2803. Ast *label = nullptr;
  2804. if (f->curr_token.kind == Token_Ident) {
  2805. label = parse_ident(f);
  2806. }
  2807. operand = ast_or_branch_expr(f, operand, token, label);
  2808. }
  2809. break;
  2810. case Token_OpenBrace:
  2811. if (!lhs && is_literal_type(operand) && f->expr_level >= 0) {
  2812. operand = parse_literal_value(f, operand);
  2813. } else {
  2814. loop = false;
  2815. }
  2816. break;
  2817. case Token_Increment:
  2818. case Token_Decrement:
  2819. if (!lhs) {
  2820. Token token = advance_token(f);
  2821. syntax_error(token, "Postfix '%.*s' operator is not supported", LIT(token.string));
  2822. } else {
  2823. loop = false;
  2824. }
  2825. break;
  2826. default:
  2827. loop = false;
  2828. break;
  2829. }
  2830. lhs = false; // NOTE(bill): 'tis not lhs anymore
  2831. }
  2832. return operand;
  2833. }
  2834. gb_internal Ast *parse_unary_expr(AstFile *f, bool lhs) {
  2835. switch (f->curr_token.kind) {
  2836. case Token_transmute:
  2837. case Token_cast: {
  2838. Token token = advance_token(f);
  2839. expect_token(f, Token_OpenParen);
  2840. Ast *type = parse_type(f);
  2841. expect_token(f, Token_CloseParen);
  2842. Ast *expr = parse_unary_expr(f, lhs);
  2843. return ast_type_cast(f, token, type, expr);
  2844. }
  2845. case Token_auto_cast: {
  2846. Token token = advance_token(f);
  2847. Ast *expr = parse_unary_expr(f, lhs);
  2848. return ast_auto_cast(f, token, expr);
  2849. }
  2850. case Token_Add:
  2851. case Token_Sub:
  2852. case Token_Xor:
  2853. case Token_And:
  2854. case Token_Not:
  2855. case Token_Mul: // Used for error handling when people do C-like things
  2856. {
  2857. Token token = advance_token(f);
  2858. Ast *expr = parse_unary_expr(f, lhs);
  2859. return ast_unary_expr(f, token, expr);
  2860. }
  2861. case Token_Increment:
  2862. case Token_Decrement: {
  2863. Token token = advance_token(f);
  2864. syntax_error(token, "Unary '%.*s' operator is not supported", LIT(token.string));
  2865. Ast *expr = parse_unary_expr(f, lhs);
  2866. return ast_unary_expr(f, token, expr);
  2867. }
  2868. case Token_Period: {
  2869. Token token = expect_token(f, Token_Period);
  2870. Ast *ident = parse_ident(f);
  2871. return ast_implicit_selector_expr(f, token, ident);
  2872. }
  2873. }
  2874. return parse_atom_expr(f, parse_operand(f, lhs), lhs);
  2875. }
  2876. gb_internal bool is_ast_range(Ast *expr) {
  2877. if (expr == nullptr) {
  2878. return false;
  2879. }
  2880. if (expr->kind != Ast_BinaryExpr) {
  2881. return false;
  2882. }
  2883. return is_token_range(expr->BinaryExpr.op.kind);
  2884. }
  2885. // NOTE(bill): result == priority
  2886. gb_internal i32 token_precedence(AstFile *f, TokenKind t) {
  2887. switch (t) {
  2888. case Token_Question:
  2889. case Token_if:
  2890. case Token_when:
  2891. case Token_or_else:
  2892. return 1;
  2893. case Token_Ellipsis:
  2894. case Token_RangeFull:
  2895. case Token_RangeHalf:
  2896. if (!f->allow_range) {
  2897. return 0;
  2898. }
  2899. return 2;
  2900. case Token_CmpOr:
  2901. return 3;
  2902. case Token_CmpAnd:
  2903. return 4;
  2904. case Token_CmpEq:
  2905. case Token_NotEq:
  2906. case Token_Lt:
  2907. case Token_Gt:
  2908. case Token_LtEq:
  2909. case Token_GtEq:
  2910. return 5;
  2911. case Token_in:
  2912. case Token_not_in:
  2913. if (f->expr_level < 0 && !f->allow_in_expr) {
  2914. return 0;
  2915. }
  2916. /*fallthrough*/
  2917. case Token_Add:
  2918. case Token_Sub:
  2919. case Token_Or:
  2920. case Token_Xor:
  2921. return 6;
  2922. case Token_Mul:
  2923. case Token_Quo:
  2924. case Token_Mod:
  2925. case Token_ModMod:
  2926. case Token_And:
  2927. case Token_AndNot:
  2928. case Token_Shl:
  2929. case Token_Shr:
  2930. return 7;
  2931. }
  2932. return 0;
  2933. }
  2934. gb_internal Ast *parse_binary_expr(AstFile *f, bool lhs, i32 prec_in) {
  2935. Ast *expr = parse_unary_expr(f, lhs);
  2936. for (;;) {
  2937. Token op = f->curr_token;
  2938. i32 op_prec = token_precedence(f, op.kind);
  2939. if (op_prec < prec_in) {
  2940. // NOTE(bill): This will also catch operators that are not valid "binary" operators
  2941. break;
  2942. }
  2943. Token prev = f->prev_token;
  2944. switch (op.kind) {
  2945. case Token_if:
  2946. case Token_when:
  2947. if (prev.pos.line < op.pos.line) {
  2948. // NOTE(bill): Check to see if the `if` or `when` is on the same line of the `lhs` condition
  2949. goto loop_end;
  2950. }
  2951. break;
  2952. }
  2953. expect_operator(f); // NOTE(bill): error checks too
  2954. if (op.kind == Token_Question) {
  2955. Ast *cond = expr;
  2956. // Token_Question
  2957. Ast *x = parse_expr(f, lhs);
  2958. Token token_c = expect_token(f, Token_Colon);
  2959. Ast *y = parse_expr(f, lhs);
  2960. expr = ast_ternary_if_expr(f, x, cond, y);
  2961. } else if (op.kind == Token_if || op.kind == Token_when) {
  2962. Ast *x = expr;
  2963. Ast *cond = parse_expr(f, lhs);
  2964. Token tok_else = expect_token(f, Token_else);
  2965. Ast *y = parse_expr(f, lhs);
  2966. switch (op.kind) {
  2967. case Token_if:
  2968. expr = ast_ternary_if_expr(f, x, cond, y);
  2969. break;
  2970. case Token_when:
  2971. expr = ast_ternary_when_expr(f, x, cond, y);
  2972. break;
  2973. }
  2974. } else {
  2975. Ast *right = parse_binary_expr(f, false, op_prec+1);
  2976. if (right == nullptr) {
  2977. syntax_error(op, "Expected expression on the right-hand side of the binary operator '%.*s'", LIT(op.string));
  2978. }
  2979. if (op.kind == Token_or_else) {
  2980. // NOTE(bill): easier to handle its logic different with its own AST kind
  2981. expr = ast_or_else_expr(f, expr, op, right);
  2982. } else {
  2983. expr = ast_binary_expr(f, op, expr, right);
  2984. }
  2985. }
  2986. lhs = false;
  2987. }
  2988. loop_end:;
  2989. return expr;
  2990. }
  2991. gb_internal Ast *parse_expr(AstFile *f, bool lhs) {
  2992. return parse_binary_expr(f, lhs, 0+1);
  2993. }
  2994. gb_internal Array<Ast *> parse_expr_list(AstFile *f, bool lhs) {
  2995. bool allow_newline = f->allow_newline;
  2996. f->allow_newline = file_allow_newline(f);
  2997. auto list = array_make<Ast *>(ast_allocator(f));
  2998. for (;;) {
  2999. Ast *e = parse_expr(f, lhs);
  3000. array_add(&list, e);
  3001. if (f->curr_token.kind != Token_Comma ||
  3002. f->curr_token.kind == Token_EOF) {
  3003. break;
  3004. }
  3005. advance_token(f);
  3006. }
  3007. f->allow_newline = allow_newline;
  3008. return list;
  3009. }
  3010. gb_internal Array<Ast *> parse_lhs_expr_list(AstFile *f) {
  3011. return parse_expr_list(f, true);
  3012. }
  3013. gb_internal Array<Ast *> parse_rhs_expr_list(AstFile *f) {
  3014. return parse_expr_list(f, false);
  3015. }
  3016. gb_internal Array<Ast *> parse_ident_list(AstFile *f, bool allow_poly_names) {
  3017. auto list = array_make<Ast *>(ast_allocator(f));
  3018. for (;;) {
  3019. array_add(&list, parse_ident(f, allow_poly_names));
  3020. if (f->curr_token.kind != Token_Comma ||
  3021. f->curr_token.kind == Token_EOF) {
  3022. break;
  3023. }
  3024. advance_token(f);
  3025. }
  3026. return list;
  3027. }
  3028. gb_internal Ast *parse_type(AstFile *f) {
  3029. Ast *type = parse_type_or_ident(f);
  3030. if (type == nullptr) {
  3031. Token token = advance_token(f);
  3032. syntax_error(token, "Expected a type");
  3033. return ast_bad_expr(f, token, f->curr_token);
  3034. } else if (type->kind == Ast_ParenExpr &&
  3035. unparen_expr(type) == nullptr) {
  3036. syntax_error(type, "Expected a type within the parentheses");
  3037. return ast_bad_expr(f, type->ParenExpr.open, type->ParenExpr.close);
  3038. }
  3039. return type;
  3040. }
  3041. gb_internal void parse_foreign_block_decl(AstFile *f, Array<Ast *> *decls) {
  3042. Ast *decl = parse_stmt(f);
  3043. switch (decl->kind) {
  3044. case Ast_EmptyStmt:
  3045. case Ast_BadStmt:
  3046. case Ast_BadDecl:
  3047. return;
  3048. case Ast_WhenStmt:
  3049. case Ast_ValueDecl:
  3050. array_add(decls, decl);
  3051. return;
  3052. default:
  3053. syntax_error(decl, "Foreign blocks only allow procedure and variable declarations");
  3054. return;
  3055. }
  3056. }
  3057. gb_internal Ast *parse_foreign_block(AstFile *f, Token token) {
  3058. CommentGroup *docs = f->lead_comment;
  3059. Ast *foreign_library = nullptr;
  3060. if (f->curr_token.kind == Token_OpenBrace) {
  3061. foreign_library = ast_ident(f, blank_token);
  3062. } else {
  3063. foreign_library = parse_ident(f);
  3064. }
  3065. Token open = {};
  3066. Token close = {};
  3067. auto decls = array_make<Ast *>(ast_allocator(f));
  3068. bool prev_in_foreign_block = f->in_foreign_block;
  3069. defer (f->in_foreign_block = prev_in_foreign_block);
  3070. f->in_foreign_block = true;
  3071. skip_possible_newline_for_literal(f);
  3072. open = expect_token(f, Token_OpenBrace);
  3073. while (f->curr_token.kind != Token_CloseBrace &&
  3074. f->curr_token.kind != Token_EOF) {
  3075. parse_foreign_block_decl(f, &decls);
  3076. }
  3077. close = expect_token(f, Token_CloseBrace);
  3078. Ast *body = ast_block_stmt(f, decls, open, close);
  3079. Ast *decl = ast_foreign_block_decl(f, token, foreign_library, body, docs);
  3080. expect_semicolon(f);
  3081. return decl;
  3082. }
  3083. gb_internal void print_comment_group(CommentGroup *group) {
  3084. if (group) {
  3085. for (Token const &token : group->list) {
  3086. gb_printf_err("%.*s\n", LIT(token.string));
  3087. }
  3088. gb_printf_err("\n");
  3089. }
  3090. }
  3091. gb_internal Ast *parse_value_decl(AstFile *f, Array<Ast *> names, CommentGroup *docs) {
  3092. bool is_mutable = true;
  3093. Array<Ast *> values = {};
  3094. Ast *type = parse_type_or_ident(f);
  3095. if (f->curr_token.kind == Token_Eq ||
  3096. f->curr_token.kind == Token_Colon) {
  3097. Token sep = {};
  3098. if (!is_mutable) {
  3099. sep = expect_token_after(f, Token_Colon, "type");
  3100. } else {
  3101. sep = advance_token(f);
  3102. is_mutable = sep.kind != Token_Colon;
  3103. }
  3104. values = parse_rhs_expr_list(f);
  3105. if (values.count > names.count) {
  3106. syntax_error(f->curr_token, "Too many values on the right hand side of the declaration");
  3107. } else if (values.count < names.count && !is_mutable) {
  3108. syntax_error(f->curr_token, "All constant declarations must be defined");
  3109. } else if (values.count == 0) {
  3110. syntax_error(f->curr_token, "Expected an expression for this declaration");
  3111. }
  3112. }
  3113. if (is_mutable) {
  3114. if (type == nullptr && values.count == 0) {
  3115. syntax_error(f->curr_token, "Missing variable type or initialization");
  3116. return ast_bad_decl(f, f->curr_token, f->curr_token);
  3117. }
  3118. } else {
  3119. if (type == nullptr && values.count == 0 && names.count > 0) {
  3120. syntax_error(f->curr_token, "Missing constant value");
  3121. return ast_bad_decl(f, f->curr_token, f->curr_token);
  3122. }
  3123. }
  3124. if (values.data == nullptr) {
  3125. values.allocator = ast_allocator(f);
  3126. }
  3127. CommentGroup *end_comment = f->lead_comment;
  3128. if (f->expr_level >= 0) {
  3129. if (f->curr_token.kind == Token_CloseBrace &&
  3130. f->curr_token.pos.line == f->prev_token.pos.line) {
  3131. } else {
  3132. expect_semicolon(f);
  3133. }
  3134. }
  3135. if (f->curr_proc == nullptr) {
  3136. if (values.count > 0 && names.count != values.count) {
  3137. syntax_error(
  3138. values[0],
  3139. "Expected %td expressions on the right hand side, got %td\n"
  3140. "\tNote: Global declarations do not allow for multi-valued expressions",
  3141. names.count, values.count
  3142. );
  3143. }
  3144. }
  3145. return ast_value_decl(f, names, type, values, is_mutable, docs, end_comment);
  3146. }
  3147. gb_internal Ast *parse_simple_stmt(AstFile *f, u32 flags) {
  3148. Token token = f->curr_token;
  3149. CommentGroup *docs = f->lead_comment;
  3150. Array<Ast *> lhs = parse_lhs_expr_list(f);
  3151. token = f->curr_token;
  3152. switch (token.kind) {
  3153. case Token_Eq:
  3154. case Token_AddEq:
  3155. case Token_SubEq:
  3156. case Token_MulEq:
  3157. case Token_QuoEq:
  3158. case Token_ModEq:
  3159. case Token_ModModEq:
  3160. case Token_AndEq:
  3161. case Token_OrEq:
  3162. case Token_XorEq:
  3163. case Token_ShlEq:
  3164. case Token_ShrEq:
  3165. case Token_AndNotEq:
  3166. case Token_CmpAndEq:
  3167. case Token_CmpOrEq:
  3168. {
  3169. if (f->curr_proc == nullptr) {
  3170. syntax_error(f->curr_token, "You cannot use a simple statement in the file scope");
  3171. return ast_bad_stmt(f, f->curr_token, f->curr_token);
  3172. }
  3173. advance_token(f);
  3174. Array<Ast *> rhs = parse_rhs_expr_list(f);
  3175. if (rhs.count == 0) {
  3176. syntax_error(token, "No right-hand side in assignment statement.");
  3177. return ast_bad_stmt(f, token, f->curr_token);
  3178. }
  3179. return ast_assign_stmt(f, token, lhs, rhs);
  3180. } break;
  3181. case Token_in:
  3182. if (flags&StmtAllowFlag_In) {
  3183. allow_token(f, Token_in);
  3184. bool prev_allow_range = f->allow_range;
  3185. f->allow_range = true;
  3186. Ast *expr = parse_expr(f, true);
  3187. f->allow_range = prev_allow_range;
  3188. auto rhs = array_make<Ast *>(ast_allocator(f), 0, 1);
  3189. array_add(&rhs, expr);
  3190. return ast_assign_stmt(f, token, lhs, rhs);
  3191. }
  3192. break;
  3193. case Token_Colon:
  3194. expect_token_after(f, Token_Colon, "identifier list");
  3195. if ((flags&StmtAllowFlag_Label) && lhs.count == 1) {
  3196. bool is_partial = false;
  3197. bool is_reverse = false;
  3198. Token partial_token = {};
  3199. if (f->curr_token.kind == Token_Hash) {
  3200. // NOTE(bill): This is purely for error messages
  3201. Token name = peek_token_n(f, 0);
  3202. if (name.kind == Token_Ident && name.string == "partial" &&
  3203. peek_token_n(f, 1).kind == Token_switch) {
  3204. partial_token = expect_token(f, Token_Hash);
  3205. expect_token(f, Token_Ident);
  3206. is_partial = true;
  3207. } else if (name.kind == Token_Ident && name.string == "reverse" &&
  3208. peek_token_n(f, 1).kind == Token_for) {
  3209. partial_token = expect_token(f, Token_Hash);
  3210. expect_token(f, Token_Ident);
  3211. is_reverse = true;
  3212. }
  3213. }
  3214. switch (f->curr_token.kind) {
  3215. case Token_OpenBrace: // block statement
  3216. case Token_if:
  3217. case Token_for:
  3218. case Token_switch: {
  3219. Ast *name = lhs[0];
  3220. Ast *label = ast_label_decl(f, ast_token(name), name);
  3221. Ast *stmt = parse_stmt(f);
  3222. #define _SET_LABEL(Kind_, label_) case GB_JOIN2(Ast_, Kind_): (stmt->Kind_).label = label_; break
  3223. switch (stmt->kind) {
  3224. _SET_LABEL(BlockStmt, label);
  3225. _SET_LABEL(IfStmt, label);
  3226. _SET_LABEL(ForStmt, label);
  3227. _SET_LABEL(RangeStmt, label);
  3228. _SET_LABEL(SwitchStmt, label);
  3229. _SET_LABEL(TypeSwitchStmt, label);
  3230. default:
  3231. syntax_error(token, "Labels can only be applied to a loop or switch statement");
  3232. break;
  3233. }
  3234. #undef _SET_LABEL
  3235. if (is_partial) {
  3236. switch (stmt->kind) {
  3237. case Ast_SwitchStmt:
  3238. stmt->SwitchStmt.partial = true;
  3239. break;
  3240. case Ast_TypeSwitchStmt:
  3241. stmt->TypeSwitchStmt.partial = true;
  3242. break;
  3243. }
  3244. syntax_error(partial_token, "Incorrect use of directive, use '#partial %.*s: switch'", LIT(ast_token(name).string));
  3245. } else if (is_reverse) {
  3246. switch (stmt->kind) {
  3247. case Ast_RangeStmt:
  3248. if (stmt->RangeStmt.reverse) {
  3249. syntax_error(token, "#reverse already applied to a 'for in' statement");
  3250. }
  3251. stmt->RangeStmt.reverse = true;
  3252. break;
  3253. default:
  3254. syntax_error(token, "#reverse can only be applied to a 'for in' statement");
  3255. break;
  3256. }
  3257. }
  3258. return stmt;
  3259. } break;
  3260. }
  3261. }
  3262. return parse_value_decl(f, lhs, docs);
  3263. }
  3264. if (lhs.count > 1) {
  3265. syntax_error(token, "Expected 1 expression");
  3266. return ast_bad_stmt(f, token, f->curr_token);
  3267. }
  3268. switch (token.kind) {
  3269. case Token_Increment:
  3270. case Token_Decrement:
  3271. advance_token(f);
  3272. syntax_error(token, "Postfix '%.*s' statement is not supported", LIT(token.string));
  3273. break;
  3274. }
  3275. #if 0
  3276. switch (token.kind) {
  3277. case Token_Inc:
  3278. case Token_Dec:
  3279. advance_token(f);
  3280. return ast_inc_dec_stmt(f, token, lhs[0]);
  3281. }
  3282. #endif
  3283. return ast_expr_stmt(f, lhs[0]);
  3284. }
  3285. gb_internal Ast *parse_block_stmt(AstFile *f, b32 is_when) {
  3286. skip_possible_newline_for_literal(f);
  3287. if (!is_when && f->curr_proc == nullptr) {
  3288. syntax_error(f->curr_token, "You cannot use a block statement in the file scope");
  3289. return ast_bad_stmt(f, f->curr_token, f->curr_token);
  3290. }
  3291. return parse_body(f);
  3292. }
  3293. gb_internal Ast *parse_results(AstFile *f, bool *diverging) {
  3294. if (!allow_token(f, Token_ArrowRight)) {
  3295. return nullptr;
  3296. }
  3297. if (allow_token(f, Token_Not)) {
  3298. if (diverging) *diverging = true;
  3299. return nullptr;
  3300. }
  3301. isize prev_level = f->expr_level;
  3302. defer (f->expr_level = prev_level);
  3303. if (f->curr_token.kind != Token_OpenParen) {
  3304. Token begin_token = f->curr_token;
  3305. Array<Ast *> empty_names = {};
  3306. auto list = array_make<Ast *>(ast_allocator(f), 0, 1);
  3307. Ast *type = parse_type(f);
  3308. Token tag = {};
  3309. array_add(&list, ast_field(f, empty_names, type, nullptr, 0, tag, nullptr, nullptr));
  3310. return ast_field_list(f, begin_token, list);
  3311. }
  3312. Ast *list = nullptr;
  3313. expect_token(f, Token_OpenParen);
  3314. list = parse_field_list(f, nullptr, FieldFlag_Results, Token_CloseParen, true, false);
  3315. if (file_allow_newline(f)) {
  3316. skip_possible_newline(f);
  3317. }
  3318. expect_token_after(f, Token_CloseParen, "parameter list");
  3319. return list;
  3320. }
  3321. gb_internal ProcCallingConvention string_to_calling_convention(String const &s) {
  3322. if (s == "odin") return ProcCC_Odin;
  3323. if (s == "contextless") return ProcCC_Contextless;
  3324. if (s == "cdecl") return ProcCC_CDecl;
  3325. if (s == "c") return ProcCC_CDecl;
  3326. if (s == "stdcall") return ProcCC_StdCall;
  3327. if (s == "std") return ProcCC_StdCall;
  3328. if (s == "fastcall") return ProcCC_FastCall;
  3329. if (s == "fast") return ProcCC_FastCall;
  3330. if (s == "none") return ProcCC_None;
  3331. if (s == "naked") return ProcCC_Naked;
  3332. if (s == "win64") return ProcCC_Win64;
  3333. if (s == "sysv") return ProcCC_SysV;
  3334. if (s == "system") {
  3335. if (build_context.metrics.os == TargetOs_windows) {
  3336. return ProcCC_StdCall;
  3337. }
  3338. return ProcCC_CDecl;
  3339. }
  3340. return ProcCC_Invalid;
  3341. }
  3342. gb_internal Ast *parse_proc_type(AstFile *f, Token proc_token) {
  3343. Ast *params = nullptr;
  3344. Ast *results = nullptr;
  3345. bool diverging = false;
  3346. ProcCallingConvention cc = ProcCC_Invalid;
  3347. if (f->curr_token.kind == Token_String) {
  3348. Token token = expect_token(f, Token_String);
  3349. auto c = string_to_calling_convention(string_value_from_token(f, token));
  3350. if (c == ProcCC_Invalid) {
  3351. syntax_error(token, "Unknown procedure calling convention: '%.*s'", LIT(token.string));
  3352. } else {
  3353. cc = c;
  3354. }
  3355. }
  3356. if (cc == ProcCC_Invalid) {
  3357. if (f->in_foreign_block) {
  3358. cc = ProcCC_ForeignBlockDefault;
  3359. } else {
  3360. cc = default_calling_convention();
  3361. }
  3362. }
  3363. expect_token(f, Token_OpenParen);
  3364. f->expr_level += 1;
  3365. params = parse_field_list(f, nullptr, FieldFlag_Signature, Token_CloseParen, true, true);
  3366. if (file_allow_newline(f)) {
  3367. skip_possible_newline(f);
  3368. }
  3369. f->expr_level -= 1;
  3370. expect_token_after(f, Token_CloseParen, "parameter list");
  3371. results = parse_results(f, &diverging);
  3372. u64 tags = 0;
  3373. bool is_generic = false;
  3374. for (Ast *param : params->FieldList.list) {
  3375. ast_node(field, Field, param);
  3376. if (field->type != nullptr) {
  3377. if (field->type->kind == Ast_PolyType) {
  3378. is_generic = true;
  3379. goto end;
  3380. }
  3381. for (Ast *name : field->names) {
  3382. if (name->kind == Ast_PolyType) {
  3383. is_generic = true;
  3384. goto end;
  3385. }
  3386. }
  3387. }
  3388. }
  3389. end:
  3390. return ast_proc_type(f, proc_token, params, results, tags, cc, is_generic, diverging);
  3391. }
  3392. gb_internal Ast *parse_var_type(AstFile *f, bool allow_ellipsis, bool allow_typeid_token) {
  3393. if (allow_ellipsis && f->curr_token.kind == Token_Ellipsis) {
  3394. Token tok = advance_token(f);
  3395. Ast *type = parse_type_or_ident(f);
  3396. if (type == nullptr) {
  3397. syntax_error(tok, "variadic field missing type after '..'");
  3398. type = ast_bad_expr(f, tok, f->curr_token);
  3399. }
  3400. return ast_ellipsis(f, tok, type);
  3401. }
  3402. Ast *type = nullptr;
  3403. if (allow_typeid_token &&
  3404. f->curr_token.kind == Token_typeid) {
  3405. Token token = expect_token(f, Token_typeid);
  3406. Ast *specialization = nullptr;
  3407. if (allow_token(f, Token_Quo)) {
  3408. specialization = parse_type(f);
  3409. }
  3410. type = ast_typeid_type(f, token, specialization);
  3411. } else {
  3412. type = parse_type(f);
  3413. }
  3414. return type;
  3415. }
  3416. struct ParseFieldPrefixMapping {
  3417. String name;
  3418. TokenKind token_kind;
  3419. FieldFlag flag;
  3420. };
  3421. gb_global ParseFieldPrefixMapping const parse_field_prefix_mappings[] = {
  3422. {str_lit("using"), Token_using, FieldFlag_using},
  3423. {str_lit("no_alias"), Token_Hash, FieldFlag_no_alias},
  3424. {str_lit("c_vararg"), Token_Hash, FieldFlag_c_vararg},
  3425. {str_lit("const"), Token_Hash, FieldFlag_const},
  3426. {str_lit("any_int"), Token_Hash, FieldFlag_any_int},
  3427. {str_lit("subtype"), Token_Hash, FieldFlag_subtype},
  3428. {str_lit("by_ptr"), Token_Hash, FieldFlag_by_ptr},
  3429. {str_lit("no_broadcast"), Token_Hash, FieldFlag_no_broadcast},
  3430. };
  3431. gb_internal FieldFlag is_token_field_prefix(AstFile *f) {
  3432. switch (f->curr_token.kind) {
  3433. case Token_EOF:
  3434. return FieldFlag_Invalid;
  3435. case Token_using:
  3436. return FieldFlag_using;
  3437. case Token_Hash:
  3438. advance_token(f);
  3439. switch (f->curr_token.kind) {
  3440. case Token_Ident:
  3441. for (i32 i = 0; i < gb_count_of(parse_field_prefix_mappings); i++) {
  3442. auto const &mapping = parse_field_prefix_mappings[i];
  3443. if (mapping.token_kind == Token_Hash) {
  3444. if (f->curr_token.string == mapping.name) {
  3445. return mapping.flag;
  3446. }
  3447. }
  3448. }
  3449. break;
  3450. }
  3451. return FieldFlag_Unknown;
  3452. }
  3453. return FieldFlag_Invalid;
  3454. }
  3455. gb_internal u32 parse_field_prefixes(AstFile *f) {
  3456. i32 counts[gb_count_of(parse_field_prefix_mappings)] = {};
  3457. for (;;) {
  3458. FieldFlag flag = is_token_field_prefix(f);
  3459. if (flag & FieldFlag_Invalid) {
  3460. break;
  3461. }
  3462. if (flag & FieldFlag_Unknown) {
  3463. syntax_error(f->curr_token, "Unknown prefix kind '#%.*s'", LIT(f->curr_token.string));
  3464. advance_token(f);
  3465. continue;
  3466. }
  3467. for (i32 i = 0; i < gb_count_of(parse_field_prefix_mappings); i++) {
  3468. if (parse_field_prefix_mappings[i].flag == flag) {
  3469. counts[i] += 1;
  3470. advance_token(f);
  3471. break;
  3472. }
  3473. }
  3474. }
  3475. u32 field_flags = 0;
  3476. for (i32 i = 0; i < gb_count_of(parse_field_prefix_mappings); i++) {
  3477. if (counts[i] > 0) {
  3478. field_flags |= parse_field_prefix_mappings[i].flag;
  3479. if (counts[i] != 1) {
  3480. auto const &mapping = parse_field_prefix_mappings[i];
  3481. String name = mapping.name;
  3482. char const *prefix = "";
  3483. if (mapping.token_kind == Token_Hash) {
  3484. prefix = "#";
  3485. }
  3486. syntax_error(f->curr_token, "Multiple '%s%.*s' in this field list", prefix, LIT(name));
  3487. }
  3488. }
  3489. }
  3490. return field_flags;
  3491. }
  3492. gb_internal u32 check_field_prefixes(AstFile *f, isize name_count, u32 allowed_flags, u32 set_flags) {
  3493. for (i32 i = 0; i < gb_count_of(parse_field_prefix_mappings); i++) {
  3494. bool err = false;
  3495. auto const &m = parse_field_prefix_mappings[i];
  3496. if ((set_flags & m.flag) != 0) {
  3497. if (m.flag == FieldFlag_using && name_count > 1) {
  3498. err = true;
  3499. syntax_error(f->curr_token, "Cannot apply 'using' to more than one of the same type");
  3500. }
  3501. if ((allowed_flags & m.flag) == 0) {
  3502. err = true;
  3503. char const *prefix = "";
  3504. if (m.token_kind == Token_Hash) {
  3505. prefix = "#";
  3506. }
  3507. syntax_error(f->curr_token, "'%s%.*s' in not allowed within this field list", prefix, LIT(m.name));
  3508. }
  3509. }
  3510. if (err) {
  3511. set_flags &= ~m.flag;
  3512. }
  3513. }
  3514. return set_flags;
  3515. }
  3516. struct AstAndFlags {
  3517. Ast *node;
  3518. u32 flags;
  3519. };
  3520. gb_internal Array<Ast *> convert_to_ident_list(AstFile *f, Array<AstAndFlags> list, bool ignore_flags, bool allow_poly_names) {
  3521. auto idents = array_make<Ast *>(ast_allocator(f), 0, list.count);
  3522. // Convert to ident list
  3523. isize i = 0;
  3524. for (AstAndFlags const &item : list) {
  3525. Ast *ident = item.node;
  3526. if (!ignore_flags) {
  3527. if (i != 0) {
  3528. syntax_error(ident, "Illegal use of prefixes in parameter list");
  3529. }
  3530. }
  3531. switch (ident->kind) {
  3532. case Ast_Ident:
  3533. case Ast_BadExpr:
  3534. break;
  3535. case Ast_Implicit:
  3536. begin_error_block();
  3537. syntax_error(ident, "Expected an identifier, '%.*s' which is a keyword", LIT(ident->Implicit.string));
  3538. if (ident->Implicit.kind == Token_context) {
  3539. error_line("\tSuggestion: Would 'ctx' suffice as an alternative name?\n");
  3540. }
  3541. end_error_block();
  3542. ident = ast_ident(f, blank_token);
  3543. break;
  3544. case Ast_PolyType:
  3545. if (allow_poly_names) {
  3546. if (ident->PolyType.specialization == nullptr) {
  3547. break;
  3548. } else {
  3549. syntax_error(ident, "Expected a polymorphic identifier without any specialization");
  3550. }
  3551. } else {
  3552. syntax_error(ident, "Expected a non-polymorphic identifier");
  3553. }
  3554. /*fallthrough*/
  3555. default:
  3556. syntax_error(ident, "Expected an identifier");
  3557. ident = ast_ident(f, blank_token);
  3558. break;
  3559. }
  3560. array_add(&idents, ident);
  3561. i += 1;
  3562. }
  3563. return idents;
  3564. }
  3565. gb_internal bool allow_field_separator(AstFile *f) {
  3566. Token token = f->curr_token;
  3567. if (allow_token(f, Token_Comma)) {
  3568. return true;
  3569. }
  3570. if (token.kind == Token_Semicolon) {
  3571. bool ok = false;
  3572. if (file_allow_newline(f) && token_is_newline(token)) {
  3573. TokenKind next = peek_token(f).kind;
  3574. switch (next) {
  3575. case Token_CloseBrace:
  3576. case Token_CloseParen:
  3577. ok = true;
  3578. break;
  3579. }
  3580. }
  3581. if (!ok) {
  3582. String p = token_to_string(token);
  3583. syntax_error(token_end_of_line(f, f->prev_token), "Expected a comma, got a %.*s", LIT(p));
  3584. }
  3585. advance_token(f);
  3586. return true;
  3587. }
  3588. return false;
  3589. }
  3590. gb_internal Ast *parse_struct_field_list(AstFile *f, isize *name_count_) {
  3591. Token start_token = f->curr_token;
  3592. auto decls = array_make<Ast *>(ast_allocator(f));
  3593. isize total_name_count = 0;
  3594. Ast *params = parse_field_list(f, &total_name_count, FieldFlag_Struct, Token_CloseBrace, false, false);
  3595. if (name_count_) *name_count_ = total_name_count;
  3596. return params;
  3597. }
  3598. // Returns true if any are polymorphic names
  3599. gb_internal bool check_procedure_name_list(Array<Ast *> const &names) {
  3600. if (names.count == 0) {
  3601. return false;
  3602. }
  3603. bool first_is_polymorphic = names[0]->kind == Ast_PolyType;
  3604. bool any_polymorphic_names = first_is_polymorphic;
  3605. for (isize i = 1; i < names.count; i++) {
  3606. Ast *name = names[i];
  3607. if (first_is_polymorphic) {
  3608. if (name->kind == Ast_PolyType) {
  3609. any_polymorphic_names = true;
  3610. } else {
  3611. syntax_error(name, "Mixture of polymorphic and non-polymorphic identifiers");
  3612. return any_polymorphic_names;
  3613. }
  3614. } else {
  3615. if (name->kind == Ast_PolyType) {
  3616. any_polymorphic_names = true;
  3617. syntax_error(name, "Mixture of polymorphic and non-polymorphic identifiers");
  3618. return any_polymorphic_names;
  3619. } else {
  3620. // Okay
  3621. }
  3622. }
  3623. }
  3624. return any_polymorphic_names;
  3625. }
  3626. gb_internal Ast *parse_field_list(AstFile *f, isize *name_count_, u32 allowed_flags, TokenKind follow, bool allow_default_parameters, bool allow_typeid_token) {
  3627. bool prev_allow_newline = f->allow_newline;
  3628. defer (f->allow_newline = prev_allow_newline);
  3629. f->allow_newline = file_allow_newline(f);
  3630. Token start_token = f->curr_token;
  3631. CommentGroup *docs = f->lead_comment;
  3632. auto params = array_make<Ast *>(ast_allocator(f));
  3633. auto list = array_make<AstAndFlags>(temporary_allocator());
  3634. bool allow_poly_names = allow_typeid_token;
  3635. isize total_name_count = 0;
  3636. bool allow_ellipsis = allowed_flags&FieldFlag_ellipsis;
  3637. bool seen_ellipsis = false;
  3638. bool is_signature = (allowed_flags & FieldFlag_Signature) == FieldFlag_Signature;
  3639. while (f->curr_token.kind != follow &&
  3640. f->curr_token.kind != Token_Colon &&
  3641. f->curr_token.kind != Token_EOF) {
  3642. u32 flags = parse_field_prefixes(f);
  3643. Ast *param = parse_var_type(f, allow_ellipsis, allow_typeid_token);
  3644. if (param->kind == Ast_Ellipsis) {
  3645. if (seen_ellipsis) syntax_error(param, "Extra variadic parameter after ellipsis");
  3646. seen_ellipsis = true;
  3647. } else if (seen_ellipsis) {
  3648. syntax_error(param, "Extra parameter after ellipsis");
  3649. }
  3650. AstAndFlags naf = {param, flags};
  3651. array_add(&list, naf);
  3652. if (!allow_field_separator(f)) {
  3653. break;
  3654. }
  3655. }
  3656. if (f->curr_token.kind == Token_Colon) {
  3657. Array<Ast *> names = convert_to_ident_list(f, list, true, allow_poly_names); // Copy for semantic reasons
  3658. if (names.count == 0) {
  3659. syntax_error(f->curr_token, "Empty field declaration");
  3660. }
  3661. bool any_polymorphic_names = check_procedure_name_list(names);
  3662. u32 set_flags = 0;
  3663. if (list.count > 0) {
  3664. set_flags = list[0].flags;
  3665. }
  3666. set_flags = check_field_prefixes(f, names.count, allowed_flags, set_flags);
  3667. total_name_count += names.count;
  3668. Ast *type = nullptr;
  3669. Ast *default_value = nullptr;
  3670. Token tag = {};
  3671. expect_token_after(f, Token_Colon, "field list");
  3672. if (f->curr_token.kind != Token_Eq) {
  3673. type = parse_var_type(f, allow_ellipsis, allow_typeid_token);
  3674. Ast *tt = unparen_expr(type);
  3675. if (tt == nullptr) {
  3676. syntax_error(f->prev_token, "Invalid type expression in field list");
  3677. } else if (is_signature && !any_polymorphic_names && tt->kind == Ast_TypeidType && tt->TypeidType.specialization != nullptr) {
  3678. syntax_error(type, "Specialization of typeid is not allowed without polymorphic names");
  3679. }
  3680. }
  3681. if (allow_token(f, Token_Eq)) {
  3682. default_value = parse_expr(f, false);
  3683. if (!allow_default_parameters) {
  3684. syntax_error(f->curr_token, "Default parameters are only allowed for procedures");
  3685. default_value = nullptr;
  3686. }
  3687. }
  3688. if (default_value != nullptr && names.count > 1) {
  3689. syntax_error(f->curr_token, "Default parameters can only be applied to single values");
  3690. }
  3691. if (allowed_flags == FieldFlag_Struct && default_value != nullptr) {
  3692. syntax_error(default_value, "Default parameters are not allowed for structs");
  3693. default_value = nullptr;
  3694. }
  3695. if (type != nullptr && type->kind == Ast_Ellipsis) {
  3696. if (seen_ellipsis) syntax_error(type, "Extra variadic parameter after ellipsis");
  3697. seen_ellipsis = true;
  3698. if (names.count != 1) {
  3699. syntax_error(type, "Variadic parameters can only have one field name");
  3700. }
  3701. } else if (seen_ellipsis && default_value == nullptr) {
  3702. syntax_error(f->curr_token, "Extra parameter after ellipsis without a default value");
  3703. }
  3704. if (type != nullptr && default_value == nullptr) {
  3705. if (f->curr_token.kind == Token_String) {
  3706. tag = expect_token(f, Token_String);
  3707. if ((allowed_flags & FieldFlag_Tags) == 0) {
  3708. syntax_error(tag, "Field tags are only allowed within structures");
  3709. }
  3710. }
  3711. }
  3712. allow_field_separator(f);
  3713. Ast *param = ast_field(f, names, type, default_value, set_flags, tag, docs, f->line_comment);
  3714. array_add(&params, param);
  3715. while (f->curr_token.kind != follow &&
  3716. f->curr_token.kind != Token_EOF &&
  3717. f->curr_token.kind != Token_Semicolon) {
  3718. CommentGroup *docs = f->lead_comment;
  3719. u32 set_flags = parse_field_prefixes(f);
  3720. Token tag = {};
  3721. Array<Ast *> names = parse_ident_list(f, allow_poly_names);
  3722. if (names.count == 0) {
  3723. syntax_error(f->curr_token, "Empty field declaration");
  3724. break;
  3725. }
  3726. bool any_polymorphic_names = check_procedure_name_list(names);
  3727. set_flags = check_field_prefixes(f, names.count, allowed_flags, set_flags);
  3728. total_name_count += names.count;
  3729. Ast *type = nullptr;
  3730. Ast *default_value = nullptr;
  3731. expect_token_after(f, Token_Colon, "field list");
  3732. if (f->curr_token.kind != Token_Eq) {
  3733. type = parse_var_type(f, allow_ellipsis, allow_typeid_token);
  3734. Ast *tt = unparen_expr(type);
  3735. if (is_signature && !any_polymorphic_names &&
  3736. tt != nullptr &&
  3737. tt->kind == Ast_TypeidType && tt->TypeidType.specialization != nullptr) {
  3738. syntax_error(type, "Specialization of typeid is not allowed without polymorphic names");
  3739. }
  3740. }
  3741. if (allow_token(f, Token_Eq)) {
  3742. default_value = parse_expr(f, false);
  3743. if (!allow_default_parameters) {
  3744. syntax_error(f->curr_token, "Default parameters are only allowed for procedures");
  3745. default_value = nullptr;
  3746. }
  3747. }
  3748. if (default_value != nullptr && names.count > 1) {
  3749. syntax_error(f->curr_token, "Default parameters can only be applied to single values");
  3750. }
  3751. if (type != nullptr && type->kind == Ast_Ellipsis) {
  3752. if (seen_ellipsis) syntax_error(type, "Extra variadic parameter after ellipsis");
  3753. seen_ellipsis = true;
  3754. if (names.count != 1) {
  3755. syntax_error(type, "Variadic parameters can only have one field name");
  3756. }
  3757. } else if (seen_ellipsis && default_value == nullptr) {
  3758. syntax_error(f->curr_token, "Extra parameter after ellipsis without a default value");
  3759. }
  3760. if (type != nullptr && default_value == nullptr) {
  3761. if (f->curr_token.kind == Token_String) {
  3762. tag = expect_token(f, Token_String);
  3763. if ((allowed_flags & FieldFlag_Tags) == 0) {
  3764. syntax_error(tag, "Field tags are only allowed within structures");
  3765. }
  3766. }
  3767. }
  3768. bool ok = allow_field_separator(f);
  3769. Ast *param = ast_field(f, names, type, default_value, set_flags, tag, docs, f->line_comment);
  3770. array_add(&params, param);
  3771. if (!ok) {
  3772. break;
  3773. }
  3774. }
  3775. if (name_count_) *name_count_ = total_name_count;
  3776. return ast_field_list(f, start_token, params);
  3777. }
  3778. for (AstAndFlags const &item : list) {
  3779. Ast *type = item.node;
  3780. Token token = blank_token;
  3781. if (allowed_flags&FieldFlag_Results) {
  3782. // NOTE(bill): Make this nothing and not `_`
  3783. token.string = str_lit("");
  3784. }
  3785. auto names = array_make<Ast *>(ast_allocator(f), 1);
  3786. token.pos = ast_token(type).pos;
  3787. names[0] = ast_ident(f, token);
  3788. u32 flags = check_field_prefixes(f, list.count, allowed_flags, item.flags);
  3789. Token tag = {};
  3790. Ast *param = ast_field(f, names, item.node, nullptr, flags, tag, docs, f->line_comment);
  3791. array_add(&params, param);
  3792. }
  3793. if (name_count_) *name_count_ = total_name_count;
  3794. return ast_field_list(f, start_token, params);
  3795. }
  3796. gb_internal Ast *parse_type_or_ident(AstFile *f) {
  3797. bool prev_allow_type = f->allow_type;
  3798. isize prev_expr_level = f->expr_level;
  3799. defer ({
  3800. f->allow_type = prev_allow_type;
  3801. f->expr_level = prev_expr_level;
  3802. });
  3803. f->allow_type = true;
  3804. f->expr_level = -1;
  3805. bool lhs = true;
  3806. Ast *operand = parse_operand(f, lhs);
  3807. Ast *type = parse_atom_expr(f, operand, lhs);
  3808. return type;
  3809. }
  3810. gb_internal Ast *parse_body(AstFile *f) {
  3811. Array<Ast *> stmts = {};
  3812. Token open, close;
  3813. isize prev_expr_level = f->expr_level;
  3814. bool prev_allow_newline = f->allow_newline;
  3815. // NOTE(bill): The body may be within an expression so reset to zero
  3816. f->expr_level = 0;
  3817. // f->allow_newline = false;
  3818. open = expect_token(f, Token_OpenBrace);
  3819. stmts = parse_stmt_list(f);
  3820. close = expect_token(f, Token_CloseBrace);
  3821. f->expr_level = prev_expr_level;
  3822. f->allow_newline = prev_allow_newline;
  3823. return ast_block_stmt(f, stmts, open, close);
  3824. }
  3825. gb_internal Ast *parse_do_body(AstFile *f, Token const &token, char const *msg) {
  3826. Token open, close;
  3827. isize prev_expr_level = f->expr_level;
  3828. bool prev_allow_newline = f->allow_newline;
  3829. // NOTE(bill): The body may be within an expression so reset to zero
  3830. f->expr_level = 0;
  3831. f->allow_newline = false;
  3832. Ast *body = convert_stmt_to_body(f, parse_stmt(f));
  3833. if (build_context.disallow_do) {
  3834. syntax_error(body, "'do' has been disallowed");
  3835. } else if (token.pos.file_id != 0 && !ast_on_same_line(token, body)) {
  3836. syntax_error(body, "The body of a 'do' must be on the same line as %s", msg);
  3837. }
  3838. f->expr_level = prev_expr_level;
  3839. f->allow_newline = prev_allow_newline;
  3840. return body;
  3841. }
  3842. gb_internal bool parse_control_statement_semicolon_separator(AstFile *f) {
  3843. Token tok = peek_token(f);
  3844. if (tok.kind != Token_OpenBrace) {
  3845. return allow_token(f, Token_Semicolon);
  3846. }
  3847. if (f->curr_token.string == ";") {
  3848. return allow_token(f, Token_Semicolon);
  3849. }
  3850. return false;
  3851. }
  3852. gb_internal Ast *parse_if_stmt(AstFile *f) {
  3853. if (f->curr_proc == nullptr) {
  3854. syntax_error(f->curr_token, "You cannot use an if statement in the file scope");
  3855. return ast_bad_stmt(f, f->curr_token, f->curr_token);
  3856. }
  3857. Token token = expect_token(f, Token_if);
  3858. Ast *init = nullptr;
  3859. Ast *cond = nullptr;
  3860. Ast *body = nullptr;
  3861. Ast *else_stmt = nullptr;
  3862. isize prev_level = f->expr_level;
  3863. f->expr_level = -1;
  3864. bool prev_allow_in_expr = f->allow_in_expr;
  3865. f->allow_in_expr = true;
  3866. if (allow_token(f, Token_Semicolon)) {
  3867. cond = parse_expr(f, false);
  3868. } else {
  3869. init = parse_simple_stmt(f, StmtAllowFlag_None);
  3870. if (parse_control_statement_semicolon_separator(f)) {
  3871. cond = parse_expr(f, false);
  3872. } else {
  3873. cond = convert_stmt_to_expr(f, init, str_lit("boolean expression"));
  3874. init = nullptr;
  3875. }
  3876. }
  3877. f->expr_level = prev_level;
  3878. f->allow_in_expr = prev_allow_in_expr;
  3879. if (cond == nullptr) {
  3880. syntax_error(f->curr_token, "Expected condition for if statement");
  3881. }
  3882. if (allow_token(f, Token_do)) {
  3883. body = parse_do_body(f, cond ? ast_token(cond) : token, "the if statement");
  3884. } else {
  3885. body = parse_block_stmt(f, false);
  3886. }
  3887. skip_possible_newline_for_literal(f);
  3888. if (f->curr_token.kind == Token_else) {
  3889. Token else_token = expect_token(f, Token_else);
  3890. switch (f->curr_token.kind) {
  3891. case Token_if:
  3892. else_stmt = parse_if_stmt(f);
  3893. break;
  3894. case Token_OpenBrace:
  3895. else_stmt = parse_block_stmt(f, false);
  3896. break;
  3897. case Token_do:
  3898. expect_token(f, Token_do);
  3899. else_stmt = parse_do_body(f, else_token, "'else'");
  3900. break;
  3901. default:
  3902. syntax_error(f->curr_token, "Expected if statement block statement");
  3903. else_stmt = ast_bad_stmt(f, f->curr_token, f->tokens[f->curr_token_index+1]);
  3904. break;
  3905. }
  3906. }
  3907. return ast_if_stmt(f, token, init, cond, body, else_stmt);
  3908. }
  3909. gb_internal Ast *parse_when_stmt(AstFile *f) {
  3910. Token token = expect_token(f, Token_when);
  3911. Ast *cond = nullptr;
  3912. Ast *body = nullptr;
  3913. Ast *else_stmt = nullptr;
  3914. isize prev_level = f->expr_level;
  3915. f->expr_level = -1;
  3916. cond = parse_expr(f, false);
  3917. f->expr_level = prev_level;
  3918. if (cond == nullptr) {
  3919. syntax_error(f->curr_token, "Expected condition for when statement");
  3920. }
  3921. bool was_in_when_statement = f->in_when_statement;
  3922. f->in_when_statement = true;
  3923. if (allow_token(f, Token_do)) {
  3924. body = parse_do_body(f, cond ? ast_token(cond) : token, "then when statement");
  3925. } else {
  3926. body = parse_block_stmt(f, true);
  3927. }
  3928. skip_possible_newline_for_literal(f);
  3929. if (f->curr_token.kind == Token_else) {
  3930. Token else_token = expect_token(f, Token_else);
  3931. switch (f->curr_token.kind) {
  3932. case Token_when:
  3933. else_stmt = parse_when_stmt(f);
  3934. break;
  3935. case Token_OpenBrace:
  3936. else_stmt = parse_block_stmt(f, true);
  3937. break;
  3938. case Token_do: {
  3939. expect_token(f, Token_do);
  3940. else_stmt = parse_do_body(f, else_token, "'else'");
  3941. } break;
  3942. default:
  3943. syntax_error(f->curr_token, "Expected when statement block statement");
  3944. else_stmt = ast_bad_stmt(f, f->curr_token, f->tokens[f->curr_token_index+1]);
  3945. break;
  3946. }
  3947. }
  3948. f->in_when_statement = was_in_when_statement;
  3949. return ast_when_stmt(f, token, cond, body, else_stmt);
  3950. }
  3951. gb_internal Ast *parse_return_stmt(AstFile *f) {
  3952. Token token = expect_token(f, Token_return);
  3953. if (f->curr_proc == nullptr) {
  3954. syntax_error(f->curr_token, "You cannot use a return statement in the file scope");
  3955. return ast_bad_stmt(f, token, f->curr_token);
  3956. }
  3957. if (f->expr_level > 0) {
  3958. syntax_error(f->curr_token, "You cannot use a return statement within an expression");
  3959. return ast_bad_stmt(f, token, f->curr_token);
  3960. }
  3961. auto results = array_make<Ast *>(ast_allocator(f));
  3962. while (f->curr_token.kind != Token_Semicolon && f->curr_token.kind != Token_CloseBrace) {
  3963. Ast *arg = parse_expr(f, false);
  3964. array_add(&results, arg);
  3965. if (f->curr_token.kind != Token_Comma ||
  3966. f->curr_token.kind == Token_EOF) {
  3967. break;
  3968. }
  3969. advance_token(f);
  3970. }
  3971. expect_semicolon(f);
  3972. return ast_return_stmt(f, token, results);
  3973. }
  3974. gb_internal Ast *parse_for_stmt(AstFile *f) {
  3975. if (f->curr_proc == nullptr) {
  3976. syntax_error(f->curr_token, "You cannot use a for statement in the file scope");
  3977. return ast_bad_stmt(f, f->curr_token, f->curr_token);
  3978. }
  3979. Token token = expect_token(f, Token_for);
  3980. Ast *init = nullptr;
  3981. Ast *cond = nullptr;
  3982. Ast *post = nullptr;
  3983. Ast *body = nullptr;
  3984. bool is_range = false;
  3985. if (f->curr_token.kind != Token_OpenBrace &&
  3986. f->curr_token.kind != Token_do) {
  3987. isize prev_level = f->expr_level;
  3988. defer (f->expr_level = prev_level);
  3989. f->expr_level = -1;
  3990. if (f->curr_token.kind == Token_in) {
  3991. Token in_token = expect_token(f, Token_in);
  3992. syntax_error(in_token, "Prefer 'for _ in' over 'for in'");
  3993. Ast *rhs = nullptr;
  3994. bool prev_allow_range = f->allow_range;
  3995. f->allow_range = true;
  3996. rhs = parse_expr(f, false);
  3997. f->allow_range = prev_allow_range;
  3998. if (allow_token(f, Token_do)) {
  3999. body = parse_do_body(f, token, "the for statement");
  4000. } else {
  4001. body = parse_block_stmt(f, false);
  4002. }
  4003. return ast_range_stmt(f, token, {}, in_token, rhs, body);
  4004. }
  4005. if (f->curr_token.kind != Token_Semicolon) {
  4006. cond = parse_simple_stmt(f, StmtAllowFlag_In);
  4007. if (cond->kind == Ast_AssignStmt && cond->AssignStmt.op.kind == Token_in) {
  4008. is_range = true;
  4009. }
  4010. }
  4011. if (!is_range && parse_control_statement_semicolon_separator(f)) {
  4012. init = cond;
  4013. cond = nullptr;
  4014. if (f->curr_token.kind == Token_OpenBrace || f->curr_token.kind == Token_do) {
  4015. syntax_error(f->curr_token, "Expected ';', followed by a condition expression and post statement, got %.*s", LIT(token_strings[f->curr_token.kind]));
  4016. } else {
  4017. if (f->curr_token.kind != Token_Semicolon) {
  4018. cond = parse_simple_stmt(f, StmtAllowFlag_None);
  4019. }
  4020. if (f->curr_token.string != ";") {
  4021. syntax_error(f->curr_token, "Expected ';', got %.*s", LIT(token_to_string(f->curr_token)));
  4022. } else {
  4023. expect_token(f, Token_Semicolon);
  4024. }
  4025. if (f->curr_token.kind != Token_OpenBrace &&
  4026. f->curr_token.kind != Token_do) {
  4027. post = parse_simple_stmt(f, StmtAllowFlag_None);
  4028. }
  4029. }
  4030. }
  4031. }
  4032. if (allow_token(f, Token_do)) {
  4033. body = parse_do_body(f, token, "the for statement");
  4034. } else {
  4035. body = parse_block_stmt(f, false);
  4036. }
  4037. if (is_range) {
  4038. GB_ASSERT(cond->kind == Ast_AssignStmt);
  4039. Token in_token = cond->AssignStmt.op;
  4040. Slice<Ast *> vals = cond->AssignStmt.lhs;
  4041. Ast *rhs = nullptr;
  4042. if (cond->AssignStmt.rhs.count > 0) {
  4043. rhs = cond->AssignStmt.rhs[0];
  4044. }
  4045. return ast_range_stmt(f, token, vals, in_token, rhs, body);
  4046. }
  4047. cond = convert_stmt_to_expr(f, cond, str_lit("boolean expression"));
  4048. if (init != nullptr &&
  4049. cond == nullptr &&
  4050. post == nullptr) {
  4051. syntax_error(init, "'for init; ; {' without an explicit condition nor post statement is not allowed, please prefer something like 'for init; true; /**/{'");
  4052. }
  4053. return ast_for_stmt(f, token, init, cond, post, body);
  4054. }
  4055. gb_internal Ast *parse_case_clause(AstFile *f, bool is_type) {
  4056. Token token = f->curr_token;
  4057. Array<Ast *> list = {};
  4058. expect_token(f, Token_case);
  4059. bool prev_allow_range = f->allow_range;
  4060. bool prev_allow_in_expr = f->allow_in_expr;
  4061. f->allow_range = !is_type;
  4062. f->allow_in_expr = !is_type;
  4063. if (f->curr_token.kind != Token_Colon) {
  4064. list = parse_rhs_expr_list(f);
  4065. }
  4066. f->allow_range = prev_allow_range;
  4067. f->allow_in_expr = prev_allow_in_expr;
  4068. expect_token(f, Token_Colon);
  4069. Array<Ast *> stmts = parse_stmt_list(f);
  4070. return ast_case_clause(f, token, list, stmts);
  4071. }
  4072. gb_internal Ast *parse_switch_stmt(AstFile *f) {
  4073. if (f->curr_proc == nullptr) {
  4074. syntax_error(f->curr_token, "You cannot use a switch statement in the file scope");
  4075. return ast_bad_stmt(f, f->curr_token, f->curr_token);
  4076. }
  4077. Token token = expect_token(f, Token_switch);
  4078. Ast *init = nullptr;
  4079. Ast *tag = nullptr;
  4080. Ast *body = nullptr;
  4081. Token open, close;
  4082. bool is_type_switch = false;
  4083. auto list = array_make<Ast *>(ast_allocator(f));
  4084. if (f->curr_token.kind != Token_OpenBrace) {
  4085. isize prev_level = f->expr_level;
  4086. f->expr_level = -1;
  4087. defer (f->expr_level = prev_level);
  4088. if (f->curr_token.kind == Token_in) {
  4089. Token in_token = expect_token(f, Token_in);
  4090. syntax_error(in_token, "Prefer 'switch _ in' over 'switch in'");
  4091. auto lhs = array_make<Ast *>(ast_allocator(f), 0, 1);
  4092. auto rhs = array_make<Ast *>(ast_allocator(f), 0, 1);
  4093. Token blank_ident = token;
  4094. blank_ident.kind = Token_Ident;
  4095. blank_ident.string = str_lit("_");
  4096. Ast *blank = ast_ident(f, blank_ident);
  4097. array_add(&lhs, blank);
  4098. array_add(&rhs, parse_expr(f, true));
  4099. tag = ast_assign_stmt(f, token, lhs, rhs);
  4100. is_type_switch = true;
  4101. } else {
  4102. tag = parse_simple_stmt(f, StmtAllowFlag_In);
  4103. if (tag->kind == Ast_AssignStmt && tag->AssignStmt.op.kind == Token_in) {
  4104. is_type_switch = true;
  4105. } else if (parse_control_statement_semicolon_separator(f)) {
  4106. init = tag;
  4107. tag = nullptr;
  4108. if (f->curr_token.kind != Token_OpenBrace) {
  4109. tag = parse_simple_stmt(f, StmtAllowFlag_None);
  4110. }
  4111. }
  4112. }
  4113. }
  4114. skip_possible_newline(f);
  4115. open = expect_token(f, Token_OpenBrace);
  4116. while (f->curr_token.kind == Token_case) {
  4117. array_add(&list, parse_case_clause(f, is_type_switch));
  4118. }
  4119. close = expect_token(f, Token_CloseBrace);
  4120. body = ast_block_stmt(f, list, open, close);
  4121. if (is_type_switch) {
  4122. return ast_type_switch_stmt(f, token, tag, body);
  4123. }
  4124. tag = convert_stmt_to_expr(f, tag, str_lit("switch expression"));
  4125. return ast_switch_stmt(f, token, init, tag, body);
  4126. }
  4127. gb_internal Ast *parse_defer_stmt(AstFile *f) {
  4128. if (f->curr_proc == nullptr) {
  4129. syntax_error(f->curr_token, "You cannot use a defer statement in the file scope");
  4130. return ast_bad_stmt(f, f->curr_token, f->curr_token);
  4131. }
  4132. Token token = expect_token(f, Token_defer);
  4133. Ast *stmt = parse_stmt(f);
  4134. switch (stmt->kind) {
  4135. case Ast_EmptyStmt:
  4136. syntax_error(token, "Empty statement after defer (e.g. ';')");
  4137. break;
  4138. case Ast_DeferStmt:
  4139. syntax_error(token, "You cannot defer a defer statement");
  4140. stmt = stmt->DeferStmt.stmt;
  4141. break;
  4142. case Ast_ReturnStmt:
  4143. syntax_error(token, "You cannot defer a return statement");
  4144. break;
  4145. }
  4146. return ast_defer_stmt(f, token, stmt);
  4147. }
  4148. enum ImportDeclKind {
  4149. ImportDecl_Standard,
  4150. ImportDecl_Using,
  4151. };
  4152. gb_internal Ast *parse_import_decl(AstFile *f, ImportDeclKind kind) {
  4153. CommentGroup *docs = f->lead_comment;
  4154. Token token = expect_token(f, Token_import);
  4155. Token import_name = {};
  4156. switch (f->curr_token.kind) {
  4157. case Token_Ident:
  4158. import_name = advance_token(f);
  4159. break;
  4160. default:
  4161. import_name.pos = f->curr_token.pos;
  4162. break;
  4163. }
  4164. Token file_path = expect_token_after(f, Token_String, "import");
  4165. Ast *s = nullptr;
  4166. if (f->curr_proc != nullptr) {
  4167. syntax_error(import_name, "Cannot use 'import' within a procedure. This must be done at the file scope");
  4168. s = ast_bad_decl(f, import_name, file_path);
  4169. } else {
  4170. s = ast_import_decl(f, token, file_path, import_name, docs, f->line_comment);
  4171. array_add(&f->imports, s);
  4172. }
  4173. if (f->in_when_statement) {
  4174. syntax_error(import_name, "Cannot use 'import' within a 'when' statement. Prefer using the file suffixes (e.g. foo_windows.odin) or '//+build' tags");
  4175. }
  4176. if (kind != ImportDecl_Standard) {
  4177. syntax_error(import_name, "'using import' is not allowed, please use the import name explicitly");
  4178. }
  4179. expect_semicolon(f);
  4180. return s;
  4181. }
  4182. gb_internal Ast *parse_foreign_decl(AstFile *f) {
  4183. CommentGroup *docs = f->lead_comment;
  4184. Token token = expect_token(f, Token_foreign);
  4185. switch (f->curr_token.kind) {
  4186. case Token_Ident:
  4187. case Token_OpenBrace:
  4188. return parse_foreign_block(f, token);
  4189. case Token_import: {
  4190. Token import_token = expect_token(f, Token_import);
  4191. Token lib_name = {};
  4192. switch (f->curr_token.kind) {
  4193. case Token_Ident:
  4194. lib_name = advance_token(f);
  4195. break;
  4196. default:
  4197. lib_name.pos = token.pos;
  4198. break;
  4199. }
  4200. if (is_blank_ident(lib_name)) {
  4201. syntax_error(lib_name, "Illegal foreign import name: '_'");
  4202. }
  4203. Array<Token> filepaths = {};
  4204. if (allow_token(f, Token_OpenBrace)) {
  4205. array_init(&filepaths, ast_allocator(f));
  4206. while (f->curr_token.kind != Token_CloseBrace &&
  4207. f->curr_token.kind != Token_EOF) {
  4208. Token path = expect_token(f, Token_String);
  4209. array_add(&filepaths, path);
  4210. if (!allow_field_separator(f)) {
  4211. break;
  4212. }
  4213. }
  4214. expect_closing_brace_of_field_list(f);
  4215. } else {
  4216. filepaths = array_make<Token>(ast_allocator(f), 0, 1);
  4217. Token path = expect_token(f, Token_String);
  4218. array_add(&filepaths, path);
  4219. }
  4220. Ast *s = nullptr;
  4221. if (filepaths.count == 0) {
  4222. syntax_error(lib_name, "foreign import without any paths");
  4223. s = ast_bad_decl(f, lib_name, f->curr_token);
  4224. } else if (f->curr_proc != nullptr) {
  4225. syntax_error(lib_name, "You cannot use foreign import within a procedure. This must be done at the file scope");
  4226. s = ast_bad_decl(f, lib_name, filepaths[0]);
  4227. } else {
  4228. s = ast_foreign_import_decl(f, token, filepaths, lib_name, docs, f->line_comment);
  4229. }
  4230. expect_semicolon(f);
  4231. return s;
  4232. }
  4233. }
  4234. syntax_error(token, "Invalid foreign declaration");
  4235. return ast_bad_decl(f, token, f->curr_token);
  4236. }
  4237. gb_internal Ast *parse_attribute(AstFile *f, Token token, TokenKind open_kind, TokenKind close_kind, CommentGroup *docs) {
  4238. Array<Ast *> elems = {};
  4239. Token open = {};
  4240. Token close = {};
  4241. if (f->curr_token.kind == Token_Ident) {
  4242. elems = array_make<Ast *>(ast_allocator(f), 0, 1);
  4243. Ast *elem = parse_ident(f);
  4244. array_add(&elems, elem);
  4245. } else {
  4246. open = expect_token(f, open_kind);
  4247. f->expr_level++;
  4248. if (f->curr_token.kind != close_kind) {
  4249. elems = array_make<Ast *>(ast_allocator(f));
  4250. while (f->curr_token.kind != close_kind &&
  4251. f->curr_token.kind != Token_EOF) {
  4252. Ast *elem = nullptr;
  4253. elem = parse_ident(f);
  4254. if (f->curr_token.kind == Token_Eq) {
  4255. Token eq = expect_token(f, Token_Eq);
  4256. Ast *value = parse_value(f);
  4257. elem = ast_field_value(f, elem, value, eq);
  4258. }
  4259. array_add(&elems, elem);
  4260. if (!allow_field_separator(f)) {
  4261. break;
  4262. }
  4263. }
  4264. }
  4265. f->expr_level--;
  4266. close = expect_closing(f, close_kind, str_lit("attribute"));
  4267. }
  4268. Ast *attribute = ast_attribute(f, token, open, close, elems);
  4269. skip_possible_newline(f);
  4270. Ast *decl = parse_stmt(f);
  4271. if (decl->kind == Ast_ValueDecl) {
  4272. if (decl->ValueDecl.docs == nullptr && docs != nullptr) {
  4273. decl->ValueDecl.docs = docs;
  4274. }
  4275. array_add(&decl->ValueDecl.attributes, attribute);
  4276. } else if (decl->kind == Ast_ForeignBlockDecl) {
  4277. array_add(&decl->ForeignBlockDecl.attributes, attribute);
  4278. } else if (decl->kind == Ast_ForeignImportDecl) {
  4279. array_add(&decl->ForeignImportDecl.attributes, attribute);
  4280. } else if (decl->kind == Ast_ImportDecl) {
  4281. array_add(&decl->ImportDecl.attributes, attribute);
  4282. } else {
  4283. syntax_error(decl, "Expected a value or foreign declaration after an attribute, got %.*s", LIT(ast_strings[decl->kind]));
  4284. return ast_bad_stmt(f, token, f->curr_token);
  4285. }
  4286. return decl;
  4287. }
  4288. gb_internal Ast *parse_unrolled_for_loop(AstFile *f, Token unroll_token) {
  4289. Token for_token = expect_token(f, Token_for);
  4290. Ast *val0 = nullptr;
  4291. Ast *val1 = nullptr;
  4292. Token in_token = {};
  4293. Ast *expr = nullptr;
  4294. Ast *body = nullptr;
  4295. bool bad_stmt = false;
  4296. if (f->curr_token.kind != Token_in) {
  4297. Array<Ast *> idents = parse_ident_list(f, false);
  4298. switch (idents.count) {
  4299. case 1:
  4300. val0 = idents[0];
  4301. break;
  4302. case 2:
  4303. val0 = idents[0];
  4304. val1 = idents[1];
  4305. break;
  4306. default:
  4307. syntax_error(for_token, "Expected either 1 or 2 identifiers");
  4308. bad_stmt = true;
  4309. break;
  4310. }
  4311. }
  4312. in_token = expect_token(f, Token_in);
  4313. bool prev_allow_range = f->allow_range;
  4314. isize prev_level = f->expr_level;
  4315. f->allow_range = true;
  4316. f->expr_level = -1;
  4317. expr = parse_expr(f, false);
  4318. f->expr_level = prev_level;
  4319. f->allow_range = prev_allow_range;
  4320. if (allow_token(f, Token_do)) {
  4321. body = parse_do_body(f, for_token, "the for statement");
  4322. } else {
  4323. body = parse_block_stmt(f, false);
  4324. }
  4325. if (bad_stmt) {
  4326. return ast_bad_stmt(f, unroll_token, f->curr_token);
  4327. }
  4328. return ast_unroll_range_stmt(f, unroll_token, for_token, val0, val1, in_token, expr, body);
  4329. }
  4330. gb_internal Ast *parse_stmt(AstFile *f) {
  4331. Ast *s = nullptr;
  4332. Token token = f->curr_token;
  4333. switch (token.kind) {
  4334. // Operands
  4335. case Token_context: // Also allows for `context =`
  4336. case Token_proc:
  4337. case Token_Ident:
  4338. case Token_Integer:
  4339. case Token_Float:
  4340. case Token_Imag:
  4341. case Token_Rune:
  4342. case Token_String:
  4343. case Token_OpenParen:
  4344. case Token_Pointer:
  4345. case Token_asm: // Inline assembly
  4346. // Unary Operators
  4347. case Token_Add:
  4348. case Token_Sub:
  4349. case Token_Xor:
  4350. case Token_Not:
  4351. case Token_And:
  4352. case Token_Mul: // Used for error handling when people do C-like things
  4353. s = parse_simple_stmt(f, StmtAllowFlag_Label);
  4354. expect_semicolon(f);
  4355. return s;
  4356. case Token_foreign:
  4357. return parse_foreign_decl(f);
  4358. case Token_import:
  4359. return parse_import_decl(f, ImportDecl_Standard);
  4360. case Token_if: return parse_if_stmt(f);
  4361. case Token_when: return parse_when_stmt(f);
  4362. case Token_for: return parse_for_stmt(f);
  4363. case Token_switch: return parse_switch_stmt(f);
  4364. case Token_defer: return parse_defer_stmt(f);
  4365. case Token_return: return parse_return_stmt(f);
  4366. case Token_break:
  4367. case Token_continue:
  4368. case Token_fallthrough: {
  4369. Token token = advance_token(f);
  4370. Ast *label = nullptr;
  4371. if (token.kind != Token_fallthrough &&
  4372. f->curr_token.kind == Token_Ident) {
  4373. label = parse_ident(f);
  4374. }
  4375. s = ast_branch_stmt(f, token, label);
  4376. expect_semicolon(f);
  4377. return s;
  4378. }
  4379. case Token_using: {
  4380. CommentGroup *docs = f->lead_comment;
  4381. Token token = expect_token(f, Token_using);
  4382. if (f->curr_token.kind == Token_import) {
  4383. return parse_import_decl(f, ImportDecl_Using);
  4384. }
  4385. Ast *decl = nullptr;
  4386. Array<Ast *> list = parse_lhs_expr_list(f);
  4387. if (list.count == 0) {
  4388. syntax_error(token, "Illegal use of 'using' statement");
  4389. expect_semicolon(f);
  4390. return ast_bad_stmt(f, token, f->curr_token);
  4391. }
  4392. if (f->curr_token.kind != Token_Colon) {
  4393. expect_semicolon(f);
  4394. return ast_using_stmt(f, token, list);
  4395. }
  4396. expect_token_after(f, Token_Colon, "identifier list");
  4397. decl = parse_value_decl(f, list, docs);
  4398. if (decl != nullptr && decl->kind == Ast_ValueDecl) {
  4399. decl->ValueDecl.is_using = true;
  4400. return decl;
  4401. }
  4402. syntax_error(token, "Illegal use of 'using' statement");
  4403. return ast_bad_stmt(f, token, f->curr_token);
  4404. } break;
  4405. case Token_At: {
  4406. CommentGroup *docs = f->lead_comment;
  4407. Token token = expect_token(f, Token_At);
  4408. return parse_attribute(f, token, Token_OpenParen, Token_CloseParen, docs);
  4409. }
  4410. case Token_Hash: {
  4411. Ast *s = nullptr;
  4412. Token hash_token = expect_token(f, Token_Hash);
  4413. Token name = expect_token(f, Token_Ident);
  4414. String tag = name.string;
  4415. if (tag == "bounds_check") {
  4416. s = parse_stmt(f);
  4417. return parse_check_directive_for_statement(s, name, StateFlag_bounds_check);
  4418. } else if (tag == "no_bounds_check") {
  4419. s = parse_stmt(f);
  4420. return parse_check_directive_for_statement(s, name, StateFlag_no_bounds_check);
  4421. } else if (tag == "type_assert") {
  4422. s = parse_stmt(f);
  4423. return parse_check_directive_for_statement(s, name, StateFlag_type_assert);
  4424. } else if (tag == "no_type_assert") {
  4425. s = parse_stmt(f);
  4426. return parse_check_directive_for_statement(s, name, StateFlag_no_type_assert);
  4427. } else if (tag == "partial") {
  4428. s = parse_stmt(f);
  4429. switch (s->kind) {
  4430. case Ast_SwitchStmt:
  4431. s->SwitchStmt.partial = true;
  4432. break;
  4433. case Ast_TypeSwitchStmt:
  4434. s->TypeSwitchStmt.partial = true;
  4435. break;
  4436. case Ast_EmptyStmt:
  4437. return parse_check_directive_for_statement(s, name, 0);
  4438. default:
  4439. syntax_error(token, "#partial can only be applied to a switch statement");
  4440. break;
  4441. }
  4442. return s;
  4443. } else if (tag == "assert" || tag == "panic") {
  4444. Ast *t = ast_basic_directive(f, hash_token, name);
  4445. Ast *stmt = ast_expr_stmt(f, parse_call_expr(f, t));
  4446. expect_semicolon(f);
  4447. return stmt;
  4448. } else if (name.string == "force_inline" ||
  4449. name.string == "force_no_inline") {
  4450. Ast *expr = parse_force_inlining_operand(f, name);
  4451. Ast *stmt = ast_expr_stmt(f, expr);
  4452. expect_semicolon(f);
  4453. return stmt;
  4454. } else if (tag == "unroll") {
  4455. return parse_unrolled_for_loop(f, name);
  4456. } else if (tag == "reverse") {
  4457. Ast *for_stmt = parse_for_stmt(f);
  4458. if (for_stmt->kind == Ast_RangeStmt) {
  4459. if (for_stmt->RangeStmt.reverse) {
  4460. syntax_error(token, "#reverse already applied to a 'for in' statement");
  4461. }
  4462. for_stmt->RangeStmt.reverse = true;
  4463. } else {
  4464. syntax_error(token, "#reverse can only be applied to a 'for in' statement");
  4465. }
  4466. return for_stmt;
  4467. } else if (tag == "include") {
  4468. syntax_error(token, "#include is not a valid import declaration kind. Did you mean 'import'?");
  4469. s = ast_bad_stmt(f, token, f->curr_token);
  4470. } else {
  4471. syntax_error(token, "Unknown tag directive used: '%.*s'", LIT(tag));
  4472. s = ast_bad_stmt(f, token, f->curr_token);
  4473. }
  4474. fix_advance_to_next_stmt(f);
  4475. return s;
  4476. } break;
  4477. case Token_OpenBrace:
  4478. return parse_block_stmt(f, false);
  4479. case Token_Semicolon:
  4480. s = ast_empty_stmt(f, token);
  4481. expect_semicolon(f);
  4482. return s;
  4483. }
  4484. // Error correction statements
  4485. switch (token.kind) {
  4486. case Token_else:
  4487. expect_token(f, Token_else);
  4488. syntax_error(token, "'else' unattached to an 'if' statement");
  4489. switch (f->curr_token.kind) {
  4490. case Token_if:
  4491. return parse_if_stmt(f);
  4492. case Token_when:
  4493. return parse_when_stmt(f);
  4494. case Token_OpenBrace:
  4495. return parse_block_stmt(f, true);
  4496. case Token_do: {
  4497. expect_token(f, Token_do);
  4498. Ast *stmt = parse_do_body(f, {}, "the for statement");
  4499. if (build_context.disallow_do) {
  4500. syntax_error(stmt, "'do' has been disallowed");
  4501. }
  4502. return stmt;
  4503. } break;
  4504. default:
  4505. fix_advance_to_next_stmt(f);
  4506. return ast_bad_stmt(f, token, f->curr_token);
  4507. }
  4508. }
  4509. syntax_error(token, "Expected a statement, got '%.*s'", LIT(token_strings[token.kind]));
  4510. fix_advance_to_next_stmt(f);
  4511. return ast_bad_stmt(f, token, f->curr_token);
  4512. }
  4513. gb_internal Array<Ast *> parse_stmt_list(AstFile *f) {
  4514. auto list = array_make<Ast *>(ast_allocator(f));
  4515. while (f->curr_token.kind != Token_case &&
  4516. f->curr_token.kind != Token_CloseBrace &&
  4517. f->curr_token.kind != Token_EOF) {
  4518. Ast *stmt = parse_stmt(f);
  4519. if (stmt && stmt->kind != Ast_EmptyStmt) {
  4520. array_add(&list, stmt);
  4521. if (stmt->kind == Ast_ExprStmt &&
  4522. stmt->ExprStmt.expr != nullptr &&
  4523. stmt->ExprStmt.expr->kind == Ast_ProcLit) {
  4524. syntax_error(stmt, "Procedure literal evaluated but not used");
  4525. }
  4526. }
  4527. }
  4528. return list;
  4529. }
  4530. gb_internal ParseFileError init_ast_file(AstFile *f, String const &fullpath, TokenPos *err_pos) {
  4531. GB_ASSERT(f != nullptr);
  4532. f->fullpath = string_trim_whitespace(fullpath); // Just in case
  4533. f->filename = remove_directory_from_path(f->fullpath);
  4534. f->directory = directory_from_path(f->fullpath);
  4535. set_file_path_string(f->id, f->fullpath);
  4536. thread_safe_set_ast_file_from_id(f->id, f);
  4537. if (!string_ends_with(f->fullpath, str_lit(".odin"))) {
  4538. return ParseFile_WrongExtension;
  4539. }
  4540. zero_item(&f->tokenizer);
  4541. f->tokenizer.curr_file_id = f->id;
  4542. TokenizerInitError err = init_tokenizer_from_fullpath(&f->tokenizer, f->fullpath, build_context.copy_file_contents);
  4543. if (err != TokenizerInit_None) {
  4544. switch (err) {
  4545. case TokenizerInit_Empty:
  4546. break;
  4547. case TokenizerInit_NotExists:
  4548. return ParseFile_NotFound;
  4549. case TokenizerInit_Permission:
  4550. return ParseFile_Permission;
  4551. case TokenizerInit_FileTooLarge:
  4552. return ParseFile_FileTooLarge;
  4553. default:
  4554. return ParseFile_InvalidFile;
  4555. }
  4556. }
  4557. isize file_size = f->tokenizer.end - f->tokenizer.start;
  4558. // NOTE(bill): Determine allocation size required for tokens
  4559. isize token_cap = file_size/3ll;
  4560. isize pow2_cap = gb_max(cast(isize)prev_pow2(cast(i64)token_cap)/2, 16);
  4561. token_cap = ((token_cap + pow2_cap-1)/pow2_cap) * pow2_cap;
  4562. isize init_token_cap = gb_max(token_cap, 16);
  4563. array_init(&f->tokens, ast_allocator(f), 0, gb_max(init_token_cap, 16));
  4564. if (err == TokenizerInit_Empty) {
  4565. Token token = {Token_EOF};
  4566. token.pos.file_id = f->id;
  4567. token.pos.line = 1;
  4568. token.pos.column = 1;
  4569. array_add(&f->tokens, token);
  4570. return ParseFile_None;
  4571. }
  4572. u64 start = time_stamp_time_now();
  4573. for (;;) {
  4574. Token *token = array_add_and_get(&f->tokens);
  4575. tokenizer_get_token(&f->tokenizer, token);
  4576. if (token->kind == Token_Invalid) {
  4577. err_pos->line = token->pos.line;
  4578. err_pos->column = token->pos.column;
  4579. return ParseFile_InvalidToken;
  4580. }
  4581. if (token->kind == Token_EOF) {
  4582. break;
  4583. }
  4584. }
  4585. u64 end = time_stamp_time_now();
  4586. f->time_to_tokenize = cast(f64)(end-start)/cast(f64)time_stamp__freq();
  4587. f->prev_token_index = 0;
  4588. f->curr_token_index = 0;
  4589. f->prev_token = f->tokens[f->prev_token_index];
  4590. f->curr_token = f->tokens[f->curr_token_index];
  4591. array_init(&f->comments, ast_allocator(f), 0, 0);
  4592. array_init(&f->imports, ast_allocator(f), 0, 0);
  4593. f->curr_proc = nullptr;
  4594. return ParseFile_None;
  4595. }
  4596. gb_internal void destroy_ast_file(AstFile *f) {
  4597. GB_ASSERT(f != nullptr);
  4598. array_free(&f->tokens);
  4599. array_free(&f->comments);
  4600. array_free(&f->imports);
  4601. }
  4602. gb_internal bool init_parser(Parser *p) {
  4603. GB_ASSERT(p != nullptr);
  4604. string_set_init(&p->imported_files);
  4605. array_init(&p->packages, permanent_allocator());
  4606. return true;
  4607. }
  4608. gb_internal void destroy_parser(Parser *p) {
  4609. GB_ASSERT(p != nullptr);
  4610. for (AstPackage *pkg : p->packages) {
  4611. for (AstFile *file : pkg->files) {
  4612. destroy_ast_file(file);
  4613. }
  4614. array_free(&pkg->files);
  4615. array_free(&pkg->foreign_files);
  4616. }
  4617. array_free(&p->packages);
  4618. string_set_destroy(&p->imported_files);
  4619. }
  4620. gb_internal void parser_add_package(Parser *p, AstPackage *pkg) {
  4621. MUTEX_GUARD_BLOCK(&p->packages_mutex) {
  4622. pkg->id = p->packages.count+1;
  4623. array_add(&p->packages, pkg);
  4624. }
  4625. }
  4626. gb_internal ParseFileError process_imported_file(Parser *p, ImportedFile imported_file);
  4627. gb_internal WORKER_TASK_PROC(parser_worker_proc) {
  4628. ParserWorkerData *wd = cast(ParserWorkerData *)data;
  4629. ParseFileError err = process_imported_file(wd->parser, wd->imported_file);
  4630. if (err != ParseFile_None) {
  4631. auto *node = gb_alloc_item(permanent_allocator(), ParseFileErrorNode);
  4632. node->err = err;
  4633. MUTEX_GUARD_BLOCK(&wd->parser->file_error_mutex) {
  4634. if (wd->parser->file_error_tail != nullptr) {
  4635. wd->parser->file_error_tail->next = node;
  4636. }
  4637. wd->parser->file_error_tail = node;
  4638. if (wd->parser->file_error_head == nullptr) {
  4639. wd->parser->file_error_head = node;
  4640. }
  4641. }
  4642. }
  4643. return cast(isize)err;
  4644. }
  4645. gb_internal void parser_add_file_to_process(Parser *p, AstPackage *pkg, FileInfo fi, TokenPos pos) {
  4646. ImportedFile f = {pkg, fi, pos, p->file_to_process_count++};
  4647. auto wd = gb_alloc_item(permanent_allocator(), ParserWorkerData);
  4648. wd->parser = p;
  4649. wd->imported_file = f;
  4650. thread_pool_add_task(parser_worker_proc, wd);
  4651. }
  4652. gb_internal WORKER_TASK_PROC(foreign_file_worker_proc) {
  4653. ForeignFileWorkerData *wd = cast(ForeignFileWorkerData *)data;
  4654. ImportedFile *imp = &wd->imported_file;
  4655. AstPackage *pkg = imp->pkg;
  4656. AstForeignFile foreign_file = {wd->foreign_kind};
  4657. String fullpath = string_trim_whitespace(imp->fi.fullpath); // Just in case
  4658. char *c_str = alloc_cstring(temporary_allocator(), fullpath);
  4659. gbFileContents fc = gb_file_read_contents(permanent_allocator(), true, c_str);
  4660. foreign_file.source.text = (u8 *)fc.data;
  4661. foreign_file.source.len = fc.size;
  4662. switch (wd->foreign_kind) {
  4663. case AstForeignFile_S:
  4664. // TODO(bill): Actually do something with it
  4665. break;
  4666. }
  4667. MUTEX_GUARD_BLOCK(&pkg->foreign_files_mutex) {
  4668. array_add(&pkg->foreign_files, foreign_file);
  4669. }
  4670. return 0;
  4671. }
  4672. gb_internal void parser_add_foreign_file_to_process(Parser *p, AstPackage *pkg, AstForeignFileKind kind, FileInfo fi, TokenPos pos) {
  4673. // TODO(bill): Use a better allocator
  4674. ImportedFile f = {pkg, fi, pos, p->file_to_process_count++};
  4675. auto wd = gb_alloc_item(permanent_allocator(), ForeignFileWorkerData);
  4676. wd->parser = p;
  4677. wd->imported_file = f;
  4678. wd->foreign_kind = kind;
  4679. thread_pool_add_task(foreign_file_worker_proc, wd);
  4680. }
  4681. // NOTE(bill): Returns true if it's added
  4682. gb_internal AstPackage *try_add_import_path(Parser *p, String path, String const &rel_path, TokenPos pos, PackageKind kind = Package_Normal) {
  4683. String const FILE_EXT = str_lit(".odin");
  4684. MUTEX_GUARD_BLOCK(&p->imported_files_mutex) {
  4685. if (string_set_update(&p->imported_files, path)) {
  4686. return nullptr;
  4687. }
  4688. }
  4689. path = copy_string(permanent_allocator(), path);
  4690. AstPackage *pkg = gb_alloc_item(permanent_allocator(), AstPackage);
  4691. pkg->kind = kind;
  4692. pkg->fullpath = path;
  4693. array_init(&pkg->files, permanent_allocator());
  4694. pkg->foreign_files.allocator = permanent_allocator();
  4695. // NOTE(bill): Single file initial package
  4696. if (kind == Package_Init && string_ends_with(path, FILE_EXT)) {
  4697. FileInfo fi = {};
  4698. fi.name = filename_from_path(path);
  4699. fi.fullpath = path;
  4700. fi.size = get_file_size(path);
  4701. fi.is_dir = false;
  4702. array_reserve(&pkg->files, 1);
  4703. pkg->is_single_file = true;
  4704. parser_add_package(p, pkg);
  4705. parser_add_file_to_process(p, pkg, fi, pos);
  4706. return pkg;
  4707. }
  4708. Array<FileInfo> list = {};
  4709. ReadDirectoryError rd_err = read_directory(path, &list);
  4710. defer (array_free(&list));
  4711. if (list.count == 1) {
  4712. GB_ASSERT(path != list[0].fullpath);
  4713. }
  4714. switch (rd_err) {
  4715. case ReadDirectory_InvalidPath:
  4716. syntax_error(pos, "Invalid path: %.*s", LIT(rel_path));
  4717. return nullptr;
  4718. case ReadDirectory_NotExists:
  4719. syntax_error(pos, "Path does not exist: %.*s", LIT(rel_path));
  4720. return nullptr;
  4721. case ReadDirectory_Permission:
  4722. syntax_error(pos, "Unknown error whilst reading path %.*s", LIT(rel_path));
  4723. return nullptr;
  4724. case ReadDirectory_NotDir:
  4725. syntax_error(pos, "Expected a directory for a package, got a file: %.*s", LIT(rel_path));
  4726. return nullptr;
  4727. case ReadDirectory_Empty:
  4728. syntax_error(pos, "Empty directory: %.*s", LIT(rel_path));
  4729. return nullptr;
  4730. case ReadDirectory_Unknown:
  4731. syntax_error(pos, "Unknown error whilst reading path %.*s", LIT(rel_path));
  4732. return nullptr;
  4733. }
  4734. isize files_with_ext = 0;
  4735. isize files_to_reserve = 1; // always reserve 1
  4736. for (FileInfo fi : list) {
  4737. String name = fi.name;
  4738. String ext = path_extension(name);
  4739. if (ext == FILE_EXT) {
  4740. files_with_ext += 1;
  4741. }
  4742. if (ext == FILE_EXT && !is_excluded_target_filename(name)) {
  4743. files_to_reserve += 1;
  4744. }
  4745. }
  4746. if (files_with_ext == 0 || files_to_reserve == 1) {
  4747. ERROR_BLOCK();
  4748. if (files_with_ext != 0) {
  4749. syntax_error(pos, "Directory contains no .odin files for the specified platform: %.*s", LIT(rel_path));
  4750. } else {
  4751. syntax_error(pos, "Empty directory that contains no .odin files: %.*s", LIT(rel_path));
  4752. }
  4753. if (build_context.command_kind == Command_test) {
  4754. error_line("\tSuggestion: Make an .odin file that imports packages to test and use the `-all-packages` flag.");
  4755. }
  4756. return nullptr;
  4757. }
  4758. array_reserve(&pkg->files, files_to_reserve);
  4759. for (FileInfo fi : list) {
  4760. String name = fi.name;
  4761. String ext = path_extension(name);
  4762. if (ext == FILE_EXT) {
  4763. if (is_excluded_target_filename(name)) {
  4764. continue;
  4765. }
  4766. parser_add_file_to_process(p, pkg, fi, pos);
  4767. } else if (ext == ".S" || ext ==".s") {
  4768. if (is_excluded_target_filename(name)) {
  4769. continue;
  4770. }
  4771. parser_add_foreign_file_to_process(p, pkg, AstForeignFile_S, fi, pos);
  4772. }
  4773. }
  4774. parser_add_package(p, pkg);
  4775. return pkg;
  4776. }
  4777. gb_global Rune illegal_import_runes[] = {
  4778. '"', '\'', '`',
  4779. '\t', '\r', '\n', '\v', '\f',
  4780. '\\', // NOTE(bill): Disallow windows style filepaths
  4781. '!', '$', '%', '^', '&', '*', '(', ')', '=',
  4782. '[', ']', '{', '}',
  4783. ';',
  4784. ':', // NOTE(bill): Disallow windows style absolute filepaths
  4785. '#',
  4786. '|', ',', '<', '>', '?',
  4787. };
  4788. gb_internal bool is_import_path_valid(String const &path) {
  4789. if (path.len > 0) {
  4790. u8 *start = path.text;
  4791. u8 *end = path.text + path.len;
  4792. u8 *curr = start;
  4793. while (curr < end) {
  4794. isize width = 1;
  4795. Rune r = *curr;
  4796. if (r >= 0x80) {
  4797. width = utf8_decode(curr, end-curr, &r);
  4798. if (r == GB_RUNE_INVALID && width == 1) {
  4799. return false;
  4800. }
  4801. else if (r == GB_RUNE_BOM && curr-start > 0) {
  4802. return false;
  4803. }
  4804. }
  4805. for (isize i = 0; i < gb_count_of(illegal_import_runes); i++) {
  4806. if (r == illegal_import_runes[i]) {
  4807. return false;
  4808. }
  4809. }
  4810. curr += width;
  4811. }
  4812. return true;
  4813. }
  4814. return false;
  4815. }
  4816. gb_internal bool is_build_flag_path_valid(String const &path) {
  4817. if (path.len > 0) {
  4818. u8 *start = path.text;
  4819. u8 *end = path.text + path.len;
  4820. u8 *curr = start;
  4821. isize index = 0;
  4822. while (curr < end) {
  4823. isize width = 1;
  4824. Rune r = *curr;
  4825. if (r >= 0x80) {
  4826. width = utf8_decode(curr, end-curr, &r);
  4827. if (r == GB_RUNE_INVALID && width == 1) {
  4828. return false;
  4829. }
  4830. else if (r == GB_RUNE_BOM && curr-start > 0) {
  4831. return false;
  4832. }
  4833. }
  4834. for (isize i = 0; i < gb_count_of(illegal_import_runes); i++) {
  4835. #if defined(GB_SYSTEM_WINDOWS)
  4836. if (r == '\\') {
  4837. break;
  4838. } else if (r == ':') {
  4839. break;
  4840. }
  4841. #endif
  4842. if (r == illegal_import_runes[i]) {
  4843. return false;
  4844. }
  4845. }
  4846. curr += width;
  4847. index += 1;
  4848. }
  4849. return true;
  4850. }
  4851. return false;
  4852. }
  4853. gb_internal bool is_package_name_reserved(String const &name) {
  4854. if (name == "builtin") {
  4855. return true;
  4856. } else if (name == "intrinsics") {
  4857. return true;
  4858. }
  4859. return false;
  4860. }
  4861. gb_internal bool determine_path_from_string(BlockingMutex *file_mutex, Ast *node, String base_dir, String const &original_string, String *path) {
  4862. GB_ASSERT(path != nullptr);
  4863. // NOTE(bill): if file_mutex == nullptr, this means that the code is used within the semantics stage
  4864. String collection_name = {};
  4865. isize colon_pos = -1;
  4866. for (isize j = 0; j < original_string.len; j++) {
  4867. if (original_string[j] == ':') {
  4868. colon_pos = j;
  4869. break;
  4870. }
  4871. }
  4872. bool has_windows_drive = false;
  4873. #if defined(GB_SYSTEM_WINDOWS)
  4874. if (file_mutex == nullptr) {
  4875. if (colon_pos == 1 && original_string.len > 2) {
  4876. if (original_string[2] == '/' || original_string[2] == '\\') {
  4877. colon_pos = -1;
  4878. has_windows_drive = true;
  4879. }
  4880. }
  4881. }
  4882. #endif
  4883. String file_str = {};
  4884. if (colon_pos == 0) {
  4885. syntax_error(node, "Expected a collection name");
  4886. return false;
  4887. }
  4888. if (original_string.len > 0 && colon_pos > 0) {
  4889. collection_name = substring(original_string, 0, colon_pos);
  4890. file_str = substring(original_string, colon_pos+1, original_string.len);
  4891. } else {
  4892. file_str = original_string;
  4893. }
  4894. if (has_windows_drive) {
  4895. String sub_file_path = substring(file_str, 3, file_str.len);
  4896. if (!is_import_path_valid(sub_file_path)) {
  4897. syntax_error(node, "Invalid import path: '%.*s'", LIT(file_str));
  4898. return false;
  4899. }
  4900. } else if (!is_import_path_valid(file_str)) {
  4901. syntax_error(node, "Invalid import path: '%.*s'", LIT(file_str));
  4902. return false;
  4903. }
  4904. if (collection_name.len > 0) {
  4905. // NOTE(bill): `base:runtime` == `core:runtime`
  4906. if (collection_name == "core" && string_starts_with(file_str, str_lit("runtime"))) {
  4907. collection_name = str_lit("base");
  4908. }
  4909. if (collection_name == "system") {
  4910. if (node->kind != Ast_ForeignImportDecl) {
  4911. syntax_error(node, "The library collection 'system' is restrict for 'foreign_library'");
  4912. return false;
  4913. } else {
  4914. *path = file_str;
  4915. return true;
  4916. }
  4917. } else if (!find_library_collection_path(collection_name, &base_dir)) {
  4918. // NOTE(bill): It's a naughty name
  4919. syntax_error(node, "Unknown library collection: '%.*s'", LIT(collection_name));
  4920. return false;
  4921. }
  4922. } else {
  4923. #if !defined(GB_SYSTEM_WINDOWS)
  4924. // @NOTE(vassvik): foreign imports of shared libraries that are not in the system collection on
  4925. // linux/mac have to be local to the executable for consistency with shared libraries.
  4926. // Unix does not have a concept of "import library" for shared/dynamic libraries,
  4927. // so we need to pass the relative path to the linker, and add the current
  4928. // working directory of the exe to the library search paths.
  4929. // Static libraries can be linked directly with the full pathname
  4930. //
  4931. if (node->kind == Ast_ForeignImportDecl && (string_ends_with(file_str, str_lit(".so")) || string_contains_string(file_str, str_lit(".so.")))) {
  4932. *path = file_str;
  4933. return true;
  4934. }
  4935. #endif
  4936. }
  4937. if (is_package_name_reserved(file_str)) {
  4938. *path = file_str;
  4939. if (collection_name == "core" || collection_name == "base") {
  4940. return true;
  4941. } else {
  4942. syntax_error(node, "The package '%.*s' must be imported with the 'base' library collection: 'base:%.*s'", LIT(file_str), LIT(file_str));
  4943. return false;
  4944. }
  4945. }
  4946. if (file_mutex) mutex_lock(file_mutex);
  4947. defer (if (file_mutex) mutex_unlock(file_mutex));
  4948. if (node->kind == Ast_ForeignImportDecl) {
  4949. node->ForeignImportDecl.collection_name = collection_name;
  4950. }
  4951. if (has_windows_drive) {
  4952. *path = file_str;
  4953. } else {
  4954. bool ok = false;
  4955. String fullpath = string_trim_whitespace(get_fullpath_relative(permanent_allocator(), base_dir, file_str, &ok));
  4956. *path = fullpath;
  4957. }
  4958. return true;
  4959. }
  4960. gb_internal void parse_setup_file_decls(Parser *p, AstFile *f, String const &base_dir, Slice<Ast *> &decls);
  4961. gb_internal void parse_setup_file_when_stmt(Parser *p, AstFile *f, String const &base_dir, AstWhenStmt *ws) {
  4962. if (ws->body != nullptr) {
  4963. auto stmts = ws->body->BlockStmt.stmts;
  4964. parse_setup_file_decls(p, f, base_dir, stmts);
  4965. }
  4966. if (ws->else_stmt != nullptr) {
  4967. switch (ws->else_stmt->kind) {
  4968. case Ast_BlockStmt: {
  4969. auto stmts = ws->else_stmt->BlockStmt.stmts;
  4970. parse_setup_file_decls(p, f, base_dir, stmts);
  4971. } break;
  4972. case Ast_WhenStmt:
  4973. parse_setup_file_when_stmt(p, f, base_dir, &ws->else_stmt->WhenStmt);
  4974. break;
  4975. }
  4976. }
  4977. }
  4978. gb_internal void parse_setup_file_decls(Parser *p, AstFile *f, String const &base_dir, Slice<Ast *> &decls) {
  4979. for_array(i, decls) {
  4980. Ast *node = decls[i];
  4981. if (!is_ast_decl(node) &&
  4982. node->kind != Ast_WhenStmt &&
  4983. node->kind != Ast_BadStmt &&
  4984. node->kind != Ast_EmptyStmt) {
  4985. // NOTE(bill): Sanity check
  4986. if (node->kind == Ast_ExprStmt) {
  4987. Ast *expr = node->ExprStmt.expr;
  4988. if (expr->kind == Ast_CallExpr &&
  4989. expr->CallExpr.proc->kind == Ast_BasicDirective) {
  4990. f->directive_count += 1;
  4991. continue;
  4992. }
  4993. }
  4994. syntax_error(node, "Only declarations are allowed at file scope, got %.*s", LIT(ast_strings[node->kind]));
  4995. } else if (node->kind == Ast_ImportDecl) {
  4996. ast_node(id, ImportDecl, node);
  4997. String original_string = string_trim_whitespace(string_value_from_token(f, id->relpath));
  4998. String import_path = {};
  4999. bool ok = determine_path_from_string(&p->file_decl_mutex, node, base_dir, original_string, &import_path);
  5000. if (!ok) {
  5001. decls[i] = ast_bad_decl(f, id->relpath, id->relpath);
  5002. continue;
  5003. }
  5004. import_path = string_trim_whitespace(import_path);
  5005. id->fullpath = import_path;
  5006. if (is_package_name_reserved(import_path)) {
  5007. continue;
  5008. }
  5009. try_add_import_path(p, import_path, original_string, ast_token(node).pos);
  5010. } else if (node->kind == Ast_ForeignImportDecl) {
  5011. ast_node(fl, ForeignImportDecl, node);
  5012. auto fullpaths = array_make<String>(permanent_allocator(), 0, fl->filepaths.count);
  5013. for (Token const &fp : fl->filepaths) {
  5014. String file_str = string_trim_whitespace(string_value_from_token(f, fp));
  5015. String fullpath = file_str;
  5016. if (allow_check_foreign_filepath()) {
  5017. String foreign_path = {};
  5018. bool ok = determine_path_from_string(&p->file_decl_mutex, node, base_dir, file_str, &foreign_path);
  5019. if (!ok) {
  5020. decls[i] = ast_bad_decl(f, fp, fl->filepaths[fl->filepaths.count-1]);
  5021. goto end;
  5022. }
  5023. fullpath = foreign_path;
  5024. }
  5025. array_add(&fullpaths, fullpath);
  5026. }
  5027. if (fullpaths.count == 0) {
  5028. syntax_error(decls[i], "No foreign paths found");
  5029. decls[i] = ast_bad_decl(f, fl->filepaths[0], fl->filepaths[fl->filepaths.count-1]);
  5030. goto end;
  5031. }
  5032. fl->fullpaths = slice_from_array(fullpaths);
  5033. } else if (node->kind == Ast_WhenStmt) {
  5034. ast_node(ws, WhenStmt, node);
  5035. parse_setup_file_when_stmt(p, f, base_dir, ws);
  5036. }
  5037. end:;
  5038. }
  5039. }
  5040. gb_internal String build_tag_get_token(String s, String *out) {
  5041. s = string_trim_whitespace(s);
  5042. isize n = 0;
  5043. while (n < s.len) {
  5044. Rune rune = 0;
  5045. isize width = utf8_decode(&s[n], s.len-n, &rune);
  5046. if (n == 0 && rune == '!') {
  5047. } else if (!rune_is_letter(rune) && !rune_is_digit(rune)) {
  5048. isize k = gb_max(gb_max(n, width), 1);
  5049. *out = substring(s, k, s.len);
  5050. return substring(s, 0, k);
  5051. }
  5052. n += width;
  5053. }
  5054. out->len = 0;
  5055. return s;
  5056. }
  5057. gb_internal bool parse_build_tag(Token token_for_pos, String s) {
  5058. String const prefix = str_lit("+build");
  5059. GB_ASSERT(string_starts_with(s, prefix));
  5060. s = string_trim_whitespace(substring(s, prefix.len, s.len));
  5061. if (s.len == 0) {
  5062. return true;
  5063. }
  5064. bool any_correct = false;
  5065. while (s.len > 0) {
  5066. bool this_kind_correct = true;
  5067. do {
  5068. String p = string_trim_whitespace(build_tag_get_token(s, &s));
  5069. if (p.len == 0) break;
  5070. if (p == ",") break;
  5071. bool is_notted = false;
  5072. if (p[0] == '!') {
  5073. is_notted = true;
  5074. p = substring(p, 1, p.len);
  5075. if (p.len == 0) {
  5076. syntax_error(token_for_pos, "Expected a build platform after '!'");
  5077. break;
  5078. }
  5079. }
  5080. if (p.len == 0) {
  5081. continue;
  5082. }
  5083. if (p == "ignore") {
  5084. this_kind_correct = false;
  5085. continue;
  5086. }
  5087. TargetOsKind os = get_target_os_from_string(p);
  5088. TargetArchKind arch = get_target_arch_from_string(p);
  5089. if (os != TargetOs_Invalid) {
  5090. GB_ASSERT(arch == TargetArch_Invalid);
  5091. if (is_notted) {
  5092. this_kind_correct = this_kind_correct && (os != build_context.metrics.os);
  5093. } else {
  5094. this_kind_correct = this_kind_correct && (os == build_context.metrics.os);
  5095. }
  5096. } else if (arch != TargetArch_Invalid) {
  5097. if (is_notted) {
  5098. this_kind_correct = this_kind_correct && (arch != build_context.metrics.arch);
  5099. } else {
  5100. this_kind_correct = this_kind_correct && (arch == build_context.metrics.arch);
  5101. }
  5102. }
  5103. if (os == TargetOs_Invalid && arch == TargetArch_Invalid) {
  5104. syntax_error(token_for_pos, "Invalid build tag platform: %.*s", LIT(p));
  5105. break;
  5106. }
  5107. } while (s.len > 0);
  5108. any_correct = any_correct || this_kind_correct;
  5109. }
  5110. return any_correct;
  5111. }
  5112. gb_internal String vet_tag_get_token(String s, String *out) {
  5113. s = string_trim_whitespace(s);
  5114. isize n = 0;
  5115. while (n < s.len) {
  5116. Rune rune = 0;
  5117. isize width = utf8_decode(&s[n], s.len-n, &rune);
  5118. if (n == 0 && rune == '!') {
  5119. } else if (!rune_is_letter(rune) && !rune_is_digit(rune) && rune != '-') {
  5120. isize k = gb_max(gb_max(n, width), 1);
  5121. *out = substring(s, k, s.len);
  5122. return substring(s, 0, k);
  5123. }
  5124. n += width;
  5125. }
  5126. out->len = 0;
  5127. return s;
  5128. }
  5129. gb_internal u64 parse_vet_tag(Token token_for_pos, String s) {
  5130. String const prefix = str_lit("+vet");
  5131. GB_ASSERT(string_starts_with(s, prefix));
  5132. s = string_trim_whitespace(substring(s, prefix.len, s.len));
  5133. if (s.len == 0) {
  5134. return VetFlag_All;
  5135. }
  5136. u64 vet_flags = 0;
  5137. u64 vet_not_flags = 0;
  5138. while (s.len > 0) {
  5139. String p = string_trim_whitespace(vet_tag_get_token(s, &s));
  5140. if (p.len == 0) {
  5141. break;
  5142. }
  5143. bool is_notted = false;
  5144. if (p[0] == '!') {
  5145. is_notted = true;
  5146. p = substring(p, 1, p.len);
  5147. if (p.len == 0) {
  5148. syntax_error(token_for_pos, "Expected a vet flag name after '!'");
  5149. return build_context.vet_flags;
  5150. }
  5151. }
  5152. u64 flag = get_vet_flag_from_name(p);
  5153. if (flag != VetFlag_NONE) {
  5154. if (is_notted) {
  5155. vet_not_flags |= flag;
  5156. } else {
  5157. vet_flags |= flag;
  5158. }
  5159. } else {
  5160. ERROR_BLOCK();
  5161. syntax_error(token_for_pos, "Invalid vet flag name: %.*s", LIT(p));
  5162. error_line("\tExpected one of the following\n");
  5163. error_line("\tunused\n");
  5164. error_line("\tshadowing\n");
  5165. error_line("\tusing-stmt\n");
  5166. error_line("\tusing-param\n");
  5167. error_line("\textra\n");
  5168. return build_context.vet_flags;
  5169. }
  5170. }
  5171. if (vet_flags == 0 && vet_not_flags == 0) {
  5172. return build_context.vet_flags;
  5173. }
  5174. if (vet_flags == 0 && vet_not_flags != 0) {
  5175. return build_context.vet_flags &~ vet_not_flags;
  5176. }
  5177. if (vet_flags != 0 && vet_not_flags == 0) {
  5178. return vet_flags;
  5179. }
  5180. GB_ASSERT(vet_flags != 0 && vet_not_flags != 0);
  5181. return vet_flags &~ vet_not_flags;
  5182. }
  5183. gb_internal String dir_from_path(String path) {
  5184. String base_dir = path;
  5185. for (isize i = path.len-1; i >= 0; i--) {
  5186. if (base_dir[i] == '\\' ||
  5187. base_dir[i] == '/') {
  5188. break;
  5189. }
  5190. base_dir.len--;
  5191. }
  5192. return base_dir;
  5193. }
  5194. gb_internal isize calc_decl_count(Ast *decl) {
  5195. isize count = 0;
  5196. switch (decl->kind) {
  5197. case Ast_BlockStmt:
  5198. for (Ast *stmt : decl->BlockStmt.stmts) {
  5199. count += calc_decl_count(stmt);
  5200. }
  5201. break;
  5202. case Ast_WhenStmt:
  5203. {
  5204. isize inner_count = calc_decl_count(decl->WhenStmt.body);
  5205. if (decl->WhenStmt.else_stmt) {
  5206. inner_count = gb_max(inner_count, calc_decl_count(decl->WhenStmt.else_stmt));
  5207. }
  5208. count += inner_count;
  5209. }
  5210. break;
  5211. case Ast_ValueDecl:
  5212. count = decl->ValueDecl.names.count;
  5213. break;
  5214. case Ast_ForeignBlockDecl:
  5215. count = calc_decl_count(decl->ForeignBlockDecl.body);
  5216. break;
  5217. case Ast_ImportDecl:
  5218. case Ast_ForeignImportDecl:
  5219. count = 1;
  5220. break;
  5221. }
  5222. return count;
  5223. }
  5224. gb_internal bool parse_build_project_directory_tag(Token token_for_pos, String s) {
  5225. String const prefix = str_lit("+build-project-name");
  5226. GB_ASSERT(string_starts_with(s, prefix));
  5227. s = string_trim_whitespace(substring(s, prefix.len, s.len));
  5228. if (s.len == 0) {
  5229. return true;
  5230. }
  5231. bool any_correct = false;
  5232. while (s.len > 0) {
  5233. bool this_kind_correct = true;
  5234. do {
  5235. String p = string_trim_whitespace(build_tag_get_token(s, &s));
  5236. if (p.len == 0) break;
  5237. if (p == ",") break;
  5238. bool is_notted = false;
  5239. if (p[0] == '!') {
  5240. is_notted = true;
  5241. p = substring(p, 1, p.len);
  5242. if (p.len == 0) {
  5243. syntax_error(token_for_pos, "Expected a build-project-name after '!'");
  5244. break;
  5245. }
  5246. }
  5247. if (p.len == 0) {
  5248. continue;
  5249. }
  5250. if (is_notted) {
  5251. this_kind_correct = this_kind_correct && (p != build_context.ODIN_BUILD_PROJECT_NAME);
  5252. } else {
  5253. this_kind_correct = this_kind_correct && (p == build_context.ODIN_BUILD_PROJECT_NAME);
  5254. }
  5255. } while (s.len > 0);
  5256. any_correct = any_correct || this_kind_correct;
  5257. }
  5258. return any_correct;
  5259. }
  5260. gb_internal bool parse_file(Parser *p, AstFile *f) {
  5261. if (f->tokens.count == 0) {
  5262. return true;
  5263. }
  5264. if (f->tokens.count > 0 && f->tokens[0].kind == Token_EOF) {
  5265. return true;
  5266. }
  5267. u64 start = time_stamp_time_now();
  5268. String filepath = f->tokenizer.fullpath;
  5269. String base_dir = dir_from_path(filepath);
  5270. if (f->curr_token.kind == Token_Comment) {
  5271. consume_comment_groups(f, f->prev_token);
  5272. }
  5273. CommentGroup *docs = f->lead_comment;
  5274. if (f->curr_token.kind != Token_package) {
  5275. ERROR_BLOCK();
  5276. syntax_error(f->curr_token, "Expected a package declaration at the beginning of the file");
  5277. // IMPORTANT NOTE(bill): this is technically a race condition with the suggestion, but it's ony a suggession
  5278. // so in practice is should be "fine"
  5279. if (f->pkg && f->pkg->name != "") {
  5280. error_line("\tSuggestion: Add 'package %.*s' to the top of the file\n", LIT(f->pkg->name));
  5281. }
  5282. return false;
  5283. }
  5284. f->package_token = expect_token(f, Token_package);
  5285. if (f->package_token.kind != Token_package) {
  5286. return false;
  5287. }
  5288. if (docs != nullptr) {
  5289. TokenPos end = token_pos_end(docs->list[docs->list.count-1]);
  5290. if (end.line == f->package_token.pos.line || end.line+1 == f->package_token.pos.line) {
  5291. // Okay
  5292. } else {
  5293. docs = nullptr;
  5294. }
  5295. }
  5296. Token package_name = expect_token_after(f, Token_Ident, "package");
  5297. if (package_name.kind == Token_Ident) {
  5298. if (package_name.string == "_") {
  5299. syntax_error(package_name, "Invalid package name '_'");
  5300. } else if (f->pkg->kind != Package_Runtime && package_name.string == "runtime") {
  5301. syntax_error(package_name, "Use of reserved package name '%.*s'", LIT(package_name.string));
  5302. } else if (is_package_name_reserved(package_name.string)) {
  5303. syntax_error(package_name, "Use of reserved package name '%.*s'", LIT(package_name.string));
  5304. }
  5305. }
  5306. f->package_name = package_name.string;
  5307. if (!f->pkg->is_single_file && docs != nullptr && docs->list.count > 0) {
  5308. for (Token const &tok : docs->list) {
  5309. GB_ASSERT(tok.kind == Token_Comment);
  5310. String str = tok.string;
  5311. if (string_starts_with(str, str_lit("//"))) {
  5312. String lc = string_trim_whitespace(substring(str, 2, str.len));
  5313. if (lc.len > 0 && lc[0] == '+') {
  5314. if (string_starts_with(lc, str_lit("+build-project-name"))) {
  5315. if (!parse_build_project_directory_tag(tok, lc)) {
  5316. return false;
  5317. }
  5318. } else if (string_starts_with(lc, str_lit("+build"))) {
  5319. if (!parse_build_tag(tok, lc)) {
  5320. return false;
  5321. }
  5322. } else if (string_starts_with(lc, str_lit("+vet"))) {
  5323. f->vet_flags = parse_vet_tag(tok, lc);
  5324. f->vet_flags_set = true;
  5325. } else if (string_starts_with(lc, str_lit("+ignore"))) {
  5326. return false;
  5327. } else if (string_starts_with(lc, str_lit("+private"))) {
  5328. f->flags |= AstFile_IsPrivatePkg;
  5329. String command = string_trim_starts_with(lc, str_lit("+private "));
  5330. command = string_trim_whitespace(command);
  5331. if (lc == "+private") {
  5332. f->flags |= AstFile_IsPrivatePkg;
  5333. } else if (command == "package") {
  5334. f->flags |= AstFile_IsPrivatePkg;
  5335. } else if (command == "file") {
  5336. f->flags |= AstFile_IsPrivateFile;
  5337. }
  5338. } else if (lc == "+lazy") {
  5339. if (build_context.ignore_lazy) {
  5340. // Ignore
  5341. } else if (f->flags & AstFile_IsTest) {
  5342. // Ignore
  5343. } else if (f->pkg->kind == Package_Init && build_context.command_kind == Command_doc) {
  5344. // Ignore
  5345. } else {
  5346. f->flags |= AstFile_IsLazy;
  5347. }
  5348. } else if (lc == "+no-instrumentation") {
  5349. f->flags |= AstFile_NoInstrumentation;
  5350. } else {
  5351. warning(tok, "Ignoring unknown tag '%.*s'", LIT(lc));
  5352. }
  5353. }
  5354. }
  5355. }
  5356. }
  5357. Ast *pd = ast_package_decl(f, f->package_token, package_name, docs, f->line_comment);
  5358. expect_semicolon(f);
  5359. f->pkg_decl = pd;
  5360. if (f->error_count == 0) {
  5361. auto decls = array_make<Ast *>(ast_allocator(f));
  5362. while (f->curr_token.kind != Token_EOF) {
  5363. Ast *stmt = parse_stmt(f);
  5364. if (stmt && stmt->kind != Ast_EmptyStmt) {
  5365. array_add(&decls, stmt);
  5366. if (stmt->kind == Ast_ExprStmt &&
  5367. stmt->ExprStmt.expr != nullptr &&
  5368. stmt->ExprStmt.expr->kind == Ast_ProcLit) {
  5369. syntax_error(stmt, "Procedure literal evaluated but not used");
  5370. }
  5371. f->total_file_decl_count += calc_decl_count(stmt);
  5372. if (stmt->kind == Ast_WhenStmt || stmt->kind == Ast_ExprStmt || stmt->kind == Ast_ImportDecl) {
  5373. f->delayed_decl_count += 1;
  5374. }
  5375. }
  5376. }
  5377. f->decls = slice_from_array(decls);
  5378. parse_setup_file_decls(p, f, base_dir, f->decls);
  5379. }
  5380. u64 end = time_stamp_time_now();
  5381. f->time_to_parse = cast(f64)(end-start)/cast(f64)time_stamp__freq();
  5382. for (int i = 0; i < AstDelayQueue_COUNT; i++) {
  5383. array_init(f->delayed_decls_queues+i, ast_allocator(f), 0, f->delayed_decl_count);
  5384. }
  5385. return f->error_count == 0;
  5386. }
  5387. gb_internal ParseFileError process_imported_file(Parser *p, ImportedFile imported_file) {
  5388. AstPackage *pkg = imported_file.pkg;
  5389. FileInfo fi = imported_file.fi;
  5390. TokenPos pos = imported_file.pos;
  5391. AstFile *file = gb_alloc_item(permanent_allocator(), AstFile);
  5392. file->pkg = pkg;
  5393. file->id = cast(i32)(imported_file.index+1);
  5394. TokenPos err_pos = {0};
  5395. ParseFileError err = init_ast_file(file, fi.fullpath, &err_pos);
  5396. err_pos.file_id = file->id;
  5397. file->last_error = err;
  5398. if (err != ParseFile_None) {
  5399. if (err == ParseFile_EmptyFile) {
  5400. if (fi.fullpath == p->init_fullpath) {
  5401. syntax_error(pos, "Initial file is empty - %.*s\n", LIT(p->init_fullpath));
  5402. exit_with_errors();
  5403. }
  5404. } else {
  5405. switch (err) {
  5406. case ParseFile_WrongExtension:
  5407. syntax_error(pos, "Failed to parse file: %.*s; invalid file extension: File must have the extension '.odin'", LIT(fi.name));
  5408. break;
  5409. case ParseFile_InvalidFile:
  5410. syntax_error(pos, "Failed to parse file: %.*s; invalid file or cannot be found", LIT(fi.name));
  5411. break;
  5412. case ParseFile_Permission:
  5413. syntax_error(pos, "Failed to parse file: %.*s; file permissions problem", LIT(fi.name));
  5414. break;
  5415. case ParseFile_NotFound:
  5416. syntax_error(pos, "Failed to parse file: %.*s; file cannot be found ('%.*s')", LIT(fi.name), LIT(fi.fullpath));
  5417. break;
  5418. case ParseFile_InvalidToken:
  5419. syntax_error(err_pos, "Failed to parse file: %.*s; invalid token found in file", LIT(fi.name));
  5420. break;
  5421. case ParseFile_EmptyFile:
  5422. syntax_error(pos, "Failed to parse file: %.*s; file contains no tokens", LIT(fi.name));
  5423. break;
  5424. case ParseFile_FileTooLarge:
  5425. syntax_error(pos, "Failed to parse file: %.*s; file is too large, exceeds maximum file size of 2 GiB", LIT(fi.name));
  5426. break;
  5427. }
  5428. return err;
  5429. }
  5430. }
  5431. {
  5432. String name = file->fullpath;
  5433. name = remove_directory_from_path(name);
  5434. name = remove_extension_from_path(name);
  5435. if (string_starts_with(name, str_lit("_"))) {
  5436. syntax_error(pos, "Files cannot start with '_', got '%.*s'", LIT(file->fullpath));
  5437. }
  5438. }
  5439. if (build_context.command_kind == Command_test) {
  5440. String name = file->fullpath;
  5441. name = remove_extension_from_path(name);
  5442. String test_suffix = str_lit("_test");
  5443. if (string_ends_with(name, test_suffix) && name != test_suffix) {
  5444. file->flags |= AstFile_IsTest;
  5445. }
  5446. }
  5447. if (parse_file(p, file)) {
  5448. MUTEX_GUARD_BLOCK(&pkg->files_mutex) {
  5449. array_add(&pkg->files, file);
  5450. }
  5451. mutex_lock(&pkg->name_mutex);
  5452. if (pkg->name.len == 0) {
  5453. pkg->name = file->package_name;
  5454. } else if (pkg->name != file->package_name) {
  5455. if (file->tokens.count > 0 && file->tokens[0].kind != Token_EOF) {
  5456. Token tok = file->package_token;
  5457. tok.pos.file_id = file->id;
  5458. tok.pos.line = gb_max(tok.pos.line, 1);
  5459. tok.pos.column = gb_max(tok.pos.column, 1);
  5460. syntax_error(tok, "Different package name, expected '%.*s', got '%.*s'", LIT(pkg->name), LIT(file->package_name));
  5461. }
  5462. }
  5463. mutex_unlock(&pkg->name_mutex);
  5464. p->total_line_count.fetch_add(file->tokenizer.line_count);
  5465. p->total_token_count.fetch_add(file->tokens.count);
  5466. }
  5467. return ParseFile_None;
  5468. }
  5469. gb_internal ParseFileError parse_packages(Parser *p, String init_filename) {
  5470. GB_ASSERT(init_filename.text[init_filename.len] == 0);
  5471. String init_fullpath = path_to_full_path(permanent_allocator(), init_filename);
  5472. if (!path_is_directory(init_fullpath)) {
  5473. String const ext = str_lit(".odin");
  5474. if (!string_ends_with(init_fullpath, ext)) {
  5475. error({}, "Expected either a directory or a .odin file, got '%.*s'\n", LIT(init_filename));
  5476. return ParseFile_WrongExtension;
  5477. }
  5478. } else if (init_fullpath.len != 0) {
  5479. String path = init_fullpath;
  5480. if (path[path.len-1] == '/') {
  5481. path.len -= 1;
  5482. }
  5483. if ((build_context.command_kind & Command__does_build) &&
  5484. build_context.build_mode == BuildMode_Executable) {
  5485. String short_path = filename_from_path(path);
  5486. char *cpath = alloc_cstring(temporary_allocator(), short_path);
  5487. if (gb_file_exists(cpath)) {
  5488. error({}, "Please specify the executable name with -out:<string> as a directory exists with the same name in the current working directory");
  5489. return ParseFile_DirectoryAlreadyExists;
  5490. }
  5491. }
  5492. }
  5493. { // Add these packages serially and then process them parallel
  5494. TokenPos init_pos = {};
  5495. {
  5496. bool ok = false;
  5497. String s = get_fullpath_base_collection(permanent_allocator(), str_lit("runtime"), &ok);
  5498. if (!ok) {
  5499. compiler_error("Unable to find The 'base:runtime' package. Is the ODIN_ROOT set up correctly?");
  5500. }
  5501. try_add_import_path(p, s, s, init_pos, Package_Runtime);
  5502. }
  5503. try_add_import_path(p, init_fullpath, init_fullpath, init_pos, Package_Init);
  5504. p->init_fullpath = init_fullpath;
  5505. if (build_context.command_kind == Command_test) {
  5506. bool ok = false;
  5507. String s = get_fullpath_core_collection(permanent_allocator(), str_lit("testing"), &ok);
  5508. if (!ok) {
  5509. compiler_error("Unable to find The 'core:testing' package. Is the ODIN_ROOT set up correctly?");
  5510. }
  5511. try_add_import_path(p, s, s, init_pos, Package_Normal);
  5512. }
  5513. for (String const &path : build_context.extra_packages) {
  5514. String fullpath = path_to_full_path(permanent_allocator(), path); // LEAK?
  5515. if (!path_is_directory(fullpath)) {
  5516. String const ext = str_lit(".odin");
  5517. if (!string_ends_with(fullpath, ext)) {
  5518. error({}, "Expected either a directory or a .odin file, got '%.*s'\n", LIT(fullpath));
  5519. return ParseFile_WrongExtension;
  5520. }
  5521. }
  5522. AstPackage *pkg = try_add_import_path(p, fullpath, fullpath, init_pos, Package_Normal);
  5523. if (pkg) {
  5524. pkg->is_extra = true;
  5525. }
  5526. }
  5527. }
  5528. thread_pool_wait();
  5529. for (ParseFileErrorNode *node = p->file_error_head; node != nullptr; node = node->next) {
  5530. if (node->err != ParseFile_None) {
  5531. return node->err;
  5532. }
  5533. }
  5534. for (isize i = p->packages.count-1; i >= 0; i--) {
  5535. AstPackage *pkg = p->packages[i];
  5536. for (isize j = pkg->files.count-1; j >= 0; j--) {
  5537. AstFile *file = pkg->files[j];
  5538. if (file->error_count != 0) {
  5539. if (file->last_error != ParseFile_None) {
  5540. return file->last_error;
  5541. }
  5542. return ParseFile_GeneralError;
  5543. }
  5544. }
  5545. }
  5546. return ParseFile_None;
  5547. }