parser.cpp 135 KB

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