parser.cpp 148 KB

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