gdscript_parser.cpp 225 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496
  1. /**************************************************************************/
  2. /* gdscript_parser.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "gdscript_parser.h"
  31. #include "gdscript.h"
  32. #include "gdscript_tokenizer_buffer.h"
  33. #include "core/config/project_settings.h"
  34. #include "core/io/resource_loader.h"
  35. #include "core/math/math_defs.h"
  36. #include "scene/main/multiplayer_api.h"
  37. #ifdef DEBUG_ENABLED
  38. #include "core/string/string_builder.h"
  39. #include "servers/text/text_server.h"
  40. #endif
  41. #ifdef TOOLS_ENABLED
  42. #include "editor/settings/editor_settings.h"
  43. #endif
  44. // This function is used to determine that a type is "built-in" as opposed to native
  45. // and custom classes. So `Variant::NIL` and `Variant::OBJECT` are excluded:
  46. // `Variant::NIL` - `null` is literal, not a type.
  47. // `Variant::OBJECT` - `Object` should be treated as a class, not as a built-in type.
  48. static HashMap<StringName, Variant::Type> builtin_types;
  49. Variant::Type GDScriptParser::get_builtin_type(const StringName &p_type) {
  50. if (unlikely(builtin_types.is_empty())) {
  51. for (int i = 0; i < Variant::VARIANT_MAX; i++) {
  52. Variant::Type type = (Variant::Type)i;
  53. if (type != Variant::NIL && type != Variant::OBJECT) {
  54. builtin_types[Variant::get_type_name(type)] = type;
  55. }
  56. }
  57. }
  58. if (builtin_types.has(p_type)) {
  59. return builtin_types[p_type];
  60. }
  61. return Variant::VARIANT_MAX;
  62. }
  63. #ifdef DEBUG_ENABLED
  64. bool GDScriptParser::is_project_ignoring_warnings = false;
  65. GDScriptWarning::WarnLevel GDScriptParser::warning_levels[GDScriptWarning::WARNING_MAX];
  66. LocalVector<GDScriptParser::WarningDirectoryRule> GDScriptParser::warning_directory_rules;
  67. #endif // DEBUG_ENABLED
  68. #ifdef TOOLS_ENABLED
  69. HashMap<String, String> GDScriptParser::theme_color_names;
  70. #endif // TOOLS_ENABLED
  71. HashMap<StringName, GDScriptParser::AnnotationInfo> GDScriptParser::valid_annotations;
  72. void GDScriptParser::cleanup() {
  73. builtin_types.clear();
  74. valid_annotations.clear();
  75. }
  76. void GDScriptParser::get_annotation_list(List<MethodInfo> *r_annotations) const {
  77. for (const KeyValue<StringName, AnnotationInfo> &E : valid_annotations) {
  78. r_annotations->push_back(E.value.info);
  79. }
  80. }
  81. bool GDScriptParser::annotation_exists(const String &p_annotation_name) const {
  82. return valid_annotations.has(p_annotation_name);
  83. }
  84. #ifdef DEBUG_ENABLED
  85. void GDScriptParser::update_project_settings() {
  86. is_project_ignoring_warnings = !GLOBAL_GET("debug/gdscript/warnings/enable").booleanize();
  87. for (int i = 0; i < GDScriptWarning::WARNING_MAX; i++) {
  88. const String setting_path = GDScriptWarning::get_setting_path_from_code((GDScriptWarning::Code)i);
  89. warning_levels[i] = (GDScriptWarning::WarnLevel)(int)GLOBAL_GET(setting_path);
  90. }
  91. #ifndef DISABLE_DEPRECATED
  92. // We do not use `GLOBAL_GET`, since we check without taking overrides into account. We leave the migration of non-trivial configurations to the user.
  93. if (unlikely(ProjectSettings::get_singleton()->has_setting("debug/gdscript/warnings/exclude_addons"))) {
  94. const bool is_excluding_addons = ProjectSettings::get_singleton()->get_setting("debug/gdscript/warnings/exclude_addons", true).booleanize();
  95. ProjectSettings::get_singleton()->clear("debug/gdscript/warnings/exclude_addons");
  96. Dictionary rules = ProjectSettings::get_singleton()->get_setting("debug/gdscript/warnings/directory_rules");
  97. rules["res://addons"] = is_excluding_addons ? WarningDirectoryRule::DECISION_EXCLUDE : WarningDirectoryRule::DECISION_INCLUDE;
  98. ProjectSettings::get_singleton()->set_setting("debug/gdscript/warnings/directory_rules", rules);
  99. }
  100. #endif // DISABLE_DEPRECATED
  101. warning_directory_rules.clear();
  102. const Dictionary rules = GLOBAL_GET("debug/gdscript/warnings/directory_rules");
  103. for (const KeyValue<Variant, Variant> &kv : rules) {
  104. String dir = kv.key.operator String().simplify_path();
  105. ERR_CONTINUE_MSG(!dir.begins_with("res://"), R"(Paths in the project setting "debug/gdscript/warnings/directory_rules" keys must start with the "res://" prefix.)");
  106. if (!dir.ends_with("/")) {
  107. dir += '/';
  108. }
  109. const int decision = kv.value;
  110. ERR_CONTINUE(decision < 0 || decision >= WarningDirectoryRule::DECISION_MAX);
  111. warning_directory_rules.push_back({ dir, (WarningDirectoryRule::Decision)decision });
  112. }
  113. struct RuleSort {
  114. bool operator()(const WarningDirectoryRule &p_a, const WarningDirectoryRule &p_b) const {
  115. return p_a.directory_path.count("/") > p_b.directory_path.count("/");
  116. }
  117. };
  118. warning_directory_rules.sort_custom<RuleSort>();
  119. }
  120. #endif // DEBUG_ENABLED
  121. GDScriptParser::GDScriptParser() {
  122. // Register valid annotations.
  123. if (unlikely(valid_annotations.is_empty())) {
  124. // Script annotations.
  125. register_annotation(MethodInfo("@tool"), AnnotationInfo::SCRIPT, &GDScriptParser::tool_annotation);
  126. register_annotation(MethodInfo("@icon", PropertyInfo(Variant::STRING, "icon_path")), AnnotationInfo::SCRIPT, &GDScriptParser::icon_annotation);
  127. register_annotation(MethodInfo("@static_unload"), AnnotationInfo::SCRIPT, &GDScriptParser::static_unload_annotation);
  128. register_annotation(MethodInfo("@abstract"), AnnotationInfo::SCRIPT | AnnotationInfo::CLASS | AnnotationInfo::FUNCTION, &GDScriptParser::abstract_annotation);
  129. // Onready annotation.
  130. register_annotation(MethodInfo("@onready"), AnnotationInfo::VARIABLE, &GDScriptParser::onready_annotation);
  131. // Export annotations.
  132. register_annotation(MethodInfo("@export"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_NONE, Variant::NIL>);
  133. register_annotation(MethodInfo("@export_enum", PropertyInfo(Variant::STRING, "names")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_ENUM, Variant::NIL>, varray(), true);
  134. register_annotation(MethodInfo("@export_file", PropertyInfo(Variant::STRING, "filter")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_FILE, Variant::STRING>, varray(""), true);
  135. register_annotation(MethodInfo("@export_file_path", PropertyInfo(Variant::STRING, "filter")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_FILE_PATH, Variant::STRING>, varray(""), true);
  136. register_annotation(MethodInfo("@export_dir"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_DIR, Variant::STRING>);
  137. register_annotation(MethodInfo("@export_global_file", PropertyInfo(Variant::STRING, "filter")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_GLOBAL_FILE, Variant::STRING>, varray(""), true);
  138. register_annotation(MethodInfo("@export_global_dir"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_GLOBAL_DIR, Variant::STRING>);
  139. register_annotation(MethodInfo("@export_multiline", PropertyInfo(Variant::STRING, "hint")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_MULTILINE_TEXT, Variant::STRING>, varray(""), true);
  140. register_annotation(MethodInfo("@export_placeholder", PropertyInfo(Variant::STRING, "placeholder")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_PLACEHOLDER_TEXT, Variant::STRING>);
  141. register_annotation(MethodInfo("@export_range", PropertyInfo(Variant::FLOAT, "min"), PropertyInfo(Variant::FLOAT, "max"), PropertyInfo(Variant::FLOAT, "step"), PropertyInfo(Variant::STRING, "extra_hints")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_RANGE, Variant::FLOAT>, varray(1.0, ""), true);
  142. register_annotation(MethodInfo("@export_exp_easing", PropertyInfo(Variant::STRING, "hints")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_EXP_EASING, Variant::FLOAT>, varray(""), true);
  143. register_annotation(MethodInfo("@export_color_no_alpha"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_COLOR_NO_ALPHA, Variant::COLOR>);
  144. register_annotation(MethodInfo("@export_node_path", PropertyInfo(Variant::STRING, "type")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_NODE_PATH_VALID_TYPES, Variant::NODE_PATH>, varray(""), true);
  145. register_annotation(MethodInfo("@export_flags", PropertyInfo(Variant::STRING, "names")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_FLAGS, Variant::INT>, varray(), true);
  146. register_annotation(MethodInfo("@export_flags_2d_render"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_2D_RENDER, Variant::INT>);
  147. register_annotation(MethodInfo("@export_flags_2d_physics"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_2D_PHYSICS, Variant::INT>);
  148. register_annotation(MethodInfo("@export_flags_2d_navigation"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_2D_NAVIGATION, Variant::INT>);
  149. register_annotation(MethodInfo("@export_flags_3d_render"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_3D_RENDER, Variant::INT>);
  150. register_annotation(MethodInfo("@export_flags_3d_physics"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_3D_PHYSICS, Variant::INT>);
  151. register_annotation(MethodInfo("@export_flags_3d_navigation"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_3D_NAVIGATION, Variant::INT>);
  152. register_annotation(MethodInfo("@export_flags_avoidance"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_AVOIDANCE, Variant::INT>);
  153. register_annotation(MethodInfo("@export_storage"), AnnotationInfo::VARIABLE, &GDScriptParser::export_storage_annotation);
  154. register_annotation(MethodInfo("@export_custom", PropertyInfo(Variant::INT, "hint", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_CLASS_IS_ENUM, "PropertyHint"), PropertyInfo(Variant::STRING, "hint_string"), PropertyInfo(Variant::INT, "usage", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_CLASS_IS_BITFIELD, "PropertyUsageFlags")), AnnotationInfo::VARIABLE, &GDScriptParser::export_custom_annotation, varray(PROPERTY_USAGE_DEFAULT));
  155. register_annotation(MethodInfo("@export_tool_button", PropertyInfo(Variant::STRING, "text"), PropertyInfo(Variant::STRING, "icon")), AnnotationInfo::VARIABLE, &GDScriptParser::export_tool_button_annotation, varray(""));
  156. // Export grouping annotations.
  157. register_annotation(MethodInfo("@export_category", PropertyInfo(Variant::STRING, "name")), AnnotationInfo::STANDALONE, &GDScriptParser::export_group_annotations<PROPERTY_USAGE_CATEGORY>);
  158. register_annotation(MethodInfo("@export_group", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::STRING, "prefix")), AnnotationInfo::STANDALONE, &GDScriptParser::export_group_annotations<PROPERTY_USAGE_GROUP>, varray(""));
  159. register_annotation(MethodInfo("@export_subgroup", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::STRING, "prefix")), AnnotationInfo::STANDALONE, &GDScriptParser::export_group_annotations<PROPERTY_USAGE_SUBGROUP>, varray(""));
  160. // Warning annotations.
  161. register_annotation(MethodInfo("@warning_ignore", PropertyInfo(Variant::STRING, "warning")), AnnotationInfo::CLASS_LEVEL | AnnotationInfo::STATEMENT, &GDScriptParser::warning_ignore_annotation, varray(), true);
  162. register_annotation(MethodInfo("@warning_ignore_start", PropertyInfo(Variant::STRING, "warning")), AnnotationInfo::STANDALONE, &GDScriptParser::warning_ignore_region_annotations, varray(), true);
  163. register_annotation(MethodInfo("@warning_ignore_restore", PropertyInfo(Variant::STRING, "warning")), AnnotationInfo::STANDALONE, &GDScriptParser::warning_ignore_region_annotations, varray(), true);
  164. // Networking.
  165. // Keep in sync with `rpc_annotation()` and `SceneRPCInterface::_parse_rpc_config()`.
  166. register_annotation(MethodInfo("@rpc", PropertyInfo(Variant::STRING, "mode"), PropertyInfo(Variant::STRING, "sync"), PropertyInfo(Variant::STRING, "transfer_mode"), PropertyInfo(Variant::INT, "transfer_channel")), AnnotationInfo::FUNCTION, &GDScriptParser::rpc_annotation, varray("authority", "call_remote", "reliable", 0));
  167. }
  168. #ifdef DEBUG_ENABLED
  169. for (int i = 0; i < GDScriptWarning::WARNING_MAX; i++) {
  170. warning_ignore_start_lines[i] = INT_MAX;
  171. }
  172. #endif // DEBUG_ENABLED
  173. #ifdef TOOLS_ENABLED
  174. if (unlikely(theme_color_names.is_empty())) {
  175. // Vectors.
  176. theme_color_names.insert("x", "axis_x_color");
  177. theme_color_names.insert("y", "axis_y_color");
  178. theme_color_names.insert("z", "axis_z_color");
  179. theme_color_names.insert("w", "axis_w_color");
  180. // Color.
  181. theme_color_names.insert("r", "axis_x_color");
  182. theme_color_names.insert("r8", "axis_x_color");
  183. theme_color_names.insert("g", "axis_y_color");
  184. theme_color_names.insert("g8", "axis_y_color");
  185. theme_color_names.insert("b", "axis_z_color");
  186. theme_color_names.insert("b8", "axis_z_color");
  187. theme_color_names.insert("a", "axis_w_color");
  188. theme_color_names.insert("a8", "axis_w_color");
  189. }
  190. #endif // TOOLS_ENABLED
  191. }
  192. GDScriptParser::~GDScriptParser() {
  193. while (list != nullptr) {
  194. Node *element = list;
  195. list = list->next;
  196. memdelete(element);
  197. }
  198. }
  199. void GDScriptParser::clear() {
  200. GDScriptParser tmp;
  201. tmp = *this;
  202. *this = GDScriptParser();
  203. }
  204. void GDScriptParser::push_error(const String &p_message, const Node *p_origin) {
  205. // TODO: Improve error reporting by pointing at source code.
  206. // TODO: Errors might point at more than one place at once (e.g. show previous declaration).
  207. panic_mode = true;
  208. // TODO: Improve positional information.
  209. if (p_origin == nullptr) {
  210. errors.push_back({ p_message, previous.start_line, previous.start_column });
  211. } else {
  212. errors.push_back({ p_message, p_origin->start_line, p_origin->start_column });
  213. }
  214. }
  215. #ifdef DEBUG_ENABLED
  216. void GDScriptParser::push_warning(const Node *p_source, GDScriptWarning::Code p_code, const Vector<String> &p_symbols) {
  217. ERR_FAIL_NULL(p_source);
  218. ERR_FAIL_INDEX(p_code, GDScriptWarning::WARNING_MAX);
  219. if (is_project_ignoring_warnings || is_script_ignoring_warnings) {
  220. return;
  221. }
  222. const GDScriptWarning::WarnLevel warn_level = warning_levels[p_code];
  223. if (warn_level == GDScriptWarning::IGNORE) {
  224. return;
  225. }
  226. PendingWarning pw;
  227. pw.source = p_source;
  228. pw.code = p_code;
  229. pw.treated_as_error = warn_level == GDScriptWarning::ERROR;
  230. pw.symbols = p_symbols;
  231. pending_warnings.push_back(pw);
  232. }
  233. void GDScriptParser::apply_pending_warnings() {
  234. for (const PendingWarning &pw : pending_warnings) {
  235. if (warning_ignored_lines[pw.code].has(pw.source->start_line)) {
  236. continue;
  237. }
  238. if (warning_ignore_start_lines[pw.code] <= pw.source->start_line) {
  239. continue;
  240. }
  241. GDScriptWarning warning;
  242. warning.code = pw.code;
  243. warning.symbols = pw.symbols;
  244. warning.start_line = pw.source->start_line;
  245. warning.end_line = pw.source->end_line;
  246. if (pw.treated_as_error) {
  247. push_error(warning.get_message() + String(" (Warning treated as error.)"), pw.source);
  248. continue;
  249. }
  250. List<GDScriptWarning>::Element *before = nullptr;
  251. for (List<GDScriptWarning>::Element *E = warnings.front(); E; E = E->next()) {
  252. if (E->get().start_line > warning.start_line) {
  253. break;
  254. }
  255. before = E;
  256. }
  257. if (before) {
  258. warnings.insert_after(before, warning);
  259. } else {
  260. warnings.push_front(warning);
  261. }
  262. }
  263. pending_warnings.clear();
  264. }
  265. void GDScriptParser::evaluate_warning_directory_rules_for_script_path() {
  266. is_script_ignoring_warnings = false;
  267. for (const WarningDirectoryRule &rule : warning_directory_rules) {
  268. if (script_path.begins_with(rule.directory_path)) {
  269. switch (rule.decision) {
  270. case WarningDirectoryRule::DECISION_EXCLUDE:
  271. is_script_ignoring_warnings = true;
  272. return; // Stop checking rules.
  273. case WarningDirectoryRule::DECISION_INCLUDE:
  274. is_script_ignoring_warnings = false;
  275. return; // Stop checking rules.
  276. case WarningDirectoryRule::DECISION_MAX:
  277. return; // Unreachable.
  278. }
  279. }
  280. }
  281. }
  282. #endif // DEBUG_ENABLED
  283. void GDScriptParser::override_completion_context(const Node *p_for_node, CompletionType p_type, Node *p_node, int p_argument) {
  284. if (!for_completion) {
  285. return;
  286. }
  287. if (p_for_node == nullptr || completion_context.node != p_for_node) {
  288. return;
  289. }
  290. CompletionContext context;
  291. context.type = p_type;
  292. context.current_class = current_class;
  293. context.current_function = current_function;
  294. context.current_suite = current_suite;
  295. context.current_line = tokenizer->get_cursor_line();
  296. context.current_argument = p_argument;
  297. context.node = p_node;
  298. context.parser = this;
  299. if (!completion_call_stack.is_empty()) {
  300. context.call = completion_call_stack.back()->get();
  301. }
  302. completion_context = context;
  303. }
  304. void GDScriptParser::make_completion_context(CompletionType p_type, Node *p_node, int p_argument, bool p_force) {
  305. if (!for_completion || (!p_force && completion_context.type != COMPLETION_NONE)) {
  306. return;
  307. }
  308. if (previous.cursor_place != GDScriptTokenizerText::CURSOR_MIDDLE && previous.cursor_place != GDScriptTokenizerText::CURSOR_END && current.cursor_place == GDScriptTokenizerText::CURSOR_NONE) {
  309. return;
  310. }
  311. CompletionContext context;
  312. context.type = p_type;
  313. context.current_class = current_class;
  314. context.current_function = current_function;
  315. context.current_suite = current_suite;
  316. context.current_line = tokenizer->get_cursor_line();
  317. context.current_argument = p_argument;
  318. context.node = p_node;
  319. context.parser = this;
  320. if (!completion_call_stack.is_empty()) {
  321. context.call = completion_call_stack.back()->get();
  322. }
  323. completion_context = context;
  324. }
  325. void GDScriptParser::make_completion_context(CompletionType p_type, Variant::Type p_builtin_type, bool p_force) {
  326. if (!for_completion || (!p_force && completion_context.type != COMPLETION_NONE)) {
  327. return;
  328. }
  329. if (previous.cursor_place != GDScriptTokenizerText::CURSOR_MIDDLE && previous.cursor_place != GDScriptTokenizerText::CURSOR_END && current.cursor_place == GDScriptTokenizerText::CURSOR_NONE) {
  330. return;
  331. }
  332. CompletionContext context;
  333. context.type = p_type;
  334. context.current_class = current_class;
  335. context.current_function = current_function;
  336. context.current_suite = current_suite;
  337. context.current_line = tokenizer->get_cursor_line();
  338. context.builtin_type = p_builtin_type;
  339. context.parser = this;
  340. if (!completion_call_stack.is_empty()) {
  341. context.call = completion_call_stack.back()->get();
  342. }
  343. completion_context = context;
  344. }
  345. void GDScriptParser::push_completion_call(Node *p_call) {
  346. if (!for_completion) {
  347. return;
  348. }
  349. CompletionCall call;
  350. call.call = p_call;
  351. call.argument = 0;
  352. completion_call_stack.push_back(call);
  353. }
  354. void GDScriptParser::pop_completion_call() {
  355. if (!for_completion) {
  356. return;
  357. }
  358. ERR_FAIL_COND_MSG(completion_call_stack.is_empty(), "Trying to pop empty completion call stack");
  359. completion_call_stack.pop_back();
  360. }
  361. void GDScriptParser::set_last_completion_call_arg(int p_argument) {
  362. if (!for_completion) {
  363. return;
  364. }
  365. ERR_FAIL_COND_MSG(completion_call_stack.is_empty(), "Trying to set argument on empty completion call stack");
  366. completion_call_stack.back()->get().argument = p_argument;
  367. }
  368. Error GDScriptParser::parse(const String &p_source_code, const String &p_script_path, bool p_for_completion, bool p_parse_body) {
  369. clear();
  370. String source = p_source_code;
  371. int cursor_line = -1;
  372. int cursor_column = -1;
  373. for_completion = p_for_completion;
  374. parse_body = p_parse_body;
  375. int tab_size = 4;
  376. #ifdef TOOLS_ENABLED
  377. if (EditorSettings::get_singleton()) {
  378. tab_size = EditorSettings::get_singleton()->get_setting("text_editor/behavior/indent/size");
  379. }
  380. #endif // TOOLS_ENABLED
  381. if (p_for_completion) {
  382. // Remove cursor sentinel char.
  383. const Vector<String> lines = p_source_code.split("\n");
  384. cursor_line = 1;
  385. cursor_column = 1;
  386. for (int i = 0; i < lines.size(); i++) {
  387. bool found = false;
  388. const String &line = lines[i];
  389. for (int j = 0; j < line.size(); j++) {
  390. if (line[j] == char32_t(0xFFFF)) {
  391. found = true;
  392. break;
  393. } else if (line[j] == '\t') {
  394. cursor_column += tab_size - 1;
  395. }
  396. cursor_column++;
  397. }
  398. if (found) {
  399. break;
  400. }
  401. cursor_line++;
  402. cursor_column = 1;
  403. }
  404. source = source.replace_first(String::chr(0xFFFF), String());
  405. }
  406. GDScriptTokenizerText *text_tokenizer = memnew(GDScriptTokenizerText);
  407. text_tokenizer->set_source_code(source);
  408. tokenizer = text_tokenizer;
  409. tokenizer->set_cursor_position(cursor_line, cursor_column);
  410. script_path = p_script_path.simplify_path();
  411. #ifdef DEBUG_ENABLED
  412. evaluate_warning_directory_rules_for_script_path();
  413. #endif // DEBUG_ENABLED
  414. current = tokenizer->scan();
  415. // Avoid error or newline as the first token.
  416. // The latter can mess with the parser when opening files filled exclusively with comments and newlines.
  417. while (current.type == GDScriptTokenizer::Token::ERROR || current.type == GDScriptTokenizer::Token::NEWLINE) {
  418. if (current.type == GDScriptTokenizer::Token::ERROR) {
  419. push_error(current.literal);
  420. }
  421. current = tokenizer->scan();
  422. }
  423. #ifdef DEBUG_ENABLED
  424. // Warn about parsing an empty script file:
  425. if (current.type == GDScriptTokenizer::Token::TK_EOF) {
  426. // Create a dummy Node for the warning, pointing to the very beginning of the file
  427. Node *nd = alloc_node<PassNode>();
  428. nd->start_line = 1;
  429. nd->start_column = 0;
  430. nd->end_line = 1;
  431. push_warning(nd, GDScriptWarning::EMPTY_FILE);
  432. }
  433. #endif // DEBUG_ENABLED
  434. push_multiline(false); // Keep one for the whole parsing.
  435. parse_program();
  436. pop_multiline();
  437. #ifdef TOOLS_ENABLED
  438. comment_data = tokenizer->get_comments();
  439. #endif // TOOLS_ENABLED
  440. memdelete(text_tokenizer);
  441. tokenizer = nullptr;
  442. #ifdef DEBUG_ENABLED
  443. if (multiline_stack.size() > 0) {
  444. ERR_PRINT("Parser bug: Imbalanced multiline stack.");
  445. }
  446. #endif // DEBUG_ENABLED
  447. if (errors.is_empty()) {
  448. return OK;
  449. } else {
  450. return ERR_PARSE_ERROR;
  451. }
  452. }
  453. Error GDScriptParser::parse_binary(const Vector<uint8_t> &p_binary, const String &p_script_path) {
  454. GDScriptTokenizerBuffer *buffer_tokenizer = memnew(GDScriptTokenizerBuffer);
  455. Error err = buffer_tokenizer->set_code_buffer(p_binary);
  456. if (err) {
  457. memdelete(buffer_tokenizer);
  458. return err;
  459. }
  460. tokenizer = buffer_tokenizer;
  461. script_path = p_script_path.simplify_path();
  462. #ifdef DEBUG_ENABLED
  463. evaluate_warning_directory_rules_for_script_path();
  464. #endif // DEBUG_ENABLED
  465. current = tokenizer->scan();
  466. // Avoid error or newline as the first token.
  467. // The latter can mess with the parser when opening files filled exclusively with comments and newlines.
  468. while (current.type == GDScriptTokenizer::Token::ERROR || current.type == GDScriptTokenizer::Token::NEWLINE) {
  469. if (current.type == GDScriptTokenizer::Token::ERROR) {
  470. push_error(current.literal);
  471. }
  472. current = tokenizer->scan();
  473. }
  474. push_multiline(false); // Keep one for the whole parsing.
  475. parse_program();
  476. pop_multiline();
  477. memdelete(buffer_tokenizer);
  478. tokenizer = nullptr;
  479. if (errors.is_empty()) {
  480. return OK;
  481. } else {
  482. return ERR_PARSE_ERROR;
  483. }
  484. }
  485. GDScriptTokenizer::Token GDScriptParser::advance() {
  486. lambda_ended = false; // Empty marker since we're past the end in any case.
  487. if (current.type == GDScriptTokenizer::Token::TK_EOF) {
  488. ERR_FAIL_COND_V_MSG(current.type == GDScriptTokenizer::Token::TK_EOF, current, "GDScript parser bug: Trying to advance past the end of stream.");
  489. }
  490. previous = current;
  491. current = tokenizer->scan();
  492. while (current.type == GDScriptTokenizer::Token::ERROR) {
  493. push_error(current.literal);
  494. current = tokenizer->scan();
  495. }
  496. if (previous.type != GDScriptTokenizer::Token::DEDENT) { // `DEDENT` belongs to the next non-empty line.
  497. for (Node *n : nodes_in_progress) {
  498. update_extents(n);
  499. }
  500. }
  501. return previous;
  502. }
  503. bool GDScriptParser::match(GDScriptTokenizer::Token::Type p_token_type) {
  504. if (!check(p_token_type)) {
  505. return false;
  506. }
  507. advance();
  508. return true;
  509. }
  510. bool GDScriptParser::check(GDScriptTokenizer::Token::Type p_token_type) const {
  511. if (p_token_type == GDScriptTokenizer::Token::IDENTIFIER) {
  512. return current.is_identifier();
  513. }
  514. return current.type == p_token_type;
  515. }
  516. bool GDScriptParser::consume(GDScriptTokenizer::Token::Type p_token_type, const String &p_error_message) {
  517. if (match(p_token_type)) {
  518. return true;
  519. }
  520. push_error(p_error_message);
  521. return false;
  522. }
  523. bool GDScriptParser::is_at_end() const {
  524. return check(GDScriptTokenizer::Token::TK_EOF);
  525. }
  526. void GDScriptParser::synchronize() {
  527. panic_mode = false;
  528. while (!is_at_end()) {
  529. if (previous.type == GDScriptTokenizer::Token::NEWLINE || previous.type == GDScriptTokenizer::Token::SEMICOLON) {
  530. return;
  531. }
  532. switch (current.type) {
  533. case GDScriptTokenizer::Token::CLASS:
  534. case GDScriptTokenizer::Token::FUNC:
  535. case GDScriptTokenizer::Token::STATIC:
  536. case GDScriptTokenizer::Token::VAR:
  537. case GDScriptTokenizer::Token::TK_CONST:
  538. case GDScriptTokenizer::Token::SIGNAL:
  539. //case GDScriptTokenizer::Token::IF: // Can also be inside expressions.
  540. case GDScriptTokenizer::Token::FOR:
  541. case GDScriptTokenizer::Token::WHILE:
  542. case GDScriptTokenizer::Token::MATCH:
  543. case GDScriptTokenizer::Token::RETURN:
  544. case GDScriptTokenizer::Token::ANNOTATION:
  545. return;
  546. default:
  547. // Do nothing.
  548. break;
  549. }
  550. advance();
  551. }
  552. }
  553. void GDScriptParser::push_multiline(bool p_state) {
  554. multiline_stack.push_back(p_state);
  555. tokenizer->set_multiline_mode(p_state);
  556. if (p_state) {
  557. // Consume potential whitespace tokens already waiting in line.
  558. while (current.type == GDScriptTokenizer::Token::NEWLINE || current.type == GDScriptTokenizer::Token::INDENT || current.type == GDScriptTokenizer::Token::DEDENT) {
  559. current = tokenizer->scan(); // Don't call advance() here, as we don't want to change the previous token.
  560. }
  561. }
  562. }
  563. void GDScriptParser::pop_multiline() {
  564. ERR_FAIL_COND_MSG(multiline_stack.is_empty(), "Parser bug: trying to pop from multiline stack without available value.");
  565. multiline_stack.pop_back();
  566. tokenizer->set_multiline_mode(multiline_stack.size() > 0 ? multiline_stack.back()->get() : false);
  567. }
  568. bool GDScriptParser::is_statement_end_token() const {
  569. return check(GDScriptTokenizer::Token::NEWLINE) || check(GDScriptTokenizer::Token::SEMICOLON) || check(GDScriptTokenizer::Token::TK_EOF);
  570. }
  571. bool GDScriptParser::is_statement_end() const {
  572. return lambda_ended || in_lambda || is_statement_end_token();
  573. }
  574. void GDScriptParser::end_statement(const String &p_context) {
  575. bool found = false;
  576. while (is_statement_end() && !is_at_end()) {
  577. // Remove sequential newlines/semicolons.
  578. if (is_statement_end_token()) {
  579. // Only consume if this is an actual token.
  580. advance();
  581. } else if (lambda_ended) {
  582. lambda_ended = false; // Consume this "token".
  583. found = true;
  584. break;
  585. } else {
  586. if (!found) {
  587. lambda_ended = true; // Mark the lambda as done since we found something else to end the statement.
  588. found = true;
  589. }
  590. break;
  591. }
  592. found = true;
  593. }
  594. if (!found && !is_at_end()) {
  595. push_error(vformat(R"(Expected end of statement after %s, found "%s" instead.)", p_context, current.get_name()));
  596. }
  597. }
  598. void GDScriptParser::parse_program() {
  599. head = alloc_node<ClassNode>();
  600. head->start_line = 1;
  601. head->end_line = 1;
  602. head->fqcn = GDScript::canonicalize_path(script_path);
  603. current_class = head;
  604. bool can_have_class_or_extends = true;
  605. #define PUSH_PENDING_ANNOTATIONS_TO_HEAD \
  606. if (!annotation_stack.is_empty()) { \
  607. for (AnnotationNode *annot : annotation_stack) { \
  608. head->annotations.push_back(annot); \
  609. } \
  610. annotation_stack.clear(); \
  611. }
  612. while (!check(GDScriptTokenizer::Token::TK_EOF)) {
  613. if (match(GDScriptTokenizer::Token::ANNOTATION)) {
  614. AnnotationNode *annotation = parse_annotation(AnnotationInfo::SCRIPT | AnnotationInfo::CLASS_LEVEL | AnnotationInfo::STANDALONE);
  615. if (annotation != nullptr) {
  616. if (annotation->applies_to(AnnotationInfo::CLASS)) {
  617. // We do not know in advance what the annotation will be applied to: the `head` class or the subsequent inner class.
  618. // If we encounter `class_name`, `extends` or pure `SCRIPT` annotation, then it's `head`, otherwise it's an inner class.
  619. annotation_stack.push_back(annotation);
  620. } else if (annotation->applies_to(AnnotationInfo::SCRIPT)) {
  621. PUSH_PENDING_ANNOTATIONS_TO_HEAD;
  622. if (annotation->name == SNAME("@tool") || annotation->name == SNAME("@icon") || annotation->name == SNAME("@static_unload")) {
  623. // Some annotations need to be resolved and applied in the parser.
  624. // The root class is not in any class, so `head->outer == nullptr`.
  625. annotation->apply(this, head, nullptr);
  626. } else {
  627. head->annotations.push_back(annotation);
  628. }
  629. } else if (annotation->applies_to(AnnotationInfo::STANDALONE)) {
  630. if (previous.type != GDScriptTokenizer::Token::NEWLINE) {
  631. push_error(R"(Expected newline after a standalone annotation.)");
  632. }
  633. if (annotation->name == SNAME("@export_category") || annotation->name == SNAME("@export_group") || annotation->name == SNAME("@export_subgroup")) {
  634. head->add_member_group(annotation);
  635. // This annotation must appear after script-level annotations and `class_name`/`extends`,
  636. // so we stop looking for script-level stuff.
  637. can_have_class_or_extends = false;
  638. break;
  639. } else if (annotation->name == SNAME("@warning_ignore_start") || annotation->name == SNAME("@warning_ignore_restore")) {
  640. // Some annotations need to be resolved and applied in the parser.
  641. annotation->apply(this, nullptr, nullptr);
  642. } else {
  643. push_error(R"(Unexpected standalone annotation.)");
  644. }
  645. } else {
  646. annotation_stack.push_back(annotation);
  647. // This annotation must appear after script-level annotations and `class_name`/`extends`,
  648. // so we stop looking for script-level stuff.
  649. can_have_class_or_extends = false;
  650. break;
  651. }
  652. }
  653. } else if (check(GDScriptTokenizer::Token::LITERAL) && current.literal.get_type() == Variant::STRING) {
  654. // Allow strings in class body as multiline comments.
  655. advance();
  656. if (!match(GDScriptTokenizer::Token::NEWLINE)) {
  657. push_error("Expected newline after comment string.");
  658. }
  659. } else {
  660. break;
  661. }
  662. }
  663. if (current.type == GDScriptTokenizer::Token::CLASS_NAME || current.type == GDScriptTokenizer::Token::EXTENDS) {
  664. // Set range of the class to only start at extends or class_name if present.
  665. reset_extents(head, current);
  666. }
  667. while (can_have_class_or_extends) {
  668. // Order here doesn't matter, but there should be only one of each at most.
  669. switch (current.type) {
  670. case GDScriptTokenizer::Token::CLASS_NAME:
  671. PUSH_PENDING_ANNOTATIONS_TO_HEAD;
  672. advance();
  673. if (head->identifier != nullptr) {
  674. push_error(R"("class_name" can only be used once.)");
  675. } else {
  676. parse_class_name();
  677. }
  678. break;
  679. case GDScriptTokenizer::Token::EXTENDS:
  680. PUSH_PENDING_ANNOTATIONS_TO_HEAD;
  681. advance();
  682. if (head->extends_used) {
  683. push_error(R"("extends" can only be used once.)");
  684. } else {
  685. parse_extends();
  686. end_statement("superclass");
  687. }
  688. break;
  689. case GDScriptTokenizer::Token::TK_EOF:
  690. PUSH_PENDING_ANNOTATIONS_TO_HEAD;
  691. can_have_class_or_extends = false;
  692. break;
  693. case GDScriptTokenizer::Token::LITERAL:
  694. if (current.literal.get_type() == Variant::STRING) {
  695. // Allow strings in class body as multiline comments.
  696. advance();
  697. if (!match(GDScriptTokenizer::Token::NEWLINE)) {
  698. push_error("Expected newline after comment string.");
  699. }
  700. break;
  701. }
  702. [[fallthrough]];
  703. default:
  704. // No tokens are allowed between script annotations and class/extends.
  705. can_have_class_or_extends = false;
  706. break;
  707. }
  708. if (panic_mode) {
  709. synchronize();
  710. }
  711. }
  712. #undef PUSH_PENDING_ANNOTATIONS_TO_HEAD
  713. for (AnnotationNode *&annotation : head->annotations) {
  714. if (annotation->name == SNAME("@abstract")) {
  715. // Some annotations need to be resolved and applied in the parser.
  716. // The root class is not in any class, so `head->outer == nullptr`.
  717. annotation->apply(this, head, nullptr);
  718. }
  719. }
  720. // When the only thing needed is the class name, icon, and abstractness; we don't need to parse the whole file.
  721. // It really speed up the call to `GDScriptLanguage::get_global_class_name()` especially for large script.
  722. if (!parse_body) {
  723. return;
  724. }
  725. parse_class_body(true);
  726. head->end_line = current.end_line;
  727. head->end_column = current.end_column;
  728. complete_extents(head);
  729. #ifdef TOOLS_ENABLED
  730. const HashMap<int, GDScriptTokenizer::CommentData> &comments = tokenizer->get_comments();
  731. int max_line = head->end_line;
  732. if (!head->members.is_empty()) {
  733. max_line = MIN(max_script_doc_line, head->members[0].get_line() - 1);
  734. }
  735. int line = 0;
  736. while (line <= max_line) {
  737. // Find the start.
  738. if (comments.has(line) && comments[line].new_line && comments[line].comment.begins_with("##")) {
  739. // Find the end.
  740. while (line + 1 <= max_line && comments.has(line + 1) && comments[line + 1].new_line && comments[line + 1].comment.begins_with("##")) {
  741. line++;
  742. }
  743. head->doc_data = parse_class_doc_comment(line);
  744. break;
  745. }
  746. line++;
  747. }
  748. #endif // TOOLS_ENABLED
  749. if (!check(GDScriptTokenizer::Token::TK_EOF)) {
  750. push_error("Expected end of file.");
  751. }
  752. clear_unused_annotations();
  753. }
  754. Ref<GDScriptParserRef> GDScriptParser::get_depended_parser_for(const String &p_path) {
  755. Ref<GDScriptParserRef> ref;
  756. if (depended_parsers.has(p_path)) {
  757. ref = depended_parsers[p_path];
  758. } else {
  759. Error err = OK;
  760. ref = GDScriptCache::get_parser(p_path, GDScriptParserRef::EMPTY, err, script_path);
  761. if (ref.is_valid()) {
  762. depended_parsers[p_path] = ref;
  763. }
  764. }
  765. return ref;
  766. }
  767. const HashMap<String, Ref<GDScriptParserRef>> &GDScriptParser::get_depended_parsers() {
  768. return depended_parsers;
  769. }
  770. GDScriptParser::ClassNode *GDScriptParser::find_class(const String &p_qualified_name) const {
  771. String first = p_qualified_name.get_slice("::", 0);
  772. Vector<String> class_names;
  773. GDScriptParser::ClassNode *result = nullptr;
  774. // Empty initial name means start at the head.
  775. if (first.is_empty() || (head->identifier && first == head->identifier->name)) {
  776. class_names = p_qualified_name.split("::");
  777. result = head;
  778. } else if (p_qualified_name.begins_with(script_path)) {
  779. // Script path could have a class path separator("::") in it.
  780. class_names = p_qualified_name.trim_prefix(script_path).split("::");
  781. result = head;
  782. } else if (head->has_member(first)) {
  783. class_names = p_qualified_name.split("::");
  784. GDScriptParser::ClassNode::Member member = head->get_member(first);
  785. if (member.type == GDScriptParser::ClassNode::Member::CLASS) {
  786. result = member.m_class;
  787. }
  788. }
  789. // Starts at index 1 because index 0 was handled above.
  790. for (int i = 1; result != nullptr && i < class_names.size(); i++) {
  791. const String &current_name = class_names[i];
  792. GDScriptParser::ClassNode *next = nullptr;
  793. if (result->has_member(current_name)) {
  794. GDScriptParser::ClassNode::Member member = result->get_member(current_name);
  795. if (member.type == GDScriptParser::ClassNode::Member::CLASS) {
  796. next = member.m_class;
  797. }
  798. }
  799. result = next;
  800. }
  801. return result;
  802. }
  803. bool GDScriptParser::has_class(const GDScriptParser::ClassNode *p_class) const {
  804. if (head->fqcn.is_empty() && p_class->fqcn.get_slice("::", 0).is_empty()) {
  805. return p_class == head;
  806. } else if (p_class->fqcn.begins_with(head->fqcn)) {
  807. return find_class(p_class->fqcn.trim_prefix(head->fqcn)) == p_class;
  808. }
  809. return false;
  810. }
  811. GDScriptParser::ClassNode *GDScriptParser::parse_class(bool p_is_static) {
  812. ClassNode *n_class = alloc_node<ClassNode>();
  813. ClassNode *previous_class = current_class;
  814. current_class = n_class;
  815. n_class->outer = previous_class;
  816. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier for the class name after "class".)")) {
  817. n_class->identifier = parse_identifier();
  818. if (n_class->outer) {
  819. String fqcn = n_class->outer->fqcn;
  820. if (fqcn.is_empty()) {
  821. fqcn = GDScript::canonicalize_path(script_path);
  822. }
  823. n_class->fqcn = fqcn + "::" + n_class->identifier->name;
  824. } else {
  825. n_class->fqcn = n_class->identifier->name;
  826. }
  827. }
  828. if (match(GDScriptTokenizer::Token::EXTENDS)) {
  829. parse_extends();
  830. }
  831. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after class declaration.)");
  832. bool multiline = match(GDScriptTokenizer::Token::NEWLINE);
  833. if (multiline && !consume(GDScriptTokenizer::Token::INDENT, R"(Expected indented block after class declaration.)")) {
  834. current_class = previous_class;
  835. complete_extents(n_class);
  836. return n_class;
  837. }
  838. if (match(GDScriptTokenizer::Token::EXTENDS)) {
  839. if (n_class->extends_used) {
  840. push_error(R"(Cannot use "extends" more than once in the same class.)");
  841. }
  842. parse_extends();
  843. end_statement("superclass");
  844. }
  845. parse_class_body(multiline);
  846. complete_extents(n_class);
  847. if (multiline) {
  848. consume(GDScriptTokenizer::Token::DEDENT, R"(Missing unindent at the end of the class body.)");
  849. }
  850. current_class = previous_class;
  851. return n_class;
  852. }
  853. void GDScriptParser::parse_class_name() {
  854. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier for the global class name after "class_name".)")) {
  855. current_class->identifier = parse_identifier();
  856. current_class->fqcn = String(current_class->identifier->name);
  857. }
  858. if (match(GDScriptTokenizer::Token::EXTENDS)) {
  859. // Allow extends on the same line.
  860. parse_extends();
  861. end_statement("superclass");
  862. } else {
  863. end_statement("class_name statement");
  864. }
  865. }
  866. void GDScriptParser::parse_extends() {
  867. current_class->extends_used = true;
  868. int chain_index = 0;
  869. if (match(GDScriptTokenizer::Token::LITERAL)) {
  870. if (previous.literal.get_type() != Variant::STRING) {
  871. push_error(vformat(R"(Only strings or identifiers can be used after "extends", found "%s" instead.)", Variant::get_type_name(previous.literal.get_type())));
  872. }
  873. current_class->extends_path = previous.literal;
  874. if (!match(GDScriptTokenizer::Token::PERIOD)) {
  875. return;
  876. }
  877. }
  878. make_completion_context(COMPLETION_INHERIT_TYPE, current_class, chain_index++);
  879. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected superclass name after "extends".)")) {
  880. return;
  881. }
  882. current_class->extends.push_back(parse_identifier());
  883. while (match(GDScriptTokenizer::Token::PERIOD)) {
  884. make_completion_context(COMPLETION_INHERIT_TYPE, current_class, chain_index++);
  885. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected superclass name after ".".)")) {
  886. return;
  887. }
  888. current_class->extends.push_back(parse_identifier());
  889. }
  890. }
  891. template <typename T>
  892. void GDScriptParser::parse_class_member(T *(GDScriptParser::*p_parse_function)(bool), AnnotationInfo::TargetKind p_target, const String &p_member_kind, bool p_is_static) {
  893. advance();
  894. // Consume annotations.
  895. List<AnnotationNode *> annotations;
  896. while (!annotation_stack.is_empty()) {
  897. AnnotationNode *last_annotation = annotation_stack.back()->get();
  898. if (last_annotation->applies_to(p_target)) {
  899. annotations.push_front(last_annotation);
  900. annotation_stack.pop_back();
  901. } else {
  902. push_error(vformat(R"(Annotation "%s" cannot be applied to a %s.)", last_annotation->name, p_member_kind));
  903. clear_unused_annotations();
  904. }
  905. }
  906. T *member = (this->*p_parse_function)(p_is_static);
  907. if (member == nullptr) {
  908. return;
  909. }
  910. #ifdef TOOLS_ENABLED
  911. int doc_comment_line = member->start_line - 1;
  912. #endif // TOOLS_ENABLED
  913. for (AnnotationNode *&annotation : annotations) {
  914. member->annotations.push_back(annotation);
  915. #ifdef TOOLS_ENABLED
  916. if (annotation->start_line <= doc_comment_line) {
  917. doc_comment_line = annotation->start_line - 1;
  918. }
  919. #endif // TOOLS_ENABLED
  920. }
  921. #ifdef TOOLS_ENABLED
  922. if constexpr (std::is_same_v<T, ClassNode>) {
  923. if (has_comment(member->start_line, true)) {
  924. // Inline doc comment.
  925. member->doc_data = parse_class_doc_comment(member->start_line, true);
  926. } else if (has_comment(doc_comment_line, true) && tokenizer->get_comments()[doc_comment_line].new_line) {
  927. // Normal doc comment. Don't check `min_member_doc_line` because a class ends parsing after its members.
  928. // This may not work correctly for cases like `var a; class B`, but it doesn't matter in practice.
  929. member->doc_data = parse_class_doc_comment(doc_comment_line);
  930. }
  931. } else {
  932. if (has_comment(member->start_line, true)) {
  933. // Inline doc comment.
  934. member->doc_data = parse_doc_comment(member->start_line, true);
  935. } else if (doc_comment_line >= min_member_doc_line && has_comment(doc_comment_line, true) && tokenizer->get_comments()[doc_comment_line].new_line) {
  936. // Normal doc comment.
  937. member->doc_data = parse_doc_comment(doc_comment_line);
  938. }
  939. }
  940. min_member_doc_line = member->end_line + 1; // Prevent multiple members from using the same doc comment.
  941. #endif // TOOLS_ENABLED
  942. if (member->identifier != nullptr) {
  943. if (!((String)member->identifier->name).is_empty()) { // Enums may be unnamed.
  944. if (current_class->members_indices.has(member->identifier->name)) {
  945. push_error(vformat(R"(%s "%s" has the same name as a previously declared %s.)", p_member_kind.capitalize(), member->identifier->name, current_class->get_member(member->identifier->name).get_type_name()), member->identifier);
  946. } else {
  947. current_class->add_member(member);
  948. }
  949. } else {
  950. current_class->add_member(member);
  951. }
  952. }
  953. }
  954. void GDScriptParser::parse_class_body(bool p_is_multiline) {
  955. bool class_end = false;
  956. bool next_is_static = false;
  957. while (!class_end && !is_at_end()) {
  958. GDScriptTokenizer::Token token = current;
  959. switch (token.type) {
  960. case GDScriptTokenizer::Token::VAR:
  961. parse_class_member(&GDScriptParser::parse_variable, AnnotationInfo::VARIABLE, "variable", next_is_static);
  962. if (next_is_static) {
  963. current_class->has_static_data = true;
  964. }
  965. break;
  966. case GDScriptTokenizer::Token::TK_CONST:
  967. parse_class_member(&GDScriptParser::parse_constant, AnnotationInfo::CONSTANT, "constant");
  968. break;
  969. case GDScriptTokenizer::Token::SIGNAL:
  970. parse_class_member(&GDScriptParser::parse_signal, AnnotationInfo::SIGNAL, "signal");
  971. break;
  972. case GDScriptTokenizer::Token::FUNC:
  973. parse_class_member(&GDScriptParser::parse_function, AnnotationInfo::FUNCTION, "function", next_is_static);
  974. break;
  975. case GDScriptTokenizer::Token::CLASS:
  976. parse_class_member(&GDScriptParser::parse_class, AnnotationInfo::CLASS, "class");
  977. break;
  978. case GDScriptTokenizer::Token::ENUM:
  979. parse_class_member(&GDScriptParser::parse_enum, AnnotationInfo::NONE, "enum");
  980. break;
  981. case GDScriptTokenizer::Token::STATIC: {
  982. advance();
  983. next_is_static = true;
  984. if (!check(GDScriptTokenizer::Token::FUNC) && !check(GDScriptTokenizer::Token::VAR)) {
  985. push_error(R"(Expected "func" or "var" after "static".)");
  986. }
  987. } break;
  988. case GDScriptTokenizer::Token::ANNOTATION: {
  989. advance();
  990. // Check for class-level and standalone annotations.
  991. AnnotationNode *annotation = parse_annotation(AnnotationInfo::CLASS_LEVEL | AnnotationInfo::STANDALONE);
  992. if (annotation != nullptr) {
  993. if (annotation->applies_to(AnnotationInfo::STANDALONE)) {
  994. if (previous.type != GDScriptTokenizer::Token::NEWLINE) {
  995. push_error(R"(Expected newline after a standalone annotation.)");
  996. }
  997. if (annotation->name == SNAME("@export_category") || annotation->name == SNAME("@export_group") || annotation->name == SNAME("@export_subgroup")) {
  998. current_class->add_member_group(annotation);
  999. } else if (annotation->name == SNAME("@warning_ignore_start") || annotation->name == SNAME("@warning_ignore_restore")) {
  1000. // Some annotations need to be resolved and applied in the parser.
  1001. annotation->apply(this, nullptr, nullptr);
  1002. } else {
  1003. push_error(R"(Unexpected standalone annotation.)");
  1004. }
  1005. } else { // `AnnotationInfo::CLASS_LEVEL`.
  1006. annotation_stack.push_back(annotation);
  1007. }
  1008. }
  1009. break;
  1010. }
  1011. case GDScriptTokenizer::Token::PASS:
  1012. advance();
  1013. end_statement(R"("pass")");
  1014. break;
  1015. case GDScriptTokenizer::Token::DEDENT:
  1016. class_end = true;
  1017. break;
  1018. case GDScriptTokenizer::Token::LITERAL:
  1019. if (current.literal.get_type() == Variant::STRING) {
  1020. // Allow strings in class body as multiline comments.
  1021. advance();
  1022. if (!match(GDScriptTokenizer::Token::NEWLINE)) {
  1023. push_error("Expected newline after comment string.");
  1024. }
  1025. break;
  1026. }
  1027. [[fallthrough]];
  1028. default:
  1029. // Display a completion with identifiers.
  1030. make_completion_context(COMPLETION_IDENTIFIER, nullptr);
  1031. advance();
  1032. if (previous.get_identifier() == "export") {
  1033. push_error(R"(The "export" keyword was removed in Godot 4. Use an export annotation ("@export", "@export_range", etc.) instead.)");
  1034. } else if (previous.get_identifier() == "tool") {
  1035. push_error(R"(The "tool" keyword was removed in Godot 4. Use the "@tool" annotation instead.)");
  1036. } else if (previous.get_identifier() == "onready") {
  1037. push_error(R"(The "onready" keyword was removed in Godot 4. Use the "@onready" annotation instead.)");
  1038. } else if (previous.get_identifier() == "remote") {
  1039. push_error(R"(The "remote" keyword was removed in Godot 4. Use the "@rpc" annotation with "any_peer" instead.)");
  1040. } else if (previous.get_identifier() == "remotesync") {
  1041. push_error(R"(The "remotesync" keyword was removed in Godot 4. Use the "@rpc" annotation with "any_peer" and "call_local" instead.)");
  1042. } else if (previous.get_identifier() == "puppet") {
  1043. push_error(R"(The "puppet" keyword was removed in Godot 4. Use the "@rpc" annotation with "authority" instead.)");
  1044. } else if (previous.get_identifier() == "puppetsync") {
  1045. push_error(R"(The "puppetsync" keyword was removed in Godot 4. Use the "@rpc" annotation with "authority" and "call_local" instead.)");
  1046. } else if (previous.get_identifier() == "master") {
  1047. push_error(R"(The "master" keyword was removed in Godot 4. Use the "@rpc" annotation with "any_peer" and perform a check inside the function instead.)");
  1048. } else if (previous.get_identifier() == "mastersync") {
  1049. push_error(R"(The "mastersync" keyword was removed in Godot 4. Use the "@rpc" annotation with "any_peer" and "call_local", and perform a check inside the function instead.)");
  1050. } else {
  1051. push_error(vformat(R"(Unexpected %s in class body.)", previous.get_debug_name()));
  1052. }
  1053. break;
  1054. }
  1055. if (token.type != GDScriptTokenizer::Token::STATIC) {
  1056. next_is_static = false;
  1057. }
  1058. if (panic_mode) {
  1059. synchronize();
  1060. }
  1061. if (!p_is_multiline) {
  1062. class_end = true;
  1063. }
  1064. }
  1065. }
  1066. GDScriptParser::VariableNode *GDScriptParser::parse_variable(bool p_is_static) {
  1067. return parse_variable(p_is_static, true);
  1068. }
  1069. GDScriptParser::VariableNode *GDScriptParser::parse_variable(bool p_is_static, bool p_allow_property) {
  1070. VariableNode *variable = alloc_node<VariableNode>();
  1071. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected variable name after "var".)")) {
  1072. complete_extents(variable);
  1073. return nullptr;
  1074. }
  1075. variable->identifier = parse_identifier();
  1076. variable->export_info.name = variable->identifier->name;
  1077. variable->is_static = p_is_static;
  1078. if (match(GDScriptTokenizer::Token::COLON)) {
  1079. if (check(GDScriptTokenizer::Token::NEWLINE)) {
  1080. if (p_allow_property) {
  1081. advance();
  1082. return parse_property(variable, true);
  1083. } else {
  1084. push_error(R"(Expected type after ":")");
  1085. complete_extents(variable);
  1086. return nullptr;
  1087. }
  1088. } else if (check((GDScriptTokenizer::Token::EQUAL))) {
  1089. // Infer type.
  1090. variable->infer_datatype = true;
  1091. } else {
  1092. if (p_allow_property) {
  1093. make_completion_context(COMPLETION_PROPERTY_DECLARATION_OR_TYPE, variable);
  1094. if (check(GDScriptTokenizer::Token::IDENTIFIER)) {
  1095. // Check if get or set.
  1096. if (current.get_identifier() == "get" || current.get_identifier() == "set") {
  1097. return parse_property(variable, false);
  1098. }
  1099. }
  1100. }
  1101. // Parse type.
  1102. variable->datatype_specifier = parse_type();
  1103. }
  1104. }
  1105. if (match(GDScriptTokenizer::Token::EQUAL)) {
  1106. // Initializer.
  1107. variable->initializer = parse_expression(false);
  1108. if (variable->initializer == nullptr) {
  1109. push_error(R"(Expected expression for variable initial value after "=".)");
  1110. }
  1111. variable->assignments++;
  1112. }
  1113. if (p_allow_property && match(GDScriptTokenizer::Token::COLON)) {
  1114. if (match(GDScriptTokenizer::Token::NEWLINE)) {
  1115. return parse_property(variable, true);
  1116. } else {
  1117. return parse_property(variable, false);
  1118. }
  1119. }
  1120. complete_extents(variable);
  1121. end_statement("variable declaration");
  1122. return variable;
  1123. }
  1124. GDScriptParser::VariableNode *GDScriptParser::parse_property(VariableNode *p_variable, bool p_need_indent) {
  1125. if (p_need_indent) {
  1126. if (!consume(GDScriptTokenizer::Token::INDENT, R"(Expected indented block for property after ":".)")) {
  1127. complete_extents(p_variable);
  1128. return nullptr;
  1129. }
  1130. }
  1131. VariableNode *property = p_variable;
  1132. make_completion_context(COMPLETION_PROPERTY_DECLARATION, property);
  1133. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected "get" or "set" for property declaration.)")) {
  1134. complete_extents(p_variable);
  1135. return nullptr;
  1136. }
  1137. IdentifierNode *function = parse_identifier();
  1138. if (check(GDScriptTokenizer::Token::EQUAL)) {
  1139. p_variable->property = VariableNode::PROP_SETGET;
  1140. } else {
  1141. p_variable->property = VariableNode::PROP_INLINE;
  1142. if (!p_need_indent) {
  1143. push_error("Property with inline code must go to an indented block.");
  1144. }
  1145. }
  1146. bool getter_used = false;
  1147. bool setter_used = false;
  1148. // Run with a loop because order doesn't matter.
  1149. for (int i = 0; i < 2; i++) {
  1150. if (function->name == SNAME("set")) {
  1151. if (setter_used) {
  1152. push_error(R"(Properties can only have one setter.)");
  1153. } else {
  1154. parse_property_setter(property);
  1155. setter_used = true;
  1156. }
  1157. } else if (function->name == SNAME("get")) {
  1158. if (getter_used) {
  1159. push_error(R"(Properties can only have one getter.)");
  1160. } else {
  1161. parse_property_getter(property);
  1162. getter_used = true;
  1163. }
  1164. } else {
  1165. // TODO: Update message to only have the missing one if it's the case.
  1166. push_error(R"(Expected "get" or "set" for property declaration.)");
  1167. }
  1168. if (i == 0 && p_variable->property == VariableNode::PROP_SETGET) {
  1169. if (match(GDScriptTokenizer::Token::COMMA)) {
  1170. // Consume potential newline.
  1171. if (match(GDScriptTokenizer::Token::NEWLINE)) {
  1172. if (!p_need_indent) {
  1173. push_error(R"(Inline setter/getter setting cannot span across multiple lines (use "\\"" if needed).)");
  1174. }
  1175. }
  1176. } else {
  1177. break;
  1178. }
  1179. }
  1180. if (!match(GDScriptTokenizer::Token::IDENTIFIER)) {
  1181. break;
  1182. }
  1183. function = parse_identifier();
  1184. }
  1185. complete_extents(p_variable);
  1186. if (p_variable->property == VariableNode::PROP_SETGET) {
  1187. end_statement("property declaration");
  1188. }
  1189. if (p_need_indent) {
  1190. consume(GDScriptTokenizer::Token::DEDENT, R"(Expected end of indented block for property.)");
  1191. }
  1192. return property;
  1193. }
  1194. void GDScriptParser::parse_property_setter(VariableNode *p_variable) {
  1195. switch (p_variable->property) {
  1196. case VariableNode::PROP_INLINE: {
  1197. FunctionNode *function = alloc_node<FunctionNode>();
  1198. IdentifierNode *identifier = alloc_node<IdentifierNode>();
  1199. complete_extents(identifier);
  1200. identifier->name = "@" + p_variable->identifier->name + "_setter";
  1201. function->identifier = identifier;
  1202. function->is_static = p_variable->is_static;
  1203. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "set".)");
  1204. ParameterNode *parameter = alloc_node<ParameterNode>();
  1205. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected parameter name after "(".)")) {
  1206. reset_extents(parameter, previous);
  1207. p_variable->setter_parameter = parse_identifier();
  1208. parameter->identifier = p_variable->setter_parameter;
  1209. function->parameters_indices[parameter->identifier->name] = 0;
  1210. function->parameters.push_back(parameter);
  1211. }
  1212. complete_extents(parameter);
  1213. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after parameter name.)*");
  1214. consume(GDScriptTokenizer::Token::COLON, R"*(Expected ":" after ")".)*");
  1215. FunctionNode *previous_function = current_function;
  1216. current_function = function;
  1217. if (p_variable->setter_parameter != nullptr) {
  1218. SuiteNode *body = alloc_node<SuiteNode>();
  1219. body->add_local(parameter, function);
  1220. function->body = parse_suite("setter declaration", body);
  1221. p_variable->setter = function;
  1222. }
  1223. current_function = previous_function;
  1224. complete_extents(function);
  1225. break;
  1226. }
  1227. case VariableNode::PROP_SETGET:
  1228. consume(GDScriptTokenizer::Token::EQUAL, R"(Expected "=" after "set")");
  1229. make_completion_context(COMPLETION_PROPERTY_METHOD, p_variable);
  1230. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected setter function name after "=".)")) {
  1231. p_variable->setter_pointer = parse_identifier();
  1232. }
  1233. break;
  1234. case VariableNode::PROP_NONE:
  1235. break; // Unreachable.
  1236. }
  1237. }
  1238. void GDScriptParser::parse_property_getter(VariableNode *p_variable) {
  1239. switch (p_variable->property) {
  1240. case VariableNode::PROP_INLINE: {
  1241. FunctionNode *function = alloc_node<FunctionNode>();
  1242. if (match(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  1243. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after "get(".)*");
  1244. consume(GDScriptTokenizer::Token::COLON, R"*(Expected ":" after "get()".)*");
  1245. } else {
  1246. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" or "(" after "get".)");
  1247. }
  1248. IdentifierNode *identifier = alloc_node<IdentifierNode>();
  1249. complete_extents(identifier);
  1250. identifier->name = "@" + p_variable->identifier->name + "_getter";
  1251. function->identifier = identifier;
  1252. function->is_static = p_variable->is_static;
  1253. FunctionNode *previous_function = current_function;
  1254. current_function = function;
  1255. SuiteNode *body = alloc_node<SuiteNode>();
  1256. function->body = parse_suite("getter declaration", body);
  1257. p_variable->getter = function;
  1258. current_function = previous_function;
  1259. complete_extents(function);
  1260. break;
  1261. }
  1262. case VariableNode::PROP_SETGET:
  1263. consume(GDScriptTokenizer::Token::EQUAL, R"(Expected "=" after "get")");
  1264. make_completion_context(COMPLETION_PROPERTY_METHOD, p_variable);
  1265. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected getter function name after "=".)")) {
  1266. p_variable->getter_pointer = parse_identifier();
  1267. }
  1268. break;
  1269. case VariableNode::PROP_NONE:
  1270. break; // Unreachable.
  1271. }
  1272. }
  1273. GDScriptParser::ConstantNode *GDScriptParser::parse_constant(bool p_is_static) {
  1274. ConstantNode *constant = alloc_node<ConstantNode>();
  1275. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected constant name after "const".)")) {
  1276. complete_extents(constant);
  1277. return nullptr;
  1278. }
  1279. constant->identifier = parse_identifier();
  1280. if (match(GDScriptTokenizer::Token::COLON)) {
  1281. if (check((GDScriptTokenizer::Token::EQUAL))) {
  1282. // Infer type.
  1283. constant->infer_datatype = true;
  1284. } else {
  1285. // Parse type.
  1286. constant->datatype_specifier = parse_type();
  1287. }
  1288. }
  1289. if (consume(GDScriptTokenizer::Token::EQUAL, R"(Expected initializer after constant name.)")) {
  1290. // Initializer.
  1291. constant->initializer = parse_expression(false);
  1292. if (constant->initializer == nullptr) {
  1293. push_error(R"(Expected initializer expression for constant.)");
  1294. complete_extents(constant);
  1295. return nullptr;
  1296. }
  1297. } else {
  1298. complete_extents(constant);
  1299. return nullptr;
  1300. }
  1301. complete_extents(constant);
  1302. end_statement("constant declaration");
  1303. return constant;
  1304. }
  1305. GDScriptParser::ParameterNode *GDScriptParser::parse_parameter() {
  1306. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected parameter name.)")) {
  1307. return nullptr;
  1308. }
  1309. ParameterNode *parameter = alloc_node<ParameterNode>();
  1310. parameter->identifier = parse_identifier();
  1311. if (match(GDScriptTokenizer::Token::COLON)) {
  1312. if (check((GDScriptTokenizer::Token::EQUAL))) {
  1313. // Infer type.
  1314. parameter->infer_datatype = true;
  1315. } else {
  1316. // Parse type.
  1317. make_completion_context(COMPLETION_TYPE_NAME, parameter);
  1318. parameter->datatype_specifier = parse_type();
  1319. }
  1320. }
  1321. if (match(GDScriptTokenizer::Token::EQUAL)) {
  1322. // Default value.
  1323. parameter->initializer = parse_expression(false);
  1324. }
  1325. complete_extents(parameter);
  1326. return parameter;
  1327. }
  1328. GDScriptParser::SignalNode *GDScriptParser::parse_signal(bool p_is_static) {
  1329. SignalNode *signal = alloc_node<SignalNode>();
  1330. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected signal name after "signal".)")) {
  1331. complete_extents(signal);
  1332. return nullptr;
  1333. }
  1334. signal->identifier = parse_identifier();
  1335. if (check(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  1336. push_multiline(true);
  1337. advance();
  1338. do {
  1339. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  1340. // Allow for trailing comma.
  1341. break;
  1342. }
  1343. ParameterNode *parameter = parse_parameter();
  1344. if (parameter == nullptr) {
  1345. push_error("Expected signal parameter name.");
  1346. break;
  1347. }
  1348. if (parameter->initializer != nullptr) {
  1349. push_error(R"(Signal parameters cannot have a default value.)");
  1350. }
  1351. if (signal->parameters_indices.has(parameter->identifier->name)) {
  1352. push_error(vformat(R"(Parameter with name "%s" was already declared for this signal.)", parameter->identifier->name));
  1353. } else {
  1354. signal->parameters_indices[parameter->identifier->name] = signal->parameters.size();
  1355. signal->parameters.push_back(parameter);
  1356. }
  1357. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  1358. pop_multiline();
  1359. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after signal parameters.)*");
  1360. }
  1361. complete_extents(signal);
  1362. end_statement("signal declaration");
  1363. return signal;
  1364. }
  1365. GDScriptParser::EnumNode *GDScriptParser::parse_enum(bool p_is_static) {
  1366. EnumNode *enum_node = alloc_node<EnumNode>();
  1367. bool named = false;
  1368. if (match(GDScriptTokenizer::Token::IDENTIFIER)) {
  1369. enum_node->identifier = parse_identifier();
  1370. named = true;
  1371. }
  1372. push_multiline(true);
  1373. consume(GDScriptTokenizer::Token::BRACE_OPEN, vformat(R"(Expected "{" after %s.)", named ? "enum name" : R"("enum")"));
  1374. #ifdef TOOLS_ENABLED
  1375. int min_enum_value_doc_line = previous.end_line + 1;
  1376. #endif
  1377. HashMap<StringName, int> elements;
  1378. #ifdef DEBUG_ENABLED
  1379. List<MethodInfo> gdscript_funcs;
  1380. GDScriptLanguage::get_singleton()->get_public_functions(&gdscript_funcs);
  1381. #endif
  1382. do {
  1383. if (check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  1384. break; // Allow trailing comma.
  1385. }
  1386. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier for enum key.)")) {
  1387. GDScriptParser::IdentifierNode *identifier = parse_identifier();
  1388. EnumNode::Value item;
  1389. item.identifier = identifier;
  1390. item.parent_enum = enum_node;
  1391. item.line = previous.start_line;
  1392. item.start_column = previous.start_column;
  1393. item.end_column = previous.end_column;
  1394. if (elements.has(item.identifier->name)) {
  1395. push_error(vformat(R"(Name "%s" was already in this enum (at line %d).)", item.identifier->name, elements[item.identifier->name]), item.identifier);
  1396. } else if (!named) {
  1397. if (current_class->members_indices.has(item.identifier->name)) {
  1398. push_error(vformat(R"(Name "%s" is already used as a class %s.)", item.identifier->name, current_class->get_member(item.identifier->name).get_type_name()));
  1399. }
  1400. }
  1401. elements[item.identifier->name] = item.line;
  1402. if (match(GDScriptTokenizer::Token::EQUAL)) {
  1403. ExpressionNode *value = parse_expression(false);
  1404. if (value == nullptr) {
  1405. push_error(R"(Expected expression value after "=".)");
  1406. }
  1407. item.custom_value = value;
  1408. }
  1409. item.index = enum_node->values.size();
  1410. enum_node->values.push_back(item);
  1411. if (!named) {
  1412. // Add as member of current class.
  1413. current_class->add_member(item);
  1414. }
  1415. }
  1416. } while (match(GDScriptTokenizer::Token::COMMA));
  1417. #ifdef TOOLS_ENABLED
  1418. // Enum values documentation.
  1419. for (int i = 0; i < enum_node->values.size(); i++) {
  1420. int enum_value_line = enum_node->values[i].line;
  1421. int doc_comment_line = enum_value_line - 1;
  1422. MemberDocData doc_data;
  1423. if (has_comment(enum_value_line, true)) {
  1424. // Inline doc comment.
  1425. if (i == enum_node->values.size() - 1 || enum_node->values[i + 1].line > enum_value_line) {
  1426. doc_data = parse_doc_comment(enum_value_line, true);
  1427. }
  1428. } else if (doc_comment_line >= min_enum_value_doc_line && has_comment(doc_comment_line, true) && tokenizer->get_comments()[doc_comment_line].new_line) {
  1429. // Normal doc comment.
  1430. doc_data = parse_doc_comment(doc_comment_line);
  1431. }
  1432. if (named) {
  1433. enum_node->values.write[i].doc_data = doc_data;
  1434. } else {
  1435. current_class->set_enum_value_doc_data(enum_node->values[i].identifier->name, doc_data);
  1436. }
  1437. min_enum_value_doc_line = enum_value_line + 1; // Prevent multiple enum values from using the same doc comment.
  1438. }
  1439. #endif // TOOLS_ENABLED
  1440. pop_multiline();
  1441. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected closing "}" for enum.)");
  1442. complete_extents(enum_node);
  1443. end_statement("enum");
  1444. return enum_node;
  1445. }
  1446. bool GDScriptParser::parse_function_signature(FunctionNode *p_function, SuiteNode *p_body, const String &p_type, int p_signature_start) {
  1447. if (!check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE) && !is_at_end()) {
  1448. bool default_used = false;
  1449. do {
  1450. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  1451. // Allow for trailing comma.
  1452. break;
  1453. }
  1454. bool is_rest = false;
  1455. if (match(GDScriptTokenizer::Token::PERIOD_PERIOD_PERIOD)) {
  1456. is_rest = true;
  1457. }
  1458. ParameterNode *parameter = parse_parameter();
  1459. if (parameter == nullptr) {
  1460. break;
  1461. }
  1462. if (p_function->is_vararg()) {
  1463. push_error("Cannot have parameters after the rest parameter.");
  1464. continue;
  1465. }
  1466. if (parameter->initializer != nullptr) {
  1467. if (is_rest) {
  1468. push_error("The rest parameter cannot have a default value.");
  1469. continue;
  1470. }
  1471. default_used = true;
  1472. } else {
  1473. if (default_used && !is_rest) {
  1474. push_error("Cannot have mandatory parameters after optional parameters.");
  1475. continue;
  1476. }
  1477. }
  1478. if (p_function->parameters_indices.has(parameter->identifier->name)) {
  1479. push_error(vformat(R"(Parameter with name "%s" was already declared for this %s.)", parameter->identifier->name, p_type));
  1480. } else if (is_rest) {
  1481. p_function->rest_parameter = parameter;
  1482. p_body->add_local(parameter, current_function);
  1483. } else {
  1484. p_function->parameters_indices[parameter->identifier->name] = p_function->parameters.size();
  1485. p_function->parameters.push_back(parameter);
  1486. p_body->add_local(parameter, current_function);
  1487. }
  1488. } while (match(GDScriptTokenizer::Token::COMMA));
  1489. }
  1490. pop_multiline();
  1491. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, vformat(R"*(Expected closing ")" after %s parameters.)*", p_type));
  1492. if (match(GDScriptTokenizer::Token::FORWARD_ARROW)) {
  1493. make_completion_context(COMPLETION_TYPE_NAME_OR_VOID, p_function);
  1494. p_function->return_type = parse_type(true);
  1495. if (p_function->return_type == nullptr) {
  1496. push_error(R"(Expected return type or "void" after "->".)");
  1497. }
  1498. }
  1499. if (!p_function->source_lambda && p_function->identifier && p_function->identifier->name == GDScriptLanguage::get_singleton()->strings._static_init) {
  1500. if (!p_function->is_static) {
  1501. push_error(R"(Static constructor must be declared static.)");
  1502. }
  1503. if (!p_function->parameters.is_empty() || p_function->is_vararg()) {
  1504. push_error(R"(Static constructor cannot have parameters.)");
  1505. }
  1506. current_class->has_static_data = true;
  1507. }
  1508. #ifdef TOOLS_ENABLED
  1509. if (p_type == "function" && p_signature_start != -1) {
  1510. const int signature_end_pos = tokenizer->get_current_position() - 1;
  1511. const String source_code = tokenizer->get_source_code();
  1512. p_function->signature = source_code.substr(p_signature_start, signature_end_pos - p_signature_start).strip_edges(false, true);
  1513. }
  1514. #endif // TOOLS_ENABLED
  1515. // TODO: Improve token consumption so it synchronizes to a statement boundary. This way we can get into the function body with unrecognized tokens.
  1516. if (p_type == "lambda") {
  1517. return consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after lambda declaration.)");
  1518. }
  1519. // The colon may not be present in the case of abstract functions.
  1520. return match(GDScriptTokenizer::Token::COLON);
  1521. }
  1522. GDScriptParser::FunctionNode *GDScriptParser::parse_function(bool p_is_static) {
  1523. FunctionNode *function = alloc_node<FunctionNode>();
  1524. function->is_static = p_is_static;
  1525. make_completion_context(COMPLETION_OVERRIDE_METHOD, function);
  1526. #ifdef TOOLS_ENABLED
  1527. // The signature is something like `(a: int, b: int = 0) -> void`.
  1528. // We start one token earlier, since the parser looks one token ahead.
  1529. const int signature_start_pos = tokenizer->get_current_position();
  1530. #endif // TOOLS_ENABLED
  1531. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected function name after "func".)")) {
  1532. complete_extents(function);
  1533. return nullptr;
  1534. }
  1535. FunctionNode *previous_function = current_function;
  1536. current_function = function;
  1537. function->identifier = parse_identifier();
  1538. SuiteNode *body = alloc_node<SuiteNode>();
  1539. SuiteNode *previous_suite = current_suite;
  1540. current_suite = body;
  1541. push_multiline(true);
  1542. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after function name.)");
  1543. #ifdef TOOLS_ENABLED
  1544. const bool has_body = parse_function_signature(function, body, "function", signature_start_pos);
  1545. #else // !TOOLS_ENABLED
  1546. const bool has_body = parse_function_signature(function, body, "function", -1);
  1547. #endif // TOOLS_ENABLED
  1548. current_suite = previous_suite;
  1549. #ifdef TOOLS_ENABLED
  1550. function->min_local_doc_line = previous.end_line + 1;
  1551. #endif // TOOLS_ENABLED
  1552. if (!has_body) {
  1553. // Abstract functions do not have a body.
  1554. end_statement("bodyless function declaration");
  1555. reset_extents(body, current);
  1556. complete_extents(body);
  1557. function->body = body;
  1558. } else {
  1559. function->body = parse_suite("function declaration", body);
  1560. }
  1561. current_function = previous_function;
  1562. complete_extents(function);
  1563. return function;
  1564. }
  1565. GDScriptParser::AnnotationNode *GDScriptParser::parse_annotation(uint32_t p_valid_targets) {
  1566. AnnotationNode *annotation = alloc_node<AnnotationNode>();
  1567. annotation->name = previous.literal;
  1568. make_completion_context(COMPLETION_ANNOTATION, annotation);
  1569. bool valid = true;
  1570. if (!valid_annotations.has(annotation->name)) {
  1571. if (annotation->name == "@deprecated") {
  1572. push_error(R"("@deprecated" annotation does not exist. Use "## @deprecated: Reason here." instead.)");
  1573. } else if (annotation->name == "@experimental") {
  1574. push_error(R"("@experimental" annotation does not exist. Use "## @experimental: Reason here." instead.)");
  1575. } else if (annotation->name == "@tutorial") {
  1576. push_error(R"("@tutorial" annotation does not exist. Use "## @tutorial(Title): https://example.com" instead.)");
  1577. } else {
  1578. push_error(vformat(R"(Unrecognized annotation: "%s".)", annotation->name));
  1579. }
  1580. valid = false;
  1581. }
  1582. if (valid) {
  1583. annotation->info = &valid_annotations[annotation->name];
  1584. if (!annotation->applies_to(p_valid_targets)) {
  1585. if (annotation->applies_to(AnnotationInfo::SCRIPT)) {
  1586. push_error(vformat(R"(Annotation "%s" must be at the top of the script, before "extends" and "class_name".)", annotation->name));
  1587. } else {
  1588. push_error(vformat(R"(Annotation "%s" is not allowed in this level.)", annotation->name));
  1589. }
  1590. valid = false;
  1591. }
  1592. }
  1593. if (check(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  1594. push_multiline(true);
  1595. advance();
  1596. // Arguments.
  1597. push_completion_call(annotation);
  1598. int argument_index = 0;
  1599. do {
  1600. make_completion_context(COMPLETION_ANNOTATION_ARGUMENTS, annotation, argument_index);
  1601. set_last_completion_call_arg(argument_index);
  1602. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  1603. // Allow for trailing comma.
  1604. break;
  1605. }
  1606. ExpressionNode *argument = parse_expression(false);
  1607. if (argument == nullptr) {
  1608. push_error("Expected expression as the annotation argument.");
  1609. valid = false;
  1610. } else {
  1611. annotation->arguments.push_back(argument);
  1612. if (argument->type == Node::LITERAL) {
  1613. override_completion_context(argument, COMPLETION_ANNOTATION_ARGUMENTS, annotation, argument_index);
  1614. }
  1615. }
  1616. argument_index++;
  1617. } while (match(GDScriptTokenizer::Token::COMMA));
  1618. pop_multiline();
  1619. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after annotation arguments.)*");
  1620. pop_completion_call();
  1621. }
  1622. complete_extents(annotation);
  1623. match(GDScriptTokenizer::Token::NEWLINE); // Newline after annotation is optional.
  1624. if (valid) {
  1625. valid = validate_annotation_arguments(annotation);
  1626. }
  1627. return valid ? annotation : nullptr;
  1628. }
  1629. void GDScriptParser::clear_unused_annotations() {
  1630. for (const AnnotationNode *annotation : annotation_stack) {
  1631. push_error(vformat(R"(Annotation "%s" does not precede a valid target, so it will have no effect.)", annotation->name), annotation);
  1632. }
  1633. annotation_stack.clear();
  1634. }
  1635. bool GDScriptParser::register_annotation(const MethodInfo &p_info, uint32_t p_target_kinds, AnnotationAction p_apply, const Vector<Variant> &p_default_arguments, bool p_is_vararg) {
  1636. ERR_FAIL_COND_V_MSG(valid_annotations.has(p_info.name), false, vformat(R"(Annotation "%s" already registered.)", p_info.name));
  1637. AnnotationInfo new_annotation;
  1638. new_annotation.info = p_info;
  1639. new_annotation.info.default_arguments = p_default_arguments;
  1640. if (p_is_vararg) {
  1641. new_annotation.info.flags |= METHOD_FLAG_VARARG;
  1642. }
  1643. new_annotation.apply = p_apply;
  1644. new_annotation.target_kind = p_target_kinds;
  1645. valid_annotations[p_info.name] = new_annotation;
  1646. return true;
  1647. }
  1648. GDScriptParser::SuiteNode *GDScriptParser::parse_suite(const String &p_context, SuiteNode *p_suite, bool p_for_lambda) {
  1649. SuiteNode *suite = p_suite != nullptr ? p_suite : alloc_node<SuiteNode>();
  1650. suite->parent_block = current_suite;
  1651. suite->parent_function = current_function;
  1652. current_suite = suite;
  1653. if (!p_for_lambda && suite->parent_block != nullptr && suite->parent_block->is_in_loop) {
  1654. // Do not reset to false if true is set before calling parse_suite().
  1655. suite->is_in_loop = true;
  1656. }
  1657. bool multiline = false;
  1658. if (match(GDScriptTokenizer::Token::NEWLINE)) {
  1659. multiline = true;
  1660. }
  1661. if (multiline) {
  1662. if (!consume(GDScriptTokenizer::Token::INDENT, vformat(R"(Expected indented block after %s.)", p_context))) {
  1663. current_suite = suite->parent_block;
  1664. complete_extents(suite);
  1665. return suite;
  1666. }
  1667. }
  1668. reset_extents(suite, current);
  1669. int error_count = 0;
  1670. do {
  1671. if (is_at_end() || (!multiline && previous.type == GDScriptTokenizer::Token::SEMICOLON && check(GDScriptTokenizer::Token::NEWLINE))) {
  1672. break;
  1673. }
  1674. Node *statement = parse_statement();
  1675. if (statement == nullptr) {
  1676. if (error_count++ > 100) {
  1677. push_error("Too many statement errors.", suite);
  1678. break;
  1679. }
  1680. continue;
  1681. }
  1682. suite->statements.push_back(statement);
  1683. // Register locals.
  1684. switch (statement->type) {
  1685. case Node::VARIABLE: {
  1686. VariableNode *variable = static_cast<VariableNode *>(statement);
  1687. const SuiteNode::Local &local = current_suite->get_local(variable->identifier->name);
  1688. if (local.type != SuiteNode::Local::UNDEFINED) {
  1689. push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", local.get_name(), variable->identifier->name), variable->identifier);
  1690. }
  1691. current_suite->add_local(variable, current_function);
  1692. break;
  1693. }
  1694. case Node::CONSTANT: {
  1695. ConstantNode *constant = static_cast<ConstantNode *>(statement);
  1696. const SuiteNode::Local &local = current_suite->get_local(constant->identifier->name);
  1697. if (local.type != SuiteNode::Local::UNDEFINED) {
  1698. String name;
  1699. if (local.type == SuiteNode::Local::CONSTANT) {
  1700. name = "constant";
  1701. } else {
  1702. name = "variable";
  1703. }
  1704. push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", name, constant->identifier->name), constant->identifier);
  1705. }
  1706. current_suite->add_local(constant, current_function);
  1707. break;
  1708. }
  1709. default:
  1710. break;
  1711. }
  1712. } while ((multiline || previous.type == GDScriptTokenizer::Token::SEMICOLON) && !check(GDScriptTokenizer::Token::DEDENT) && !lambda_ended && !is_at_end());
  1713. complete_extents(suite);
  1714. if (multiline) {
  1715. if (!lambda_ended) {
  1716. consume(GDScriptTokenizer::Token::DEDENT, vformat(R"(Missing unindent at the end of %s.)", p_context));
  1717. } else {
  1718. match(GDScriptTokenizer::Token::DEDENT);
  1719. }
  1720. } else if (previous.type == GDScriptTokenizer::Token::SEMICOLON) {
  1721. consume(GDScriptTokenizer::Token::NEWLINE, vformat(R"(Expected newline after ";" at the end of %s.)", p_context));
  1722. }
  1723. if (p_for_lambda) {
  1724. lambda_ended = true;
  1725. }
  1726. current_suite = suite->parent_block;
  1727. return suite;
  1728. }
  1729. GDScriptParser::Node *GDScriptParser::parse_statement() {
  1730. Node *result = nullptr;
  1731. #ifdef DEBUG_ENABLED
  1732. bool unreachable = current_suite->has_return && !current_suite->has_unreachable_code;
  1733. #endif
  1734. List<AnnotationNode *> annotations;
  1735. if (current.type != GDScriptTokenizer::Token::ANNOTATION) {
  1736. while (!annotation_stack.is_empty()) {
  1737. AnnotationNode *last_annotation = annotation_stack.back()->get();
  1738. if (last_annotation->applies_to(AnnotationInfo::STATEMENT)) {
  1739. annotations.push_front(last_annotation);
  1740. annotation_stack.pop_back();
  1741. } else {
  1742. push_error(vformat(R"(Annotation "%s" cannot be applied to a statement.)", last_annotation->name));
  1743. clear_unused_annotations();
  1744. }
  1745. }
  1746. }
  1747. switch (current.type) {
  1748. case GDScriptTokenizer::Token::PASS:
  1749. advance();
  1750. result = alloc_node<PassNode>();
  1751. complete_extents(result);
  1752. end_statement(R"("pass")");
  1753. break;
  1754. case GDScriptTokenizer::Token::VAR:
  1755. advance();
  1756. result = parse_variable(false, false);
  1757. break;
  1758. case GDScriptTokenizer::Token::TK_CONST:
  1759. advance();
  1760. result = parse_constant(false);
  1761. break;
  1762. case GDScriptTokenizer::Token::IF:
  1763. advance();
  1764. result = parse_if();
  1765. break;
  1766. case GDScriptTokenizer::Token::FOR:
  1767. advance();
  1768. result = parse_for();
  1769. break;
  1770. case GDScriptTokenizer::Token::WHILE:
  1771. advance();
  1772. result = parse_while();
  1773. break;
  1774. case GDScriptTokenizer::Token::MATCH:
  1775. advance();
  1776. result = parse_match();
  1777. break;
  1778. case GDScriptTokenizer::Token::BREAK:
  1779. advance();
  1780. result = parse_break();
  1781. break;
  1782. case GDScriptTokenizer::Token::CONTINUE:
  1783. advance();
  1784. result = parse_continue();
  1785. break;
  1786. case GDScriptTokenizer::Token::RETURN: {
  1787. advance();
  1788. ReturnNode *n_return = alloc_node<ReturnNode>();
  1789. if (!is_statement_end()) {
  1790. if (current_function && (current_function->identifier->name == GDScriptLanguage::get_singleton()->strings._init || current_function->identifier->name == GDScriptLanguage::get_singleton()->strings._static_init)) {
  1791. push_error(R"(Constructor cannot return a value.)");
  1792. }
  1793. n_return->return_value = parse_expression(false);
  1794. } else if (in_lambda && !is_statement_end_token()) {
  1795. // Try to parse it anyway as this might not be the statement end in a lambda.
  1796. // If this fails the expression will be nullptr, but that's the same as no return, so it's fine.
  1797. n_return->return_value = parse_expression(false);
  1798. }
  1799. complete_extents(n_return);
  1800. result = n_return;
  1801. current_suite->has_return = true;
  1802. end_statement("return statement");
  1803. break;
  1804. }
  1805. case GDScriptTokenizer::Token::BREAKPOINT:
  1806. advance();
  1807. result = alloc_node<BreakpointNode>();
  1808. complete_extents(result);
  1809. end_statement(R"("breakpoint")");
  1810. break;
  1811. case GDScriptTokenizer::Token::ASSERT:
  1812. advance();
  1813. result = parse_assert();
  1814. break;
  1815. case GDScriptTokenizer::Token::ANNOTATION: {
  1816. advance();
  1817. AnnotationNode *annotation = parse_annotation(AnnotationInfo::STATEMENT | AnnotationInfo::STANDALONE);
  1818. if (annotation != nullptr) {
  1819. if (annotation->applies_to(AnnotationInfo::STANDALONE)) {
  1820. if (previous.type != GDScriptTokenizer::Token::NEWLINE) {
  1821. push_error(R"(Expected newline after a standalone annotation.)");
  1822. }
  1823. if (annotation->name == SNAME("@warning_ignore_start") || annotation->name == SNAME("@warning_ignore_restore")) {
  1824. // Some annotations need to be resolved and applied in the parser.
  1825. annotation->apply(this, nullptr, nullptr);
  1826. } else {
  1827. push_error(R"(Unexpected standalone annotation.)");
  1828. }
  1829. } else {
  1830. annotation_stack.push_back(annotation);
  1831. }
  1832. }
  1833. break;
  1834. }
  1835. default: {
  1836. // Expression statement.
  1837. ExpressionNode *expression = parse_expression(true); // Allow assignment here.
  1838. bool has_ended_lambda = false;
  1839. if (expression == nullptr) {
  1840. if (in_lambda) {
  1841. // If it's not a valid expression beginning, it might be the continuation of the outer expression where this lambda is.
  1842. lambda_ended = true;
  1843. has_ended_lambda = true;
  1844. } else {
  1845. advance();
  1846. push_error(vformat(R"(Expected statement, found "%s" instead.)", previous.get_name()));
  1847. }
  1848. } else {
  1849. end_statement("expression");
  1850. }
  1851. lambda_ended = lambda_ended || has_ended_lambda;
  1852. result = expression;
  1853. #ifdef DEBUG_ENABLED
  1854. if (expression != nullptr) {
  1855. switch (expression->type) {
  1856. case Node::ASSIGNMENT:
  1857. case Node::AWAIT:
  1858. case Node::CALL:
  1859. // Fine.
  1860. break;
  1861. case Node::PRELOAD:
  1862. // `preload` is a function-like keyword.
  1863. push_warning(expression, GDScriptWarning::RETURN_VALUE_DISCARDED, "preload");
  1864. break;
  1865. case Node::LAMBDA:
  1866. // Standalone lambdas can't be used, so make this an error.
  1867. push_error("Standalone lambdas cannot be accessed. Consider assigning it to a variable.", expression);
  1868. break;
  1869. case Node::LITERAL:
  1870. // Allow strings as multiline comments.
  1871. if (static_cast<GDScriptParser::LiteralNode *>(expression)->value.get_type() != Variant::STRING) {
  1872. push_warning(expression, GDScriptWarning::STANDALONE_EXPRESSION);
  1873. }
  1874. break;
  1875. case Node::TERNARY_OPERATOR:
  1876. push_warning(expression, GDScriptWarning::STANDALONE_TERNARY);
  1877. break;
  1878. default:
  1879. push_warning(expression, GDScriptWarning::STANDALONE_EXPRESSION);
  1880. }
  1881. }
  1882. #endif
  1883. break;
  1884. }
  1885. }
  1886. #ifdef TOOLS_ENABLED
  1887. int doc_comment_line = 0;
  1888. if (result != nullptr) {
  1889. doc_comment_line = result->start_line - 1;
  1890. }
  1891. #endif // TOOLS_ENABLED
  1892. if (result != nullptr && !annotations.is_empty()) {
  1893. for (AnnotationNode *&annotation : annotations) {
  1894. result->annotations.push_back(annotation);
  1895. #ifdef TOOLS_ENABLED
  1896. if (annotation->start_line <= doc_comment_line) {
  1897. doc_comment_line = annotation->start_line - 1;
  1898. }
  1899. #endif // TOOLS_ENABLED
  1900. }
  1901. }
  1902. #ifdef TOOLS_ENABLED
  1903. if (result != nullptr) {
  1904. MemberDocData doc_data;
  1905. if (has_comment(result->start_line, true)) {
  1906. // Inline doc comment.
  1907. doc_data = parse_doc_comment(result->start_line, true);
  1908. } else if (doc_comment_line >= current_function->min_local_doc_line && has_comment(doc_comment_line, true) && tokenizer->get_comments()[doc_comment_line].new_line) {
  1909. // Normal doc comment.
  1910. doc_data = parse_doc_comment(doc_comment_line);
  1911. }
  1912. if (result->type == Node::CONSTANT) {
  1913. static_cast<ConstantNode *>(result)->doc_data = doc_data;
  1914. } else if (result->type == Node::VARIABLE) {
  1915. static_cast<VariableNode *>(result)->doc_data = doc_data;
  1916. }
  1917. current_function->min_local_doc_line = result->end_line + 1; // Prevent multiple locals from using the same doc comment.
  1918. }
  1919. #endif // TOOLS_ENABLED
  1920. #ifdef DEBUG_ENABLED
  1921. if (unreachable && result != nullptr) {
  1922. current_suite->has_unreachable_code = true;
  1923. if (current_function) {
  1924. push_warning(result, GDScriptWarning::UNREACHABLE_CODE, current_function->identifier ? current_function->identifier->name : "<anonymous lambda>");
  1925. } else {
  1926. // TODO: Properties setters and getters with unreachable code are not being warned
  1927. }
  1928. }
  1929. #endif
  1930. if (panic_mode) {
  1931. synchronize();
  1932. }
  1933. return result;
  1934. }
  1935. GDScriptParser::AssertNode *GDScriptParser::parse_assert() {
  1936. // TODO: Add assert message.
  1937. AssertNode *assert = alloc_node<AssertNode>();
  1938. push_multiline(true);
  1939. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "assert".)");
  1940. assert->condition = parse_expression(false);
  1941. if (assert->condition == nullptr) {
  1942. push_error("Expected expression to assert.");
  1943. pop_multiline();
  1944. complete_extents(assert);
  1945. return nullptr;
  1946. }
  1947. if (match(GDScriptTokenizer::Token::COMMA) && !check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  1948. assert->message = parse_expression(false);
  1949. if (assert->message == nullptr) {
  1950. push_error(R"(Expected error message for assert after ",".)");
  1951. pop_multiline();
  1952. complete_extents(assert);
  1953. return nullptr;
  1954. }
  1955. match(GDScriptTokenizer::Token::COMMA);
  1956. }
  1957. pop_multiline();
  1958. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after assert expression.)*");
  1959. complete_extents(assert);
  1960. end_statement(R"("assert")");
  1961. return assert;
  1962. }
  1963. GDScriptParser::BreakNode *GDScriptParser::parse_break() {
  1964. if (!can_break) {
  1965. push_error(R"(Cannot use "break" outside of a loop.)");
  1966. }
  1967. BreakNode *break_node = alloc_node<BreakNode>();
  1968. complete_extents(break_node);
  1969. end_statement(R"("break")");
  1970. return break_node;
  1971. }
  1972. GDScriptParser::ContinueNode *GDScriptParser::parse_continue() {
  1973. if (!can_continue) {
  1974. push_error(R"(Cannot use "continue" outside of a loop.)");
  1975. }
  1976. current_suite->has_continue = true;
  1977. ContinueNode *cont = alloc_node<ContinueNode>();
  1978. complete_extents(cont);
  1979. end_statement(R"("continue")");
  1980. return cont;
  1981. }
  1982. GDScriptParser::ForNode *GDScriptParser::parse_for() {
  1983. ForNode *n_for = alloc_node<ForNode>();
  1984. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected loop variable name after "for".)")) {
  1985. n_for->variable = parse_identifier();
  1986. }
  1987. if (match(GDScriptTokenizer::Token::COLON)) {
  1988. n_for->datatype_specifier = parse_type();
  1989. if (n_for->datatype_specifier == nullptr) {
  1990. push_error(R"(Expected type specifier after ":".)");
  1991. }
  1992. }
  1993. if (n_for->datatype_specifier == nullptr) {
  1994. consume(GDScriptTokenizer::Token::TK_IN, R"(Expected "in" or ":" after "for" variable name.)");
  1995. } else {
  1996. consume(GDScriptTokenizer::Token::TK_IN, R"(Expected "in" after "for" variable type specifier.)");
  1997. }
  1998. n_for->list = parse_expression(false);
  1999. if (!n_for->list) {
  2000. push_error(R"(Expected iterable after "in".)");
  2001. }
  2002. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "for" condition.)");
  2003. // Save break/continue state.
  2004. bool could_break = can_break;
  2005. bool could_continue = can_continue;
  2006. // Allow break/continue.
  2007. can_break = true;
  2008. can_continue = true;
  2009. SuiteNode *suite = alloc_node<SuiteNode>();
  2010. if (n_for->variable) {
  2011. const SuiteNode::Local &local = current_suite->get_local(n_for->variable->name);
  2012. if (local.type != SuiteNode::Local::UNDEFINED) {
  2013. push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", local.get_name(), n_for->variable->name), n_for->variable);
  2014. }
  2015. suite->add_local(SuiteNode::Local(n_for->variable, current_function));
  2016. }
  2017. suite->is_in_loop = true;
  2018. n_for->loop = parse_suite(R"("for" block)", suite);
  2019. complete_extents(n_for);
  2020. // Reset break/continue state.
  2021. can_break = could_break;
  2022. can_continue = could_continue;
  2023. return n_for;
  2024. }
  2025. GDScriptParser::IfNode *GDScriptParser::parse_if(const String &p_token) {
  2026. IfNode *n_if = alloc_node<IfNode>();
  2027. n_if->condition = parse_expression(false);
  2028. if (n_if->condition == nullptr) {
  2029. push_error(vformat(R"(Expected conditional expression after "%s".)", p_token));
  2030. }
  2031. consume(GDScriptTokenizer::Token::COLON, vformat(R"(Expected ":" after "%s" condition.)", p_token));
  2032. n_if->true_block = parse_suite(vformat(R"("%s" block)", p_token));
  2033. n_if->true_block->parent_if = n_if;
  2034. if (n_if->true_block->has_continue) {
  2035. current_suite->has_continue = true;
  2036. }
  2037. if (match(GDScriptTokenizer::Token::ELIF)) {
  2038. SuiteNode *else_block = alloc_node<SuiteNode>();
  2039. else_block->parent_function = current_function;
  2040. else_block->parent_block = current_suite;
  2041. SuiteNode *previous_suite = current_suite;
  2042. current_suite = else_block;
  2043. IfNode *elif = parse_if("elif");
  2044. else_block->statements.push_back(elif);
  2045. complete_extents(else_block);
  2046. n_if->false_block = else_block;
  2047. current_suite = previous_suite;
  2048. } else if (match(GDScriptTokenizer::Token::ELSE)) {
  2049. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "else".)");
  2050. n_if->false_block = parse_suite(R"("else" block)");
  2051. }
  2052. complete_extents(n_if);
  2053. if (n_if->false_block != nullptr && n_if->false_block->has_return && n_if->true_block->has_return) {
  2054. current_suite->has_return = true;
  2055. }
  2056. if (n_if->false_block != nullptr && n_if->false_block->has_continue) {
  2057. current_suite->has_continue = true;
  2058. }
  2059. return n_if;
  2060. }
  2061. GDScriptParser::MatchNode *GDScriptParser::parse_match() {
  2062. MatchNode *match_node = alloc_node<MatchNode>();
  2063. match_node->test = parse_expression(false);
  2064. if (match_node->test == nullptr) {
  2065. push_error(R"(Expected expression to test after "match".)");
  2066. }
  2067. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "match" expression.)");
  2068. consume(GDScriptTokenizer::Token::NEWLINE, R"(Expected a newline after "match" statement.)");
  2069. if (!consume(GDScriptTokenizer::Token::INDENT, R"(Expected an indented block after "match" statement.)")) {
  2070. complete_extents(match_node);
  2071. return match_node;
  2072. }
  2073. bool all_have_return = true;
  2074. bool have_wildcard = false;
  2075. List<AnnotationNode *> match_branch_annotation_stack;
  2076. while (!check(GDScriptTokenizer::Token::DEDENT) && !is_at_end()) {
  2077. if (match(GDScriptTokenizer::Token::PASS)) {
  2078. consume(GDScriptTokenizer::Token::NEWLINE, R"(Expected newline after "pass".)");
  2079. continue;
  2080. }
  2081. if (match(GDScriptTokenizer::Token::ANNOTATION)) {
  2082. AnnotationNode *annotation = parse_annotation(AnnotationInfo::STATEMENT);
  2083. if (annotation == nullptr) {
  2084. continue;
  2085. }
  2086. if (annotation->name != SNAME("@warning_ignore")) {
  2087. push_error(vformat(R"(Annotation "%s" is not allowed in this level.)", annotation->name), annotation);
  2088. continue;
  2089. }
  2090. match_branch_annotation_stack.push_back(annotation);
  2091. continue;
  2092. }
  2093. MatchBranchNode *branch = parse_match_branch();
  2094. if (branch == nullptr) {
  2095. advance();
  2096. continue;
  2097. }
  2098. for (AnnotationNode *annotation : match_branch_annotation_stack) {
  2099. branch->annotations.push_back(annotation);
  2100. }
  2101. match_branch_annotation_stack.clear();
  2102. #ifdef DEBUG_ENABLED
  2103. if (have_wildcard && !branch->patterns.is_empty()) {
  2104. push_warning(branch->patterns[0], GDScriptWarning::UNREACHABLE_PATTERN);
  2105. }
  2106. #endif
  2107. have_wildcard = have_wildcard || branch->has_wildcard;
  2108. all_have_return = all_have_return && branch->block->has_return;
  2109. match_node->branches.push_back(branch);
  2110. }
  2111. complete_extents(match_node);
  2112. consume(GDScriptTokenizer::Token::DEDENT, R"(Expected an indented block after "match" statement.)");
  2113. if (all_have_return && have_wildcard) {
  2114. current_suite->has_return = true;
  2115. }
  2116. for (const AnnotationNode *annotation : match_branch_annotation_stack) {
  2117. push_error(vformat(R"(Annotation "%s" does not precede a valid target, so it will have no effect.)", annotation->name), annotation);
  2118. }
  2119. match_branch_annotation_stack.clear();
  2120. return match_node;
  2121. }
  2122. GDScriptParser::MatchBranchNode *GDScriptParser::parse_match_branch() {
  2123. MatchBranchNode *branch = alloc_node<MatchBranchNode>();
  2124. reset_extents(branch, current);
  2125. bool has_bind = false;
  2126. do {
  2127. PatternNode *pattern = parse_match_pattern();
  2128. if (pattern == nullptr) {
  2129. continue;
  2130. }
  2131. if (pattern->binds.size() > 0) {
  2132. has_bind = true;
  2133. }
  2134. if (branch->patterns.size() > 0 && has_bind) {
  2135. push_error(R"(Cannot use a variable bind with multiple patterns.)");
  2136. }
  2137. if (pattern->pattern_type == PatternNode::PT_REST) {
  2138. push_error(R"(Rest pattern can only be used inside array and dictionary patterns.)");
  2139. } else if (pattern->pattern_type == PatternNode::PT_BIND || pattern->pattern_type == PatternNode::PT_WILDCARD) {
  2140. branch->has_wildcard = true;
  2141. }
  2142. branch->patterns.push_back(pattern);
  2143. } while (match(GDScriptTokenizer::Token::COMMA));
  2144. if (branch->patterns.is_empty()) {
  2145. push_error(R"(No pattern found for "match" branch.)");
  2146. }
  2147. bool has_guard = false;
  2148. if (match(GDScriptTokenizer::Token::WHEN)) {
  2149. // Pattern guard.
  2150. // Create block for guard because it also needs to access the bound variables from patterns, and we don't want to add them to the outer scope.
  2151. branch->guard_body = alloc_node<SuiteNode>();
  2152. if (branch->patterns.size() > 0) {
  2153. for (const KeyValue<StringName, IdentifierNode *> &E : branch->patterns[0]->binds) {
  2154. SuiteNode::Local local(E.value, current_function);
  2155. local.type = SuiteNode::Local::PATTERN_BIND;
  2156. branch->guard_body->add_local(local);
  2157. }
  2158. }
  2159. SuiteNode *parent_block = current_suite;
  2160. branch->guard_body->parent_block = parent_block;
  2161. current_suite = branch->guard_body;
  2162. ExpressionNode *guard = parse_expression(false);
  2163. if (guard == nullptr) {
  2164. push_error(R"(Expected expression for pattern guard after "when".)");
  2165. } else {
  2166. branch->guard_body->statements.append(guard);
  2167. }
  2168. current_suite = parent_block;
  2169. complete_extents(branch->guard_body);
  2170. has_guard = true;
  2171. branch->has_wildcard = false; // If it has a guard, the wildcard might still not match.
  2172. }
  2173. if (!consume(GDScriptTokenizer::Token::COLON, vformat(R"(Expected ":"%s after "match" %s.)", has_guard ? "" : R"( or "when")", has_guard ? "pattern guard" : "patterns"))) {
  2174. branch->block = alloc_recovery_suite();
  2175. complete_extents(branch);
  2176. // Consume the whole line and treat the next one as new match branch.
  2177. while (current.type != GDScriptTokenizer::Token::NEWLINE && !is_at_end()) {
  2178. advance();
  2179. }
  2180. if (!is_at_end()) {
  2181. advance();
  2182. }
  2183. return branch;
  2184. }
  2185. SuiteNode *suite = alloc_node<SuiteNode>();
  2186. if (branch->patterns.size() > 0) {
  2187. for (const KeyValue<StringName, IdentifierNode *> &E : branch->patterns[0]->binds) {
  2188. SuiteNode::Local local(E.value, current_function);
  2189. local.type = SuiteNode::Local::PATTERN_BIND;
  2190. suite->add_local(local);
  2191. }
  2192. }
  2193. branch->block = parse_suite("match pattern block", suite);
  2194. complete_extents(branch);
  2195. return branch;
  2196. }
  2197. GDScriptParser::PatternNode *GDScriptParser::parse_match_pattern(PatternNode *p_root_pattern) {
  2198. PatternNode *pattern = alloc_node<PatternNode>();
  2199. reset_extents(pattern, current);
  2200. switch (current.type) {
  2201. case GDScriptTokenizer::Token::VAR: {
  2202. // Bind.
  2203. advance();
  2204. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected bind name after "var".)")) {
  2205. complete_extents(pattern);
  2206. return nullptr;
  2207. }
  2208. pattern->pattern_type = PatternNode::PT_BIND;
  2209. pattern->bind = parse_identifier();
  2210. PatternNode *root_pattern = p_root_pattern == nullptr ? pattern : p_root_pattern;
  2211. if (p_root_pattern != nullptr) {
  2212. if (p_root_pattern->has_bind(pattern->bind->name)) {
  2213. push_error(vformat(R"(Bind variable name "%s" was already used in this pattern.)", pattern->bind->name));
  2214. complete_extents(pattern);
  2215. return nullptr;
  2216. }
  2217. }
  2218. if (current_suite->has_local(pattern->bind->name)) {
  2219. push_error(vformat(R"(There's already a %s named "%s" in this scope.)", current_suite->get_local(pattern->bind->name).get_name(), pattern->bind->name));
  2220. complete_extents(pattern);
  2221. return nullptr;
  2222. }
  2223. root_pattern->binds[pattern->bind->name] = pattern->bind;
  2224. } break;
  2225. case GDScriptTokenizer::Token::UNDERSCORE:
  2226. // Wildcard.
  2227. advance();
  2228. pattern->pattern_type = PatternNode::PT_WILDCARD;
  2229. break;
  2230. case GDScriptTokenizer::Token::PERIOD_PERIOD:
  2231. // Rest.
  2232. advance();
  2233. pattern->pattern_type = PatternNode::PT_REST;
  2234. break;
  2235. case GDScriptTokenizer::Token::BRACKET_OPEN: {
  2236. // Array.
  2237. push_multiline(true);
  2238. advance();
  2239. pattern->pattern_type = PatternNode::PT_ARRAY;
  2240. do {
  2241. if (is_at_end() || check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  2242. break;
  2243. }
  2244. PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
  2245. if (sub_pattern == nullptr) {
  2246. continue;
  2247. }
  2248. if (pattern->rest_used) {
  2249. push_error(R"(The ".." pattern must be the last element in the pattern array.)");
  2250. } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
  2251. pattern->rest_used = true;
  2252. }
  2253. pattern->array.push_back(sub_pattern);
  2254. } while (match(GDScriptTokenizer::Token::COMMA));
  2255. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" to close the array pattern.)");
  2256. pop_multiline();
  2257. break;
  2258. }
  2259. case GDScriptTokenizer::Token::BRACE_OPEN: {
  2260. // Dictionary.
  2261. push_multiline(true);
  2262. advance();
  2263. pattern->pattern_type = PatternNode::PT_DICTIONARY;
  2264. do {
  2265. if (check(GDScriptTokenizer::Token::BRACE_CLOSE) || is_at_end()) {
  2266. break;
  2267. }
  2268. if (match(GDScriptTokenizer::Token::PERIOD_PERIOD)) {
  2269. // Rest.
  2270. if (pattern->rest_used) {
  2271. push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
  2272. } else {
  2273. PatternNode *sub_pattern = alloc_node<PatternNode>();
  2274. complete_extents(sub_pattern);
  2275. sub_pattern->pattern_type = PatternNode::PT_REST;
  2276. pattern->dictionary.push_back({ nullptr, sub_pattern });
  2277. pattern->rest_used = true;
  2278. }
  2279. } else {
  2280. ExpressionNode *key = parse_expression(false);
  2281. if (key == nullptr) {
  2282. push_error(R"(Expected expression as key for dictionary pattern.)");
  2283. }
  2284. if (match(GDScriptTokenizer::Token::COLON)) {
  2285. // Value pattern.
  2286. PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
  2287. if (sub_pattern == nullptr) {
  2288. continue;
  2289. }
  2290. if (pattern->rest_used) {
  2291. push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
  2292. } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
  2293. push_error(R"(The ".." pattern cannot be used as a value.)");
  2294. } else {
  2295. pattern->dictionary.push_back({ key, sub_pattern });
  2296. }
  2297. } else {
  2298. // Key match only.
  2299. pattern->dictionary.push_back({ key, nullptr });
  2300. }
  2301. }
  2302. } while (match(GDScriptTokenizer::Token::COMMA));
  2303. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected "}" to close the dictionary pattern.)");
  2304. pop_multiline();
  2305. break;
  2306. }
  2307. default: {
  2308. // Expression.
  2309. ExpressionNode *expression = parse_expression(false);
  2310. if (expression == nullptr) {
  2311. push_error(R"(Expected expression for match pattern.)");
  2312. complete_extents(pattern);
  2313. return nullptr;
  2314. } else {
  2315. if (expression->type == GDScriptParser::Node::LITERAL) {
  2316. pattern->pattern_type = PatternNode::PT_LITERAL;
  2317. } else {
  2318. pattern->pattern_type = PatternNode::PT_EXPRESSION;
  2319. }
  2320. pattern->expression = expression;
  2321. }
  2322. break;
  2323. }
  2324. }
  2325. complete_extents(pattern);
  2326. return pattern;
  2327. }
  2328. bool GDScriptParser::PatternNode::has_bind(const StringName &p_name) {
  2329. return binds.has(p_name);
  2330. }
  2331. GDScriptParser::IdentifierNode *GDScriptParser::PatternNode::get_bind(const StringName &p_name) {
  2332. return binds[p_name];
  2333. }
  2334. GDScriptParser::WhileNode *GDScriptParser::parse_while() {
  2335. WhileNode *n_while = alloc_node<WhileNode>();
  2336. n_while->condition = parse_expression(false);
  2337. if (n_while->condition == nullptr) {
  2338. push_error(R"(Expected conditional expression after "while".)");
  2339. }
  2340. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "while" condition.)");
  2341. // Save break/continue state.
  2342. bool could_break = can_break;
  2343. bool could_continue = can_continue;
  2344. // Allow break/continue.
  2345. can_break = true;
  2346. can_continue = true;
  2347. SuiteNode *suite = alloc_node<SuiteNode>();
  2348. suite->is_in_loop = true;
  2349. n_while->loop = parse_suite(R"("while" block)", suite);
  2350. complete_extents(n_while);
  2351. // Reset break/continue state.
  2352. can_break = could_break;
  2353. can_continue = could_continue;
  2354. return n_while;
  2355. }
  2356. GDScriptParser::ExpressionNode *GDScriptParser::parse_precedence(Precedence p_precedence, bool p_can_assign, bool p_stop_on_assign) {
  2357. // Switch multiline mode on for grouping tokens.
  2358. // Do this early to avoid the tokenizer generating whitespace tokens.
  2359. switch (current.type) {
  2360. case GDScriptTokenizer::Token::PARENTHESIS_OPEN:
  2361. case GDScriptTokenizer::Token::BRACE_OPEN:
  2362. case GDScriptTokenizer::Token::BRACKET_OPEN:
  2363. push_multiline(true);
  2364. break;
  2365. default:
  2366. break; // Nothing to do.
  2367. }
  2368. // Completion can appear whenever an expression is expected.
  2369. make_completion_context(COMPLETION_IDENTIFIER, nullptr, -1, false);
  2370. GDScriptTokenizer::Token token = current;
  2371. GDScriptTokenizer::Token::Type token_type = token.type;
  2372. if (token.is_identifier()) {
  2373. // Allow keywords that can be treated as identifiers.
  2374. token_type = GDScriptTokenizer::Token::IDENTIFIER;
  2375. }
  2376. ParseFunction prefix_rule = get_rule(token_type)->prefix;
  2377. if (prefix_rule == nullptr) {
  2378. // Expected expression. Let the caller give the proper error message.
  2379. return nullptr;
  2380. }
  2381. advance(); // Only consume the token if there's a valid rule.
  2382. // After a token was consumed, update the completion context regardless of a previously set context.
  2383. ExpressionNode *previous_operand = (this->*prefix_rule)(nullptr, p_can_assign);
  2384. #ifdef TOOLS_ENABLED
  2385. // HACK: We can't create a context in parse_identifier since it is used in places were we don't want completion.
  2386. if (previous_operand != nullptr && previous_operand->type == GDScriptParser::Node::IDENTIFIER && prefix_rule == static_cast<ParseFunction>(&GDScriptParser::parse_identifier)) {
  2387. make_completion_context(COMPLETION_IDENTIFIER, previous_operand);
  2388. }
  2389. #endif
  2390. while (p_precedence <= get_rule(current.type)->precedence) {
  2391. if (previous_operand == nullptr || (p_stop_on_assign && current.type == GDScriptTokenizer::Token::EQUAL) || lambda_ended) {
  2392. return previous_operand;
  2393. }
  2394. // Also switch multiline mode on here for infix operators.
  2395. switch (current.type) {
  2396. // case GDScriptTokenizer::Token::BRACE_OPEN: // Not an infix operator.
  2397. case GDScriptTokenizer::Token::PARENTHESIS_OPEN:
  2398. case GDScriptTokenizer::Token::BRACKET_OPEN:
  2399. push_multiline(true);
  2400. break;
  2401. default:
  2402. break; // Nothing to do.
  2403. }
  2404. token = advance();
  2405. ParseFunction infix_rule = get_rule(token.type)->infix;
  2406. previous_operand = (this->*infix_rule)(previous_operand, p_can_assign);
  2407. }
  2408. return previous_operand;
  2409. }
  2410. GDScriptParser::ExpressionNode *GDScriptParser::parse_expression(bool p_can_assign, bool p_stop_on_assign) {
  2411. return parse_precedence(PREC_ASSIGNMENT, p_can_assign, p_stop_on_assign);
  2412. }
  2413. GDScriptParser::IdentifierNode *GDScriptParser::parse_identifier() {
  2414. IdentifierNode *identifier = static_cast<IdentifierNode *>(parse_identifier(nullptr, false));
  2415. #ifdef DEBUG_ENABLED
  2416. // Check for spoofing here (if available in TextServer) since this isn't called inside expressions. This is only relevant for declarations.
  2417. if (identifier && TS->has_feature(TextServer::FEATURE_UNICODE_SECURITY) && TS->spoof_check(identifier->name)) {
  2418. push_warning(identifier, GDScriptWarning::CONFUSABLE_IDENTIFIER, identifier->name.operator String());
  2419. }
  2420. #endif
  2421. return identifier;
  2422. }
  2423. GDScriptParser::ExpressionNode *GDScriptParser::parse_identifier(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2424. if (!previous.is_identifier()) {
  2425. ERR_FAIL_V_MSG(nullptr, "Parser bug: parsing identifier node without identifier token.");
  2426. }
  2427. IdentifierNode *identifier = alloc_node<IdentifierNode>();
  2428. complete_extents(identifier);
  2429. identifier->name = previous.get_identifier();
  2430. if (identifier->name.operator String().is_empty()) {
  2431. print_line("Empty identifier found.");
  2432. }
  2433. identifier->suite = current_suite;
  2434. if (current_suite != nullptr && current_suite->has_local(identifier->name)) {
  2435. const SuiteNode::Local &declaration = current_suite->get_local(identifier->name);
  2436. identifier->source_function = declaration.source_function;
  2437. switch (declaration.type) {
  2438. case SuiteNode::Local::CONSTANT:
  2439. identifier->source = IdentifierNode::LOCAL_CONSTANT;
  2440. identifier->constant_source = declaration.constant;
  2441. declaration.constant->usages++;
  2442. break;
  2443. case SuiteNode::Local::VARIABLE:
  2444. identifier->source = IdentifierNode::LOCAL_VARIABLE;
  2445. identifier->variable_source = declaration.variable;
  2446. declaration.variable->usages++;
  2447. break;
  2448. case SuiteNode::Local::PARAMETER:
  2449. identifier->source = IdentifierNode::FUNCTION_PARAMETER;
  2450. identifier->parameter_source = declaration.parameter;
  2451. declaration.parameter->usages++;
  2452. break;
  2453. case SuiteNode::Local::FOR_VARIABLE:
  2454. identifier->source = IdentifierNode::LOCAL_ITERATOR;
  2455. identifier->bind_source = declaration.bind;
  2456. declaration.bind->usages++;
  2457. break;
  2458. case SuiteNode::Local::PATTERN_BIND:
  2459. identifier->source = IdentifierNode::LOCAL_BIND;
  2460. identifier->bind_source = declaration.bind;
  2461. declaration.bind->usages++;
  2462. break;
  2463. case SuiteNode::Local::UNDEFINED:
  2464. ERR_FAIL_V_MSG(nullptr, "Undefined local found.");
  2465. }
  2466. }
  2467. return identifier;
  2468. }
  2469. GDScriptParser::LiteralNode *GDScriptParser::parse_literal() {
  2470. return static_cast<LiteralNode *>(parse_literal(nullptr, false));
  2471. }
  2472. GDScriptParser::ExpressionNode *GDScriptParser::parse_literal(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2473. if (previous.type != GDScriptTokenizer::Token::LITERAL) {
  2474. push_error("Parser bug: parsing literal node without literal token.");
  2475. ERR_FAIL_V_MSG(nullptr, "Parser bug: parsing literal node without literal token.");
  2476. }
  2477. LiteralNode *literal = alloc_node<LiteralNode>();
  2478. literal->value = previous.literal;
  2479. reset_extents(literal, p_previous_operand);
  2480. update_extents(literal);
  2481. make_completion_context(COMPLETION_NONE, literal, -1);
  2482. complete_extents(literal);
  2483. return literal;
  2484. }
  2485. GDScriptParser::ExpressionNode *GDScriptParser::parse_self(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2486. if (current_function && current_function->is_static) {
  2487. push_error(R"(Cannot use "self" inside a static function.)");
  2488. }
  2489. SelfNode *self = alloc_node<SelfNode>();
  2490. complete_extents(self);
  2491. self->current_class = current_class;
  2492. return self;
  2493. }
  2494. GDScriptParser::ExpressionNode *GDScriptParser::parse_builtin_constant(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2495. GDScriptTokenizer::Token::Type op_type = previous.type;
  2496. LiteralNode *constant = alloc_node<LiteralNode>();
  2497. complete_extents(constant);
  2498. switch (op_type) {
  2499. case GDScriptTokenizer::Token::CONST_PI:
  2500. constant->value = Math::PI;
  2501. break;
  2502. case GDScriptTokenizer::Token::CONST_TAU:
  2503. constant->value = Math::TAU;
  2504. break;
  2505. case GDScriptTokenizer::Token::CONST_INF:
  2506. constant->value = Math::INF;
  2507. break;
  2508. case GDScriptTokenizer::Token::CONST_NAN:
  2509. constant->value = Math::NaN;
  2510. break;
  2511. default:
  2512. return nullptr; // Unreachable.
  2513. }
  2514. return constant;
  2515. }
  2516. GDScriptParser::ExpressionNode *GDScriptParser::parse_unary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2517. GDScriptTokenizer::Token::Type op_type = previous.type;
  2518. UnaryOpNode *operation = alloc_node<UnaryOpNode>();
  2519. switch (op_type) {
  2520. case GDScriptTokenizer::Token::MINUS:
  2521. operation->operation = UnaryOpNode::OP_NEGATIVE;
  2522. operation->variant_op = Variant::OP_NEGATE;
  2523. operation->operand = parse_precedence(PREC_SIGN, false);
  2524. if (operation->operand == nullptr) {
  2525. push_error(R"(Expected expression after "-" operator.)");
  2526. }
  2527. break;
  2528. case GDScriptTokenizer::Token::PLUS:
  2529. operation->operation = UnaryOpNode::OP_POSITIVE;
  2530. operation->variant_op = Variant::OP_POSITIVE;
  2531. operation->operand = parse_precedence(PREC_SIGN, false);
  2532. if (operation->operand == nullptr) {
  2533. push_error(R"(Expected expression after "+" operator.)");
  2534. }
  2535. break;
  2536. case GDScriptTokenizer::Token::TILDE:
  2537. operation->operation = UnaryOpNode::OP_COMPLEMENT;
  2538. operation->variant_op = Variant::OP_BIT_NEGATE;
  2539. operation->operand = parse_precedence(PREC_BIT_NOT, false);
  2540. if (operation->operand == nullptr) {
  2541. push_error(R"(Expected expression after "~" operator.)");
  2542. }
  2543. break;
  2544. case GDScriptTokenizer::Token::NOT:
  2545. case GDScriptTokenizer::Token::BANG:
  2546. operation->operation = UnaryOpNode::OP_LOGIC_NOT;
  2547. operation->variant_op = Variant::OP_NOT;
  2548. operation->operand = parse_precedence(PREC_LOGIC_NOT, false);
  2549. if (operation->operand == nullptr) {
  2550. push_error(vformat(R"(Expected expression after "%s" operator.)", op_type == GDScriptTokenizer::Token::NOT ? "not" : "!"));
  2551. }
  2552. break;
  2553. default:
  2554. complete_extents(operation);
  2555. return nullptr; // Unreachable.
  2556. }
  2557. complete_extents(operation);
  2558. return operation;
  2559. }
  2560. GDScriptParser::ExpressionNode *GDScriptParser::parse_binary_not_in_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2561. // check that NOT is followed by IN by consuming it before calling parse_binary_operator which will only receive a plain IN
  2562. UnaryOpNode *operation = alloc_node<UnaryOpNode>();
  2563. reset_extents(operation, p_previous_operand);
  2564. update_extents(operation);
  2565. consume(GDScriptTokenizer::Token::TK_IN, R"(Expected "in" after "not" in content-test operator.)");
  2566. ExpressionNode *in_operation = parse_binary_operator(p_previous_operand, p_can_assign);
  2567. operation->operation = UnaryOpNode::OP_LOGIC_NOT;
  2568. operation->variant_op = Variant::OP_NOT;
  2569. operation->operand = in_operation;
  2570. complete_extents(operation);
  2571. return operation;
  2572. }
  2573. GDScriptParser::ExpressionNode *GDScriptParser::parse_binary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2574. GDScriptTokenizer::Token op = previous;
  2575. BinaryOpNode *operation = alloc_node<BinaryOpNode>();
  2576. reset_extents(operation, p_previous_operand);
  2577. update_extents(operation);
  2578. Precedence precedence = (Precedence)(get_rule(op.type)->precedence + 1);
  2579. operation->left_operand = p_previous_operand;
  2580. operation->right_operand = parse_precedence(precedence, false);
  2581. complete_extents(operation);
  2582. if (operation->right_operand == nullptr) {
  2583. push_error(vformat(R"(Expected expression after "%s" operator.)", op.get_name()));
  2584. }
  2585. // TODO: Also for unary, ternary, and assignment.
  2586. switch (op.type) {
  2587. case GDScriptTokenizer::Token::PLUS:
  2588. operation->operation = BinaryOpNode::OP_ADDITION;
  2589. operation->variant_op = Variant::OP_ADD;
  2590. break;
  2591. case GDScriptTokenizer::Token::MINUS:
  2592. operation->operation = BinaryOpNode::OP_SUBTRACTION;
  2593. operation->variant_op = Variant::OP_SUBTRACT;
  2594. break;
  2595. case GDScriptTokenizer::Token::STAR:
  2596. operation->operation = BinaryOpNode::OP_MULTIPLICATION;
  2597. operation->variant_op = Variant::OP_MULTIPLY;
  2598. break;
  2599. case GDScriptTokenizer::Token::SLASH:
  2600. operation->operation = BinaryOpNode::OP_DIVISION;
  2601. operation->variant_op = Variant::OP_DIVIDE;
  2602. break;
  2603. case GDScriptTokenizer::Token::PERCENT:
  2604. operation->operation = BinaryOpNode::OP_MODULO;
  2605. operation->variant_op = Variant::OP_MODULE;
  2606. break;
  2607. case GDScriptTokenizer::Token::STAR_STAR:
  2608. operation->operation = BinaryOpNode::OP_POWER;
  2609. operation->variant_op = Variant::OP_POWER;
  2610. break;
  2611. case GDScriptTokenizer::Token::LESS_LESS:
  2612. operation->operation = BinaryOpNode::OP_BIT_LEFT_SHIFT;
  2613. operation->variant_op = Variant::OP_SHIFT_LEFT;
  2614. break;
  2615. case GDScriptTokenizer::Token::GREATER_GREATER:
  2616. operation->operation = BinaryOpNode::OP_BIT_RIGHT_SHIFT;
  2617. operation->variant_op = Variant::OP_SHIFT_RIGHT;
  2618. break;
  2619. case GDScriptTokenizer::Token::AMPERSAND:
  2620. operation->operation = BinaryOpNode::OP_BIT_AND;
  2621. operation->variant_op = Variant::OP_BIT_AND;
  2622. break;
  2623. case GDScriptTokenizer::Token::PIPE:
  2624. operation->operation = BinaryOpNode::OP_BIT_OR;
  2625. operation->variant_op = Variant::OP_BIT_OR;
  2626. break;
  2627. case GDScriptTokenizer::Token::CARET:
  2628. operation->operation = BinaryOpNode::OP_BIT_XOR;
  2629. operation->variant_op = Variant::OP_BIT_XOR;
  2630. break;
  2631. case GDScriptTokenizer::Token::AND:
  2632. case GDScriptTokenizer::Token::AMPERSAND_AMPERSAND:
  2633. operation->operation = BinaryOpNode::OP_LOGIC_AND;
  2634. operation->variant_op = Variant::OP_AND;
  2635. break;
  2636. case GDScriptTokenizer::Token::OR:
  2637. case GDScriptTokenizer::Token::PIPE_PIPE:
  2638. operation->operation = BinaryOpNode::OP_LOGIC_OR;
  2639. operation->variant_op = Variant::OP_OR;
  2640. break;
  2641. case GDScriptTokenizer::Token::TK_IN:
  2642. operation->operation = BinaryOpNode::OP_CONTENT_TEST;
  2643. operation->variant_op = Variant::OP_IN;
  2644. break;
  2645. case GDScriptTokenizer::Token::EQUAL_EQUAL:
  2646. operation->operation = BinaryOpNode::OP_COMP_EQUAL;
  2647. operation->variant_op = Variant::OP_EQUAL;
  2648. break;
  2649. case GDScriptTokenizer::Token::BANG_EQUAL:
  2650. operation->operation = BinaryOpNode::OP_COMP_NOT_EQUAL;
  2651. operation->variant_op = Variant::OP_NOT_EQUAL;
  2652. break;
  2653. case GDScriptTokenizer::Token::LESS:
  2654. operation->operation = BinaryOpNode::OP_COMP_LESS;
  2655. operation->variant_op = Variant::OP_LESS;
  2656. break;
  2657. case GDScriptTokenizer::Token::LESS_EQUAL:
  2658. operation->operation = BinaryOpNode::OP_COMP_LESS_EQUAL;
  2659. operation->variant_op = Variant::OP_LESS_EQUAL;
  2660. break;
  2661. case GDScriptTokenizer::Token::GREATER:
  2662. operation->operation = BinaryOpNode::OP_COMP_GREATER;
  2663. operation->variant_op = Variant::OP_GREATER;
  2664. break;
  2665. case GDScriptTokenizer::Token::GREATER_EQUAL:
  2666. operation->operation = BinaryOpNode::OP_COMP_GREATER_EQUAL;
  2667. operation->variant_op = Variant::OP_GREATER_EQUAL;
  2668. break;
  2669. default:
  2670. return nullptr; // Unreachable.
  2671. }
  2672. return operation;
  2673. }
  2674. GDScriptParser::ExpressionNode *GDScriptParser::parse_ternary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2675. // Only one ternary operation exists, so no abstraction here.
  2676. TernaryOpNode *operation = alloc_node<TernaryOpNode>();
  2677. reset_extents(operation, p_previous_operand);
  2678. update_extents(operation);
  2679. operation->true_expr = p_previous_operand;
  2680. operation->condition = parse_precedence(PREC_TERNARY, false);
  2681. if (operation->condition == nullptr) {
  2682. push_error(R"(Expected expression as ternary condition after "if".)");
  2683. }
  2684. consume(GDScriptTokenizer::Token::ELSE, R"(Expected "else" after ternary operator condition.)");
  2685. operation->false_expr = parse_precedence(PREC_TERNARY, false);
  2686. if (operation->false_expr == nullptr) {
  2687. push_error(R"(Expected expression after "else".)");
  2688. }
  2689. complete_extents(operation);
  2690. return operation;
  2691. }
  2692. GDScriptParser::ExpressionNode *GDScriptParser::parse_assignment(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2693. if (!p_can_assign) {
  2694. push_error("Assignment is not allowed inside an expression.");
  2695. return parse_expression(false); // Return the following expression.
  2696. }
  2697. if (p_previous_operand == nullptr) {
  2698. return parse_expression(false); // Return the following expression.
  2699. }
  2700. switch (p_previous_operand->type) {
  2701. case Node::IDENTIFIER: {
  2702. #ifdef DEBUG_ENABLED
  2703. // Get source to store assignment count.
  2704. // Also remove one usage since assignment isn't usage.
  2705. IdentifierNode *id = static_cast<IdentifierNode *>(p_previous_operand);
  2706. switch (id->source) {
  2707. case IdentifierNode::LOCAL_VARIABLE:
  2708. id->variable_source->usages--;
  2709. break;
  2710. case IdentifierNode::LOCAL_CONSTANT:
  2711. id->constant_source->usages--;
  2712. break;
  2713. case IdentifierNode::FUNCTION_PARAMETER:
  2714. id->parameter_source->usages--;
  2715. break;
  2716. case IdentifierNode::LOCAL_ITERATOR:
  2717. case IdentifierNode::LOCAL_BIND:
  2718. id->bind_source->usages--;
  2719. break;
  2720. default:
  2721. break;
  2722. }
  2723. #endif
  2724. } break;
  2725. case Node::SUBSCRIPT:
  2726. // Okay.
  2727. break;
  2728. default:
  2729. push_error(R"(Only identifier, attribute access, and subscription access can be used as assignment target.)");
  2730. return parse_expression(false); // Return the following expression.
  2731. }
  2732. AssignmentNode *assignment = alloc_node<AssignmentNode>();
  2733. reset_extents(assignment, p_previous_operand);
  2734. update_extents(assignment);
  2735. make_completion_context(COMPLETION_ASSIGN, assignment);
  2736. switch (previous.type) {
  2737. case GDScriptTokenizer::Token::EQUAL:
  2738. assignment->operation = AssignmentNode::OP_NONE;
  2739. assignment->variant_op = Variant::OP_MAX;
  2740. break;
  2741. case GDScriptTokenizer::Token::PLUS_EQUAL:
  2742. assignment->operation = AssignmentNode::OP_ADDITION;
  2743. assignment->variant_op = Variant::OP_ADD;
  2744. break;
  2745. case GDScriptTokenizer::Token::MINUS_EQUAL:
  2746. assignment->operation = AssignmentNode::OP_SUBTRACTION;
  2747. assignment->variant_op = Variant::OP_SUBTRACT;
  2748. break;
  2749. case GDScriptTokenizer::Token::STAR_EQUAL:
  2750. assignment->operation = AssignmentNode::OP_MULTIPLICATION;
  2751. assignment->variant_op = Variant::OP_MULTIPLY;
  2752. break;
  2753. case GDScriptTokenizer::Token::STAR_STAR_EQUAL:
  2754. assignment->operation = AssignmentNode::OP_POWER;
  2755. assignment->variant_op = Variant::OP_POWER;
  2756. break;
  2757. case GDScriptTokenizer::Token::SLASH_EQUAL:
  2758. assignment->operation = AssignmentNode::OP_DIVISION;
  2759. assignment->variant_op = Variant::OP_DIVIDE;
  2760. break;
  2761. case GDScriptTokenizer::Token::PERCENT_EQUAL:
  2762. assignment->operation = AssignmentNode::OP_MODULO;
  2763. assignment->variant_op = Variant::OP_MODULE;
  2764. break;
  2765. case GDScriptTokenizer::Token::LESS_LESS_EQUAL:
  2766. assignment->operation = AssignmentNode::OP_BIT_SHIFT_LEFT;
  2767. assignment->variant_op = Variant::OP_SHIFT_LEFT;
  2768. break;
  2769. case GDScriptTokenizer::Token::GREATER_GREATER_EQUAL:
  2770. assignment->operation = AssignmentNode::OP_BIT_SHIFT_RIGHT;
  2771. assignment->variant_op = Variant::OP_SHIFT_RIGHT;
  2772. break;
  2773. case GDScriptTokenizer::Token::AMPERSAND_EQUAL:
  2774. assignment->operation = AssignmentNode::OP_BIT_AND;
  2775. assignment->variant_op = Variant::OP_BIT_AND;
  2776. break;
  2777. case GDScriptTokenizer::Token::PIPE_EQUAL:
  2778. assignment->operation = AssignmentNode::OP_BIT_OR;
  2779. assignment->variant_op = Variant::OP_BIT_OR;
  2780. break;
  2781. case GDScriptTokenizer::Token::CARET_EQUAL:
  2782. assignment->operation = AssignmentNode::OP_BIT_XOR;
  2783. assignment->variant_op = Variant::OP_BIT_XOR;
  2784. break;
  2785. default:
  2786. break; // Unreachable.
  2787. }
  2788. assignment->assignee = p_previous_operand;
  2789. assignment->assigned_value = parse_expression(false);
  2790. #ifdef TOOLS_ENABLED
  2791. if (assignment->assigned_value != nullptr && assignment->assigned_value->type == GDScriptParser::Node::IDENTIFIER) {
  2792. override_completion_context(assignment->assigned_value, COMPLETION_ASSIGN, assignment);
  2793. }
  2794. #endif
  2795. if (assignment->assigned_value == nullptr) {
  2796. push_error(R"(Expected an expression after "=".)");
  2797. }
  2798. complete_extents(assignment);
  2799. return assignment;
  2800. }
  2801. GDScriptParser::ExpressionNode *GDScriptParser::parse_await(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2802. AwaitNode *await = alloc_node<AwaitNode>();
  2803. ExpressionNode *element = parse_precedence(PREC_AWAIT, false);
  2804. if (element == nullptr) {
  2805. push_error(R"(Expected signal or coroutine after "await".)");
  2806. }
  2807. await->to_await = element;
  2808. complete_extents(await);
  2809. if (current_function) { // Might be null in a getter or setter.
  2810. current_function->is_coroutine = true;
  2811. }
  2812. return await;
  2813. }
  2814. GDScriptParser::ExpressionNode *GDScriptParser::parse_array(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2815. ArrayNode *array = alloc_node<ArrayNode>();
  2816. if (!check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  2817. do {
  2818. if (check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  2819. // Allow for trailing comma.
  2820. break;
  2821. }
  2822. ExpressionNode *element = parse_expression(false);
  2823. if (element == nullptr) {
  2824. push_error(R"(Expected expression as array element.)");
  2825. } else {
  2826. array->elements.push_back(element);
  2827. }
  2828. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  2829. }
  2830. pop_multiline();
  2831. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected closing "]" after array elements.)");
  2832. complete_extents(array);
  2833. return array;
  2834. }
  2835. GDScriptParser::ExpressionNode *GDScriptParser::parse_dictionary(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2836. DictionaryNode *dictionary = alloc_node<DictionaryNode>();
  2837. bool decided_style = false;
  2838. if (!check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  2839. do {
  2840. if (check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  2841. // Allow for trailing comma.
  2842. break;
  2843. }
  2844. // Key.
  2845. ExpressionNode *key = parse_expression(false, true); // Stop on "=" so we can check for Lua table style.
  2846. if (key == nullptr) {
  2847. push_error(R"(Expected expression as dictionary key.)");
  2848. }
  2849. if (!decided_style) {
  2850. switch (current.type) {
  2851. case GDScriptTokenizer::Token::COLON:
  2852. dictionary->style = DictionaryNode::PYTHON_DICT;
  2853. break;
  2854. case GDScriptTokenizer::Token::EQUAL:
  2855. dictionary->style = DictionaryNode::LUA_TABLE;
  2856. break;
  2857. default:
  2858. push_error(R"(Expected ":" or "=" after dictionary key.)");
  2859. break;
  2860. }
  2861. decided_style = true;
  2862. }
  2863. switch (dictionary->style) {
  2864. case DictionaryNode::LUA_TABLE:
  2865. if (key != nullptr && key->type != Node::IDENTIFIER && key->type != Node::LITERAL) {
  2866. push_error(R"(Expected identifier or string as Lua-style dictionary key (e.g "{ key = value }").)");
  2867. }
  2868. if (key != nullptr && key->type == Node::LITERAL && static_cast<LiteralNode *>(key)->value.get_type() != Variant::STRING) {
  2869. push_error(R"(Expected identifier or string as Lua-style dictionary key (e.g "{ key = value }").)");
  2870. }
  2871. if (!match(GDScriptTokenizer::Token::EQUAL)) {
  2872. if (match(GDScriptTokenizer::Token::COLON)) {
  2873. push_error(R"(Expected "=" after dictionary key. Mixing dictionary styles is not allowed.)");
  2874. advance(); // Consume wrong separator anyway.
  2875. } else {
  2876. push_error(R"(Expected "=" after dictionary key.)");
  2877. }
  2878. }
  2879. if (key != nullptr) {
  2880. key->is_constant = true;
  2881. if (key->type == Node::IDENTIFIER) {
  2882. key->reduced_value = static_cast<IdentifierNode *>(key)->name;
  2883. } else if (key->type == Node::LITERAL) {
  2884. key->reduced_value = StringName(static_cast<LiteralNode *>(key)->value.operator String());
  2885. }
  2886. }
  2887. break;
  2888. case DictionaryNode::PYTHON_DICT:
  2889. if (!match(GDScriptTokenizer::Token::COLON)) {
  2890. if (match(GDScriptTokenizer::Token::EQUAL)) {
  2891. push_error(R"(Expected ":" after dictionary key. Mixing dictionary styles is not allowed.)");
  2892. advance(); // Consume wrong separator anyway.
  2893. } else {
  2894. push_error(R"(Expected ":" after dictionary key.)");
  2895. }
  2896. }
  2897. break;
  2898. }
  2899. // Value.
  2900. ExpressionNode *value = parse_expression(false);
  2901. if (value == nullptr) {
  2902. push_error(R"(Expected expression as dictionary value.)");
  2903. }
  2904. if (key != nullptr && value != nullptr) {
  2905. dictionary->elements.push_back({ key, value });
  2906. }
  2907. // Do phrase level recovery by inserting an imaginary expression for missing keys or values.
  2908. // This ensures the successfully parsed expression is part of the AST and can be analyzed.
  2909. if (key != nullptr && value == nullptr) {
  2910. LiteralNode *dummy = alloc_recovery_node<LiteralNode>();
  2911. dummy->value = Variant();
  2912. dictionary->elements.push_back({ key, dummy });
  2913. } else if (key == nullptr && value != nullptr) {
  2914. LiteralNode *dummy = alloc_recovery_node<LiteralNode>();
  2915. dummy->value = Variant();
  2916. dictionary->elements.push_back({ dummy, value });
  2917. }
  2918. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  2919. }
  2920. pop_multiline();
  2921. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected closing "}" after dictionary elements.)");
  2922. complete_extents(dictionary);
  2923. return dictionary;
  2924. }
  2925. GDScriptParser::ExpressionNode *GDScriptParser::parse_grouping(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2926. ExpressionNode *grouped = parse_expression(false);
  2927. pop_multiline();
  2928. if (grouped == nullptr) {
  2929. push_error(R"(Expected grouping expression.)");
  2930. } else {
  2931. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after grouping expression.)*");
  2932. }
  2933. return grouped;
  2934. }
  2935. GDScriptParser::ExpressionNode *GDScriptParser::parse_attribute(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2936. SubscriptNode *attribute = alloc_node<SubscriptNode>();
  2937. reset_extents(attribute, p_previous_operand);
  2938. update_extents(attribute);
  2939. if (for_completion) {
  2940. bool is_builtin = false;
  2941. if (p_previous_operand && p_previous_operand->type == Node::IDENTIFIER) {
  2942. const IdentifierNode *id = static_cast<const IdentifierNode *>(p_previous_operand);
  2943. Variant::Type builtin_type = get_builtin_type(id->name);
  2944. if (builtin_type < Variant::VARIANT_MAX) {
  2945. make_completion_context(COMPLETION_BUILT_IN_TYPE_CONSTANT_OR_STATIC_METHOD, builtin_type);
  2946. is_builtin = true;
  2947. }
  2948. }
  2949. if (!is_builtin) {
  2950. make_completion_context(COMPLETION_ATTRIBUTE, attribute, -1);
  2951. }
  2952. }
  2953. attribute->base = p_previous_operand;
  2954. if (current.is_node_name()) {
  2955. current.type = GDScriptTokenizer::Token::IDENTIFIER;
  2956. }
  2957. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier after "." for attribute access.)")) {
  2958. complete_extents(attribute);
  2959. return attribute;
  2960. }
  2961. attribute->is_attribute = true;
  2962. attribute->attribute = parse_identifier();
  2963. complete_extents(attribute);
  2964. return attribute;
  2965. }
  2966. GDScriptParser::ExpressionNode *GDScriptParser::parse_subscript(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2967. SubscriptNode *subscript = alloc_node<SubscriptNode>();
  2968. reset_extents(subscript, p_previous_operand);
  2969. update_extents(subscript);
  2970. make_completion_context(COMPLETION_SUBSCRIPT, subscript);
  2971. subscript->base = p_previous_operand;
  2972. subscript->index = parse_expression(false);
  2973. #ifdef TOOLS_ENABLED
  2974. if (subscript->index != nullptr && subscript->index->type == Node::LITERAL) {
  2975. override_completion_context(subscript->index, COMPLETION_SUBSCRIPT, subscript);
  2976. }
  2977. #endif
  2978. if (subscript->index == nullptr) {
  2979. push_error(R"(Expected expression after "[".)");
  2980. }
  2981. pop_multiline();
  2982. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" after subscription index.)");
  2983. complete_extents(subscript);
  2984. return subscript;
  2985. }
  2986. GDScriptParser::ExpressionNode *GDScriptParser::parse_cast(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2987. CastNode *cast = alloc_node<CastNode>();
  2988. reset_extents(cast, p_previous_operand);
  2989. update_extents(cast);
  2990. cast->operand = p_previous_operand;
  2991. cast->cast_type = parse_type();
  2992. complete_extents(cast);
  2993. if (cast->cast_type == nullptr) {
  2994. push_error(R"(Expected type specifier after "as".)");
  2995. return p_previous_operand;
  2996. }
  2997. return cast;
  2998. }
  2999. GDScriptParser::ExpressionNode *GDScriptParser::parse_call(ExpressionNode *p_previous_operand, bool p_can_assign) {
  3000. CallNode *call = alloc_node<CallNode>();
  3001. reset_extents(call, p_previous_operand);
  3002. if (previous.type == GDScriptTokenizer::Token::SUPER) {
  3003. // Super call.
  3004. call->is_super = true;
  3005. if (!check(GDScriptTokenizer::Token::PERIOD)) {
  3006. make_completion_context(COMPLETION_SUPER, call);
  3007. }
  3008. push_multiline(true);
  3009. if (match(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  3010. // Implicit call to the parent method of the same name.
  3011. if (current_function == nullptr) {
  3012. push_error(R"(Cannot use implicit "super" call outside of a function.)");
  3013. pop_multiline();
  3014. complete_extents(call);
  3015. return nullptr;
  3016. }
  3017. if (current_function->identifier) {
  3018. call->function_name = current_function->identifier->name;
  3019. } else {
  3020. call->function_name = SNAME("<anonymous>");
  3021. }
  3022. } else {
  3023. consume(GDScriptTokenizer::Token::PERIOD, R"(Expected "." or "(" after "super".)");
  3024. make_completion_context(COMPLETION_SUPER_METHOD, call);
  3025. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected function name after ".".)")) {
  3026. pop_multiline();
  3027. complete_extents(call);
  3028. return nullptr;
  3029. }
  3030. IdentifierNode *identifier = parse_identifier();
  3031. call->callee = identifier;
  3032. call->function_name = identifier->name;
  3033. if (!consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after function name.)")) {
  3034. pop_multiline();
  3035. complete_extents(call);
  3036. return nullptr;
  3037. }
  3038. }
  3039. } else {
  3040. call->callee = p_previous_operand;
  3041. if (call->callee == nullptr) {
  3042. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  3043. } else if (call->callee->type == Node::IDENTIFIER) {
  3044. call->function_name = static_cast<IdentifierNode *>(call->callee)->name;
  3045. make_completion_context(COMPLETION_METHOD, call->callee);
  3046. } else if (call->callee->type == Node::SUBSCRIPT) {
  3047. SubscriptNode *attribute = static_cast<SubscriptNode *>(call->callee);
  3048. if (attribute->is_attribute) {
  3049. if (attribute->attribute) {
  3050. call->function_name = attribute->attribute->name;
  3051. }
  3052. make_completion_context(COMPLETION_ATTRIBUTE_METHOD, call->callee);
  3053. } else {
  3054. // TODO: The analyzer can see if this is actually a Callable and give better error message.
  3055. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  3056. }
  3057. } else {
  3058. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  3059. }
  3060. }
  3061. // Arguments.
  3062. CompletionType ct = COMPLETION_CALL_ARGUMENTS;
  3063. if (call->function_name == SNAME("load")) {
  3064. ct = COMPLETION_RESOURCE_PATH;
  3065. }
  3066. push_completion_call(call);
  3067. int argument_index = 0;
  3068. do {
  3069. make_completion_context(ct, call, argument_index);
  3070. set_last_completion_call_arg(argument_index);
  3071. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  3072. // Allow for trailing comma.
  3073. break;
  3074. }
  3075. ExpressionNode *argument = parse_expression(false);
  3076. if (argument == nullptr) {
  3077. push_error(R"(Expected expression as the function argument.)");
  3078. } else {
  3079. call->arguments.push_back(argument);
  3080. if (argument->type == Node::LITERAL) {
  3081. override_completion_context(argument, ct, call, argument_index);
  3082. }
  3083. }
  3084. ct = COMPLETION_CALL_ARGUMENTS;
  3085. argument_index++;
  3086. } while (match(GDScriptTokenizer::Token::COMMA));
  3087. pop_completion_call();
  3088. pop_multiline();
  3089. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after call arguments.)*");
  3090. complete_extents(call);
  3091. return call;
  3092. }
  3093. GDScriptParser::ExpressionNode *GDScriptParser::parse_get_node(ExpressionNode *p_previous_operand, bool p_can_assign) {
  3094. // We want code completion after a DOLLAR even if the current code is invalid.
  3095. make_completion_context(COMPLETION_GET_NODE, nullptr, -1);
  3096. if (!current.is_node_name() && !check(GDScriptTokenizer::Token::LITERAL) && !check(GDScriptTokenizer::Token::SLASH) && !check(GDScriptTokenizer::Token::PERCENT)) {
  3097. push_error(vformat(R"(Expected node path as string or identifier after "%s".)", previous.get_name()));
  3098. return nullptr;
  3099. }
  3100. if (check(GDScriptTokenizer::Token::LITERAL)) {
  3101. if (current.literal.get_type() != Variant::STRING) {
  3102. push_error(vformat(R"(Expected node path as string or identifier after "%s".)", previous.get_name()));
  3103. return nullptr;
  3104. }
  3105. }
  3106. GetNodeNode *get_node = alloc_node<GetNodeNode>();
  3107. // Store the last item in the path so the parser knows what to expect.
  3108. // Allow allows more specific error messages.
  3109. enum PathState {
  3110. PATH_STATE_START,
  3111. PATH_STATE_SLASH,
  3112. PATH_STATE_PERCENT,
  3113. PATH_STATE_NODE_NAME,
  3114. } path_state = PATH_STATE_START;
  3115. if (previous.type == GDScriptTokenizer::Token::DOLLAR) {
  3116. // Detect initial slash, which will be handled in the loop if it matches.
  3117. match(GDScriptTokenizer::Token::SLASH);
  3118. } else {
  3119. get_node->use_dollar = false;
  3120. }
  3121. int context_argument = 0;
  3122. do {
  3123. if (previous.type == GDScriptTokenizer::Token::PERCENT) {
  3124. if (path_state != PATH_STATE_START && path_state != PATH_STATE_SLASH) {
  3125. push_error(R"("%" is only valid in the beginning of a node name (either after "$" or after "/"))");
  3126. complete_extents(get_node);
  3127. return nullptr;
  3128. }
  3129. get_node->full_path += "%";
  3130. path_state = PATH_STATE_PERCENT;
  3131. } else if (previous.type == GDScriptTokenizer::Token::SLASH) {
  3132. if (path_state != PATH_STATE_START && path_state != PATH_STATE_NODE_NAME) {
  3133. push_error(R"("/" is only valid at the beginning of the path or after a node name.)");
  3134. complete_extents(get_node);
  3135. return nullptr;
  3136. }
  3137. get_node->full_path += "/";
  3138. path_state = PATH_STATE_SLASH;
  3139. }
  3140. make_completion_context(COMPLETION_GET_NODE, get_node, context_argument++);
  3141. if (match(GDScriptTokenizer::Token::LITERAL)) {
  3142. if (previous.literal.get_type() != Variant::STRING) {
  3143. String previous_token;
  3144. switch (path_state) {
  3145. case PATH_STATE_START:
  3146. previous_token = "$";
  3147. break;
  3148. case PATH_STATE_PERCENT:
  3149. previous_token = "%";
  3150. break;
  3151. case PATH_STATE_SLASH:
  3152. previous_token = "/";
  3153. break;
  3154. default:
  3155. break;
  3156. }
  3157. push_error(vformat(R"(Expected node path as string or identifier after "%s".)", previous_token));
  3158. complete_extents(get_node);
  3159. return nullptr;
  3160. }
  3161. get_node->full_path += previous.literal.operator String();
  3162. path_state = PATH_STATE_NODE_NAME;
  3163. } else if (current.is_node_name()) {
  3164. advance();
  3165. String identifier = previous.get_identifier();
  3166. #ifdef DEBUG_ENABLED
  3167. // Check spoofing.
  3168. if (TS->has_feature(TextServer::FEATURE_UNICODE_SECURITY) && TS->spoof_check(identifier)) {
  3169. push_warning(get_node, GDScriptWarning::CONFUSABLE_IDENTIFIER, identifier);
  3170. }
  3171. #endif
  3172. get_node->full_path += identifier;
  3173. path_state = PATH_STATE_NODE_NAME;
  3174. } else if (!check(GDScriptTokenizer::Token::SLASH) && !check(GDScriptTokenizer::Token::PERCENT)) {
  3175. push_error(vformat(R"(Unexpected "%s" in node path.)", current.get_name()));
  3176. complete_extents(get_node);
  3177. return nullptr;
  3178. }
  3179. } while (match(GDScriptTokenizer::Token::SLASH) || match(GDScriptTokenizer::Token::PERCENT));
  3180. complete_extents(get_node);
  3181. return get_node;
  3182. }
  3183. GDScriptParser::ExpressionNode *GDScriptParser::parse_preload(ExpressionNode *p_previous_operand, bool p_can_assign) {
  3184. PreloadNode *preload = alloc_node<PreloadNode>();
  3185. preload->resolved_path = "<missing path>";
  3186. push_multiline(true);
  3187. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "preload".)");
  3188. make_completion_context(COMPLETION_RESOURCE_PATH, preload);
  3189. push_completion_call(preload);
  3190. preload->path = parse_expression(false);
  3191. if (preload->path == nullptr) {
  3192. push_error(R"(Expected resource path after "(".)");
  3193. } else if (preload->path->type == Node::LITERAL) {
  3194. override_completion_context(preload->path, COMPLETION_RESOURCE_PATH, preload);
  3195. }
  3196. pop_completion_call();
  3197. // Allow trailing comma.
  3198. match(GDScriptTokenizer::Token::COMMA);
  3199. pop_multiline();
  3200. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after preload path.)*");
  3201. complete_extents(preload);
  3202. return preload;
  3203. }
  3204. GDScriptParser::ExpressionNode *GDScriptParser::parse_lambda(ExpressionNode *p_previous_operand, bool p_can_assign) {
  3205. LambdaNode *lambda = alloc_node<LambdaNode>();
  3206. lambda->parent_function = current_function;
  3207. lambda->parent_lambda = current_lambda;
  3208. FunctionNode *function = alloc_node<FunctionNode>();
  3209. function->source_lambda = lambda;
  3210. function->is_static = current_function != nullptr ? current_function->is_static : false;
  3211. if (match(GDScriptTokenizer::Token::IDENTIFIER)) {
  3212. function->identifier = parse_identifier();
  3213. }
  3214. bool multiline_context = multiline_stack.back()->get();
  3215. push_completion_call(nullptr);
  3216. // Reset the multiline stack since we don't want the multiline mode one in the lambda body.
  3217. push_multiline(false);
  3218. if (multiline_context) {
  3219. tokenizer->push_expression_indented_block();
  3220. }
  3221. push_multiline(true); // For the parameters.
  3222. if (function->identifier) {
  3223. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after lambda name.)");
  3224. } else {
  3225. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after "func".)");
  3226. }
  3227. FunctionNode *previous_function = current_function;
  3228. current_function = function;
  3229. LambdaNode *previous_lambda = current_lambda;
  3230. current_lambda = lambda;
  3231. SuiteNode *body = alloc_node<SuiteNode>();
  3232. body->parent_function = current_function;
  3233. body->parent_block = current_suite;
  3234. SuiteNode *previous_suite = current_suite;
  3235. current_suite = body;
  3236. parse_function_signature(function, body, "lambda", -1);
  3237. current_suite = previous_suite;
  3238. bool previous_in_lambda = in_lambda;
  3239. in_lambda = true;
  3240. // Save break/continue state.
  3241. bool could_break = can_break;
  3242. bool could_continue = can_continue;
  3243. // Disallow break/continue.
  3244. can_break = false;
  3245. can_continue = false;
  3246. function->body = parse_suite("lambda declaration", body, true);
  3247. complete_extents(function);
  3248. complete_extents(lambda);
  3249. pop_multiline();
  3250. pop_completion_call();
  3251. if (multiline_context) {
  3252. // If we're in multiline mode, we want to skip the spurious DEDENT and NEWLINE tokens.
  3253. while (check(GDScriptTokenizer::Token::DEDENT) || check(GDScriptTokenizer::Token::INDENT) || check(GDScriptTokenizer::Token::NEWLINE)) {
  3254. current = tokenizer->scan(); // Not advance() since we don't want to change the previous token.
  3255. }
  3256. tokenizer->pop_expression_indented_block();
  3257. }
  3258. current_function = previous_function;
  3259. current_lambda = previous_lambda;
  3260. in_lambda = previous_in_lambda;
  3261. lambda->function = function;
  3262. // Reset break/continue state.
  3263. can_break = could_break;
  3264. can_continue = could_continue;
  3265. return lambda;
  3266. }
  3267. GDScriptParser::ExpressionNode *GDScriptParser::parse_type_test(ExpressionNode *p_previous_operand, bool p_can_assign) {
  3268. // x is not int
  3269. // ^ ^^^ ExpressionNode, TypeNode
  3270. // ^^^^^^^^^^^^ TypeTestNode
  3271. // ^^^^^^^^^^^^ UnaryOpNode
  3272. UnaryOpNode *not_node = nullptr;
  3273. if (match(GDScriptTokenizer::Token::NOT)) {
  3274. not_node = alloc_node<UnaryOpNode>();
  3275. not_node->operation = UnaryOpNode::OP_LOGIC_NOT;
  3276. not_node->variant_op = Variant::OP_NOT;
  3277. reset_extents(not_node, p_previous_operand);
  3278. update_extents(not_node);
  3279. }
  3280. TypeTestNode *type_test = alloc_node<TypeTestNode>();
  3281. reset_extents(type_test, p_previous_operand);
  3282. update_extents(type_test);
  3283. type_test->operand = p_previous_operand;
  3284. type_test->test_type = parse_type();
  3285. complete_extents(type_test);
  3286. if (not_node != nullptr) {
  3287. not_node->operand = type_test;
  3288. complete_extents(not_node);
  3289. }
  3290. if (type_test->test_type == nullptr) {
  3291. if (not_node == nullptr) {
  3292. push_error(R"(Expected type specifier after "is".)");
  3293. } else {
  3294. push_error(R"(Expected type specifier after "is not".)");
  3295. }
  3296. }
  3297. if (not_node != nullptr) {
  3298. return not_node;
  3299. }
  3300. return type_test;
  3301. }
  3302. GDScriptParser::ExpressionNode *GDScriptParser::parse_yield(ExpressionNode *p_previous_operand, bool p_can_assign) {
  3303. push_error(R"("yield" was removed in Godot 4. Use "await" instead.)");
  3304. return nullptr;
  3305. }
  3306. GDScriptParser::ExpressionNode *GDScriptParser::parse_invalid_token(ExpressionNode *p_previous_operand, bool p_can_assign) {
  3307. // Just for better error messages.
  3308. GDScriptTokenizer::Token::Type invalid = previous.type;
  3309. switch (invalid) {
  3310. case GDScriptTokenizer::Token::QUESTION_MARK:
  3311. push_error(R"(Unexpected "?" in source. If you want a ternary operator, use "truthy_value if true_condition else falsy_value".)");
  3312. break;
  3313. default:
  3314. return nullptr; // Unreachable.
  3315. }
  3316. // Return the previous expression.
  3317. return p_previous_operand;
  3318. }
  3319. GDScriptParser::TypeNode *GDScriptParser::parse_type(bool p_allow_void) {
  3320. TypeNode *type = alloc_node<TypeNode>();
  3321. make_completion_context(p_allow_void ? COMPLETION_TYPE_NAME_OR_VOID : COMPLETION_TYPE_NAME, type);
  3322. if (!match(GDScriptTokenizer::Token::IDENTIFIER)) {
  3323. if (match(GDScriptTokenizer::Token::TK_VOID)) {
  3324. if (p_allow_void) {
  3325. complete_extents(type);
  3326. TypeNode *void_type = type;
  3327. return void_type;
  3328. } else {
  3329. push_error(R"("void" is only allowed for a function return type.)");
  3330. }
  3331. }
  3332. // Leave error message to the caller who knows the context.
  3333. complete_extents(type);
  3334. return nullptr;
  3335. }
  3336. IdentifierNode *type_element = parse_identifier();
  3337. type->type_chain.push_back(type_element);
  3338. if (match(GDScriptTokenizer::Token::BRACKET_OPEN)) {
  3339. // Typed collection (like Array[int], Dictionary[String, int]).
  3340. bool first_pass = true;
  3341. do {
  3342. TypeNode *container_type = parse_type(false); // Don't allow void for element type.
  3343. if (container_type == nullptr) {
  3344. push_error(vformat(R"(Expected type for collection after "%s".)", first_pass ? "[" : ","));
  3345. complete_extents(type);
  3346. type = nullptr;
  3347. break;
  3348. } else if (container_type->container_types.size() > 0) {
  3349. push_error("Nested typed collections are not supported.");
  3350. } else {
  3351. type->container_types.append(container_type);
  3352. }
  3353. first_pass = false;
  3354. } while (match(GDScriptTokenizer::Token::COMMA));
  3355. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected closing "]" after collection type.)");
  3356. if (type != nullptr) {
  3357. complete_extents(type);
  3358. }
  3359. return type;
  3360. }
  3361. int chain_index = 1;
  3362. while (match(GDScriptTokenizer::Token::PERIOD)) {
  3363. make_completion_context(COMPLETION_TYPE_ATTRIBUTE, type, chain_index++);
  3364. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected inner type name after ".".)")) {
  3365. type_element = parse_identifier();
  3366. type->type_chain.push_back(type_element);
  3367. }
  3368. }
  3369. complete_extents(type);
  3370. return type;
  3371. }
  3372. #ifdef TOOLS_ENABLED
  3373. enum DocLineState {
  3374. DOC_LINE_NORMAL,
  3375. DOC_LINE_IN_CODE,
  3376. DOC_LINE_IN_CODEBLOCK,
  3377. DOC_LINE_IN_KBD,
  3378. };
  3379. static String _process_doc_line(const String &p_line, const String &p_text, const String &p_space_prefix, DocLineState &r_state) {
  3380. String line = p_line;
  3381. if (r_state == DOC_LINE_NORMAL) {
  3382. line = line.strip_edges(true, false);
  3383. } else {
  3384. line = line.trim_prefix(p_space_prefix);
  3385. }
  3386. String line_join;
  3387. if (!p_text.is_empty()) {
  3388. if (r_state == DOC_LINE_NORMAL) {
  3389. if (p_text.ends_with("[/codeblock]")) {
  3390. line_join = "\n";
  3391. } else if (!p_text.ends_with("[br]")) {
  3392. line_join = " ";
  3393. }
  3394. } else {
  3395. line_join = "\n";
  3396. }
  3397. }
  3398. String result;
  3399. int from = 0;
  3400. int buffer_start = 0;
  3401. const int len = line.length();
  3402. bool process = true;
  3403. while (process) {
  3404. switch (r_state) {
  3405. case DOC_LINE_NORMAL: {
  3406. int lb_pos = line.find_char('[', from);
  3407. if (lb_pos < 0) {
  3408. process = false;
  3409. break;
  3410. }
  3411. int rb_pos = line.find_char(']', lb_pos + 1);
  3412. if (rb_pos < 0) {
  3413. process = false;
  3414. break;
  3415. }
  3416. from = rb_pos + 1;
  3417. String tag = line.substr(lb_pos + 1, rb_pos - lb_pos - 1);
  3418. if (tag == "code" || tag.begins_with("code ")) {
  3419. r_state = DOC_LINE_IN_CODE;
  3420. } else if (tag == "codeblock" || tag.begins_with("codeblock ")) {
  3421. if (lb_pos == 0) {
  3422. line_join = "\n";
  3423. } else {
  3424. result += line.substr(buffer_start, lb_pos - buffer_start) + '\n';
  3425. }
  3426. result += "[" + tag + "]";
  3427. if (from < len) {
  3428. result += '\n';
  3429. }
  3430. r_state = DOC_LINE_IN_CODEBLOCK;
  3431. buffer_start = from;
  3432. } else if (tag == "kbd") {
  3433. r_state = DOC_LINE_IN_KBD;
  3434. }
  3435. } break;
  3436. case DOC_LINE_IN_CODE: {
  3437. int pos = line.find("[/code]", from);
  3438. if (pos < 0) {
  3439. process = false;
  3440. break;
  3441. }
  3442. from = pos + 7; // `len("[/code]")`.
  3443. r_state = DOC_LINE_NORMAL;
  3444. } break;
  3445. case DOC_LINE_IN_CODEBLOCK: {
  3446. int pos = line.find("[/codeblock]", from);
  3447. if (pos < 0) {
  3448. process = false;
  3449. break;
  3450. }
  3451. from = pos + 12; // `len("[/codeblock]")`.
  3452. if (pos == 0) {
  3453. line_join = "\n";
  3454. } else {
  3455. result += line.substr(buffer_start, pos - buffer_start) + '\n';
  3456. }
  3457. result += "[/codeblock]";
  3458. if (from < len) {
  3459. result += '\n';
  3460. }
  3461. r_state = DOC_LINE_NORMAL;
  3462. buffer_start = from;
  3463. } break;
  3464. case DOC_LINE_IN_KBD: {
  3465. int pos = line.find("[/kbd]", from);
  3466. if (pos < 0) {
  3467. process = false;
  3468. break;
  3469. }
  3470. from = pos + 6; // `len("[/kbd]")`.
  3471. r_state = DOC_LINE_NORMAL;
  3472. } break;
  3473. }
  3474. }
  3475. result += line.substr(buffer_start);
  3476. if (r_state == DOC_LINE_NORMAL) {
  3477. result = result.strip_edges(false, true);
  3478. }
  3479. return line_join + result;
  3480. }
  3481. bool GDScriptParser::has_comment(int p_line, bool p_must_be_doc) {
  3482. bool has_comment = tokenizer->get_comments().has(p_line);
  3483. // If there are no comments or if we don't care whether the comment
  3484. // is a docstring, we have our result.
  3485. if (!p_must_be_doc || !has_comment) {
  3486. return has_comment;
  3487. }
  3488. return tokenizer->get_comments()[p_line].comment.begins_with("##");
  3489. }
  3490. GDScriptParser::MemberDocData GDScriptParser::parse_doc_comment(int p_line, bool p_single_line) {
  3491. ERR_FAIL_COND_V(!has_comment(p_line, true), MemberDocData());
  3492. const HashMap<int, GDScriptTokenizer::CommentData> &comments = tokenizer->get_comments();
  3493. int line = p_line;
  3494. if (!p_single_line) {
  3495. while (comments.has(line - 1) && comments[line - 1].new_line && comments[line - 1].comment.begins_with("##")) {
  3496. line--;
  3497. }
  3498. }
  3499. max_script_doc_line = MIN(max_script_doc_line, line - 1);
  3500. String space_prefix;
  3501. {
  3502. int i = 2;
  3503. for (; i < comments[line].comment.length(); i++) {
  3504. if (comments[line].comment[i] != ' ') {
  3505. break;
  3506. }
  3507. }
  3508. space_prefix = String(" ").repeat(i - 2);
  3509. }
  3510. DocLineState state = DOC_LINE_NORMAL;
  3511. MemberDocData result;
  3512. while (line <= p_line) {
  3513. String doc_line = comments[line].comment.trim_prefix("##");
  3514. line++;
  3515. if (state == DOC_LINE_NORMAL) {
  3516. String stripped_line = doc_line.strip_edges();
  3517. if (stripped_line == "@deprecated" || stripped_line.begins_with("@deprecated:")) {
  3518. result.is_deprecated = true;
  3519. if (stripped_line.begins_with("@deprecated:")) {
  3520. result.deprecated_message = stripped_line.trim_prefix("@deprecated:").strip_edges();
  3521. }
  3522. continue;
  3523. } else if (stripped_line == "@experimental" || stripped_line.begins_with("@experimental:")) {
  3524. result.is_experimental = true;
  3525. if (stripped_line.begins_with("@experimental:")) {
  3526. result.experimental_message = stripped_line.trim_prefix("@experimental:").strip_edges();
  3527. }
  3528. continue;
  3529. }
  3530. }
  3531. result.description += _process_doc_line(doc_line, result.description, space_prefix, state);
  3532. }
  3533. return result;
  3534. }
  3535. GDScriptParser::ClassDocData GDScriptParser::parse_class_doc_comment(int p_line, bool p_single_line) {
  3536. ERR_FAIL_COND_V(!has_comment(p_line, true), ClassDocData());
  3537. const HashMap<int, GDScriptTokenizer::CommentData> &comments = tokenizer->get_comments();
  3538. int line = p_line;
  3539. if (!p_single_line) {
  3540. while (comments.has(line - 1) && comments[line - 1].new_line && comments[line - 1].comment.begins_with("##")) {
  3541. line--;
  3542. }
  3543. }
  3544. max_script_doc_line = MIN(max_script_doc_line, line - 1);
  3545. String space_prefix;
  3546. {
  3547. int i = 2;
  3548. for (; i < comments[line].comment.length(); i++) {
  3549. if (comments[line].comment[i] != ' ') {
  3550. break;
  3551. }
  3552. }
  3553. space_prefix = String(" ").repeat(i - 2);
  3554. }
  3555. DocLineState state = DOC_LINE_NORMAL;
  3556. bool is_in_brief = true;
  3557. ClassDocData result;
  3558. while (line <= p_line) {
  3559. String doc_line = comments[line].comment.trim_prefix("##");
  3560. line++;
  3561. if (state == DOC_LINE_NORMAL) {
  3562. String stripped_line = doc_line.strip_edges();
  3563. // A blank line separates the description from the brief.
  3564. if (is_in_brief && !result.brief.is_empty() && stripped_line.is_empty()) {
  3565. is_in_brief = false;
  3566. continue;
  3567. }
  3568. if (stripped_line.begins_with("@tutorial")) {
  3569. String title, link;
  3570. int begin_scan = String("@tutorial").length();
  3571. if (begin_scan >= stripped_line.length()) {
  3572. continue; // Invalid syntax.
  3573. }
  3574. if (stripped_line[begin_scan] == ':') { // No title.
  3575. // Syntax: ## @tutorial: https://godotengine.org/ // The title argument is optional.
  3576. title = "";
  3577. link = stripped_line.trim_prefix("@tutorial:").strip_edges();
  3578. } else {
  3579. /* Syntax:
  3580. * @tutorial ( The Title Here ) : https://the.url/
  3581. * ^ open ^ close ^ colon ^ url
  3582. */
  3583. int open_bracket_pos = begin_scan, close_bracket_pos = 0;
  3584. while (open_bracket_pos < stripped_line.length() && (stripped_line[open_bracket_pos] == ' ' || stripped_line[open_bracket_pos] == '\t')) {
  3585. open_bracket_pos++;
  3586. }
  3587. if (open_bracket_pos == stripped_line.length() || stripped_line[open_bracket_pos++] != '(') {
  3588. continue; // Invalid syntax.
  3589. }
  3590. close_bracket_pos = open_bracket_pos;
  3591. while (close_bracket_pos < stripped_line.length() && stripped_line[close_bracket_pos] != ')') {
  3592. close_bracket_pos++;
  3593. }
  3594. if (close_bracket_pos == stripped_line.length()) {
  3595. continue; // Invalid syntax.
  3596. }
  3597. int colon_pos = close_bracket_pos + 1;
  3598. while (colon_pos < stripped_line.length() && (stripped_line[colon_pos] == ' ' || stripped_line[colon_pos] == '\t')) {
  3599. colon_pos++;
  3600. }
  3601. if (colon_pos == stripped_line.length() || stripped_line[colon_pos++] != ':') {
  3602. continue; // Invalid syntax.
  3603. }
  3604. title = stripped_line.substr(open_bracket_pos, close_bracket_pos - open_bracket_pos).strip_edges();
  3605. link = stripped_line.substr(colon_pos).strip_edges();
  3606. }
  3607. result.tutorials.append(Pair<String, String>(title, link));
  3608. continue;
  3609. } else if (stripped_line == "@deprecated" || stripped_line.begins_with("@deprecated:")) {
  3610. result.is_deprecated = true;
  3611. if (stripped_line.begins_with("@deprecated:")) {
  3612. result.deprecated_message = stripped_line.trim_prefix("@deprecated:").strip_edges();
  3613. }
  3614. continue;
  3615. } else if (stripped_line == "@experimental" || stripped_line.begins_with("@experimental:")) {
  3616. result.is_experimental = true;
  3617. if (stripped_line.begins_with("@experimental:")) {
  3618. result.experimental_message = stripped_line.trim_prefix("@experimental:").strip_edges();
  3619. }
  3620. continue;
  3621. }
  3622. }
  3623. if (is_in_brief) {
  3624. result.brief += _process_doc_line(doc_line, result.brief, space_prefix, state);
  3625. } else {
  3626. result.description += _process_doc_line(doc_line, result.description, space_prefix, state);
  3627. }
  3628. }
  3629. return result;
  3630. }
  3631. #endif // TOOLS_ENABLED
  3632. GDScriptParser::ParseRule *GDScriptParser::get_rule(GDScriptTokenizer::Token::Type p_token_type) {
  3633. // Function table for expression parsing.
  3634. // clang-format destroys the alignment here, so turn off for the table.
  3635. /* clang-format off */
  3636. static ParseRule rules[] = {
  3637. // PREFIX INFIX PRECEDENCE (for infix)
  3638. { nullptr, nullptr, PREC_NONE }, // EMPTY,
  3639. // Basic
  3640. { nullptr, nullptr, PREC_NONE }, // ANNOTATION,
  3641. { &GDScriptParser::parse_identifier, nullptr, PREC_NONE }, // IDENTIFIER,
  3642. { &GDScriptParser::parse_literal, nullptr, PREC_NONE }, // LITERAL,
  3643. // Comparison
  3644. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS,
  3645. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS_EQUAL,
  3646. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER,
  3647. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER_EQUAL,
  3648. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // EQUAL_EQUAL,
  3649. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // BANG_EQUAL,
  3650. // Logical
  3651. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AND,
  3652. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // OR,
  3653. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_not_in_operator, PREC_CONTENT_TEST }, // NOT,
  3654. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AMPERSAND_AMPERSAND,
  3655. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // PIPE_PIPE,
  3656. { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // BANG,
  3657. // Bitwise
  3658. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_AND }, // AMPERSAND,
  3659. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_OR }, // PIPE,
  3660. { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // TILDE,
  3661. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_XOR }, // CARET,
  3662. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // LESS_LESS,
  3663. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // GREATER_GREATER,
  3664. // Math
  3665. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // PLUS,
  3666. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // MINUS,
  3667. { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // STAR,
  3668. { nullptr, &GDScriptParser::parse_binary_operator, PREC_POWER }, // STAR_STAR,
  3669. { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // SLASH,
  3670. { &GDScriptParser::parse_get_node, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // PERCENT,
  3671. // Assignment
  3672. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // EQUAL,
  3673. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PLUS_EQUAL,
  3674. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // MINUS_EQUAL,
  3675. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // STAR_EQUAL,
  3676. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // STAR_STAR_EQUAL,
  3677. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // SLASH_EQUAL,
  3678. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PERCENT_EQUAL,
  3679. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // LESS_LESS_EQUAL,
  3680. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // GREATER_GREATER_EQUAL,
  3681. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // AMPERSAND_EQUAL,
  3682. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PIPE_EQUAL,
  3683. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // CARET_EQUAL,
  3684. // Control flow
  3685. { nullptr, &GDScriptParser::parse_ternary_operator, PREC_TERNARY }, // IF,
  3686. { nullptr, nullptr, PREC_NONE }, // ELIF,
  3687. { nullptr, nullptr, PREC_NONE }, // ELSE,
  3688. { nullptr, nullptr, PREC_NONE }, // FOR,
  3689. { nullptr, nullptr, PREC_NONE }, // WHILE,
  3690. { nullptr, nullptr, PREC_NONE }, // BREAK,
  3691. { nullptr, nullptr, PREC_NONE }, // CONTINUE,
  3692. { nullptr, nullptr, PREC_NONE }, // PASS,
  3693. { nullptr, nullptr, PREC_NONE }, // RETURN,
  3694. { nullptr, nullptr, PREC_NONE }, // MATCH,
  3695. { nullptr, nullptr, PREC_NONE }, // WHEN,
  3696. // Keywords
  3697. { nullptr, &GDScriptParser::parse_cast, PREC_CAST }, // AS,
  3698. { nullptr, nullptr, PREC_NONE }, // ASSERT,
  3699. { &GDScriptParser::parse_await, nullptr, PREC_NONE }, // AWAIT,
  3700. { nullptr, nullptr, PREC_NONE }, // BREAKPOINT,
  3701. { nullptr, nullptr, PREC_NONE }, // CLASS,
  3702. { nullptr, nullptr, PREC_NONE }, // CLASS_NAME,
  3703. { nullptr, nullptr, PREC_NONE }, // TK_CONST,
  3704. { nullptr, nullptr, PREC_NONE }, // ENUM,
  3705. { nullptr, nullptr, PREC_NONE }, // EXTENDS,
  3706. { &GDScriptParser::parse_lambda, nullptr, PREC_NONE }, // FUNC,
  3707. { nullptr, &GDScriptParser::parse_binary_operator, PREC_CONTENT_TEST }, // TK_IN,
  3708. { nullptr, &GDScriptParser::parse_type_test, PREC_TYPE_TEST }, // IS,
  3709. { nullptr, nullptr, PREC_NONE }, // NAMESPACE,
  3710. { &GDScriptParser::parse_preload, nullptr, PREC_NONE }, // PRELOAD,
  3711. { &GDScriptParser::parse_self, nullptr, PREC_NONE }, // SELF,
  3712. { nullptr, nullptr, PREC_NONE }, // SIGNAL,
  3713. { nullptr, nullptr, PREC_NONE }, // STATIC,
  3714. { &GDScriptParser::parse_call, nullptr, PREC_NONE }, // SUPER,
  3715. { nullptr, nullptr, PREC_NONE }, // TRAIT,
  3716. { nullptr, nullptr, PREC_NONE }, // VAR,
  3717. { nullptr, nullptr, PREC_NONE }, // TK_VOID,
  3718. { &GDScriptParser::parse_yield, nullptr, PREC_NONE }, // YIELD,
  3719. // Punctuation
  3720. { &GDScriptParser::parse_array, &GDScriptParser::parse_subscript, PREC_SUBSCRIPT }, // BRACKET_OPEN,
  3721. { nullptr, nullptr, PREC_NONE }, // BRACKET_CLOSE,
  3722. { &GDScriptParser::parse_dictionary, nullptr, PREC_NONE }, // BRACE_OPEN,
  3723. { nullptr, nullptr, PREC_NONE }, // BRACE_CLOSE,
  3724. { &GDScriptParser::parse_grouping, &GDScriptParser::parse_call, PREC_CALL }, // PARENTHESIS_OPEN,
  3725. { nullptr, nullptr, PREC_NONE }, // PARENTHESIS_CLOSE,
  3726. { nullptr, nullptr, PREC_NONE }, // COMMA,
  3727. { nullptr, nullptr, PREC_NONE }, // SEMICOLON,
  3728. { nullptr, &GDScriptParser::parse_attribute, PREC_ATTRIBUTE }, // PERIOD,
  3729. { nullptr, nullptr, PREC_NONE }, // PERIOD_PERIOD,
  3730. { nullptr, nullptr, PREC_NONE }, // PERIOD_PERIOD_PERIOD,
  3731. { nullptr, nullptr, PREC_NONE }, // COLON,
  3732. { &GDScriptParser::parse_get_node, nullptr, PREC_NONE }, // DOLLAR,
  3733. { nullptr, nullptr, PREC_NONE }, // FORWARD_ARROW,
  3734. { nullptr, nullptr, PREC_NONE }, // UNDERSCORE,
  3735. // Whitespace
  3736. { nullptr, nullptr, PREC_NONE }, // NEWLINE,
  3737. { nullptr, nullptr, PREC_NONE }, // INDENT,
  3738. { nullptr, nullptr, PREC_NONE }, // DEDENT,
  3739. // Constants
  3740. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_PI,
  3741. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_TAU,
  3742. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_INF,
  3743. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_NAN,
  3744. // Error message improvement
  3745. { nullptr, nullptr, PREC_NONE }, // VCS_CONFLICT_MARKER,
  3746. { nullptr, nullptr, PREC_NONE }, // BACKTICK,
  3747. { nullptr, &GDScriptParser::parse_invalid_token, PREC_CAST }, // QUESTION_MARK,
  3748. // Special
  3749. { nullptr, nullptr, PREC_NONE }, // ERROR,
  3750. { nullptr, nullptr, PREC_NONE }, // TK_EOF,
  3751. };
  3752. /* clang-format on */
  3753. // Avoid desync.
  3754. static_assert(std_size(rules) == GDScriptTokenizer::Token::TK_MAX, "Amount of parse rules don't match the amount of token types.");
  3755. // Let's assume this is never invalid, since nothing generates a TK_MAX.
  3756. return &rules[p_token_type];
  3757. }
  3758. bool GDScriptParser::SuiteNode::has_local(const StringName &p_name) const {
  3759. if (locals_indices.has(p_name)) {
  3760. return true;
  3761. }
  3762. if (parent_block != nullptr) {
  3763. return parent_block->has_local(p_name);
  3764. }
  3765. return false;
  3766. }
  3767. const GDScriptParser::SuiteNode::Local &GDScriptParser::SuiteNode::get_local(const StringName &p_name) const {
  3768. if (locals_indices.has(p_name)) {
  3769. return locals[locals_indices[p_name]];
  3770. }
  3771. if (parent_block != nullptr) {
  3772. return parent_block->get_local(p_name);
  3773. }
  3774. return empty;
  3775. }
  3776. bool GDScriptParser::AnnotationNode::apply(GDScriptParser *p_this, Node *p_target, ClassNode *p_class) {
  3777. if (is_applied) {
  3778. return true;
  3779. }
  3780. is_applied = true;
  3781. return (p_this->*(p_this->valid_annotations[name].apply))(this, p_target, p_class);
  3782. }
  3783. bool GDScriptParser::AnnotationNode::applies_to(uint32_t p_target_kinds) const {
  3784. return (info->target_kind & p_target_kinds) > 0;
  3785. }
  3786. bool GDScriptParser::validate_annotation_arguments(AnnotationNode *p_annotation) {
  3787. ERR_FAIL_COND_V_MSG(!valid_annotations.has(p_annotation->name), false, vformat(R"(Annotation "%s" not found to validate.)", p_annotation->name));
  3788. const MethodInfo &info = valid_annotations[p_annotation->name].info;
  3789. if (((info.flags & METHOD_FLAG_VARARG) == 0) && p_annotation->arguments.size() > info.arguments.size()) {
  3790. push_error(vformat(R"(Annotation "%s" requires at most %d arguments, but %d were given.)", p_annotation->name, info.arguments.size(), p_annotation->arguments.size()));
  3791. return false;
  3792. }
  3793. if (p_annotation->arguments.size() < info.arguments.size() - info.default_arguments.size()) {
  3794. push_error(vformat(R"(Annotation "%s" requires at least %d arguments, but %d were given.)", p_annotation->name, info.arguments.size() - info.default_arguments.size(), p_annotation->arguments.size()));
  3795. return false;
  3796. }
  3797. // Some annotations need to be resolved and applied in the parser.
  3798. if (p_annotation->name == SNAME("@icon") || p_annotation->name == SNAME("@warning_ignore_start") || p_annotation->name == SNAME("@warning_ignore_restore")) {
  3799. for (int i = 0; i < p_annotation->arguments.size(); i++) {
  3800. ExpressionNode *argument = p_annotation->arguments[i];
  3801. if (argument->type != Node::LITERAL) {
  3802. push_error(vformat(R"(Argument %d of annotation "%s" must be a string literal.)", i + 1, p_annotation->name), argument);
  3803. return false;
  3804. }
  3805. Variant value = static_cast<LiteralNode *>(argument)->value;
  3806. if (value.get_type() != Variant::STRING) {
  3807. push_error(vformat(R"(Argument %d of annotation "%s" must be a string literal.)", i + 1, p_annotation->name), argument);
  3808. return false;
  3809. }
  3810. p_annotation->resolved_arguments.push_back(value);
  3811. }
  3812. }
  3813. // For other annotations, see `GDScriptAnalyzer::resolve_annotation()`.
  3814. return true;
  3815. }
  3816. bool GDScriptParser::tool_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  3817. #ifdef DEBUG_ENABLED
  3818. if (_is_tool) {
  3819. push_error(R"("@tool" annotation can only be used once.)", p_annotation);
  3820. return false;
  3821. }
  3822. #endif // DEBUG_ENABLED
  3823. _is_tool = true;
  3824. return true;
  3825. }
  3826. bool GDScriptParser::icon_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  3827. ERR_FAIL_COND_V_MSG(p_target->type != Node::CLASS, false, R"("@icon" annotation can only be applied to classes.)");
  3828. ERR_FAIL_COND_V(p_annotation->resolved_arguments.is_empty(), false);
  3829. ClassNode *class_node = static_cast<ClassNode *>(p_target);
  3830. String path = p_annotation->resolved_arguments[0];
  3831. #ifdef DEBUG_ENABLED
  3832. if (!class_node->icon_path.is_empty()) {
  3833. push_error(R"("@icon" annotation can only be used once.)", p_annotation);
  3834. return false;
  3835. }
  3836. if (path.is_empty()) {
  3837. push_error(R"("@icon" annotation argument must contain the path to the icon.)", p_annotation->arguments[0]);
  3838. return false;
  3839. }
  3840. #endif // DEBUG_ENABLED
  3841. class_node->icon_path = path;
  3842. if (path.is_empty() || path.is_absolute_path()) {
  3843. class_node->simplified_icon_path = path.simplify_path();
  3844. } else if (path.is_relative_path()) {
  3845. class_node->simplified_icon_path = script_path.get_base_dir().path_join(path).simplify_path();
  3846. } else {
  3847. class_node->simplified_icon_path = path;
  3848. }
  3849. return true;
  3850. }
  3851. bool GDScriptParser::static_unload_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  3852. ERR_FAIL_COND_V_MSG(p_target->type != Node::CLASS, false, vformat(R"("%s" annotation can only be applied to classes.)", p_annotation->name));
  3853. ClassNode *class_node = static_cast<ClassNode *>(p_target);
  3854. if (class_node->annotated_static_unload) {
  3855. push_error(vformat(R"("%s" annotation can only be used once per script.)", p_annotation->name), p_annotation);
  3856. return false;
  3857. }
  3858. class_node->annotated_static_unload = true;
  3859. return true;
  3860. }
  3861. bool GDScriptParser::abstract_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  3862. // NOTE: Use `p_target`, **not** `p_class`, because when `p_target` is a class then `p_class` refers to the outer class.
  3863. if (p_target->type == Node::CLASS) {
  3864. ClassNode *class_node = static_cast<ClassNode *>(p_target);
  3865. if (class_node->is_abstract) {
  3866. push_error(R"("@abstract" annotation can only be used once per class.)", p_annotation);
  3867. return false;
  3868. }
  3869. class_node->is_abstract = true;
  3870. return true;
  3871. }
  3872. if (p_target->type == Node::FUNCTION) {
  3873. FunctionNode *function_node = static_cast<FunctionNode *>(p_target);
  3874. if (function_node->is_static) {
  3875. push_error(R"("@abstract" annotation cannot be applied to static functions.)", p_annotation);
  3876. return false;
  3877. }
  3878. if (function_node->is_abstract) {
  3879. push_error(R"("@abstract" annotation can only be used once per function.)", p_annotation);
  3880. return false;
  3881. }
  3882. function_node->is_abstract = true;
  3883. return true;
  3884. }
  3885. ERR_FAIL_V_MSG(false, R"("@abstract" annotation can only be applied to classes and functions.)");
  3886. }
  3887. bool GDScriptParser::onready_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  3888. ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, R"("@onready" annotation can only be applied to class variables.)");
  3889. if (current_class && !ClassDB::is_parent_class(current_class->get_datatype().native_type, SNAME("Node"))) {
  3890. push_error(R"("@onready" can only be used in classes that inherit "Node".)", p_annotation);
  3891. return false;
  3892. }
  3893. VariableNode *variable = static_cast<VariableNode *>(p_target);
  3894. if (variable->is_static) {
  3895. push_error(R"("@onready" annotation cannot be applied to a static variable.)", p_annotation);
  3896. return false;
  3897. }
  3898. if (variable->onready) {
  3899. push_error(R"("@onready" annotation can only be used once per variable.)", p_annotation);
  3900. return false;
  3901. }
  3902. variable->onready = true;
  3903. current_class->onready_used = true;
  3904. return true;
  3905. }
  3906. static String _get_annotation_error_string(const StringName &p_annotation_name, const Vector<Variant::Type> &p_expected_types, const GDScriptParser::DataType &p_provided_type) {
  3907. Vector<String> types;
  3908. for (int i = 0; i < p_expected_types.size(); i++) {
  3909. const Variant::Type &type = p_expected_types[i];
  3910. types.push_back(Variant::get_type_name(type));
  3911. types.push_back("Array[" + Variant::get_type_name(type) + "]");
  3912. switch (type) {
  3913. case Variant::INT:
  3914. types.push_back("PackedByteArray");
  3915. types.push_back("PackedInt32Array");
  3916. types.push_back("PackedInt64Array");
  3917. break;
  3918. case Variant::FLOAT:
  3919. types.push_back("PackedFloat32Array");
  3920. types.push_back("PackedFloat64Array");
  3921. break;
  3922. case Variant::STRING:
  3923. types.push_back("PackedStringArray");
  3924. break;
  3925. case Variant::VECTOR2:
  3926. types.push_back("PackedVector2Array");
  3927. break;
  3928. case Variant::VECTOR3:
  3929. types.push_back("PackedVector3Array");
  3930. break;
  3931. case Variant::COLOR:
  3932. types.push_back("PackedColorArray");
  3933. break;
  3934. case Variant::VECTOR4:
  3935. types.push_back("PackedVector4Array");
  3936. break;
  3937. default:
  3938. break;
  3939. }
  3940. }
  3941. String string;
  3942. if (types.size() == 1) {
  3943. string = types[0].quote();
  3944. } else if (types.size() == 2) {
  3945. string = types[0].quote() + " or " + types[1].quote();
  3946. } else if (types.size() >= 3) {
  3947. string = types[0].quote();
  3948. for (int i = 1; i < types.size() - 1; i++) {
  3949. string += ", " + types[i].quote();
  3950. }
  3951. string += ", or " + types[types.size() - 1].quote();
  3952. }
  3953. return vformat(R"("%s" annotation requires a variable of type %s, but type "%s" was given instead.)", p_annotation_name, string, p_provided_type.to_string());
  3954. }
  3955. static StringName _find_narrowest_native_or_global_class(const GDScriptParser::DataType &p_type) {
  3956. switch (p_type.kind) {
  3957. case GDScriptParser::DataType::NATIVE: {
  3958. if (p_type.is_meta_type) {
  3959. return Object::get_class_static(); // `GDScriptNativeClass` is not an exposed class.
  3960. }
  3961. return p_type.native_type;
  3962. } break;
  3963. case GDScriptParser::DataType::SCRIPT: {
  3964. Ref<Script> script;
  3965. if (p_type.script_type.is_valid()) {
  3966. script = p_type.script_type;
  3967. } else {
  3968. script = ResourceLoader::load(p_type.script_path, SNAME("Script"));
  3969. }
  3970. if (p_type.is_meta_type) {
  3971. return script.is_valid() ? script->get_class_name() : Script::get_class_static();
  3972. }
  3973. if (script.is_null()) {
  3974. return p_type.native_type;
  3975. }
  3976. if (script->get_global_name() != StringName()) {
  3977. return script->get_global_name();
  3978. }
  3979. Ref<Script> base_script = script->get_base_script();
  3980. if (base_script.is_null()) {
  3981. return script->get_instance_base_type();
  3982. }
  3983. GDScriptParser::DataType base_type;
  3984. base_type.kind = GDScriptParser::DataType::SCRIPT;
  3985. base_type.builtin_type = Variant::OBJECT;
  3986. base_type.native_type = base_script->get_instance_base_type();
  3987. base_type.script_type = base_script;
  3988. base_type.script_path = base_script->get_path();
  3989. return _find_narrowest_native_or_global_class(base_type);
  3990. } break;
  3991. case GDScriptParser::DataType::CLASS: {
  3992. if (p_type.is_meta_type) {
  3993. return GDScript::get_class_static();
  3994. }
  3995. if (p_type.class_type == nullptr) {
  3996. return p_type.native_type;
  3997. }
  3998. if (p_type.class_type->get_global_name() != StringName()) {
  3999. return p_type.class_type->get_global_name();
  4000. }
  4001. return _find_narrowest_native_or_global_class(p_type.class_type->base_type);
  4002. } break;
  4003. default: {
  4004. ERR_FAIL_V(StringName());
  4005. } break;
  4006. }
  4007. }
  4008. template <PropertyHint t_hint, Variant::Type t_type>
  4009. bool GDScriptParser::export_annotations(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  4010. ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
  4011. ERR_FAIL_NULL_V(p_class, false);
  4012. VariableNode *variable = static_cast<VariableNode *>(p_target);
  4013. if (variable->is_static) {
  4014. push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
  4015. return false;
  4016. }
  4017. if (variable->exported) {
  4018. push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
  4019. return false;
  4020. }
  4021. variable->exported = true;
  4022. variable->export_info.type = t_type;
  4023. variable->export_info.hint = t_hint;
  4024. String hint_string;
  4025. for (int i = 0; i < p_annotation->resolved_arguments.size(); i++) {
  4026. String arg_string = String(p_annotation->resolved_arguments[i]);
  4027. if (p_annotation->name != SNAME("@export_placeholder")) {
  4028. if (arg_string.is_empty()) {
  4029. push_error(vformat(R"(Argument %d of annotation "%s" is empty.)", i + 1, p_annotation->name), p_annotation->arguments[i]);
  4030. return false;
  4031. }
  4032. if (arg_string.contains_char(',')) {
  4033. push_error(vformat(R"(Argument %d of annotation "%s" contains a comma. Use separate arguments instead.)", i + 1, p_annotation->name), p_annotation->arguments[i]);
  4034. return false;
  4035. }
  4036. }
  4037. // WARNING: Do not merge with the previous `if` because there `!=`, not `==`!
  4038. if (p_annotation->name == SNAME("@export_flags")) {
  4039. const int64_t max_flags = 32;
  4040. Vector<String> t = arg_string.split(":", true, 1);
  4041. if (t[0].is_empty()) {
  4042. push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": Expected flag name.)", i + 1), p_annotation->arguments[i]);
  4043. return false;
  4044. }
  4045. if (t.size() == 2) {
  4046. if (t[1].is_empty()) {
  4047. push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": Expected flag value.)", i + 1), p_annotation->arguments[i]);
  4048. return false;
  4049. }
  4050. if (!t[1].is_valid_int()) {
  4051. push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": The flag value must be a valid integer.)", i + 1), p_annotation->arguments[i]);
  4052. return false;
  4053. }
  4054. int64_t value = t[1].to_int();
  4055. if (value < 1 || value >= (1LL << max_flags)) {
  4056. push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": The flag value must be at least 1 and at most 2 ** %d - 1.)", i + 1, max_flags), p_annotation->arguments[i]);
  4057. return false;
  4058. }
  4059. } else if (i >= max_flags) {
  4060. push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": Starting from argument %d, the flag value must be specified explicitly.)", i + 1, max_flags + 1), p_annotation->arguments[i]);
  4061. return false;
  4062. }
  4063. } else if (p_annotation->name == SNAME("@export_node_path")) {
  4064. String native_class = arg_string;
  4065. if (ScriptServer::is_global_class(arg_string)) {
  4066. native_class = ScriptServer::get_global_class_native_base(arg_string);
  4067. }
  4068. if (!ClassDB::class_exists(native_class) || !ClassDB::is_class_exposed(native_class)) {
  4069. push_error(vformat(R"(Invalid argument %d of annotation "@export_node_path": The class "%s" was not found in the global scope.)", i + 1, arg_string), p_annotation->arguments[i]);
  4070. return false;
  4071. } else if (!ClassDB::is_parent_class(native_class, SNAME("Node"))) {
  4072. push_error(vformat(R"(Invalid argument %d of annotation "@export_node_path": The class "%s" does not inherit "Node".)", i + 1, arg_string), p_annotation->arguments[i]);
  4073. return false;
  4074. }
  4075. }
  4076. if (i > 0) {
  4077. hint_string += ",";
  4078. }
  4079. hint_string += arg_string;
  4080. }
  4081. variable->export_info.hint_string = hint_string;
  4082. // This is called after the analyzer is done finding the type, so this should be set here.
  4083. DataType export_type = variable->get_datatype();
  4084. // Use initializer type if specified type is `Variant`.
  4085. if (export_type.is_variant() && variable->initializer != nullptr && variable->initializer->datatype.is_set()) {
  4086. export_type = variable->initializer->get_datatype();
  4087. export_type.type_source = DataType::INFERRED;
  4088. }
  4089. const Variant::Type original_export_type_builtin = export_type.builtin_type;
  4090. // Process array and packed array annotations on the element type.
  4091. bool is_array = false;
  4092. if (export_type.builtin_type == Variant::ARRAY && export_type.has_container_element_type(0)) {
  4093. is_array = true;
  4094. export_type = export_type.get_container_element_type(0);
  4095. } else if (export_type.is_typed_container_type()) {
  4096. is_array = true;
  4097. export_type = export_type.get_typed_container_type();
  4098. export_type.type_source = variable->datatype.type_source;
  4099. }
  4100. bool is_dict = false;
  4101. if (export_type.builtin_type == Variant::DICTIONARY && export_type.has_container_element_types()) {
  4102. is_dict = true;
  4103. DataType inner_type = export_type.get_container_element_type_or_variant(1);
  4104. export_type = export_type.get_container_element_type_or_variant(0);
  4105. export_type.set_container_element_type(0, inner_type); // Store earlier extracted value within key to separately parse after.
  4106. }
  4107. bool use_default_variable_type_check = true;
  4108. if (p_annotation->name == SNAME("@export_range")) {
  4109. if (export_type.builtin_type == Variant::INT) {
  4110. variable->export_info.type = Variant::INT;
  4111. }
  4112. } else if (p_annotation->name == SNAME("@export_multiline")) {
  4113. use_default_variable_type_check = false;
  4114. if (export_type.builtin_type != Variant::STRING && export_type.builtin_type != Variant::DICTIONARY) {
  4115. Vector<Variant::Type> expected_types = { Variant::STRING, Variant::DICTIONARY };
  4116. push_error(_get_annotation_error_string(p_annotation->name, expected_types, variable->get_datatype()), p_annotation);
  4117. return false;
  4118. }
  4119. if (export_type.builtin_type == Variant::DICTIONARY) {
  4120. variable->export_info.type = Variant::DICTIONARY;
  4121. }
  4122. } else if (p_annotation->name == SNAME("@export")) {
  4123. use_default_variable_type_check = false;
  4124. if (variable->datatype_specifier == nullptr && variable->initializer == nullptr) {
  4125. push_error(R"(Cannot use simple "@export" annotation with variable without type or initializer, since type can't be inferred.)", p_annotation);
  4126. return false;
  4127. }
  4128. if (export_type.has_no_type()) {
  4129. push_error(R"(Cannot use simple "@export" annotation because the type of the initialized value can't be inferred.)", p_annotation);
  4130. return false;
  4131. }
  4132. switch (export_type.kind) {
  4133. case GDScriptParser::DataType::BUILTIN:
  4134. variable->export_info.type = export_type.builtin_type;
  4135. variable->export_info.hint = PROPERTY_HINT_NONE;
  4136. variable->export_info.hint_string = String();
  4137. break;
  4138. case GDScriptParser::DataType::NATIVE:
  4139. case GDScriptParser::DataType::SCRIPT:
  4140. case GDScriptParser::DataType::CLASS: {
  4141. const StringName class_name = _find_narrowest_native_or_global_class(export_type);
  4142. if (ClassDB::is_parent_class(export_type.native_type, SNAME("Resource"))) {
  4143. variable->export_info.type = Variant::OBJECT;
  4144. variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE;
  4145. variable->export_info.hint_string = class_name;
  4146. } else if (ClassDB::is_parent_class(export_type.native_type, SNAME("Node"))) {
  4147. variable->export_info.type = Variant::OBJECT;
  4148. variable->export_info.hint = PROPERTY_HINT_NODE_TYPE;
  4149. variable->export_info.hint_string = class_name;
  4150. } else {
  4151. push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", p_annotation);
  4152. return false;
  4153. }
  4154. } break;
  4155. case GDScriptParser::DataType::ENUM: {
  4156. if (export_type.is_meta_type) {
  4157. variable->export_info.type = Variant::DICTIONARY;
  4158. } else {
  4159. variable->export_info.type = Variant::INT;
  4160. variable->export_info.hint = PROPERTY_HINT_ENUM;
  4161. String enum_hint_string;
  4162. bool first = true;
  4163. for (const KeyValue<StringName, int64_t> &E : export_type.enum_values) {
  4164. if (!first) {
  4165. enum_hint_string += ",";
  4166. } else {
  4167. first = false;
  4168. }
  4169. enum_hint_string += E.key.operator String().capitalize().xml_escape();
  4170. enum_hint_string += ":";
  4171. enum_hint_string += String::num_int64(E.value).xml_escape();
  4172. }
  4173. variable->export_info.hint_string = enum_hint_string;
  4174. variable->export_info.usage |= PROPERTY_USAGE_CLASS_IS_ENUM;
  4175. variable->export_info.class_name = String(export_type.native_type).replace("::", ".");
  4176. }
  4177. } break;
  4178. case GDScriptParser::DataType::VARIANT: {
  4179. if (export_type.is_variant()) {
  4180. variable->export_info.type = Variant::NIL;
  4181. variable->export_info.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  4182. }
  4183. } break;
  4184. default:
  4185. push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", p_annotation);
  4186. return false;
  4187. }
  4188. if (variable->export_info.hint == PROPERTY_HINT_NODE_TYPE && !ClassDB::is_parent_class(p_class->base_type.native_type, SNAME("Node"))) {
  4189. push_error(vformat(R"(Node export is only supported in Node-derived classes, but the current class inherits "%s".)", p_class->base_type.to_string()), p_annotation);
  4190. return false;
  4191. }
  4192. if (is_dict) {
  4193. String key_prefix = itos(variable->export_info.type);
  4194. if (variable->export_info.hint) {
  4195. key_prefix += "/" + itos(variable->export_info.hint);
  4196. }
  4197. key_prefix += ":" + variable->export_info.hint_string;
  4198. // Now parse value.
  4199. export_type = export_type.get_container_element_type(0);
  4200. if (export_type.is_variant() || export_type.has_no_type()) {
  4201. export_type.kind = GDScriptParser::DataType::BUILTIN;
  4202. }
  4203. switch (export_type.kind) {
  4204. case GDScriptParser::DataType::BUILTIN:
  4205. variable->export_info.type = export_type.builtin_type;
  4206. variable->export_info.hint = PROPERTY_HINT_NONE;
  4207. variable->export_info.hint_string = String();
  4208. break;
  4209. case GDScriptParser::DataType::NATIVE:
  4210. case GDScriptParser::DataType::SCRIPT:
  4211. case GDScriptParser::DataType::CLASS: {
  4212. const StringName class_name = _find_narrowest_native_or_global_class(export_type);
  4213. if (ClassDB::is_parent_class(export_type.native_type, SNAME("Resource"))) {
  4214. variable->export_info.type = Variant::OBJECT;
  4215. variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE;
  4216. variable->export_info.hint_string = class_name;
  4217. } else if (ClassDB::is_parent_class(export_type.native_type, SNAME("Node"))) {
  4218. variable->export_info.type = Variant::OBJECT;
  4219. variable->export_info.hint = PROPERTY_HINT_NODE_TYPE;
  4220. variable->export_info.hint_string = class_name;
  4221. } else {
  4222. push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", p_annotation);
  4223. return false;
  4224. }
  4225. } break;
  4226. case GDScriptParser::DataType::ENUM: {
  4227. if (export_type.is_meta_type) {
  4228. variable->export_info.type = Variant::DICTIONARY;
  4229. } else {
  4230. variable->export_info.type = Variant::INT;
  4231. variable->export_info.hint = PROPERTY_HINT_ENUM;
  4232. String enum_hint_string;
  4233. bool first = true;
  4234. for (const KeyValue<StringName, int64_t> &E : export_type.enum_values) {
  4235. if (!first) {
  4236. enum_hint_string += ",";
  4237. } else {
  4238. first = false;
  4239. }
  4240. enum_hint_string += E.key.operator String().capitalize().xml_escape();
  4241. enum_hint_string += ":";
  4242. enum_hint_string += String::num_int64(E.value).xml_escape();
  4243. }
  4244. variable->export_info.hint_string = enum_hint_string;
  4245. variable->export_info.usage |= PROPERTY_USAGE_CLASS_IS_ENUM;
  4246. variable->export_info.class_name = String(export_type.native_type).replace("::", ".");
  4247. }
  4248. } break;
  4249. default:
  4250. push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", p_annotation);
  4251. return false;
  4252. }
  4253. if (variable->export_info.hint == PROPERTY_HINT_NODE_TYPE && !ClassDB::is_parent_class(p_class->base_type.native_type, SNAME("Node"))) {
  4254. push_error(vformat(R"(Node export is only supported in Node-derived classes, but the current class inherits "%s".)", p_class->base_type.to_string()), p_annotation);
  4255. return false;
  4256. }
  4257. String value_prefix = itos(variable->export_info.type);
  4258. if (variable->export_info.hint) {
  4259. value_prefix += "/" + itos(variable->export_info.hint);
  4260. }
  4261. value_prefix += ":" + variable->export_info.hint_string;
  4262. variable->export_info.type = Variant::DICTIONARY;
  4263. variable->export_info.hint = PROPERTY_HINT_TYPE_STRING;
  4264. variable->export_info.hint_string = key_prefix + ";" + value_prefix;
  4265. variable->export_info.usage = PROPERTY_USAGE_DEFAULT;
  4266. variable->export_info.class_name = StringName();
  4267. }
  4268. } else if (p_annotation->name == SNAME("@export_enum")) {
  4269. use_default_variable_type_check = false;
  4270. Variant::Type enum_type = Variant::INT;
  4271. if (export_type.kind == DataType::BUILTIN && export_type.builtin_type == Variant::STRING) {
  4272. enum_type = Variant::STRING;
  4273. }
  4274. variable->export_info.type = enum_type;
  4275. if (!export_type.is_variant() && (export_type.kind != DataType::BUILTIN || export_type.builtin_type != enum_type)) {
  4276. Vector<Variant::Type> expected_types = { Variant::INT, Variant::STRING };
  4277. push_error(_get_annotation_error_string(p_annotation->name, expected_types, variable->get_datatype()), p_annotation);
  4278. return false;
  4279. }
  4280. }
  4281. if (use_default_variable_type_check) {
  4282. // Validate variable type with export.
  4283. if (!export_type.is_variant() && (export_type.kind != DataType::BUILTIN || export_type.builtin_type != t_type)) {
  4284. // Allow float/int conversion.
  4285. if ((t_type != Variant::FLOAT || export_type.builtin_type != Variant::INT) && (t_type != Variant::INT || export_type.builtin_type != Variant::FLOAT)) {
  4286. Vector<Variant::Type> expected_types = { t_type };
  4287. push_error(_get_annotation_error_string(p_annotation->name, expected_types, variable->get_datatype()), p_annotation);
  4288. return false;
  4289. }
  4290. }
  4291. }
  4292. if (is_array) {
  4293. String hint_prefix = itos(variable->export_info.type);
  4294. if (variable->export_info.hint) {
  4295. hint_prefix += "/" + itos(variable->export_info.hint);
  4296. }
  4297. variable->export_info.type = original_export_type_builtin;
  4298. variable->export_info.hint = PROPERTY_HINT_TYPE_STRING;
  4299. variable->export_info.hint_string = hint_prefix + ":" + variable->export_info.hint_string;
  4300. variable->export_info.usage = PROPERTY_USAGE_DEFAULT;
  4301. variable->export_info.class_name = StringName();
  4302. }
  4303. return true;
  4304. }
  4305. // For `@export_storage` and `@export_custom`, there is no need to check the variable type, argument values,
  4306. // or handle array exports in a special way, so they are implemented as separate methods.
  4307. bool GDScriptParser::export_storage_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  4308. ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
  4309. VariableNode *variable = static_cast<VariableNode *>(p_target);
  4310. if (variable->is_static) {
  4311. push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
  4312. return false;
  4313. }
  4314. if (variable->exported) {
  4315. push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
  4316. return false;
  4317. }
  4318. variable->exported = true;
  4319. // Save the info because the compiler uses export info for overwriting member info.
  4320. variable->export_info = variable->get_datatype().to_property_info(variable->identifier->name);
  4321. variable->export_info.usage |= PROPERTY_USAGE_STORAGE;
  4322. return true;
  4323. }
  4324. bool GDScriptParser::export_custom_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  4325. ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
  4326. ERR_FAIL_COND_V_MSG(p_annotation->resolved_arguments.size() < 2, false, R"(Annotation "@export_custom" requires 2 arguments.)");
  4327. VariableNode *variable = static_cast<VariableNode *>(p_target);
  4328. if (variable->is_static) {
  4329. push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
  4330. return false;
  4331. }
  4332. if (variable->exported) {
  4333. push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
  4334. return false;
  4335. }
  4336. variable->exported = true;
  4337. DataType export_type = variable->get_datatype();
  4338. variable->export_info.type = export_type.builtin_type;
  4339. variable->export_info.hint = static_cast<PropertyHint>(p_annotation->resolved_arguments[0].operator int64_t());
  4340. variable->export_info.hint_string = p_annotation->resolved_arguments[1];
  4341. if (p_annotation->resolved_arguments.size() >= 3) {
  4342. variable->export_info.usage = p_annotation->resolved_arguments[2].operator int64_t();
  4343. }
  4344. return true;
  4345. }
  4346. bool GDScriptParser::export_tool_button_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  4347. #ifdef TOOLS_ENABLED
  4348. ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
  4349. ERR_FAIL_COND_V(p_annotation->resolved_arguments.is_empty(), false);
  4350. if (!is_tool()) {
  4351. push_error(R"(Tool buttons can only be used in tool scripts (add "@tool" to the top of the script).)", p_annotation);
  4352. return false;
  4353. }
  4354. VariableNode *variable = static_cast<VariableNode *>(p_target);
  4355. if (variable->is_static) {
  4356. push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
  4357. return false;
  4358. }
  4359. if (variable->exported) {
  4360. push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
  4361. return false;
  4362. }
  4363. const DataType variable_type = variable->get_datatype();
  4364. if (!variable_type.is_variant() && variable_type.is_hard_type()) {
  4365. if (variable_type.kind != DataType::BUILTIN || variable_type.builtin_type != Variant::CALLABLE) {
  4366. push_error(vformat(R"("@export_tool_button" annotation requires a variable of type "Callable", but type "%s" was given instead.)", variable_type.to_string()), p_annotation);
  4367. return false;
  4368. }
  4369. }
  4370. variable->exported = true;
  4371. // Build the hint string (format: `<text>[,<icon>]`).
  4372. String hint_string = p_annotation->resolved_arguments[0].operator String(); // Button text.
  4373. if (p_annotation->resolved_arguments.size() > 1) {
  4374. hint_string += "," + p_annotation->resolved_arguments[1].operator String(); // Button icon.
  4375. }
  4376. variable->export_info.type = Variant::CALLABLE;
  4377. variable->export_info.hint = PROPERTY_HINT_TOOL_BUTTON;
  4378. variable->export_info.hint_string = hint_string;
  4379. variable->export_info.usage = PROPERTY_USAGE_EDITOR;
  4380. #endif // TOOLS_ENABLED
  4381. return true; // Only available in editor.
  4382. }
  4383. template <PropertyUsageFlags t_usage>
  4384. bool GDScriptParser::export_group_annotations(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  4385. ERR_FAIL_COND_V(p_annotation->resolved_arguments.is_empty(), false);
  4386. p_annotation->export_info.name = p_annotation->resolved_arguments[0];
  4387. switch (t_usage) {
  4388. case PROPERTY_USAGE_CATEGORY: {
  4389. p_annotation->export_info.usage = t_usage;
  4390. } break;
  4391. case PROPERTY_USAGE_GROUP: {
  4392. p_annotation->export_info.usage = t_usage;
  4393. if (p_annotation->resolved_arguments.size() == 2) {
  4394. p_annotation->export_info.hint_string = p_annotation->resolved_arguments[1];
  4395. }
  4396. } break;
  4397. case PROPERTY_USAGE_SUBGROUP: {
  4398. p_annotation->export_info.usage = t_usage;
  4399. if (p_annotation->resolved_arguments.size() == 2) {
  4400. p_annotation->export_info.hint_string = p_annotation->resolved_arguments[1];
  4401. }
  4402. } break;
  4403. }
  4404. return true;
  4405. }
  4406. bool GDScriptParser::warning_ignore_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  4407. #ifdef DEBUG_ENABLED
  4408. bool has_error = false;
  4409. for (const Variant &warning_name : p_annotation->resolved_arguments) {
  4410. GDScriptWarning::Code warning_code = GDScriptWarning::get_code_from_name(String(warning_name).to_upper());
  4411. if (warning_code == GDScriptWarning::WARNING_MAX) {
  4412. push_error(vformat(R"(Invalid warning name: "%s".)", warning_name), p_annotation);
  4413. has_error = true;
  4414. } else {
  4415. int start_line = p_annotation->start_line;
  4416. int end_line = p_target->end_line;
  4417. switch (p_target->type) {
  4418. #define SIMPLE_CASE(m_type, m_class, m_property) \
  4419. case m_type: { \
  4420. m_class *node = static_cast<m_class *>(p_target); \
  4421. if (node->m_property == nullptr) { \
  4422. end_line = node->start_line; \
  4423. } else { \
  4424. end_line = node->m_property->end_line; \
  4425. } \
  4426. } break;
  4427. // Can contain properties (set/get).
  4428. SIMPLE_CASE(Node::VARIABLE, VariableNode, initializer)
  4429. // Contain bodies.
  4430. SIMPLE_CASE(Node::FOR, ForNode, list)
  4431. SIMPLE_CASE(Node::IF, IfNode, condition)
  4432. SIMPLE_CASE(Node::MATCH, MatchNode, test)
  4433. SIMPLE_CASE(Node::WHILE, WhileNode, condition)
  4434. #undef SIMPLE_CASE
  4435. case Node::CLASS: {
  4436. end_line = p_target->start_line;
  4437. for (const AnnotationNode *annotation : p_target->annotations) {
  4438. start_line = MIN(start_line, annotation->start_line);
  4439. end_line = MAX(end_line, annotation->end_line);
  4440. }
  4441. } break;
  4442. case Node::FUNCTION: {
  4443. FunctionNode *function = static_cast<FunctionNode *>(p_target);
  4444. end_line = function->start_line;
  4445. for (int i = 0; i < function->parameters.size(); i++) {
  4446. end_line = MAX(end_line, function->parameters[i]->end_line);
  4447. if (function->parameters[i]->initializer != nullptr) {
  4448. end_line = MAX(end_line, function->parameters[i]->initializer->end_line);
  4449. }
  4450. }
  4451. } break;
  4452. case Node::MATCH_BRANCH: {
  4453. MatchBranchNode *branch = static_cast<MatchBranchNode *>(p_target);
  4454. end_line = branch->start_line;
  4455. for (int i = 0; i < branch->patterns.size(); i++) {
  4456. end_line = MAX(end_line, branch->patterns[i]->end_line);
  4457. }
  4458. } break;
  4459. default: {
  4460. } break;
  4461. }
  4462. end_line = MAX(start_line, end_line); // Prevent infinite loop.
  4463. for (int line = start_line; line <= end_line; line++) {
  4464. warning_ignored_lines[warning_code].insert(line);
  4465. }
  4466. }
  4467. }
  4468. return !has_error;
  4469. #else // !DEBUG_ENABLED
  4470. // Only available in debug builds.
  4471. return true;
  4472. #endif // DEBUG_ENABLED
  4473. }
  4474. bool GDScriptParser::warning_ignore_region_annotations(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  4475. #ifdef DEBUG_ENABLED
  4476. bool has_error = false;
  4477. const bool is_start = p_annotation->name == SNAME("@warning_ignore_start");
  4478. for (const Variant &warning_name : p_annotation->resolved_arguments) {
  4479. GDScriptWarning::Code warning_code = GDScriptWarning::get_code_from_name(String(warning_name).to_upper());
  4480. if (warning_code == GDScriptWarning::WARNING_MAX) {
  4481. push_error(vformat(R"(Invalid warning name: "%s".)", warning_name), p_annotation);
  4482. has_error = true;
  4483. continue;
  4484. }
  4485. if (is_start) {
  4486. if (warning_ignore_start_lines[warning_code] != INT_MAX) {
  4487. push_error(vformat(R"(Warning "%s" is already being ignored by "@warning_ignore_start" at line %d.)", String(warning_name).to_upper(), warning_ignore_start_lines[warning_code]), p_annotation);
  4488. has_error = true;
  4489. continue;
  4490. }
  4491. warning_ignore_start_lines[warning_code] = p_annotation->start_line;
  4492. } else {
  4493. if (warning_ignore_start_lines[warning_code] == INT_MAX) {
  4494. push_error(vformat(R"(Warning "%s" is not being ignored by "@warning_ignore_start".)", String(warning_name).to_upper()), p_annotation);
  4495. has_error = true;
  4496. continue;
  4497. }
  4498. const int start_line = warning_ignore_start_lines[warning_code];
  4499. const int end_line = MAX(start_line, p_annotation->start_line); // Prevent infinite loop.
  4500. for (int i = start_line; i <= end_line; i++) {
  4501. warning_ignored_lines[warning_code].insert(i);
  4502. }
  4503. warning_ignore_start_lines[warning_code] = INT_MAX;
  4504. }
  4505. }
  4506. return !has_error;
  4507. #else // !DEBUG_ENABLED
  4508. // Only available in debug builds.
  4509. return true;
  4510. #endif // DEBUG_ENABLED
  4511. }
  4512. bool GDScriptParser::rpc_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  4513. ERR_FAIL_COND_V_MSG(p_target->type != Node::FUNCTION, false, vformat(R"("%s" annotation can only be applied to functions.)", p_annotation->name));
  4514. FunctionNode *function = static_cast<FunctionNode *>(p_target);
  4515. if (function->rpc_config.get_type() != Variant::NIL) {
  4516. push_error(R"(RPC annotations can only be used once per function.)", p_annotation);
  4517. return false;
  4518. }
  4519. // Default values should match the annotation registration defaults and `SceneRPCInterface::_parse_rpc_config()`.
  4520. Dictionary rpc_config;
  4521. rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_AUTHORITY;
  4522. if (!p_annotation->resolved_arguments.is_empty()) {
  4523. unsigned char locality_args = 0;
  4524. unsigned char permission_args = 0;
  4525. unsigned char transfer_mode_args = 0;
  4526. for (int i = 0; i < p_annotation->resolved_arguments.size(); i++) {
  4527. if (i == 3) {
  4528. rpc_config["channel"] = p_annotation->resolved_arguments[i].operator int();
  4529. continue;
  4530. }
  4531. String arg = p_annotation->resolved_arguments[i].operator String();
  4532. if (arg == "call_local") {
  4533. locality_args++;
  4534. rpc_config["call_local"] = true;
  4535. } else if (arg == "call_remote") {
  4536. locality_args++;
  4537. rpc_config["call_local"] = false;
  4538. } else if (arg == "any_peer") {
  4539. permission_args++;
  4540. rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_ANY_PEER;
  4541. } else if (arg == "authority") {
  4542. permission_args++;
  4543. rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_AUTHORITY;
  4544. } else if (arg == "reliable") {
  4545. transfer_mode_args++;
  4546. rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_RELIABLE;
  4547. } else if (arg == "unreliable") {
  4548. transfer_mode_args++;
  4549. rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_UNRELIABLE;
  4550. } else if (arg == "unreliable_ordered") {
  4551. transfer_mode_args++;
  4552. rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_UNRELIABLE_ORDERED;
  4553. } else {
  4554. push_error(R"(Invalid RPC argument. Must be one of: "call_local"/"call_remote" (local calls), "any_peer"/"authority" (permission), "reliable"/"unreliable"/"unreliable_ordered" (transfer mode).)", p_annotation);
  4555. }
  4556. }
  4557. if (locality_args > 1) {
  4558. push_error(R"(Invalid RPC config. The locality ("call_local"/"call_remote") must be specified no more than once.)", p_annotation);
  4559. } else if (permission_args > 1) {
  4560. push_error(R"(Invalid RPC config. The permission ("any_peer"/"authority") must be specified no more than once.)", p_annotation);
  4561. } else if (transfer_mode_args > 1) {
  4562. push_error(R"(Invalid RPC config. The transfer mode ("reliable"/"unreliable"/"unreliable_ordered") must be specified no more than once.)", p_annotation);
  4563. }
  4564. }
  4565. function->rpc_config = rpc_config;
  4566. return true;
  4567. }
  4568. GDScriptParser::DataType GDScriptParser::SuiteNode::Local::get_datatype() const {
  4569. switch (type) {
  4570. case CONSTANT:
  4571. return constant->get_datatype();
  4572. case VARIABLE:
  4573. return variable->get_datatype();
  4574. case PARAMETER:
  4575. return parameter->get_datatype();
  4576. case FOR_VARIABLE:
  4577. case PATTERN_BIND:
  4578. return bind->get_datatype();
  4579. case UNDEFINED:
  4580. return DataType();
  4581. }
  4582. return DataType();
  4583. }
  4584. String GDScriptParser::SuiteNode::Local::get_name() const {
  4585. switch (type) {
  4586. case SuiteNode::Local::PARAMETER:
  4587. return "parameter";
  4588. case SuiteNode::Local::CONSTANT:
  4589. return "constant";
  4590. case SuiteNode::Local::VARIABLE:
  4591. return "variable";
  4592. case SuiteNode::Local::FOR_VARIABLE:
  4593. return "for loop iterator";
  4594. case SuiteNode::Local::PATTERN_BIND:
  4595. return "pattern bind";
  4596. case SuiteNode::Local::UNDEFINED:
  4597. return "<undefined>";
  4598. default:
  4599. return String();
  4600. }
  4601. }
  4602. String GDScriptParser::DataType::to_string() const {
  4603. switch (kind) {
  4604. case VARIANT:
  4605. return "Variant";
  4606. case BUILTIN:
  4607. if (builtin_type == Variant::NIL) {
  4608. return "null";
  4609. }
  4610. if (builtin_type == Variant::ARRAY && has_container_element_type(0)) {
  4611. return vformat("Array[%s]", get_container_element_type(0).to_string());
  4612. }
  4613. if (builtin_type == Variant::DICTIONARY && has_container_element_types()) {
  4614. return vformat("Dictionary[%s, %s]", get_container_element_type_or_variant(0).to_string(), get_container_element_type_or_variant(1).to_string());
  4615. }
  4616. return Variant::get_type_name(builtin_type);
  4617. case NATIVE:
  4618. if (is_meta_type) {
  4619. return GDScriptNativeClass::get_class_static();
  4620. }
  4621. return native_type.operator String();
  4622. case CLASS:
  4623. if (class_type->identifier != nullptr) {
  4624. return class_type->identifier->name.operator String();
  4625. }
  4626. return class_type->fqcn;
  4627. case SCRIPT: {
  4628. if (is_meta_type) {
  4629. return script_type.is_valid() ? script_type->get_class_name().operator String() : "";
  4630. }
  4631. String name = script_type.is_valid() ? script_type->get_name() : "";
  4632. if (!name.is_empty()) {
  4633. return name;
  4634. }
  4635. name = script_path;
  4636. if (!name.is_empty()) {
  4637. return name;
  4638. }
  4639. return native_type.operator String();
  4640. }
  4641. case ENUM: {
  4642. // native_type contains either the native class defining the enum
  4643. // or the fully qualified class name of the script defining the enum
  4644. return String(native_type).get_file(); // Remove path, keep filename
  4645. }
  4646. case RESOLVING:
  4647. case UNRESOLVED:
  4648. return "<unresolved type>";
  4649. }
  4650. ERR_FAIL_V_MSG("<unresolved type>", "Kind set outside the enum range.");
  4651. }
  4652. PropertyInfo GDScriptParser::DataType::to_property_info(const String &p_name) const {
  4653. PropertyInfo result;
  4654. result.name = p_name;
  4655. result.usage = PROPERTY_USAGE_NONE;
  4656. if (!is_hard_type()) {
  4657. result.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  4658. return result;
  4659. }
  4660. switch (kind) {
  4661. case BUILTIN:
  4662. result.type = builtin_type;
  4663. if (builtin_type == Variant::ARRAY && has_container_element_type(0)) {
  4664. const DataType elem_type = get_container_element_type(0);
  4665. switch (elem_type.kind) {
  4666. case BUILTIN:
  4667. result.hint = PROPERTY_HINT_ARRAY_TYPE;
  4668. result.hint_string = Variant::get_type_name(elem_type.builtin_type);
  4669. break;
  4670. case NATIVE:
  4671. result.hint = PROPERTY_HINT_ARRAY_TYPE;
  4672. result.hint_string = elem_type.native_type;
  4673. break;
  4674. case SCRIPT:
  4675. result.hint = PROPERTY_HINT_ARRAY_TYPE;
  4676. if (elem_type.script_type.is_valid() && elem_type.script_type->get_global_name() != StringName()) {
  4677. result.hint_string = elem_type.script_type->get_global_name();
  4678. } else {
  4679. result.hint_string = elem_type.native_type;
  4680. }
  4681. break;
  4682. case CLASS:
  4683. result.hint = PROPERTY_HINT_ARRAY_TYPE;
  4684. if (elem_type.class_type != nullptr && elem_type.class_type->get_global_name() != StringName()) {
  4685. result.hint_string = elem_type.class_type->get_global_name();
  4686. } else {
  4687. result.hint_string = elem_type.native_type;
  4688. }
  4689. break;
  4690. case ENUM:
  4691. result.hint = PROPERTY_HINT_ARRAY_TYPE;
  4692. result.hint_string = String(elem_type.native_type).replace("::", ".");
  4693. break;
  4694. case VARIANT:
  4695. case RESOLVING:
  4696. case UNRESOLVED:
  4697. break;
  4698. }
  4699. } else if (builtin_type == Variant::DICTIONARY && has_container_element_types()) {
  4700. const DataType key_type = get_container_element_type_or_variant(0);
  4701. const DataType value_type = get_container_element_type_or_variant(1);
  4702. if ((key_type.kind == VARIANT && value_type.kind == VARIANT) || key_type.kind == RESOLVING ||
  4703. key_type.kind == UNRESOLVED || value_type.kind == RESOLVING || value_type.kind == UNRESOLVED) {
  4704. break;
  4705. }
  4706. String key_hint, value_hint;
  4707. switch (key_type.kind) {
  4708. case BUILTIN:
  4709. key_hint = Variant::get_type_name(key_type.builtin_type);
  4710. break;
  4711. case NATIVE:
  4712. key_hint = key_type.native_type;
  4713. break;
  4714. case SCRIPT:
  4715. if (key_type.script_type.is_valid() && key_type.script_type->get_global_name() != StringName()) {
  4716. key_hint = key_type.script_type->get_global_name();
  4717. } else {
  4718. key_hint = key_type.native_type;
  4719. }
  4720. break;
  4721. case CLASS:
  4722. if (key_type.class_type != nullptr && key_type.class_type->get_global_name() != StringName()) {
  4723. key_hint = key_type.class_type->get_global_name();
  4724. } else {
  4725. key_hint = key_type.native_type;
  4726. }
  4727. break;
  4728. case ENUM:
  4729. key_hint = String(key_type.native_type).replace("::", ".");
  4730. break;
  4731. default:
  4732. key_hint = "Variant";
  4733. break;
  4734. }
  4735. switch (value_type.kind) {
  4736. case BUILTIN:
  4737. value_hint = Variant::get_type_name(value_type.builtin_type);
  4738. break;
  4739. case NATIVE:
  4740. value_hint = value_type.native_type;
  4741. break;
  4742. case SCRIPT:
  4743. if (value_type.script_type.is_valid() && value_type.script_type->get_global_name() != StringName()) {
  4744. value_hint = value_type.script_type->get_global_name();
  4745. } else {
  4746. value_hint = value_type.native_type;
  4747. }
  4748. break;
  4749. case CLASS:
  4750. if (value_type.class_type != nullptr && value_type.class_type->get_global_name() != StringName()) {
  4751. value_hint = value_type.class_type->get_global_name();
  4752. } else {
  4753. value_hint = value_type.native_type;
  4754. }
  4755. break;
  4756. case ENUM:
  4757. value_hint = String(value_type.native_type).replace("::", ".");
  4758. break;
  4759. default:
  4760. value_hint = "Variant";
  4761. break;
  4762. }
  4763. result.hint = PROPERTY_HINT_DICTIONARY_TYPE;
  4764. result.hint_string = key_hint + ";" + value_hint;
  4765. }
  4766. break;
  4767. case NATIVE:
  4768. result.type = Variant::OBJECT;
  4769. if (is_meta_type) {
  4770. result.class_name = GDScriptNativeClass::get_class_static();
  4771. } else {
  4772. result.class_name = native_type;
  4773. }
  4774. break;
  4775. case SCRIPT:
  4776. result.type = Variant::OBJECT;
  4777. if (is_meta_type) {
  4778. result.class_name = script_type.is_valid() ? script_type->get_class_name() : Script::get_class_static();
  4779. } else if (script_type.is_valid() && script_type->get_global_name() != StringName()) {
  4780. result.class_name = script_type->get_global_name();
  4781. } else {
  4782. result.class_name = native_type;
  4783. }
  4784. break;
  4785. case CLASS:
  4786. result.type = Variant::OBJECT;
  4787. if (is_meta_type) {
  4788. result.class_name = GDScript::get_class_static();
  4789. } else if (class_type != nullptr && class_type->get_global_name() != StringName()) {
  4790. result.class_name = class_type->get_global_name();
  4791. } else {
  4792. result.class_name = native_type;
  4793. }
  4794. break;
  4795. case ENUM:
  4796. if (is_meta_type) {
  4797. result.type = Variant::DICTIONARY;
  4798. } else {
  4799. result.type = Variant::INT;
  4800. result.usage |= PROPERTY_USAGE_CLASS_IS_ENUM;
  4801. result.class_name = String(native_type).replace("::", ".");
  4802. }
  4803. break;
  4804. case VARIANT:
  4805. case RESOLVING:
  4806. case UNRESOLVED:
  4807. result.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  4808. break;
  4809. }
  4810. return result;
  4811. }
  4812. static Variant::Type _variant_type_to_typed_array_element_type(Variant::Type p_type) {
  4813. switch (p_type) {
  4814. case Variant::PACKED_BYTE_ARRAY:
  4815. case Variant::PACKED_INT32_ARRAY:
  4816. case Variant::PACKED_INT64_ARRAY:
  4817. return Variant::INT;
  4818. case Variant::PACKED_FLOAT32_ARRAY:
  4819. case Variant::PACKED_FLOAT64_ARRAY:
  4820. return Variant::FLOAT;
  4821. case Variant::PACKED_STRING_ARRAY:
  4822. return Variant::STRING;
  4823. case Variant::PACKED_VECTOR2_ARRAY:
  4824. return Variant::VECTOR2;
  4825. case Variant::PACKED_VECTOR3_ARRAY:
  4826. return Variant::VECTOR3;
  4827. case Variant::PACKED_COLOR_ARRAY:
  4828. return Variant::COLOR;
  4829. case Variant::PACKED_VECTOR4_ARRAY:
  4830. return Variant::VECTOR4;
  4831. default:
  4832. return Variant::NIL;
  4833. }
  4834. }
  4835. bool GDScriptParser::DataType::is_typed_container_type() const {
  4836. return kind == GDScriptParser::DataType::BUILTIN && _variant_type_to_typed_array_element_type(builtin_type) != Variant::NIL;
  4837. }
  4838. GDScriptParser::DataType GDScriptParser::DataType::get_typed_container_type() const {
  4839. GDScriptParser::DataType type;
  4840. type.kind = GDScriptParser::DataType::BUILTIN;
  4841. type.builtin_type = _variant_type_to_typed_array_element_type(builtin_type);
  4842. return type;
  4843. }
  4844. bool GDScriptParser::DataType::can_reference(const GDScriptParser::DataType &p_other) const {
  4845. if (p_other.is_meta_type) {
  4846. return false;
  4847. } else if (builtin_type != p_other.builtin_type) {
  4848. return false;
  4849. } else if (builtin_type != Variant::OBJECT) {
  4850. return true;
  4851. }
  4852. if (native_type == StringName()) {
  4853. return true;
  4854. } else if (p_other.native_type == StringName()) {
  4855. return false;
  4856. } else if (native_type != p_other.native_type && !ClassDB::is_parent_class(p_other.native_type, native_type)) {
  4857. return false;
  4858. }
  4859. Ref<Script> script = script_type;
  4860. if (kind == GDScriptParser::DataType::CLASS && script.is_null()) {
  4861. Error err = OK;
  4862. Ref<GDScript> scr = GDScriptCache::get_shallow_script(script_path, err);
  4863. ERR_FAIL_COND_V_MSG(err, false, vformat(R"(Error while getting cache for script "%s".)", script_path));
  4864. script.reference_ptr(scr->find_class(class_type->fqcn));
  4865. }
  4866. Ref<Script> script_other = p_other.script_type;
  4867. if (p_other.kind == GDScriptParser::DataType::CLASS && script_other.is_null()) {
  4868. Error err = OK;
  4869. Ref<GDScript> scr = GDScriptCache::get_shallow_script(p_other.script_path, err);
  4870. ERR_FAIL_COND_V_MSG(err, false, vformat(R"(Error while getting cache for script "%s".)", p_other.script_path));
  4871. script_other.reference_ptr(scr->find_class(p_other.class_type->fqcn));
  4872. }
  4873. if (script.is_null()) {
  4874. return true;
  4875. } else if (script_other.is_null()) {
  4876. return false;
  4877. } else if (script != script_other && !script_other->inherits_script(script)) {
  4878. return false;
  4879. }
  4880. return true;
  4881. }
  4882. void GDScriptParser::complete_extents(Node *p_node) {
  4883. while (!nodes_in_progress.is_empty() && nodes_in_progress.back()->get() != p_node) {
  4884. ERR_PRINT("Parser bug: Mismatch in extents tracking stack.");
  4885. nodes_in_progress.pop_back();
  4886. }
  4887. if (nodes_in_progress.is_empty()) {
  4888. ERR_PRINT("Parser bug: Extents tracking stack is empty.");
  4889. } else {
  4890. nodes_in_progress.pop_back();
  4891. }
  4892. }
  4893. void GDScriptParser::update_extents(Node *p_node) {
  4894. p_node->end_line = previous.end_line;
  4895. p_node->end_column = previous.end_column;
  4896. }
  4897. void GDScriptParser::reset_extents(Node *p_node, GDScriptTokenizer::Token p_token) {
  4898. p_node->start_line = p_token.start_line;
  4899. p_node->end_line = p_token.end_line;
  4900. p_node->start_column = p_token.start_column;
  4901. p_node->end_column = p_token.end_column;
  4902. }
  4903. void GDScriptParser::reset_extents(Node *p_node, Node *p_from) {
  4904. if (p_from == nullptr) {
  4905. return;
  4906. }
  4907. p_node->start_line = p_from->start_line;
  4908. p_node->end_line = p_from->end_line;
  4909. p_node->start_column = p_from->start_column;
  4910. p_node->end_column = p_from->end_column;
  4911. }
  4912. /*---------- PRETTY PRINT FOR DEBUG ----------*/
  4913. #ifdef DEBUG_ENABLED
  4914. void GDScriptParser::TreePrinter::increase_indent() {
  4915. indent_level++;
  4916. indent = "";
  4917. for (int i = 0; i < indent_level * 4; i++) {
  4918. if (i % 4 == 0) {
  4919. indent += "|";
  4920. } else {
  4921. indent += " ";
  4922. }
  4923. }
  4924. }
  4925. void GDScriptParser::TreePrinter::decrease_indent() {
  4926. indent_level--;
  4927. indent = "";
  4928. for (int i = 0; i < indent_level * 4; i++) {
  4929. if (i % 4 == 0) {
  4930. indent += "|";
  4931. } else {
  4932. indent += " ";
  4933. }
  4934. }
  4935. }
  4936. void GDScriptParser::TreePrinter::push_line(const String &p_line) {
  4937. if (!p_line.is_empty()) {
  4938. push_text(p_line);
  4939. }
  4940. printed += "\n";
  4941. pending_indent = true;
  4942. }
  4943. void GDScriptParser::TreePrinter::push_text(const String &p_text) {
  4944. if (pending_indent) {
  4945. printed += indent;
  4946. pending_indent = false;
  4947. }
  4948. printed += p_text;
  4949. }
  4950. void GDScriptParser::TreePrinter::print_annotation(const AnnotationNode *p_annotation) {
  4951. push_text(p_annotation->name);
  4952. push_text(" (");
  4953. for (int i = 0; i < p_annotation->arguments.size(); i++) {
  4954. if (i > 0) {
  4955. push_text(" , ");
  4956. }
  4957. print_expression(p_annotation->arguments[i]);
  4958. }
  4959. push_line(")");
  4960. }
  4961. void GDScriptParser::TreePrinter::print_array(ArrayNode *p_array) {
  4962. push_text("[ ");
  4963. for (int i = 0; i < p_array->elements.size(); i++) {
  4964. if (i > 0) {
  4965. push_text(" , ");
  4966. }
  4967. print_expression(p_array->elements[i]);
  4968. }
  4969. push_text(" ]");
  4970. }
  4971. void GDScriptParser::TreePrinter::print_assert(AssertNode *p_assert) {
  4972. push_text("Assert ( ");
  4973. print_expression(p_assert->condition);
  4974. push_line(" )");
  4975. }
  4976. void GDScriptParser::TreePrinter::print_assignment(AssignmentNode *p_assignment) {
  4977. switch (p_assignment->assignee->type) {
  4978. case Node::IDENTIFIER:
  4979. print_identifier(static_cast<IdentifierNode *>(p_assignment->assignee));
  4980. break;
  4981. case Node::SUBSCRIPT:
  4982. print_subscript(static_cast<SubscriptNode *>(p_assignment->assignee));
  4983. break;
  4984. default:
  4985. break; // Unreachable.
  4986. }
  4987. push_text(" ");
  4988. switch (p_assignment->operation) {
  4989. case AssignmentNode::OP_ADDITION:
  4990. push_text("+");
  4991. break;
  4992. case AssignmentNode::OP_SUBTRACTION:
  4993. push_text("-");
  4994. break;
  4995. case AssignmentNode::OP_MULTIPLICATION:
  4996. push_text("*");
  4997. break;
  4998. case AssignmentNode::OP_DIVISION:
  4999. push_text("/");
  5000. break;
  5001. case AssignmentNode::OP_MODULO:
  5002. push_text("%");
  5003. break;
  5004. case AssignmentNode::OP_POWER:
  5005. push_text("**");
  5006. break;
  5007. case AssignmentNode::OP_BIT_SHIFT_LEFT:
  5008. push_text("<<");
  5009. break;
  5010. case AssignmentNode::OP_BIT_SHIFT_RIGHT:
  5011. push_text(">>");
  5012. break;
  5013. case AssignmentNode::OP_BIT_AND:
  5014. push_text("&");
  5015. break;
  5016. case AssignmentNode::OP_BIT_OR:
  5017. push_text("|");
  5018. break;
  5019. case AssignmentNode::OP_BIT_XOR:
  5020. push_text("^");
  5021. break;
  5022. case AssignmentNode::OP_NONE:
  5023. break;
  5024. }
  5025. push_text("= ");
  5026. print_expression(p_assignment->assigned_value);
  5027. push_line();
  5028. }
  5029. void GDScriptParser::TreePrinter::print_await(AwaitNode *p_await) {
  5030. push_text("Await ");
  5031. print_expression(p_await->to_await);
  5032. }
  5033. void GDScriptParser::TreePrinter::print_binary_op(BinaryOpNode *p_binary_op) {
  5034. // Surround in parenthesis for disambiguation.
  5035. push_text("(");
  5036. print_expression(p_binary_op->left_operand);
  5037. switch (p_binary_op->operation) {
  5038. case BinaryOpNode::OP_ADDITION:
  5039. push_text(" + ");
  5040. break;
  5041. case BinaryOpNode::OP_SUBTRACTION:
  5042. push_text(" - ");
  5043. break;
  5044. case BinaryOpNode::OP_MULTIPLICATION:
  5045. push_text(" * ");
  5046. break;
  5047. case BinaryOpNode::OP_DIVISION:
  5048. push_text(" / ");
  5049. break;
  5050. case BinaryOpNode::OP_MODULO:
  5051. push_text(" % ");
  5052. break;
  5053. case BinaryOpNode::OP_POWER:
  5054. push_text(" ** ");
  5055. break;
  5056. case BinaryOpNode::OP_BIT_LEFT_SHIFT:
  5057. push_text(" << ");
  5058. break;
  5059. case BinaryOpNode::OP_BIT_RIGHT_SHIFT:
  5060. push_text(" >> ");
  5061. break;
  5062. case BinaryOpNode::OP_BIT_AND:
  5063. push_text(" & ");
  5064. break;
  5065. case BinaryOpNode::OP_BIT_OR:
  5066. push_text(" | ");
  5067. break;
  5068. case BinaryOpNode::OP_BIT_XOR:
  5069. push_text(" ^ ");
  5070. break;
  5071. case BinaryOpNode::OP_LOGIC_AND:
  5072. push_text(" AND ");
  5073. break;
  5074. case BinaryOpNode::OP_LOGIC_OR:
  5075. push_text(" OR ");
  5076. break;
  5077. case BinaryOpNode::OP_CONTENT_TEST:
  5078. push_text(" IN ");
  5079. break;
  5080. case BinaryOpNode::OP_COMP_EQUAL:
  5081. push_text(" == ");
  5082. break;
  5083. case BinaryOpNode::OP_COMP_NOT_EQUAL:
  5084. push_text(" != ");
  5085. break;
  5086. case BinaryOpNode::OP_COMP_LESS:
  5087. push_text(" < ");
  5088. break;
  5089. case BinaryOpNode::OP_COMP_LESS_EQUAL:
  5090. push_text(" <= ");
  5091. break;
  5092. case BinaryOpNode::OP_COMP_GREATER:
  5093. push_text(" > ");
  5094. break;
  5095. case BinaryOpNode::OP_COMP_GREATER_EQUAL:
  5096. push_text(" >= ");
  5097. break;
  5098. }
  5099. print_expression(p_binary_op->right_operand);
  5100. // Surround in parenthesis for disambiguation.
  5101. push_text(")");
  5102. }
  5103. void GDScriptParser::TreePrinter::print_call(CallNode *p_call) {
  5104. if (p_call->is_super) {
  5105. push_text("super");
  5106. if (p_call->callee != nullptr) {
  5107. push_text(".");
  5108. print_expression(p_call->callee);
  5109. }
  5110. } else {
  5111. print_expression(p_call->callee);
  5112. }
  5113. push_text("( ");
  5114. for (int i = 0; i < p_call->arguments.size(); i++) {
  5115. if (i > 0) {
  5116. push_text(" , ");
  5117. }
  5118. print_expression(p_call->arguments[i]);
  5119. }
  5120. push_text(" )");
  5121. }
  5122. void GDScriptParser::TreePrinter::print_cast(CastNode *p_cast) {
  5123. print_expression(p_cast->operand);
  5124. push_text(" AS ");
  5125. print_type(p_cast->cast_type);
  5126. }
  5127. void GDScriptParser::TreePrinter::print_class(ClassNode *p_class) {
  5128. for (const AnnotationNode *E : p_class->annotations) {
  5129. print_annotation(E);
  5130. }
  5131. push_text("Class ");
  5132. if (p_class->identifier == nullptr) {
  5133. push_text("<unnamed>");
  5134. } else {
  5135. print_identifier(p_class->identifier);
  5136. }
  5137. if (p_class->extends_used) {
  5138. bool first = true;
  5139. push_text(" Extends ");
  5140. if (!p_class->extends_path.is_empty()) {
  5141. push_text(vformat(R"("%s")", p_class->extends_path));
  5142. first = false;
  5143. }
  5144. for (int i = 0; i < p_class->extends.size(); i++) {
  5145. if (!first) {
  5146. push_text(".");
  5147. } else {
  5148. first = false;
  5149. }
  5150. push_text(p_class->extends[i]->name);
  5151. }
  5152. }
  5153. push_line(" :");
  5154. increase_indent();
  5155. for (int i = 0; i < p_class->members.size(); i++) {
  5156. const ClassNode::Member &m = p_class->members[i];
  5157. switch (m.type) {
  5158. case ClassNode::Member::CLASS:
  5159. print_class(m.m_class);
  5160. break;
  5161. case ClassNode::Member::VARIABLE:
  5162. print_variable(m.variable);
  5163. break;
  5164. case ClassNode::Member::CONSTANT:
  5165. print_constant(m.constant);
  5166. break;
  5167. case ClassNode::Member::SIGNAL:
  5168. print_signal(m.signal);
  5169. break;
  5170. case ClassNode::Member::FUNCTION:
  5171. print_function(m.function);
  5172. break;
  5173. case ClassNode::Member::ENUM:
  5174. print_enum(m.m_enum);
  5175. break;
  5176. case ClassNode::Member::ENUM_VALUE:
  5177. break; // Nothing. Will be printed by enum.
  5178. case ClassNode::Member::GROUP:
  5179. break; // Nothing. Groups are only used by inspector.
  5180. case ClassNode::Member::UNDEFINED:
  5181. push_line("<unknown member>");
  5182. break;
  5183. }
  5184. }
  5185. decrease_indent();
  5186. }
  5187. void GDScriptParser::TreePrinter::print_constant(ConstantNode *p_constant) {
  5188. push_text("Constant ");
  5189. print_identifier(p_constant->identifier);
  5190. increase_indent();
  5191. push_line();
  5192. push_text("= ");
  5193. if (p_constant->initializer == nullptr) {
  5194. push_text("<missing value>");
  5195. } else {
  5196. print_expression(p_constant->initializer);
  5197. }
  5198. decrease_indent();
  5199. push_line();
  5200. }
  5201. void GDScriptParser::TreePrinter::print_dictionary(DictionaryNode *p_dictionary) {
  5202. push_line("{");
  5203. increase_indent();
  5204. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  5205. print_expression(p_dictionary->elements[i].key);
  5206. if (p_dictionary->style == DictionaryNode::PYTHON_DICT) {
  5207. push_text(" : ");
  5208. } else {
  5209. push_text(" = ");
  5210. }
  5211. print_expression(p_dictionary->elements[i].value);
  5212. push_line(" ,");
  5213. }
  5214. decrease_indent();
  5215. push_text("}");
  5216. }
  5217. void GDScriptParser::TreePrinter::print_expression(ExpressionNode *p_expression) {
  5218. if (p_expression == nullptr) {
  5219. push_text("<invalid expression>");
  5220. return;
  5221. }
  5222. switch (p_expression->type) {
  5223. case Node::ARRAY:
  5224. print_array(static_cast<ArrayNode *>(p_expression));
  5225. break;
  5226. case Node::ASSIGNMENT:
  5227. print_assignment(static_cast<AssignmentNode *>(p_expression));
  5228. break;
  5229. case Node::AWAIT:
  5230. print_await(static_cast<AwaitNode *>(p_expression));
  5231. break;
  5232. case Node::BINARY_OPERATOR:
  5233. print_binary_op(static_cast<BinaryOpNode *>(p_expression));
  5234. break;
  5235. case Node::CALL:
  5236. print_call(static_cast<CallNode *>(p_expression));
  5237. break;
  5238. case Node::CAST:
  5239. print_cast(static_cast<CastNode *>(p_expression));
  5240. break;
  5241. case Node::DICTIONARY:
  5242. print_dictionary(static_cast<DictionaryNode *>(p_expression));
  5243. break;
  5244. case Node::GET_NODE:
  5245. print_get_node(static_cast<GetNodeNode *>(p_expression));
  5246. break;
  5247. case Node::IDENTIFIER:
  5248. print_identifier(static_cast<IdentifierNode *>(p_expression));
  5249. break;
  5250. case Node::LAMBDA:
  5251. print_lambda(static_cast<LambdaNode *>(p_expression));
  5252. break;
  5253. case Node::LITERAL:
  5254. print_literal(static_cast<LiteralNode *>(p_expression));
  5255. break;
  5256. case Node::PRELOAD:
  5257. print_preload(static_cast<PreloadNode *>(p_expression));
  5258. break;
  5259. case Node::SELF:
  5260. print_self(static_cast<SelfNode *>(p_expression));
  5261. break;
  5262. case Node::SUBSCRIPT:
  5263. print_subscript(static_cast<SubscriptNode *>(p_expression));
  5264. break;
  5265. case Node::TERNARY_OPERATOR:
  5266. print_ternary_op(static_cast<TernaryOpNode *>(p_expression));
  5267. break;
  5268. case Node::TYPE_TEST:
  5269. print_type_test(static_cast<TypeTestNode *>(p_expression));
  5270. break;
  5271. case Node::UNARY_OPERATOR:
  5272. print_unary_op(static_cast<UnaryOpNode *>(p_expression));
  5273. break;
  5274. default:
  5275. push_text(vformat("<unknown expression %d>", p_expression->type));
  5276. break;
  5277. }
  5278. }
  5279. void GDScriptParser::TreePrinter::print_enum(EnumNode *p_enum) {
  5280. push_text("Enum ");
  5281. if (p_enum->identifier != nullptr) {
  5282. print_identifier(p_enum->identifier);
  5283. } else {
  5284. push_text("<unnamed>");
  5285. }
  5286. push_line(" {");
  5287. increase_indent();
  5288. for (int i = 0; i < p_enum->values.size(); i++) {
  5289. const EnumNode::Value &item = p_enum->values[i];
  5290. print_identifier(item.identifier);
  5291. push_text(" = ");
  5292. push_text(itos(item.value));
  5293. push_line(" ,");
  5294. }
  5295. decrease_indent();
  5296. push_line("}");
  5297. }
  5298. void GDScriptParser::TreePrinter::print_for(ForNode *p_for) {
  5299. push_text("For ");
  5300. print_identifier(p_for->variable);
  5301. push_text(" IN ");
  5302. print_expression(p_for->list);
  5303. push_line(" :");
  5304. increase_indent();
  5305. print_suite(p_for->loop);
  5306. decrease_indent();
  5307. }
  5308. void GDScriptParser::TreePrinter::print_function(FunctionNode *p_function, const String &p_context) {
  5309. for (const AnnotationNode *E : p_function->annotations) {
  5310. print_annotation(E);
  5311. }
  5312. if (p_function->is_static) {
  5313. push_text("Static ");
  5314. }
  5315. push_text(p_context);
  5316. push_text(" ");
  5317. if (p_function->identifier) {
  5318. print_identifier(p_function->identifier);
  5319. } else {
  5320. push_text("<anonymous>");
  5321. }
  5322. push_text("( ");
  5323. for (int i = 0; i < p_function->parameters.size(); i++) {
  5324. if (i > 0) {
  5325. push_text(" , ");
  5326. }
  5327. print_parameter(p_function->parameters[i]);
  5328. }
  5329. push_line(" ) :");
  5330. increase_indent();
  5331. print_suite(p_function->body);
  5332. decrease_indent();
  5333. }
  5334. void GDScriptParser::TreePrinter::print_get_node(GetNodeNode *p_get_node) {
  5335. if (p_get_node->use_dollar) {
  5336. push_text("$");
  5337. }
  5338. push_text(p_get_node->full_path);
  5339. }
  5340. void GDScriptParser::TreePrinter::print_identifier(IdentifierNode *p_identifier) {
  5341. if (p_identifier != nullptr) {
  5342. push_text(p_identifier->name);
  5343. } else {
  5344. push_text("<invalid identifier>");
  5345. }
  5346. }
  5347. void GDScriptParser::TreePrinter::print_if(IfNode *p_if, bool p_is_elif) {
  5348. if (p_is_elif) {
  5349. push_text("Elif ");
  5350. } else {
  5351. push_text("If ");
  5352. }
  5353. print_expression(p_if->condition);
  5354. push_line(" :");
  5355. increase_indent();
  5356. print_suite(p_if->true_block);
  5357. decrease_indent();
  5358. // FIXME: Properly detect "elif" blocks.
  5359. if (p_if->false_block != nullptr) {
  5360. push_line("Else :");
  5361. increase_indent();
  5362. print_suite(p_if->false_block);
  5363. decrease_indent();
  5364. }
  5365. }
  5366. void GDScriptParser::TreePrinter::print_lambda(LambdaNode *p_lambda) {
  5367. print_function(p_lambda->function, "Lambda");
  5368. push_text("| captures [ ");
  5369. for (int i = 0; i < p_lambda->captures.size(); i++) {
  5370. if (i > 0) {
  5371. push_text(" , ");
  5372. }
  5373. push_text(p_lambda->captures[i]->name.operator String());
  5374. }
  5375. push_line(" ]");
  5376. }
  5377. void GDScriptParser::TreePrinter::print_literal(LiteralNode *p_literal) {
  5378. // Prefix for string types.
  5379. switch (p_literal->value.get_type()) {
  5380. case Variant::NODE_PATH:
  5381. push_text("^\"");
  5382. break;
  5383. case Variant::STRING:
  5384. push_text("\"");
  5385. break;
  5386. case Variant::STRING_NAME:
  5387. push_text("&\"");
  5388. break;
  5389. default:
  5390. break;
  5391. }
  5392. push_text(p_literal->value);
  5393. // Suffix for string types.
  5394. switch (p_literal->value.get_type()) {
  5395. case Variant::NODE_PATH:
  5396. case Variant::STRING:
  5397. case Variant::STRING_NAME:
  5398. push_text("\"");
  5399. break;
  5400. default:
  5401. break;
  5402. }
  5403. }
  5404. void GDScriptParser::TreePrinter::print_match(MatchNode *p_match) {
  5405. push_text("Match ");
  5406. print_expression(p_match->test);
  5407. push_line(" :");
  5408. increase_indent();
  5409. for (int i = 0; i < p_match->branches.size(); i++) {
  5410. print_match_branch(p_match->branches[i]);
  5411. }
  5412. decrease_indent();
  5413. }
  5414. void GDScriptParser::TreePrinter::print_match_branch(MatchBranchNode *p_match_branch) {
  5415. for (int i = 0; i < p_match_branch->patterns.size(); i++) {
  5416. if (i > 0) {
  5417. push_text(" , ");
  5418. }
  5419. print_match_pattern(p_match_branch->patterns[i]);
  5420. }
  5421. push_line(" :");
  5422. increase_indent();
  5423. print_suite(p_match_branch->block);
  5424. decrease_indent();
  5425. }
  5426. void GDScriptParser::TreePrinter::print_match_pattern(PatternNode *p_match_pattern) {
  5427. switch (p_match_pattern->pattern_type) {
  5428. case PatternNode::PT_LITERAL:
  5429. print_literal(p_match_pattern->literal);
  5430. break;
  5431. case PatternNode::PT_WILDCARD:
  5432. push_text("_");
  5433. break;
  5434. case PatternNode::PT_REST:
  5435. push_text("..");
  5436. break;
  5437. case PatternNode::PT_BIND:
  5438. push_text("Var ");
  5439. print_identifier(p_match_pattern->bind);
  5440. break;
  5441. case PatternNode::PT_EXPRESSION:
  5442. print_expression(p_match_pattern->expression);
  5443. break;
  5444. case PatternNode::PT_ARRAY:
  5445. push_text("[ ");
  5446. for (int i = 0; i < p_match_pattern->array.size(); i++) {
  5447. if (i > 0) {
  5448. push_text(" , ");
  5449. }
  5450. print_match_pattern(p_match_pattern->array[i]);
  5451. }
  5452. push_text(" ]");
  5453. break;
  5454. case PatternNode::PT_DICTIONARY:
  5455. push_text("{ ");
  5456. for (int i = 0; i < p_match_pattern->dictionary.size(); i++) {
  5457. if (i > 0) {
  5458. push_text(" , ");
  5459. }
  5460. if (p_match_pattern->dictionary[i].key != nullptr) {
  5461. // Key can be null for rest pattern.
  5462. print_expression(p_match_pattern->dictionary[i].key);
  5463. push_text(" : ");
  5464. }
  5465. print_match_pattern(p_match_pattern->dictionary[i].value_pattern);
  5466. }
  5467. push_text(" }");
  5468. break;
  5469. }
  5470. }
  5471. void GDScriptParser::TreePrinter::print_parameter(ParameterNode *p_parameter) {
  5472. print_identifier(p_parameter->identifier);
  5473. if (p_parameter->datatype_specifier != nullptr) {
  5474. push_text(" : ");
  5475. print_type(p_parameter->datatype_specifier);
  5476. }
  5477. if (p_parameter->initializer != nullptr) {
  5478. push_text(" = ");
  5479. print_expression(p_parameter->initializer);
  5480. }
  5481. }
  5482. void GDScriptParser::TreePrinter::print_preload(PreloadNode *p_preload) {
  5483. push_text(R"(Preload ( ")");
  5484. push_text(p_preload->resolved_path);
  5485. push_text(R"(" )");
  5486. }
  5487. void GDScriptParser::TreePrinter::print_return(ReturnNode *p_return) {
  5488. push_text("Return");
  5489. if (p_return->return_value != nullptr) {
  5490. push_text(" ");
  5491. print_expression(p_return->return_value);
  5492. }
  5493. push_line();
  5494. }
  5495. void GDScriptParser::TreePrinter::print_self(SelfNode *p_self) {
  5496. push_text("Self(");
  5497. if (p_self->current_class->identifier != nullptr) {
  5498. print_identifier(p_self->current_class->identifier);
  5499. } else {
  5500. push_text("<main class>");
  5501. }
  5502. push_text(")");
  5503. }
  5504. void GDScriptParser::TreePrinter::print_signal(SignalNode *p_signal) {
  5505. push_text("Signal ");
  5506. print_identifier(p_signal->identifier);
  5507. push_text("( ");
  5508. for (int i = 0; i < p_signal->parameters.size(); i++) {
  5509. print_parameter(p_signal->parameters[i]);
  5510. }
  5511. push_line(" )");
  5512. }
  5513. void GDScriptParser::TreePrinter::print_subscript(SubscriptNode *p_subscript) {
  5514. print_expression(p_subscript->base);
  5515. if (p_subscript->is_attribute) {
  5516. push_text(".");
  5517. print_identifier(p_subscript->attribute);
  5518. } else {
  5519. push_text("[ ");
  5520. print_expression(p_subscript->index);
  5521. push_text(" ]");
  5522. }
  5523. }
  5524. void GDScriptParser::TreePrinter::print_statement(Node *p_statement) {
  5525. switch (p_statement->type) {
  5526. case Node::ASSERT:
  5527. print_assert(static_cast<AssertNode *>(p_statement));
  5528. break;
  5529. case Node::VARIABLE:
  5530. print_variable(static_cast<VariableNode *>(p_statement));
  5531. break;
  5532. case Node::CONSTANT:
  5533. print_constant(static_cast<ConstantNode *>(p_statement));
  5534. break;
  5535. case Node::IF:
  5536. print_if(static_cast<IfNode *>(p_statement));
  5537. break;
  5538. case Node::FOR:
  5539. print_for(static_cast<ForNode *>(p_statement));
  5540. break;
  5541. case Node::WHILE:
  5542. print_while(static_cast<WhileNode *>(p_statement));
  5543. break;
  5544. case Node::MATCH:
  5545. print_match(static_cast<MatchNode *>(p_statement));
  5546. break;
  5547. case Node::RETURN:
  5548. print_return(static_cast<ReturnNode *>(p_statement));
  5549. break;
  5550. case Node::BREAK:
  5551. push_line("Break");
  5552. break;
  5553. case Node::CONTINUE:
  5554. push_line("Continue");
  5555. break;
  5556. case Node::PASS:
  5557. push_line("Pass");
  5558. break;
  5559. case Node::BREAKPOINT:
  5560. push_line("Breakpoint");
  5561. break;
  5562. case Node::ASSIGNMENT:
  5563. print_assignment(static_cast<AssignmentNode *>(p_statement));
  5564. break;
  5565. default:
  5566. if (p_statement->is_expression()) {
  5567. print_expression(static_cast<ExpressionNode *>(p_statement));
  5568. push_line();
  5569. } else {
  5570. push_line(vformat("<unknown statement %d>", p_statement->type));
  5571. }
  5572. break;
  5573. }
  5574. }
  5575. void GDScriptParser::TreePrinter::print_suite(SuiteNode *p_suite) {
  5576. for (int i = 0; i < p_suite->statements.size(); i++) {
  5577. print_statement(p_suite->statements[i]);
  5578. }
  5579. }
  5580. void GDScriptParser::TreePrinter::print_ternary_op(TernaryOpNode *p_ternary_op) {
  5581. // Surround in parenthesis for disambiguation.
  5582. push_text("(");
  5583. print_expression(p_ternary_op->true_expr);
  5584. push_text(") IF (");
  5585. print_expression(p_ternary_op->condition);
  5586. push_text(") ELSE (");
  5587. print_expression(p_ternary_op->false_expr);
  5588. push_text(")");
  5589. }
  5590. void GDScriptParser::TreePrinter::print_type(TypeNode *p_type) {
  5591. if (p_type->type_chain.is_empty()) {
  5592. push_text("Void");
  5593. } else {
  5594. for (int i = 0; i < p_type->type_chain.size(); i++) {
  5595. if (i > 0) {
  5596. push_text(".");
  5597. }
  5598. print_identifier(p_type->type_chain[i]);
  5599. }
  5600. }
  5601. }
  5602. void GDScriptParser::TreePrinter::print_type_test(TypeTestNode *p_test) {
  5603. print_expression(p_test->operand);
  5604. push_text(" IS ");
  5605. print_type(p_test->test_type);
  5606. }
  5607. void GDScriptParser::TreePrinter::print_unary_op(UnaryOpNode *p_unary_op) {
  5608. // Surround in parenthesis for disambiguation.
  5609. push_text("(");
  5610. switch (p_unary_op->operation) {
  5611. case UnaryOpNode::OP_POSITIVE:
  5612. push_text("+");
  5613. break;
  5614. case UnaryOpNode::OP_NEGATIVE:
  5615. push_text("-");
  5616. break;
  5617. case UnaryOpNode::OP_LOGIC_NOT:
  5618. push_text("NOT");
  5619. break;
  5620. case UnaryOpNode::OP_COMPLEMENT:
  5621. push_text("~");
  5622. break;
  5623. }
  5624. print_expression(p_unary_op->operand);
  5625. // Surround in parenthesis for disambiguation.
  5626. push_text(")");
  5627. }
  5628. void GDScriptParser::TreePrinter::print_variable(VariableNode *p_variable) {
  5629. for (const AnnotationNode *E : p_variable->annotations) {
  5630. print_annotation(E);
  5631. }
  5632. if (p_variable->is_static) {
  5633. push_text("Static ");
  5634. }
  5635. push_text("Variable ");
  5636. print_identifier(p_variable->identifier);
  5637. push_text(" : ");
  5638. if (p_variable->datatype_specifier != nullptr) {
  5639. print_type(p_variable->datatype_specifier);
  5640. } else if (p_variable->infer_datatype) {
  5641. push_text("<inferred type>");
  5642. } else {
  5643. push_text("Variant");
  5644. }
  5645. increase_indent();
  5646. push_line();
  5647. push_text("= ");
  5648. if (p_variable->initializer == nullptr) {
  5649. push_text("<default value>");
  5650. } else {
  5651. print_expression(p_variable->initializer);
  5652. }
  5653. push_line();
  5654. if (p_variable->property != VariableNode::PROP_NONE) {
  5655. if (p_variable->getter != nullptr) {
  5656. push_text("Get");
  5657. if (p_variable->property == VariableNode::PROP_INLINE) {
  5658. push_line(":");
  5659. increase_indent();
  5660. print_suite(p_variable->getter->body);
  5661. decrease_indent();
  5662. } else {
  5663. push_line(" =");
  5664. increase_indent();
  5665. print_identifier(p_variable->getter_pointer);
  5666. push_line();
  5667. decrease_indent();
  5668. }
  5669. }
  5670. if (p_variable->setter != nullptr) {
  5671. push_text("Set (");
  5672. if (p_variable->property == VariableNode::PROP_INLINE) {
  5673. if (p_variable->setter_parameter != nullptr) {
  5674. print_identifier(p_variable->setter_parameter);
  5675. } else {
  5676. push_text("<missing>");
  5677. }
  5678. push_line("):");
  5679. increase_indent();
  5680. print_suite(p_variable->setter->body);
  5681. decrease_indent();
  5682. } else {
  5683. push_line(" =");
  5684. increase_indent();
  5685. print_identifier(p_variable->setter_pointer);
  5686. push_line();
  5687. decrease_indent();
  5688. }
  5689. }
  5690. }
  5691. decrease_indent();
  5692. push_line();
  5693. }
  5694. void GDScriptParser::TreePrinter::print_while(WhileNode *p_while) {
  5695. push_text("While ");
  5696. print_expression(p_while->condition);
  5697. push_line(" :");
  5698. increase_indent();
  5699. print_suite(p_while->loop);
  5700. decrease_indent();
  5701. }
  5702. void GDScriptParser::TreePrinter::print_tree(const GDScriptParser &p_parser) {
  5703. ClassNode *class_tree = p_parser.get_tree();
  5704. ERR_FAIL_NULL_MSG(class_tree, "Parse the code before printing the parse tree.");
  5705. if (p_parser.is_tool()) {
  5706. push_line("@tool");
  5707. }
  5708. if (!class_tree->icon_path.is_empty()) {
  5709. push_text(R"(@icon (")");
  5710. push_text(class_tree->icon_path);
  5711. push_line("\")");
  5712. }
  5713. print_class(class_tree);
  5714. print_line(String(printed));
  5715. }
  5716. #endif // DEBUG_ENABLED