parser.cpp 161 KB

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