parser.cpp 145 KB

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