parser.cpp 189 KB

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