parser.cpp 136 KB

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