2
0

parser.cpp 152 KB

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