parser.cpp 146 KB

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