parser.cpp 191 KB

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