parser.cpp 135 KB

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