parser.cpp 184 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429
  1. #include "parser_pos.cpp"
  2. gb_internal u64 ast_file_vet_flags(AstFile *f) {
  3. if (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. }
  3035. return type;
  3036. }
  3037. gb_internal void parse_foreign_block_decl(AstFile *f, Array<Ast *> *decls) {
  3038. Ast *decl = parse_stmt(f);
  3039. switch (decl->kind) {
  3040. case Ast_EmptyStmt:
  3041. case Ast_BadStmt:
  3042. case Ast_BadDecl:
  3043. return;
  3044. case Ast_WhenStmt:
  3045. case Ast_ValueDecl:
  3046. array_add(decls, decl);
  3047. return;
  3048. default:
  3049. syntax_error(decl, "Foreign blocks only allow procedure and variable declarations");
  3050. return;
  3051. }
  3052. }
  3053. gb_internal Ast *parse_foreign_block(AstFile *f, Token token) {
  3054. CommentGroup *docs = f->lead_comment;
  3055. Ast *foreign_library = nullptr;
  3056. if (f->curr_token.kind == Token_OpenBrace) {
  3057. foreign_library = ast_ident(f, blank_token);
  3058. } else {
  3059. foreign_library = parse_ident(f);
  3060. }
  3061. Token open = {};
  3062. Token close = {};
  3063. auto decls = array_make<Ast *>(ast_allocator(f));
  3064. bool prev_in_foreign_block = f->in_foreign_block;
  3065. defer (f->in_foreign_block = prev_in_foreign_block);
  3066. f->in_foreign_block = true;
  3067. skip_possible_newline_for_literal(f);
  3068. open = expect_token(f, Token_OpenBrace);
  3069. while (f->curr_token.kind != Token_CloseBrace &&
  3070. f->curr_token.kind != Token_EOF) {
  3071. parse_foreign_block_decl(f, &decls);
  3072. }
  3073. close = expect_token(f, Token_CloseBrace);
  3074. Ast *body = ast_block_stmt(f, decls, open, close);
  3075. Ast *decl = ast_foreign_block_decl(f, token, foreign_library, body, docs);
  3076. expect_semicolon(f);
  3077. return decl;
  3078. }
  3079. gb_internal void print_comment_group(CommentGroup *group) {
  3080. if (group) {
  3081. for (Token const &token : group->list) {
  3082. gb_printf_err("%.*s\n", LIT(token.string));
  3083. }
  3084. gb_printf_err("\n");
  3085. }
  3086. }
  3087. gb_internal Ast *parse_value_decl(AstFile *f, Array<Ast *> names, CommentGroup *docs) {
  3088. bool is_mutable = true;
  3089. Array<Ast *> values = {};
  3090. Ast *type = parse_type_or_ident(f);
  3091. if (f->curr_token.kind == Token_Eq ||
  3092. f->curr_token.kind == Token_Colon) {
  3093. Token sep = {};
  3094. if (!is_mutable) {
  3095. sep = expect_token_after(f, Token_Colon, "type");
  3096. } else {
  3097. sep = advance_token(f);
  3098. is_mutable = sep.kind != Token_Colon;
  3099. }
  3100. values = parse_rhs_expr_list(f);
  3101. if (values.count > names.count) {
  3102. syntax_error(f->curr_token, "Too many values on the right hand side of the declaration");
  3103. } else if (values.count < names.count && !is_mutable) {
  3104. syntax_error(f->curr_token, "All constant declarations must be defined");
  3105. } else if (values.count == 0) {
  3106. syntax_error(f->curr_token, "Expected an expression for this declaration");
  3107. }
  3108. }
  3109. if (is_mutable) {
  3110. if (type == nullptr && values.count == 0) {
  3111. syntax_error(f->curr_token, "Missing variable type or initialization");
  3112. return ast_bad_decl(f, f->curr_token, f->curr_token);
  3113. }
  3114. } else {
  3115. if (type == nullptr && values.count == 0 && names.count > 0) {
  3116. syntax_error(f->curr_token, "Missing constant value");
  3117. return ast_bad_decl(f, f->curr_token, f->curr_token);
  3118. }
  3119. }
  3120. if (values.data == nullptr) {
  3121. values.allocator = ast_allocator(f);
  3122. }
  3123. CommentGroup *end_comment = f->lead_comment;
  3124. if (f->expr_level >= 0) {
  3125. if (f->curr_token.kind == Token_CloseBrace &&
  3126. f->curr_token.pos.line == f->prev_token.pos.line) {
  3127. } else {
  3128. expect_semicolon(f);
  3129. }
  3130. }
  3131. if (f->curr_proc == nullptr) {
  3132. if (values.count > 0 && names.count != values.count) {
  3133. syntax_error(
  3134. values[0],
  3135. "Expected %td expressions on the right hand side, got %td\n"
  3136. "\tNote: Global declarations do not allow for multi-valued expressions",
  3137. names.count, values.count
  3138. );
  3139. }
  3140. }
  3141. return ast_value_decl(f, names, type, values, is_mutable, docs, end_comment);
  3142. }
  3143. gb_internal Ast *parse_simple_stmt(AstFile *f, u32 flags) {
  3144. Token token = f->curr_token;
  3145. CommentGroup *docs = f->lead_comment;
  3146. Array<Ast *> lhs = parse_lhs_expr_list(f);
  3147. token = f->curr_token;
  3148. switch (token.kind) {
  3149. case Token_Eq:
  3150. case Token_AddEq:
  3151. case Token_SubEq:
  3152. case Token_MulEq:
  3153. case Token_QuoEq:
  3154. case Token_ModEq:
  3155. case Token_ModModEq:
  3156. case Token_AndEq:
  3157. case Token_OrEq:
  3158. case Token_XorEq:
  3159. case Token_ShlEq:
  3160. case Token_ShrEq:
  3161. case Token_AndNotEq:
  3162. case Token_CmpAndEq:
  3163. case Token_CmpOrEq:
  3164. {
  3165. if (f->curr_proc == nullptr) {
  3166. syntax_error(f->curr_token, "You cannot use a simple statement in the file scope");
  3167. return ast_bad_stmt(f, f->curr_token, f->curr_token);
  3168. }
  3169. advance_token(f);
  3170. Array<Ast *> rhs = parse_rhs_expr_list(f);
  3171. if (rhs.count == 0) {
  3172. syntax_error(token, "No right-hand side in assignment statement.");
  3173. return ast_bad_stmt(f, token, f->curr_token);
  3174. }
  3175. return ast_assign_stmt(f, token, lhs, rhs);
  3176. } break;
  3177. case Token_in:
  3178. if (flags&StmtAllowFlag_In) {
  3179. allow_token(f, Token_in);
  3180. bool prev_allow_range = f->allow_range;
  3181. f->allow_range = true;
  3182. Ast *expr = parse_expr(f, true);
  3183. f->allow_range = prev_allow_range;
  3184. auto rhs = array_make<Ast *>(ast_allocator(f), 0, 1);
  3185. array_add(&rhs, expr);
  3186. return ast_assign_stmt(f, token, lhs, rhs);
  3187. }
  3188. break;
  3189. case Token_Colon:
  3190. expect_token_after(f, Token_Colon, "identifier list");
  3191. if ((flags&StmtAllowFlag_Label) && lhs.count == 1) {
  3192. bool is_partial = false;
  3193. bool is_reverse = false;
  3194. Token partial_token = {};
  3195. if (f->curr_token.kind == Token_Hash) {
  3196. // NOTE(bill): This is purely for error messages
  3197. Token name = peek_token_n(f, 0);
  3198. if (name.kind == Token_Ident && name.string == "partial" &&
  3199. peek_token_n(f, 1).kind == Token_switch) {
  3200. partial_token = expect_token(f, Token_Hash);
  3201. expect_token(f, Token_Ident);
  3202. is_partial = true;
  3203. } else if (name.kind == Token_Ident && name.string == "reverse" &&
  3204. peek_token_n(f, 1).kind == Token_for) {
  3205. partial_token = expect_token(f, Token_Hash);
  3206. expect_token(f, Token_Ident);
  3207. is_reverse = true;
  3208. }
  3209. }
  3210. switch (f->curr_token.kind) {
  3211. case Token_OpenBrace: // block statement
  3212. case Token_if:
  3213. case Token_for:
  3214. case Token_switch: {
  3215. Ast *name = lhs[0];
  3216. Ast *label = ast_label_decl(f, ast_token(name), name);
  3217. Ast *stmt = parse_stmt(f);
  3218. #define _SET_LABEL(Kind_, label_) case GB_JOIN2(Ast_, Kind_): (stmt->Kind_).label = label_; break
  3219. switch (stmt->kind) {
  3220. _SET_LABEL(BlockStmt, label);
  3221. _SET_LABEL(IfStmt, label);
  3222. _SET_LABEL(ForStmt, label);
  3223. _SET_LABEL(RangeStmt, label);
  3224. _SET_LABEL(SwitchStmt, label);
  3225. _SET_LABEL(TypeSwitchStmt, label);
  3226. default:
  3227. syntax_error(token, "Labels can only be applied to a loop or switch statement");
  3228. break;
  3229. }
  3230. #undef _SET_LABEL
  3231. if (is_partial) {
  3232. switch (stmt->kind) {
  3233. case Ast_SwitchStmt:
  3234. stmt->SwitchStmt.partial = true;
  3235. break;
  3236. case Ast_TypeSwitchStmt:
  3237. stmt->TypeSwitchStmt.partial = true;
  3238. break;
  3239. }
  3240. syntax_error(partial_token, "Incorrect use of directive, use '#partial %.*s: switch'", LIT(ast_token(name).string));
  3241. } else if (is_reverse) {
  3242. switch (stmt->kind) {
  3243. case Ast_RangeStmt:
  3244. if (stmt->RangeStmt.reverse) {
  3245. syntax_error(token, "#reverse already applied to a 'for in' statement");
  3246. }
  3247. stmt->RangeStmt.reverse = true;
  3248. break;
  3249. default:
  3250. syntax_error(token, "#reverse can only be applied to a 'for in' statement");
  3251. break;
  3252. }
  3253. }
  3254. return stmt;
  3255. } break;
  3256. }
  3257. }
  3258. return parse_value_decl(f, lhs, docs);
  3259. }
  3260. if (lhs.count > 1) {
  3261. syntax_error(token, "Expected 1 expression");
  3262. return ast_bad_stmt(f, token, f->curr_token);
  3263. }
  3264. switch (token.kind) {
  3265. case Token_Increment:
  3266. case Token_Decrement:
  3267. advance_token(f);
  3268. syntax_error(token, "Postfix '%.*s' statement is not supported", LIT(token.string));
  3269. break;
  3270. }
  3271. #if 0
  3272. switch (token.kind) {
  3273. case Token_Inc:
  3274. case Token_Dec:
  3275. advance_token(f);
  3276. return ast_inc_dec_stmt(f, token, lhs[0]);
  3277. }
  3278. #endif
  3279. return ast_expr_stmt(f, lhs[0]);
  3280. }
  3281. gb_internal Ast *parse_block_stmt(AstFile *f, b32 is_when) {
  3282. skip_possible_newline_for_literal(f);
  3283. if (!is_when && f->curr_proc == nullptr) {
  3284. syntax_error(f->curr_token, "You cannot use a block statement in the file scope");
  3285. return ast_bad_stmt(f, f->curr_token, f->curr_token);
  3286. }
  3287. return parse_body(f);
  3288. }
  3289. gb_internal Ast *parse_results(AstFile *f, bool *diverging) {
  3290. if (!allow_token(f, Token_ArrowRight)) {
  3291. return nullptr;
  3292. }
  3293. if (allow_token(f, Token_Not)) {
  3294. if (diverging) *diverging = true;
  3295. return nullptr;
  3296. }
  3297. isize prev_level = f->expr_level;
  3298. defer (f->expr_level = prev_level);
  3299. if (f->curr_token.kind != Token_OpenParen) {
  3300. Token begin_token = f->curr_token;
  3301. Array<Ast *> empty_names = {};
  3302. auto list = array_make<Ast *>(ast_allocator(f), 0, 1);
  3303. Ast *type = parse_type(f);
  3304. Token tag = {};
  3305. array_add(&list, ast_field(f, empty_names, type, nullptr, 0, tag, nullptr, nullptr));
  3306. return ast_field_list(f, begin_token, list);
  3307. }
  3308. Ast *list = nullptr;
  3309. expect_token(f, Token_OpenParen);
  3310. list = parse_field_list(f, nullptr, FieldFlag_Results, Token_CloseParen, true, false);
  3311. if (file_allow_newline(f)) {
  3312. skip_possible_newline(f);
  3313. }
  3314. expect_token_after(f, Token_CloseParen, "parameter list");
  3315. return list;
  3316. }
  3317. gb_internal ProcCallingConvention string_to_calling_convention(String const &s) {
  3318. if (s == "odin") return ProcCC_Odin;
  3319. if (s == "contextless") return ProcCC_Contextless;
  3320. if (s == "cdecl") return ProcCC_CDecl;
  3321. if (s == "c") return ProcCC_CDecl;
  3322. if (s == "stdcall") return ProcCC_StdCall;
  3323. if (s == "std") return ProcCC_StdCall;
  3324. if (s == "fastcall") return ProcCC_FastCall;
  3325. if (s == "fast") return ProcCC_FastCall;
  3326. if (s == "none") return ProcCC_None;
  3327. if (s == "naked") return ProcCC_Naked;
  3328. if (s == "win64") return ProcCC_Win64;
  3329. if (s == "sysv") return ProcCC_SysV;
  3330. if (s == "system") {
  3331. if (build_context.metrics.os == TargetOs_windows) {
  3332. return ProcCC_StdCall;
  3333. }
  3334. return ProcCC_CDecl;
  3335. }
  3336. return ProcCC_Invalid;
  3337. }
  3338. gb_internal Ast *parse_proc_type(AstFile *f, Token proc_token) {
  3339. Ast *params = nullptr;
  3340. Ast *results = nullptr;
  3341. bool diverging = false;
  3342. ProcCallingConvention cc = ProcCC_Invalid;
  3343. if (f->curr_token.kind == Token_String) {
  3344. Token token = expect_token(f, Token_String);
  3345. auto c = string_to_calling_convention(string_value_from_token(f, token));
  3346. if (c == ProcCC_Invalid) {
  3347. syntax_error(token, "Unknown procedure calling convention: '%.*s'", LIT(token.string));
  3348. } else {
  3349. cc = c;
  3350. }
  3351. }
  3352. if (cc == ProcCC_Invalid) {
  3353. if (f->in_foreign_block) {
  3354. cc = ProcCC_ForeignBlockDefault;
  3355. } else {
  3356. cc = default_calling_convention();
  3357. }
  3358. }
  3359. expect_token(f, Token_OpenParen);
  3360. params = parse_field_list(f, nullptr, FieldFlag_Signature, Token_CloseParen, true, true);
  3361. if (file_allow_newline(f)) {
  3362. skip_possible_newline(f);
  3363. }
  3364. expect_token_after(f, Token_CloseParen, "parameter list");
  3365. results = parse_results(f, &diverging);
  3366. u64 tags = 0;
  3367. bool is_generic = false;
  3368. for (Ast *param : params->FieldList.list) {
  3369. ast_node(field, Field, param);
  3370. if (field->type != nullptr) {
  3371. if (field->type->kind == Ast_PolyType) {
  3372. is_generic = true;
  3373. goto end;
  3374. }
  3375. for (Ast *name : field->names) {
  3376. if (name->kind == Ast_PolyType) {
  3377. is_generic = true;
  3378. goto end;
  3379. }
  3380. }
  3381. }
  3382. }
  3383. end:
  3384. return ast_proc_type(f, proc_token, params, results, tags, cc, is_generic, diverging);
  3385. }
  3386. gb_internal Ast *parse_var_type(AstFile *f, bool allow_ellipsis, bool allow_typeid_token) {
  3387. if (allow_ellipsis && f->curr_token.kind == Token_Ellipsis) {
  3388. Token tok = advance_token(f);
  3389. Ast *type = parse_type_or_ident(f);
  3390. if (type == nullptr) {
  3391. syntax_error(tok, "variadic field missing type after '..'");
  3392. type = ast_bad_expr(f, tok, f->curr_token);
  3393. }
  3394. return ast_ellipsis(f, tok, type);
  3395. }
  3396. Ast *type = nullptr;
  3397. if (allow_typeid_token &&
  3398. f->curr_token.kind == Token_typeid) {
  3399. Token token = expect_token(f, Token_typeid);
  3400. Ast *specialization = nullptr;
  3401. if (allow_token(f, Token_Quo)) {
  3402. specialization = parse_type(f);
  3403. }
  3404. type = ast_typeid_type(f, token, specialization);
  3405. } else {
  3406. type = parse_type(f);
  3407. }
  3408. return type;
  3409. }
  3410. struct ParseFieldPrefixMapping {
  3411. String name;
  3412. TokenKind token_kind;
  3413. FieldFlag flag;
  3414. };
  3415. gb_global ParseFieldPrefixMapping const parse_field_prefix_mappings[] = {
  3416. {str_lit("using"), Token_using, FieldFlag_using},
  3417. {str_lit("no_alias"), Token_Hash, FieldFlag_no_alias},
  3418. {str_lit("c_vararg"), Token_Hash, FieldFlag_c_vararg},
  3419. {str_lit("const"), Token_Hash, FieldFlag_const},
  3420. {str_lit("any_int"), Token_Hash, FieldFlag_any_int},
  3421. {str_lit("subtype"), Token_Hash, FieldFlag_subtype},
  3422. {str_lit("by_ptr"), Token_Hash, FieldFlag_by_ptr},
  3423. {str_lit("no_broadcast"), Token_Hash, FieldFlag_no_broadcast},
  3424. };
  3425. gb_internal FieldFlag is_token_field_prefix(AstFile *f) {
  3426. switch (f->curr_token.kind) {
  3427. case Token_EOF:
  3428. return FieldFlag_Invalid;
  3429. case Token_using:
  3430. return FieldFlag_using;
  3431. case Token_Hash:
  3432. advance_token(f);
  3433. switch (f->curr_token.kind) {
  3434. case Token_Ident:
  3435. for (i32 i = 0; i < gb_count_of(parse_field_prefix_mappings); i++) {
  3436. auto const &mapping = parse_field_prefix_mappings[i];
  3437. if (mapping.token_kind == Token_Hash) {
  3438. if (f->curr_token.string == mapping.name) {
  3439. return mapping.flag;
  3440. }
  3441. }
  3442. }
  3443. break;
  3444. }
  3445. return FieldFlag_Unknown;
  3446. }
  3447. return FieldFlag_Invalid;
  3448. }
  3449. gb_internal u32 parse_field_prefixes(AstFile *f) {
  3450. i32 counts[gb_count_of(parse_field_prefix_mappings)] = {};
  3451. for (;;) {
  3452. FieldFlag flag = is_token_field_prefix(f);
  3453. if (flag & FieldFlag_Invalid) {
  3454. break;
  3455. }
  3456. if (flag & FieldFlag_Unknown) {
  3457. syntax_error(f->curr_token, "Unknown prefix kind '#%.*s'", LIT(f->curr_token.string));
  3458. advance_token(f);
  3459. continue;
  3460. }
  3461. for (i32 i = 0; i < gb_count_of(parse_field_prefix_mappings); i++) {
  3462. if (parse_field_prefix_mappings[i].flag == flag) {
  3463. counts[i] += 1;
  3464. advance_token(f);
  3465. break;
  3466. }
  3467. }
  3468. }
  3469. u32 field_flags = 0;
  3470. for (i32 i = 0; i < gb_count_of(parse_field_prefix_mappings); i++) {
  3471. if (counts[i] > 0) {
  3472. field_flags |= parse_field_prefix_mappings[i].flag;
  3473. if (counts[i] != 1) {
  3474. auto const &mapping = parse_field_prefix_mappings[i];
  3475. String name = mapping.name;
  3476. char const *prefix = "";
  3477. if (mapping.token_kind == Token_Hash) {
  3478. prefix = "#";
  3479. }
  3480. syntax_error(f->curr_token, "Multiple '%s%.*s' in this field list", prefix, LIT(name));
  3481. }
  3482. }
  3483. }
  3484. return field_flags;
  3485. }
  3486. gb_internal u32 check_field_prefixes(AstFile *f, isize name_count, u32 allowed_flags, u32 set_flags) {
  3487. for (i32 i = 0; i < gb_count_of(parse_field_prefix_mappings); i++) {
  3488. bool err = false;
  3489. auto const &m = parse_field_prefix_mappings[i];
  3490. if ((set_flags & m.flag) != 0) {
  3491. if (m.flag == FieldFlag_using && name_count > 1) {
  3492. err = true;
  3493. syntax_error(f->curr_token, "Cannot apply 'using' to more than one of the same type");
  3494. }
  3495. if ((allowed_flags & m.flag) == 0) {
  3496. err = true;
  3497. char const *prefix = "";
  3498. if (m.token_kind == Token_Hash) {
  3499. prefix = "#";
  3500. }
  3501. syntax_error(f->curr_token, "'%s%.*s' in not allowed within this field list", prefix, LIT(m.name));
  3502. }
  3503. }
  3504. if (err) {
  3505. set_flags &= ~m.flag;
  3506. }
  3507. }
  3508. return set_flags;
  3509. }
  3510. struct AstAndFlags {
  3511. Ast *node;
  3512. u32 flags;
  3513. };
  3514. gb_internal Array<Ast *> convert_to_ident_list(AstFile *f, Array<AstAndFlags> list, bool ignore_flags, bool allow_poly_names) {
  3515. auto idents = array_make<Ast *>(ast_allocator(f), 0, list.count);
  3516. // Convert to ident list
  3517. isize i = 0;
  3518. for (AstAndFlags const &item : list) {
  3519. Ast *ident = item.node;
  3520. if (!ignore_flags) {
  3521. if (i != 0) {
  3522. syntax_error(ident, "Illegal use of prefixes in parameter list");
  3523. }
  3524. }
  3525. switch (ident->kind) {
  3526. case Ast_Ident:
  3527. case Ast_BadExpr:
  3528. break;
  3529. case Ast_Implicit:
  3530. begin_error_block();
  3531. syntax_error(ident, "Expected an identifier, '%.*s' which is a keyword", LIT(ident->Implicit.string));
  3532. if (ident->Implicit.kind == Token_context) {
  3533. error_line("\tSuggestion: Would 'ctx' suffice as an alternative name?\n");
  3534. }
  3535. end_error_block();
  3536. ident = ast_ident(f, blank_token);
  3537. break;
  3538. case Ast_PolyType:
  3539. if (allow_poly_names) {
  3540. if (ident->PolyType.specialization == nullptr) {
  3541. break;
  3542. } else {
  3543. syntax_error(ident, "Expected a polymorphic identifier without any specialization");
  3544. }
  3545. } else {
  3546. syntax_error(ident, "Expected a non-polymorphic identifier");
  3547. }
  3548. /*fallthrough*/
  3549. default:
  3550. syntax_error(ident, "Expected an identifier");
  3551. ident = ast_ident(f, blank_token);
  3552. break;
  3553. }
  3554. array_add(&idents, ident);
  3555. i += 1;
  3556. }
  3557. return idents;
  3558. }
  3559. gb_internal bool allow_field_separator(AstFile *f) {
  3560. Token token = f->curr_token;
  3561. if (allow_token(f, Token_Comma)) {
  3562. return true;
  3563. }
  3564. if (token.kind == Token_Semicolon) {
  3565. bool ok = false;
  3566. if (file_allow_newline(f) && token_is_newline(token)) {
  3567. TokenKind next = peek_token(f).kind;
  3568. switch (next) {
  3569. case Token_CloseBrace:
  3570. case Token_CloseParen:
  3571. ok = true;
  3572. break;
  3573. }
  3574. }
  3575. if (!ok) {
  3576. String p = token_to_string(token);
  3577. syntax_error(token_end_of_line(f, f->prev_token), "Expected a comma, got a %.*s", LIT(p));
  3578. }
  3579. advance_token(f);
  3580. return true;
  3581. }
  3582. return false;
  3583. }
  3584. gb_internal Ast *parse_struct_field_list(AstFile *f, isize *name_count_) {
  3585. Token start_token = f->curr_token;
  3586. auto decls = array_make<Ast *>(ast_allocator(f));
  3587. isize total_name_count = 0;
  3588. Ast *params = parse_field_list(f, &total_name_count, FieldFlag_Struct, Token_CloseBrace, false, false);
  3589. if (name_count_) *name_count_ = total_name_count;
  3590. return params;
  3591. }
  3592. // Returns true if any are polymorphic names
  3593. gb_internal bool check_procedure_name_list(Array<Ast *> const &names) {
  3594. if (names.count == 0) {
  3595. return false;
  3596. }
  3597. bool first_is_polymorphic = names[0]->kind == Ast_PolyType;
  3598. bool any_polymorphic_names = first_is_polymorphic;
  3599. for (isize i = 1; i < names.count; i++) {
  3600. Ast *name = names[i];
  3601. if (first_is_polymorphic) {
  3602. if (name->kind == Ast_PolyType) {
  3603. any_polymorphic_names = true;
  3604. } else {
  3605. syntax_error(name, "Mixture of polymorphic and non-polymorphic identifiers");
  3606. return any_polymorphic_names;
  3607. }
  3608. } else {
  3609. if (name->kind == Ast_PolyType) {
  3610. any_polymorphic_names = true;
  3611. syntax_error(name, "Mixture of polymorphic and non-polymorphic identifiers");
  3612. return any_polymorphic_names;
  3613. } else {
  3614. // Okay
  3615. }
  3616. }
  3617. }
  3618. return any_polymorphic_names;
  3619. }
  3620. gb_internal Ast *parse_field_list(AstFile *f, isize *name_count_, u32 allowed_flags, TokenKind follow, bool allow_default_parameters, bool allow_typeid_token) {
  3621. bool prev_allow_newline = f->allow_newline;
  3622. defer (f->allow_newline = prev_allow_newline);
  3623. f->allow_newline = file_allow_newline(f);
  3624. Token start_token = f->curr_token;
  3625. CommentGroup *docs = f->lead_comment;
  3626. auto params = array_make<Ast *>(ast_allocator(f));
  3627. auto list = array_make<AstAndFlags>(temporary_allocator());
  3628. bool allow_poly_names = allow_typeid_token;
  3629. isize total_name_count = 0;
  3630. bool allow_ellipsis = allowed_flags&FieldFlag_ellipsis;
  3631. bool seen_ellipsis = false;
  3632. bool is_signature = (allowed_flags & FieldFlag_Signature) == FieldFlag_Signature;
  3633. while (f->curr_token.kind != follow &&
  3634. f->curr_token.kind != Token_Colon &&
  3635. f->curr_token.kind != Token_EOF) {
  3636. u32 flags = parse_field_prefixes(f);
  3637. Ast *param = parse_var_type(f, allow_ellipsis, allow_typeid_token);
  3638. if (param->kind == Ast_Ellipsis) {
  3639. if (seen_ellipsis) syntax_error(param, "Extra variadic parameter after ellipsis");
  3640. seen_ellipsis = true;
  3641. } else if (seen_ellipsis) {
  3642. syntax_error(param, "Extra parameter after ellipsis");
  3643. }
  3644. AstAndFlags naf = {param, flags};
  3645. array_add(&list, naf);
  3646. if (!allow_field_separator(f)) {
  3647. break;
  3648. }
  3649. }
  3650. if (f->curr_token.kind == Token_Colon) {
  3651. Array<Ast *> names = convert_to_ident_list(f, list, true, allow_poly_names); // Copy for semantic reasons
  3652. if (names.count == 0) {
  3653. syntax_error(f->curr_token, "Empty field declaration");
  3654. }
  3655. bool any_polymorphic_names = check_procedure_name_list(names);
  3656. u32 set_flags = 0;
  3657. if (list.count > 0) {
  3658. set_flags = list[0].flags;
  3659. }
  3660. set_flags = check_field_prefixes(f, names.count, allowed_flags, set_flags);
  3661. total_name_count += names.count;
  3662. Ast *type = nullptr;
  3663. Ast *default_value = nullptr;
  3664. Token tag = {};
  3665. expect_token_after(f, Token_Colon, "field list");
  3666. if (f->curr_token.kind != Token_Eq) {
  3667. type = parse_var_type(f, allow_ellipsis, allow_typeid_token);
  3668. Ast *tt = unparen_expr(type);
  3669. if (tt == nullptr) {
  3670. syntax_error(f->prev_token, "Invalid type expression in field list");
  3671. } else if (is_signature && !any_polymorphic_names && tt->kind == Ast_TypeidType && tt->TypeidType.specialization != nullptr) {
  3672. syntax_error(type, "Specialization of typeid is not allowed without polymorphic names");
  3673. }
  3674. }
  3675. if (allow_token(f, Token_Eq)) {
  3676. default_value = parse_expr(f, false);
  3677. if (!allow_default_parameters) {
  3678. syntax_error(f->curr_token, "Default parameters are only allowed for procedures");
  3679. default_value = nullptr;
  3680. }
  3681. }
  3682. if (default_value != nullptr && names.count > 1) {
  3683. syntax_error(f->curr_token, "Default parameters can only be applied to single values");
  3684. }
  3685. if (allowed_flags == FieldFlag_Struct && default_value != nullptr) {
  3686. syntax_error(default_value, "Default parameters are not allowed for structs");
  3687. default_value = nullptr;
  3688. }
  3689. if (type != nullptr && type->kind == Ast_Ellipsis) {
  3690. if (seen_ellipsis) syntax_error(type, "Extra variadic parameter after ellipsis");
  3691. seen_ellipsis = true;
  3692. if (names.count != 1) {
  3693. syntax_error(type, "Variadic parameters can only have one field name");
  3694. }
  3695. } else if (seen_ellipsis && default_value == nullptr) {
  3696. syntax_error(f->curr_token, "Extra parameter after ellipsis without a default value");
  3697. }
  3698. if (type != nullptr && default_value == nullptr) {
  3699. if (f->curr_token.kind == Token_String) {
  3700. tag = expect_token(f, Token_String);
  3701. if ((allowed_flags & FieldFlag_Tags) == 0) {
  3702. syntax_error(tag, "Field tags are only allowed within structures");
  3703. }
  3704. }
  3705. }
  3706. allow_field_separator(f);
  3707. Ast *param = ast_field(f, names, type, default_value, set_flags, tag, docs, f->line_comment);
  3708. array_add(&params, param);
  3709. while (f->curr_token.kind != follow &&
  3710. f->curr_token.kind != Token_EOF &&
  3711. f->curr_token.kind != Token_Semicolon) {
  3712. CommentGroup *docs = f->lead_comment;
  3713. u32 set_flags = parse_field_prefixes(f);
  3714. Token tag = {};
  3715. Array<Ast *> names = parse_ident_list(f, allow_poly_names);
  3716. if (names.count == 0) {
  3717. syntax_error(f->curr_token, "Empty field declaration");
  3718. break;
  3719. }
  3720. bool any_polymorphic_names = check_procedure_name_list(names);
  3721. set_flags = check_field_prefixes(f, names.count, allowed_flags, set_flags);
  3722. total_name_count += names.count;
  3723. Ast *type = nullptr;
  3724. Ast *default_value = nullptr;
  3725. expect_token_after(f, Token_Colon, "field list");
  3726. if (f->curr_token.kind != Token_Eq) {
  3727. type = parse_var_type(f, allow_ellipsis, allow_typeid_token);
  3728. Ast *tt = unparen_expr(type);
  3729. if (is_signature && !any_polymorphic_names &&
  3730. tt != nullptr &&
  3731. tt->kind == Ast_TypeidType && tt->TypeidType.specialization != nullptr) {
  3732. syntax_error(type, "Specialization of typeid is not allowed without polymorphic names");
  3733. }
  3734. }
  3735. if (allow_token(f, Token_Eq)) {
  3736. default_value = parse_expr(f, false);
  3737. if (!allow_default_parameters) {
  3738. syntax_error(f->curr_token, "Default parameters are only allowed for procedures");
  3739. default_value = nullptr;
  3740. }
  3741. }
  3742. if (default_value != nullptr && names.count > 1) {
  3743. syntax_error(f->curr_token, "Default parameters can only be applied to single values");
  3744. }
  3745. if (type != nullptr && type->kind == Ast_Ellipsis) {
  3746. if (seen_ellipsis) syntax_error(type, "Extra variadic parameter after ellipsis");
  3747. seen_ellipsis = true;
  3748. if (names.count != 1) {
  3749. syntax_error(type, "Variadic parameters can only have one field name");
  3750. }
  3751. } else if (seen_ellipsis && default_value == nullptr) {
  3752. syntax_error(f->curr_token, "Extra parameter after ellipsis without a default value");
  3753. }
  3754. if (type != nullptr && default_value == nullptr) {
  3755. if (f->curr_token.kind == Token_String) {
  3756. tag = expect_token(f, Token_String);
  3757. if ((allowed_flags & FieldFlag_Tags) == 0) {
  3758. syntax_error(tag, "Field tags are only allowed within structures");
  3759. }
  3760. }
  3761. }
  3762. bool ok = allow_field_separator(f);
  3763. Ast *param = ast_field(f, names, type, default_value, set_flags, tag, docs, f->line_comment);
  3764. array_add(&params, param);
  3765. if (!ok) {
  3766. break;
  3767. }
  3768. }
  3769. if (name_count_) *name_count_ = total_name_count;
  3770. return ast_field_list(f, start_token, params);
  3771. }
  3772. for (AstAndFlags const &item : list) {
  3773. Ast *type = item.node;
  3774. Token token = blank_token;
  3775. if (allowed_flags&FieldFlag_Results) {
  3776. // NOTE(bill): Make this nothing and not `_`
  3777. token.string = str_lit("");
  3778. }
  3779. auto names = array_make<Ast *>(ast_allocator(f), 1);
  3780. token.pos = ast_token(type).pos;
  3781. names[0] = ast_ident(f, token);
  3782. u32 flags = check_field_prefixes(f, list.count, allowed_flags, item.flags);
  3783. Token tag = {};
  3784. Ast *param = ast_field(f, names, item.node, nullptr, flags, tag, docs, f->line_comment);
  3785. array_add(&params, param);
  3786. }
  3787. if (name_count_) *name_count_ = total_name_count;
  3788. return ast_field_list(f, start_token, params);
  3789. }
  3790. gb_internal Ast *parse_type_or_ident(AstFile *f) {
  3791. bool prev_allow_type = f->allow_type;
  3792. isize prev_expr_level = f->expr_level;
  3793. defer ({
  3794. f->allow_type = prev_allow_type;
  3795. f->expr_level = prev_expr_level;
  3796. });
  3797. f->allow_type = true;
  3798. f->expr_level = -1;
  3799. bool lhs = true;
  3800. Ast *operand = parse_operand(f, lhs);
  3801. Ast *type = parse_atom_expr(f, operand, lhs);
  3802. return type;
  3803. }
  3804. gb_internal Ast *parse_body(AstFile *f) {
  3805. Array<Ast *> stmts = {};
  3806. Token open, close;
  3807. isize prev_expr_level = f->expr_level;
  3808. bool prev_allow_newline = f->allow_newline;
  3809. // NOTE(bill): The body may be within an expression so reset to zero
  3810. f->expr_level = 0;
  3811. // f->allow_newline = false;
  3812. open = expect_token(f, Token_OpenBrace);
  3813. stmts = parse_stmt_list(f);
  3814. close = expect_token(f, Token_CloseBrace);
  3815. f->expr_level = prev_expr_level;
  3816. f->allow_newline = prev_allow_newline;
  3817. return ast_block_stmt(f, stmts, open, close);
  3818. }
  3819. gb_internal Ast *parse_do_body(AstFile *f, Token const &token, char const *msg) {
  3820. Token open, close;
  3821. isize prev_expr_level = f->expr_level;
  3822. bool prev_allow_newline = f->allow_newline;
  3823. // NOTE(bill): The body may be within an expression so reset to zero
  3824. f->expr_level = 0;
  3825. f->allow_newline = false;
  3826. Ast *body = convert_stmt_to_body(f, parse_stmt(f));
  3827. if (build_context.disallow_do) {
  3828. syntax_error(body, "'do' has been disallowed");
  3829. } else if (token.pos.file_id != 0 && !ast_on_same_line(token, body)) {
  3830. syntax_error(body, "The body of a 'do' must be on the same line as %s", msg);
  3831. }
  3832. f->expr_level = prev_expr_level;
  3833. f->allow_newline = prev_allow_newline;
  3834. return body;
  3835. }
  3836. gb_internal bool parse_control_statement_semicolon_separator(AstFile *f) {
  3837. Token tok = peek_token(f);
  3838. if (tok.kind != Token_OpenBrace) {
  3839. return allow_token(f, Token_Semicolon);
  3840. }
  3841. if (f->curr_token.string == ";") {
  3842. return allow_token(f, Token_Semicolon);
  3843. }
  3844. return false;
  3845. }
  3846. gb_internal Ast *parse_if_stmt(AstFile *f) {
  3847. if (f->curr_proc == nullptr) {
  3848. syntax_error(f->curr_token, "You cannot use an if statement in the file scope");
  3849. return ast_bad_stmt(f, f->curr_token, f->curr_token);
  3850. }
  3851. Token token = expect_token(f, Token_if);
  3852. Ast *init = nullptr;
  3853. Ast *cond = nullptr;
  3854. Ast *body = nullptr;
  3855. Ast *else_stmt = nullptr;
  3856. isize prev_level = f->expr_level;
  3857. f->expr_level = -1;
  3858. bool prev_allow_in_expr = f->allow_in_expr;
  3859. f->allow_in_expr = true;
  3860. if (allow_token(f, Token_Semicolon)) {
  3861. cond = parse_expr(f, false);
  3862. } else {
  3863. init = parse_simple_stmt(f, StmtAllowFlag_None);
  3864. if (parse_control_statement_semicolon_separator(f)) {
  3865. cond = parse_expr(f, false);
  3866. } else {
  3867. cond = convert_stmt_to_expr(f, init, str_lit("boolean expression"));
  3868. init = nullptr;
  3869. }
  3870. }
  3871. f->expr_level = prev_level;
  3872. f->allow_in_expr = prev_allow_in_expr;
  3873. if (cond == nullptr) {
  3874. syntax_error(f->curr_token, "Expected condition for if statement");
  3875. }
  3876. if (allow_token(f, Token_do)) {
  3877. body = parse_do_body(f, cond ? ast_token(cond) : token, "the if statement");
  3878. } else {
  3879. body = parse_block_stmt(f, false);
  3880. }
  3881. skip_possible_newline_for_literal(f);
  3882. if (f->curr_token.kind == Token_else) {
  3883. Token else_token = expect_token(f, Token_else);
  3884. switch (f->curr_token.kind) {
  3885. case Token_if:
  3886. else_stmt = parse_if_stmt(f);
  3887. break;
  3888. case Token_OpenBrace:
  3889. else_stmt = parse_block_stmt(f, false);
  3890. break;
  3891. case Token_do:
  3892. expect_token(f, Token_do);
  3893. else_stmt = parse_do_body(f, else_token, "'else'");
  3894. break;
  3895. default:
  3896. syntax_error(f->curr_token, "Expected if statement block statement");
  3897. else_stmt = ast_bad_stmt(f, f->curr_token, f->tokens[f->curr_token_index+1]);
  3898. break;
  3899. }
  3900. }
  3901. return ast_if_stmt(f, token, init, cond, body, else_stmt);
  3902. }
  3903. gb_internal Ast *parse_when_stmt(AstFile *f) {
  3904. Token token = expect_token(f, Token_when);
  3905. Ast *cond = nullptr;
  3906. Ast *body = nullptr;
  3907. Ast *else_stmt = nullptr;
  3908. isize prev_level = f->expr_level;
  3909. f->expr_level = -1;
  3910. cond = parse_expr(f, false);
  3911. f->expr_level = prev_level;
  3912. if (cond == nullptr) {
  3913. syntax_error(f->curr_token, "Expected condition for when statement");
  3914. }
  3915. bool was_in_when_statement = f->in_when_statement;
  3916. f->in_when_statement = true;
  3917. if (allow_token(f, Token_do)) {
  3918. body = parse_do_body(f, cond ? ast_token(cond) : token, "then when statement");
  3919. } else {
  3920. body = parse_block_stmt(f, true);
  3921. }
  3922. skip_possible_newline_for_literal(f);
  3923. if (f->curr_token.kind == Token_else) {
  3924. Token else_token = expect_token(f, Token_else);
  3925. switch (f->curr_token.kind) {
  3926. case Token_when:
  3927. else_stmt = parse_when_stmt(f);
  3928. break;
  3929. case Token_OpenBrace:
  3930. else_stmt = parse_block_stmt(f, true);
  3931. break;
  3932. case Token_do: {
  3933. expect_token(f, Token_do);
  3934. else_stmt = parse_do_body(f, else_token, "'else'");
  3935. } break;
  3936. default:
  3937. syntax_error(f->curr_token, "Expected when statement block statement");
  3938. else_stmt = ast_bad_stmt(f, f->curr_token, f->tokens[f->curr_token_index+1]);
  3939. break;
  3940. }
  3941. }
  3942. f->in_when_statement = was_in_when_statement;
  3943. return ast_when_stmt(f, token, cond, body, else_stmt);
  3944. }
  3945. gb_internal Ast *parse_return_stmt(AstFile *f) {
  3946. Token token = expect_token(f, Token_return);
  3947. if (f->curr_proc == nullptr) {
  3948. syntax_error(f->curr_token, "You cannot use a return statement in the file scope");
  3949. return ast_bad_stmt(f, token, f->curr_token);
  3950. }
  3951. if (f->expr_level > 0) {
  3952. syntax_error(f->curr_token, "You cannot use a return statement within an expression");
  3953. return ast_bad_stmt(f, token, f->curr_token);
  3954. }
  3955. auto results = array_make<Ast *>(ast_allocator(f));
  3956. while (f->curr_token.kind != Token_Semicolon && f->curr_token.kind != Token_CloseBrace) {
  3957. Ast *arg = parse_expr(f, false);
  3958. array_add(&results, arg);
  3959. if (f->curr_token.kind != Token_Comma ||
  3960. f->curr_token.kind == Token_EOF) {
  3961. break;
  3962. }
  3963. advance_token(f);
  3964. }
  3965. expect_semicolon(f);
  3966. return ast_return_stmt(f, token, results);
  3967. }
  3968. gb_internal Ast *parse_for_stmt(AstFile *f) {
  3969. if (f->curr_proc == nullptr) {
  3970. syntax_error(f->curr_token, "You cannot use a for statement in the file scope");
  3971. return ast_bad_stmt(f, f->curr_token, f->curr_token);
  3972. }
  3973. Token token = expect_token(f, Token_for);
  3974. Ast *init = nullptr;
  3975. Ast *cond = nullptr;
  3976. Ast *post = nullptr;
  3977. Ast *body = nullptr;
  3978. bool is_range = false;
  3979. if (f->curr_token.kind != Token_OpenBrace &&
  3980. f->curr_token.kind != Token_do) {
  3981. isize prev_level = f->expr_level;
  3982. defer (f->expr_level = prev_level);
  3983. f->expr_level = -1;
  3984. if (f->curr_token.kind == Token_in) {
  3985. Token in_token = expect_token(f, Token_in);
  3986. syntax_error(in_token, "Prefer 'for _ in' over 'for in'");
  3987. Ast *rhs = nullptr;
  3988. bool prev_allow_range = f->allow_range;
  3989. f->allow_range = true;
  3990. rhs = parse_expr(f, false);
  3991. f->allow_range = prev_allow_range;
  3992. if (allow_token(f, Token_do)) {
  3993. body = parse_do_body(f, token, "the for statement");
  3994. } else {
  3995. body = parse_block_stmt(f, false);
  3996. }
  3997. return ast_range_stmt(f, token, {}, in_token, rhs, body);
  3998. }
  3999. if (f->curr_token.kind != Token_Semicolon) {
  4000. cond = parse_simple_stmt(f, StmtAllowFlag_In);
  4001. if (cond->kind == Ast_AssignStmt && cond->AssignStmt.op.kind == Token_in) {
  4002. is_range = true;
  4003. }
  4004. }
  4005. if (!is_range && parse_control_statement_semicolon_separator(f)) {
  4006. init = cond;
  4007. cond = nullptr;
  4008. if (f->curr_token.kind == Token_OpenBrace || f->curr_token.kind == Token_do) {
  4009. syntax_error(f->curr_token, "Expected ';', followed by a condition expression and post statement, got %.*s", LIT(token_strings[f->curr_token.kind]));
  4010. } else {
  4011. if (f->curr_token.kind != Token_Semicolon) {
  4012. cond = parse_simple_stmt(f, StmtAllowFlag_None);
  4013. }
  4014. if (f->curr_token.string != ";") {
  4015. syntax_error(f->curr_token, "Expected ';', got %.*s", LIT(token_to_string(f->curr_token)));
  4016. } else {
  4017. expect_token(f, Token_Semicolon);
  4018. }
  4019. if (f->curr_token.kind != Token_OpenBrace &&
  4020. f->curr_token.kind != Token_do) {
  4021. post = parse_simple_stmt(f, StmtAllowFlag_None);
  4022. }
  4023. }
  4024. }
  4025. }
  4026. if (allow_token(f, Token_do)) {
  4027. body = parse_do_body(f, token, "the for statement");
  4028. } else {
  4029. body = parse_block_stmt(f, false);
  4030. }
  4031. if (is_range) {
  4032. GB_ASSERT(cond->kind == Ast_AssignStmt);
  4033. Token in_token = cond->AssignStmt.op;
  4034. Slice<Ast *> vals = cond->AssignStmt.lhs;
  4035. Ast *rhs = nullptr;
  4036. if (cond->AssignStmt.rhs.count > 0) {
  4037. rhs = cond->AssignStmt.rhs[0];
  4038. }
  4039. return ast_range_stmt(f, token, vals, in_token, rhs, body);
  4040. }
  4041. cond = convert_stmt_to_expr(f, cond, str_lit("boolean expression"));
  4042. if (init != nullptr &&
  4043. cond == nullptr &&
  4044. post == nullptr) {
  4045. syntax_error(init, "'for init; ; {' without an explicit condition nor post statement is not allowed, please prefer something like 'for init; true; /**/{'");
  4046. }
  4047. return ast_for_stmt(f, token, init, cond, post, body);
  4048. }
  4049. gb_internal Ast *parse_case_clause(AstFile *f, bool is_type) {
  4050. Token token = f->curr_token;
  4051. Array<Ast *> list = {};
  4052. expect_token(f, Token_case);
  4053. bool prev_allow_range = f->allow_range;
  4054. bool prev_allow_in_expr = f->allow_in_expr;
  4055. f->allow_range = !is_type;
  4056. f->allow_in_expr = !is_type;
  4057. if (f->curr_token.kind != Token_Colon) {
  4058. list = parse_rhs_expr_list(f);
  4059. }
  4060. f->allow_range = prev_allow_range;
  4061. f->allow_in_expr = prev_allow_in_expr;
  4062. expect_token(f, Token_Colon);
  4063. Array<Ast *> stmts = parse_stmt_list(f);
  4064. return ast_case_clause(f, token, list, stmts);
  4065. }
  4066. gb_internal Ast *parse_switch_stmt(AstFile *f) {
  4067. if (f->curr_proc == nullptr) {
  4068. syntax_error(f->curr_token, "You cannot use a switch statement in the file scope");
  4069. return ast_bad_stmt(f, f->curr_token, f->curr_token);
  4070. }
  4071. Token token = expect_token(f, Token_switch);
  4072. Ast *init = nullptr;
  4073. Ast *tag = nullptr;
  4074. Ast *body = nullptr;
  4075. Token open, close;
  4076. bool is_type_switch = false;
  4077. auto list = array_make<Ast *>(ast_allocator(f));
  4078. if (f->curr_token.kind != Token_OpenBrace) {
  4079. isize prev_level = f->expr_level;
  4080. f->expr_level = -1;
  4081. defer (f->expr_level = prev_level);
  4082. if (f->curr_token.kind == Token_in) {
  4083. Token in_token = expect_token(f, Token_in);
  4084. syntax_error(in_token, "Prefer 'switch _ in' over 'switch in'");
  4085. auto lhs = array_make<Ast *>(ast_allocator(f), 0, 1);
  4086. auto rhs = array_make<Ast *>(ast_allocator(f), 0, 1);
  4087. Token blank_ident = token;
  4088. blank_ident.kind = Token_Ident;
  4089. blank_ident.string = str_lit("_");
  4090. Ast *blank = ast_ident(f, blank_ident);
  4091. array_add(&lhs, blank);
  4092. array_add(&rhs, parse_expr(f, true));
  4093. tag = ast_assign_stmt(f, token, lhs, rhs);
  4094. is_type_switch = true;
  4095. } else {
  4096. tag = parse_simple_stmt(f, StmtAllowFlag_In);
  4097. if (tag->kind == Ast_AssignStmt && tag->AssignStmt.op.kind == Token_in) {
  4098. is_type_switch = true;
  4099. } else if (parse_control_statement_semicolon_separator(f)) {
  4100. init = tag;
  4101. tag = nullptr;
  4102. if (f->curr_token.kind != Token_OpenBrace) {
  4103. tag = parse_simple_stmt(f, StmtAllowFlag_None);
  4104. }
  4105. }
  4106. }
  4107. }
  4108. skip_possible_newline(f);
  4109. open = expect_token(f, Token_OpenBrace);
  4110. while (f->curr_token.kind == Token_case) {
  4111. array_add(&list, parse_case_clause(f, is_type_switch));
  4112. }
  4113. close = expect_token(f, Token_CloseBrace);
  4114. body = ast_block_stmt(f, list, open, close);
  4115. if (is_type_switch) {
  4116. return ast_type_switch_stmt(f, token, tag, body);
  4117. }
  4118. tag = convert_stmt_to_expr(f, tag, str_lit("switch expression"));
  4119. return ast_switch_stmt(f, token, init, tag, body);
  4120. }
  4121. gb_internal Ast *parse_defer_stmt(AstFile *f) {
  4122. if (f->curr_proc == nullptr) {
  4123. syntax_error(f->curr_token, "You cannot use a defer statement in the file scope");
  4124. return ast_bad_stmt(f, f->curr_token, f->curr_token);
  4125. }
  4126. Token token = expect_token(f, Token_defer);
  4127. Ast *stmt = parse_stmt(f);
  4128. switch (stmt->kind) {
  4129. case Ast_EmptyStmt:
  4130. syntax_error(token, "Empty statement after defer (e.g. ';')");
  4131. break;
  4132. case Ast_DeferStmt:
  4133. syntax_error(token, "You cannot defer a defer statement");
  4134. stmt = stmt->DeferStmt.stmt;
  4135. break;
  4136. case Ast_ReturnStmt:
  4137. syntax_error(token, "You cannot defer a return statement");
  4138. break;
  4139. }
  4140. return ast_defer_stmt(f, token, stmt);
  4141. }
  4142. enum ImportDeclKind {
  4143. ImportDecl_Standard,
  4144. ImportDecl_Using,
  4145. };
  4146. gb_internal Ast *parse_import_decl(AstFile *f, ImportDeclKind kind) {
  4147. CommentGroup *docs = f->lead_comment;
  4148. Token token = expect_token(f, Token_import);
  4149. Token import_name = {};
  4150. switch (f->curr_token.kind) {
  4151. case Token_Ident:
  4152. import_name = advance_token(f);
  4153. break;
  4154. default:
  4155. import_name.pos = f->curr_token.pos;
  4156. break;
  4157. }
  4158. Token file_path = expect_token_after(f, Token_String, "import");
  4159. Ast *s = nullptr;
  4160. if (f->curr_proc != nullptr) {
  4161. syntax_error(import_name, "Cannot use 'import' within a procedure. This must be done at the file scope");
  4162. s = ast_bad_decl(f, import_name, file_path);
  4163. } else {
  4164. s = ast_import_decl(f, token, file_path, import_name, docs, f->line_comment);
  4165. array_add(&f->imports, s);
  4166. }
  4167. if (f->in_when_statement) {
  4168. syntax_error(import_name, "Cannot use 'import' within a 'when' statement. Prefer using the file suffixes (e.g. foo_windows.odin) or '//+build' tags");
  4169. }
  4170. if (kind != ImportDecl_Standard) {
  4171. syntax_error(import_name, "'using import' is not allowed, please use the import name explicitly");
  4172. }
  4173. expect_semicolon(f);
  4174. return s;
  4175. }
  4176. gb_internal Ast *parse_foreign_decl(AstFile *f) {
  4177. CommentGroup *docs = f->lead_comment;
  4178. Token token = expect_token(f, Token_foreign);
  4179. switch (f->curr_token.kind) {
  4180. case Token_Ident:
  4181. case Token_OpenBrace:
  4182. return parse_foreign_block(f, token);
  4183. case Token_import: {
  4184. Token import_token = expect_token(f, Token_import);
  4185. Token lib_name = {};
  4186. switch (f->curr_token.kind) {
  4187. case Token_Ident:
  4188. lib_name = advance_token(f);
  4189. break;
  4190. default:
  4191. lib_name.pos = token.pos;
  4192. break;
  4193. }
  4194. if (is_blank_ident(lib_name)) {
  4195. syntax_error(lib_name, "Illegal foreign import name: '_'");
  4196. }
  4197. Array<Token> filepaths = {};
  4198. if (allow_token(f, Token_OpenBrace)) {
  4199. array_init(&filepaths, ast_allocator(f));
  4200. while (f->curr_token.kind != Token_CloseBrace &&
  4201. f->curr_token.kind != Token_EOF) {
  4202. Token path = expect_token(f, Token_String);
  4203. array_add(&filepaths, path);
  4204. if (!allow_field_separator(f)) {
  4205. break;
  4206. }
  4207. }
  4208. expect_closing_brace_of_field_list(f);
  4209. } else {
  4210. filepaths = array_make<Token>(ast_allocator(f), 0, 1);
  4211. Token path = expect_token(f, Token_String);
  4212. array_add(&filepaths, path);
  4213. }
  4214. Ast *s = nullptr;
  4215. if (filepaths.count == 0) {
  4216. syntax_error(lib_name, "foreign import without any paths");
  4217. s = ast_bad_decl(f, lib_name, f->curr_token);
  4218. } else if (f->curr_proc != nullptr) {
  4219. syntax_error(lib_name, "You cannot use foreign import within a procedure. This must be done at the file scope");
  4220. s = ast_bad_decl(f, lib_name, filepaths[0]);
  4221. } else {
  4222. s = ast_foreign_import_decl(f, token, filepaths, lib_name, docs, f->line_comment);
  4223. }
  4224. expect_semicolon(f);
  4225. return s;
  4226. }
  4227. }
  4228. syntax_error(token, "Invalid foreign declaration");
  4229. return ast_bad_decl(f, token, f->curr_token);
  4230. }
  4231. gb_internal Ast *parse_attribute(AstFile *f, Token token, TokenKind open_kind, TokenKind close_kind, CommentGroup *docs) {
  4232. Array<Ast *> elems = {};
  4233. Token open = {};
  4234. Token close = {};
  4235. if (f->curr_token.kind == Token_Ident) {
  4236. elems = array_make<Ast *>(ast_allocator(f), 0, 1);
  4237. Ast *elem = parse_ident(f);
  4238. array_add(&elems, elem);
  4239. } else {
  4240. open = expect_token(f, open_kind);
  4241. f->expr_level++;
  4242. if (f->curr_token.kind != close_kind) {
  4243. elems = array_make<Ast *>(ast_allocator(f));
  4244. while (f->curr_token.kind != close_kind &&
  4245. f->curr_token.kind != Token_EOF) {
  4246. Ast *elem = nullptr;
  4247. elem = parse_ident(f);
  4248. if (f->curr_token.kind == Token_Eq) {
  4249. Token eq = expect_token(f, Token_Eq);
  4250. Ast *value = parse_value(f);
  4251. elem = ast_field_value(f, elem, value, eq);
  4252. }
  4253. array_add(&elems, elem);
  4254. if (!allow_field_separator(f)) {
  4255. break;
  4256. }
  4257. }
  4258. }
  4259. f->expr_level--;
  4260. close = expect_closing(f, close_kind, str_lit("attribute"));
  4261. }
  4262. Ast *attribute = ast_attribute(f, token, open, close, elems);
  4263. skip_possible_newline(f);
  4264. Ast *decl = parse_stmt(f);
  4265. if (decl->kind == Ast_ValueDecl) {
  4266. if (decl->ValueDecl.docs == nullptr && docs != nullptr) {
  4267. decl->ValueDecl.docs = docs;
  4268. }
  4269. array_add(&decl->ValueDecl.attributes, attribute);
  4270. } else if (decl->kind == Ast_ForeignBlockDecl) {
  4271. array_add(&decl->ForeignBlockDecl.attributes, attribute);
  4272. } else if (decl->kind == Ast_ForeignImportDecl) {
  4273. array_add(&decl->ForeignImportDecl.attributes, attribute);
  4274. } else if (decl->kind == Ast_ImportDecl) {
  4275. array_add(&decl->ImportDecl.attributes, attribute);
  4276. } else {
  4277. syntax_error(decl, "Expected a value or foreign declaration after an attribute, got %.*s", LIT(ast_strings[decl->kind]));
  4278. return ast_bad_stmt(f, token, f->curr_token);
  4279. }
  4280. return decl;
  4281. }
  4282. gb_internal Ast *parse_unrolled_for_loop(AstFile *f, Token unroll_token) {
  4283. Token for_token = expect_token(f, Token_for);
  4284. Ast *val0 = nullptr;
  4285. Ast *val1 = nullptr;
  4286. Token in_token = {};
  4287. Ast *expr = nullptr;
  4288. Ast *body = nullptr;
  4289. bool bad_stmt = false;
  4290. if (f->curr_token.kind != Token_in) {
  4291. Array<Ast *> idents = parse_ident_list(f, false);
  4292. switch (idents.count) {
  4293. case 1:
  4294. val0 = idents[0];
  4295. break;
  4296. case 2:
  4297. val0 = idents[0];
  4298. val1 = idents[1];
  4299. break;
  4300. default:
  4301. syntax_error(for_token, "Expected either 1 or 2 identifiers");
  4302. bad_stmt = true;
  4303. break;
  4304. }
  4305. }
  4306. in_token = expect_token(f, Token_in);
  4307. bool prev_allow_range = f->allow_range;
  4308. isize prev_level = f->expr_level;
  4309. f->allow_range = true;
  4310. f->expr_level = -1;
  4311. expr = parse_expr(f, false);
  4312. f->expr_level = prev_level;
  4313. f->allow_range = prev_allow_range;
  4314. if (allow_token(f, Token_do)) {
  4315. body = parse_do_body(f, for_token, "the for statement");
  4316. } else {
  4317. body = parse_block_stmt(f, false);
  4318. }
  4319. if (bad_stmt) {
  4320. return ast_bad_stmt(f, unroll_token, f->curr_token);
  4321. }
  4322. return ast_unroll_range_stmt(f, unroll_token, for_token, val0, val1, in_token, expr, body);
  4323. }
  4324. gb_internal Ast *parse_stmt(AstFile *f) {
  4325. Ast *s = nullptr;
  4326. Token token = f->curr_token;
  4327. switch (token.kind) {
  4328. // Operands
  4329. case Token_context: // Also allows for `context =`
  4330. case Token_proc:
  4331. case Token_Ident:
  4332. case Token_Integer:
  4333. case Token_Float:
  4334. case Token_Imag:
  4335. case Token_Rune:
  4336. case Token_String:
  4337. case Token_OpenParen:
  4338. case Token_Pointer:
  4339. case Token_asm: // Inline assembly
  4340. // Unary Operators
  4341. case Token_Add:
  4342. case Token_Sub:
  4343. case Token_Xor:
  4344. case Token_Not:
  4345. case Token_And:
  4346. case Token_Mul: // Used for error handling when people do C-like things
  4347. s = parse_simple_stmt(f, StmtAllowFlag_Label);
  4348. expect_semicolon(f);
  4349. return s;
  4350. case Token_foreign:
  4351. return parse_foreign_decl(f);
  4352. case Token_import:
  4353. return parse_import_decl(f, ImportDecl_Standard);
  4354. case Token_if: return parse_if_stmt(f);
  4355. case Token_when: return parse_when_stmt(f);
  4356. case Token_for: return parse_for_stmt(f);
  4357. case Token_switch: return parse_switch_stmt(f);
  4358. case Token_defer: return parse_defer_stmt(f);
  4359. case Token_return: return parse_return_stmt(f);
  4360. case Token_break:
  4361. case Token_continue:
  4362. case Token_fallthrough: {
  4363. Token token = advance_token(f);
  4364. Ast *label = nullptr;
  4365. if (token.kind != Token_fallthrough &&
  4366. f->curr_token.kind == Token_Ident) {
  4367. label = parse_ident(f);
  4368. }
  4369. s = ast_branch_stmt(f, token, label);
  4370. expect_semicolon(f);
  4371. return s;
  4372. }
  4373. case Token_using: {
  4374. CommentGroup *docs = f->lead_comment;
  4375. Token token = expect_token(f, Token_using);
  4376. if (f->curr_token.kind == Token_import) {
  4377. return parse_import_decl(f, ImportDecl_Using);
  4378. }
  4379. Ast *decl = nullptr;
  4380. Array<Ast *> list = parse_lhs_expr_list(f);
  4381. if (list.count == 0) {
  4382. syntax_error(token, "Illegal use of 'using' statement");
  4383. expect_semicolon(f);
  4384. return ast_bad_stmt(f, token, f->curr_token);
  4385. }
  4386. if (f->curr_token.kind != Token_Colon) {
  4387. expect_semicolon(f);
  4388. return ast_using_stmt(f, token, list);
  4389. }
  4390. expect_token_after(f, Token_Colon, "identifier list");
  4391. decl = parse_value_decl(f, list, docs);
  4392. if (decl != nullptr && decl->kind == Ast_ValueDecl) {
  4393. decl->ValueDecl.is_using = true;
  4394. return decl;
  4395. }
  4396. syntax_error(token, "Illegal use of 'using' statement");
  4397. return ast_bad_stmt(f, token, f->curr_token);
  4398. } break;
  4399. case Token_At: {
  4400. CommentGroup *docs = f->lead_comment;
  4401. Token token = expect_token(f, Token_At);
  4402. return parse_attribute(f, token, Token_OpenParen, Token_CloseParen, docs);
  4403. }
  4404. case Token_Hash: {
  4405. Ast *s = nullptr;
  4406. Token hash_token = expect_token(f, Token_Hash);
  4407. Token name = expect_token(f, Token_Ident);
  4408. String tag = name.string;
  4409. if (tag == "bounds_check") {
  4410. s = parse_stmt(f);
  4411. return parse_check_directive_for_statement(s, name, StateFlag_bounds_check);
  4412. } else if (tag == "no_bounds_check") {
  4413. s = parse_stmt(f);
  4414. return parse_check_directive_for_statement(s, name, StateFlag_no_bounds_check);
  4415. } else if (tag == "type_assert") {
  4416. s = parse_stmt(f);
  4417. return parse_check_directive_for_statement(s, name, StateFlag_type_assert);
  4418. } else if (tag == "no_type_assert") {
  4419. s = parse_stmt(f);
  4420. return parse_check_directive_for_statement(s, name, StateFlag_no_type_assert);
  4421. } else if (tag == "partial") {
  4422. s = parse_stmt(f);
  4423. switch (s->kind) {
  4424. case Ast_SwitchStmt:
  4425. s->SwitchStmt.partial = true;
  4426. break;
  4427. case Ast_TypeSwitchStmt:
  4428. s->TypeSwitchStmt.partial = true;
  4429. break;
  4430. case Ast_EmptyStmt:
  4431. return parse_check_directive_for_statement(s, name, 0);
  4432. default:
  4433. syntax_error(token, "#partial can only be applied to a switch statement");
  4434. break;
  4435. }
  4436. return s;
  4437. } else if (tag == "assert" || tag == "panic") {
  4438. Ast *t = ast_basic_directive(f, hash_token, name);
  4439. Ast *stmt = ast_expr_stmt(f, parse_call_expr(f, t));
  4440. expect_semicolon(f);
  4441. return stmt;
  4442. } else if (name.string == "force_inline" ||
  4443. name.string == "force_no_inline") {
  4444. Ast *expr = parse_force_inlining_operand(f, name);
  4445. Ast *stmt = ast_expr_stmt(f, expr);
  4446. expect_semicolon(f);
  4447. return stmt;
  4448. } else if (tag == "unroll") {
  4449. return parse_unrolled_for_loop(f, name);
  4450. } else if (tag == "reverse") {
  4451. Ast *for_stmt = parse_for_stmt(f);
  4452. if (for_stmt->kind == Ast_RangeStmt) {
  4453. if (for_stmt->RangeStmt.reverse) {
  4454. syntax_error(token, "#reverse already applied to a 'for in' statement");
  4455. }
  4456. for_stmt->RangeStmt.reverse = true;
  4457. } else {
  4458. syntax_error(token, "#reverse can only be applied to a 'for in' statement");
  4459. }
  4460. return for_stmt;
  4461. } else if (tag == "include") {
  4462. syntax_error(token, "#include is not a valid import declaration kind. Did you mean 'import'?");
  4463. s = ast_bad_stmt(f, token, f->curr_token);
  4464. } else {
  4465. syntax_error(token, "Unknown tag directive used: '%.*s'", LIT(tag));
  4466. s = ast_bad_stmt(f, token, f->curr_token);
  4467. }
  4468. fix_advance_to_next_stmt(f);
  4469. return s;
  4470. } break;
  4471. case Token_OpenBrace:
  4472. return parse_block_stmt(f, false);
  4473. case Token_Semicolon:
  4474. s = ast_empty_stmt(f, token);
  4475. expect_semicolon(f);
  4476. return s;
  4477. }
  4478. // Error correction statements
  4479. switch (token.kind) {
  4480. case Token_else:
  4481. expect_token(f, Token_else);
  4482. syntax_error(token, "'else' unattached to an 'if' statement");
  4483. switch (f->curr_token.kind) {
  4484. case Token_if:
  4485. return parse_if_stmt(f);
  4486. case Token_when:
  4487. return parse_when_stmt(f);
  4488. case Token_OpenBrace:
  4489. return parse_block_stmt(f, true);
  4490. case Token_do: {
  4491. expect_token(f, Token_do);
  4492. Ast *stmt = parse_do_body(f, {}, "the for statement");
  4493. if (build_context.disallow_do) {
  4494. syntax_error(stmt, "'do' has been disallowed");
  4495. }
  4496. return stmt;
  4497. } break;
  4498. default:
  4499. fix_advance_to_next_stmt(f);
  4500. return ast_bad_stmt(f, token, f->curr_token);
  4501. }
  4502. }
  4503. syntax_error(token, "Expected a statement, got '%.*s'", LIT(token_strings[token.kind]));
  4504. fix_advance_to_next_stmt(f);
  4505. return ast_bad_stmt(f, token, f->curr_token);
  4506. }
  4507. gb_internal Array<Ast *> parse_stmt_list(AstFile *f) {
  4508. auto list = array_make<Ast *>(ast_allocator(f));
  4509. while (f->curr_token.kind != Token_case &&
  4510. f->curr_token.kind != Token_CloseBrace &&
  4511. f->curr_token.kind != Token_EOF) {
  4512. Ast *stmt = parse_stmt(f);
  4513. if (stmt && stmt->kind != Ast_EmptyStmt) {
  4514. array_add(&list, stmt);
  4515. if (stmt->kind == Ast_ExprStmt &&
  4516. stmt->ExprStmt.expr != nullptr &&
  4517. stmt->ExprStmt.expr->kind == Ast_ProcLit) {
  4518. syntax_error(stmt, "Procedure literal evaluated but not used");
  4519. }
  4520. }
  4521. }
  4522. return list;
  4523. }
  4524. gb_internal ParseFileError init_ast_file(AstFile *f, String const &fullpath, TokenPos *err_pos) {
  4525. GB_ASSERT(f != nullptr);
  4526. f->fullpath = string_trim_whitespace(fullpath); // Just in case
  4527. f->filename = remove_directory_from_path(f->fullpath);
  4528. f->directory = directory_from_path(f->fullpath);
  4529. set_file_path_string(f->id, f->fullpath);
  4530. thread_safe_set_ast_file_from_id(f->id, f);
  4531. if (!string_ends_with(f->fullpath, str_lit(".odin"))) {
  4532. return ParseFile_WrongExtension;
  4533. }
  4534. zero_item(&f->tokenizer);
  4535. f->tokenizer.curr_file_id = f->id;
  4536. TokenizerInitError err = init_tokenizer_from_fullpath(&f->tokenizer, f->fullpath, build_context.copy_file_contents);
  4537. if (err != TokenizerInit_None) {
  4538. switch (err) {
  4539. case TokenizerInit_Empty:
  4540. break;
  4541. case TokenizerInit_NotExists:
  4542. return ParseFile_NotFound;
  4543. case TokenizerInit_Permission:
  4544. return ParseFile_Permission;
  4545. case TokenizerInit_FileTooLarge:
  4546. return ParseFile_FileTooLarge;
  4547. default:
  4548. return ParseFile_InvalidFile;
  4549. }
  4550. }
  4551. isize file_size = f->tokenizer.end - f->tokenizer.start;
  4552. // NOTE(bill): Determine allocation size required for tokens
  4553. isize token_cap = file_size/3ll;
  4554. isize pow2_cap = gb_max(cast(isize)prev_pow2(cast(i64)token_cap)/2, 16);
  4555. token_cap = ((token_cap + pow2_cap-1)/pow2_cap) * pow2_cap;
  4556. isize init_token_cap = gb_max(token_cap, 16);
  4557. array_init(&f->tokens, ast_allocator(f), 0, gb_max(init_token_cap, 16));
  4558. if (err == TokenizerInit_Empty) {
  4559. Token token = {Token_EOF};
  4560. token.pos.file_id = f->id;
  4561. token.pos.line = 1;
  4562. token.pos.column = 1;
  4563. array_add(&f->tokens, token);
  4564. return ParseFile_None;
  4565. }
  4566. u64 start = time_stamp_time_now();
  4567. for (;;) {
  4568. Token *token = array_add_and_get(&f->tokens);
  4569. tokenizer_get_token(&f->tokenizer, token);
  4570. if (token->kind == Token_Invalid) {
  4571. err_pos->line = token->pos.line;
  4572. err_pos->column = token->pos.column;
  4573. return ParseFile_InvalidToken;
  4574. }
  4575. if (token->kind == Token_EOF) {
  4576. break;
  4577. }
  4578. }
  4579. u64 end = time_stamp_time_now();
  4580. f->time_to_tokenize = cast(f64)(end-start)/cast(f64)time_stamp__freq();
  4581. f->prev_token_index = 0;
  4582. f->curr_token_index = 0;
  4583. f->prev_token = f->tokens[f->prev_token_index];
  4584. f->curr_token = f->tokens[f->curr_token_index];
  4585. array_init(&f->comments, ast_allocator(f), 0, 0);
  4586. array_init(&f->imports, ast_allocator(f), 0, 0);
  4587. f->curr_proc = nullptr;
  4588. return ParseFile_None;
  4589. }
  4590. gb_internal void destroy_ast_file(AstFile *f) {
  4591. GB_ASSERT(f != nullptr);
  4592. array_free(&f->tokens);
  4593. array_free(&f->comments);
  4594. array_free(&f->imports);
  4595. }
  4596. gb_internal bool init_parser(Parser *p) {
  4597. GB_ASSERT(p != nullptr);
  4598. string_set_init(&p->imported_files);
  4599. array_init(&p->packages, permanent_allocator());
  4600. return true;
  4601. }
  4602. gb_internal void destroy_parser(Parser *p) {
  4603. GB_ASSERT(p != nullptr);
  4604. for (AstPackage *pkg : p->packages) {
  4605. for (AstFile *file : pkg->files) {
  4606. destroy_ast_file(file);
  4607. }
  4608. array_free(&pkg->files);
  4609. array_free(&pkg->foreign_files);
  4610. }
  4611. array_free(&p->packages);
  4612. string_set_destroy(&p->imported_files);
  4613. }
  4614. gb_internal void parser_add_package(Parser *p, AstPackage *pkg) {
  4615. MUTEX_GUARD_BLOCK(&p->packages_mutex) {
  4616. pkg->id = p->packages.count+1;
  4617. array_add(&p->packages, pkg);
  4618. }
  4619. }
  4620. gb_internal ParseFileError process_imported_file(Parser *p, ImportedFile imported_file);
  4621. gb_internal WORKER_TASK_PROC(parser_worker_proc) {
  4622. ParserWorkerData *wd = cast(ParserWorkerData *)data;
  4623. ParseFileError err = process_imported_file(wd->parser, wd->imported_file);
  4624. if (err != ParseFile_None) {
  4625. auto *node = gb_alloc_item(permanent_allocator(), ParseFileErrorNode);
  4626. node->err = err;
  4627. MUTEX_GUARD_BLOCK(&wd->parser->file_error_mutex) {
  4628. if (wd->parser->file_error_tail != nullptr) {
  4629. wd->parser->file_error_tail->next = node;
  4630. }
  4631. wd->parser->file_error_tail = node;
  4632. if (wd->parser->file_error_head == nullptr) {
  4633. wd->parser->file_error_head = node;
  4634. }
  4635. }
  4636. }
  4637. return cast(isize)err;
  4638. }
  4639. gb_internal void parser_add_file_to_process(Parser *p, AstPackage *pkg, FileInfo fi, TokenPos pos) {
  4640. ImportedFile f = {pkg, fi, pos, p->file_to_process_count++};
  4641. auto wd = gb_alloc_item(permanent_allocator(), ParserWorkerData);
  4642. wd->parser = p;
  4643. wd->imported_file = f;
  4644. thread_pool_add_task(parser_worker_proc, wd);
  4645. }
  4646. gb_internal WORKER_TASK_PROC(foreign_file_worker_proc) {
  4647. ForeignFileWorkerData *wd = cast(ForeignFileWorkerData *)data;
  4648. ImportedFile *imp = &wd->imported_file;
  4649. AstPackage *pkg = imp->pkg;
  4650. AstForeignFile foreign_file = {wd->foreign_kind};
  4651. String fullpath = string_trim_whitespace(imp->fi.fullpath); // Just in case
  4652. char *c_str = alloc_cstring(temporary_allocator(), fullpath);
  4653. gbFileContents fc = gb_file_read_contents(permanent_allocator(), true, c_str);
  4654. foreign_file.source.text = (u8 *)fc.data;
  4655. foreign_file.source.len = fc.size;
  4656. switch (wd->foreign_kind) {
  4657. case AstForeignFile_S:
  4658. // TODO(bill): Actually do something with it
  4659. break;
  4660. }
  4661. MUTEX_GUARD_BLOCK(&pkg->foreign_files_mutex) {
  4662. array_add(&pkg->foreign_files, foreign_file);
  4663. }
  4664. return 0;
  4665. }
  4666. gb_internal void parser_add_foreign_file_to_process(Parser *p, AstPackage *pkg, AstForeignFileKind kind, FileInfo fi, TokenPos pos) {
  4667. // TODO(bill): Use a better allocator
  4668. ImportedFile f = {pkg, fi, pos, p->file_to_process_count++};
  4669. auto wd = gb_alloc_item(permanent_allocator(), ForeignFileWorkerData);
  4670. wd->parser = p;
  4671. wd->imported_file = f;
  4672. wd->foreign_kind = kind;
  4673. thread_pool_add_task(foreign_file_worker_proc, wd);
  4674. }
  4675. // NOTE(bill): Returns true if it's added
  4676. gb_internal AstPackage *try_add_import_path(Parser *p, String path, String const &rel_path, TokenPos pos, PackageKind kind = Package_Normal) {
  4677. String const FILE_EXT = str_lit(".odin");
  4678. MUTEX_GUARD_BLOCK(&p->imported_files_mutex) {
  4679. if (string_set_update(&p->imported_files, path)) {
  4680. return nullptr;
  4681. }
  4682. }
  4683. path = copy_string(permanent_allocator(), path);
  4684. AstPackage *pkg = gb_alloc_item(permanent_allocator(), AstPackage);
  4685. pkg->kind = kind;
  4686. pkg->fullpath = path;
  4687. array_init(&pkg->files, permanent_allocator());
  4688. pkg->foreign_files.allocator = permanent_allocator();
  4689. // NOTE(bill): Single file initial package
  4690. if (kind == Package_Init && string_ends_with(path, FILE_EXT)) {
  4691. FileInfo fi = {};
  4692. fi.name = filename_from_path(path);
  4693. fi.fullpath = path;
  4694. fi.size = get_file_size(path);
  4695. fi.is_dir = false;
  4696. array_reserve(&pkg->files, 1);
  4697. pkg->is_single_file = true;
  4698. parser_add_package(p, pkg);
  4699. parser_add_file_to_process(p, pkg, fi, pos);
  4700. return pkg;
  4701. }
  4702. Array<FileInfo> list = {};
  4703. ReadDirectoryError rd_err = read_directory(path, &list);
  4704. defer (array_free(&list));
  4705. if (list.count == 1) {
  4706. GB_ASSERT(path != list[0].fullpath);
  4707. }
  4708. switch (rd_err) {
  4709. case ReadDirectory_InvalidPath:
  4710. syntax_error(pos, "Invalid path: %.*s", LIT(rel_path));
  4711. return nullptr;
  4712. case ReadDirectory_NotExists:
  4713. syntax_error(pos, "Path does not exist: %.*s", LIT(rel_path));
  4714. return nullptr;
  4715. case ReadDirectory_Permission:
  4716. syntax_error(pos, "Unknown error whilst reading path %.*s", LIT(rel_path));
  4717. return nullptr;
  4718. case ReadDirectory_NotDir:
  4719. syntax_error(pos, "Expected a directory for a package, got a file: %.*s", LIT(rel_path));
  4720. return nullptr;
  4721. case ReadDirectory_Empty:
  4722. syntax_error(pos, "Empty directory: %.*s", LIT(rel_path));
  4723. return nullptr;
  4724. case ReadDirectory_Unknown:
  4725. syntax_error(pos, "Unknown error whilst reading path %.*s", LIT(rel_path));
  4726. return nullptr;
  4727. }
  4728. isize files_with_ext = 0;
  4729. isize files_to_reserve = 1; // always reserve 1
  4730. for (FileInfo fi : list) {
  4731. String name = fi.name;
  4732. String ext = path_extension(name);
  4733. if (ext == FILE_EXT) {
  4734. files_with_ext += 1;
  4735. }
  4736. if (ext == FILE_EXT && !is_excluded_target_filename(name)) {
  4737. files_to_reserve += 1;
  4738. }
  4739. }
  4740. if (files_with_ext == 0 || files_to_reserve == 1) {
  4741. if (files_with_ext != 0) {
  4742. syntax_error(pos, "Directory contains no .odin files for the specified platform: %.*s", LIT(rel_path));
  4743. } else {
  4744. syntax_error(pos, "Empty directory that contains no .odin files: %.*s", LIT(rel_path));
  4745. }
  4746. return nullptr;
  4747. }
  4748. array_reserve(&pkg->files, files_to_reserve);
  4749. for (FileInfo fi : list) {
  4750. String name = fi.name;
  4751. String ext = path_extension(name);
  4752. if (ext == FILE_EXT) {
  4753. if (is_excluded_target_filename(name)) {
  4754. continue;
  4755. }
  4756. parser_add_file_to_process(p, pkg, fi, pos);
  4757. } else if (ext == ".S" || ext ==".s") {
  4758. if (is_excluded_target_filename(name)) {
  4759. continue;
  4760. }
  4761. parser_add_foreign_file_to_process(p, pkg, AstForeignFile_S, fi, pos);
  4762. }
  4763. }
  4764. parser_add_package(p, pkg);
  4765. return pkg;
  4766. }
  4767. gb_global Rune illegal_import_runes[] = {
  4768. '"', '\'', '`',
  4769. '\t', '\r', '\n', '\v', '\f',
  4770. '\\', // NOTE(bill): Disallow windows style filepaths
  4771. '!', '$', '%', '^', '&', '*', '(', ')', '=',
  4772. '[', ']', '{', '}',
  4773. ';',
  4774. ':', // NOTE(bill): Disallow windows style absolute filepaths
  4775. '#',
  4776. '|', ',', '<', '>', '?',
  4777. };
  4778. gb_internal bool is_import_path_valid(String const &path) {
  4779. if (path.len > 0) {
  4780. u8 *start = path.text;
  4781. u8 *end = path.text + path.len;
  4782. u8 *curr = start;
  4783. while (curr < end) {
  4784. isize width = 1;
  4785. Rune r = *curr;
  4786. if (r >= 0x80) {
  4787. width = utf8_decode(curr, end-curr, &r);
  4788. if (r == GB_RUNE_INVALID && width == 1) {
  4789. return false;
  4790. }
  4791. else if (r == GB_RUNE_BOM && curr-start > 0) {
  4792. return false;
  4793. }
  4794. }
  4795. for (isize i = 0; i < gb_count_of(illegal_import_runes); i++) {
  4796. if (r == illegal_import_runes[i]) {
  4797. return false;
  4798. }
  4799. }
  4800. curr += width;
  4801. }
  4802. return true;
  4803. }
  4804. return false;
  4805. }
  4806. gb_internal bool is_build_flag_path_valid(String const &path) {
  4807. if (path.len > 0) {
  4808. u8 *start = path.text;
  4809. u8 *end = path.text + path.len;
  4810. u8 *curr = start;
  4811. isize index = 0;
  4812. while (curr < end) {
  4813. isize width = 1;
  4814. Rune r = *curr;
  4815. if (r >= 0x80) {
  4816. width = utf8_decode(curr, end-curr, &r);
  4817. if (r == GB_RUNE_INVALID && width == 1) {
  4818. return false;
  4819. }
  4820. else if (r == GB_RUNE_BOM && curr-start > 0) {
  4821. return false;
  4822. }
  4823. }
  4824. for (isize i = 0; i < gb_count_of(illegal_import_runes); i++) {
  4825. #if defined(GB_SYSTEM_WINDOWS)
  4826. if (r == '\\') {
  4827. break;
  4828. } else if (r == ':') {
  4829. break;
  4830. }
  4831. #endif
  4832. if (r == illegal_import_runes[i]) {
  4833. return false;
  4834. }
  4835. }
  4836. curr += width;
  4837. index += 1;
  4838. }
  4839. return true;
  4840. }
  4841. return false;
  4842. }
  4843. gb_internal bool is_package_name_reserved(String const &name) {
  4844. if (name == "builtin") {
  4845. return true;
  4846. } else if (name == "intrinsics") {
  4847. return true;
  4848. }
  4849. return false;
  4850. }
  4851. gb_internal bool determine_path_from_string(BlockingMutex *file_mutex, Ast *node, String base_dir, String const &original_string, String *path) {
  4852. GB_ASSERT(path != nullptr);
  4853. // NOTE(bill): if file_mutex == nullptr, this means that the code is used within the semantics stage
  4854. String collection_name = {};
  4855. isize colon_pos = -1;
  4856. for (isize j = 0; j < original_string.len; j++) {
  4857. if (original_string[j] == ':') {
  4858. colon_pos = j;
  4859. break;
  4860. }
  4861. }
  4862. bool has_windows_drive = false;
  4863. #if defined(GB_SYSTEM_WINDOWS)
  4864. if (file_mutex == nullptr) {
  4865. if (colon_pos == 1 && original_string.len > 2) {
  4866. if (original_string[2] == '/' || original_string[2] == '\\') {
  4867. colon_pos = -1;
  4868. has_windows_drive = true;
  4869. }
  4870. }
  4871. }
  4872. #endif
  4873. String file_str = {};
  4874. if (colon_pos == 0) {
  4875. syntax_error(node, "Expected a collection name");
  4876. return false;
  4877. }
  4878. if (original_string.len > 0 && colon_pos > 0) {
  4879. collection_name = substring(original_string, 0, colon_pos);
  4880. file_str = substring(original_string, colon_pos+1, original_string.len);
  4881. } else {
  4882. file_str = original_string;
  4883. }
  4884. if (has_windows_drive) {
  4885. String sub_file_path = substring(file_str, 3, file_str.len);
  4886. if (!is_import_path_valid(sub_file_path)) {
  4887. syntax_error(node, "Invalid import path: '%.*s'", LIT(file_str));
  4888. return false;
  4889. }
  4890. } else if (!is_import_path_valid(file_str)) {
  4891. syntax_error(node, "Invalid import path: '%.*s'", LIT(file_str));
  4892. return false;
  4893. }
  4894. if (collection_name.len > 0) {
  4895. // NOTE(bill): `base:runtime` == `core:runtime`
  4896. if (collection_name == "core" && string_starts_with(file_str, str_lit("runtime"))) {
  4897. collection_name = str_lit("base");
  4898. }
  4899. if (collection_name == "system") {
  4900. if (node->kind != Ast_ForeignImportDecl) {
  4901. syntax_error(node, "The library collection 'system' is restrict for 'foreign_library'");
  4902. return false;
  4903. } else {
  4904. *path = file_str;
  4905. return true;
  4906. }
  4907. } else if (!find_library_collection_path(collection_name, &base_dir)) {
  4908. // NOTE(bill): It's a naughty name
  4909. syntax_error(node, "Unknown library collection: '%.*s'", LIT(collection_name));
  4910. return false;
  4911. }
  4912. } else {
  4913. #if !defined(GB_SYSTEM_WINDOWS)
  4914. // @NOTE(vassvik): foreign imports of shared libraries that are not in the system collection on
  4915. // linux/mac have to be local to the executable for consistency with shared libraries.
  4916. // Unix does not have a concept of "import library" for shared/dynamic libraries,
  4917. // so we need to pass the relative path to the linker, and add the current
  4918. // working directory of the exe to the library search paths.
  4919. // Static libraries can be linked directly with the full pathname
  4920. //
  4921. if (node->kind == Ast_ForeignImportDecl && string_ends_with(file_str, str_lit(".so"))) {
  4922. *path = file_str;
  4923. return true;
  4924. }
  4925. #endif
  4926. }
  4927. if (is_package_name_reserved(file_str)) {
  4928. *path = file_str;
  4929. if (collection_name == "core" || collection_name == "base") {
  4930. return true;
  4931. } else {
  4932. syntax_error(node, "The package '%.*s' must be imported with the 'base' library collection: 'base:%.*s'", LIT(file_str), LIT(file_str));
  4933. return false;
  4934. }
  4935. }
  4936. if (file_mutex) mutex_lock(file_mutex);
  4937. defer (if (file_mutex) mutex_unlock(file_mutex));
  4938. if (node->kind == Ast_ForeignImportDecl) {
  4939. node->ForeignImportDecl.collection_name = collection_name;
  4940. }
  4941. if (has_windows_drive) {
  4942. *path = file_str;
  4943. } else {
  4944. bool ok = false;
  4945. String fullpath = string_trim_whitespace(get_fullpath_relative(permanent_allocator(), base_dir, file_str, &ok));
  4946. *path = fullpath;
  4947. }
  4948. return true;
  4949. }
  4950. gb_internal void parse_setup_file_decls(Parser *p, AstFile *f, String const &base_dir, Slice<Ast *> &decls);
  4951. gb_internal void parse_setup_file_when_stmt(Parser *p, AstFile *f, String const &base_dir, AstWhenStmt *ws) {
  4952. if (ws->body != nullptr) {
  4953. auto stmts = ws->body->BlockStmt.stmts;
  4954. parse_setup_file_decls(p, f, base_dir, stmts);
  4955. }
  4956. if (ws->else_stmt != nullptr) {
  4957. switch (ws->else_stmt->kind) {
  4958. case Ast_BlockStmt: {
  4959. auto stmts = ws->else_stmt->BlockStmt.stmts;
  4960. parse_setup_file_decls(p, f, base_dir, stmts);
  4961. } break;
  4962. case Ast_WhenStmt:
  4963. parse_setup_file_when_stmt(p, f, base_dir, &ws->else_stmt->WhenStmt);
  4964. break;
  4965. }
  4966. }
  4967. }
  4968. gb_internal void parse_setup_file_decls(Parser *p, AstFile *f, String const &base_dir, Slice<Ast *> &decls) {
  4969. for_array(i, decls) {
  4970. Ast *node = decls[i];
  4971. if (!is_ast_decl(node) &&
  4972. node->kind != Ast_WhenStmt &&
  4973. node->kind != Ast_BadStmt &&
  4974. node->kind != Ast_EmptyStmt) {
  4975. // NOTE(bill): Sanity check
  4976. if (node->kind == Ast_ExprStmt) {
  4977. Ast *expr = node->ExprStmt.expr;
  4978. if (expr->kind == Ast_CallExpr &&
  4979. expr->CallExpr.proc->kind == Ast_BasicDirective) {
  4980. f->directive_count += 1;
  4981. continue;
  4982. }
  4983. }
  4984. syntax_error(node, "Only declarations are allowed at file scope, got %.*s", LIT(ast_strings[node->kind]));
  4985. } else if (node->kind == Ast_ImportDecl) {
  4986. ast_node(id, ImportDecl, node);
  4987. String original_string = string_trim_whitespace(string_value_from_token(f, id->relpath));
  4988. String import_path = {};
  4989. bool ok = determine_path_from_string(&p->file_decl_mutex, node, base_dir, original_string, &import_path);
  4990. if (!ok) {
  4991. decls[i] = ast_bad_decl(f, id->relpath, id->relpath);
  4992. continue;
  4993. }
  4994. import_path = string_trim_whitespace(import_path);
  4995. id->fullpath = import_path;
  4996. if (is_package_name_reserved(import_path)) {
  4997. continue;
  4998. }
  4999. try_add_import_path(p, import_path, original_string, ast_token(node).pos);
  5000. } else if (node->kind == Ast_ForeignImportDecl) {
  5001. ast_node(fl, ForeignImportDecl, node);
  5002. auto fullpaths = array_make<String>(permanent_allocator(), 0, fl->filepaths.count);
  5003. for (Token const &fp : fl->filepaths) {
  5004. String file_str = string_trim_whitespace(string_value_from_token(f, fp));
  5005. String fullpath = file_str;
  5006. if (allow_check_foreign_filepath()) {
  5007. String foreign_path = {};
  5008. bool ok = determine_path_from_string(&p->file_decl_mutex, node, base_dir, file_str, &foreign_path);
  5009. if (!ok) {
  5010. decls[i] = ast_bad_decl(f, fp, fl->filepaths[fl->filepaths.count-1]);
  5011. goto end;
  5012. }
  5013. fullpath = foreign_path;
  5014. }
  5015. array_add(&fullpaths, fullpath);
  5016. }
  5017. if (fullpaths.count == 0) {
  5018. syntax_error(decls[i], "No foreign paths found");
  5019. decls[i] = ast_bad_decl(f, fl->filepaths[0], fl->filepaths[fl->filepaths.count-1]);
  5020. goto end;
  5021. }
  5022. fl->fullpaths = slice_from_array(fullpaths);
  5023. } else if (node->kind == Ast_WhenStmt) {
  5024. ast_node(ws, WhenStmt, node);
  5025. parse_setup_file_when_stmt(p, f, base_dir, ws);
  5026. }
  5027. end:;
  5028. }
  5029. }
  5030. gb_internal String build_tag_get_token(String s, String *out) {
  5031. s = string_trim_whitespace(s);
  5032. isize n = 0;
  5033. while (n < s.len) {
  5034. Rune rune = 0;
  5035. isize width = utf8_decode(&s[n], s.len-n, &rune);
  5036. if (n == 0 && rune == '!') {
  5037. } else if (!rune_is_letter(rune) && !rune_is_digit(rune)) {
  5038. isize k = gb_max(gb_max(n, width), 1);
  5039. *out = substring(s, k, s.len);
  5040. return substring(s, 0, k);
  5041. }
  5042. n += width;
  5043. }
  5044. out->len = 0;
  5045. return s;
  5046. }
  5047. gb_internal bool parse_build_tag(Token token_for_pos, String s) {
  5048. String const prefix = str_lit("+build");
  5049. GB_ASSERT(string_starts_with(s, prefix));
  5050. s = string_trim_whitespace(substring(s, prefix.len, s.len));
  5051. if (s.len == 0) {
  5052. return true;
  5053. }
  5054. bool any_correct = false;
  5055. while (s.len > 0) {
  5056. bool this_kind_correct = true;
  5057. do {
  5058. String p = string_trim_whitespace(build_tag_get_token(s, &s));
  5059. if (p.len == 0) break;
  5060. if (p == ",") break;
  5061. bool is_notted = false;
  5062. if (p[0] == '!') {
  5063. is_notted = true;
  5064. p = substring(p, 1, p.len);
  5065. if (p.len == 0) {
  5066. syntax_error(token_for_pos, "Expected a build platform after '!'");
  5067. break;
  5068. }
  5069. }
  5070. if (p.len == 0) {
  5071. continue;
  5072. }
  5073. if (p == "ignore") {
  5074. this_kind_correct = false;
  5075. continue;
  5076. }
  5077. TargetOsKind os = get_target_os_from_string(p);
  5078. TargetArchKind arch = get_target_arch_from_string(p);
  5079. if (os != TargetOs_Invalid) {
  5080. GB_ASSERT(arch == TargetArch_Invalid);
  5081. if (is_notted) {
  5082. this_kind_correct = this_kind_correct && (os != build_context.metrics.os);
  5083. } else {
  5084. this_kind_correct = this_kind_correct && (os == build_context.metrics.os);
  5085. }
  5086. } else if (arch != TargetArch_Invalid) {
  5087. if (is_notted) {
  5088. this_kind_correct = this_kind_correct && (arch != build_context.metrics.arch);
  5089. } else {
  5090. this_kind_correct = this_kind_correct && (arch == build_context.metrics.arch);
  5091. }
  5092. }
  5093. if (os == TargetOs_Invalid && arch == TargetArch_Invalid) {
  5094. syntax_error(token_for_pos, "Invalid build tag platform: %.*s", LIT(p));
  5095. break;
  5096. }
  5097. } while (s.len > 0);
  5098. any_correct = any_correct || this_kind_correct;
  5099. }
  5100. return any_correct;
  5101. }
  5102. gb_internal String vet_tag_get_token(String s, String *out) {
  5103. s = string_trim_whitespace(s);
  5104. isize n = 0;
  5105. while (n < s.len) {
  5106. Rune rune = 0;
  5107. isize width = utf8_decode(&s[n], s.len-n, &rune);
  5108. if (n == 0 && rune == '!') {
  5109. } else if (!rune_is_letter(rune) && !rune_is_digit(rune) && rune != '-') {
  5110. isize k = gb_max(gb_max(n, width), 1);
  5111. *out = substring(s, k, s.len);
  5112. return substring(s, 0, k);
  5113. }
  5114. n += width;
  5115. }
  5116. out->len = 0;
  5117. return s;
  5118. }
  5119. gb_internal u64 parse_vet_tag(Token token_for_pos, String s) {
  5120. String const prefix = str_lit("+vet");
  5121. GB_ASSERT(string_starts_with(s, prefix));
  5122. s = string_trim_whitespace(substring(s, prefix.len, s.len));
  5123. if (s.len == 0) {
  5124. return VetFlag_All;
  5125. }
  5126. u64 vet_flags = 0;
  5127. u64 vet_not_flags = 0;
  5128. while (s.len > 0) {
  5129. String p = string_trim_whitespace(vet_tag_get_token(s, &s));
  5130. if (p.len == 0) {
  5131. break;
  5132. }
  5133. bool is_notted = false;
  5134. if (p[0] == '!') {
  5135. is_notted = true;
  5136. p = substring(p, 1, p.len);
  5137. if (p.len == 0) {
  5138. syntax_error(token_for_pos, "Expected a vet flag name after '!'");
  5139. return build_context.vet_flags;
  5140. }
  5141. }
  5142. u64 flag = get_vet_flag_from_name(p);
  5143. if (flag != VetFlag_NONE) {
  5144. if (is_notted) {
  5145. vet_not_flags |= flag;
  5146. } else {
  5147. vet_flags |= flag;
  5148. }
  5149. } else {
  5150. ERROR_BLOCK();
  5151. syntax_error(token_for_pos, "Invalid vet flag name: %.*s", LIT(p));
  5152. error_line("\tExpected one of the following\n");
  5153. error_line("\tunused\n");
  5154. error_line("\tshadowing\n");
  5155. error_line("\tusing-stmt\n");
  5156. error_line("\tusing-param\n");
  5157. error_line("\textra\n");
  5158. return build_context.vet_flags;
  5159. }
  5160. }
  5161. if (vet_flags == 0 && vet_not_flags == 0) {
  5162. return build_context.vet_flags;
  5163. }
  5164. if (vet_flags == 0 && vet_not_flags != 0) {
  5165. return build_context.vet_flags &~ vet_not_flags;
  5166. }
  5167. if (vet_flags != 0 && vet_not_flags == 0) {
  5168. return vet_flags;
  5169. }
  5170. GB_ASSERT(vet_flags != 0 && vet_not_flags != 0);
  5171. return vet_flags &~ vet_not_flags;
  5172. }
  5173. gb_internal String dir_from_path(String path) {
  5174. String base_dir = path;
  5175. for (isize i = path.len-1; i >= 0; i--) {
  5176. if (base_dir[i] == '\\' ||
  5177. base_dir[i] == '/') {
  5178. break;
  5179. }
  5180. base_dir.len--;
  5181. }
  5182. return base_dir;
  5183. }
  5184. gb_internal isize calc_decl_count(Ast *decl) {
  5185. isize count = 0;
  5186. switch (decl->kind) {
  5187. case Ast_BlockStmt:
  5188. for (Ast *stmt : decl->BlockStmt.stmts) {
  5189. count += calc_decl_count(stmt);
  5190. }
  5191. break;
  5192. case Ast_WhenStmt:
  5193. {
  5194. isize inner_count = calc_decl_count(decl->WhenStmt.body);
  5195. if (decl->WhenStmt.else_stmt) {
  5196. inner_count = gb_max(inner_count, calc_decl_count(decl->WhenStmt.else_stmt));
  5197. }
  5198. count += inner_count;
  5199. }
  5200. break;
  5201. case Ast_ValueDecl:
  5202. count = decl->ValueDecl.names.count;
  5203. break;
  5204. case Ast_ForeignBlockDecl:
  5205. count = calc_decl_count(decl->ForeignBlockDecl.body);
  5206. break;
  5207. case Ast_ImportDecl:
  5208. case Ast_ForeignImportDecl:
  5209. count = 1;
  5210. break;
  5211. }
  5212. return count;
  5213. }
  5214. gb_internal bool parse_build_project_directory_tag(Token token_for_pos, String s) {
  5215. String const prefix = str_lit("+build-project-name");
  5216. GB_ASSERT(string_starts_with(s, prefix));
  5217. s = string_trim_whitespace(substring(s, prefix.len, s.len));
  5218. if (s.len == 0) {
  5219. return true;
  5220. }
  5221. bool any_correct = false;
  5222. while (s.len > 0) {
  5223. bool this_kind_correct = true;
  5224. do {
  5225. String p = string_trim_whitespace(build_tag_get_token(s, &s));
  5226. if (p.len == 0) break;
  5227. if (p == ",") break;
  5228. bool is_notted = false;
  5229. if (p[0] == '!') {
  5230. is_notted = true;
  5231. p = substring(p, 1, p.len);
  5232. if (p.len == 0) {
  5233. syntax_error(token_for_pos, "Expected a build-project-name after '!'");
  5234. break;
  5235. }
  5236. }
  5237. if (p.len == 0) {
  5238. continue;
  5239. }
  5240. if (is_notted) {
  5241. this_kind_correct = this_kind_correct && (p != build_context.ODIN_BUILD_PROJECT_NAME);
  5242. } else {
  5243. this_kind_correct = this_kind_correct && (p == build_context.ODIN_BUILD_PROJECT_NAME);
  5244. }
  5245. } while (s.len > 0);
  5246. any_correct = any_correct || this_kind_correct;
  5247. }
  5248. return any_correct;
  5249. }
  5250. gb_internal bool parse_file(Parser *p, AstFile *f) {
  5251. if (f->tokens.count == 0) {
  5252. return true;
  5253. }
  5254. if (f->tokens.count > 0 && f->tokens[0].kind == Token_EOF) {
  5255. return true;
  5256. }
  5257. u64 start = time_stamp_time_now();
  5258. String filepath = f->tokenizer.fullpath;
  5259. String base_dir = dir_from_path(filepath);
  5260. if (f->curr_token.kind == Token_Comment) {
  5261. consume_comment_groups(f, f->prev_token);
  5262. }
  5263. CommentGroup *docs = f->lead_comment;
  5264. if (f->curr_token.kind != Token_package) {
  5265. ERROR_BLOCK();
  5266. syntax_error(f->curr_token, "Expected a package declaration at the beginning of the file");
  5267. // IMPORTANT NOTE(bill): this is technically a race condition with the suggestion, but it's ony a suggession
  5268. // so in practice is should be "fine"
  5269. if (f->pkg && f->pkg->name != "") {
  5270. error_line("\tSuggestion: Add 'package %.*s' to the top of the file\n", LIT(f->pkg->name));
  5271. }
  5272. return false;
  5273. }
  5274. f->package_token = expect_token(f, Token_package);
  5275. if (f->package_token.kind != Token_package) {
  5276. return false;
  5277. }
  5278. if (docs != nullptr) {
  5279. TokenPos end = token_pos_end(docs->list[docs->list.count-1]);
  5280. if (end.line == f->package_token.pos.line || end.line+1 == f->package_token.pos.line) {
  5281. // Okay
  5282. } else {
  5283. docs = nullptr;
  5284. }
  5285. }
  5286. Token package_name = expect_token_after(f, Token_Ident, "package");
  5287. if (package_name.kind == Token_Ident) {
  5288. if (package_name.string == "_") {
  5289. syntax_error(package_name, "Invalid package name '_'");
  5290. } else if (f->pkg->kind != Package_Runtime && package_name.string == "runtime") {
  5291. syntax_error(package_name, "Use of reserved package name '%.*s'", LIT(package_name.string));
  5292. } else if (is_package_name_reserved(package_name.string)) {
  5293. syntax_error(package_name, "Use of reserved package name '%.*s'", LIT(package_name.string));
  5294. }
  5295. }
  5296. f->package_name = package_name.string;
  5297. if (!f->pkg->is_single_file && docs != nullptr && docs->list.count > 0) {
  5298. for (Token const &tok : docs->list) {
  5299. GB_ASSERT(tok.kind == Token_Comment);
  5300. String str = tok.string;
  5301. if (string_starts_with(str, str_lit("//"))) {
  5302. String lc = string_trim_whitespace(substring(str, 2, str.len));
  5303. if (lc.len > 0 && lc[0] == '+') {
  5304. if (string_starts_with(lc, str_lit("+build-project-name"))) {
  5305. if (!parse_build_project_directory_tag(tok, lc)) {
  5306. return false;
  5307. }
  5308. } else if (string_starts_with(lc, str_lit("+build"))) {
  5309. if (!parse_build_tag(tok, lc)) {
  5310. return false;
  5311. }
  5312. } else if (string_starts_with(lc, str_lit("+vet"))) {
  5313. f->vet_flags = parse_vet_tag(tok, lc);
  5314. f->vet_flags_set = true;
  5315. } else if (string_starts_with(lc, str_lit("+ignore"))) {
  5316. return false;
  5317. } else if (string_starts_with(lc, str_lit("+private"))) {
  5318. f->flags |= AstFile_IsPrivatePkg;
  5319. String command = string_trim_starts_with(lc, str_lit("+private "));
  5320. command = string_trim_whitespace(command);
  5321. if (lc == "+private") {
  5322. f->flags |= AstFile_IsPrivatePkg;
  5323. } else if (command == "package") {
  5324. f->flags |= AstFile_IsPrivatePkg;
  5325. } else if (command == "file") {
  5326. f->flags |= AstFile_IsPrivateFile;
  5327. }
  5328. } else if (lc == "+lazy") {
  5329. if (build_context.ignore_lazy) {
  5330. // Ignore
  5331. } else if (f->flags & AstFile_IsTest) {
  5332. // Ignore
  5333. } else if (f->pkg->kind == Package_Init && build_context.command_kind == Command_doc) {
  5334. // Ignore
  5335. } else {
  5336. f->flags |= AstFile_IsLazy;
  5337. }
  5338. } else if (lc == "+no-instrumentation") {
  5339. f->flags |= AstFile_NoInstrumentation;
  5340. } else {
  5341. warning(tok, "Ignoring unknown tag '%.*s'", LIT(lc));
  5342. }
  5343. }
  5344. }
  5345. }
  5346. }
  5347. Ast *pd = ast_package_decl(f, f->package_token, package_name, docs, f->line_comment);
  5348. expect_semicolon(f);
  5349. f->pkg_decl = pd;
  5350. if (f->error_count == 0) {
  5351. auto decls = array_make<Ast *>(ast_allocator(f));
  5352. while (f->curr_token.kind != Token_EOF) {
  5353. Ast *stmt = parse_stmt(f);
  5354. if (stmt && stmt->kind != Ast_EmptyStmt) {
  5355. array_add(&decls, stmt);
  5356. if (stmt->kind == Ast_ExprStmt &&
  5357. stmt->ExprStmt.expr != nullptr &&
  5358. stmt->ExprStmt.expr->kind == Ast_ProcLit) {
  5359. syntax_error(stmt, "Procedure literal evaluated but not used");
  5360. }
  5361. f->total_file_decl_count += calc_decl_count(stmt);
  5362. if (stmt->kind == Ast_WhenStmt || stmt->kind == Ast_ExprStmt || stmt->kind == Ast_ImportDecl) {
  5363. f->delayed_decl_count += 1;
  5364. }
  5365. }
  5366. }
  5367. f->decls = slice_from_array(decls);
  5368. parse_setup_file_decls(p, f, base_dir, f->decls);
  5369. }
  5370. u64 end = time_stamp_time_now();
  5371. f->time_to_parse = cast(f64)(end-start)/cast(f64)time_stamp__freq();
  5372. for (int i = 0; i < AstDelayQueue_COUNT; i++) {
  5373. array_init(f->delayed_decls_queues+i, ast_allocator(f), 0, f->delayed_decl_count);
  5374. }
  5375. return f->error_count == 0;
  5376. }
  5377. gb_internal ParseFileError process_imported_file(Parser *p, ImportedFile imported_file) {
  5378. AstPackage *pkg = imported_file.pkg;
  5379. FileInfo fi = imported_file.fi;
  5380. TokenPos pos = imported_file.pos;
  5381. AstFile *file = gb_alloc_item(permanent_allocator(), AstFile);
  5382. file->pkg = pkg;
  5383. file->id = cast(i32)(imported_file.index+1);
  5384. TokenPos err_pos = {0};
  5385. ParseFileError err = init_ast_file(file, fi.fullpath, &err_pos);
  5386. err_pos.file_id = file->id;
  5387. file->last_error = err;
  5388. if (err != ParseFile_None) {
  5389. if (err == ParseFile_EmptyFile) {
  5390. if (fi.fullpath == p->init_fullpath) {
  5391. syntax_error(pos, "Initial file is empty - %.*s\n", LIT(p->init_fullpath));
  5392. exit_with_errors();
  5393. }
  5394. } else {
  5395. switch (err) {
  5396. case ParseFile_WrongExtension:
  5397. syntax_error(pos, "Failed to parse file: %.*s; invalid file extension: File must have the extension '.odin'", LIT(fi.name));
  5398. break;
  5399. case ParseFile_InvalidFile:
  5400. syntax_error(pos, "Failed to parse file: %.*s; invalid file or cannot be found", LIT(fi.name));
  5401. break;
  5402. case ParseFile_Permission:
  5403. syntax_error(pos, "Failed to parse file: %.*s; file permissions problem", LIT(fi.name));
  5404. break;
  5405. case ParseFile_NotFound:
  5406. syntax_error(pos, "Failed to parse file: %.*s; file cannot be found ('%.*s')", LIT(fi.name), LIT(fi.fullpath));
  5407. break;
  5408. case ParseFile_InvalidToken:
  5409. syntax_error(err_pos, "Failed to parse file: %.*s; invalid token found in file", LIT(fi.name));
  5410. break;
  5411. case ParseFile_EmptyFile:
  5412. syntax_error(pos, "Failed to parse file: %.*s; file contains no tokens", LIT(fi.name));
  5413. break;
  5414. case ParseFile_FileTooLarge:
  5415. syntax_error(pos, "Failed to parse file: %.*s; file is too large, exceeds maximum file size of 2 GiB", LIT(fi.name));
  5416. break;
  5417. }
  5418. return err;
  5419. }
  5420. }
  5421. {
  5422. String name = file->fullpath;
  5423. name = remove_directory_from_path(name);
  5424. name = remove_extension_from_path(name);
  5425. if (string_starts_with(name, str_lit("_"))) {
  5426. syntax_error(pos, "Files cannot start with '_', got '%.*s'", LIT(file->fullpath));
  5427. }
  5428. }
  5429. if (build_context.command_kind == Command_test) {
  5430. String name = file->fullpath;
  5431. name = remove_extension_from_path(name);
  5432. String test_suffix = str_lit("_test");
  5433. if (string_ends_with(name, test_suffix) && name != test_suffix) {
  5434. file->flags |= AstFile_IsTest;
  5435. }
  5436. }
  5437. if (parse_file(p, file)) {
  5438. MUTEX_GUARD_BLOCK(&pkg->files_mutex) {
  5439. array_add(&pkg->files, file);
  5440. }
  5441. mutex_lock(&pkg->name_mutex);
  5442. if (pkg->name.len == 0) {
  5443. pkg->name = file->package_name;
  5444. } else if (pkg->name != file->package_name) {
  5445. if (file->tokens.count > 0 && file->tokens[0].kind != Token_EOF) {
  5446. Token tok = file->package_token;
  5447. tok.pos.file_id = file->id;
  5448. tok.pos.line = gb_max(tok.pos.line, 1);
  5449. tok.pos.column = gb_max(tok.pos.column, 1);
  5450. syntax_error(tok, "Different package name, expected '%.*s', got '%.*s'", LIT(pkg->name), LIT(file->package_name));
  5451. }
  5452. }
  5453. mutex_unlock(&pkg->name_mutex);
  5454. p->total_line_count.fetch_add(file->tokenizer.line_count);
  5455. p->total_token_count.fetch_add(file->tokens.count);
  5456. }
  5457. return ParseFile_None;
  5458. }
  5459. gb_internal ParseFileError parse_packages(Parser *p, String init_filename) {
  5460. GB_ASSERT(init_filename.text[init_filename.len] == 0);
  5461. String init_fullpath = path_to_full_path(permanent_allocator(), init_filename);
  5462. if (!path_is_directory(init_fullpath)) {
  5463. String const ext = str_lit(".odin");
  5464. if (!string_ends_with(init_fullpath, ext)) {
  5465. error({}, "Expected either a directory or a .odin file, got '%.*s'\n", LIT(init_filename));
  5466. return ParseFile_WrongExtension;
  5467. }
  5468. } else if (init_fullpath.len != 0) {
  5469. String path = init_fullpath;
  5470. if (path[path.len-1] == '/') {
  5471. path.len -= 1;
  5472. }
  5473. if ((build_context.command_kind & Command__does_build) &&
  5474. build_context.build_mode == BuildMode_Executable) {
  5475. String short_path = filename_from_path(path);
  5476. char *cpath = alloc_cstring(temporary_allocator(), short_path);
  5477. if (gb_file_exists(cpath)) {
  5478. error({}, "Please specify the executable name with -out:<string> as a directory exists with the same name in the current working directory");
  5479. return ParseFile_DirectoryAlreadyExists;
  5480. }
  5481. }
  5482. }
  5483. { // Add these packages serially and then process them parallel
  5484. TokenPos init_pos = {};
  5485. {
  5486. bool ok = false;
  5487. String s = get_fullpath_base_collection(permanent_allocator(), str_lit("runtime"), &ok);
  5488. if (!ok) {
  5489. compiler_error("Unable to find The 'base:runtime' package. Is the ODIN_ROOT set up correctly?");
  5490. }
  5491. try_add_import_path(p, s, s, init_pos, Package_Runtime);
  5492. }
  5493. try_add_import_path(p, init_fullpath, init_fullpath, init_pos, Package_Init);
  5494. p->init_fullpath = init_fullpath;
  5495. if (build_context.command_kind == Command_test) {
  5496. bool ok = false;
  5497. String s = get_fullpath_core_collection(permanent_allocator(), str_lit("testing"), &ok);
  5498. if (!ok) {
  5499. compiler_error("Unable to find The 'core:testing' package. Is the ODIN_ROOT set up correctly?");
  5500. }
  5501. try_add_import_path(p, s, s, init_pos, Package_Normal);
  5502. }
  5503. for (String const &path : build_context.extra_packages) {
  5504. String fullpath = path_to_full_path(permanent_allocator(), path); // LEAK?
  5505. if (!path_is_directory(fullpath)) {
  5506. String const ext = str_lit(".odin");
  5507. if (!string_ends_with(fullpath, ext)) {
  5508. error({}, "Expected either a directory or a .odin file, got '%.*s'\n", LIT(fullpath));
  5509. return ParseFile_WrongExtension;
  5510. }
  5511. }
  5512. AstPackage *pkg = try_add_import_path(p, fullpath, fullpath, init_pos, Package_Normal);
  5513. if (pkg) {
  5514. pkg->is_extra = true;
  5515. }
  5516. }
  5517. }
  5518. thread_pool_wait();
  5519. for (ParseFileErrorNode *node = p->file_error_head; node != nullptr; node = node->next) {
  5520. if (node->err != ParseFile_None) {
  5521. return node->err;
  5522. }
  5523. }
  5524. for (isize i = p->packages.count-1; i >= 0; i--) {
  5525. AstPackage *pkg = p->packages[i];
  5526. for (isize j = pkg->files.count-1; j >= 0; j--) {
  5527. AstFile *file = pkg->files[j];
  5528. if (file->error_count != 0) {
  5529. if (file->last_error != ParseFile_None) {
  5530. return file->last_error;
  5531. }
  5532. return ParseFile_GeneralError;
  5533. }
  5534. }
  5535. }
  5536. return ParseFile_None;
  5537. }