parser.cpp 157 KB

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