gdscript_parser.cpp 222 KB

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