parser.cpp 173 KB

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