parser.cpp 166 KB

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