parser.cpp 122 KB

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