parser.cpp 158 KB

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