parser.cpp 123 KB

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