parser.cpp 164 KB

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