parser.cpp 155 KB

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