parser.cpp 120 KB

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