parser.cpp 122 KB

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