parser.cpp 138 KB

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