parser.cpp 131 KB

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