parser.cpp 146 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163
  1. struct AstNode;
  2. struct Scope;
  3. struct DeclInfo;
  4. enum ParseFileError {
  5. ParseFile_None,
  6. ParseFile_WrongExtension,
  7. ParseFile_InvalidFile,
  8. ParseFile_EmptyFile,
  9. ParseFile_Permission,
  10. ParseFile_NotFound,
  11. ParseFile_InvalidToken,
  12. ParseFile_Count,
  13. };
  14. struct CommentGroup {
  15. Array<Token> list; // Token_Comment
  16. };
  17. enum ImportedFileKind {
  18. ImportedFile_Normal,
  19. ImportedFile_Shared,
  20. ImportedFile_Init,
  21. };
  22. struct ImportedFile {
  23. ImportedFileKind kind;
  24. String path;
  25. String rel_path;
  26. TokenPos pos; // import
  27. isize index;
  28. };
  29. struct AstFile {
  30. isize id;
  31. String fullpath;
  32. gbArena arena;
  33. Tokenizer tokenizer;
  34. Array<Token> tokens;
  35. isize curr_token_index;
  36. Token curr_token;
  37. Token prev_token; // previous non-comment
  38. // >= 0: In Expression
  39. // < 0: In Control Clause
  40. // NOTE(bill): Used to prevent type literals in control clauses
  41. isize expr_level;
  42. bool allow_range; // NOTE(bill): Ranges are only allowed in certain cases
  43. bool in_foreign_block;
  44. bool allow_type;
  45. isize when_level;
  46. Array<AstNode *> decls;
  47. ImportedFileKind file_kind;
  48. bool is_global_scope;
  49. Array<AstNode *> imports_and_exports; // `import` `using import` `export`
  50. AstNode * curr_proc;
  51. isize scope_level;
  52. Scope * scope; // NOTE(bill): Created in checker
  53. DeclInfo * decl_info; // NOTE(bill): Created in checker
  54. CommentGroup lead_comment; // Comment (block) before the decl
  55. CommentGroup line_comment; // Comment after the semicolon
  56. CommentGroup docs; // current docs
  57. Array<CommentGroup> comments; // All the comments!
  58. #define PARSER_MAX_FIX_COUNT 6
  59. isize fix_count;
  60. TokenPos fix_prev_pos;
  61. };
  62. struct Parser {
  63. String init_fullpath;
  64. Array<AstFile *> files;
  65. Array<ImportedFile> imports;
  66. isize total_token_count;
  67. isize total_line_count;
  68. gbMutex file_add_mutex;
  69. gbMutex file_decl_mutex;
  70. };
  71. enum ProcTag {
  72. ProcTag_bounds_check = 1<<0,
  73. ProcTag_no_bounds_check = 1<<1,
  74. ProcTag_require_results = 1<<4,
  75. ProcTag_foreign = 1<<10,
  76. ProcTag_export = 1<<11,
  77. ProcTag_link_name = 1<<12,
  78. ProcTag_inline = 1<<13,
  79. ProcTag_no_inline = 1<<14,
  80. // ProcTag_dll_import = 1<<15,
  81. // ProcTag_dll_export = 1<<16,
  82. };
  83. enum ProcCallingConvention {
  84. ProcCC_Invalid = 0,
  85. ProcCC_Odin = 1,
  86. ProcCC_Contextless = 2,
  87. ProcCC_C = 3,
  88. ProcCC_Std = 4,
  89. ProcCC_Fast = 5,
  90. };
  91. enum VarDeclFlag {
  92. VarDeclFlag_using = 1<<0,
  93. VarDeclFlag_thread_local = 1<<1,
  94. };
  95. enum StmtStateFlag {
  96. StmtStateFlag_bounds_check = 1<<0,
  97. StmtStateFlag_no_bounds_check = 1<<1,
  98. };
  99. enum FieldFlag {
  100. FieldFlag_NONE = 0,
  101. FieldFlag_ellipsis = 1<<0,
  102. FieldFlag_using = 1<<1,
  103. FieldFlag_no_alias = 1<<2,
  104. FieldFlag_c_vararg = 1<<3,
  105. FieldFlag_Signature = FieldFlag_ellipsis|FieldFlag_using|FieldFlag_no_alias|FieldFlag_c_vararg,
  106. FieldFlag_Struct = FieldFlag_using,
  107. };
  108. enum StmtAllowFlag {
  109. StmtAllowFlag_None = 0,
  110. StmtAllowFlag_In = 1<<0,
  111. StmtAllowFlag_Label = 1<<1,
  112. };
  113. Array<AstNode *> make_ast_node_array(AstFile *f, isize init_capacity = 8) {
  114. Array<AstNode *> a;
  115. array_init(&a, heap_allocator(), init_capacity);
  116. return a;
  117. }
  118. // NOTE(bill): This massive define is so it is possible to create a discriminated union (and extra debug info)
  119. // for the AstNode. I personally prefer discriminated unions over subtype polymorphism as I can preallocate
  120. // all the nodes and even memcpy in a different kind of node
  121. #define AST_NODE_KINDS \
  122. AST_NODE_KIND(Ident, "identifier", struct { \
  123. Token token; \
  124. }) \
  125. AST_NODE_KIND(Implicit, "implicit", Token) \
  126. AST_NODE_KIND(Undef, "undef", Token) \
  127. AST_NODE_KIND(BasicLit, "basic literal", Token) \
  128. AST_NODE_KIND(BasicDirective, "basic directive", struct { \
  129. Token token; \
  130. String name; \
  131. }) \
  132. AST_NODE_KIND(Ellipsis, "ellipsis", struct { \
  133. Token token; \
  134. AstNode *expr; \
  135. }) \
  136. AST_NODE_KIND(ProcLit, "procedure literal", struct { \
  137. AstNode *type; \
  138. AstNode *body; \
  139. u64 tags; \
  140. String link_name; \
  141. }) \
  142. AST_NODE_KIND(CompoundLit, "compound literal", struct { \
  143. AstNode *type; \
  144. Array<AstNode *> elems; \
  145. Token open, close; \
  146. }) \
  147. AST_NODE_KIND(Alias, "alias", struct { \
  148. Token token; \
  149. AstNode *expr; \
  150. }) \
  151. AST_NODE_KIND(_ExprBegin, "", i32) \
  152. AST_NODE_KIND(BadExpr, "bad expression", struct { Token begin, end; }) \
  153. AST_NODE_KIND(TagExpr, "tag expression", struct { Token token, name; AstNode *expr; }) \
  154. AST_NODE_KIND(RunExpr, "run expression", struct { Token token, name; AstNode *expr; }) \
  155. AST_NODE_KIND(UnaryExpr, "unary expression", struct { Token op; AstNode *expr; }) \
  156. AST_NODE_KIND(BinaryExpr, "binary expression", struct { Token op; AstNode *left, *right; } ) \
  157. AST_NODE_KIND(ParenExpr, "parentheses expression", struct { AstNode *expr; Token open, close; }) \
  158. AST_NODE_KIND(SelectorExpr, "selector expression", struct { Token token; AstNode *expr, *selector; }) \
  159. AST_NODE_KIND(IndexExpr, "index expression", struct { AstNode *expr, *index; Token open, close; }) \
  160. AST_NODE_KIND(DerefExpr, "dereference expression", struct { Token op; AstNode *expr; }) \
  161. AST_NODE_KIND(SliceExpr, "slice expression", struct { \
  162. AstNode *expr; \
  163. Token open, close; \
  164. Token interval0; \
  165. Token interval1; \
  166. bool index3; \
  167. AstNode *low, *high, *max; \
  168. }) \
  169. AST_NODE_KIND(CallExpr, "call expression", struct { \
  170. AstNode * proc; \
  171. Array<AstNode *> args; \
  172. Token open; \
  173. Token close; \
  174. Token ellipsis; \
  175. }) \
  176. AST_NODE_KIND(MacroCallExpr, "macro call expression", struct { \
  177. AstNode * macro; \
  178. Token bang; \
  179. Array<AstNode *> args; \
  180. Token open; \
  181. Token close; \
  182. }) \
  183. AST_NODE_KIND(FieldValue, "field value", struct { Token eq; AstNode *field, *value; }) \
  184. AST_NODE_KIND(TernaryExpr, "ternary expression", struct { AstNode *cond, *x, *y; }) \
  185. AST_NODE_KIND(TypeAssertion, "type assertion", struct { AstNode *expr; Token dot; AstNode *type; }) \
  186. AST_NODE_KIND(TypeCast, "type cast", struct { Token token; AstNode *type, *expr; }) \
  187. AST_NODE_KIND(_ExprEnd, "", i32) \
  188. AST_NODE_KIND(_StmtBegin, "", i32) \
  189. AST_NODE_KIND(BadStmt, "bad statement", struct { Token begin, end; }) \
  190. AST_NODE_KIND(EmptyStmt, "empty statement", struct { Token token; }) \
  191. AST_NODE_KIND(ExprStmt, "expression statement", struct { AstNode *expr; } ) \
  192. AST_NODE_KIND(TagStmt, "tag statement", struct { \
  193. Token token; \
  194. Token name; \
  195. AstNode *stmt; \
  196. }) \
  197. AST_NODE_KIND(AssignStmt, "assign statement", struct { \
  198. Token op; \
  199. Array<AstNode *> lhs, rhs; \
  200. }) \
  201. AST_NODE_KIND(IncDecStmt, "increment decrement statement", struct { \
  202. Token op; \
  203. AstNode *expr; \
  204. }) \
  205. AST_NODE_KIND(_ComplexStmtBegin, "", i32) \
  206. AST_NODE_KIND(BlockStmt, "block statement", struct { \
  207. Array<AstNode *> stmts; \
  208. Token open, close; \
  209. }) \
  210. AST_NODE_KIND(IfStmt, "if statement", struct { \
  211. Token token; \
  212. AstNode *init; \
  213. AstNode *cond; \
  214. AstNode *body; \
  215. AstNode *else_stmt; \
  216. }) \
  217. AST_NODE_KIND(WhenStmt, "when statement", struct { \
  218. Token token; \
  219. AstNode *cond; \
  220. AstNode *body; \
  221. AstNode *else_stmt; \
  222. bool is_cond_determined; \
  223. bool determined_cond; \
  224. }) \
  225. AST_NODE_KIND(ReturnStmt, "return statement", struct { \
  226. Token token; \
  227. Array<AstNode *> results; \
  228. }) \
  229. AST_NODE_KIND(ForStmt, "for statement", struct { \
  230. Token token; \
  231. AstNode *label; \
  232. AstNode *init; \
  233. AstNode *cond; \
  234. AstNode *post; \
  235. AstNode *body; \
  236. }) \
  237. AST_NODE_KIND(RangeStmt, "range statement", struct { \
  238. Token token; \
  239. AstNode *label; \
  240. AstNode *value; \
  241. AstNode *index; \
  242. Token in_token; \
  243. AstNode *expr; \
  244. AstNode *body; \
  245. }) \
  246. AST_NODE_KIND(CaseClause, "case clause", struct { \
  247. Token token; \
  248. Array<AstNode *> list; \
  249. Array<AstNode *> stmts; \
  250. }) \
  251. AST_NODE_KIND(SwitchStmt, "switch statement", struct { \
  252. Token token; \
  253. AstNode *label; \
  254. AstNode *init; \
  255. AstNode *tag; \
  256. AstNode *body; \
  257. }) \
  258. AST_NODE_KIND(TypeSwitchStmt, "type switch statement", struct { \
  259. Token token; \
  260. AstNode *label; \
  261. AstNode *tag; \
  262. AstNode *body; \
  263. }) \
  264. AST_NODE_KIND(DeferStmt, "defer statement", struct { Token token; AstNode *stmt; }) \
  265. AST_NODE_KIND(BranchStmt, "branch statement", struct { Token token; AstNode *label; }) \
  266. AST_NODE_KIND(UsingStmt, "using statement", struct { \
  267. Token token; \
  268. Array<AstNode *> list; \
  269. }) \
  270. AST_NODE_KIND(AsmOperand, "assembly operand", struct { \
  271. Token string; \
  272. AstNode *operand; \
  273. }) \
  274. AST_NODE_KIND(AsmStmt, "assembly statement", struct { \
  275. Token token; \
  276. bool is_volatile; \
  277. Token open, close; \
  278. Token code_string; \
  279. AstNode *output_list; \
  280. AstNode *input_list; \
  281. AstNode *clobber_list; \
  282. isize output_count, input_count, clobber_count; \
  283. }) \
  284. AST_NODE_KIND(PushAllocator, "push_allocator statement", struct { \
  285. Token token; \
  286. AstNode *expr; \
  287. AstNode *body; \
  288. }) \
  289. AST_NODE_KIND(PushContext, "push_context statement", struct { \
  290. Token token; \
  291. AstNode *expr; \
  292. AstNode *body; \
  293. }) \
  294. AST_NODE_KIND(_ComplexStmtEnd, "", i32) \
  295. AST_NODE_KIND(_StmtEnd, "", i32) \
  296. AST_NODE_KIND(_DeclBegin, "", i32) \
  297. AST_NODE_KIND(BadDecl, "bad declaration", struct { Token begin, end; }) \
  298. AST_NODE_KIND(ForeignBlockDecl, "foreign block declaration", struct { \
  299. Token token; \
  300. AstNode * foreign_library; \
  301. Token open, close; \
  302. Array<AstNode *> decls; \
  303. bool been_handled; \
  304. CommentGroup docs; \
  305. }) \
  306. AST_NODE_KIND(Label, "label", struct { \
  307. Token token; \
  308. AstNode *name; \
  309. }) \
  310. AST_NODE_KIND(ValueDecl, "value declaration", struct { \
  311. Array<AstNode *> names; \
  312. AstNode * type; \
  313. Array<AstNode *> values; \
  314. u64 flags; \
  315. bool is_mutable; \
  316. bool been_handled; \
  317. CommentGroup docs; \
  318. CommentGroup comment; \
  319. }) \
  320. AST_NODE_KIND(ImportDecl, "import declaration", struct { \
  321. AstFile *file; \
  322. Token token; \
  323. Token relpath; \
  324. String fullpath; \
  325. Token import_name; \
  326. bool is_using; \
  327. bool been_handled; \
  328. CommentGroup docs; \
  329. CommentGroup comment; \
  330. }) \
  331. AST_NODE_KIND(ExportDecl, "export declaration", struct { \
  332. AstFile *file; \
  333. Token token; \
  334. Token relpath; \
  335. String fullpath; \
  336. bool been_handled; \
  337. CommentGroup docs; \
  338. CommentGroup comment; \
  339. }) \
  340. AST_NODE_KIND(ForeignLibraryDecl, "foreign library declaration", struct { \
  341. Token token; \
  342. Token filepath; \
  343. Token library_name; \
  344. String base_dir; \
  345. bool been_handled; \
  346. CommentGroup docs; \
  347. CommentGroup comment; \
  348. }) \
  349. AST_NODE_KIND(_DeclEnd, "", i32) \
  350. AST_NODE_KIND(Field, "field", struct { \
  351. Array<AstNode *> names; \
  352. AstNode * type; \
  353. AstNode * default_value; \
  354. u32 flags; \
  355. CommentGroup docs; \
  356. CommentGroup comment; \
  357. }) \
  358. AST_NODE_KIND(FieldList, "field list", struct { \
  359. Token token; \
  360. Array<AstNode *> list; \
  361. }) \
  362. AST_NODE_KIND(UnionField, "union field", struct { \
  363. AstNode *name; \
  364. AstNode *list; \
  365. }) \
  366. AST_NODE_KIND(_TypeBegin, "", i32) \
  367. AST_NODE_KIND(TypeType, "type", struct { \
  368. Token token; \
  369. AstNode *specialization; \
  370. }) \
  371. AST_NODE_KIND(HelperType, "helper type", struct { \
  372. Token token; \
  373. AstNode *type; \
  374. }) \
  375. AST_NODE_KIND(PolyType, "polymorphic type", struct { \
  376. Token token; \
  377. AstNode *type; \
  378. AstNode *specialization; \
  379. }) \
  380. AST_NODE_KIND(ProcType, "procedure type", struct { \
  381. Token token; \
  382. AstNode *params; \
  383. AstNode *results; \
  384. u64 tags; \
  385. ProcCallingConvention calling_convention; \
  386. bool generic; \
  387. }) \
  388. AST_NODE_KIND(PointerType, "pointer type", struct { \
  389. Token token; \
  390. AstNode *type; \
  391. }) \
  392. AST_NODE_KIND(ArrayType, "array type", struct { \
  393. Token token; \
  394. AstNode *count; \
  395. AstNode *elem; \
  396. }) \
  397. AST_NODE_KIND(DynamicArrayType, "dynamic array type", struct { \
  398. Token token; \
  399. AstNode *elem; \
  400. }) \
  401. AST_NODE_KIND(VectorType, "vector type", struct { \
  402. Token token; \
  403. AstNode *count; \
  404. AstNode *elem; \
  405. }) \
  406. AST_NODE_KIND(StructType, "struct type", struct { \
  407. Token token; \
  408. Array<AstNode *> fields; \
  409. isize field_count; \
  410. AstNode * polymorphic_params; \
  411. bool is_packed; \
  412. bool is_ordered; \
  413. bool is_raw_union; \
  414. AstNode * align; \
  415. }) \
  416. AST_NODE_KIND(UnionType, "union type", struct { \
  417. Token token; \
  418. Array<AstNode *> variants; \
  419. AstNode * align; \
  420. }) \
  421. AST_NODE_KIND(EnumType, "enum type", struct { \
  422. Token token; \
  423. AstNode * base_type; \
  424. Array<AstNode *> fields; /* FieldValue */ \
  425. }) \
  426. AST_NODE_KIND(BitFieldType, "bit field type", struct { \
  427. Token token; \
  428. Array<AstNode *> fields; /* FieldValue with : */ \
  429. AstNode * align; \
  430. }) \
  431. AST_NODE_KIND(MapType, "map type", struct { \
  432. Token token; \
  433. AstNode *count; \
  434. AstNode *key; \
  435. AstNode *value; \
  436. }) \
  437. AST_NODE_KIND(_TypeEnd, "", i32)
  438. enum AstNodeKind {
  439. AstNode_Invalid,
  440. #define AST_NODE_KIND(_kind_name_, ...) GB_JOIN2(AstNode_, _kind_name_),
  441. AST_NODE_KINDS
  442. #undef AST_NODE_KIND
  443. AstNode_Count,
  444. };
  445. String const ast_node_strings[] = {
  446. {cast(u8 *)"invalid node", gb_size_of("invalid node")},
  447. #define AST_NODE_KIND(_kind_name_, name, ...) {cast(u8 *)name, gb_size_of(name)-1},
  448. AST_NODE_KINDS
  449. #undef AST_NODE_KIND
  450. };
  451. #define AST_NODE_KIND(_kind_name_, name, ...) typedef __VA_ARGS__ GB_JOIN2(AstNode, _kind_name_);
  452. AST_NODE_KINDS
  453. #undef AST_NODE_KIND
  454. struct AstNode {
  455. AstNodeKind kind;
  456. u32 stmt_state_flags;
  457. AstFile * file;
  458. union {
  459. #define AST_NODE_KIND(_kind_name_, name, ...) GB_JOIN2(AstNode, _kind_name_) _kind_name_;
  460. AST_NODE_KINDS
  461. #undef AST_NODE_KIND
  462. };
  463. };
  464. #define ast_node(n_, Kind_, node_) GB_JOIN2(AstNode, Kind_) *n_ = &(node_)->Kind_; GB_ASSERT((node_)->kind == GB_JOIN2(AstNode_, Kind_))
  465. #define case_ast_node(n_, Kind_, node_) case GB_JOIN2(AstNode_, Kind_): { ast_node(n_, Kind_, node_);
  466. #ifndef case_end
  467. #define case_end } break;
  468. #endif
  469. gb_inline bool is_ast_node_expr(AstNode *node) {
  470. return gb_is_between(node->kind, AstNode__ExprBegin+1, AstNode__ExprEnd-1);
  471. }
  472. gb_inline bool is_ast_node_stmt(AstNode *node) {
  473. return gb_is_between(node->kind, AstNode__StmtBegin+1, AstNode__StmtEnd-1);
  474. }
  475. gb_inline bool is_ast_node_complex_stmt(AstNode *node) {
  476. return gb_is_between(node->kind, AstNode__ComplexStmtBegin+1, AstNode__ComplexStmtEnd-1);
  477. }
  478. gb_inline bool is_ast_node_decl(AstNode *node) {
  479. return gb_is_between(node->kind, AstNode__DeclBegin+1, AstNode__DeclEnd-1);
  480. }
  481. gb_inline bool is_ast_node_type(AstNode *node) {
  482. return gb_is_between(node->kind, AstNode__TypeBegin+1, AstNode__TypeEnd-1);
  483. }
  484. gb_inline bool is_ast_node_when_stmt(AstNode *node) {
  485. return node->kind == AstNode_WhenStmt;
  486. }
  487. Token ast_node_token(AstNode *node) {
  488. switch (node->kind) {
  489. case AstNode_Ident: return node->Ident.token;
  490. case AstNode_Implicit: return node->Implicit;
  491. case AstNode_Undef: return node->Undef;
  492. case AstNode_BasicLit: return node->BasicLit;
  493. case AstNode_BasicDirective: return node->BasicDirective.token;
  494. case AstNode_ProcLit: return ast_node_token(node->ProcLit.type);
  495. case AstNode_CompoundLit:
  496. if (node->CompoundLit.type != nullptr) {
  497. return ast_node_token(node->CompoundLit.type);
  498. }
  499. return node->CompoundLit.open;
  500. case AstNode_Alias: return node->Alias.token;
  501. case AstNode_TagExpr: return node->TagExpr.token;
  502. case AstNode_RunExpr: return node->RunExpr.token;
  503. case AstNode_BadExpr: return node->BadExpr.begin;
  504. case AstNode_UnaryExpr: return node->UnaryExpr.op;
  505. case AstNode_BinaryExpr: return ast_node_token(node->BinaryExpr.left);
  506. case AstNode_ParenExpr: return node->ParenExpr.open;
  507. case AstNode_CallExpr: return ast_node_token(node->CallExpr.proc);
  508. case AstNode_MacroCallExpr: return ast_node_token(node->MacroCallExpr.macro);
  509. case AstNode_SelectorExpr:
  510. if (node->SelectorExpr.selector != nullptr) {
  511. return ast_node_token(node->SelectorExpr.selector);
  512. }
  513. return node->SelectorExpr.token;
  514. case AstNode_IndexExpr: return node->IndexExpr.open;
  515. case AstNode_SliceExpr: return node->SliceExpr.open;
  516. case AstNode_Ellipsis: return node->Ellipsis.token;
  517. case AstNode_FieldValue: return node->FieldValue.eq;
  518. case AstNode_DerefExpr: return node->DerefExpr.op;
  519. case AstNode_TernaryExpr: return ast_node_token(node->TernaryExpr.cond);
  520. case AstNode_TypeAssertion: return ast_node_token(node->TypeAssertion.expr);
  521. case AstNode_TypeCast: return node->TypeCast.token;
  522. case AstNode_BadStmt: return node->BadStmt.begin;
  523. case AstNode_EmptyStmt: return node->EmptyStmt.token;
  524. case AstNode_ExprStmt: return ast_node_token(node->ExprStmt.expr);
  525. case AstNode_TagStmt: return node->TagStmt.token;
  526. case AstNode_AssignStmt: return node->AssignStmt.op;
  527. case AstNode_IncDecStmt: return ast_node_token(node->IncDecStmt.expr);
  528. case AstNode_BlockStmt: return node->BlockStmt.open;
  529. case AstNode_IfStmt: return node->IfStmt.token;
  530. case AstNode_WhenStmt: return node->WhenStmt.token;
  531. case AstNode_ReturnStmt: return node->ReturnStmt.token;
  532. case AstNode_ForStmt: return node->ForStmt.token;
  533. case AstNode_RangeStmt: return node->RangeStmt.token;
  534. case AstNode_CaseClause: return node->CaseClause.token;
  535. case AstNode_SwitchStmt: return node->SwitchStmt.token;
  536. case AstNode_TypeSwitchStmt: return node->TypeSwitchStmt.token;
  537. case AstNode_DeferStmt: return node->DeferStmt.token;
  538. case AstNode_BranchStmt: return node->BranchStmt.token;
  539. case AstNode_UsingStmt: return node->UsingStmt.token;
  540. case AstNode_AsmStmt: return node->AsmStmt.token;
  541. case AstNode_PushAllocator: return node->PushAllocator.token;
  542. case AstNode_PushContext: return node->PushContext.token;
  543. case AstNode_BadDecl: return node->BadDecl.begin;
  544. case AstNode_Label: return node->Label.token;
  545. case AstNode_ValueDecl: return ast_node_token(node->ValueDecl.names[0]);
  546. case AstNode_ImportDecl: return node->ImportDecl.token;
  547. case AstNode_ExportDecl: return node->ExportDecl.token;
  548. case AstNode_ForeignLibraryDecl: return node->ForeignLibraryDecl.token;
  549. case AstNode_ForeignBlockDecl: return node->ForeignBlockDecl.token;
  550. case AstNode_Field:
  551. if (node->Field.names.count > 0) {
  552. return ast_node_token(node->Field.names[0]);
  553. }
  554. return ast_node_token(node->Field.type);
  555. case AstNode_FieldList:
  556. return node->FieldList.token;
  557. case AstNode_UnionField:
  558. return ast_node_token(node->UnionField.name);
  559. case AstNode_TypeType: return node->TypeType.token;
  560. case AstNode_HelperType: return node->HelperType.token;
  561. case AstNode_PolyType: return node->PolyType.token;
  562. case AstNode_ProcType: return node->ProcType.token;
  563. case AstNode_PointerType: return node->PointerType.token;
  564. case AstNode_ArrayType: return node->ArrayType.token;
  565. case AstNode_DynamicArrayType: return node->DynamicArrayType.token;
  566. case AstNode_VectorType: return node->VectorType.token;
  567. case AstNode_StructType: return node->StructType.token;
  568. case AstNode_UnionType: return node->UnionType.token;
  569. case AstNode_EnumType: return node->EnumType.token;
  570. case AstNode_BitFieldType: return node->BitFieldType.token;
  571. case AstNode_MapType: return node->MapType.token;
  572. }
  573. return empty_token;
  574. }
  575. AstNode *clone_ast_node(gbAllocator a, AstNode *node);
  576. Array<AstNode *> clone_ast_node_array(gbAllocator a, Array<AstNode *> array) {
  577. Array<AstNode *> result = {};
  578. if (array.count > 0) {
  579. array_init_count(&result, a, array.count);
  580. for_array(i, array) {
  581. result[i] = clone_ast_node(a, array[i]);
  582. }
  583. }
  584. return result;
  585. }
  586. AstNode *clone_ast_node(gbAllocator a, AstNode *node) {
  587. if (node == nullptr) {
  588. return nullptr;
  589. }
  590. AstNode *n = gb_alloc_item(a, AstNode);
  591. gb_memmove(n, node, gb_size_of(AstNode));
  592. switch (n->kind) {
  593. default: GB_PANIC("Unhandled AstNode %.*s", LIT(ast_node_strings[n->kind])); break;
  594. case AstNode_Invalid: break;
  595. case AstNode_Ident: break;
  596. case AstNode_Implicit: break;
  597. case AstNode_Undef: break;
  598. case AstNode_BasicLit: break;
  599. case AstNode_BasicDirective: break;
  600. case AstNode_PolyType:
  601. n->PolyType.type = clone_ast_node(a, n->PolyType.type);
  602. n->PolyType.specialization = clone_ast_node(a, n->PolyType.specialization);
  603. break;
  604. case AstNode_Ellipsis:
  605. n->Ellipsis.expr = clone_ast_node(a, n->Ellipsis.expr);
  606. break;
  607. case AstNode_ProcLit:
  608. n->ProcLit.type = clone_ast_node(a, n->ProcLit.type);
  609. n->ProcLit.body = clone_ast_node(a, n->ProcLit.body);
  610. break;
  611. case AstNode_CompoundLit:
  612. n->CompoundLit.type = clone_ast_node(a, n->CompoundLit.type);
  613. n->CompoundLit.elems = clone_ast_node_array(a, n->CompoundLit.elems);
  614. break;
  615. case AstNode_Alias:
  616. n->Alias.expr = clone_ast_node(a, n->Alias.expr);
  617. break;
  618. case AstNode_BadExpr: break;
  619. case AstNode_TagExpr:
  620. n->TagExpr.expr = clone_ast_node(a, n->TagExpr.expr);
  621. break;
  622. case AstNode_RunExpr:
  623. n->RunExpr.expr = clone_ast_node(a, n->RunExpr.expr);
  624. break;
  625. case AstNode_UnaryExpr:
  626. n->UnaryExpr.expr = clone_ast_node(a, n->UnaryExpr.expr);
  627. break;
  628. case AstNode_BinaryExpr:
  629. n->BinaryExpr.left = clone_ast_node(a, n->BinaryExpr.left);
  630. n->BinaryExpr.right = clone_ast_node(a, n->BinaryExpr.right);
  631. break;
  632. case AstNode_ParenExpr:
  633. n->ParenExpr.expr = clone_ast_node(a, n->ParenExpr.expr);
  634. break;
  635. case AstNode_SelectorExpr:
  636. n->SelectorExpr.expr = clone_ast_node(a, n->SelectorExpr.expr);
  637. n->SelectorExpr.selector = clone_ast_node(a, n->SelectorExpr.selector);
  638. break;
  639. case AstNode_IndexExpr:
  640. n->IndexExpr.expr = clone_ast_node(a, n->IndexExpr.expr);
  641. n->IndexExpr.index = clone_ast_node(a, n->IndexExpr.index);
  642. break;
  643. case AstNode_DerefExpr:
  644. n->DerefExpr.expr = clone_ast_node(a, n->DerefExpr.expr);
  645. break;
  646. case AstNode_SliceExpr:
  647. n->SliceExpr.expr = clone_ast_node(a, n->SliceExpr.expr);
  648. n->SliceExpr.low = clone_ast_node(a, n->SliceExpr.low);
  649. n->SliceExpr.high = clone_ast_node(a, n->SliceExpr.high);
  650. n->SliceExpr.max = clone_ast_node(a, n->SliceExpr.max);
  651. break;
  652. case AstNode_CallExpr:
  653. n->CallExpr.proc = clone_ast_node(a, n->CallExpr.proc);
  654. n->CallExpr.args = clone_ast_node_array(a, n->CallExpr.args);
  655. break;
  656. case AstNode_MacroCallExpr:
  657. n->MacroCallExpr.macro = clone_ast_node(a, n->MacroCallExpr.macro);
  658. n->MacroCallExpr.args = clone_ast_node_array(a, n->MacroCallExpr.args);
  659. break;
  660. case AstNode_FieldValue:
  661. n->FieldValue.field = clone_ast_node(a, n->FieldValue.field);
  662. n->FieldValue.value = clone_ast_node(a, n->FieldValue.value);
  663. break;
  664. case AstNode_TernaryExpr:
  665. n->TernaryExpr.cond = clone_ast_node(a, n->TernaryExpr.cond);
  666. n->TernaryExpr.x = clone_ast_node(a, n->TernaryExpr.x);
  667. n->TernaryExpr.y = clone_ast_node(a, n->TernaryExpr.y);
  668. break;
  669. case AstNode_TypeAssertion:
  670. n->TypeAssertion.expr = clone_ast_node(a, n->TypeAssertion.expr);
  671. n->TypeAssertion.type = clone_ast_node(a, n->TypeAssertion.type);
  672. break;
  673. case AstNode_TypeCast:
  674. n->TypeCast.type = clone_ast_node(a, n->TypeCast.type);
  675. n->TypeCast.expr = clone_ast_node(a, n->TypeCast.expr);
  676. break;
  677. case AstNode_BadStmt: break;
  678. case AstNode_EmptyStmt: break;
  679. case AstNode_ExprStmt:
  680. n->ExprStmt.expr = clone_ast_node(a, n->ExprStmt.expr);
  681. break;
  682. case AstNode_TagStmt:
  683. n->TagStmt.stmt = clone_ast_node(a, n->TagStmt.stmt);
  684. break;
  685. case AstNode_AssignStmt:
  686. n->AssignStmt.lhs = clone_ast_node_array(a, n->AssignStmt.lhs);
  687. n->AssignStmt.rhs = clone_ast_node_array(a, n->AssignStmt.rhs);
  688. break;
  689. case AstNode_IncDecStmt:
  690. n->IncDecStmt.expr = clone_ast_node(a, n->IncDecStmt.expr);
  691. break;
  692. case AstNode_BlockStmt:
  693. n->BlockStmt.stmts = clone_ast_node_array(a, n->BlockStmt.stmts);
  694. break;
  695. case AstNode_IfStmt:
  696. n->IfStmt.init = clone_ast_node(a, n->IfStmt.init);
  697. n->IfStmt.cond = clone_ast_node(a, n->IfStmt.cond);
  698. n->IfStmt.body = clone_ast_node(a, n->IfStmt.body);
  699. n->IfStmt.else_stmt = clone_ast_node(a, n->IfStmt.else_stmt);
  700. break;
  701. case AstNode_WhenStmt:
  702. n->WhenStmt.cond = clone_ast_node(a, n->WhenStmt.cond);
  703. n->WhenStmt.body = clone_ast_node(a, n->WhenStmt.body);
  704. n->WhenStmt.else_stmt = clone_ast_node(a, n->WhenStmt.else_stmt);
  705. break;
  706. case AstNode_ReturnStmt:
  707. n->ReturnStmt.results = clone_ast_node_array(a, n->ReturnStmt.results);
  708. break;
  709. case AstNode_ForStmt:
  710. n->ForStmt.label = clone_ast_node(a, n->ForStmt.label);
  711. n->ForStmt.init = clone_ast_node(a, n->ForStmt.init);
  712. n->ForStmt.cond = clone_ast_node(a, n->ForStmt.cond);
  713. n->ForStmt.post = clone_ast_node(a, n->ForStmt.post);
  714. n->ForStmt.body = clone_ast_node(a, n->ForStmt.body);
  715. break;
  716. case AstNode_RangeStmt:
  717. n->RangeStmt.label = clone_ast_node(a, n->RangeStmt.label);
  718. n->RangeStmt.value = clone_ast_node(a, n->RangeStmt.value);
  719. n->RangeStmt.index = clone_ast_node(a, n->RangeStmt.index);
  720. n->RangeStmt.expr = clone_ast_node(a, n->RangeStmt.expr);
  721. n->RangeStmt.body = clone_ast_node(a, n->RangeStmt.body);
  722. break;
  723. case AstNode_CaseClause:
  724. n->CaseClause.list = clone_ast_node_array(a, n->CaseClause.list);
  725. n->CaseClause.stmts = clone_ast_node_array(a, n->CaseClause.stmts);
  726. break;
  727. case AstNode_SwitchStmt:
  728. n->SwitchStmt.label = clone_ast_node(a, n->SwitchStmt.label);
  729. n->SwitchStmt.init = clone_ast_node(a, n->SwitchStmt.init);
  730. n->SwitchStmt.tag = clone_ast_node(a, n->SwitchStmt.tag);
  731. n->SwitchStmt.body = clone_ast_node(a, n->SwitchStmt.body);
  732. break;
  733. case AstNode_TypeSwitchStmt:
  734. n->TypeSwitchStmt.label = clone_ast_node(a, n->TypeSwitchStmt.label);
  735. n->TypeSwitchStmt.tag = clone_ast_node(a, n->TypeSwitchStmt.tag);
  736. n->TypeSwitchStmt.body = clone_ast_node(a, n->TypeSwitchStmt.body);
  737. break;
  738. case AstNode_DeferStmt:
  739. n->DeferStmt.stmt = clone_ast_node(a, n->DeferStmt.stmt);
  740. break;
  741. case AstNode_BranchStmt:
  742. n->BranchStmt.label = clone_ast_node(a, n->BranchStmt.label);
  743. break;
  744. case AstNode_UsingStmt:
  745. n->UsingStmt.list = clone_ast_node_array(a, n->UsingStmt.list);
  746. break;
  747. case AstNode_AsmOperand:
  748. n->AsmOperand.operand = clone_ast_node(a, n->AsmOperand.operand);
  749. break;
  750. case AstNode_AsmStmt:
  751. n->AsmStmt.output_list = clone_ast_node(a, n->AsmStmt.output_list);
  752. n->AsmStmt.input_list = clone_ast_node(a, n->AsmStmt.input_list);
  753. n->AsmStmt.clobber_list = clone_ast_node(a, n->AsmStmt.clobber_list);
  754. break;
  755. case AstNode_PushAllocator:
  756. n->PushAllocator.expr = clone_ast_node(a, n->PushAllocator.expr);
  757. n->PushAllocator.body = clone_ast_node(a, n->PushAllocator.body);
  758. break;
  759. case AstNode_PushContext:
  760. n->PushContext.expr = clone_ast_node(a, n->PushContext.expr);
  761. n->PushContext.body = clone_ast_node(a, n->PushContext.body);
  762. break;
  763. case AstNode_BadDecl: break;
  764. case AstNode_ForeignBlockDecl:
  765. n->ForeignBlockDecl.foreign_library = clone_ast_node(a, n->ForeignBlockDecl.foreign_library);
  766. n->ForeignBlockDecl.decls = clone_ast_node_array(a, n->ForeignBlockDecl.decls);
  767. break;
  768. case AstNode_Label:
  769. n->Label.name = clone_ast_node(a, n->Label.name);
  770. break;
  771. case AstNode_ValueDecl:
  772. n->ValueDecl.names = clone_ast_node_array(a, n->ValueDecl.names);
  773. n->ValueDecl.type = clone_ast_node(a, n->ValueDecl.type);
  774. n->ValueDecl.values = clone_ast_node_array(a, n->ValueDecl.values);
  775. break;
  776. case AstNode_Field:
  777. n->Field.names = clone_ast_node_array(a, n->Field.names);
  778. n->Field.type = clone_ast_node(a, n->Field.type);
  779. break;
  780. case AstNode_FieldList:
  781. n->FieldList.list = clone_ast_node_array(a, n->FieldList.list);
  782. break;
  783. case AstNode_UnionField:
  784. n->UnionField.name = clone_ast_node(a, n->UnionField.name);
  785. n->UnionField.list = clone_ast_node(a, n->UnionField.list);
  786. break;
  787. case AstNode_TypeType:
  788. n->TypeType.specialization = clone_ast_node(a, n->TypeType.specialization);
  789. break;
  790. case AstNode_HelperType:
  791. n->HelperType.type = clone_ast_node(a, n->HelperType.type);
  792. break;
  793. case AstNode_ProcType:
  794. n->ProcType.params = clone_ast_node(a, n->ProcType.params);
  795. n->ProcType.results = clone_ast_node(a, n->ProcType.results);
  796. break;
  797. case AstNode_PointerType:
  798. n->PointerType.type = clone_ast_node(a, n->PointerType.type);
  799. break;
  800. case AstNode_ArrayType:
  801. n->ArrayType.count = clone_ast_node(a, n->ArrayType.count);
  802. n->ArrayType.elem = clone_ast_node(a, n->ArrayType.elem);
  803. break;
  804. case AstNode_DynamicArrayType:
  805. n->DynamicArrayType.elem = clone_ast_node(a, n->DynamicArrayType.elem);
  806. break;
  807. case AstNode_VectorType:
  808. n->VectorType.count = clone_ast_node(a, n->VectorType.count);
  809. n->VectorType.elem = clone_ast_node(a, n->VectorType.elem);
  810. break;
  811. case AstNode_StructType:
  812. n->StructType.fields = clone_ast_node_array(a, n->StructType.fields);
  813. n->StructType.polymorphic_params = clone_ast_node(a, n->StructType.polymorphic_params);
  814. n->StructType.align = clone_ast_node(a, n->StructType.align);
  815. break;
  816. case AstNode_UnionType:
  817. n->UnionType.variants = clone_ast_node_array(a, n->UnionType.variants);
  818. break;
  819. case AstNode_EnumType:
  820. n->EnumType.base_type = clone_ast_node(a, n->EnumType.base_type);
  821. n->EnumType.fields = clone_ast_node_array(a, n->EnumType.fields);
  822. break;
  823. case AstNode_BitFieldType:
  824. n->BitFieldType.fields = clone_ast_node_array(a, n->BitFieldType.fields);
  825. n->BitFieldType.align = clone_ast_node(a, n->BitFieldType.align);
  826. case AstNode_MapType:
  827. n->MapType.count = clone_ast_node(a, n->MapType.count);
  828. n->MapType.key = clone_ast_node(a, n->MapType.key);
  829. n->MapType.value = clone_ast_node(a, n->MapType.value);
  830. break;
  831. }
  832. return n;
  833. }
  834. void error(AstNode *node, char *fmt, ...) {
  835. Token token = {};
  836. if (node != nullptr) {
  837. token = ast_node_token(node);
  838. }
  839. va_list va;
  840. va_start(va, fmt);
  841. error_va(token, fmt, va);
  842. va_end(va);
  843. }
  844. void warning(AstNode *node, char *fmt, ...) {
  845. va_list va;
  846. va_start(va, fmt);
  847. warning_va(ast_node_token(node), fmt, va);
  848. va_end(va);
  849. }
  850. void syntax_error(AstNode *node, char *fmt, ...) {
  851. va_list va;
  852. va_start(va, fmt);
  853. syntax_error_va(ast_node_token(node), fmt, va);
  854. va_end(va);
  855. }
  856. bool ast_node_expect(AstNode *node, AstNodeKind kind) {
  857. if (node->kind != kind) {
  858. error(node, "Expected %.*s, got %.*s", LIT(ast_node_strings[node->kind]));
  859. return false;
  860. }
  861. return true;
  862. }
  863. // NOTE(bill): And this below is why is I/we need a new language! Discriminated unions are a pain in C/C++
  864. AstNode *make_ast_node(AstFile *f, AstNodeKind kind) {
  865. gbArena *arena = &f->arena;
  866. if (gb_arena_size_remaining(arena, GB_DEFAULT_MEMORY_ALIGNMENT) <= gb_size_of(AstNode)) {
  867. // NOTE(bill): If a syntax error is so bad, just quit!
  868. gb_exit(1);
  869. }
  870. AstNode *node = gb_alloc_item(gb_arena_allocator(arena), AstNode);
  871. node->kind = kind;
  872. node->file = f;
  873. return node;
  874. }
  875. AstNode *ast_bad_expr(AstFile *f, Token begin, Token end) {
  876. AstNode *result = make_ast_node(f, AstNode_BadExpr);
  877. result->BadExpr.begin = begin;
  878. result->BadExpr.end = end;
  879. return result;
  880. }
  881. AstNode *ast_tag_expr(AstFile *f, Token token, Token name, AstNode *expr) {
  882. AstNode *result = make_ast_node(f, AstNode_TagExpr);
  883. result->TagExpr.token = token;
  884. result->TagExpr.name = name;
  885. result->TagExpr.expr = expr;
  886. return result;
  887. }
  888. AstNode *ast_run_expr(AstFile *f, Token token, Token name, AstNode *expr) {
  889. AstNode *result = make_ast_node(f, AstNode_RunExpr);
  890. result->RunExpr.token = token;
  891. result->RunExpr.name = name;
  892. result->RunExpr.expr = expr;
  893. return result;
  894. }
  895. AstNode *ast_tag_stmt(AstFile *f, Token token, Token name, AstNode *stmt) {
  896. AstNode *result = make_ast_node(f, AstNode_TagStmt);
  897. result->TagStmt.token = token;
  898. result->TagStmt.name = name;
  899. result->TagStmt.stmt = stmt;
  900. return result;
  901. }
  902. AstNode *ast_unary_expr(AstFile *f, Token op, AstNode *expr) {
  903. AstNode *result = make_ast_node(f, AstNode_UnaryExpr);
  904. result->UnaryExpr.op = op;
  905. result->UnaryExpr.expr = expr;
  906. return result;
  907. }
  908. AstNode *ast_binary_expr(AstFile *f, Token op, AstNode *left, AstNode *right) {
  909. AstNode *result = make_ast_node(f, AstNode_BinaryExpr);
  910. if (left == nullptr) {
  911. syntax_error(op, "No lhs expression for binary expression `%.*s`", LIT(op.string));
  912. left = ast_bad_expr(f, op, op);
  913. }
  914. if (right == nullptr) {
  915. syntax_error(op, "No rhs expression for binary expression `%.*s`", LIT(op.string));
  916. right = ast_bad_expr(f, op, op);
  917. }
  918. result->BinaryExpr.op = op;
  919. result->BinaryExpr.left = left;
  920. result->BinaryExpr.right = right;
  921. return result;
  922. }
  923. AstNode *ast_paren_expr(AstFile *f, AstNode *expr, Token open, Token close) {
  924. AstNode *result = make_ast_node(f, AstNode_ParenExpr);
  925. result->ParenExpr.expr = expr;
  926. result->ParenExpr.open = open;
  927. result->ParenExpr.close = close;
  928. return result;
  929. }
  930. AstNode *ast_call_expr(AstFile *f, AstNode *proc, Array<AstNode *> args, Token open, Token close, Token ellipsis) {
  931. AstNode *result = make_ast_node(f, AstNode_CallExpr);
  932. result->CallExpr.proc = proc;
  933. result->CallExpr.args = args;
  934. result->CallExpr.open = open;
  935. result->CallExpr.close = close;
  936. result->CallExpr.ellipsis = ellipsis;
  937. return result;
  938. }
  939. AstNode *ast_macro_call_expr(AstFile *f, AstNode *macro, Token bang, Array<AstNode *> args, Token open, Token close) {
  940. AstNode *result = make_ast_node(f, AstNode_MacroCallExpr);
  941. result->MacroCallExpr.macro = macro;
  942. result->MacroCallExpr.bang = bang;
  943. result->MacroCallExpr.args = args;
  944. result->MacroCallExpr.open = open;
  945. result->MacroCallExpr.close = close;
  946. return result;
  947. }
  948. AstNode *ast_selector_expr(AstFile *f, Token token, AstNode *expr, AstNode *selector) {
  949. AstNode *result = make_ast_node(f, AstNode_SelectorExpr);
  950. result->SelectorExpr.expr = expr;
  951. result->SelectorExpr.selector = selector;
  952. return result;
  953. }
  954. AstNode *ast_index_expr(AstFile *f, AstNode *expr, AstNode *index, Token open, Token close) {
  955. AstNode *result = make_ast_node(f, AstNode_IndexExpr);
  956. result->IndexExpr.expr = expr;
  957. result->IndexExpr.index = index;
  958. result->IndexExpr.open = open;
  959. result->IndexExpr.close = close;
  960. return result;
  961. }
  962. AstNode *ast_slice_expr(AstFile *f, AstNode *expr, Token open, Token close, Token interval0, Token interval1, bool index3, AstNode *low, AstNode *high, AstNode *max) {
  963. AstNode *result = make_ast_node(f, AstNode_SliceExpr);
  964. result->SliceExpr.expr = expr;
  965. result->SliceExpr.open = open;
  966. result->SliceExpr.close = close;
  967. result->SliceExpr.interval0 = interval0;
  968. result->SliceExpr.interval1 = interval1;
  969. result->SliceExpr.index3 = index3;
  970. result->SliceExpr.low = low;
  971. result->SliceExpr.high = high;
  972. result->SliceExpr.max = max;
  973. return result;
  974. }
  975. AstNode *ast_deref_expr(AstFile *f, AstNode *expr, Token op) {
  976. AstNode *result = make_ast_node(f, AstNode_DerefExpr);
  977. result->DerefExpr.expr = expr;
  978. result->DerefExpr.op = op;
  979. return result;
  980. }
  981. AstNode *ast_ident(AstFile *f, Token token) {
  982. AstNode *result = make_ast_node(f, AstNode_Ident);
  983. result->Ident.token = token;
  984. return result;
  985. }
  986. AstNode *ast_implicit(AstFile *f, Token token) {
  987. AstNode *result = make_ast_node(f, AstNode_Implicit);
  988. result->Implicit = token;
  989. return result;
  990. }
  991. AstNode *ast_undef(AstFile *f, Token token) {
  992. AstNode *result = make_ast_node(f, AstNode_Undef);
  993. result->Undef = token;
  994. return result;
  995. }
  996. AstNode *ast_basic_lit(AstFile *f, Token basic_lit) {
  997. AstNode *result = make_ast_node(f, AstNode_BasicLit);
  998. result->BasicLit = basic_lit;
  999. return result;
  1000. }
  1001. AstNode *ast_basic_directive(AstFile *f, Token token, String name) {
  1002. AstNode *result = make_ast_node(f, AstNode_BasicDirective);
  1003. result->BasicDirective.token = token;
  1004. result->BasicDirective.name = name;
  1005. return result;
  1006. }
  1007. AstNode *ast_ellipsis(AstFile *f, Token token, AstNode *expr) {
  1008. AstNode *result = make_ast_node(f, AstNode_Ellipsis);
  1009. result->Ellipsis.token = token;
  1010. result->Ellipsis.expr = expr;
  1011. return result;
  1012. }
  1013. AstNode *ast_proc_lit(AstFile *f, AstNode *type, AstNode *body, u64 tags, String link_name) {
  1014. AstNode *result = make_ast_node(f, AstNode_ProcLit);
  1015. result->ProcLit.type = type;
  1016. result->ProcLit.body = body;
  1017. result->ProcLit.tags = tags;
  1018. result->ProcLit.link_name = link_name;
  1019. return result;
  1020. }
  1021. AstNode *ast_field_value(AstFile *f, AstNode *field, AstNode *value, Token eq) {
  1022. AstNode *result = make_ast_node(f, AstNode_FieldValue);
  1023. result->FieldValue.field = field;
  1024. result->FieldValue.value = value;
  1025. result->FieldValue.eq = eq;
  1026. return result;
  1027. }
  1028. AstNode *ast_compound_lit(AstFile *f, AstNode *type, Array<AstNode *> elems, Token open, Token close) {
  1029. AstNode *result = make_ast_node(f, AstNode_CompoundLit);
  1030. result->CompoundLit.type = type;
  1031. result->CompoundLit.elems = elems;
  1032. result->CompoundLit.open = open;
  1033. result->CompoundLit.close = close;
  1034. return result;
  1035. }
  1036. AstNode *ast_alias(AstFile *f, Token token, AstNode *expr) {
  1037. AstNode *result = make_ast_node(f, AstNode_Alias);
  1038. result->Alias.token = token;
  1039. result->Alias.expr = expr;
  1040. return result;
  1041. }
  1042. AstNode *ast_ternary_expr(AstFile *f, AstNode *cond, AstNode *x, AstNode *y) {
  1043. AstNode *result = make_ast_node(f, AstNode_TernaryExpr);
  1044. result->TernaryExpr.cond = cond;
  1045. result->TernaryExpr.x = x;
  1046. result->TernaryExpr.y = y;
  1047. return result;
  1048. }
  1049. AstNode *ast_type_assertion(AstFile *f, AstNode *expr, Token dot, AstNode *type) {
  1050. AstNode *result = make_ast_node(f, AstNode_TypeAssertion);
  1051. result->TypeAssertion.expr = expr;
  1052. result->TypeAssertion.dot = dot;
  1053. result->TypeAssertion.type = type;
  1054. return result;
  1055. }
  1056. AstNode *ast_type_cast(AstFile *f, Token token, AstNode *type, AstNode *expr) {
  1057. AstNode *result = make_ast_node(f, AstNode_TypeCast);
  1058. result->TypeCast.token = token;
  1059. result->TypeCast.type = type;
  1060. result->TypeCast.expr = expr;
  1061. return result;
  1062. }
  1063. AstNode *ast_bad_stmt(AstFile *f, Token begin, Token end) {
  1064. AstNode *result = make_ast_node(f, AstNode_BadStmt);
  1065. result->BadStmt.begin = begin;
  1066. result->BadStmt.end = end;
  1067. return result;
  1068. }
  1069. AstNode *ast_empty_stmt(AstFile *f, Token token) {
  1070. AstNode *result = make_ast_node(f, AstNode_EmptyStmt);
  1071. result->EmptyStmt.token = token;
  1072. return result;
  1073. }
  1074. AstNode *ast_expr_stmt(AstFile *f, AstNode *expr) {
  1075. AstNode *result = make_ast_node(f, AstNode_ExprStmt);
  1076. result->ExprStmt.expr = expr;
  1077. return result;
  1078. }
  1079. AstNode *ast_assign_stmt(AstFile *f, Token op, Array<AstNode *> lhs, Array<AstNode *> rhs) {
  1080. AstNode *result = make_ast_node(f, AstNode_AssignStmt);
  1081. result->AssignStmt.op = op;
  1082. result->AssignStmt.lhs = lhs;
  1083. result->AssignStmt.rhs = rhs;
  1084. return result;
  1085. }
  1086. AstNode *ast_inc_dec_stmt(AstFile *f, Token op, AstNode *expr) {
  1087. AstNode *result = make_ast_node(f, AstNode_IncDecStmt);
  1088. result->IncDecStmt.op = op;
  1089. result->IncDecStmt.expr = expr;
  1090. return result;
  1091. }
  1092. AstNode *ast_block_stmt(AstFile *f, Array<AstNode *> stmts, Token open, Token close) {
  1093. AstNode *result = make_ast_node(f, AstNode_BlockStmt);
  1094. result->BlockStmt.stmts = stmts;
  1095. result->BlockStmt.open = open;
  1096. result->BlockStmt.close = close;
  1097. return result;
  1098. }
  1099. AstNode *ast_if_stmt(AstFile *f, Token token, AstNode *init, AstNode *cond, AstNode *body, AstNode *else_stmt) {
  1100. AstNode *result = make_ast_node(f, AstNode_IfStmt);
  1101. result->IfStmt.token = token;
  1102. result->IfStmt.init = init;
  1103. result->IfStmt.cond = cond;
  1104. result->IfStmt.body = body;
  1105. result->IfStmt.else_stmt = else_stmt;
  1106. return result;
  1107. }
  1108. AstNode *ast_when_stmt(AstFile *f, Token token, AstNode *cond, AstNode *body, AstNode *else_stmt) {
  1109. AstNode *result = make_ast_node(f, AstNode_WhenStmt);
  1110. result->WhenStmt.token = token;
  1111. result->WhenStmt.cond = cond;
  1112. result->WhenStmt.body = body;
  1113. result->WhenStmt.else_stmt = else_stmt;
  1114. return result;
  1115. }
  1116. AstNode *ast_return_stmt(AstFile *f, Token token, Array<AstNode *> results) {
  1117. AstNode *result = make_ast_node(f, AstNode_ReturnStmt);
  1118. result->ReturnStmt.token = token;
  1119. result->ReturnStmt.results = results;
  1120. return result;
  1121. }
  1122. AstNode *ast_for_stmt(AstFile *f, Token token, AstNode *init, AstNode *cond, AstNode *post, AstNode *body) {
  1123. AstNode *result = make_ast_node(f, AstNode_ForStmt);
  1124. result->ForStmt.token = token;
  1125. result->ForStmt.init = init;
  1126. result->ForStmt.cond = cond;
  1127. result->ForStmt.post = post;
  1128. result->ForStmt.body = body;
  1129. return result;
  1130. }
  1131. AstNode *ast_range_stmt(AstFile *f, Token token, AstNode *value, AstNode *index, Token in_token, AstNode *expr, AstNode *body) {
  1132. AstNode *result = make_ast_node(f, AstNode_RangeStmt);
  1133. result->RangeStmt.token = token;
  1134. result->RangeStmt.value = value;
  1135. result->RangeStmt.index = index;
  1136. result->RangeStmt.in_token = in_token;
  1137. result->RangeStmt.expr = expr;
  1138. result->RangeStmt.body = body;
  1139. return result;
  1140. }
  1141. AstNode *ast_switch_stmt(AstFile *f, Token token, AstNode *init, AstNode *tag, AstNode *body) {
  1142. AstNode *result = make_ast_node(f, AstNode_SwitchStmt);
  1143. result->SwitchStmt.token = token;
  1144. result->SwitchStmt.init = init;
  1145. result->SwitchStmt.tag = tag;
  1146. result->SwitchStmt.body = body;
  1147. return result;
  1148. }
  1149. AstNode *ast_type_switch_stmt(AstFile *f, Token token, AstNode *tag, AstNode *body) {
  1150. AstNode *result = make_ast_node(f, AstNode_TypeSwitchStmt);
  1151. result->TypeSwitchStmt.token = token;
  1152. result->TypeSwitchStmt.tag = tag;
  1153. result->TypeSwitchStmt.body = body;
  1154. return result;
  1155. }
  1156. AstNode *ast_case_clause(AstFile *f, Token token, Array<AstNode *> list, Array<AstNode *> stmts) {
  1157. AstNode *result = make_ast_node(f, AstNode_CaseClause);
  1158. result->CaseClause.token = token;
  1159. result->CaseClause.list = list;
  1160. result->CaseClause.stmts = stmts;
  1161. return result;
  1162. }
  1163. AstNode *ast_defer_stmt(AstFile *f, Token token, AstNode *stmt) {
  1164. AstNode *result = make_ast_node(f, AstNode_DeferStmt);
  1165. result->DeferStmt.token = token;
  1166. result->DeferStmt.stmt = stmt;
  1167. return result;
  1168. }
  1169. AstNode *ast_branch_stmt(AstFile *f, Token token, AstNode *label) {
  1170. AstNode *result = make_ast_node(f, AstNode_BranchStmt);
  1171. result->BranchStmt.token = token;
  1172. result->BranchStmt.label = label;
  1173. return result;
  1174. }
  1175. AstNode *ast_using_stmt(AstFile *f, Token token, Array<AstNode *> list) {
  1176. AstNode *result = make_ast_node(f, AstNode_UsingStmt);
  1177. result->UsingStmt.token = token;
  1178. result->UsingStmt.list = list;
  1179. return result;
  1180. }
  1181. AstNode *ast_asm_operand(AstFile *f, Token string, AstNode *operand) {
  1182. AstNode *result = make_ast_node(f, AstNode_AsmOperand);
  1183. result->AsmOperand.string = string;
  1184. result->AsmOperand.operand = operand;
  1185. return result;
  1186. }
  1187. AstNode *ast_asm_stmt(AstFile *f, Token token, bool is_volatile, Token open, Token close, Token code_string,
  1188. AstNode *output_list, AstNode *input_list, AstNode *clobber_list,
  1189. isize output_count, isize input_count, isize clobber_count) {
  1190. AstNode *result = make_ast_node(f, AstNode_AsmStmt);
  1191. result->AsmStmt.token = token;
  1192. result->AsmStmt.is_volatile = is_volatile;
  1193. result->AsmStmt.open = open;
  1194. result->AsmStmt.close = close;
  1195. result->AsmStmt.code_string = code_string;
  1196. result->AsmStmt.output_list = output_list;
  1197. result->AsmStmt.input_list = input_list;
  1198. result->AsmStmt.clobber_list = clobber_list;
  1199. result->AsmStmt.output_count = output_count;
  1200. result->AsmStmt.input_count = input_count;
  1201. result->AsmStmt.clobber_count = clobber_count;
  1202. return result;
  1203. }
  1204. AstNode *ast_push_allocator(AstFile *f, Token token, AstNode *expr, AstNode *body) {
  1205. AstNode *result = make_ast_node(f, AstNode_PushAllocator);
  1206. result->PushAllocator.token = token;
  1207. result->PushAllocator.expr = expr;
  1208. result->PushAllocator.body = body;
  1209. return result;
  1210. }
  1211. AstNode *ast_push_context(AstFile *f, Token token, AstNode *expr, AstNode *body) {
  1212. AstNode *result = make_ast_node(f, AstNode_PushContext);
  1213. result->PushContext.token = token;
  1214. result->PushContext.expr = expr;
  1215. result->PushContext.body = body;
  1216. return result;
  1217. }
  1218. AstNode *ast_bad_decl(AstFile *f, Token begin, Token end) {
  1219. AstNode *result = make_ast_node(f, AstNode_BadDecl);
  1220. result->BadDecl.begin = begin;
  1221. result->BadDecl.end = end;
  1222. return result;
  1223. }
  1224. AstNode *ast_field(AstFile *f, Array<AstNode *> names, AstNode *type, AstNode *default_value, u32 flags,
  1225. CommentGroup docs, CommentGroup comment) {
  1226. AstNode *result = make_ast_node(f, AstNode_Field);
  1227. result->Field.names = names;
  1228. result->Field.type = type;
  1229. result->Field.default_value = default_value;
  1230. result->Field.flags = flags;
  1231. result->Field.docs = docs;
  1232. result->Field.comment = comment;
  1233. return result;
  1234. }
  1235. AstNode *ast_field_list(AstFile *f, Token token, Array<AstNode *> list) {
  1236. AstNode *result = make_ast_node(f, AstNode_FieldList);
  1237. result->FieldList.token = token;
  1238. result->FieldList.list = list;
  1239. return result;
  1240. }
  1241. AstNode *ast_union_field(AstFile *f, AstNode *name, AstNode *list) {
  1242. AstNode *result = make_ast_node(f, AstNode_UnionField);
  1243. result->UnionField.name = name;
  1244. result->UnionField.list = list;
  1245. return result;
  1246. }
  1247. AstNode *ast_type_type(AstFile *f, Token token, AstNode *specialization) {
  1248. AstNode *result = make_ast_node(f, AstNode_TypeType);
  1249. result->TypeType.token = token;
  1250. result->TypeType.specialization = specialization;
  1251. return result;
  1252. }
  1253. AstNode *ast_helper_type(AstFile *f, Token token, AstNode *type) {
  1254. AstNode *result = make_ast_node(f, AstNode_HelperType);
  1255. result->HelperType.token = token;
  1256. result->HelperType.type = type;
  1257. return result;
  1258. }
  1259. AstNode *ast_poly_type(AstFile *f, Token token, AstNode *type, AstNode *specialization) {
  1260. AstNode *result = make_ast_node(f, AstNode_PolyType);
  1261. result->PolyType.token = token;
  1262. result->PolyType.type = type;
  1263. result->PolyType.specialization = specialization;
  1264. return result;
  1265. }
  1266. AstNode *ast_proc_type(AstFile *f, Token token, AstNode *params, AstNode *results, u64 tags, ProcCallingConvention calling_convention, bool generic) {
  1267. AstNode *result = make_ast_node(f, AstNode_ProcType);
  1268. result->ProcType.token = token;
  1269. result->ProcType.params = params;
  1270. result->ProcType.results = results;
  1271. result->ProcType.tags = tags;
  1272. result->ProcType.calling_convention = calling_convention;
  1273. result->ProcType.generic = generic;
  1274. return result;
  1275. }
  1276. AstNode *ast_pointer_type(AstFile *f, Token token, AstNode *type) {
  1277. AstNode *result = make_ast_node(f, AstNode_PointerType);
  1278. result->PointerType.token = token;
  1279. result->PointerType.type = type;
  1280. return result;
  1281. }
  1282. AstNode *ast_array_type(AstFile *f, Token token, AstNode *count, AstNode *elem) {
  1283. AstNode *result = make_ast_node(f, AstNode_ArrayType);
  1284. result->ArrayType.token = token;
  1285. result->ArrayType.count = count;
  1286. result->ArrayType.elem = elem;
  1287. return result;
  1288. }
  1289. AstNode *ast_dynamic_array_type(AstFile *f, Token token, AstNode *elem) {
  1290. AstNode *result = make_ast_node(f, AstNode_DynamicArrayType);
  1291. result->DynamicArrayType.token = token;
  1292. result->DynamicArrayType.elem = elem;
  1293. return result;
  1294. }
  1295. AstNode *ast_vector_type(AstFile *f, Token token, AstNode *count, AstNode *elem) {
  1296. AstNode *result = make_ast_node(f, AstNode_VectorType);
  1297. result->VectorType.token = token;
  1298. result->VectorType.count = count;
  1299. result->VectorType.elem = elem;
  1300. return result;
  1301. }
  1302. AstNode *ast_struct_type(AstFile *f, Token token, Array<AstNode *> fields, isize field_count,
  1303. AstNode *polymorphic_params, bool is_packed, bool is_ordered, bool is_raw_union,
  1304. AstNode *align) {
  1305. AstNode *result = make_ast_node(f, AstNode_StructType);
  1306. result->StructType.token = token;
  1307. result->StructType.fields = fields;
  1308. result->StructType.field_count = field_count;
  1309. result->StructType.polymorphic_params = polymorphic_params;
  1310. result->StructType.is_packed = is_packed;
  1311. result->StructType.is_ordered = is_ordered;
  1312. result->StructType.is_raw_union = is_raw_union;
  1313. result->StructType.align = align;
  1314. return result;
  1315. }
  1316. AstNode *ast_union_type(AstFile *f, Token token, Array<AstNode *> variants, AstNode *align) {
  1317. AstNode *result = make_ast_node(f, AstNode_UnionType);
  1318. result->UnionType.token = token;
  1319. result->UnionType.variants = variants;
  1320. result->UnionType.align = align;
  1321. return result;
  1322. }
  1323. AstNode *ast_enum_type(AstFile *f, Token token, AstNode *base_type, Array<AstNode *> fields) {
  1324. AstNode *result = make_ast_node(f, AstNode_EnumType);
  1325. result->EnumType.token = token;
  1326. result->EnumType.base_type = base_type;
  1327. result->EnumType.fields = fields;
  1328. return result;
  1329. }
  1330. AstNode *ast_bit_field_type(AstFile *f, Token token, Array<AstNode *> fields, AstNode *align) {
  1331. AstNode *result = make_ast_node(f, AstNode_BitFieldType);
  1332. result->BitFieldType.token = token;
  1333. result->BitFieldType.fields = fields;
  1334. result->BitFieldType.align = align;
  1335. return result;
  1336. }
  1337. AstNode *ast_map_type(AstFile *f, Token token, AstNode *key, AstNode *value) {
  1338. AstNode *result = make_ast_node(f, AstNode_MapType);
  1339. result->MapType.token = token;
  1340. result->MapType.key = key;
  1341. result->MapType.value = value;
  1342. return result;
  1343. }
  1344. AstNode *ast_foreign_block_decl(AstFile *f, Token token, AstNode *foreign_library, Token open, Token close, Array<AstNode *> decls,
  1345. CommentGroup docs) {
  1346. AstNode *result = make_ast_node(f, AstNode_ForeignBlockDecl);
  1347. result->ForeignBlockDecl.token = token;
  1348. result->ForeignBlockDecl.foreign_library = foreign_library;
  1349. result->ForeignBlockDecl.open = open;
  1350. result->ForeignBlockDecl.close = close;
  1351. result->ForeignBlockDecl.decls = decls;
  1352. result->ForeignBlockDecl.docs = docs;
  1353. return result;
  1354. }
  1355. AstNode *ast_label_decl(AstFile *f, Token token, AstNode *name) {
  1356. AstNode *result = make_ast_node(f, AstNode_Label);
  1357. result->Label.token = token;
  1358. result->Label.name = name;
  1359. return result;
  1360. }
  1361. AstNode *ast_value_decl(AstFile *f, Array<AstNode *> names, AstNode *type, Array<AstNode *> values, bool is_mutable,
  1362. CommentGroup docs, CommentGroup comment) {
  1363. AstNode *result = make_ast_node(f, AstNode_ValueDecl);
  1364. result->ValueDecl.names = names;
  1365. result->ValueDecl.type = type;
  1366. result->ValueDecl.values = values;
  1367. result->ValueDecl.is_mutable = is_mutable;
  1368. result->ValueDecl.docs = docs;
  1369. result->ValueDecl.comment = comment;
  1370. return result;
  1371. }
  1372. AstNode *ast_import_decl(AstFile *f, Token token, bool is_using, Token relpath, Token import_name, AstNode *cond,
  1373. CommentGroup docs, CommentGroup comment) {
  1374. AstNode *result = make_ast_node(f, AstNode_ImportDecl);
  1375. result->ImportDecl.token = token;
  1376. result->ImportDecl.is_using = is_using;
  1377. result->ImportDecl.relpath = relpath;
  1378. result->ImportDecl.import_name = import_name;
  1379. result->ImportDecl.docs = docs;
  1380. result->ImportDecl.comment = comment;
  1381. return result;
  1382. }
  1383. AstNode *ast_export_decl(AstFile *f, Token token, Token relpath, AstNode *cond,
  1384. CommentGroup docs, CommentGroup comment) {
  1385. AstNode *result = make_ast_node(f, AstNode_ExportDecl);
  1386. result->ExportDecl.token = token;
  1387. result->ExportDecl.relpath = relpath;
  1388. result->ExportDecl.docs = docs;
  1389. result->ExportDecl.comment = comment;
  1390. return result;
  1391. }
  1392. AstNode *ast_foreign_library_decl(AstFile *f, Token token, Token filepath, Token library_name, AstNode *cond,
  1393. CommentGroup docs, CommentGroup comment) {
  1394. AstNode *result = make_ast_node(f, AstNode_ForeignLibraryDecl);
  1395. result->ForeignLibraryDecl.token = token;
  1396. result->ForeignLibraryDecl.filepath = filepath;
  1397. result->ForeignLibraryDecl.library_name = library_name;
  1398. result->ForeignLibraryDecl.docs = docs;
  1399. result->ForeignLibraryDecl.comment = comment;
  1400. return result;
  1401. }
  1402. bool next_token0(AstFile *f) {
  1403. // Token prev = f->curr_token;
  1404. if (f->curr_token_index+1 < f->tokens.count) {
  1405. f->curr_token = f->tokens[++f->curr_token_index];
  1406. return true;
  1407. }
  1408. syntax_error(f->curr_token, "Token is EOF");
  1409. return false;
  1410. }
  1411. Token consume_comment(AstFile *f, isize *end_line_) {
  1412. Token tok = f->curr_token;
  1413. GB_ASSERT(tok.kind == Token_Comment);
  1414. isize end_line = tok.pos.line;
  1415. if (tok.string[1] == '*') {
  1416. for (isize i = 0; i < tok.string.len; i++) {
  1417. if (tok.string[i] == '\n') {
  1418. end_line++;
  1419. }
  1420. }
  1421. }
  1422. if (end_line_) *end_line_ = end_line;
  1423. next_token0(f);
  1424. return tok;
  1425. }
  1426. CommentGroup consume_comment_group(AstFile *f, isize n, isize *end_line_) {
  1427. Array<Token> list = {};
  1428. isize end_line = f->curr_token.pos.line;
  1429. if (f->curr_token.kind == Token_Comment) {
  1430. array_init(&list, heap_allocator());
  1431. while (f->curr_token.kind == Token_Comment &&
  1432. f->curr_token.pos.line <= end_line+n) {
  1433. array_add(&list, consume_comment(f, &end_line));
  1434. }
  1435. }
  1436. if (end_line_) *end_line_ = end_line;
  1437. CommentGroup comments = {};
  1438. comments.list = list;
  1439. array_add(&f->comments, comments);
  1440. return comments;
  1441. }
  1442. void comsume_comment_groups(AstFile *f, Token prev) {
  1443. if (f->curr_token.kind != Token_Comment) return;
  1444. CommentGroup comment = {};
  1445. isize end_line = 0;
  1446. if (f->curr_token.pos.line == prev.pos.line) {
  1447. comment = consume_comment_group(f, 0, &end_line);
  1448. if (f->curr_token.pos.line != end_line) {
  1449. f->line_comment = comment;
  1450. }
  1451. }
  1452. end_line = -1;
  1453. while (f->curr_token.kind == Token_Comment) {
  1454. comment = consume_comment_group(f, 1, &end_line);
  1455. }
  1456. if (end_line+1 == f->curr_token.pos.line) {
  1457. f->lead_comment = comment;
  1458. }
  1459. GB_ASSERT(f->curr_token.kind != Token_Comment);
  1460. }
  1461. Token advance_token(AstFile *f) {
  1462. gb_zero_item(&f->lead_comment);
  1463. gb_zero_item(&f->line_comment);
  1464. Token prev = f->prev_token = f->curr_token;
  1465. bool ok = next_token0(f);
  1466. if (ok) comsume_comment_groups(f, prev);
  1467. return prev;
  1468. }
  1469. TokenKind look_ahead_token_kind(AstFile *f, isize amount) {
  1470. GB_ASSERT(amount > 0);
  1471. TokenKind kind = Token_Invalid;
  1472. isize index = f->curr_token_index;
  1473. while (amount > 0) {
  1474. index++;
  1475. kind = f->tokens[index].kind;
  1476. if (kind != Token_Comment) {
  1477. amount--;
  1478. }
  1479. }
  1480. return kind;
  1481. }
  1482. Token expect_token(AstFile *f, TokenKind kind) {
  1483. Token prev = f->curr_token;
  1484. if (prev.kind != kind) {
  1485. String c = token_strings[kind];
  1486. String p = token_strings[prev.kind];
  1487. syntax_error(f->curr_token, "Expected `%.*s`, got `%.*s`", LIT(c), LIT(p));
  1488. if (prev.kind == Token_EOF) {
  1489. gb_exit(1);
  1490. }
  1491. }
  1492. advance_token(f);
  1493. return prev;
  1494. }
  1495. Token expect_token_after(AstFile *f, TokenKind kind, char *msg) {
  1496. Token prev = f->curr_token;
  1497. if (prev.kind != kind) {
  1498. String p = token_strings[prev.kind];
  1499. syntax_error(f->curr_token, "Expected `%.*s` after %s, got `%.*s`",
  1500. LIT(token_strings[kind]),
  1501. msg,
  1502. LIT(p));
  1503. }
  1504. advance_token(f);
  1505. return prev;
  1506. }
  1507. Token expect_operator(AstFile *f) {
  1508. Token prev = f->curr_token;
  1509. if (!gb_is_between(prev.kind, Token__OperatorBegin+1, Token__OperatorEnd-1)) {
  1510. syntax_error(f->curr_token, "Expected an operator, got `%.*s`",
  1511. LIT(token_strings[prev.kind]));
  1512. } else if (!f->allow_range && (prev.kind == Token_Ellipsis || prev.kind == Token_HalfClosed)) {
  1513. syntax_error(f->curr_token, "Expected an non-range operator, got `%.*s`",
  1514. LIT(token_strings[prev.kind]));
  1515. }
  1516. advance_token(f);
  1517. return prev;
  1518. }
  1519. Token expect_keyword(AstFile *f) {
  1520. Token prev = f->curr_token;
  1521. if (!gb_is_between(prev.kind, Token__KeywordBegin+1, Token__KeywordEnd-1)) {
  1522. syntax_error(f->curr_token, "Expected a keyword, got `%.*s`",
  1523. LIT(token_strings[prev.kind]));
  1524. }
  1525. advance_token(f);
  1526. return prev;
  1527. }
  1528. bool allow_token(AstFile *f, TokenKind kind) {
  1529. Token prev = f->curr_token;
  1530. if (prev.kind == kind) {
  1531. advance_token(f);
  1532. return true;
  1533. }
  1534. return false;
  1535. }
  1536. bool is_blank_ident(String str) {
  1537. if (str.len == 1) {
  1538. return str[0] == '_';
  1539. }
  1540. return false;
  1541. }
  1542. bool is_blank_ident(Token token) {
  1543. if (token.kind == Token_Ident) {
  1544. return is_blank_ident(token.string);
  1545. }
  1546. return false;
  1547. }
  1548. bool is_blank_ident(AstNode *node) {
  1549. if (node->kind == AstNode_Ident) {
  1550. ast_node(i, Ident, node);
  1551. return is_blank_ident(i->token.string);
  1552. }
  1553. return false;
  1554. }
  1555. // NOTE(bill): Go to next statement to prevent numerous error messages popping up
  1556. void fix_advance_to_next_stmt(AstFile *f) {
  1557. for (;;) {
  1558. Token t = f->curr_token;
  1559. switch (t.kind) {
  1560. case Token_EOF:
  1561. case Token_Semicolon:
  1562. return;
  1563. case Token_foreign:
  1564. case Token_foreign_library:
  1565. case Token_foreign_system_library:
  1566. case Token_if:
  1567. case Token_for:
  1568. case Token_when:
  1569. case Token_return:
  1570. case Token_switch:
  1571. case Token_defer:
  1572. case Token_asm:
  1573. case Token_using:
  1574. // case Token_thread_local:
  1575. // case Token_no_alias:
  1576. case Token_break:
  1577. case Token_continue:
  1578. case Token_fallthrough:
  1579. case Token_push_allocator:
  1580. case Token_push_context:
  1581. case Token_Hash:
  1582. {
  1583. if (t.pos == f->fix_prev_pos &&
  1584. f->fix_count < PARSER_MAX_FIX_COUNT) {
  1585. f->fix_count++;
  1586. return;
  1587. }
  1588. if (f->fix_prev_pos < t.pos) {
  1589. f->fix_prev_pos = t.pos;
  1590. f->fix_count = 0; // NOTE(bill): Reset
  1591. return;
  1592. }
  1593. // NOTE(bill): Reaching here means there is a parsing bug
  1594. } break;
  1595. }
  1596. advance_token(f);
  1597. }
  1598. }
  1599. Token expect_closing(AstFile *f, TokenKind kind, String context) {
  1600. if (f->curr_token.kind != kind &&
  1601. f->curr_token.kind == Token_Semicolon &&
  1602. f->curr_token.string == "\n") {
  1603. error(f->curr_token, "Missing `,` before newline in %.*s", LIT(context));
  1604. advance_token(f);
  1605. }
  1606. return expect_token(f, kind);
  1607. }
  1608. bool is_semicolon_optional_for_node(AstFile *f, AstNode *s) {
  1609. if (s == nullptr) {
  1610. return false;
  1611. }
  1612. switch (s->kind) {
  1613. case AstNode_EmptyStmt:
  1614. return true;
  1615. case AstNode_IfStmt:
  1616. case AstNode_WhenStmt:
  1617. case AstNode_ForStmt:
  1618. case AstNode_RangeStmt:
  1619. case AstNode_SwitchStmt:
  1620. case AstNode_TypeSwitchStmt:
  1621. return true;
  1622. case AstNode_PointerType:
  1623. return is_semicolon_optional_for_node(f, s->PointerType.type);
  1624. case AstNode_StructType:
  1625. case AstNode_UnionType:
  1626. case AstNode_EnumType:
  1627. case AstNode_BitFieldType:
  1628. return true;
  1629. case AstNode_ProcLit:
  1630. return s->ProcLit.body != nullptr;
  1631. case AstNode_ImportDecl:
  1632. case AstNode_ExportDecl:
  1633. case AstNode_ForeignLibraryDecl:
  1634. return true;
  1635. case AstNode_ValueDecl:
  1636. if (s->ValueDecl.is_mutable) {
  1637. return false;
  1638. }
  1639. if (s->ValueDecl.values.count > 0) {
  1640. return is_semicolon_optional_for_node(f, s->ValueDecl.values[s->ValueDecl.values.count-1]);
  1641. }
  1642. break;
  1643. case AstNode_ForeignBlockDecl:
  1644. if (s->ForeignBlockDecl.close.pos.line != 0) {
  1645. return true;
  1646. }
  1647. if (s->ForeignBlockDecl.decls.count == 1) {
  1648. return is_semicolon_optional_for_node(f, s->ForeignBlockDecl.decls[0]);
  1649. }
  1650. break;
  1651. }
  1652. return false;
  1653. }
  1654. void expect_semicolon(AstFile *f, AstNode *s) {
  1655. if (allow_token(f, Token_Semicolon)) {
  1656. return;
  1657. }
  1658. Token prev_token = f->prev_token;
  1659. if (prev_token.kind == Token_Semicolon) {
  1660. return;
  1661. }
  1662. switch (f->curr_token.kind) {
  1663. case Token_EOF:
  1664. return;
  1665. }
  1666. if (s != nullptr) {
  1667. if (prev_token.pos.line != f->curr_token.pos.line) {
  1668. if (is_semicolon_optional_for_node(f, s)) {
  1669. return;
  1670. }
  1671. } else if (f->curr_token.kind == Token_CloseBrace) {
  1672. return;
  1673. }
  1674. String node_string = ast_node_strings[s->kind];
  1675. syntax_error(prev_token, "Expected `;` after %.*s, got %.*s",
  1676. LIT(node_string), LIT(token_strings[prev_token.kind]));
  1677. } else {
  1678. syntax_error(prev_token, "Expected `;`");
  1679. }
  1680. fix_advance_to_next_stmt(f);
  1681. }
  1682. AstNode * parse_expr(AstFile *f, bool lhs);
  1683. AstNode * parse_proc_type(AstFile *f, Token proc_token, String *link_name);
  1684. Array<AstNode *> parse_stmt_list(AstFile *f);
  1685. AstNode * parse_stmt(AstFile *f);
  1686. AstNode * parse_body(AstFile *f);
  1687. AstNode *parse_ident(AstFile *f) {
  1688. Token token = f->curr_token;
  1689. if (token.kind == Token_Ident) {
  1690. advance_token(f);
  1691. } else {
  1692. token.string = str_lit("_");
  1693. expect_token(f, Token_Ident);
  1694. }
  1695. return ast_ident(f, token);
  1696. }
  1697. AstNode *parse_tag_expr(AstFile *f, AstNode *expression) {
  1698. Token token = expect_token(f, Token_Hash);
  1699. Token name = {};
  1700. if (f->curr_token.kind == Token_export) {
  1701. name = expect_token(f, Token_export);
  1702. } else {
  1703. name = expect_token(f, Token_Ident);
  1704. }
  1705. return ast_tag_expr(f, token, name, expression);
  1706. }
  1707. AstNode *unparen_expr(AstNode *node) {
  1708. for (;;) {
  1709. if (node == nullptr) {
  1710. return nullptr;
  1711. }
  1712. if (node->kind != AstNode_ParenExpr) {
  1713. return node;
  1714. }
  1715. node = node->ParenExpr.expr;
  1716. }
  1717. }
  1718. AstNode *parse_value(AstFile *f);
  1719. Array<AstNode *> parse_element_list(AstFile *f) {
  1720. Array<AstNode *> elems = make_ast_node_array(f);
  1721. while (f->curr_token.kind != Token_CloseBrace &&
  1722. f->curr_token.kind != Token_EOF) {
  1723. AstNode *elem = parse_value(f);
  1724. if (f->curr_token.kind == Token_Eq) {
  1725. Token eq = expect_token(f, Token_Eq);
  1726. AstNode *value = parse_value(f);
  1727. elem = ast_field_value(f, elem, value, eq);
  1728. }
  1729. array_add(&elems, elem);
  1730. if (!allow_token(f, Token_Comma)) {
  1731. break;
  1732. }
  1733. }
  1734. return elems;
  1735. }
  1736. AstNode *parse_literal_value(AstFile *f, AstNode *type) {
  1737. Array<AstNode *> elems = {};
  1738. Token open = expect_token(f, Token_OpenBrace);
  1739. f->expr_level++;
  1740. if (f->curr_token.kind != Token_CloseBrace) {
  1741. elems = parse_element_list(f);
  1742. }
  1743. f->expr_level--;
  1744. Token close = expect_closing(f, Token_CloseBrace, str_lit("compound literal"));
  1745. return ast_compound_lit(f, type, elems, open, close);
  1746. }
  1747. AstNode *parse_value(AstFile *f) {
  1748. if (f->curr_token.kind == Token_OpenBrace) {
  1749. return parse_literal_value(f, nullptr);
  1750. }
  1751. AstNode *value = parse_expr(f, false);
  1752. return value;
  1753. }
  1754. AstNode *parse_type_or_ident(AstFile *f);
  1755. void check_proc_add_tag(AstFile *f, AstNode *tag_expr, u64 *tags, ProcTag tag, String tag_name) {
  1756. if (*tags & tag) {
  1757. syntax_error(tag_expr, "Procedure tag already used: %.*s", LIT(tag_name));
  1758. }
  1759. *tags |= tag;
  1760. }
  1761. bool is_foreign_name_valid(String name) {
  1762. if (name.len == 0) {
  1763. return false;
  1764. }
  1765. isize offset = 0;
  1766. while (offset < name.len) {
  1767. Rune rune;
  1768. isize remaining = name.len - offset;
  1769. isize width = gb_utf8_decode(name.text+offset, remaining, &rune);
  1770. if (rune == GB_RUNE_INVALID && width == 1) {
  1771. return false;
  1772. } else if (rune == GB_RUNE_BOM && remaining > 0) {
  1773. return false;
  1774. }
  1775. if (offset == 0) {
  1776. switch (rune) {
  1777. case '-':
  1778. case '$':
  1779. case '.':
  1780. case '_':
  1781. break;
  1782. default:
  1783. if (!gb_char_is_alpha(cast(char)rune))
  1784. return false;
  1785. break;
  1786. }
  1787. } else {
  1788. switch (rune) {
  1789. case '-':
  1790. case '$':
  1791. case '.':
  1792. case '_':
  1793. break;
  1794. default:
  1795. if (!gb_char_is_alphanumeric(cast(char)rune)) {
  1796. return false;
  1797. }
  1798. break;
  1799. }
  1800. }
  1801. offset += width;
  1802. }
  1803. return true;
  1804. }
  1805. void parse_proc_tags(AstFile *f, u64 *tags, String *link_name, ProcCallingConvention *calling_convention) {
  1806. GB_ASSERT(tags != nullptr);
  1807. GB_ASSERT(link_name != nullptr);
  1808. ProcCallingConvention cc = ProcCC_Invalid;
  1809. while (f->curr_token.kind == Token_Hash) {
  1810. AstNode *tag_expr = parse_tag_expr(f, nullptr);
  1811. ast_node(te, TagExpr, tag_expr);
  1812. String tag_name = te->name.string;
  1813. #define ELSE_IF_ADD_TAG(name) \
  1814. else if (tag_name == #name) { \
  1815. check_proc_add_tag(f, tag_expr, tags, ProcTag_##name, tag_name); \
  1816. }
  1817. if (tag_name == "link_name") {
  1818. check_proc_add_tag(f, tag_expr, tags, ProcTag_link_name, tag_name);
  1819. if (f->curr_token.kind == Token_String) {
  1820. *link_name = f->curr_token.string;
  1821. if (!is_foreign_name_valid(*link_name)) {
  1822. syntax_error(tag_expr, "Invalid alternative link procedure name `%.*s`", LIT(*link_name));
  1823. }
  1824. advance_token(f);
  1825. } else {
  1826. expect_token(f, Token_String);
  1827. }
  1828. }
  1829. ELSE_IF_ADD_TAG(require_results)
  1830. ELSE_IF_ADD_TAG(export)
  1831. ELSE_IF_ADD_TAG(bounds_check)
  1832. ELSE_IF_ADD_TAG(no_bounds_check)
  1833. ELSE_IF_ADD_TAG(inline)
  1834. ELSE_IF_ADD_TAG(no_inline)
  1835. else if (tag_name == "cc_odin") {
  1836. if (cc == ProcCC_Invalid) {
  1837. cc = ProcCC_Odin;
  1838. } else {
  1839. syntax_error(tag_expr, "Multiple calling conventions for procedure type");
  1840. }
  1841. } else if (tag_name == "cc_contextless") {
  1842. if (cc == ProcCC_Invalid) {
  1843. cc = ProcCC_Contextless;
  1844. } else {
  1845. syntax_error(tag_expr, "Multiple calling conventions for procedure type");
  1846. }
  1847. } else if (tag_name == "cc_c") {
  1848. if (cc == ProcCC_Invalid) {
  1849. cc = ProcCC_C;
  1850. } else {
  1851. syntax_error(tag_expr, "Multiple calling conventions for procedure type");
  1852. }
  1853. } else if (tag_name == "cc_std") {
  1854. if (cc == ProcCC_Invalid) {
  1855. cc = ProcCC_Std;
  1856. } else {
  1857. syntax_error(tag_expr, "Multiple calling conventions for procedure type");
  1858. }
  1859. } else if (tag_name == "cc_fast") {
  1860. if (cc == ProcCC_Invalid) {
  1861. cc = ProcCC_Fast;
  1862. } else {
  1863. syntax_error(tag_expr, "Multiple calling conventions for procedure type");
  1864. }
  1865. } else {
  1866. syntax_error(tag_expr, "Unknown procedure tag #%.*s\n", LIT(tag_name));
  1867. }
  1868. #undef ELSE_IF_ADD_TAG
  1869. }
  1870. if (cc == ProcCC_Invalid) {
  1871. if ((*tags) & ProcTag_foreign || f->in_foreign_block) {
  1872. cc = ProcCC_C;
  1873. } else {
  1874. cc = ProcCC_Odin;
  1875. }
  1876. }
  1877. if (calling_convention) {
  1878. *calling_convention = cc;
  1879. }
  1880. if ((*tags & ProcTag_foreign) && (*tags & ProcTag_export)) {
  1881. syntax_error(f->curr_token, "A foreign procedure cannot have #export");
  1882. }
  1883. if ((*tags & ProcTag_inline) && (*tags & ProcTag_no_inline)) {
  1884. syntax_error(f->curr_token, "You cannot apply both #inline and #no_inline to a procedure");
  1885. }
  1886. if ((*tags & ProcTag_bounds_check) && (*tags & ProcTag_no_bounds_check)) {
  1887. syntax_error(f->curr_token, "You cannot apply both #bounds_check and #no_bounds_check to a procedure");
  1888. }
  1889. if (((*tags & ProcTag_bounds_check) || (*tags & ProcTag_no_bounds_check)) && (*tags & ProcTag_foreign)) {
  1890. syntax_error(f->curr_token, "You cannot apply both #bounds_check or #no_bounds_check to a procedure without a body");
  1891. }
  1892. }
  1893. Array<AstNode *> parse_lhs_expr_list (AstFile *f);
  1894. Array<AstNode *> parse_rhs_expr_list (AstFile *f);
  1895. AstNode * parse_simple_stmt (AstFile *f, StmtAllowFlag flags);
  1896. AstNode * parse_type (AstFile *f);
  1897. AstNode * parse_call_expr (AstFile *f, AstNode *operand);
  1898. AstNode * parse_struct_field_list(AstFile *f, isize *name_count_);
  1899. AstNode *parse_field_list(AstFile *f, isize *name_count_, u32 allowed_flags, TokenKind follow, bool allow_default_parameters, bool allow_type_token);
  1900. AstNode *convert_stmt_to_expr(AstFile *f, AstNode *statement, String kind) {
  1901. if (statement == nullptr) {
  1902. return nullptr;
  1903. }
  1904. if (statement->kind == AstNode_ExprStmt) {
  1905. return statement->ExprStmt.expr;
  1906. }
  1907. syntax_error(f->curr_token, "Expected `%.*s`, found a simple statement.", LIT(kind));
  1908. Token end = f->curr_token;
  1909. if (f->tokens.count < f->curr_token_index) {
  1910. end = f->tokens[f->curr_token_index+1];
  1911. }
  1912. return ast_bad_expr(f, f->curr_token, end);
  1913. }
  1914. AstNode *convert_stmt_to_body(AstFile *f, AstNode *stmt) {
  1915. if (stmt->kind == AstNode_BlockStmt) {
  1916. syntax_error(stmt, "Expected a normal statement rather than a block statement");
  1917. return stmt;
  1918. }
  1919. if (stmt->kind == AstNode_EmptyStmt) {
  1920. syntax_error(stmt, "Expected a non-empty statement");
  1921. }
  1922. GB_ASSERT(is_ast_node_stmt(stmt) || is_ast_node_decl(stmt));
  1923. Token open = ast_node_token(stmt);
  1924. Token close = ast_node_token(stmt);
  1925. Array<AstNode *> stmts = make_ast_node_array(f, 1);
  1926. array_add(&stmts, stmt);
  1927. return ast_block_stmt(f, stmts, open, close);
  1928. }
  1929. AstNode *parse_operand(AstFile *f, bool lhs) {
  1930. AstNode *operand = nullptr; // Operand
  1931. switch (f->curr_token.kind) {
  1932. case Token_Ident:
  1933. return parse_ident(f);
  1934. case Token_Undef:
  1935. return ast_undef(f, expect_token(f, Token_Undef));
  1936. case Token_context:
  1937. return ast_implicit(f, expect_token(f, Token_context));
  1938. case Token_Integer:
  1939. case Token_Float:
  1940. case Token_Imag:
  1941. case Token_Rune:
  1942. return ast_basic_lit(f, advance_token(f));
  1943. case Token_size_of:
  1944. case Token_align_of:
  1945. case Token_offset_of:
  1946. case Token_type_info_of:
  1947. return parse_call_expr(f, ast_implicit(f, advance_token(f)));
  1948. case Token_String: {
  1949. Token token = advance_token(f);
  1950. if (f->curr_token.kind == Token_String) {
  1951. // NOTE(bill): Allow neighbouring string literals to be merge together to
  1952. // become one big string
  1953. String s = f->curr_token.string;
  1954. Array<u8> data = {};
  1955. array_init_count(&data, heap_allocator(), token.string.len+s.len);
  1956. gb_memmove(data.data, token.string.text, token.string.len);
  1957. while (f->curr_token.kind == Token_String) {
  1958. String s = f->curr_token.string;
  1959. isize old_count = data.count;
  1960. array_resize(&data, data.count + s.len);
  1961. gb_memmove(data.data+old_count, s.text, s.len);
  1962. advance_token(f);
  1963. }
  1964. token.string = make_string(data.data, data.count);
  1965. array_add(&f->tokenizer.allocated_strings, token.string);
  1966. }
  1967. return ast_basic_lit(f, token);
  1968. }
  1969. case Token_OpenParen: {
  1970. Token open, close;
  1971. // NOTE(bill): Skip the Paren Expression
  1972. open = expect_token(f, Token_OpenParen);
  1973. f->expr_level++;
  1974. operand = parse_expr(f, false);
  1975. f->expr_level--;
  1976. close = expect_token(f, Token_CloseParen);
  1977. return ast_paren_expr(f, operand, open, close);
  1978. }
  1979. case Token_Hash: {
  1980. Token token = expect_token(f, Token_Hash);
  1981. if (allow_token(f, Token_type)) {
  1982. return ast_helper_type(f, token, parse_type(f));
  1983. }
  1984. Token name = expect_token(f, Token_Ident);
  1985. if (name.string == "run") {
  1986. AstNode *expr = parse_expr(f, false);
  1987. operand = ast_run_expr(f, token, name, expr);
  1988. if (unparen_expr(expr)->kind != AstNode_CallExpr) {
  1989. error(expr, "#run can only be applied to procedure calls");
  1990. operand = ast_bad_expr(f, token, f->curr_token);
  1991. }
  1992. warning(token, "#run is not yet implemented");
  1993. } else if (name.string == "file") { return ast_basic_directive(f, token, name.string);
  1994. } else if (name.string == "line") { return ast_basic_directive(f, token, name.string);
  1995. } else if (name.string == "procedure") { return ast_basic_directive(f, token, name.string);
  1996. } else if (name.string == "caller_location") { return ast_basic_directive(f, token, name.string);
  1997. } else if (name.string == "location") {
  1998. AstNode *tag = ast_basic_directive(f, token, name.string);
  1999. return parse_call_expr(f, tag);
  2000. } else {
  2001. operand = ast_tag_expr(f, token, name, parse_expr(f, false));
  2002. }
  2003. return operand;
  2004. }
  2005. // Parse Procedure Type or Literal
  2006. case Token_proc: {
  2007. Token token = expect_token(f, Token_proc);
  2008. String link_name = {};
  2009. AstNode *type = parse_proc_type(f, token, &link_name);
  2010. if (f->allow_type && f->expr_level < 0) {
  2011. return type;
  2012. }
  2013. u64 tags = type->ProcType.tags;
  2014. if (allow_token(f, Token_Undef)) {
  2015. return ast_proc_lit(f, type, nullptr, tags, link_name);
  2016. } else if (f->curr_token.kind == Token_OpenBrace) {
  2017. if ((tags & ProcTag_foreign) != 0) {
  2018. syntax_error(token, "A procedure tagged as `#foreign` cannot have a body");
  2019. }
  2020. AstNode *curr_proc = f->curr_proc;
  2021. AstNode *body = nullptr;
  2022. f->curr_proc = type;
  2023. body = parse_body(f);
  2024. f->curr_proc = curr_proc;
  2025. return ast_proc_lit(f, type, body, tags, link_name);
  2026. } else if (allow_token(f, Token_do)) {
  2027. if ((tags & ProcTag_foreign) != 0) {
  2028. syntax_error(token, "A procedure tagged as `#foreign` cannot have a body");
  2029. }
  2030. AstNode *curr_proc = f->curr_proc;
  2031. AstNode *body = nullptr;
  2032. f->curr_proc = type;
  2033. body = convert_stmt_to_body(f, parse_stmt(f));
  2034. f->curr_proc = curr_proc;
  2035. return ast_proc_lit(f, type, body, tags, link_name);
  2036. }
  2037. if ((tags & ProcTag_foreign) != 0) {
  2038. return ast_proc_lit(f, type, nullptr, tags, link_name);
  2039. }
  2040. if (tags != 0) {
  2041. // syntax_error(token, "A procedure type cannot have tags");
  2042. }
  2043. return type;
  2044. }
  2045. // Check for Types
  2046. case Token_Dollar: {
  2047. Token token = expect_token(f, Token_Dollar);
  2048. AstNode *type = parse_ident(f);
  2049. AstNode *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_type_of: {
  2056. AstNode *i = ast_implicit(f, expect_token(f, Token_type_of));
  2057. AstNode *type = parse_call_expr(f, i);
  2058. while (f->curr_token.kind == Token_Period) {
  2059. Token token = advance_token(f);
  2060. AstNode *sel = parse_ident(f);
  2061. type = ast_selector_expr(f, token, type, sel);
  2062. }
  2063. return type;
  2064. } break;
  2065. case Token_Pointer: {
  2066. Token token = expect_token(f, Token_Pointer);
  2067. AstNode *elem = parse_type(f);
  2068. return ast_pointer_type(f, token, elem);
  2069. } break;
  2070. case Token_OpenBracket: {
  2071. Token token = expect_token(f, Token_OpenBracket);
  2072. AstNode *count_expr = nullptr;
  2073. bool is_vector = false;
  2074. if (f->curr_token.kind == Token_Ellipsis) {
  2075. count_expr = ast_unary_expr(f, expect_token(f, Token_Ellipsis), nullptr);
  2076. } else if (allow_token(f, Token_vector)) {
  2077. if (f->curr_token.kind != Token_CloseBracket) {
  2078. f->expr_level++;
  2079. count_expr = parse_expr(f, false);
  2080. f->expr_level--;
  2081. } else {
  2082. syntax_error(f->curr_token, "Vector type missing count");
  2083. }
  2084. is_vector = true;
  2085. } else if (allow_token(f, Token_dynamic)) {
  2086. expect_token(f, Token_CloseBracket);
  2087. return ast_dynamic_array_type(f, token, parse_type(f));
  2088. } else if (f->curr_token.kind != Token_CloseBracket) {
  2089. f->expr_level++;
  2090. count_expr = parse_expr(f, false);
  2091. f->expr_level--;
  2092. }
  2093. expect_token(f, Token_CloseBracket);
  2094. if (is_vector) {
  2095. return ast_vector_type(f, token, count_expr, parse_type(f));
  2096. }
  2097. return ast_array_type(f, token, count_expr, parse_type(f));
  2098. } break;
  2099. case Token_map: {
  2100. Token token = expect_token(f, Token_map);
  2101. AstNode *key = nullptr;
  2102. AstNode *value = nullptr;
  2103. Token open, close;
  2104. open = expect_token_after(f, Token_OpenBracket, "map");
  2105. key = parse_expr(f, true);
  2106. close = expect_token(f, Token_CloseBracket);
  2107. value = parse_type(f);
  2108. return ast_map_type(f, token, key, value);
  2109. } break;
  2110. case Token_struct: {
  2111. Token token = expect_token(f, Token_struct);
  2112. AstNode *polymorphic_params = nullptr;
  2113. bool is_packed = false;
  2114. bool is_ordered = false;
  2115. bool is_raw_union = false;
  2116. AstNode *align = nullptr;
  2117. if (allow_token(f, Token_OpenParen)) {
  2118. isize param_count = 0;
  2119. polymorphic_params = parse_field_list(f, &param_count, 0, Token_CloseParen, false, true);
  2120. if (param_count == 0) {
  2121. syntax_error(polymorphic_params, "Expected at least 1 polymorphic parametric");
  2122. polymorphic_params = nullptr;
  2123. }
  2124. expect_token_after(f, Token_CloseParen, "parameter list");
  2125. }
  2126. isize 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 == "ordered") {
  2136. if (is_ordered) {
  2137. syntax_error(tag, "Duplicate struct tag `#%.*s`", LIT(tag.string));
  2138. }
  2139. is_ordered = true;
  2140. } else if (tag.string == "align") {
  2141. if (align) {
  2142. syntax_error(tag, "Duplicate struct tag `#%.*s`", LIT(tag.string));
  2143. }
  2144. align = parse_expr(f, true);
  2145. } else if (tag.string == "raw_union") {
  2146. if (is_raw_union) {
  2147. syntax_error(tag, "Duplicate struct tag `#%.*s`", LIT(tag.string));
  2148. }
  2149. is_raw_union = true;
  2150. } else {
  2151. syntax_error(tag, "Invalid struct tag `#%.*s`", LIT(tag.string));
  2152. }
  2153. }
  2154. f->expr_level = prev_level;
  2155. if (is_packed && is_ordered) {
  2156. syntax_error(token, "`#ordered` is not needed with `#packed` which implies ordering");
  2157. }
  2158. if (is_raw_union && is_packed) {
  2159. is_packed = false;
  2160. syntax_error(token, "`#raw_union` cannot also be `#packed`");
  2161. }
  2162. if (is_raw_union && is_ordered) {
  2163. is_ordered = false;
  2164. syntax_error(token, "`#raw_union` cannot also be `#ordered`");
  2165. }
  2166. Token open = expect_token_after(f, Token_OpenBrace, "struct");
  2167. isize name_count = 0;
  2168. AstNode *fields = parse_struct_field_list(f, &name_count);
  2169. Token close = expect_token(f, Token_CloseBrace);
  2170. Array<AstNode *> decls = {};
  2171. if (fields != nullptr) {
  2172. GB_ASSERT(fields->kind == AstNode_FieldList);
  2173. decls = fields->FieldList.list;
  2174. }
  2175. return ast_struct_type(f, token, decls, name_count, polymorphic_params, is_packed, is_ordered, is_raw_union, align);
  2176. } break;
  2177. case Token_union: {
  2178. Token token = expect_token(f, Token_union);
  2179. Token open = expect_token_after(f, Token_OpenBrace, "union");
  2180. Array<AstNode *> variants = make_ast_node_array(f);
  2181. isize total_decl_name_count = 0;
  2182. AstNode *align = nullptr;
  2183. CommentGroup docs = f->lead_comment;
  2184. Token start_token = f->curr_token;
  2185. while (allow_token(f, Token_Hash)) {
  2186. Token tag = expect_token_after(f, Token_Ident, "#");
  2187. if (tag.string == "align") {
  2188. if (align) {
  2189. syntax_error(tag, "Duplicate union tag `#%.*s`", LIT(tag.string));
  2190. }
  2191. align = parse_expr(f, true);
  2192. } else {
  2193. syntax_error(tag, "Invalid union tag `#%.*s`", LIT(tag.string));
  2194. }
  2195. }
  2196. while (f->curr_token.kind != Token_CloseBrace &&
  2197. f->curr_token.kind != Token_EOF) {
  2198. AstNode *type = parse_type(f);
  2199. if (type->kind != AstNode_BadExpr) {
  2200. array_add(&variants, type);
  2201. }
  2202. if (!allow_token(f, Token_Comma)) {
  2203. break;
  2204. }
  2205. }
  2206. Token close = expect_token(f, Token_CloseBrace);
  2207. return ast_union_type(f, token, variants, align);
  2208. } break;
  2209. case Token_enum: {
  2210. Token token = expect_token(f, Token_enum);
  2211. AstNode *base_type = nullptr;
  2212. if (f->curr_token.kind != Token_OpenBrace) {
  2213. base_type = parse_type(f);
  2214. }
  2215. Token open = expect_token(f, Token_OpenBrace);
  2216. Array<AstNode *> values = parse_element_list(f);
  2217. Token close = expect_token(f, Token_CloseBrace);
  2218. return ast_enum_type(f, token, base_type, values);
  2219. } break;
  2220. case Token_bit_field: {
  2221. Token token = expect_token(f, Token_bit_field);
  2222. Array<AstNode *> fields = make_ast_node_array(f);
  2223. AstNode *align = nullptr;
  2224. Token open, close;
  2225. isize prev_level = f->expr_level;
  2226. f->expr_level = -1;
  2227. while (allow_token(f, Token_Hash)) {
  2228. Token tag = expect_token_after(f, Token_Ident, "#");
  2229. if (tag.string == "align") {
  2230. if (align) {
  2231. syntax_error(tag, "Duplicate bit_field tag `#%.*s`", LIT(tag.string));
  2232. }
  2233. align = parse_expr(f, true);
  2234. } else {
  2235. syntax_error(tag, "Invalid bit_field tag `#%.*s`", LIT(tag.string));
  2236. }
  2237. }
  2238. f->expr_level = prev_level;
  2239. open = expect_token_after(f, Token_OpenBrace, "bit_field");
  2240. while (f->curr_token.kind != Token_EOF &&
  2241. f->curr_token.kind != Token_CloseBrace) {
  2242. AstNode *name = parse_ident(f);
  2243. Token colon = expect_token(f, Token_Colon);
  2244. AstNode *value = parse_expr(f, true);
  2245. AstNode *field = ast_field_value(f, name, value, colon);
  2246. array_add(&fields, field);
  2247. if (f->curr_token.kind != Token_Comma) {
  2248. break;
  2249. }
  2250. advance_token(f);
  2251. }
  2252. close = expect_token(f, Token_CloseBrace);
  2253. return ast_bit_field_type(f, token, fields, align);
  2254. } break;
  2255. default: {
  2256. #if 0
  2257. AstNode *type = parse_type_or_ident(f);
  2258. if (type != nullptr) {
  2259. // TODO(bill): Is this correct???
  2260. // NOTE(bill): Sanity check as identifiers should be handled already
  2261. TokenPos pos = ast_node_token(type).pos;
  2262. GB_ASSERT_MSG(type->kind != AstNode_Ident, "Type cannot be identifier %.*s(%td:%td)", LIT(pos.file), pos.line, pos.column);
  2263. return type;
  2264. }
  2265. #endif
  2266. break;
  2267. }
  2268. }
  2269. return nullptr;
  2270. }
  2271. bool is_literal_type(AstNode *node) {
  2272. node = unparen_expr(node);
  2273. switch (node->kind) {
  2274. case AstNode_BadExpr:
  2275. case AstNode_Ident:
  2276. case AstNode_SelectorExpr:
  2277. case AstNode_ArrayType:
  2278. case AstNode_VectorType:
  2279. case AstNode_StructType:
  2280. case AstNode_UnionType:
  2281. case AstNode_EnumType:
  2282. case AstNode_DynamicArrayType:
  2283. case AstNode_MapType:
  2284. case AstNode_CallExpr:
  2285. return true;
  2286. }
  2287. return false;
  2288. }
  2289. AstNode *parse_call_expr(AstFile *f, AstNode *operand) {
  2290. Array<AstNode *> args = make_ast_node_array(f);
  2291. Token open_paren, close_paren;
  2292. Token ellipsis = {};
  2293. f->expr_level++;
  2294. open_paren = expect_token(f, Token_OpenParen);
  2295. while (f->curr_token.kind != Token_CloseParen &&
  2296. f->curr_token.kind != Token_EOF &&
  2297. ellipsis.pos.line == 0) {
  2298. if (f->curr_token.kind == Token_Comma) {
  2299. syntax_error(f->curr_token, "Expected an expression not ,");
  2300. } else if (f->curr_token.kind == Token_Eq) {
  2301. syntax_error(f->curr_token, "Expected an expression not =");
  2302. }
  2303. bool prefix_ellipsis = false;
  2304. if (f->curr_token.kind == Token_Ellipsis) {
  2305. prefix_ellipsis = true;
  2306. ellipsis = f->curr_token;
  2307. advance_token(f);
  2308. }
  2309. AstNode *arg = parse_expr(f, false);
  2310. if (f->curr_token.kind == Token_Eq) {
  2311. Token eq = expect_token(f, Token_Eq);
  2312. if (prefix_ellipsis) {
  2313. syntax_error(ellipsis, "`..` must be applied to value rather than the field name");
  2314. }
  2315. if (f->curr_token.kind == Token_Ellipsis) {
  2316. ellipsis = f->curr_token;
  2317. advance_token(f);
  2318. }
  2319. AstNode *value = parse_value(f);
  2320. arg = ast_field_value(f, arg, value, eq);
  2321. }
  2322. array_add(&args, arg);
  2323. if (!allow_token(f, Token_Comma)) {
  2324. break;
  2325. }
  2326. }
  2327. f->expr_level--;
  2328. close_paren = expect_closing(f, Token_CloseParen, str_lit("argument list"));
  2329. return ast_call_expr(f, operand, args, open_paren, close_paren, ellipsis);
  2330. }
  2331. AstNode *parse_macro_call_expr(AstFile *f, AstNode *operand) {
  2332. Array<AstNode *> args = make_ast_node_array(f);
  2333. Token bang, open_paren, close_paren;
  2334. bang = expect_token(f, Token_Not);
  2335. f->expr_level++;
  2336. open_paren = expect_token(f, Token_OpenParen);
  2337. while (f->curr_token.kind != Token_CloseParen &&
  2338. f->curr_token.kind != Token_EOF) {
  2339. if (f->curr_token.kind == Token_Comma) {
  2340. syntax_error(f->curr_token, "Expected an expression not a ,");
  2341. }
  2342. AstNode *arg = parse_expr(f, false);
  2343. array_add(&args, arg);
  2344. if (!allow_token(f, Token_Comma)) {
  2345. break;
  2346. }
  2347. }
  2348. f->expr_level--;
  2349. close_paren = expect_closing(f, Token_CloseParen, str_lit("argument list"));
  2350. return ast_macro_call_expr(f, operand, bang, args, open_paren, close_paren);
  2351. }
  2352. AstNode *parse_atom_expr(AstFile *f, AstNode *operand, bool lhs) {
  2353. if (operand == nullptr) {
  2354. if (f->allow_type) return nullptr;
  2355. Token begin = f->curr_token;
  2356. syntax_error(begin, "Expected an operand");
  2357. fix_advance_to_next_stmt(f);
  2358. operand = ast_bad_expr(f, begin, f->curr_token);
  2359. }
  2360. bool loop = true;
  2361. while (loop) {
  2362. switch (f->curr_token.kind) {
  2363. case Token_OpenParen:
  2364. operand = parse_call_expr(f, operand);
  2365. break;
  2366. case Token_Not:
  2367. operand = parse_macro_call_expr(f, operand);
  2368. break;
  2369. case Token_Period: {
  2370. Token token = advance_token(f);
  2371. switch (f->curr_token.kind) {
  2372. case Token_Ident:
  2373. operand = ast_selector_expr(f, token, operand, parse_ident(f));
  2374. break;
  2375. case Token_Integer:
  2376. operand = ast_selector_expr(f, token, operand, parse_expr(f, lhs));
  2377. break;
  2378. case Token_OpenParen: {
  2379. Token open = expect_token(f, Token_OpenParen);
  2380. AstNode *type = parse_type(f);
  2381. Token close = expect_token(f, Token_CloseParen);
  2382. operand = ast_type_assertion(f, operand, token, type);
  2383. } break;
  2384. default:
  2385. syntax_error(f->curr_token, "Expected a selector");
  2386. advance_token(f);
  2387. operand = ast_bad_expr(f, ast_node_token(operand), f->curr_token);
  2388. // operand = ast_selector_expr(f, f->curr_token, operand, nullptr);
  2389. break;
  2390. }
  2391. } break;
  2392. case Token_OpenBracket: {
  2393. if (lhs) {
  2394. // TODO(bill): Handle this
  2395. }
  2396. bool prev_allow_range = f->allow_range;
  2397. f->allow_range = false;
  2398. Token open = {}, close = {}, interval = {};
  2399. AstNode *indices[3] = {};
  2400. isize ellipsis_count = 0;
  2401. Token ellipses[2] = {};
  2402. f->expr_level++;
  2403. open = expect_token(f, Token_OpenBracket);
  2404. if (f->curr_token.kind != Token_Ellipsis &&
  2405. f->curr_token.kind != Token_HalfClosed) {
  2406. indices[0] = parse_expr(f, false);
  2407. }
  2408. bool is_index = true;
  2409. while ((f->curr_token.kind == Token_Ellipsis ||
  2410. f->curr_token.kind == Token_HalfClosed)
  2411. && ellipsis_count < gb_count_of(ellipses)) {
  2412. ellipses[ellipsis_count++] = advance_token(f);
  2413. if (f->curr_token.kind != Token_Ellipsis &&
  2414. f->curr_token.kind != Token_HalfClosed &&
  2415. f->curr_token.kind != Token_CloseBracket &&
  2416. f->curr_token.kind != Token_EOF) {
  2417. indices[ellipsis_count] = parse_expr(f, false);
  2418. }
  2419. }
  2420. f->expr_level--;
  2421. close = expect_token(f, Token_CloseBracket);
  2422. if (ellipsis_count > 0) {
  2423. bool index3 = false;
  2424. if (ellipsis_count == 2) {
  2425. index3 = true;
  2426. // 2nd and 3rd index must be present
  2427. if (indices[1] == nullptr) {
  2428. error(ellipses[0], "2nd index required in 3-index slice expression");
  2429. indices[1] = ast_bad_expr(f, ellipses[0], ellipses[1]);
  2430. }
  2431. if (indices[2] == nullptr) {
  2432. error(ellipses[1], "3rd index required in 3-index slice expression");
  2433. indices[2] = ast_bad_expr(f, ellipses[1], close);
  2434. }
  2435. }
  2436. operand = ast_slice_expr(f, operand, open, close, ellipses[0], ellipses[1], index3, indices[0], indices[1], indices[2]);
  2437. } else {
  2438. operand = ast_index_expr(f, operand, indices[0], open, close);
  2439. }
  2440. f->allow_range = prev_allow_range;
  2441. } break;
  2442. case Token_Pointer: // Deference
  2443. operand = ast_deref_expr(f, operand, expect_token(f, Token_Pointer));
  2444. break;
  2445. case Token_OpenBrace:
  2446. if (!lhs && is_literal_type(operand) && f->expr_level >= 0) {
  2447. operand = parse_literal_value(f, operand);
  2448. } else {
  2449. loop = false;
  2450. }
  2451. break;
  2452. default:
  2453. loop = false;
  2454. break;
  2455. }
  2456. lhs = false; // NOTE(bill): 'tis not lhs anymore
  2457. }
  2458. return operand;
  2459. }
  2460. AstNode *parse_unary_expr(AstFile *f, bool lhs) {
  2461. switch (f->curr_token.kind) {
  2462. case Token_Add:
  2463. case Token_Sub:
  2464. case Token_Not:
  2465. case Token_Xor:
  2466. case Token_And: {
  2467. Token op = advance_token(f);
  2468. return ast_unary_expr(f, op, parse_unary_expr(f, lhs));
  2469. } break;
  2470. case Token_cast: {
  2471. Token token = expect_token(f, Token_cast);
  2472. Token open = expect_token_after(f, Token_OpenParen, "cast");
  2473. AstNode *type = parse_type(f);
  2474. Token close = expect_token(f, Token_CloseParen);
  2475. return ast_type_cast(f, token, type, parse_unary_expr(f, lhs));
  2476. } break;
  2477. case Token_transmute: {
  2478. Token token = expect_token(f, Token_transmute);
  2479. Token open = expect_token_after(f, Token_OpenParen, "transmute");
  2480. AstNode *type = parse_type(f);
  2481. Token close = expect_token(f, Token_CloseParen);
  2482. return ast_type_cast(f, token, type, parse_unary_expr(f, lhs));
  2483. } break;
  2484. }
  2485. AstNode *operand = parse_operand(f, lhs);
  2486. return parse_atom_expr(f, operand, lhs);
  2487. }
  2488. bool is_ast_node_a_range(AstNode *expr) {
  2489. if (expr == nullptr) {
  2490. return false;
  2491. }
  2492. if (expr->kind != AstNode_BinaryExpr) {
  2493. return false;
  2494. }
  2495. TokenKind op = expr->BinaryExpr.op.kind;
  2496. switch (op) {
  2497. case Token_Ellipsis:
  2498. case Token_HalfClosed:
  2499. return true;
  2500. }
  2501. return false;
  2502. }
  2503. // NOTE(bill): result == priority
  2504. i32 token_precedence(AstFile *f, TokenKind t) {
  2505. switch (t) {
  2506. case Token_Question:
  2507. return 1;
  2508. case Token_Ellipsis:
  2509. case Token_HalfClosed:
  2510. if (f->allow_range) {
  2511. return 2;
  2512. }
  2513. return 0;
  2514. case Token_CmpOr:
  2515. return 3;
  2516. case Token_CmpAnd:
  2517. return 4;
  2518. case Token_CmpEq:
  2519. case Token_NotEq:
  2520. case Token_Lt:
  2521. case Token_Gt:
  2522. case Token_LtEq:
  2523. case Token_GtEq:
  2524. return 5;
  2525. case Token_Add:
  2526. case Token_Sub:
  2527. case Token_Or:
  2528. case Token_Xor:
  2529. return 6;
  2530. case Token_Mul:
  2531. case Token_Quo:
  2532. case Token_Mod:
  2533. case Token_ModMod:
  2534. case Token_And:
  2535. case Token_AndNot:
  2536. case Token_Shl:
  2537. case Token_Shr:
  2538. return 7;
  2539. }
  2540. return 0;
  2541. }
  2542. AstNode *parse_binary_expr(AstFile *f, bool lhs, i32 prec_in) {
  2543. AstNode *expr = parse_unary_expr(f, lhs);
  2544. for (i32 prec = token_precedence(f, f->curr_token.kind); prec >= prec_in; prec--) {
  2545. for (;;) {
  2546. Token op = f->curr_token;
  2547. i32 op_prec = token_precedence(f, op.kind);
  2548. if (op_prec != prec) {
  2549. // NOTE(bill): This will also catch operators that are not valid "binary" operators
  2550. break;
  2551. }
  2552. expect_operator(f); // NOTE(bill): error checks too
  2553. if (op.kind == Token_Question) {
  2554. AstNode *cond = expr;
  2555. // Token_Question
  2556. AstNode *x = parse_expr(f, lhs);
  2557. Token token_c = expect_token(f, Token_Colon);
  2558. AstNode *y = parse_expr(f, lhs);
  2559. expr = ast_ternary_expr(f, cond, x, y);
  2560. } else {
  2561. AstNode *right = parse_binary_expr(f, false, prec+1);
  2562. if (right == nullptr) {
  2563. syntax_error(op, "Expected expression on the right-hand side of the binary operator");
  2564. }
  2565. expr = ast_binary_expr(f, op, expr, right);
  2566. }
  2567. lhs = false;
  2568. }
  2569. }
  2570. return expr;
  2571. }
  2572. AstNode *parse_expr(AstFile *f, bool lhs) {
  2573. return parse_binary_expr(f, lhs, 0+1);
  2574. }
  2575. Array<AstNode *> parse_expr_list(AstFile *f, bool lhs) {
  2576. Array<AstNode *> list = make_ast_node_array(f);
  2577. for (;;) {
  2578. AstNode *e = parse_expr(f, lhs);
  2579. array_add(&list, e);
  2580. if (f->curr_token.kind != Token_Comma ||
  2581. f->curr_token.kind == Token_EOF) {
  2582. break;
  2583. }
  2584. advance_token(f);
  2585. }
  2586. return list;
  2587. }
  2588. Array<AstNode *> parse_lhs_expr_list(AstFile *f) {
  2589. return parse_expr_list(f, true);
  2590. }
  2591. Array<AstNode *> parse_rhs_expr_list(AstFile *f) {
  2592. return parse_expr_list(f, false);
  2593. }
  2594. Array<AstNode *> parse_ident_list(AstFile *f) {
  2595. Array<AstNode *> list = make_ast_node_array(f);
  2596. do {
  2597. array_add(&list, parse_ident(f));
  2598. if (f->curr_token.kind != Token_Comma ||
  2599. f->curr_token.kind == Token_EOF) {
  2600. break;
  2601. }
  2602. advance_token(f);
  2603. } while (true);
  2604. return list;
  2605. }
  2606. AstNode *parse_type_attempt(AstFile *f) {
  2607. AstNode *type = parse_type_or_ident(f);
  2608. if (type != nullptr) {
  2609. // TODO(bill): Handle?
  2610. }
  2611. return type;
  2612. }
  2613. AstNode *parse_type(AstFile *f) {
  2614. AstNode *type = parse_type_attempt(f);
  2615. if (type == nullptr) {
  2616. Token token = advance_token(f);
  2617. syntax_error(token, "Expected a type");
  2618. return ast_bad_expr(f, token, f->curr_token);
  2619. }
  2620. return type;
  2621. }
  2622. void parse_foreign_block_decl(AstFile *f, Array<AstNode *> *decls) {
  2623. AstNode *decl = parse_stmt(f);
  2624. switch (decl->kind) {
  2625. case AstNode_EmptyStmt:
  2626. case AstNode_BadStmt:
  2627. case AstNode_BadDecl:
  2628. return;
  2629. case AstNode_ValueDecl:
  2630. array_add(decls, decl);
  2631. return;
  2632. /* fallthrough */
  2633. default:
  2634. error(decl, "Foreign blocks only allow procedure and variable declarations");
  2635. return;
  2636. }
  2637. }
  2638. AstNode *parse_foreign_block(AstFile *f) {
  2639. CommentGroup docs = f->lead_comment;
  2640. Token token = expect_token(f, Token_foreign);
  2641. AstNode *foreign_library = parse_ident(f);
  2642. Token open = {};
  2643. Token close = {};
  2644. Array<AstNode *> decls = make_ast_node_array(f);
  2645. bool prev_in_foreign_block = f->in_foreign_block;
  2646. defer (f->in_foreign_block = prev_in_foreign_block);
  2647. f->in_foreign_block = true;
  2648. if (f->curr_token.kind != Token_OpenBrace) {
  2649. parse_foreign_block_decl(f, &decls);
  2650. } else {
  2651. open = expect_token(f, Token_OpenBrace);
  2652. while (f->curr_token.kind != Token_CloseBrace &&
  2653. f->curr_token.kind != Token_EOF) {
  2654. parse_foreign_block_decl(f, &decls);
  2655. }
  2656. close = expect_token(f, Token_CloseBrace);
  2657. }
  2658. AstNode *decl = ast_foreign_block_decl(f, token, foreign_library, open, close, decls, docs);
  2659. expect_semicolon(f, decl);
  2660. return decl;
  2661. }
  2662. AstNode *parse_value_decl(AstFile *f, Array<AstNode *> names, CommentGroup docs) {
  2663. bool is_mutable = true;
  2664. AstNode *type = nullptr;
  2665. Array<AstNode *> values = {};
  2666. expect_token_after(f, Token_Colon, "identifier list");
  2667. if (f->curr_token.kind == Token_type) {
  2668. type = ast_type_type(f, advance_token(f), nullptr);
  2669. is_mutable = false;
  2670. } else {
  2671. type = parse_type_attempt(f);
  2672. }
  2673. if (f->curr_token.kind == Token_Eq ||
  2674. f->curr_token.kind == Token_Colon) {
  2675. Token sep = {};
  2676. if (!is_mutable) {
  2677. sep = expect_token_after(f, Token_Colon, "type");
  2678. } else {
  2679. sep = advance_token(f);
  2680. is_mutable = sep.kind != Token_Colon;
  2681. }
  2682. values = parse_rhs_expr_list(f);
  2683. if (values.count > names.count) {
  2684. syntax_error(f->curr_token, "Too many values on the right hand side of the declaration");
  2685. } else if (values.count < names.count && !is_mutable) {
  2686. syntax_error(f->curr_token, "All constant declarations must be defined");
  2687. } else if (values.count == 0) {
  2688. syntax_error(f->curr_token, "Expected an expression for this declaration");
  2689. }
  2690. }
  2691. if (is_mutable) {
  2692. if (type == nullptr && values.count == 0) {
  2693. syntax_error(f->curr_token, "Missing variable type or initialization");
  2694. return ast_bad_decl(f, f->curr_token, f->curr_token);
  2695. }
  2696. } else {
  2697. if (type == nullptr && values.count == 0 && names.count > 0) {
  2698. syntax_error(f->curr_token, "Missing constant value");
  2699. return ast_bad_decl(f, f->curr_token, f->curr_token);
  2700. }
  2701. }
  2702. if (values.data == nullptr) {
  2703. values = make_ast_node_array(f);
  2704. }
  2705. if (f->expr_level >= 0) {
  2706. AstNode *end = nullptr;
  2707. if (!is_mutable && values.count > 0) {
  2708. end = values[values.count-1];
  2709. }
  2710. if (f->curr_token.kind == Token_CloseBrace &&
  2711. f->curr_token.pos.line == f->prev_token.pos.line) {
  2712. } else {
  2713. expect_semicolon(f, end);
  2714. }
  2715. }
  2716. return ast_value_decl(f, names, type, values, is_mutable, docs, f->line_comment);
  2717. }
  2718. AstNode *parse_simple_stmt(AstFile *f, StmtAllowFlag flags) {
  2719. Token token = f->curr_token;
  2720. CommentGroup docs = f->lead_comment;
  2721. Array<AstNode *> lhs = parse_lhs_expr_list(f);
  2722. token = f->curr_token;
  2723. switch (token.kind) {
  2724. case Token_Eq:
  2725. case Token_AddEq:
  2726. case Token_SubEq:
  2727. case Token_MulEq:
  2728. case Token_QuoEq:
  2729. case Token_ModEq:
  2730. case Token_ModModEq:
  2731. case Token_AndEq:
  2732. case Token_OrEq:
  2733. case Token_XorEq:
  2734. case Token_ShlEq:
  2735. case Token_ShrEq:
  2736. case Token_AndNotEq:
  2737. case Token_CmpAndEq:
  2738. case Token_CmpOrEq:
  2739. {
  2740. if (f->curr_proc == nullptr) {
  2741. syntax_error(f->curr_token, "You cannot use a simple statement in the file scope");
  2742. return ast_bad_stmt(f, f->curr_token, f->curr_token);
  2743. }
  2744. advance_token(f);
  2745. Array<AstNode *> rhs = parse_rhs_expr_list(f);
  2746. if (rhs.count == 0) {
  2747. syntax_error(token, "No right-hand side in assignment statement.");
  2748. return ast_bad_stmt(f, token, f->curr_token);
  2749. }
  2750. return ast_assign_stmt(f, token, lhs, rhs);
  2751. } break;
  2752. case Token_in:
  2753. if (flags&StmtAllowFlag_In) {
  2754. allow_token(f, Token_in);
  2755. bool prev_allow_range = f->allow_range;
  2756. f->allow_range = true;
  2757. AstNode *expr = parse_expr(f, false);
  2758. f->allow_range = prev_allow_range;
  2759. Array<AstNode *> rhs = make_ast_node_array(f, 1);
  2760. array_add(&rhs, expr);
  2761. return ast_assign_stmt(f, token, lhs, rhs);
  2762. }
  2763. break;
  2764. case Token_Colon:
  2765. if ((flags&StmtAllowFlag_Label) && lhs.count == 1) {
  2766. TokenKind next = look_ahead_token_kind(f, 1);
  2767. switch (next) {
  2768. case Token_for:
  2769. case Token_switch: {
  2770. expect_token_after(f, Token_Colon, "identifier list");
  2771. AstNode *name = lhs[0];
  2772. AstNode *label = ast_label_decl(f, ast_node_token(name), name);
  2773. AstNode *stmt = parse_stmt(f);
  2774. #define _SET_LABEL(Kind_, label_) case GB_JOIN2(AstNode_, Kind_): (stmt->Kind_).label = label_; break
  2775. switch (stmt->kind) {
  2776. _SET_LABEL(ForStmt, label);
  2777. _SET_LABEL(RangeStmt, label);
  2778. _SET_LABEL(SwitchStmt, label);
  2779. _SET_LABEL(TypeSwitchStmt, label);
  2780. default:
  2781. syntax_error(token, "Labels can only be applied to a loop or match statement");
  2782. break;
  2783. }
  2784. #undef _SET_LABEL
  2785. return stmt;
  2786. } break;
  2787. }
  2788. }
  2789. return parse_value_decl(f, lhs, docs);
  2790. }
  2791. if (lhs.count > 1) {
  2792. syntax_error(token, "Expected 1 expression");
  2793. return ast_bad_stmt(f, token, f->curr_token);
  2794. }
  2795. #if 0
  2796. switch (token.kind) {
  2797. case Token_Inc:
  2798. case Token_Dec:
  2799. advance_token(f);
  2800. return ast_inc_dec_stmt(f, token, lhs[0]);
  2801. }
  2802. #endif
  2803. return ast_expr_stmt(f, lhs[0]);
  2804. }
  2805. AstNode *parse_block_stmt(AstFile *f, b32 is_when) {
  2806. if (!is_when && f->curr_proc == nullptr) {
  2807. syntax_error(f->curr_token, "You cannot use a block statement in the file scope");
  2808. return ast_bad_stmt(f, f->curr_token, f->curr_token);
  2809. }
  2810. return parse_body(f);
  2811. }
  2812. AstNode *parse_results(AstFile *f) {
  2813. if (!allow_token(f, Token_ArrowRight)) {
  2814. return nullptr;
  2815. }
  2816. isize prev_level = f->expr_level;
  2817. defer (f->expr_level = prev_level);
  2818. // f->expr_level = -1;
  2819. if (f->curr_token.kind != Token_OpenParen) {
  2820. CommentGroup empty_group = {};
  2821. Token begin_token = f->curr_token;
  2822. Array<AstNode *> empty_names = {};
  2823. Array<AstNode *> list = make_ast_node_array(f, 1);
  2824. AstNode *type = parse_type(f);
  2825. array_add(&list, ast_field(f, empty_names, type, nullptr, 0, empty_group, empty_group));
  2826. return ast_field_list(f, begin_token, list);
  2827. }
  2828. AstNode *list = nullptr;
  2829. expect_token(f, Token_OpenParen);
  2830. list = parse_field_list(f, nullptr, 0, Token_CloseParen, true, false);
  2831. expect_token_after(f, Token_CloseParen, "parameter list");
  2832. return list;
  2833. }
  2834. AstNode *parse_proc_type(AstFile *f, Token proc_token, String *link_name_) {
  2835. AstNode *params = nullptr;
  2836. AstNode *results = nullptr;
  2837. expect_token(f, Token_OpenParen);
  2838. params = parse_field_list(f, nullptr, FieldFlag_Signature, Token_CloseParen, true, true);
  2839. expect_token_after(f, Token_CloseParen, "parameter list");
  2840. results = parse_results(f);
  2841. u64 tags = 0;
  2842. String link_name = {};
  2843. ProcCallingConvention cc = ProcCC_Invalid;
  2844. parse_proc_tags(f, &tags, &link_name, &cc);
  2845. if (link_name_) *link_name_ = link_name;
  2846. bool is_generic = false;
  2847. for_array(i, params->FieldList.list) {
  2848. AstNode *param = params->FieldList.list[i];
  2849. ast_node(f, Field, param);
  2850. if (f->type != nullptr &&
  2851. (f->type->kind == AstNode_TypeType ||
  2852. f->type->kind == AstNode_PolyType)) {
  2853. is_generic = true;
  2854. break;
  2855. }
  2856. }
  2857. return ast_proc_type(f, proc_token, params, results, tags, cc, is_generic);
  2858. }
  2859. AstNode *parse_var_type(AstFile *f, bool allow_ellipsis, bool allow_type_token) {
  2860. if (allow_ellipsis && f->curr_token.kind == Token_Ellipsis) {
  2861. Token tok = advance_token(f);
  2862. AstNode *type = parse_type_or_ident(f);
  2863. if (type == nullptr) {
  2864. error(tok, "variadic field missing type after `...`");
  2865. type = ast_bad_expr(f, tok, f->curr_token);
  2866. }
  2867. return ast_ellipsis(f, tok, type);
  2868. }
  2869. AstNode *type = nullptr;
  2870. if (allow_type_token &&
  2871. f->curr_token.kind == Token_type) {
  2872. Token token = expect_token(f, Token_type);
  2873. AstNode *specialization = nullptr;
  2874. if (allow_token(f, Token_Quo)) {
  2875. specialization = parse_type(f);
  2876. }
  2877. type = ast_type_type(f, token, specialization);
  2878. } else {
  2879. type = parse_type_attempt(f);
  2880. }
  2881. if (type == nullptr) {
  2882. Token tok = f->curr_token;
  2883. error(tok, "Expected a type");
  2884. type = ast_bad_expr(f, tok, f->curr_token);
  2885. }
  2886. return type;
  2887. }
  2888. enum FieldPrefixKind {
  2889. FieldPrefix_Invalid,
  2890. FieldPrefix_Using,
  2891. FieldPrefix_NoAlias,
  2892. FieldPrefix_CVarArg,
  2893. };
  2894. FieldPrefixKind is_token_field_prefix(AstFile *f) {
  2895. switch (f->curr_token.kind) {
  2896. case Token_EOF:
  2897. return FieldPrefix_Invalid;
  2898. case Token_using:
  2899. return FieldPrefix_Using;
  2900. case Token_Hash: {
  2901. advance_token(f);
  2902. switch (f->curr_token.kind) {
  2903. case Token_Ident:
  2904. if (f->curr_token.string == "no_alias") {
  2905. return FieldPrefix_NoAlias;
  2906. }
  2907. if (f->curr_token.string == "c_vararg") {
  2908. return FieldPrefix_CVarArg;
  2909. }
  2910. break;
  2911. }
  2912. } break;
  2913. }
  2914. return FieldPrefix_Invalid;
  2915. }
  2916. u32 parse_field_prefixes(AstFile *f) {
  2917. i32 using_count = 0;
  2918. i32 no_alias_count = 0;
  2919. i32 c_vararg_count = 0;
  2920. for (;;) {
  2921. FieldPrefixKind kind = is_token_field_prefix(f);
  2922. if (kind == FieldPrefix_Invalid) {
  2923. break;
  2924. }
  2925. switch (kind) {
  2926. case FieldPrefix_Using: using_count += 1; advance_token(f); break;
  2927. case FieldPrefix_NoAlias: no_alias_count += 1; advance_token(f); break;
  2928. case FieldPrefix_CVarArg: c_vararg_count += 1; advance_token(f); break;
  2929. }
  2930. }
  2931. if (using_count > 1) syntax_error(f->curr_token, "Multiple `using` in this field list");
  2932. if (no_alias_count > 1) syntax_error(f->curr_token, "Multiple `#no_alias` in this field list");
  2933. if (c_vararg_count > 1) syntax_error(f->curr_token, "Multiple `#c_vararg` in this field list");
  2934. u32 field_flags = 0;
  2935. if (using_count > 0) field_flags |= FieldFlag_using;
  2936. if (no_alias_count > 0) field_flags |= FieldFlag_no_alias;
  2937. if (c_vararg_count > 0) field_flags |= FieldFlag_c_vararg;
  2938. return field_flags;
  2939. }
  2940. u32 check_field_prefixes(AstFile *f, isize name_count, u32 allowed_flags, u32 set_flags) {
  2941. if (name_count > 1 && (set_flags&FieldFlag_using)) {
  2942. syntax_error(f->curr_token, "Cannot apply `using` to more than one of the same type");
  2943. set_flags &= ~FieldFlag_using;
  2944. }
  2945. if ((allowed_flags&FieldFlag_using) == 0 && (set_flags&FieldFlag_using)) {
  2946. syntax_error(f->curr_token, "`using` is not allowed within this field list");
  2947. set_flags &= ~FieldFlag_using;
  2948. }
  2949. if ((allowed_flags&FieldFlag_no_alias) == 0 && (set_flags&FieldFlag_no_alias)) {
  2950. syntax_error(f->curr_token, "`#no_alias` is not allowed within this field list");
  2951. set_flags &= ~FieldFlag_no_alias;
  2952. }
  2953. if ((allowed_flags&FieldFlag_c_vararg) == 0 && (set_flags&FieldFlag_c_vararg)) {
  2954. syntax_error(f->curr_token, "`#c_vararg` is not allowed within this field list");
  2955. set_flags &= ~FieldFlag_c_vararg;
  2956. }
  2957. return set_flags;
  2958. }
  2959. struct AstNodeAndFlags {
  2960. AstNode *node;
  2961. u32 flags;
  2962. };
  2963. Array<AstNode *> convert_to_ident_list(AstFile *f, Array<AstNodeAndFlags> list, bool ignore_flags) {
  2964. Array<AstNode *> idents = make_ast_node_array(f, list.count);
  2965. // Convert to ident list
  2966. for_array(i, list) {
  2967. AstNode *ident = list[i].node;
  2968. if (!ignore_flags) {
  2969. if (i != 0) {
  2970. error(ident, "Illegal use of prefixes in parameter list");
  2971. }
  2972. }
  2973. switch (ident->kind) {
  2974. case AstNode_Ident:
  2975. case AstNode_BadExpr:
  2976. break;
  2977. default:
  2978. error(ident, "Expected an identifier");
  2979. ident = ast_ident(f, blank_token);
  2980. break;
  2981. }
  2982. array_add(&idents, ident);
  2983. }
  2984. return idents;
  2985. }
  2986. bool parse_expect_field_separator(AstFile *f, AstNode *param) {
  2987. Token token = f->curr_token;
  2988. if (allow_token(f, Token_Comma)) {
  2989. return true;
  2990. }
  2991. if (token.kind == Token_Semicolon) {
  2992. error(f->curr_token, "Expected a comma, got a semicolon");
  2993. advance_token(f);
  2994. return true;
  2995. }
  2996. return false;
  2997. }
  2998. bool parse_expect_struct_separator(AstFile *f, AstNode *param) {
  2999. Token token = f->curr_token;
  3000. if (allow_token(f, Token_Semicolon)) {
  3001. return true;
  3002. }
  3003. if (token.kind == Token_Colon) {
  3004. error(f->curr_token, "Expected a semicolon, got a comma");
  3005. advance_token(f);
  3006. return true;
  3007. }
  3008. if (token.kind == Token_CloseBrace) {
  3009. if (token.pos.line == f->prev_token.pos.line) {
  3010. return true;
  3011. }
  3012. }
  3013. expect_token_after(f, Token_Semicolon, "field list");
  3014. return false;
  3015. }
  3016. AstNode *parse_struct_field_list(AstFile *f, isize *name_count_) {
  3017. CommentGroup docs = f->lead_comment;
  3018. Token start_token = f->curr_token;
  3019. Array<AstNode *> decls = make_ast_node_array(f);
  3020. isize total_name_count = 0;
  3021. AstNode *params = parse_field_list(f, &total_name_count, FieldFlag_Struct, Token_CloseBrace, true, false);
  3022. if (name_count_) *name_count_ = total_name_count;
  3023. return params;
  3024. #if 0
  3025. while (f->curr_token.kind != Token_CloseBrace &&
  3026. f->curr_token.kind != Token_EOF) {
  3027. AstNode *decl = parse_stmt(f);
  3028. switch (decl->kind) {
  3029. case AstNode_EmptyStmt:
  3030. case AstNode_BadStmt:
  3031. case AstNode_BadDecl:
  3032. break;
  3033. case_ast_node(vd, ValueDecl, decl);
  3034. if (vd->flags&VarDeclFlag_thread_local) {
  3035. vd->flags &= ~VarDeclFlag_thread_local;
  3036. error(decl, "Field values cannot be #thread_local");
  3037. }
  3038. array_add(&decls, decl);
  3039. total_name_count += vd->names.count;
  3040. case_end;
  3041. case AstNode_WhenStmt:
  3042. array_add(&decls, decl);
  3043. break;
  3044. default:
  3045. error(decl, "Expected a value declaration, got %.*s", LIT(ast_node_strings[decl->kind]));
  3046. break;
  3047. }
  3048. }
  3049. if (name_count_) *name_count_ = total_name_count;
  3050. return ast_field_list(f, start_token, decls);
  3051. #endif
  3052. }
  3053. AstNode *parse_field_list(AstFile *f, isize *name_count_, u32 allowed_flags, TokenKind follow, bool allow_default_parameters, bool allow_type_token) {
  3054. TokenKind separator = Token_Comma;
  3055. Token start_token = f->curr_token;
  3056. CommentGroup docs = f->lead_comment;
  3057. Array<AstNode *> params = make_ast_node_array(f);
  3058. Array<AstNodeAndFlags> list = {}; array_init(&list, heap_allocator());
  3059. defer (array_free(&list));
  3060. isize total_name_count = 0;
  3061. bool allow_ellipsis = allowed_flags&FieldFlag_ellipsis;
  3062. while (f->curr_token.kind != follow &&
  3063. f->curr_token.kind != Token_Colon &&
  3064. f->curr_token.kind != Token_EOF) {
  3065. u32 flags = parse_field_prefixes(f);
  3066. AstNode *param = parse_var_type(f, allow_ellipsis, allow_type_token);
  3067. AstNodeAndFlags naf = {param, flags};
  3068. array_add(&list, naf);
  3069. if (!allow_token(f, Token_Comma)) {
  3070. break;
  3071. }
  3072. }
  3073. if (f->curr_token.kind == Token_Colon) {
  3074. Array<AstNode *> names = convert_to_ident_list(f, list, true); // Copy for semantic reasons
  3075. if (names.count == 0) {
  3076. syntax_error(f->curr_token, "Empty field declaration");
  3077. }
  3078. u32 set_flags = 0;
  3079. if (list.count > 0) {
  3080. set_flags = list[0].flags;
  3081. }
  3082. set_flags = check_field_prefixes(f, names.count, allowed_flags, set_flags);
  3083. total_name_count += names.count;
  3084. AstNode *type = nullptr;
  3085. AstNode *default_value = nullptr;
  3086. expect_token_after(f, Token_Colon, "field list");
  3087. if (f->curr_token.kind != Token_Eq) {
  3088. type = parse_var_type(f, allow_ellipsis, allow_type_token);
  3089. }
  3090. if (allow_token(f, Token_Eq)) {
  3091. // TODO(bill): Should this be true==lhs or false==rhs?
  3092. default_value = parse_expr(f, false);
  3093. if (!allow_default_parameters) {
  3094. syntax_error(f->curr_token, "Default parameters are only allowed for procedures");
  3095. }
  3096. }
  3097. if (default_value != nullptr && names.count > 1) {
  3098. syntax_error(f->curr_token, "Default parameters can only be applied to single values");
  3099. }
  3100. parse_expect_field_separator(f, type);
  3101. AstNode *param = ast_field(f, names, type, default_value, set_flags, docs, f->line_comment);
  3102. array_add(&params, param);
  3103. while (f->curr_token.kind != follow &&
  3104. f->curr_token.kind != Token_EOF) {
  3105. CommentGroup docs = f->lead_comment;
  3106. u32 set_flags = parse_field_prefixes(f);
  3107. Array<AstNode *> names = parse_ident_list(f);
  3108. if (names.count == 0) {
  3109. syntax_error(f->curr_token, "Empty field declaration");
  3110. break;
  3111. }
  3112. set_flags = check_field_prefixes(f, names.count, allowed_flags, set_flags);
  3113. total_name_count += names.count;
  3114. AstNode *type = nullptr;
  3115. AstNode *default_value = nullptr;
  3116. expect_token_after(f, Token_Colon, "field list");
  3117. if (f->curr_token.kind != Token_Eq) {
  3118. type = parse_var_type(f, allow_ellipsis, allow_type_token);
  3119. }
  3120. if (allow_token(f, Token_Eq)) {
  3121. // TODO(bill): Should this be true==lhs or false==rhs?
  3122. default_value = parse_expr(f, false);
  3123. if (!allow_default_parameters) {
  3124. syntax_error(f->curr_token, "Default parameters are only allowed for procedures");
  3125. }
  3126. }
  3127. if (default_value != nullptr && names.count > 1) {
  3128. syntax_error(f->curr_token, "Default parameters can only be applied to single values");
  3129. }
  3130. bool ok = parse_expect_field_separator(f, param);
  3131. AstNode *param = ast_field(f, names, type, default_value, set_flags, docs, f->line_comment);
  3132. array_add(&params, param);
  3133. if (!ok) {
  3134. break;
  3135. }
  3136. }
  3137. if (name_count_) *name_count_ = total_name_count;
  3138. return ast_field_list(f, start_token, params);
  3139. }
  3140. for_array(i, list) {
  3141. Array<AstNode *> names = {};
  3142. AstNode *type = list[i].node;
  3143. Token token = blank_token;
  3144. array_init_count(&names, heap_allocator(), 1);
  3145. token.pos = ast_node_token(type).pos;
  3146. names[0] = ast_ident(f, token);
  3147. u32 flags = check_field_prefixes(f, list.count, allowed_flags, list[i].flags);
  3148. AstNode *param = ast_field(f, names, list[i].node, nullptr, flags, docs, f->line_comment);
  3149. array_add(&params, param);
  3150. }
  3151. if (name_count_) *name_count_ = total_name_count;
  3152. return ast_field_list(f, start_token, params);
  3153. }
  3154. AstNode *parse_type_or_ident(AstFile *f) {
  3155. #if 1
  3156. bool prev_allow_type = f->allow_type;
  3157. isize prev_expr_level = f->expr_level;
  3158. defer (f->allow_type = prev_allow_type);
  3159. defer (f->expr_level = prev_expr_level);
  3160. f->allow_type = true;
  3161. f->expr_level = -1;
  3162. AstNode *operand = parse_operand(f, true);
  3163. AstNode *type = parse_atom_expr(f, operand, true);
  3164. return type;
  3165. #else
  3166. switch (f->curr_token.kind) {
  3167. case Token_Dollar: {
  3168. Token token = expect_token(f, Token_Dollar);
  3169. AstNode *type = parse_ident(f);
  3170. return ast_poly_type(f, token, type);
  3171. } break;
  3172. case Token_type_of: {
  3173. AstNode *i = ast_implicit(f, expect_token(f, Token_type_of));
  3174. AstNode *type = parse_call_expr(f, i);
  3175. while (f->curr_token.kind == Token_Period) {
  3176. Token token = advance_token(f);
  3177. AstNode *sel = parse_ident(f);
  3178. type = ast_selector_expr(f, token, type, sel);
  3179. }
  3180. return type;
  3181. } break;
  3182. case Token_Ident: {
  3183. AstNode *e = parse_ident(f);
  3184. while (f->curr_token.kind == Token_Period) {
  3185. Token token = advance_token(f);
  3186. AstNode *sel = parse_ident(f);
  3187. e = ast_selector_expr(f, token, e, sel);
  3188. }
  3189. // TODO(bill): Merge type_or_ident into the general parsing for expressions
  3190. // if (f->curr_token.kind == Token_OpenParen) {
  3191. // HACK NOTE(bill): For type_of_val(expr) et al.
  3192. // e = parse_call_expr(f, e);
  3193. // }
  3194. return e;
  3195. } break;
  3196. case Token_Pointer: {
  3197. Token token = expect_token(f, Token_Pointer);
  3198. AstNode *elem = parse_type(f);
  3199. return ast_pointer_type(f, token, elem);
  3200. } break;
  3201. case Token_atomic: {
  3202. Token token = expect_token(f, Token_atomic);
  3203. AstNode *elem = parse_type(f);
  3204. return ast_atomic_type(f, token, elem);
  3205. } break;
  3206. case Token_Hash: {
  3207. Token hash_token = expect_token(f, Token_Hash);
  3208. Token type_token = expect_token(f, Token_type);
  3209. AstNode *type = parse_type(f);
  3210. return ast_helper_type(f, hash_token, type);
  3211. }
  3212. case Token_OpenBracket: {
  3213. Token token = expect_token(f, Token_OpenBracket);
  3214. AstNode *count_expr = nullptr;
  3215. bool is_vector = false;
  3216. if (f->curr_token.kind == Token_Ellipsis) {
  3217. count_expr = ast_unary_expr(f, expect_token(f, Token_Ellipsis), nullptr);
  3218. } else if (allow_token(f, Token_vector)) {
  3219. if (f->curr_token.kind != Token_CloseBracket) {
  3220. f->expr_level++;
  3221. count_expr = parse_expr(f, false);
  3222. f->expr_level--;
  3223. } else {
  3224. syntax_error(f->curr_token, "Vector type missing count");
  3225. }
  3226. is_vector = true;
  3227. } else if (allow_token(f, Token_dynamic)) {
  3228. expect_token(f, Token_CloseBracket);
  3229. return ast_dynamic_array_type(f, token, parse_type(f));
  3230. } else if (f->curr_token.kind != Token_CloseBracket) {
  3231. f->expr_level++;
  3232. count_expr = parse_expr(f, false);
  3233. f->expr_level--;
  3234. }
  3235. expect_token(f, Token_CloseBracket);
  3236. if (is_vector) {
  3237. return ast_vector_type(f, token, count_expr, parse_type(f));
  3238. }
  3239. return ast_array_type(f, token, count_expr, parse_type(f));
  3240. } break;
  3241. case Token_map: {
  3242. Token token = expect_token(f, Token_map);
  3243. AstNode *count = nullptr;
  3244. AstNode *key = nullptr;
  3245. AstNode *value = nullptr;
  3246. Token open = expect_token_after(f, Token_OpenBracket, "map");
  3247. key = parse_expr(f, true);
  3248. if (allow_token(f, Token_Comma)) {
  3249. count = key;
  3250. key = parse_type(f);
  3251. }
  3252. Token close = expect_token(f, Token_CloseBracket);
  3253. value = parse_type(f);
  3254. return ast_map_type(f, token, count, key, value);
  3255. } break;
  3256. case Token_struct: {
  3257. Token token = expect_token(f, Token_struct);
  3258. bool is_packed = false;
  3259. bool is_ordered = false;
  3260. AstNode *align = nullptr;
  3261. isize prev_level = f->expr_level;
  3262. f->expr_level = -1;
  3263. while (allow_token(f, Token_Hash)) {
  3264. Token tag = expect_token_after(f, Token_Ident, "#");
  3265. if (tag.string == "packed") {
  3266. if (is_packed) {
  3267. syntax_error(tag, "Duplicate struct tag `#%.*s`", LIT(tag.string));
  3268. }
  3269. is_packed = true;
  3270. } else if (tag.string == "ordered") {
  3271. if (is_ordered) {
  3272. syntax_error(tag, "Duplicate struct tag `#%.*s`", LIT(tag.string));
  3273. }
  3274. is_ordered = true;
  3275. } else if (tag.string == "align") {
  3276. if (align) {
  3277. syntax_error(tag, "Duplicate struct tag `#%.*s`", LIT(tag.string));
  3278. }
  3279. align = parse_expr(f, true);
  3280. } else {
  3281. syntax_error(tag, "Invalid struct tag `#%.*s`", LIT(tag.string));
  3282. }
  3283. }
  3284. f->expr_level = prev_level;
  3285. if (is_packed && is_ordered) {
  3286. syntax_error(token, "`#ordered` is not needed with `#packed` which implies ordering");
  3287. }
  3288. Token open = expect_token_after(f, Token_OpenBrace, "struct");
  3289. isize name_count = 0;
  3290. AstNode *fields = parse_struct_field_list(f, &name_count);
  3291. Token close = expect_token(f, Token_CloseBrace);
  3292. Array<AstNode *> decls = {};
  3293. if (fields != nullptr) {
  3294. GB_ASSERT(fields->kind == AstNode_FieldList);
  3295. decls = fields->FieldList.list;
  3296. }
  3297. return ast_struct_type(f, token, decls, name_count, is_packed, is_ordered, align);
  3298. } break;
  3299. case Token_union: {
  3300. Token token = expect_token(f, Token_union);
  3301. Token open = expect_token_after(f, Token_OpenBrace, "union");
  3302. Array<AstNode *> variants = make_ast_node_array(f);
  3303. isize total_decl_name_count = 0;
  3304. CommentGroup docs = f->lead_comment;
  3305. Token start_token = f->curr_token;
  3306. while (f->curr_token.kind != Token_CloseBrace &&
  3307. f->curr_token.kind != Token_EOF) {
  3308. AstNode *type = parse_type(f);
  3309. if (type->kind != AstNode_BadExpr) {
  3310. array_add(&variants, type);
  3311. }
  3312. if (!allow_token(f, Token_Comma)) {
  3313. break;
  3314. }
  3315. }
  3316. Token close = expect_token(f, Token_CloseBrace);
  3317. return ast_union_type(f, token, variants);
  3318. } break;
  3319. case Token_raw_union: {
  3320. Token token = expect_token(f, Token_raw_union);
  3321. Token open = expect_token_after(f, Token_OpenBrace, "raw_union");
  3322. isize decl_count = 0;
  3323. AstNode *fields = parse_struct_field_list(f, &decl_count);
  3324. Token close = expect_token(f, Token_CloseBrace);
  3325. Array<AstNode *> decls = {};
  3326. if (fields != nullptr) {
  3327. GB_ASSERT(fields->kind == AstNode_FieldList);
  3328. decls = fields->FieldList.list;
  3329. }
  3330. return ast_raw_union_type(f, token, decls, decl_count);
  3331. } break;
  3332. case Token_enum: {
  3333. Token token = expect_token(f, Token_enum);
  3334. AstNode *base_type = nullptr;
  3335. if (f->curr_token.kind != Token_OpenBrace) {
  3336. base_type = parse_type(f);
  3337. }
  3338. Token open = expect_token(f, Token_OpenBrace);
  3339. Array<AstNode *> values = parse_element_list(f);
  3340. Token close = expect_token(f, Token_CloseBrace);
  3341. return ast_enum_type(f, token, base_type, values);
  3342. } break;
  3343. case Token_bit_field: {
  3344. Token token = expect_token(f, Token_bit_field);
  3345. Array<AstNode *> fields = make_ast_node_array(f);
  3346. AstNode *align = nullptr;
  3347. Token open, close;
  3348. isize prev_level = f->expr_level;
  3349. f->expr_level = -1;
  3350. while (allow_token(f, Token_Hash)) {
  3351. Token tag = expect_token_after(f, Token_Ident, "#");
  3352. if (tag.string == "align") {
  3353. if (align) {
  3354. syntax_error(tag, "Duplicate bit_field tag `#%.*s`", LIT(tag.string));
  3355. }
  3356. align = parse_expr(f, true);
  3357. } else {
  3358. syntax_error(tag, "Invalid bit_field tag `#%.*s`", LIT(tag.string));
  3359. }
  3360. }
  3361. f->expr_level = prev_level;
  3362. open = expect_token_after(f, Token_OpenBrace, "bit_field");
  3363. while (f->curr_token.kind != Token_EOF &&
  3364. f->curr_token.kind != Token_CloseBrace) {
  3365. AstNode *name = parse_ident(f);
  3366. Token colon = expect_token(f, Token_Colon);
  3367. AstNode *value = parse_expr(f, true);
  3368. AstNode *field = ast_field_value(f, name, value, colon);
  3369. array_add(&fields, field);
  3370. if (f->curr_token.kind != Token_Comma) {
  3371. break;
  3372. }
  3373. advance_token(f);
  3374. }
  3375. close = expect_token(f, Token_CloseBrace);
  3376. return ast_bit_field_type(f, token, fields, align);
  3377. } break;
  3378. case Token_proc: {
  3379. Token token = advance_token(f);
  3380. AstNode *pt = parse_proc_type(f, token, nullptr);
  3381. if (pt->ProcType.tags != 0) {
  3382. syntax_error(token, "A procedure type cannot have tags");
  3383. }
  3384. return pt;
  3385. } break;
  3386. case Token_OpenParen: {
  3387. Token open = expect_token(f, Token_OpenParen);
  3388. AstNode *type = parse_type(f);
  3389. Token close = expect_token(f, Token_CloseParen);
  3390. return ast_paren_expr(f, type, open, close);
  3391. } break;
  3392. }
  3393. return nullptr;
  3394. #endif
  3395. }
  3396. AstNode *parse_body(AstFile *f) {
  3397. Array<AstNode *> stmts = {};
  3398. Token open, close;
  3399. isize prev_expr_level = f->expr_level;
  3400. // NOTE(bill): The body may be within an expression so reset to zero
  3401. f->expr_level = 0;
  3402. open = expect_token(f, Token_OpenBrace);
  3403. stmts = parse_stmt_list(f);
  3404. close = expect_token(f, Token_CloseBrace);
  3405. f->expr_level = prev_expr_level;
  3406. return ast_block_stmt(f, stmts, open, close);
  3407. }
  3408. AstNode *parse_if_stmt(AstFile *f) {
  3409. if (f->curr_proc == nullptr) {
  3410. syntax_error(f->curr_token, "You cannot use an if statement in the file scope");
  3411. return ast_bad_stmt(f, f->curr_token, f->curr_token);
  3412. }
  3413. Token token = expect_token(f, Token_if);
  3414. AstNode *init = nullptr;
  3415. AstNode *cond = nullptr;
  3416. AstNode *body = nullptr;
  3417. AstNode *else_stmt = nullptr;
  3418. isize prev_level = f->expr_level;
  3419. f->expr_level = -1;
  3420. if (allow_token(f, Token_Semicolon)) {
  3421. cond = parse_expr(f, false);
  3422. } else {
  3423. init = parse_simple_stmt(f, StmtAllowFlag_None);
  3424. if (allow_token(f, Token_Semicolon)) {
  3425. cond = parse_expr(f, false);
  3426. } else {
  3427. cond = convert_stmt_to_expr(f, init, str_lit("boolean expression"));
  3428. init = nullptr;
  3429. }
  3430. }
  3431. f->expr_level = prev_level;
  3432. if (cond == nullptr) {
  3433. syntax_error(f->curr_token, "Expected condition for if statement");
  3434. }
  3435. if (allow_token(f, Token_do)) {
  3436. body = convert_stmt_to_body(f, parse_stmt(f));
  3437. } else {
  3438. body = parse_block_stmt(f, false);
  3439. }
  3440. if (allow_token(f, Token_else)) {
  3441. switch (f->curr_token.kind) {
  3442. case Token_if:
  3443. else_stmt = parse_if_stmt(f);
  3444. break;
  3445. case Token_OpenBrace:
  3446. else_stmt = parse_block_stmt(f, false);
  3447. break;
  3448. case Token_do: {
  3449. Token arrow = expect_token(f, Token_do);
  3450. else_stmt = convert_stmt_to_body(f, parse_stmt(f));
  3451. } break;
  3452. default:
  3453. syntax_error(f->curr_token, "Expected if statement block statement");
  3454. else_stmt = ast_bad_stmt(f, f->curr_token, f->tokens[f->curr_token_index+1]);
  3455. break;
  3456. }
  3457. }
  3458. return ast_if_stmt(f, token, init, cond, body, else_stmt);
  3459. }
  3460. AstNode *parse_when_stmt(AstFile *f) {
  3461. Token token = expect_token(f, Token_when);
  3462. AstNode *cond = nullptr;
  3463. AstNode *body = nullptr;
  3464. AstNode *else_stmt = nullptr;
  3465. isize prev_level = f->expr_level;
  3466. isize when_level = f->when_level;
  3467. defer (f->when_level = when_level);
  3468. f->expr_level = -1;
  3469. f->when_level += 1;
  3470. cond = parse_expr(f, false);
  3471. f->expr_level = prev_level;
  3472. if (cond == nullptr) {
  3473. syntax_error(f->curr_token, "Expected condition for when statement");
  3474. }
  3475. if (allow_token(f, Token_do)) {
  3476. body = convert_stmt_to_body(f, parse_stmt(f));
  3477. } else {
  3478. body = parse_block_stmt(f, true);
  3479. }
  3480. if (allow_token(f, Token_else)) {
  3481. switch (f->curr_token.kind) {
  3482. case Token_when:
  3483. else_stmt = parse_when_stmt(f);
  3484. break;
  3485. case Token_OpenBrace:
  3486. else_stmt = parse_block_stmt(f, true);
  3487. break;
  3488. case Token_do: {
  3489. Token arrow = expect_token(f, Token_do);
  3490. body = convert_stmt_to_body(f, parse_stmt(f));
  3491. } break;
  3492. default:
  3493. syntax_error(f->curr_token, "Expected when statement block statement");
  3494. else_stmt = ast_bad_stmt(f, f->curr_token, f->tokens[f->curr_token_index+1]);
  3495. break;
  3496. }
  3497. }
  3498. // if (f->curr_proc == nullptr && f->when_level > 1) {
  3499. // syntax_error(token, "Nested when statements are not currently supported at the file scope");
  3500. // return ast_bad_stmt(f, token, f->curr_token);
  3501. // }
  3502. return ast_when_stmt(f, token, cond, body, else_stmt);
  3503. }
  3504. AstNode *parse_return_stmt(AstFile *f) {
  3505. if (f->curr_proc == nullptr) {
  3506. syntax_error(f->curr_token, "You cannot use a return statement in the file scope");
  3507. return ast_bad_stmt(f, f->curr_token, f->curr_token);
  3508. }
  3509. if (f->expr_level > 0) {
  3510. syntax_error(f->curr_token, "You cannot use a return statement within an expression");
  3511. return ast_bad_stmt(f, f->curr_token, f->curr_token);
  3512. }
  3513. Token token = expect_token(f, Token_return);
  3514. Array<AstNode *> results = make_ast_node_array(f);
  3515. while (f->curr_token.kind != Token_Semicolon) {
  3516. AstNode *arg = parse_expr(f, false);
  3517. if (f->curr_token.kind == Token_Eq) {
  3518. Token eq = expect_token(f, Token_Eq);
  3519. AstNode *value = parse_value(f);
  3520. arg = ast_field_value(f, arg, value, eq);
  3521. }
  3522. array_add(&results, arg);
  3523. if (f->curr_token.kind != Token_Comma ||
  3524. f->curr_token.kind == Token_EOF) {
  3525. break;
  3526. }
  3527. advance_token(f);
  3528. }
  3529. AstNode *end = nullptr;
  3530. if (results.count > 0) {
  3531. end = results[results.count-1];
  3532. }
  3533. expect_semicolon(f, end);
  3534. return ast_return_stmt(f, token, results);
  3535. }
  3536. // AstNode *parse_give_stmt(AstFile *f) {
  3537. // if (f->curr_proc == nullptr) {
  3538. // syntax_error(f->curr_token, "You cannot use a give statement in the file scope");
  3539. // return ast_bad_stmt(f, f->curr_token, f->curr_token);
  3540. // }
  3541. // if (f->expr_level == 0) {
  3542. // syntax_error(f->curr_token, "A give statement must be used within an expression");
  3543. // return ast_bad_stmt(f, f->curr_token, f->curr_token);
  3544. // }
  3545. // Token token = expect_token(f, Token_give);
  3546. // Array<AstNode *> results;
  3547. // if (f->curr_token.kind != Token_Semicolon && f->curr_token.kind != Token_CloseBrace) {
  3548. // results = parse_rhs_expr_list(f);
  3549. // } else {
  3550. // results = make_ast_node_array(f);
  3551. // }
  3552. // AstNode *ge = ast_give_expr(f, token, results);
  3553. // expect_semicolon(f, ge);
  3554. // return ast_expr_stmt(f, ge);
  3555. // }
  3556. AstNode *parse_for_stmt(AstFile *f) {
  3557. if (f->curr_proc == nullptr) {
  3558. syntax_error(f->curr_token, "You cannot use a for statement in the file scope");
  3559. return ast_bad_stmt(f, f->curr_token, f->curr_token);
  3560. }
  3561. Token token = expect_token(f, Token_for);
  3562. AstNode *init = nullptr;
  3563. AstNode *cond = nullptr;
  3564. AstNode *post = nullptr;
  3565. AstNode *body = nullptr;
  3566. bool is_range = false;
  3567. if (f->curr_token.kind != Token_OpenBrace &&
  3568. f->curr_token.kind != Token_do) {
  3569. isize prev_level = f->expr_level;
  3570. defer (f->expr_level = prev_level);
  3571. f->expr_level = -1;
  3572. if (f->curr_token.kind == Token_in) {
  3573. Token in_token = expect_token(f, Token_in);
  3574. AstNode *rhs = nullptr;
  3575. bool prev_allow_range = f->allow_range;
  3576. f->allow_range = true;
  3577. rhs = parse_expr(f, false);
  3578. f->allow_range = prev_allow_range;
  3579. if (allow_token(f, Token_do)) {
  3580. body = convert_stmt_to_body(f, parse_stmt(f));
  3581. } else {
  3582. body = parse_block_stmt(f, false);
  3583. }
  3584. return ast_range_stmt(f, token, nullptr, nullptr, in_token, rhs, body);
  3585. }
  3586. if (f->curr_token.kind != Token_Semicolon) {
  3587. cond = parse_simple_stmt(f, StmtAllowFlag_In);
  3588. if (cond->kind == AstNode_AssignStmt && cond->AssignStmt.op.kind == Token_in) {
  3589. is_range = true;
  3590. }
  3591. }
  3592. if (!is_range && allow_token(f, Token_Semicolon)) {
  3593. init = cond;
  3594. cond = nullptr;
  3595. if (f->curr_token.kind != Token_Semicolon) {
  3596. cond = parse_simple_stmt(f, StmtAllowFlag_None);
  3597. }
  3598. expect_semicolon(f, cond);
  3599. if (f->curr_token.kind != Token_OpenBrace &&
  3600. f->curr_token.kind != Token_do) {
  3601. post = parse_simple_stmt(f, StmtAllowFlag_None);
  3602. }
  3603. }
  3604. }
  3605. if (allow_token(f, Token_do)) {
  3606. body = convert_stmt_to_body(f, parse_stmt(f));
  3607. } else {
  3608. body = parse_block_stmt(f, false);
  3609. }
  3610. if (is_range) {
  3611. GB_ASSERT(cond->kind == AstNode_AssignStmt);
  3612. Token in_token = cond->AssignStmt.op;
  3613. AstNode *value = nullptr;
  3614. AstNode *index = nullptr;
  3615. switch (cond->AssignStmt.lhs.count) {
  3616. case 1:
  3617. value = cond->AssignStmt.lhs[0];
  3618. break;
  3619. case 2:
  3620. value = cond->AssignStmt.lhs[0];
  3621. index = cond->AssignStmt.lhs[1];
  3622. break;
  3623. default:
  3624. error(cond, "Expected either 1 or 2 identifiers");
  3625. return ast_bad_stmt(f, token, f->curr_token);
  3626. }
  3627. AstNode *rhs = nullptr;
  3628. if (cond->AssignStmt.rhs.count > 0) {
  3629. rhs = cond->AssignStmt.rhs[0];
  3630. }
  3631. return ast_range_stmt(f, token, value, index, in_token, rhs, body);
  3632. }
  3633. cond = convert_stmt_to_expr(f, cond, str_lit("boolean expression"));
  3634. return ast_for_stmt(f, token, init, cond, post, body);
  3635. }
  3636. AstNode *parse_case_clause(AstFile *f, bool is_type) {
  3637. Token token = f->curr_token;
  3638. Array<AstNode *> list = {};
  3639. expect_token(f, Token_case);
  3640. bool prev_allow_range = f->allow_range;
  3641. f->allow_range = !is_type;
  3642. if (f->curr_token.kind != Token_Colon) {
  3643. list = parse_rhs_expr_list(f);
  3644. }
  3645. f->allow_range = prev_allow_range;
  3646. expect_token(f, Token_Colon); // TODO(bill): Is this the best syntax?
  3647. Array<AstNode *> stmts = parse_stmt_list(f);
  3648. return ast_case_clause(f, token, list, stmts);
  3649. }
  3650. AstNode *parse_switch_stmt(AstFile *f) {
  3651. if (f->curr_proc == nullptr) {
  3652. syntax_error(f->curr_token, "You cannot use a match statement in the file scope");
  3653. return ast_bad_stmt(f, f->curr_token, f->curr_token);
  3654. }
  3655. Token token = expect_token(f, Token_switch);
  3656. AstNode *init = nullptr;
  3657. AstNode *tag = nullptr;
  3658. AstNode *body = nullptr;
  3659. Token open, close;
  3660. bool is_type_match = false;
  3661. Array<AstNode *> list = make_ast_node_array(f);
  3662. if (f->curr_token.kind != Token_OpenBrace) {
  3663. isize prev_level = f->expr_level;
  3664. f->expr_level = -1;
  3665. defer (f->expr_level = prev_level);
  3666. if (allow_token(f, Token_in)) {
  3667. Array<AstNode *> lhs = {};
  3668. Array<AstNode *> rhs = make_ast_node_array(f, 1);
  3669. array_add(&rhs, parse_expr(f, false));
  3670. tag = ast_assign_stmt(f, token, lhs, rhs);
  3671. is_type_match = true;
  3672. } else {
  3673. tag = parse_simple_stmt(f, StmtAllowFlag_In);
  3674. if (tag->kind == AstNode_AssignStmt && tag->AssignStmt.op.kind == Token_in) {
  3675. is_type_match = true;
  3676. } else {
  3677. if (allow_token(f, Token_Semicolon)) {
  3678. init = tag;
  3679. tag = nullptr;
  3680. if (f->curr_token.kind != Token_OpenBrace) {
  3681. tag = parse_simple_stmt(f, StmtAllowFlag_None);
  3682. }
  3683. }
  3684. }
  3685. }
  3686. }
  3687. open = expect_token(f, Token_OpenBrace);
  3688. while (f->curr_token.kind == Token_case) {
  3689. array_add(&list, parse_case_clause(f, is_type_match));
  3690. }
  3691. close = expect_token(f, Token_CloseBrace);
  3692. body = ast_block_stmt(f, list, open, close);
  3693. if (!is_type_match) {
  3694. tag = convert_stmt_to_expr(f, tag, str_lit("match expression"));
  3695. return ast_switch_stmt(f, token, init, tag, body);
  3696. } else {
  3697. return ast_type_switch_stmt(f, token, tag, body);
  3698. }
  3699. }
  3700. AstNode *parse_defer_stmt(AstFile *f) {
  3701. if (f->curr_proc == nullptr) {
  3702. syntax_error(f->curr_token, "You cannot use a defer statement in the file scope");
  3703. return ast_bad_stmt(f, f->curr_token, f->curr_token);
  3704. }
  3705. Token token = expect_token(f, Token_defer);
  3706. AstNode *stmt = parse_stmt(f);
  3707. switch (stmt->kind) {
  3708. case AstNode_EmptyStmt:
  3709. syntax_error(token, "Empty statement after defer (e.g. `;`)");
  3710. break;
  3711. case AstNode_DeferStmt:
  3712. syntax_error(token, "You cannot defer a defer statement");
  3713. stmt = stmt->DeferStmt.stmt;
  3714. break;
  3715. case AstNode_ReturnStmt:
  3716. syntax_error(token, "You cannot a return statement");
  3717. break;
  3718. }
  3719. return ast_defer_stmt(f, token, stmt);
  3720. }
  3721. AstNode *parse_asm_stmt(AstFile *f) {
  3722. Token token = expect_token(f, Token_asm);
  3723. bool is_volatile = false;
  3724. Token open, close, code_string;
  3725. open = expect_token(f, Token_OpenBrace);
  3726. code_string = expect_token(f, Token_String);
  3727. AstNode *output_list = nullptr;
  3728. AstNode *input_list = nullptr;
  3729. AstNode *clobber_list = nullptr;
  3730. isize output_count = 0;
  3731. isize input_count = 0;
  3732. isize clobber_count = 0;
  3733. // TODO(bill): Finish asm statement and determine syntax
  3734. // if (f->curr_token.kind != Token_CloseBrace) {
  3735. // expect_token(f, Token_Colon);
  3736. // }
  3737. close = expect_token(f, Token_CloseBrace);
  3738. return ast_asm_stmt(f, token, is_volatile, open, close, code_string,
  3739. output_list, input_list, clobber_list,
  3740. output_count, input_count, clobber_count);
  3741. }
  3742. AstNode *parse_import_decl(AstFile *f, bool is_using) {
  3743. CommentGroup docs = f->lead_comment;
  3744. Token token = expect_token(f, Token_import);
  3745. AstNode *cond = nullptr;
  3746. Token import_name = {};
  3747. switch (f->curr_token.kind) {
  3748. case Token_Ident:
  3749. import_name = advance_token(f);
  3750. break;
  3751. default:
  3752. import_name.pos = f->curr_token.pos;
  3753. break;
  3754. }
  3755. if (is_blank_ident(import_name)) {
  3756. syntax_error(import_name, "Illegal import name: `_`");
  3757. }
  3758. Token file_path = expect_token_after(f, Token_String, "import");
  3759. if (allow_token(f, Token_when)) {
  3760. cond = parse_expr(f, false);
  3761. }
  3762. AstNode *s = nullptr;
  3763. if (f->curr_proc != nullptr) {
  3764. syntax_error(import_name, "You cannot use `import` within a procedure. This must be done at the file scope");
  3765. s = ast_bad_decl(f, import_name, file_path);
  3766. } else {
  3767. s = ast_import_decl(f, token, is_using, file_path, import_name, cond, docs, f->line_comment);
  3768. array_add(&f->imports_and_exports, s);
  3769. }
  3770. expect_semicolon(f, s);
  3771. return s;
  3772. }
  3773. AstNode *parse_export_decl(AstFile *f) {
  3774. CommentGroup docs = f->lead_comment;
  3775. Token token = expect_token(f, Token_export);
  3776. AstNode *cond = nullptr;
  3777. Token file_path = expect_token_after(f, Token_String, "export");
  3778. if (allow_token(f, Token_when)) {
  3779. cond = parse_expr(f, false);
  3780. }
  3781. AstNode *s = nullptr;
  3782. if (f->curr_proc != nullptr) {
  3783. syntax_error(token, "You cannot use `export` within a procedure. This must be done at the file scope");
  3784. s = ast_bad_decl(f, token, file_path);
  3785. } else {
  3786. s = ast_export_decl(f, token, file_path, cond, docs, f->line_comment);
  3787. array_add(&f->imports_and_exports, s);
  3788. }
  3789. expect_semicolon(f, s);
  3790. return s;
  3791. }
  3792. AstNode *parse_foreign_decl(AstFile *f) {
  3793. CommentGroup docs = f->lead_comment;
  3794. Token token = {};
  3795. switch (f->curr_token.kind) {
  3796. case Token_foreign_library:
  3797. case Token_foreign_system_library:
  3798. token = advance_token(f);
  3799. break;
  3800. default:
  3801. token = advance_token(f);
  3802. syntax_error(token, "Expected either foreign_library or foreign_system_library, got `%.*s`", LIT(token.string));
  3803. return ast_bad_decl(f, token, token);
  3804. }
  3805. AstNode *cond = nullptr;
  3806. Token lib_name = {};
  3807. switch (f->curr_token.kind) {
  3808. case Token_Ident:
  3809. lib_name = advance_token(f);
  3810. break;
  3811. default:
  3812. lib_name.pos = f->curr_token.pos;
  3813. break;
  3814. }
  3815. if (is_blank_ident(lib_name)) {
  3816. syntax_error(lib_name, "Illegal foreign_library name: `_`");
  3817. }
  3818. Token file_path = expect_token(f, Token_String);
  3819. if (allow_token(f, Token_when)) {
  3820. cond = parse_expr(f, false);
  3821. }
  3822. AstNode *s = nullptr;
  3823. if (f->curr_proc != nullptr) {
  3824. syntax_error(lib_name, "You cannot use foreign_system_library within a procedure. This must be done at the file scope");
  3825. s = ast_bad_decl(f, lib_name, file_path);
  3826. } else {
  3827. s = ast_foreign_library_decl(f, token, file_path, lib_name, cond, docs, f->line_comment);
  3828. }
  3829. expect_semicolon(f, s);
  3830. return s;
  3831. }
  3832. AstNode *parse_stmt(AstFile *f) {
  3833. AstNode *s = nullptr;
  3834. Token token = f->curr_token;
  3835. switch (token.kind) {
  3836. // Operands
  3837. case Token_context:
  3838. case Token_Ident:
  3839. case Token_Integer:
  3840. case Token_Float:
  3841. case Token_Imag:
  3842. case Token_Rune:
  3843. case Token_String:
  3844. case Token_OpenParen:
  3845. case Token_Pointer:
  3846. // Unary Operators
  3847. case Token_Add:
  3848. case Token_Sub:
  3849. case Token_Xor:
  3850. case Token_Not:
  3851. case Token_And:
  3852. s = parse_simple_stmt(f, StmtAllowFlag_Label);
  3853. expect_semicolon(f, s);
  3854. return s;
  3855. case Token_foreign:
  3856. return parse_foreign_block(f);
  3857. case Token_foreign_library:
  3858. case Token_foreign_system_library:
  3859. return parse_foreign_decl(f);
  3860. case Token_import:
  3861. return parse_import_decl(f, false);
  3862. case Token_export:
  3863. return parse_export_decl(f);
  3864. case Token_if: return parse_if_stmt(f);
  3865. case Token_when: return parse_when_stmt(f);
  3866. case Token_for: return parse_for_stmt(f);
  3867. case Token_switch: return parse_switch_stmt(f);
  3868. case Token_defer: return parse_defer_stmt(f);
  3869. case Token_return: return parse_return_stmt(f);
  3870. case Token_asm: return parse_asm_stmt(f);
  3871. case Token_break:
  3872. case Token_continue:
  3873. case Token_fallthrough: {
  3874. Token token = advance_token(f);
  3875. AstNode *label = nullptr;
  3876. if (token.kind != Token_fallthrough &&
  3877. f->curr_token.kind == Token_Ident) {
  3878. label = parse_ident(f);
  3879. }
  3880. s = ast_branch_stmt(f, token, label);
  3881. expect_semicolon(f, s);
  3882. return s;
  3883. }
  3884. case Token_using: {
  3885. CommentGroup docs = f->lead_comment;
  3886. Token token = expect_token(f, Token_using);
  3887. if (f->curr_token.kind == Token_import) {
  3888. return parse_import_decl(f, true);
  3889. }
  3890. AstNode *decl = nullptr;
  3891. Array<AstNode *> list = parse_lhs_expr_list(f);
  3892. if (list.count == 0) {
  3893. syntax_error(token, "Illegal use of `using` statement");
  3894. expect_semicolon(f, nullptr);
  3895. return ast_bad_stmt(f, token, f->curr_token);
  3896. }
  3897. if (f->curr_token.kind != Token_Colon) {
  3898. expect_semicolon(f, list[list.count-1]);
  3899. return ast_using_stmt(f, token, list);
  3900. }
  3901. decl = parse_value_decl(f, list, docs);
  3902. if (decl != nullptr && decl->kind == AstNode_ValueDecl) {
  3903. if (!decl->ValueDecl.is_mutable) {
  3904. syntax_error(token, "`using` may only be applied to variable declarations");
  3905. return decl;
  3906. }
  3907. decl->ValueDecl.flags |= VarDeclFlag_using;
  3908. return decl;
  3909. }
  3910. syntax_error(token, "Illegal use of `using` statement");
  3911. return ast_bad_stmt(f, token, f->curr_token);
  3912. } break;
  3913. case Token_push_allocator: {
  3914. advance_token(f);
  3915. AstNode *body = nullptr;
  3916. isize prev_level = f->expr_level;
  3917. f->expr_level = -1;
  3918. AstNode *expr = parse_expr(f, false);
  3919. f->expr_level = prev_level;
  3920. if (allow_token(f, Token_do)) {
  3921. body = convert_stmt_to_body(f, parse_stmt(f));
  3922. } else {
  3923. body = parse_block_stmt(f, false);
  3924. }
  3925. return ast_push_allocator(f, token, expr, body);
  3926. } break;
  3927. case Token_push_context: {
  3928. advance_token(f);
  3929. AstNode *body = nullptr;
  3930. isize prev_level = f->expr_level;
  3931. f->expr_level = -1;
  3932. AstNode *expr = parse_expr(f, false);
  3933. f->expr_level = prev_level;
  3934. if (allow_token(f, Token_do)) {
  3935. body = convert_stmt_to_body(f, parse_stmt(f));
  3936. } else {
  3937. body = parse_block_stmt(f, false);
  3938. }
  3939. return ast_push_context(f, token, expr, body);
  3940. } break;
  3941. case Token_Hash: {
  3942. AstNode *s = nullptr;
  3943. Token hash_token = expect_token(f, Token_Hash);
  3944. Token name = expect_token(f, Token_Ident);
  3945. String tag = name.string;
  3946. if (tag == "shared_global_scope") {
  3947. if (f->curr_proc == nullptr) {
  3948. f->is_global_scope = true;
  3949. s = ast_empty_stmt(f, f->curr_token);
  3950. } else {
  3951. syntax_error(token, "You cannot use #shared_global_scope within a procedure. This must be done at the file scope");
  3952. s = ast_bad_decl(f, token, f->curr_token);
  3953. }
  3954. expect_semicolon(f, s);
  3955. return s;
  3956. } else if (tag == "thread_local") {
  3957. AstNode *s = parse_stmt(f);
  3958. if (s->kind == AstNode_ValueDecl) {
  3959. if (!s->ValueDecl.is_mutable) {
  3960. syntax_error(token, "`thread_local` may only be applied to variable declarations");
  3961. }
  3962. if (f->curr_proc != nullptr) {
  3963. syntax_error(token, "`thread_local` is only allowed at the file scope");
  3964. } else {
  3965. s->ValueDecl.flags |= VarDeclFlag_thread_local;
  3966. }
  3967. return s;
  3968. }
  3969. syntax_error(token, "`thread_local` may only be applied to a variable declaration");
  3970. return ast_bad_stmt(f, token, f->curr_token);
  3971. } else if (tag == "bounds_check") {
  3972. s = parse_stmt(f);
  3973. s->stmt_state_flags |= StmtStateFlag_bounds_check;
  3974. if ((s->stmt_state_flags & StmtStateFlag_no_bounds_check) != 0) {
  3975. syntax_error(token, "#bounds_check and #no_bounds_check cannot be applied together");
  3976. }
  3977. return s;
  3978. } else if (tag == "no_bounds_check") {
  3979. s = parse_stmt(f);
  3980. s->stmt_state_flags |= StmtStateFlag_no_bounds_check;
  3981. if ((s->stmt_state_flags & StmtStateFlag_bounds_check) != 0) {
  3982. syntax_error(token, "#bounds_check and #no_bounds_check cannot be applied together");
  3983. }
  3984. return s;
  3985. }
  3986. if (tag == "include") {
  3987. syntax_error(token, "#include is not a valid import declaration kind. Did you mean `import`?");
  3988. s = ast_bad_stmt(f, token, f->curr_token);
  3989. } else {
  3990. syntax_error(token, "Unknown tag directive used: `%.*s`", LIT(tag));
  3991. s = ast_bad_stmt(f, token, f->curr_token);
  3992. }
  3993. fix_advance_to_next_stmt(f);
  3994. return s;
  3995. } break;
  3996. case Token_OpenBrace:
  3997. return parse_block_stmt(f, false);
  3998. case Token_Semicolon:
  3999. s = ast_empty_stmt(f, token);
  4000. advance_token(f);
  4001. return s;
  4002. }
  4003. syntax_error(token,
  4004. "Expected a statement, got `%.*s`",
  4005. LIT(token_strings[token.kind]));
  4006. fix_advance_to_next_stmt(f);
  4007. return ast_bad_stmt(f, token, f->curr_token);
  4008. }
  4009. Array<AstNode *> parse_stmt_list(AstFile *f) {
  4010. Array<AstNode *> list = make_ast_node_array(f);
  4011. while (f->curr_token.kind != Token_case &&
  4012. f->curr_token.kind != Token_CloseBrace &&
  4013. f->curr_token.kind != Token_EOF) {
  4014. AstNode *stmt = parse_stmt(f);
  4015. if (stmt && stmt->kind != AstNode_EmptyStmt) {
  4016. array_add(&list, stmt);
  4017. if (stmt->kind == AstNode_ExprStmt &&
  4018. stmt->ExprStmt.expr != nullptr &&
  4019. stmt->ExprStmt.expr->kind == AstNode_ProcLit) {
  4020. syntax_error(stmt, "Procedure literal evaluated but not used");
  4021. }
  4022. }
  4023. }
  4024. return list;
  4025. }
  4026. ParseFileError init_ast_file(AstFile *f, String fullpath, TokenPos *err_pos) {
  4027. f->fullpath = string_trim_whitespace(fullpath); // Just in case
  4028. if (!string_has_extension(f->fullpath, str_lit("odin"))) {
  4029. return ParseFile_WrongExtension;
  4030. }
  4031. TokenizerInitError err = init_tokenizer(&f->tokenizer, f->fullpath);
  4032. if (err != TokenizerInit_None) {
  4033. switch (err) {
  4034. case TokenizerInit_NotExists:
  4035. return ParseFile_NotFound;
  4036. case TokenizerInit_Permission:
  4037. return ParseFile_Permission;
  4038. case TokenizerInit_Empty:
  4039. return ParseFile_EmptyFile;
  4040. }
  4041. return ParseFile_InvalidFile;
  4042. }
  4043. isize file_size = f->tokenizer.end - f->tokenizer.start;
  4044. isize init_token_cap = cast(isize)gb_max(next_pow2(cast(i64)(file_size/2ll)), 16);
  4045. array_init(&f->tokens, heap_allocator(), gb_max(init_token_cap, 16));
  4046. for (;;) {
  4047. Token token = tokenizer_get_token(&f->tokenizer);
  4048. if (token.kind == Token_Invalid) {
  4049. err_pos->line = token.pos.line;
  4050. err_pos->column = token.pos.column;
  4051. return ParseFile_InvalidToken;
  4052. }
  4053. array_add(&f->tokens, token);
  4054. if (token.kind == Token_EOF) {
  4055. break;
  4056. }
  4057. }
  4058. f->curr_token_index = 0;
  4059. f->prev_token = f->tokens[f->curr_token_index];
  4060. f->curr_token = f->tokens[f->curr_token_index];
  4061. // NOTE(bill): Is this big enough or too small?
  4062. isize arena_size = gb_size_of(AstNode);
  4063. arena_size *= 2*f->tokens.count;
  4064. gb_arena_init_from_allocator(&f->arena, heap_allocator(), arena_size);
  4065. array_init(&f->comments, heap_allocator());
  4066. array_init(&f->imports_and_exports, heap_allocator());
  4067. f->curr_proc = nullptr;
  4068. return ParseFile_None;
  4069. }
  4070. void destroy_ast_file(AstFile *f) {
  4071. gb_arena_free(&f->arena);
  4072. array_free(&f->tokens);
  4073. array_free(&f->comments);
  4074. array_free(&f->imports_and_exports);
  4075. gb_free(heap_allocator(), f->tokenizer.fullpath.text);
  4076. destroy_tokenizer(&f->tokenizer);
  4077. }
  4078. bool init_parser(Parser *p) {
  4079. array_init(&p->files, heap_allocator());
  4080. array_init(&p->imports, heap_allocator());
  4081. gb_mutex_init(&p->file_add_mutex);
  4082. gb_mutex_init(&p->file_decl_mutex);
  4083. return true;
  4084. }
  4085. void destroy_parser(Parser *p) {
  4086. // TODO(bill): Fix memory leak
  4087. for_array(i, p->files) {
  4088. destroy_ast_file(p->files[i]);
  4089. }
  4090. #if 0
  4091. for_array(i, p->imports) {
  4092. // gb_free(heap_allocator(), p->imports[i].text);
  4093. }
  4094. #endif
  4095. array_free(&p->files);
  4096. array_free(&p->imports);
  4097. gb_mutex_destroy(&p->file_add_mutex);
  4098. gb_mutex_destroy(&p->file_decl_mutex);
  4099. }
  4100. // NOTE(bill): Returns true if it's added
  4101. bool try_add_import_path(Parser *p, String path, String rel_path, TokenPos pos) {
  4102. if (build_context.generate_docs) {
  4103. return false;
  4104. }
  4105. path = string_trim_whitespace(path);
  4106. rel_path = string_trim_whitespace(rel_path);
  4107. for_array(i, p->imports) {
  4108. String import = p->imports[i].path;
  4109. if (import == path) {
  4110. return false;
  4111. }
  4112. }
  4113. ImportedFile item = {};
  4114. item.kind = ImportedFile_Normal;
  4115. item.path = path;
  4116. item.rel_path = rel_path;
  4117. item.pos = pos;
  4118. item.index = p->imports.count;
  4119. array_add(&p->imports, item);
  4120. return true;
  4121. }
  4122. gb_global Rune illegal_import_runes[] = {
  4123. '"', '\'', '`', ' ', '\t', '\r', '\n', '\v', '\f',
  4124. '\\', // NOTE(bill): Disallow windows style filepaths
  4125. '!', '$', '%', '^', '&', '*', '(', ')', '=', '+',
  4126. '[', ']', '{', '}',
  4127. ';', ':', '#',
  4128. '|', ',', '<', '>', '?',
  4129. };
  4130. bool is_import_path_valid(String path) {
  4131. if (path.len > 0) {
  4132. u8 *start = path.text;
  4133. u8 *end = path.text + path.len;
  4134. u8 *curr = start;
  4135. while (curr < end) {
  4136. isize width = 1;
  4137. Rune r = curr[0];
  4138. if (r >= 0x80) {
  4139. width = gb_utf8_decode(curr, end-curr, &r);
  4140. if (r == GB_RUNE_INVALID && width == 1) {
  4141. return false;
  4142. }
  4143. else if (r == GB_RUNE_BOM && curr-start > 0) {
  4144. return false;
  4145. }
  4146. }
  4147. for (isize i = 0; i < gb_count_of(illegal_import_runes); i++) {
  4148. if (r == illegal_import_runes[i]) {
  4149. return false;
  4150. }
  4151. }
  4152. curr += width;
  4153. }
  4154. return true;
  4155. }
  4156. return false;
  4157. }
  4158. bool determine_path_from_string(Parser *p, AstNode *node, String base_dir, String original_string, String *path) {
  4159. GB_ASSERT(path != nullptr);
  4160. gbAllocator a = heap_allocator();
  4161. String collection_name = {};
  4162. isize colon_pos = -1;
  4163. for (isize j = 0; j < original_string.len; j++) {
  4164. if (original_string[j] == ':') {
  4165. colon_pos = j;
  4166. break;
  4167. }
  4168. }
  4169. String file_str = {};
  4170. if (colon_pos == 0) {
  4171. syntax_error(node, "Expected a collection name");
  4172. return false;
  4173. }
  4174. if (original_string.len > 0 && colon_pos > 0) {
  4175. collection_name = substring(original_string, 0, colon_pos);
  4176. file_str = substring(original_string, colon_pos+1, original_string.len);
  4177. } else {
  4178. file_str = original_string;
  4179. }
  4180. if (!is_import_path_valid(file_str)) {
  4181. syntax_error(node, "Invalid import path: `%.*s`", LIT(file_str));
  4182. return false;
  4183. }
  4184. gb_mutex_lock(&p->file_decl_mutex);
  4185. defer (gb_mutex_unlock(&p->file_decl_mutex));
  4186. if (collection_name.len > 0) {
  4187. if (!find_library_collection_path(collection_name, &base_dir)) {
  4188. // NOTE(bill): It's a naughty name
  4189. syntax_error(node, "Unknown library colleciton: `%.*s`", LIT(base_dir));
  4190. return false;
  4191. }
  4192. }
  4193. String fullpath = string_trim_whitespace(get_fullpath_relative(a, base_dir, file_str));
  4194. *path = fullpath;
  4195. return true;
  4196. }
  4197. void parse_setup_file_decls(Parser *p, AstFile *f, String base_dir, Array<AstNode *> decls);
  4198. void parse_setup_file_when_stmt(Parser *p, AstFile *f, String base_dir, AstNodeWhenStmt *ws) {
  4199. if (ws->body != nullptr) {
  4200. auto stmts = ws->body->BlockStmt.stmts;
  4201. parse_setup_file_decls(p, f, base_dir, stmts);
  4202. }
  4203. if (ws->else_stmt != nullptr) {
  4204. switch (ws->else_stmt->kind) {
  4205. case AstNode_BlockStmt: {
  4206. auto stmts = ws->else_stmt->BlockStmt.stmts;
  4207. parse_setup_file_decls(p, f, base_dir, stmts);
  4208. } break;
  4209. case AstNode_WhenStmt:
  4210. parse_setup_file_when_stmt(p, f, base_dir, &ws->else_stmt->WhenStmt);
  4211. break;
  4212. }
  4213. }
  4214. }
  4215. void parse_setup_file_decls(Parser *p, AstFile *f, String base_dir, Array<AstNode *> decls) {
  4216. for_array(i, decls) {
  4217. AstNode *node = decls[i];
  4218. if (!is_ast_node_decl(node) &&
  4219. node->kind != AstNode_BadStmt &&
  4220. node->kind != AstNode_EmptyStmt &&
  4221. node->kind != AstNode_WhenStmt) {
  4222. // NOTE(bill): Sanity check
  4223. syntax_error(node, "Only declarations are allowed at file scope, got %.*s", LIT(ast_node_strings[node->kind]));
  4224. } else if (node->kind == AstNode_ImportDecl) {
  4225. ast_node(id, ImportDecl, node);
  4226. String original_string = id->relpath.string;
  4227. String import_path = {};
  4228. bool ok = determine_path_from_string(p, node, base_dir, original_string, &import_path);
  4229. if (!ok) {
  4230. decls[i] = ast_bad_decl(f, id->relpath, id->relpath);
  4231. continue;
  4232. }
  4233. id->fullpath = import_path;
  4234. try_add_import_path(p, import_path, original_string, ast_node_token(node).pos);
  4235. } else if (node->kind == AstNode_ExportDecl) {
  4236. ast_node(ed, ExportDecl, node);
  4237. String original_string = ed->relpath.string;
  4238. String export_path = {};
  4239. bool ok = determine_path_from_string(p, node, base_dir, original_string, &export_path);
  4240. if (!ok) {
  4241. decls[i] = ast_bad_decl(f, ed->relpath, ed->relpath);
  4242. continue;
  4243. }
  4244. export_path = string_trim_whitespace(export_path);
  4245. ed->fullpath = export_path;
  4246. try_add_import_path(p, export_path, original_string, ast_node_token(node).pos);
  4247. } else if (node->kind == AstNode_ForeignLibraryDecl) {
  4248. ast_node(fl, ForeignLibraryDecl, node);
  4249. String file_str = fl->filepath.string;
  4250. if (!is_import_path_valid(file_str)) {
  4251. syntax_error(node, "Invalid `%.*s` path", LIT(fl->token.string));
  4252. // NOTE(bill): It's a naughty name
  4253. decls[i] = ast_bad_decl(f, fl->filepath, fl->filepath);
  4254. } else {
  4255. fl->base_dir = base_dir;
  4256. }
  4257. } else if (node->kind == AstNode_WhenStmt) {
  4258. ast_node(ws, WhenStmt, node);
  4259. parse_setup_file_when_stmt(p, f, base_dir, ws);
  4260. }
  4261. }
  4262. }
  4263. void parse_file(Parser *p, AstFile *f) {
  4264. String filepath = f->tokenizer.fullpath;
  4265. String base_dir = filepath;
  4266. for (isize i = filepath.len-1; i >= 0; i--) {
  4267. if (base_dir[i] == '\\' ||
  4268. base_dir[i] == '/') {
  4269. break;
  4270. }
  4271. base_dir.len--;
  4272. }
  4273. comsume_comment_groups(f, f->prev_token);
  4274. f->decls = parse_stmt_list(f);
  4275. parse_setup_file_decls(p, f, base_dir, f->decls);
  4276. }
  4277. ParseFileError parse_import(Parser *p, ImportedFile imported_file) {
  4278. String import_path = imported_file.path;
  4279. String import_rel_path = imported_file.rel_path;
  4280. TokenPos pos = imported_file.pos;
  4281. AstFile *file = gb_alloc_item(heap_allocator(), AstFile);
  4282. file->file_kind = imported_file.kind;
  4283. if (file->file_kind == ImportedFile_Shared) {
  4284. file->is_global_scope = true;
  4285. }
  4286. TokenPos err_pos = {0};
  4287. ParseFileError err = init_ast_file(file, import_path, &err_pos);
  4288. if (err != ParseFile_None) {
  4289. if (err == ParseFile_EmptyFile) {
  4290. if (import_path == p->init_fullpath) {
  4291. gb_printf_err("Initial file is empty - %.*s\n", LIT(p->init_fullpath));
  4292. gb_exit(1);
  4293. }
  4294. return ParseFile_None;
  4295. }
  4296. if (pos.line != 0) {
  4297. gb_printf_err("%.*s(%td:%td) ", LIT(pos.file), pos.line, pos.column);
  4298. }
  4299. gb_printf_err("Failed to parse file: %.*s\n\t", LIT(import_rel_path));
  4300. switch (err) {
  4301. case ParseFile_WrongExtension:
  4302. gb_printf_err("Invalid file extension: File must have the extension `.odin`");
  4303. break;
  4304. case ParseFile_InvalidFile:
  4305. gb_printf_err("Invalid file or cannot be found");
  4306. break;
  4307. case ParseFile_Permission:
  4308. gb_printf_err("File permissions problem");
  4309. break;
  4310. case ParseFile_NotFound:
  4311. gb_printf_err("File cannot be found (`%.*s`)", LIT(import_path));
  4312. break;
  4313. case ParseFile_InvalidToken:
  4314. gb_printf_err("Invalid token found in file at (%td:%td)", err_pos.line, err_pos.column);
  4315. break;
  4316. }
  4317. gb_printf_err("\n");
  4318. return err;
  4319. }
  4320. parse_file(p, file);
  4321. gb_mutex_lock(&p->file_add_mutex);
  4322. file->id = imported_file.index;
  4323. array_add(&p->files, file);
  4324. p->total_line_count += file->tokenizer.line_count;
  4325. gb_mutex_unlock(&p->file_add_mutex);
  4326. return ParseFile_None;
  4327. }
  4328. GB_THREAD_PROC(parse_worker_file_proc) {
  4329. if (thread == nullptr) return 0;
  4330. auto *p = cast(Parser *)thread->user_data;
  4331. isize index = thread->user_index;
  4332. ImportedFile imported_file = p->imports[index];
  4333. ParseFileError err = parse_import(p, imported_file);
  4334. return cast(isize)err;
  4335. }
  4336. struct ParserThreadWork {
  4337. Parser *parser;
  4338. isize import_index;
  4339. };
  4340. ParseFileError parse_files(Parser *p, String init_filename) {
  4341. GB_ASSERT(init_filename.text[init_filename.len] == 0);
  4342. char *fullpath_str = gb_path_get_full_name(heap_allocator(), cast(char *)&init_filename[0]);
  4343. String init_fullpath = string_trim_whitespace(make_string_c(fullpath_str));
  4344. TokenPos init_pos = {};
  4345. ImportedFile init_imported_file = {ImportedFile_Init, init_fullpath, init_fullpath, init_pos};
  4346. isize shared_file_count = 0;
  4347. if (!build_context.generate_docs) {
  4348. String s = get_fullpath_core(heap_allocator(), str_lit("_preload.odin"));
  4349. ImportedFile runtime_file = {ImportedFile_Shared, s, s, init_pos};
  4350. array_add(&p->imports, runtime_file);
  4351. shared_file_count++;
  4352. }
  4353. if (!build_context.generate_docs) {
  4354. String s = get_fullpath_core(heap_allocator(), str_lit("_soft_numbers.odin"));
  4355. ImportedFile runtime_file = {ImportedFile_Shared, s, s, init_pos};
  4356. array_add(&p->imports, runtime_file);
  4357. shared_file_count++;
  4358. }
  4359. array_add(&p->imports, init_imported_file);
  4360. p->init_fullpath = init_fullpath;
  4361. /*
  4362. // IMPORTANT TODO(bill): Figure out why this doesn't work on *nix sometimes
  4363. #if USE_THREADED_PARSER && defined(GB_SYSTEM_WINDOWS)
  4364. isize thread_count = gb_max(build_context.thread_count, 1);
  4365. if (thread_count > 1) {
  4366. Array<gbThread> worker_threads = {};
  4367. array_init_count(&worker_threads, heap_allocator(), thread_count);
  4368. defer (array_free(&worker_threads));
  4369. for_array(i, p->imports) {
  4370. gbThread *t = &worker_threads[i];
  4371. gb_thread_init(t);
  4372. }
  4373. isize curr_import_index = 0;
  4374. // NOTE(bill): Make sure that these are in parsed in this order
  4375. for (isize i = 0; i < shared_file_count; i++) {
  4376. ParseFileError err = parse_import(p, p->imports[i]);
  4377. if (err != ParseFile_None) {
  4378. return err;
  4379. }
  4380. curr_import_index++;
  4381. }
  4382. for (;;) {
  4383. bool are_any_alive = false;
  4384. for_array(i, worker_threads) {
  4385. gbThread *t = &worker_threads[i];
  4386. if (gb_thread_is_running(t)) {
  4387. are_any_alive = true;
  4388. } else if (curr_import_index < p->imports.count) {
  4389. auto err = cast(ParseFileError)t->return_value;
  4390. if (err != ParseFile_None) {
  4391. for_array(i, worker_threads) {
  4392. gb_thread_destroy(&worker_threads[i]);
  4393. }
  4394. return err;
  4395. }
  4396. t->user_index = curr_import_index++;
  4397. gb_thread_start(t, parse_worker_file_proc, p);
  4398. are_any_alive = true;
  4399. }
  4400. }
  4401. if (!are_any_alive && curr_import_index >= p->imports.count) {
  4402. break;
  4403. }
  4404. }
  4405. for_array(i, worker_threads) {
  4406. gb_thread_destroy(&worker_threads[i]);
  4407. }
  4408. } else {
  4409. for_array(i, p->imports) {
  4410. ParseFileError err = parse_import(p, p->imports[i]);
  4411. if (err != ParseFile_None) {
  4412. return err;
  4413. }
  4414. }
  4415. }
  4416. #else */
  4417. isize import_index = 0;
  4418. for (; import_index < p->imports.count; import_index++) {
  4419. ParseFileError err = parse_import(p, p->imports[import_index]);
  4420. if (err != ParseFile_None) {
  4421. return err;
  4422. }
  4423. }
  4424. // #endif
  4425. for_array(i, p->files) {
  4426. p->total_token_count += p->files[i]->tokens.count;
  4427. }
  4428. return ParseFile_None;
  4429. }