parser.cpp 199 KB

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