gdscript_analyzer.cpp 196 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052
  1. /**************************************************************************/
  2. /* gdscript_analyzer.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_analyzer.h"
  31. #include "core/config/engine.h"
  32. #include "core/config/project_settings.h"
  33. #include "core/core_string_names.h"
  34. #include "core/io/file_access.h"
  35. #include "core/io/resource_loader.h"
  36. #include "core/object/class_db.h"
  37. #include "core/object/script_language.h"
  38. #include "core/templates/hash_map.h"
  39. #include "gdscript.h"
  40. #include "gdscript_utility_functions.h"
  41. #include "scene/resources/packed_scene.h"
  42. #define UNNAMED_ENUM "<anonymous enum>"
  43. #define ENUM_SEPARATOR "::"
  44. static MethodInfo info_from_utility_func(const StringName &p_function) {
  45. ERR_FAIL_COND_V(!Variant::has_utility_function(p_function), MethodInfo());
  46. MethodInfo info(p_function);
  47. if (Variant::has_utility_function_return_value(p_function)) {
  48. info.return_val.type = Variant::get_utility_function_return_type(p_function);
  49. if (info.return_val.type == Variant::NIL) {
  50. info.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  51. }
  52. }
  53. if (Variant::is_utility_function_vararg(p_function)) {
  54. info.flags |= METHOD_FLAG_VARARG;
  55. } else {
  56. for (int i = 0; i < Variant::get_utility_function_argument_count(p_function); i++) {
  57. PropertyInfo pi;
  58. #ifdef DEBUG_METHODS_ENABLED
  59. pi.name = Variant::get_utility_function_argument_name(p_function, i);
  60. #else
  61. pi.name = "arg" + itos(i + 1);
  62. #endif
  63. pi.type = Variant::get_utility_function_argument_type(p_function, i);
  64. info.arguments.push_back(pi);
  65. }
  66. }
  67. return info;
  68. }
  69. static GDScriptParser::DataType make_callable_type(const MethodInfo &p_info) {
  70. GDScriptParser::DataType type;
  71. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  72. type.kind = GDScriptParser::DataType::BUILTIN;
  73. type.builtin_type = Variant::CALLABLE;
  74. type.is_constant = true;
  75. type.method_info = p_info;
  76. return type;
  77. }
  78. static GDScriptParser::DataType make_signal_type(const MethodInfo &p_info) {
  79. GDScriptParser::DataType type;
  80. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  81. type.kind = GDScriptParser::DataType::BUILTIN;
  82. type.builtin_type = Variant::SIGNAL;
  83. type.is_constant = true;
  84. type.method_info = p_info;
  85. return type;
  86. }
  87. static GDScriptParser::DataType make_native_meta_type(const StringName &p_class_name) {
  88. GDScriptParser::DataType type;
  89. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  90. type.kind = GDScriptParser::DataType::NATIVE;
  91. type.builtin_type = Variant::OBJECT;
  92. type.native_type = p_class_name;
  93. type.is_constant = true;
  94. type.is_meta_type = true;
  95. return type;
  96. }
  97. static GDScriptParser::DataType make_script_meta_type(const Ref<Script> &p_script) {
  98. GDScriptParser::DataType type;
  99. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  100. type.kind = GDScriptParser::DataType::SCRIPT;
  101. type.builtin_type = Variant::OBJECT;
  102. type.native_type = p_script->get_instance_base_type();
  103. type.script_type = p_script;
  104. type.script_path = p_script->get_path();
  105. type.is_constant = true;
  106. type.is_meta_type = true;
  107. return type;
  108. }
  109. // In enum types, native_type is used to store the class (native or otherwise) that the enum belongs to.
  110. // This disambiguates between similarly named enums in base classes or outer classes
  111. static GDScriptParser::DataType make_enum_type(const StringName &p_enum_name, const String &p_base_name, const bool p_meta = false) {
  112. GDScriptParser::DataType type;
  113. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  114. type.kind = GDScriptParser::DataType::ENUM;
  115. type.builtin_type = p_meta ? Variant::DICTIONARY : Variant::INT;
  116. type.enum_type = p_enum_name;
  117. type.is_constant = true;
  118. type.is_meta_type = p_meta;
  119. // For enums, native_type is only used to check compatibility in is_type_compatible()
  120. // We can set anything readable here for error messages, as long as it uniquely identifies the type of the enum
  121. type.native_type = p_base_name + ENUM_SEPARATOR + p_enum_name;
  122. return type;
  123. }
  124. static GDScriptParser::DataType make_native_enum_type(const StringName &p_enum_name, const StringName &p_native_class, const bool p_meta = true) {
  125. // Find out which base class declared the enum, so the name is always the same even when coming from other contexts.
  126. StringName native_base = p_native_class;
  127. while (true && native_base != StringName()) {
  128. if (ClassDB::has_enum(native_base, p_enum_name, true)) {
  129. break;
  130. }
  131. native_base = ClassDB::get_parent_class_nocheck(native_base);
  132. }
  133. GDScriptParser::DataType type = make_enum_type(p_enum_name, native_base, p_meta);
  134. if (p_meta) {
  135. type.builtin_type = Variant::NIL; // Native enum types are not Dictionaries
  136. }
  137. List<StringName> enum_values;
  138. ClassDB::get_enum_constants(native_base, p_enum_name, &enum_values, true);
  139. for (const StringName &E : enum_values) {
  140. type.enum_values[E] = ClassDB::get_integer_constant(native_base, E);
  141. }
  142. return type;
  143. }
  144. static GDScriptParser::DataType make_builtin_meta_type(Variant::Type p_type) {
  145. GDScriptParser::DataType type;
  146. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  147. type.kind = GDScriptParser::DataType::BUILTIN;
  148. type.builtin_type = p_type;
  149. type.is_constant = true;
  150. type.is_meta_type = true;
  151. return type;
  152. }
  153. bool GDScriptAnalyzer::has_member_name_conflict_in_script_class(const StringName &p_member_name, const GDScriptParser::ClassNode *p_class, const GDScriptParser::Node *p_member) {
  154. if (p_class->members_indices.has(p_member_name)) {
  155. int index = p_class->members_indices[p_member_name];
  156. const GDScriptParser::ClassNode::Member *member = &p_class->members[index];
  157. if (member->type == GDScriptParser::ClassNode::Member::VARIABLE ||
  158. member->type == GDScriptParser::ClassNode::Member::CONSTANT ||
  159. member->type == GDScriptParser::ClassNode::Member::ENUM ||
  160. member->type == GDScriptParser::ClassNode::Member::ENUM_VALUE ||
  161. member->type == GDScriptParser::ClassNode::Member::CLASS ||
  162. member->type == GDScriptParser::ClassNode::Member::SIGNAL) {
  163. return true;
  164. }
  165. if (p_member->type != GDScriptParser::Node::FUNCTION && member->type == GDScriptParser::ClassNode::Member::FUNCTION) {
  166. return true;
  167. }
  168. }
  169. return false;
  170. }
  171. bool GDScriptAnalyzer::has_member_name_conflict_in_native_type(const StringName &p_member_name, const StringName &p_native_type_string) {
  172. if (ClassDB::has_signal(p_native_type_string, p_member_name)) {
  173. return true;
  174. }
  175. if (ClassDB::has_property(p_native_type_string, p_member_name)) {
  176. return true;
  177. }
  178. if (ClassDB::has_integer_constant(p_native_type_string, p_member_name)) {
  179. return true;
  180. }
  181. if (p_member_name == CoreStringNames::get_singleton()->_script) {
  182. return true;
  183. }
  184. return false;
  185. }
  186. Error GDScriptAnalyzer::check_native_member_name_conflict(const StringName &p_member_name, const GDScriptParser::Node *p_member_node, const StringName &p_native_type_string) {
  187. if (has_member_name_conflict_in_native_type(p_member_name, p_native_type_string)) {
  188. push_error(vformat(R"(Member "%s" redefined (original in native class '%s'))", p_member_name, p_native_type_string), p_member_node);
  189. return ERR_PARSE_ERROR;
  190. }
  191. if (class_exists(p_member_name)) {
  192. push_error(vformat(R"(The member "%s" shadows a native class.)", p_member_name), p_member_node);
  193. return ERR_PARSE_ERROR;
  194. }
  195. if (GDScriptParser::get_builtin_type(p_member_name) != Variant::VARIANT_MAX) {
  196. push_error(vformat(R"(The member "%s" cannot have the same name as a builtin type.)", p_member_name), p_member_node);
  197. return ERR_PARSE_ERROR;
  198. }
  199. return OK;
  200. }
  201. Error GDScriptAnalyzer::check_class_member_name_conflict(const GDScriptParser::ClassNode *p_class_node, const StringName &p_member_name, const GDScriptParser::Node *p_member_node) {
  202. // TODO check outer classes for static members only
  203. const GDScriptParser::DataType *current_data_type = &p_class_node->base_type;
  204. while (current_data_type && current_data_type->kind == GDScriptParser::DataType::Kind::CLASS) {
  205. GDScriptParser::ClassNode *current_class_node = current_data_type->class_type;
  206. if (has_member_name_conflict_in_script_class(p_member_name, current_class_node, p_member_node)) {
  207. String parent_class_name = current_class_node->fqcn;
  208. if (current_class_node->identifier != nullptr) {
  209. parent_class_name = current_class_node->identifier->name;
  210. }
  211. push_error(vformat(R"(The member "%s" already exists in parent class %s.)", p_member_name, parent_class_name), p_member_node);
  212. return ERR_PARSE_ERROR;
  213. }
  214. current_data_type = &current_class_node->base_type;
  215. }
  216. // No need for native class recursion because Node exposes all Object's properties.
  217. if (current_data_type && current_data_type->kind == GDScriptParser::DataType::Kind::NATIVE) {
  218. if (current_data_type->native_type != StringName()) {
  219. return check_native_member_name_conflict(
  220. p_member_name,
  221. p_member_node,
  222. current_data_type->native_type);
  223. }
  224. }
  225. return OK;
  226. }
  227. void GDScriptAnalyzer::get_class_node_current_scope_classes(GDScriptParser::ClassNode *p_node, List<GDScriptParser::ClassNode *> *p_list) {
  228. ERR_FAIL_NULL(p_node);
  229. ERR_FAIL_NULL(p_list);
  230. if (p_list->find(p_node) != nullptr) {
  231. return;
  232. }
  233. p_list->push_back(p_node);
  234. // TODO: Try to solve class inheritance if not yet resolving.
  235. // Prioritize node base type over its outer class
  236. if (p_node->base_type.class_type != nullptr) {
  237. get_class_node_current_scope_classes(p_node->base_type.class_type, p_list);
  238. }
  239. if (p_node->outer != nullptr) {
  240. get_class_node_current_scope_classes(p_node->outer, p_list);
  241. }
  242. }
  243. Error GDScriptAnalyzer::resolve_class_inheritance(GDScriptParser::ClassNode *p_class, const GDScriptParser::Node *p_source) {
  244. if (p_source == nullptr && parser->has_class(p_class)) {
  245. p_source = p_class;
  246. }
  247. if (p_class->base_type.is_resolving()) {
  248. push_error(vformat(R"(Could not resolve class "%s": Cyclic reference.)", type_from_metatype(p_class->get_datatype()).to_string()), p_source);
  249. return ERR_PARSE_ERROR;
  250. }
  251. if (!p_class->base_type.has_no_type()) {
  252. // Already resolved.
  253. return OK;
  254. }
  255. if (!parser->has_class(p_class)) {
  256. String script_path = p_class->get_datatype().script_path;
  257. Ref<GDScriptParserRef> parser_ref = get_parser_for(script_path);
  258. if (parser_ref.is_null()) {
  259. push_error(vformat(R"(Could not find script "%s".)", script_path), p_source);
  260. return ERR_PARSE_ERROR;
  261. }
  262. Error err = parser_ref->raise_status(GDScriptParserRef::PARSED);
  263. if (err) {
  264. push_error(vformat(R"(Could not parse script "%s": %s.)", script_path, error_names[err]), p_source);
  265. return ERR_PARSE_ERROR;
  266. }
  267. ERR_FAIL_COND_V_MSG(!parser_ref->get_parser()->has_class(p_class), ERR_PARSE_ERROR, R"(Parser bug: Mismatched external parser.)");
  268. GDScriptAnalyzer *other_analyzer = parser_ref->get_analyzer();
  269. GDScriptParser *other_parser = parser_ref->get_parser();
  270. int error_count = other_parser->errors.size();
  271. other_analyzer->resolve_class_inheritance(p_class);
  272. if (other_parser->errors.size() > error_count) {
  273. push_error(vformat(R"(Could not resolve inheritance for class "%s".)", p_class->fqcn), p_source);
  274. return ERR_PARSE_ERROR;
  275. }
  276. return OK;
  277. }
  278. GDScriptParser::ClassNode *previous_class = parser->current_class;
  279. parser->current_class = p_class;
  280. if (p_class->identifier) {
  281. StringName class_name = p_class->identifier->name;
  282. if (GDScriptParser::get_builtin_type(class_name) < Variant::VARIANT_MAX) {
  283. push_error(vformat(R"(Class "%s" hides a built-in type.)", class_name), p_class->identifier);
  284. } else if (class_exists(class_name)) {
  285. push_error(vformat(R"(Class "%s" hides a native class.)", class_name), p_class->identifier);
  286. } else if (ScriptServer::is_global_class(class_name) && (ScriptServer::get_global_class_path(class_name) != parser->script_path || p_class != parser->head)) {
  287. push_error(vformat(R"(Class "%s" hides a global script class.)", class_name), p_class->identifier);
  288. } else if (ProjectSettings::get_singleton()->has_autoload(class_name) && ProjectSettings::get_singleton()->get_autoload(class_name).is_singleton) {
  289. push_error(vformat(R"(Class "%s" hides an autoload singleton.)", class_name), p_class->identifier);
  290. }
  291. }
  292. GDScriptParser::DataType resolving_datatype;
  293. resolving_datatype.kind = GDScriptParser::DataType::RESOLVING;
  294. p_class->base_type = resolving_datatype;
  295. // Set datatype for class.
  296. GDScriptParser::DataType class_type;
  297. class_type.is_constant = true;
  298. class_type.is_meta_type = true;
  299. class_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  300. class_type.kind = GDScriptParser::DataType::CLASS;
  301. class_type.class_type = p_class;
  302. class_type.script_path = parser->script_path;
  303. class_type.builtin_type = Variant::OBJECT;
  304. p_class->set_datatype(class_type);
  305. GDScriptParser::DataType result;
  306. if (!p_class->extends_used) {
  307. result.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  308. result.kind = GDScriptParser::DataType::NATIVE;
  309. result.native_type = SNAME("RefCounted");
  310. } else {
  311. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  312. GDScriptParser::DataType base;
  313. int extends_index = 0;
  314. if (!p_class->extends_path.is_empty()) {
  315. if (p_class->extends_path.is_relative_path()) {
  316. p_class->extends_path = class_type.script_path.get_base_dir().path_join(p_class->extends_path).simplify_path();
  317. }
  318. Ref<GDScriptParserRef> ext_parser = get_parser_for(p_class->extends_path);
  319. if (ext_parser.is_null()) {
  320. push_error(vformat(R"(Could not resolve super class path "%s".)", p_class->extends_path), p_class);
  321. return ERR_PARSE_ERROR;
  322. }
  323. Error err = ext_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  324. if (err != OK) {
  325. push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", p_class->extends_path), p_class);
  326. return err;
  327. }
  328. base = ext_parser->get_parser()->head->get_datatype();
  329. } else {
  330. if (p_class->extends.is_empty()) {
  331. push_error("Could not resolve an empty super class path.", p_class);
  332. return ERR_PARSE_ERROR;
  333. }
  334. const StringName &name = p_class->extends[extends_index++];
  335. base.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  336. if (ScriptServer::is_global_class(name)) {
  337. String base_path = ScriptServer::get_global_class_path(name);
  338. if (base_path == parser->script_path) {
  339. base = parser->head->get_datatype();
  340. } else {
  341. Ref<GDScriptParserRef> base_parser = get_parser_for(base_path);
  342. if (base_parser.is_null()) {
  343. push_error(vformat(R"(Could not resolve super class "%s".)", name), p_class);
  344. return ERR_PARSE_ERROR;
  345. }
  346. Error err = base_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  347. if (err != OK) {
  348. push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), p_class);
  349. return err;
  350. }
  351. base = base_parser->get_parser()->head->get_datatype();
  352. }
  353. } else if (ProjectSettings::get_singleton()->has_autoload(name) && ProjectSettings::get_singleton()->get_autoload(name).is_singleton) {
  354. const ProjectSettings::AutoloadInfo &info = ProjectSettings::get_singleton()->get_autoload(name);
  355. if (info.path.get_extension().to_lower() != GDScriptLanguage::get_singleton()->get_extension()) {
  356. push_error(vformat(R"(Singleton %s is not a GDScript.)", info.name), p_class);
  357. return ERR_PARSE_ERROR;
  358. }
  359. Ref<GDScriptParserRef> info_parser = get_parser_for(info.path);
  360. if (info_parser.is_null()) {
  361. push_error(vformat(R"(Could not parse singleton from "%s".)", info.path), p_class);
  362. return ERR_PARSE_ERROR;
  363. }
  364. Error err = info_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  365. if (err != OK) {
  366. push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), p_class);
  367. return err;
  368. }
  369. base = info_parser->get_parser()->head->get_datatype();
  370. } else if (class_exists(name)) {
  371. base.kind = GDScriptParser::DataType::NATIVE;
  372. base.native_type = name;
  373. } else {
  374. // Look for other classes in script.
  375. bool found = false;
  376. List<GDScriptParser::ClassNode *> script_classes;
  377. get_class_node_current_scope_classes(p_class, &script_classes);
  378. for (GDScriptParser::ClassNode *look_class : script_classes) {
  379. if (look_class->identifier && look_class->identifier->name == name) {
  380. if (!look_class->get_datatype().is_set()) {
  381. Error err = resolve_class_inheritance(look_class, p_class);
  382. if (err) {
  383. return err;
  384. }
  385. }
  386. base = look_class->get_datatype();
  387. found = true;
  388. break;
  389. }
  390. if (look_class->has_member(name)) {
  391. resolve_class_member(look_class, name, p_class);
  392. base = look_class->get_member(name).get_datatype();
  393. found = true;
  394. break;
  395. }
  396. }
  397. if (!found) {
  398. push_error(vformat(R"(Could not find base class "%s".)", name), p_class);
  399. return ERR_PARSE_ERROR;
  400. }
  401. }
  402. }
  403. for (int index = extends_index; index < p_class->extends.size(); index++) {
  404. if (base.kind != GDScriptParser::DataType::CLASS) {
  405. push_error(R"(Super type "%s" is not a GDScript. Cannot get nested types.)", p_class);
  406. return ERR_PARSE_ERROR;
  407. }
  408. // TODO: Extends could use identifier nodes. That way errors can be pointed out properly and it can be used here.
  409. GDScriptParser::IdentifierNode *id = parser->alloc_node<GDScriptParser::IdentifierNode>();
  410. id->name = p_class->extends[index];
  411. reduce_identifier_from_base(id, &base);
  412. GDScriptParser::DataType id_type = id->get_datatype();
  413. if (!id_type.is_set()) {
  414. push_error(vformat(R"(Could not find type "%s" under base "%s".)", id->name, base.to_string()), p_class);
  415. }
  416. base = id_type;
  417. }
  418. result = base;
  419. }
  420. if (!result.is_set() || result.has_no_type()) {
  421. // TODO: More specific error messages.
  422. push_error(vformat(R"(Could not resolve inheritance for class "%s".)", p_class->identifier == nullptr ? "<main>" : p_class->identifier->name), p_class);
  423. return ERR_PARSE_ERROR;
  424. }
  425. // Check for cyclic inheritance.
  426. const GDScriptParser::ClassNode *base_class = result.class_type;
  427. while (base_class) {
  428. if (base_class->fqcn == p_class->fqcn) {
  429. push_error("Cyclic inheritance.", p_class);
  430. return ERR_PARSE_ERROR;
  431. }
  432. base_class = base_class->base_type.class_type;
  433. }
  434. p_class->base_type = result;
  435. class_type.native_type = result.native_type;
  436. p_class->set_datatype(class_type);
  437. parser->current_class = previous_class;
  438. return OK;
  439. }
  440. Error GDScriptAnalyzer::resolve_class_inheritance(GDScriptParser::ClassNode *p_class, bool p_recursive) {
  441. Error err = resolve_class_inheritance(p_class);
  442. if (err) {
  443. return err;
  444. }
  445. if (p_recursive) {
  446. for (int i = 0; i < p_class->members.size(); i++) {
  447. if (p_class->members[i].type == GDScriptParser::ClassNode::Member::CLASS) {
  448. err = resolve_class_inheritance(p_class->members[i].m_class, true);
  449. if (err) {
  450. return err;
  451. }
  452. }
  453. }
  454. }
  455. return OK;
  456. }
  457. GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::TypeNode *p_type) {
  458. GDScriptParser::DataType bad_type;
  459. bad_type.kind = GDScriptParser::DataType::VARIANT;
  460. bad_type.type_source = GDScriptParser::DataType::INFERRED;
  461. if (p_type == nullptr) {
  462. return bad_type;
  463. }
  464. if (p_type->get_datatype().is_resolving()) {
  465. push_error(R"(Could not resolve datatype: Cyclic reference.)", p_type);
  466. return bad_type;
  467. }
  468. if (!p_type->get_datatype().has_no_type()) {
  469. return p_type->get_datatype();
  470. }
  471. GDScriptParser::DataType resolving_datatype;
  472. resolving_datatype.kind = GDScriptParser::DataType::RESOLVING;
  473. p_type->set_datatype(resolving_datatype);
  474. GDScriptParser::DataType result;
  475. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  476. result.builtin_type = Variant::OBJECT;
  477. if (p_type->type_chain.is_empty()) {
  478. // void.
  479. result.kind = GDScriptParser::DataType::BUILTIN;
  480. result.builtin_type = Variant::NIL;
  481. p_type->set_datatype(result);
  482. return result;
  483. }
  484. StringName first = p_type->type_chain[0]->name;
  485. if (first == SNAME("Variant")) {
  486. if (p_type->type_chain.size() > 1) {
  487. // TODO: Variant does actually have a nested Type though.
  488. push_error(R"(Variant doesn't contain nested types.)", p_type->type_chain[1]);
  489. return bad_type;
  490. }
  491. result.kind = GDScriptParser::DataType::VARIANT;
  492. } else if (first == SNAME("Object")) {
  493. // Object is treated like a native type, not a built-in.
  494. result.kind = GDScriptParser::DataType::NATIVE;
  495. result.native_type = SNAME("Object");
  496. } else if (GDScriptParser::get_builtin_type(first) < Variant::VARIANT_MAX) {
  497. // Built-in types.
  498. if (p_type->type_chain.size() > 1) {
  499. push_error(R"(Built-in types don't contain nested types.)", p_type->type_chain[1]);
  500. return bad_type;
  501. }
  502. result.kind = GDScriptParser::DataType::BUILTIN;
  503. result.builtin_type = GDScriptParser::get_builtin_type(first);
  504. if (result.builtin_type == Variant::ARRAY) {
  505. GDScriptParser::DataType container_type = type_from_metatype(resolve_datatype(p_type->container_type));
  506. if (container_type.kind != GDScriptParser::DataType::VARIANT) {
  507. container_type.is_constant = false;
  508. result.set_container_element_type(container_type);
  509. }
  510. }
  511. } else if (class_exists(first)) {
  512. // Native engine classes.
  513. result.kind = GDScriptParser::DataType::NATIVE;
  514. result.native_type = first;
  515. } else if (ScriptServer::is_global_class(first)) {
  516. if (parser->script_path == ScriptServer::get_global_class_path(first)) {
  517. result = parser->head->get_datatype();
  518. } else {
  519. String path = ScriptServer::get_global_class_path(first);
  520. String ext = path.get_extension();
  521. if (ext == GDScriptLanguage::get_singleton()->get_extension()) {
  522. Ref<GDScriptParserRef> ref = get_parser_for(path);
  523. if (!ref.is_valid() || ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED) != OK) {
  524. push_error(vformat(R"(Could not parse global class "%s" from "%s".)", first, ScriptServer::get_global_class_path(first)), p_type);
  525. return bad_type;
  526. }
  527. result = ref->get_parser()->head->get_datatype();
  528. } else {
  529. result = make_script_meta_type(ResourceLoader::load(path, "Script"));
  530. }
  531. }
  532. } else if (ProjectSettings::get_singleton()->has_autoload(first) && ProjectSettings::get_singleton()->get_autoload(first).is_singleton) {
  533. const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(first);
  534. Ref<GDScriptParserRef> ref = get_parser_for(autoload.path);
  535. if (ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED) != OK) {
  536. push_error(vformat(R"(Could not parse singleton "%s" from "%s".)", first, autoload.path), p_type);
  537. return bad_type;
  538. }
  539. result = ref->get_parser()->head->get_datatype();
  540. } else if (ClassDB::has_enum(parser->current_class->base_type.native_type, first)) {
  541. // Native enum in current class.
  542. result = make_native_enum_type(first, parser->current_class->base_type.native_type);
  543. } else {
  544. // Classes in current scope.
  545. List<GDScriptParser::ClassNode *> script_classes;
  546. bool found = false;
  547. get_class_node_current_scope_classes(parser->current_class, &script_classes);
  548. for (GDScriptParser::ClassNode *script_class : script_classes) {
  549. if (found) {
  550. break;
  551. }
  552. if (script_class->identifier && script_class->identifier->name == first) {
  553. result = script_class->get_datatype();
  554. break;
  555. }
  556. if (script_class->members_indices.has(first)) {
  557. resolve_class_member(script_class, first, p_type);
  558. GDScriptParser::ClassNode::Member member = script_class->get_member(first);
  559. switch (member.type) {
  560. case GDScriptParser::ClassNode::Member::CLASS:
  561. result = member.get_datatype();
  562. found = true;
  563. break;
  564. case GDScriptParser::ClassNode::Member::ENUM:
  565. result = member.get_datatype();
  566. found = true;
  567. break;
  568. case GDScriptParser::ClassNode::Member::CONSTANT:
  569. if (member.get_datatype().is_meta_type) {
  570. result = member.get_datatype();
  571. found = true;
  572. break;
  573. } else if (Ref<Script>(member.constant->initializer->reduced_value).is_valid()) {
  574. Ref<GDScript> gdscript = member.constant->initializer->reduced_value;
  575. if (gdscript.is_valid()) {
  576. Ref<GDScriptParserRef> ref = get_parser_for(gdscript->get_script_path());
  577. if (ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED) != OK) {
  578. push_error(vformat(R"(Could not parse script from "%s".)", gdscript->get_script_path()), p_type);
  579. return bad_type;
  580. }
  581. result = ref->get_parser()->head->get_datatype();
  582. } else {
  583. result = make_script_meta_type(member.constant->initializer->reduced_value);
  584. }
  585. found = true;
  586. break;
  587. }
  588. [[fallthrough]];
  589. default:
  590. push_error(vformat(R"("%s" is a %s but does not contain a type.)", first, member.get_type_name()), p_type);
  591. return bad_type;
  592. }
  593. }
  594. }
  595. }
  596. if (!result.is_set()) {
  597. push_error(vformat(R"("%s" was not found in the current scope.)", first), p_type);
  598. return bad_type;
  599. }
  600. if (p_type->type_chain.size() > 1) {
  601. if (result.kind == GDScriptParser::DataType::CLASS) {
  602. for (int i = 1; i < p_type->type_chain.size(); i++) {
  603. GDScriptParser::DataType base = result;
  604. reduce_identifier_from_base(p_type->type_chain[i], &base);
  605. result = p_type->type_chain[i]->get_datatype();
  606. if (!result.is_set()) {
  607. push_error(vformat(R"(Could not find type "%s" under base "%s".)", p_type->type_chain[i]->name, base.to_string()), p_type->type_chain[1]);
  608. return bad_type;
  609. } else if (!result.is_meta_type) {
  610. push_error(vformat(R"(Member "%s" under base "%s" is not a valid type.)", p_type->type_chain[i]->name, base.to_string()), p_type->type_chain[1]);
  611. return bad_type;
  612. }
  613. }
  614. } else if (result.kind == GDScriptParser::DataType::NATIVE) {
  615. // Only enums allowed for native.
  616. if (ClassDB::has_enum(result.native_type, p_type->type_chain[1]->name)) {
  617. if (p_type->type_chain.size() > 2) {
  618. push_error(R"(Enums cannot contain nested types.)", p_type->type_chain[2]);
  619. return bad_type;
  620. } else {
  621. result = make_native_enum_type(p_type->type_chain[1]->name, result.native_type);
  622. }
  623. } else {
  624. push_error(vformat(R"(Could not find type "%s" in "%s".)", p_type->type_chain[1]->name, first), p_type->type_chain[1]);
  625. return bad_type;
  626. }
  627. } else {
  628. push_error(vformat(R"(Could not find nested type "%s" under base "%s".)", p_type->type_chain[1]->name, result.to_string()), p_type->type_chain[1]);
  629. return bad_type;
  630. }
  631. }
  632. if (result.builtin_type != Variant::ARRAY && p_type->container_type != nullptr) {
  633. push_error("Only arrays can specify the collection element type.", p_type);
  634. }
  635. p_type->set_datatype(result);
  636. return result;
  637. }
  638. void GDScriptAnalyzer::resolve_class_member(GDScriptParser::ClassNode *p_class, StringName p_name, const GDScriptParser::Node *p_source) {
  639. ERR_FAIL_COND(!p_class->has_member(p_name));
  640. resolve_class_member(p_class, p_class->members_indices[p_name], p_source);
  641. }
  642. void GDScriptAnalyzer::resolve_class_member(GDScriptParser::ClassNode *p_class, int p_index, const GDScriptParser::Node *p_source) {
  643. ERR_FAIL_INDEX(p_index, p_class->members.size());
  644. GDScriptParser::ClassNode::Member &member = p_class->members.write[p_index];
  645. if (p_source == nullptr && parser->has_class(p_class)) {
  646. p_source = member.get_source_node();
  647. }
  648. if (member.get_datatype().is_resolving()) {
  649. push_error(vformat(R"(Could not resolve member "%s": Cyclic reference.)", member.get_name()), p_source);
  650. return;
  651. }
  652. if (member.get_datatype().is_set()) {
  653. return;
  654. }
  655. if (!parser->has_class(p_class)) {
  656. String script_path = p_class->get_datatype().script_path;
  657. Ref<GDScriptParserRef> parser_ref = get_parser_for(script_path);
  658. if (parser_ref.is_null()) {
  659. push_error(vformat(R"(Could not find script "%s" (While resolving "%s").)", script_path, member.get_name()), p_source);
  660. return;
  661. }
  662. Error err = parser_ref->raise_status(GDScriptParserRef::PARSED);
  663. if (err) {
  664. push_error(vformat(R"(Could not resolve script "%s": %s (While resolving "%s").)", script_path, error_names[err], member.get_name()), p_source);
  665. return;
  666. }
  667. ERR_FAIL_COND_MSG(!parser_ref->get_parser()->has_class(p_class), R"(Parser bug: Mismatched external parser.)");
  668. GDScriptAnalyzer *other_analyzer = parser_ref->get_analyzer();
  669. GDScriptParser *other_parser = parser_ref->get_parser();
  670. int error_count = other_parser->errors.size();
  671. other_analyzer->resolve_class_member(p_class, p_index);
  672. if (other_parser->errors.size() > error_count) {
  673. push_error(vformat(R"(Could not resolve member "%s".)", member.get_name()), p_source);
  674. }
  675. return;
  676. }
  677. // If it's already resolving, that's ok.
  678. if (!p_class->base_type.is_resolving()) {
  679. Error err = resolve_class_inheritance(p_class);
  680. if (err) {
  681. return;
  682. }
  683. }
  684. GDScriptParser::ClassNode *previous_class = parser->current_class;
  685. parser->current_class = p_class;
  686. GDScriptParser::DataType resolving_datatype;
  687. resolving_datatype.kind = GDScriptParser::DataType::RESOLVING;
  688. {
  689. #ifdef DEBUG_ENABLED
  690. HashSet<GDScriptWarning::Code> previously_ignored_warnings = parser->ignored_warnings;
  691. GDScriptParser::Node *member_node = member.get_source_node();
  692. if (member_node && member_node->type != GDScriptParser::Node::ANNOTATION) {
  693. // Apply @warning_ignore annotations before resolving member.
  694. for (GDScriptParser::AnnotationNode *&E : member_node->annotations) {
  695. if (E->name == SNAME("@warning_ignore")) {
  696. resolve_annotation(E);
  697. E->apply(parser, member.variable);
  698. }
  699. }
  700. for (GDScriptWarning::Code ignored_warning : member_node->ignored_warnings) {
  701. parser->ignored_warnings.insert(ignored_warning);
  702. }
  703. }
  704. #endif
  705. switch (member.type) {
  706. case GDScriptParser::ClassNode::Member::VARIABLE: {
  707. check_class_member_name_conflict(p_class, member.variable->identifier->name, member.variable);
  708. member.variable->set_datatype(resolving_datatype);
  709. resolve_variable(member.variable, false);
  710. // Apply annotations.
  711. for (GDScriptParser::AnnotationNode *&E : member.variable->annotations) {
  712. if (E->name != SNAME("@warning_ignore")) {
  713. resolve_annotation(E);
  714. E->apply(parser, member.variable);
  715. }
  716. }
  717. #ifdef DEBUG_ENABLED
  718. if (member.variable->exported && member.variable->onready) {
  719. parser->push_warning(member.variable, GDScriptWarning::ONREADY_WITH_EXPORT);
  720. }
  721. if (member.variable->initializer) {
  722. // Check if it is call to get_node() on self (using shorthand $ or not), so we can check if @onready is needed.
  723. // This could be improved by traversing the expression fully and checking the presence of get_node at any level.
  724. if (!member.variable->onready && member.variable->initializer && (member.variable->initializer->type == GDScriptParser::Node::GET_NODE || member.variable->initializer->type == GDScriptParser::Node::CALL || member.variable->initializer->type == GDScriptParser::Node::CAST)) {
  725. GDScriptParser::Node *expr = member.variable->initializer;
  726. if (expr->type == GDScriptParser::Node::CAST) {
  727. expr = static_cast<GDScriptParser::CastNode *>(expr)->operand;
  728. }
  729. bool is_get_node = expr->type == GDScriptParser::Node::GET_NODE;
  730. bool is_using_shorthand = is_get_node;
  731. if (!is_get_node && expr->type == GDScriptParser::Node::CALL) {
  732. is_using_shorthand = false;
  733. GDScriptParser::CallNode *call = static_cast<GDScriptParser::CallNode *>(expr);
  734. if (call->function_name == SNAME("get_node")) {
  735. switch (call->get_callee_type()) {
  736. case GDScriptParser::Node::IDENTIFIER: {
  737. is_get_node = true;
  738. } break;
  739. case GDScriptParser::Node::SUBSCRIPT: {
  740. GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(call->callee);
  741. is_get_node = subscript->is_attribute && subscript->base->type == GDScriptParser::Node::SELF;
  742. } break;
  743. default:
  744. break;
  745. }
  746. }
  747. }
  748. if (is_get_node) {
  749. parser->push_warning(member.variable, GDScriptWarning::GET_NODE_DEFAULT_WITHOUT_ONREADY, is_using_shorthand ? "$" : "get_node()");
  750. }
  751. }
  752. }
  753. #endif
  754. } break;
  755. case GDScriptParser::ClassNode::Member::CONSTANT: {
  756. check_class_member_name_conflict(p_class, member.constant->identifier->name, member.constant);
  757. member.constant->set_datatype(resolving_datatype);
  758. resolve_constant(member.constant, false);
  759. // Apply annotations.
  760. for (GDScriptParser::AnnotationNode *&E : member.constant->annotations) {
  761. resolve_annotation(E);
  762. E->apply(parser, member.constant);
  763. }
  764. } break;
  765. case GDScriptParser::ClassNode::Member::SIGNAL: {
  766. check_class_member_name_conflict(p_class, member.signal->identifier->name, member.signal);
  767. member.signal->set_datatype(resolving_datatype);
  768. // This is the _only_ way to declare a signal. Therefore, we can generate its
  769. // MethodInfo inline so it's a tiny bit more efficient.
  770. MethodInfo mi = MethodInfo(member.signal->identifier->name);
  771. for (int j = 0; j < member.signal->parameters.size(); j++) {
  772. GDScriptParser::ParameterNode *param = member.signal->parameters[j];
  773. GDScriptParser::DataType param_type = type_from_metatype(resolve_datatype(param->datatype_specifier));
  774. param->set_datatype(param_type);
  775. mi.arguments.push_back(PropertyInfo(param_type.builtin_type, param->identifier->name));
  776. // TODO: add signal parameter default values
  777. }
  778. member.signal->set_datatype(make_signal_type(mi));
  779. // Apply annotations.
  780. for (GDScriptParser::AnnotationNode *&E : member.signal->annotations) {
  781. resolve_annotation(E);
  782. E->apply(parser, member.signal);
  783. }
  784. } break;
  785. case GDScriptParser::ClassNode::Member::ENUM: {
  786. check_class_member_name_conflict(p_class, member.m_enum->identifier->name, member.m_enum);
  787. member.m_enum->set_datatype(resolving_datatype);
  788. GDScriptParser::DataType enum_type = make_enum_type(member.m_enum->identifier->name, p_class->fqcn, true);
  789. const GDScriptParser::EnumNode *prev_enum = current_enum;
  790. current_enum = member.m_enum;
  791. Dictionary dictionary;
  792. for (int j = 0; j < member.m_enum->values.size(); j++) {
  793. GDScriptParser::EnumNode::Value &element = member.m_enum->values.write[j];
  794. if (element.custom_value) {
  795. reduce_expression(element.custom_value);
  796. if (!element.custom_value->is_constant) {
  797. push_error(R"(Enum values must be constant.)", element.custom_value);
  798. } else if (element.custom_value->reduced_value.get_type() != Variant::INT) {
  799. push_error(R"(Enum values must be integers.)", element.custom_value);
  800. } else {
  801. element.value = element.custom_value->reduced_value;
  802. element.resolved = true;
  803. }
  804. } else {
  805. if (element.index > 0) {
  806. element.value = element.parent_enum->values[element.index - 1].value + 1;
  807. } else {
  808. element.value = 0;
  809. }
  810. element.resolved = true;
  811. }
  812. enum_type.enum_values[element.identifier->name] = element.value;
  813. dictionary[String(element.identifier->name)] = element.value;
  814. }
  815. current_enum = prev_enum;
  816. dictionary.make_read_only();
  817. member.m_enum->set_datatype(enum_type);
  818. member.m_enum->dictionary = dictionary;
  819. // Apply annotations.
  820. for (GDScriptParser::AnnotationNode *&E : member.m_enum->annotations) {
  821. resolve_annotation(E);
  822. E->apply(parser, member.m_enum);
  823. }
  824. } break;
  825. case GDScriptParser::ClassNode::Member::FUNCTION:
  826. for (GDScriptParser::AnnotationNode *&E : member.function->annotations) {
  827. resolve_annotation(E);
  828. E->apply(parser, member.function);
  829. }
  830. resolve_function_signature(member.function, p_source);
  831. break;
  832. case GDScriptParser::ClassNode::Member::ENUM_VALUE: {
  833. member.enum_value.identifier->set_datatype(resolving_datatype);
  834. if (member.enum_value.custom_value) {
  835. check_class_member_name_conflict(p_class, member.enum_value.identifier->name, member.enum_value.custom_value);
  836. const GDScriptParser::EnumNode *prev_enum = current_enum;
  837. current_enum = member.enum_value.parent_enum;
  838. reduce_expression(member.enum_value.custom_value);
  839. current_enum = prev_enum;
  840. if (!member.enum_value.custom_value->is_constant) {
  841. push_error(R"(Enum values must be constant.)", member.enum_value.custom_value);
  842. } else if (member.enum_value.custom_value->reduced_value.get_type() != Variant::INT) {
  843. push_error(R"(Enum values must be integers.)", member.enum_value.custom_value);
  844. } else {
  845. member.enum_value.value = member.enum_value.custom_value->reduced_value;
  846. member.enum_value.resolved = true;
  847. }
  848. } else {
  849. check_class_member_name_conflict(p_class, member.enum_value.identifier->name, member.enum_value.parent_enum);
  850. if (member.enum_value.index > 0) {
  851. const GDScriptParser::EnumNode::Value &prev_value = member.enum_value.parent_enum->values[member.enum_value.index - 1];
  852. resolve_class_member(p_class, prev_value.identifier->name, member.enum_value.identifier);
  853. member.enum_value.value = prev_value.value + 1;
  854. } else {
  855. member.enum_value.value = 0;
  856. }
  857. member.enum_value.resolved = true;
  858. }
  859. // Also update the original references.
  860. member.enum_value.parent_enum->values.set(member.enum_value.index, member.enum_value);
  861. member.enum_value.identifier->set_datatype(make_enum_type(UNNAMED_ENUM, p_class->fqcn, false));
  862. } break;
  863. case GDScriptParser::ClassNode::Member::CLASS:
  864. check_class_member_name_conflict(p_class, member.m_class->identifier->name, member.m_class);
  865. // If it's already resolving, that's ok.
  866. if (!member.m_class->base_type.is_resolving()) {
  867. resolve_class_inheritance(member.m_class, p_source);
  868. }
  869. break;
  870. case GDScriptParser::ClassNode::Member::GROUP:
  871. // No-op, but needed to silence warnings.
  872. break;
  873. case GDScriptParser::ClassNode::Member::UNDEFINED:
  874. ERR_PRINT("Trying to resolve undefined member.");
  875. break;
  876. }
  877. #ifdef DEBUG_ENABLED
  878. parser->ignored_warnings = previously_ignored_warnings;
  879. #endif
  880. }
  881. parser->current_class = previous_class;
  882. }
  883. void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_class, const GDScriptParser::Node *p_source) {
  884. if (p_source == nullptr && parser->has_class(p_class)) {
  885. p_source = p_class;
  886. }
  887. if (!p_class->resolved_interface) {
  888. if (!parser->has_class(p_class)) {
  889. String script_path = p_class->get_datatype().script_path;
  890. Ref<GDScriptParserRef> parser_ref = get_parser_for(script_path);
  891. if (parser_ref.is_null()) {
  892. push_error(vformat(R"(Could not find script "%s".)", script_path), p_source);
  893. return;
  894. }
  895. Error err = parser_ref->raise_status(GDScriptParserRef::PARSED);
  896. if (err) {
  897. push_error(vformat(R"(Could not resolve script "%s": %s.)", script_path, error_names[err]), p_source);
  898. return;
  899. }
  900. ERR_FAIL_COND_MSG(!parser_ref->get_parser()->has_class(p_class), R"(Parser bug: Mismatched external parser.)");
  901. GDScriptAnalyzer *other_analyzer = parser_ref->get_analyzer();
  902. GDScriptParser *other_parser = parser_ref->get_parser();
  903. int error_count = other_parser->errors.size();
  904. other_analyzer->resolve_class_interface(p_class);
  905. if (other_parser->errors.size() > error_count) {
  906. push_error(vformat(R"(Could not resolve class "%s".)", p_class->fqcn), p_source);
  907. }
  908. return;
  909. }
  910. p_class->resolved_interface = true;
  911. if (resolve_class_inheritance(p_class) != OK) {
  912. return;
  913. }
  914. GDScriptParser::DataType base_type = p_class->base_type;
  915. if (base_type.kind == GDScriptParser::DataType::CLASS) {
  916. GDScriptParser::ClassNode *base_class = base_type.class_type;
  917. resolve_class_interface(base_class, p_class);
  918. }
  919. for (int i = 0; i < p_class->members.size(); i++) {
  920. resolve_class_member(p_class, i);
  921. }
  922. }
  923. }
  924. void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_class, bool p_recursive) {
  925. resolve_class_interface(p_class);
  926. if (p_recursive) {
  927. for (int i = 0; i < p_class->members.size(); i++) {
  928. GDScriptParser::ClassNode::Member member = p_class->members[i];
  929. if (member.type == GDScriptParser::ClassNode::Member::CLASS) {
  930. resolve_class_interface(member.m_class, true);
  931. }
  932. }
  933. }
  934. }
  935. void GDScriptAnalyzer::resolve_class_body(GDScriptParser::ClassNode *p_class, const GDScriptParser::Node *p_source) {
  936. if (p_source == nullptr && parser->has_class(p_class)) {
  937. p_source = p_class;
  938. }
  939. if (p_class->resolved_body) {
  940. return;
  941. }
  942. if (!parser->has_class(p_class)) {
  943. String script_path = p_class->get_datatype().script_path;
  944. Ref<GDScriptParserRef> parser_ref = get_parser_for(script_path);
  945. if (parser_ref.is_null()) {
  946. push_error(vformat(R"(Could not find script "%s".)", script_path), p_source);
  947. return;
  948. }
  949. Error err = parser_ref->raise_status(GDScriptParserRef::PARSED);
  950. if (err) {
  951. push_error(vformat(R"(Could not resolve script "%s": %s.)", script_path, error_names[err]), p_source);
  952. return;
  953. }
  954. ERR_FAIL_COND_MSG(!parser_ref->get_parser()->has_class(p_class), R"(Parser bug: Mismatched external parser.)");
  955. GDScriptAnalyzer *other_analyzer = parser_ref->get_analyzer();
  956. GDScriptParser *other_parser = parser_ref->get_parser();
  957. int error_count = other_parser->errors.size();
  958. other_analyzer->resolve_class_body(p_class);
  959. if (other_parser->errors.size() > error_count) {
  960. push_error(vformat(R"(Could not resolve class "%s".)", p_class->fqcn), p_source);
  961. }
  962. return;
  963. }
  964. p_class->resolved_body = true;
  965. GDScriptParser::ClassNode *previous_class = parser->current_class;
  966. parser->current_class = p_class;
  967. resolve_class_interface(p_class, p_source);
  968. GDScriptParser::DataType base_type = p_class->base_type;
  969. if (base_type.kind == GDScriptParser::DataType::CLASS) {
  970. GDScriptParser::ClassNode *base_class = base_type.class_type;
  971. resolve_class_body(base_class, p_class);
  972. }
  973. // Do functions, properties, and groups now.
  974. for (int i = 0; i < p_class->members.size(); i++) {
  975. GDScriptParser::ClassNode::Member member = p_class->members[i];
  976. if (member.type == GDScriptParser::ClassNode::Member::FUNCTION) {
  977. // Apply annotations.
  978. for (GDScriptParser::AnnotationNode *&E : member.function->annotations) {
  979. resolve_annotation(E);
  980. E->apply(parser, member.function);
  981. }
  982. resolve_function_body(member.function);
  983. } else if (member.type == GDScriptParser::ClassNode::Member::VARIABLE && member.variable->property != GDScriptParser::VariableNode::PROP_NONE) {
  984. if (member.variable->property == GDScriptParser::VariableNode::PROP_INLINE) {
  985. if (member.variable->getter != nullptr) {
  986. member.variable->getter->set_datatype(member.variable->datatype);
  987. resolve_function_body(member.variable->getter);
  988. }
  989. if (member.variable->setter != nullptr) {
  990. resolve_function_signature(member.variable->setter);
  991. if (member.variable->setter->parameters.size() > 0) {
  992. member.variable->setter->parameters[0]->datatype_specifier = member.variable->datatype_specifier;
  993. member.variable->setter->parameters[0]->set_datatype(member.get_datatype());
  994. }
  995. resolve_function_body(member.variable->setter);
  996. }
  997. }
  998. } else if (member.type == GDScriptParser::ClassNode::Member::GROUP) {
  999. // Apply annotation (`@export_{category,group,subgroup}`).
  1000. resolve_annotation(member.annotation);
  1001. member.annotation->apply(parser, nullptr);
  1002. }
  1003. }
  1004. // Check unused variables and datatypes of property getters and setters.
  1005. for (int i = 0; i < p_class->members.size(); i++) {
  1006. GDScriptParser::ClassNode::Member member = p_class->members[i];
  1007. if (member.type == GDScriptParser::ClassNode::Member::VARIABLE) {
  1008. #ifdef DEBUG_ENABLED
  1009. HashSet<GDScriptWarning::Code> previously_ignored_warnings = parser->ignored_warnings;
  1010. for (GDScriptWarning::Code ignored_warning : member.variable->ignored_warnings) {
  1011. parser->ignored_warnings.insert(ignored_warning);
  1012. }
  1013. if (member.variable->usages == 0 && String(member.variable->identifier->name).begins_with("_")) {
  1014. parser->push_warning(member.variable->identifier, GDScriptWarning::UNUSED_PRIVATE_CLASS_VARIABLE, member.variable->identifier->name);
  1015. }
  1016. #endif
  1017. if (member.variable->property == GDScriptParser::VariableNode::PROP_SETGET) {
  1018. GDScriptParser::FunctionNode *getter_function = nullptr;
  1019. GDScriptParser::FunctionNode *setter_function = nullptr;
  1020. bool has_valid_getter = false;
  1021. bool has_valid_setter = false;
  1022. if (member.variable->getter_pointer != nullptr) {
  1023. if (p_class->has_function(member.variable->getter_pointer->name)) {
  1024. getter_function = p_class->get_member(member.variable->getter_pointer->name).function;
  1025. }
  1026. if (getter_function == nullptr) {
  1027. push_error(vformat(R"(Getter "%s" not found.)", member.variable->getter_pointer->name), member.variable);
  1028. } else {
  1029. GDScriptParser::DataType return_datatype = getter_function->datatype;
  1030. if (getter_function->return_type != nullptr) {
  1031. return_datatype = getter_function->return_type->datatype;
  1032. return_datatype.is_meta_type = false;
  1033. }
  1034. if (getter_function->parameters.size() != 0 || return_datatype.has_no_type()) {
  1035. push_error(vformat(R"(Function "%s" cannot be used as getter because of its signature.)", getter_function->identifier->name), member.variable);
  1036. } else if (!is_type_compatible(member.variable->datatype, return_datatype, true)) {
  1037. push_error(vformat(R"(Function with return type "%s" cannot be used as getter for a property of type "%s".)", return_datatype.to_string(), member.variable->datatype.to_string()), member.variable);
  1038. } else {
  1039. has_valid_getter = true;
  1040. #ifdef DEBUG_ENABLED
  1041. if (member.variable->datatype.builtin_type == Variant::INT && return_datatype.builtin_type == Variant::FLOAT) {
  1042. parser->push_warning(member.variable, GDScriptWarning::NARROWING_CONVERSION);
  1043. }
  1044. #endif
  1045. }
  1046. }
  1047. }
  1048. if (member.variable->setter_pointer != nullptr) {
  1049. if (p_class->has_function(member.variable->setter_pointer->name)) {
  1050. setter_function = p_class->get_member(member.variable->setter_pointer->name).function;
  1051. }
  1052. if (setter_function == nullptr) {
  1053. push_error(vformat(R"(Setter "%s" not found.)", member.variable->setter_pointer->name), member.variable);
  1054. } else if (setter_function->parameters.size() != 1) {
  1055. push_error(vformat(R"(Function "%s" cannot be used as setter because of its signature.)", setter_function->identifier->name), member.variable);
  1056. } else if (!is_type_compatible(member.variable->datatype, setter_function->parameters[0]->datatype, true)) {
  1057. push_error(vformat(R"(Function with argument type "%s" cannot be used as setter for a property of type "%s".)", setter_function->parameters[0]->datatype.to_string(), member.variable->datatype.to_string()), member.variable);
  1058. } else {
  1059. has_valid_setter = true;
  1060. #ifdef DEBUG_ENABLED
  1061. if (member.variable->datatype.builtin_type == Variant::FLOAT && setter_function->parameters[0]->datatype.builtin_type == Variant::INT) {
  1062. parser->push_warning(member.variable, GDScriptWarning::NARROWING_CONVERSION);
  1063. }
  1064. #endif
  1065. }
  1066. }
  1067. if (member.variable->datatype.is_variant() && has_valid_getter && has_valid_setter) {
  1068. if (!is_type_compatible(getter_function->datatype, setter_function->parameters[0]->datatype, true)) {
  1069. push_error(vformat(R"(Getter with type "%s" cannot be used along with setter of type "%s".)", getter_function->datatype.to_string(), setter_function->parameters[0]->datatype.to_string()), member.variable);
  1070. }
  1071. }
  1072. #ifdef DEBUG_ENABLED
  1073. parser->ignored_warnings = previously_ignored_warnings;
  1074. #endif // DEBUG_ENABLED
  1075. }
  1076. }
  1077. }
  1078. parser->current_class = previous_class;
  1079. }
  1080. void GDScriptAnalyzer::resolve_class_body(GDScriptParser::ClassNode *p_class, bool p_recursive) {
  1081. resolve_class_body(p_class);
  1082. if (p_recursive) {
  1083. for (int i = 0; i < p_class->members.size(); i++) {
  1084. GDScriptParser::ClassNode::Member member = p_class->members[i];
  1085. if (member.type == GDScriptParser::ClassNode::Member::CLASS) {
  1086. resolve_class_body(member.m_class, true);
  1087. }
  1088. }
  1089. }
  1090. }
  1091. void GDScriptAnalyzer::resolve_node(GDScriptParser::Node *p_node, bool p_is_root) {
  1092. ERR_FAIL_COND_MSG(p_node == nullptr, "Trying to resolve type of a null node.");
  1093. switch (p_node->type) {
  1094. case GDScriptParser::Node::NONE:
  1095. break; // Unreachable.
  1096. case GDScriptParser::Node::CLASS:
  1097. if (OK == resolve_class_inheritance(static_cast<GDScriptParser::ClassNode *>(p_node), true)) {
  1098. resolve_class_interface(static_cast<GDScriptParser::ClassNode *>(p_node), true);
  1099. resolve_class_body(static_cast<GDScriptParser::ClassNode *>(p_node), true);
  1100. }
  1101. break;
  1102. case GDScriptParser::Node::CONSTANT:
  1103. resolve_constant(static_cast<GDScriptParser::ConstantNode *>(p_node), true);
  1104. break;
  1105. case GDScriptParser::Node::FOR:
  1106. resolve_for(static_cast<GDScriptParser::ForNode *>(p_node));
  1107. break;
  1108. case GDScriptParser::Node::IF:
  1109. resolve_if(static_cast<GDScriptParser::IfNode *>(p_node));
  1110. break;
  1111. case GDScriptParser::Node::SUITE:
  1112. resolve_suite(static_cast<GDScriptParser::SuiteNode *>(p_node));
  1113. break;
  1114. case GDScriptParser::Node::VARIABLE:
  1115. resolve_variable(static_cast<GDScriptParser::VariableNode *>(p_node), true);
  1116. break;
  1117. case GDScriptParser::Node::WHILE:
  1118. resolve_while(static_cast<GDScriptParser::WhileNode *>(p_node));
  1119. break;
  1120. case GDScriptParser::Node::ANNOTATION:
  1121. resolve_annotation(static_cast<GDScriptParser::AnnotationNode *>(p_node));
  1122. break;
  1123. case GDScriptParser::Node::ASSERT:
  1124. resolve_assert(static_cast<GDScriptParser::AssertNode *>(p_node));
  1125. break;
  1126. case GDScriptParser::Node::MATCH:
  1127. resolve_match(static_cast<GDScriptParser::MatchNode *>(p_node));
  1128. break;
  1129. case GDScriptParser::Node::MATCH_BRANCH:
  1130. resolve_match_branch(static_cast<GDScriptParser::MatchBranchNode *>(p_node), nullptr);
  1131. break;
  1132. case GDScriptParser::Node::PARAMETER:
  1133. resolve_parameter(static_cast<GDScriptParser::ParameterNode *>(p_node));
  1134. break;
  1135. case GDScriptParser::Node::PATTERN:
  1136. resolve_match_pattern(static_cast<GDScriptParser::PatternNode *>(p_node), nullptr);
  1137. break;
  1138. case GDScriptParser::Node::RETURN:
  1139. resolve_return(static_cast<GDScriptParser::ReturnNode *>(p_node));
  1140. break;
  1141. case GDScriptParser::Node::TYPE:
  1142. resolve_datatype(static_cast<GDScriptParser::TypeNode *>(p_node));
  1143. break;
  1144. // Resolving expression is the same as reducing them.
  1145. case GDScriptParser::Node::ARRAY:
  1146. case GDScriptParser::Node::ASSIGNMENT:
  1147. case GDScriptParser::Node::AWAIT:
  1148. case GDScriptParser::Node::BINARY_OPERATOR:
  1149. case GDScriptParser::Node::CALL:
  1150. case GDScriptParser::Node::CAST:
  1151. case GDScriptParser::Node::DICTIONARY:
  1152. case GDScriptParser::Node::GET_NODE:
  1153. case GDScriptParser::Node::IDENTIFIER:
  1154. case GDScriptParser::Node::LAMBDA:
  1155. case GDScriptParser::Node::LITERAL:
  1156. case GDScriptParser::Node::PRELOAD:
  1157. case GDScriptParser::Node::SELF:
  1158. case GDScriptParser::Node::SUBSCRIPT:
  1159. case GDScriptParser::Node::TERNARY_OPERATOR:
  1160. case GDScriptParser::Node::UNARY_OPERATOR:
  1161. reduce_expression(static_cast<GDScriptParser::ExpressionNode *>(p_node), p_is_root);
  1162. break;
  1163. case GDScriptParser::Node::BREAK:
  1164. case GDScriptParser::Node::BREAKPOINT:
  1165. case GDScriptParser::Node::CONTINUE:
  1166. case GDScriptParser::Node::ENUM:
  1167. case GDScriptParser::Node::FUNCTION:
  1168. case GDScriptParser::Node::PASS:
  1169. case GDScriptParser::Node::SIGNAL:
  1170. // Nothing to do.
  1171. break;
  1172. }
  1173. }
  1174. void GDScriptAnalyzer::resolve_annotation(GDScriptParser::AnnotationNode *p_annotation) {
  1175. ERR_FAIL_COND_MSG(!parser->valid_annotations.has(p_annotation->name), vformat(R"(Annotation "%s" not found to validate.)", p_annotation->name));
  1176. if (p_annotation->is_resolved) {
  1177. return;
  1178. }
  1179. p_annotation->is_resolved = true;
  1180. const MethodInfo &annotation_info = parser->valid_annotations[p_annotation->name].info;
  1181. const List<PropertyInfo>::Element *E = annotation_info.arguments.front();
  1182. for (int i = 0; i < p_annotation->arguments.size(); i++) {
  1183. GDScriptParser::ExpressionNode *argument = p_annotation->arguments[i];
  1184. const PropertyInfo &argument_info = E->get();
  1185. if (E->next() != nullptr) {
  1186. E = E->next();
  1187. }
  1188. reduce_expression(argument);
  1189. if (!argument->is_constant) {
  1190. push_error(vformat(R"(Argument %d of annotation "%s" isn't a constant expression.)", i + 1, p_annotation->name), argument);
  1191. return;
  1192. }
  1193. Variant value = argument->reduced_value;
  1194. if (value.get_type() != argument_info.type) {
  1195. #ifdef DEBUG_ENABLED
  1196. if (argument_info.type == Variant::INT && value.get_type() == Variant::FLOAT) {
  1197. parser->push_warning(argument, GDScriptWarning::NARROWING_CONVERSION);
  1198. }
  1199. #endif
  1200. if (!Variant::can_convert_strict(value.get_type(), argument_info.type)) {
  1201. push_error(vformat(R"(Invalid argument for annotation "%s": argument %d should be "%s" but is "%s".)", p_annotation->name, i + 1, Variant::get_type_name(argument_info.type), argument->get_datatype().to_string()), argument);
  1202. return;
  1203. }
  1204. Variant converted_to;
  1205. const Variant *converted_from = &value;
  1206. Callable::CallError call_error;
  1207. Variant::construct(argument_info.type, converted_to, &converted_from, 1, call_error);
  1208. if (call_error.error != Callable::CallError::CALL_OK) {
  1209. push_error(vformat(R"(Cannot convert argument %d of annotation "%s" from "%s" to "%s".)", i + 1, p_annotation->name, Variant::get_type_name(value.get_type()), Variant::get_type_name(argument_info.type)), argument);
  1210. return;
  1211. }
  1212. value = converted_to;
  1213. }
  1214. p_annotation->resolved_arguments.push_back(value);
  1215. }
  1216. }
  1217. void GDScriptAnalyzer::resolve_function_signature(GDScriptParser::FunctionNode *p_function, const GDScriptParser::Node *p_source, bool p_is_lambda) {
  1218. if (p_source == nullptr) {
  1219. p_source = p_function;
  1220. }
  1221. StringName function_name = p_function->identifier != nullptr ? p_function->identifier->name : StringName();
  1222. if (p_function->get_datatype().is_resolving()) {
  1223. push_error(vformat(R"(Could not resolve function "%s": Cyclic reference.)", function_name), p_source);
  1224. return;
  1225. }
  1226. if (p_function->resolved_signature) {
  1227. return;
  1228. }
  1229. p_function->resolved_signature = true;
  1230. #ifdef DEBUG_ENABLED
  1231. HashSet<GDScriptWarning::Code> previously_ignored_warnings = parser->ignored_warnings;
  1232. for (GDScriptWarning::Code ignored_warning : p_function->ignored_warnings) {
  1233. parser->ignored_warnings.insert(ignored_warning);
  1234. }
  1235. #endif
  1236. GDScriptParser::FunctionNode *previous_function = parser->current_function;
  1237. parser->current_function = p_function;
  1238. GDScriptParser::DataType prev_datatype = p_function->get_datatype();
  1239. GDScriptParser::DataType resolving_datatype;
  1240. resolving_datatype.kind = GDScriptParser::DataType::RESOLVING;
  1241. p_function->set_datatype(resolving_datatype);
  1242. #ifdef TOOLS_ENABLED
  1243. int default_value_count = 0;
  1244. #endif // TOOLS_ENABLED
  1245. for (int i = 0; i < p_function->parameters.size(); i++) {
  1246. resolve_parameter(p_function->parameters[i]);
  1247. #ifdef DEBUG_ENABLED
  1248. if (p_function->parameters[i]->usages == 0 && !String(p_function->parameters[i]->identifier->name).begins_with("_")) {
  1249. parser->push_warning(p_function->parameters[i]->identifier, GDScriptWarning::UNUSED_PARAMETER, function_name, p_function->parameters[i]->identifier->name);
  1250. }
  1251. is_shadowing(p_function->parameters[i]->identifier, "function parameter");
  1252. #endif // DEBUG_ENABLED
  1253. #ifdef TOOLS_ENABLED
  1254. if (p_function->parameters[i]->initializer) {
  1255. default_value_count++;
  1256. if (p_function->parameters[i]->initializer->is_constant) {
  1257. p_function->default_arg_values.push_back(p_function->parameters[i]->initializer->reduced_value);
  1258. } else {
  1259. p_function->default_arg_values.push_back(Variant()); // Prevent shift.
  1260. }
  1261. }
  1262. #endif // TOOLS_ENABLED
  1263. }
  1264. if (!p_is_lambda && function_name == GDScriptLanguage::get_singleton()->strings._init) {
  1265. // Constructor.
  1266. GDScriptParser::DataType return_type = parser->current_class->get_datatype();
  1267. return_type.is_meta_type = false;
  1268. p_function->set_datatype(return_type);
  1269. if (p_function->return_type) {
  1270. GDScriptParser::DataType declared_return = resolve_datatype(p_function->return_type);
  1271. if (declared_return.kind != GDScriptParser::DataType::BUILTIN || declared_return.builtin_type != Variant::NIL) {
  1272. push_error("Constructor cannot have an explicit return type.", p_function->return_type);
  1273. }
  1274. }
  1275. } else {
  1276. if (p_function->return_type != nullptr) {
  1277. p_function->set_datatype(type_from_metatype(resolve_datatype(p_function->return_type)));
  1278. } else {
  1279. // In case the function is not typed, we can safely assume it's a Variant, so it's okay to mark as "inferred" here.
  1280. // It's not "undetected" to not mix up with unknown functions.
  1281. GDScriptParser::DataType return_type;
  1282. return_type.type_source = GDScriptParser::DataType::INFERRED;
  1283. return_type.kind = GDScriptParser::DataType::VARIANT;
  1284. p_function->set_datatype(return_type);
  1285. }
  1286. #ifdef TOOLS_ENABLED
  1287. // Check if the function signature matches the parent. If not it's an error since it breaks polymorphism.
  1288. // Not for the constructor which can vary in signature.
  1289. GDScriptParser::DataType base_type = parser->current_class->base_type;
  1290. GDScriptParser::DataType parent_return_type;
  1291. List<GDScriptParser::DataType> parameters_types;
  1292. int default_par_count = 0;
  1293. bool is_static = false;
  1294. bool is_vararg = false;
  1295. StringName native_base;
  1296. if (!p_is_lambda && get_function_signature(p_function, false, base_type, function_name, parent_return_type, parameters_types, default_par_count, is_static, is_vararg, &native_base)) {
  1297. bool valid = p_function->is_static == is_static;
  1298. valid = valid && parent_return_type == p_function->get_datatype();
  1299. int par_count_diff = p_function->parameters.size() - parameters_types.size();
  1300. valid = valid && par_count_diff >= 0;
  1301. valid = valid && default_value_count >= default_par_count + par_count_diff;
  1302. int i = 0;
  1303. for (const GDScriptParser::DataType &par_type : parameters_types) {
  1304. valid = valid && par_type == p_function->parameters[i++]->get_datatype();
  1305. }
  1306. if (!valid) {
  1307. // Compute parent signature as a string to show in the error message.
  1308. String parent_signature = String(function_name) + "(";
  1309. int j = 0;
  1310. for (const GDScriptParser::DataType &par_type : parameters_types) {
  1311. if (j > 0) {
  1312. parent_signature += ", ";
  1313. }
  1314. String parameter = par_type.to_string();
  1315. if (parameter == "null") {
  1316. parameter = "Variant";
  1317. }
  1318. parent_signature += parameter;
  1319. if (j >= parameters_types.size() - default_par_count) {
  1320. parent_signature += " = <default>";
  1321. }
  1322. j++;
  1323. }
  1324. parent_signature += ") -> ";
  1325. const String return_type = parent_return_type.is_hard_type() ? parent_return_type.to_string() : "Variant";
  1326. if (return_type == "null") {
  1327. parent_signature += "void";
  1328. } else {
  1329. parent_signature += return_type;
  1330. }
  1331. push_error(vformat(R"(The function signature doesn't match the parent. Parent signature is "%s".)", parent_signature), p_function);
  1332. }
  1333. #ifdef DEBUG_ENABLED
  1334. if (native_base != StringName()) {
  1335. parser->push_warning(p_function, GDScriptWarning::NATIVE_METHOD_OVERRIDE, function_name, native_base);
  1336. }
  1337. #endif
  1338. }
  1339. #endif // TOOLS_ENABLED
  1340. }
  1341. if (p_function->get_datatype().is_resolving()) {
  1342. p_function->set_datatype(prev_datatype);
  1343. }
  1344. #ifdef DEBUG_ENABLED
  1345. parser->ignored_warnings = previously_ignored_warnings;
  1346. #endif
  1347. parser->current_function = previous_function;
  1348. }
  1349. void GDScriptAnalyzer::resolve_function_body(GDScriptParser::FunctionNode *p_function, bool p_is_lambda) {
  1350. if (p_function->resolved_body) {
  1351. return;
  1352. }
  1353. p_function->resolved_body = true;
  1354. #ifdef DEBUG_ENABLED
  1355. HashSet<GDScriptWarning::Code> previously_ignored_warnings = parser->ignored_warnings;
  1356. for (GDScriptWarning::Code ignored_warning : p_function->ignored_warnings) {
  1357. parser->ignored_warnings.insert(ignored_warning);
  1358. }
  1359. #endif
  1360. GDScriptParser::FunctionNode *previous_function = parser->current_function;
  1361. parser->current_function = p_function;
  1362. resolve_suite(p_function->body);
  1363. GDScriptParser::DataType return_type = p_function->body->get_datatype();
  1364. if (!p_function->get_datatype().is_hard_type() && return_type.is_set()) {
  1365. // Use the suite inferred type if return isn't explicitly set.
  1366. return_type.type_source = GDScriptParser::DataType::INFERRED;
  1367. p_function->set_datatype(p_function->body->get_datatype());
  1368. } else if (p_function->get_datatype().is_hard_type() && (p_function->get_datatype().kind != GDScriptParser::DataType::BUILTIN || p_function->get_datatype().builtin_type != Variant::NIL)) {
  1369. if (!p_function->body->has_return && (p_is_lambda || p_function->identifier->name != GDScriptLanguage::get_singleton()->strings._init)) {
  1370. push_error(R"(Not all code paths return a value.)", p_function);
  1371. }
  1372. }
  1373. #ifdef DEBUG_ENABLED
  1374. parser->ignored_warnings = previously_ignored_warnings;
  1375. #endif
  1376. parser->current_function = previous_function;
  1377. }
  1378. void GDScriptAnalyzer::decide_suite_type(GDScriptParser::Node *p_suite, GDScriptParser::Node *p_statement) {
  1379. if (p_statement == nullptr) {
  1380. return;
  1381. }
  1382. switch (p_statement->type) {
  1383. case GDScriptParser::Node::IF:
  1384. case GDScriptParser::Node::FOR:
  1385. case GDScriptParser::Node::MATCH:
  1386. case GDScriptParser::Node::PATTERN:
  1387. case GDScriptParser::Node::RETURN:
  1388. case GDScriptParser::Node::WHILE:
  1389. // Use return or nested suite type as this suite type.
  1390. if (p_suite->get_datatype().is_set() && (p_suite->get_datatype() != p_statement->get_datatype())) {
  1391. // Mixed types.
  1392. // TODO: This could use the common supertype instead.
  1393. p_suite->datatype.kind = GDScriptParser::DataType::VARIANT;
  1394. p_suite->datatype.type_source = GDScriptParser::DataType::UNDETECTED;
  1395. } else {
  1396. p_suite->set_datatype(p_statement->get_datatype());
  1397. p_suite->datatype.type_source = GDScriptParser::DataType::INFERRED;
  1398. }
  1399. break;
  1400. default:
  1401. break;
  1402. }
  1403. }
  1404. void GDScriptAnalyzer::resolve_suite(GDScriptParser::SuiteNode *p_suite) {
  1405. for (int i = 0; i < p_suite->statements.size(); i++) {
  1406. GDScriptParser::Node *stmt = p_suite->statements[i];
  1407. // Apply annotations.
  1408. for (GDScriptParser::AnnotationNode *&E : stmt->annotations) {
  1409. resolve_annotation(E);
  1410. E->apply(parser, stmt);
  1411. }
  1412. #ifdef DEBUG_ENABLED
  1413. HashSet<GDScriptWarning::Code> previously_ignored_warnings = parser->ignored_warnings;
  1414. for (GDScriptWarning::Code ignored_warning : stmt->ignored_warnings) {
  1415. parser->ignored_warnings.insert(ignored_warning);
  1416. }
  1417. #endif // DEBUG_ENABLED
  1418. resolve_node(stmt);
  1419. #ifdef DEBUG_ENABLED
  1420. parser->ignored_warnings = previously_ignored_warnings;
  1421. #endif // DEBUG_ENABLED
  1422. decide_suite_type(p_suite, stmt);
  1423. }
  1424. }
  1425. void GDScriptAnalyzer::resolve_assignable(GDScriptParser::AssignableNode *p_assignable, const char *p_kind) {
  1426. GDScriptParser::DataType type;
  1427. type.kind = GDScriptParser::DataType::VARIANT;
  1428. bool is_constant = p_assignable->type == GDScriptParser::Node::CONSTANT;
  1429. GDScriptParser::DataType specified_type;
  1430. bool has_specified_type = p_assignable->datatype_specifier != nullptr;
  1431. if (has_specified_type) {
  1432. specified_type = type_from_metatype(resolve_datatype(p_assignable->datatype_specifier));
  1433. type = specified_type;
  1434. }
  1435. if (p_assignable->initializer != nullptr) {
  1436. reduce_expression(p_assignable->initializer);
  1437. if (p_assignable->initializer->type == GDScriptParser::Node::ARRAY) {
  1438. GDScriptParser::ArrayNode *array = static_cast<GDScriptParser::ArrayNode *>(p_assignable->initializer);
  1439. if (has_specified_type && specified_type.has_container_element_type()) {
  1440. update_array_literal_element_type(array, specified_type.get_container_element_type());
  1441. }
  1442. }
  1443. if (is_constant && !p_assignable->initializer->is_constant) {
  1444. bool is_initializer_value_reduced = false;
  1445. Variant initializer_value = make_expression_reduced_value(p_assignable->initializer, is_initializer_value_reduced);
  1446. if (is_initializer_value_reduced) {
  1447. p_assignable->initializer->is_constant = true;
  1448. p_assignable->initializer->reduced_value = initializer_value;
  1449. } else {
  1450. push_error(vformat(R"(Assigned value for %s "%s" isn't a constant expression.)", p_kind, p_assignable->identifier->name), p_assignable->initializer);
  1451. }
  1452. }
  1453. if (has_specified_type && p_assignable->initializer->is_constant) {
  1454. update_const_expression_builtin_type(p_assignable->initializer, specified_type, "assign");
  1455. }
  1456. GDScriptParser::DataType initializer_type = p_assignable->initializer->get_datatype();
  1457. if (p_assignable->infer_datatype) {
  1458. if (!initializer_type.is_set() || initializer_type.has_no_type() || !initializer_type.is_hard_type()) {
  1459. push_error(vformat(R"(Cannot infer the type of "%s" %s because the value doesn't have a set type.)", p_assignable->identifier->name, p_kind), p_assignable->initializer);
  1460. } else if (initializer_type.kind == GDScriptParser::DataType::BUILTIN && initializer_type.builtin_type == Variant::NIL && !is_constant) {
  1461. push_error(vformat(R"(Cannot infer the type of "%s" %s because the value is "null".)", p_assignable->identifier->name, p_kind), p_assignable->initializer);
  1462. }
  1463. #ifdef DEBUG_ENABLED
  1464. if (initializer_type.is_hard_type() && initializer_type.is_variant()) {
  1465. parser->push_warning(p_assignable, GDScriptWarning::INFERENCE_ON_VARIANT, p_kind);
  1466. }
  1467. #endif
  1468. } else {
  1469. if (!initializer_type.is_set()) {
  1470. push_error(vformat(R"(Could not resolve type for %s "%s".)", p_kind, p_assignable->identifier->name), p_assignable->initializer);
  1471. }
  1472. }
  1473. if (!has_specified_type) {
  1474. type = initializer_type;
  1475. if (!type.is_set() || (type.is_hard_type() && type.kind == GDScriptParser::DataType::BUILTIN && type.builtin_type == Variant::NIL && !is_constant)) {
  1476. type.kind = GDScriptParser::DataType::VARIANT;
  1477. }
  1478. if (p_assignable->infer_datatype || is_constant) {
  1479. type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  1480. } else {
  1481. type.type_source = GDScriptParser::DataType::INFERRED;
  1482. }
  1483. } else if (!specified_type.is_variant()) {
  1484. if (initializer_type.is_variant() || !initializer_type.is_hard_type()) {
  1485. mark_node_unsafe(p_assignable->initializer);
  1486. p_assignable->use_conversion_assign = true;
  1487. if (!initializer_type.is_variant() && !is_type_compatible(specified_type, initializer_type, true, p_assignable->initializer)) {
  1488. downgrade_node_type_source(p_assignable->initializer);
  1489. }
  1490. } else if (!is_type_compatible(specified_type, initializer_type, true, p_assignable->initializer)) {
  1491. if (!is_constant && is_type_compatible(initializer_type, specified_type)) {
  1492. mark_node_unsafe(p_assignable->initializer);
  1493. p_assignable->use_conversion_assign = true;
  1494. } else {
  1495. push_error(vformat(R"(Cannot assign a value of type %s to %s "%s" with specified type %s.)", initializer_type.to_string(), p_kind, p_assignable->identifier->name, specified_type.to_string()), p_assignable->initializer);
  1496. }
  1497. } else if (specified_type.has_container_element_type() && !initializer_type.has_container_element_type()) {
  1498. mark_node_unsafe(p_assignable->initializer);
  1499. #ifdef DEBUG_ENABLED
  1500. } else if (specified_type.builtin_type == Variant::INT && initializer_type.builtin_type == Variant::FLOAT) {
  1501. parser->push_warning(p_assignable->initializer, GDScriptWarning::NARROWING_CONVERSION);
  1502. #endif
  1503. }
  1504. }
  1505. }
  1506. type.is_constant = is_constant;
  1507. p_assignable->set_datatype(type);
  1508. }
  1509. void GDScriptAnalyzer::resolve_variable(GDScriptParser::VariableNode *p_variable, bool p_is_local) {
  1510. static constexpr const char *kind = "variable";
  1511. resolve_assignable(p_variable, kind);
  1512. #ifdef DEBUG_ENABLED
  1513. if (p_is_local) {
  1514. if (p_variable->usages == 0 && !String(p_variable->identifier->name).begins_with("_")) {
  1515. parser->push_warning(p_variable, GDScriptWarning::UNUSED_VARIABLE, p_variable->identifier->name);
  1516. } else if (p_variable->assignments == 0) {
  1517. parser->push_warning(p_variable, GDScriptWarning::UNASSIGNED_VARIABLE, p_variable->identifier->name);
  1518. }
  1519. is_shadowing(p_variable->identifier, kind);
  1520. }
  1521. #endif
  1522. }
  1523. void GDScriptAnalyzer::resolve_constant(GDScriptParser::ConstantNode *p_constant, bool p_is_local) {
  1524. static constexpr const char *kind = "constant";
  1525. resolve_assignable(p_constant, kind);
  1526. #ifdef DEBUG_ENABLED
  1527. if (p_is_local) {
  1528. if (p_constant->usages == 0) {
  1529. parser->push_warning(p_constant, GDScriptWarning::UNUSED_LOCAL_CONSTANT, p_constant->identifier->name);
  1530. }
  1531. is_shadowing(p_constant->identifier, kind);
  1532. }
  1533. #endif
  1534. }
  1535. void GDScriptAnalyzer::resolve_parameter(GDScriptParser::ParameterNode *p_parameter) {
  1536. static constexpr const char *kind = "parameter";
  1537. resolve_assignable(p_parameter, kind);
  1538. }
  1539. void GDScriptAnalyzer::resolve_if(GDScriptParser::IfNode *p_if) {
  1540. reduce_expression(p_if->condition);
  1541. resolve_suite(p_if->true_block);
  1542. p_if->set_datatype(p_if->true_block->get_datatype());
  1543. if (p_if->false_block != nullptr) {
  1544. resolve_suite(p_if->false_block);
  1545. decide_suite_type(p_if, p_if->false_block);
  1546. }
  1547. }
  1548. void GDScriptAnalyzer::resolve_for(GDScriptParser::ForNode *p_for) {
  1549. bool list_resolved = false;
  1550. // Optimize constant range() call to not allocate an array.
  1551. // Use int, Vector2i, Vector3i instead, which also can be used as range iterators.
  1552. if (p_for->list && p_for->list->type == GDScriptParser::Node::CALL) {
  1553. GDScriptParser::CallNode *call = static_cast<GDScriptParser::CallNode *>(p_for->list);
  1554. GDScriptParser::Node::Type callee_type = call->get_callee_type();
  1555. if (callee_type == GDScriptParser::Node::IDENTIFIER) {
  1556. GDScriptParser::IdentifierNode *callee = static_cast<GDScriptParser::IdentifierNode *>(call->callee);
  1557. if (callee->name == "range") {
  1558. list_resolved = true;
  1559. if (call->arguments.size() < 1) {
  1560. push_error(R"*(Invalid call for "range()" function. Expected at least 1 argument, none given.)*", call->callee);
  1561. } else if (call->arguments.size() > 3) {
  1562. push_error(vformat(R"*(Invalid call for "range()" function. Expected at most 3 arguments, %d given.)*", call->arguments.size()), call->callee);
  1563. } else {
  1564. // Now we can optimize it.
  1565. bool all_is_constant = true;
  1566. Vector<Variant> args;
  1567. args.resize(call->arguments.size());
  1568. for (int i = 0; i < call->arguments.size(); i++) {
  1569. reduce_expression(call->arguments[i]);
  1570. if (!call->arguments[i]->is_constant) {
  1571. all_is_constant = false;
  1572. } else if (all_is_constant) {
  1573. args.write[i] = call->arguments[i]->reduced_value;
  1574. }
  1575. GDScriptParser::DataType arg_type = call->arguments[i]->get_datatype();
  1576. if (!arg_type.is_variant()) {
  1577. if (arg_type.kind != GDScriptParser::DataType::BUILTIN) {
  1578. all_is_constant = false;
  1579. push_error(vformat(R"*(Invalid argument for "range()" call. Argument %d should be int or float but "%s" was given.)*", i + 1, arg_type.to_string()), call->arguments[i]);
  1580. } else if (arg_type.builtin_type != Variant::INT && arg_type.builtin_type != Variant::FLOAT) {
  1581. all_is_constant = false;
  1582. push_error(vformat(R"*(Invalid argument for "range()" call. Argument %d should be int or float but "%s" was given.)*", i + 1, arg_type.to_string()), call->arguments[i]);
  1583. }
  1584. }
  1585. }
  1586. Variant reduced;
  1587. if (all_is_constant) {
  1588. switch (args.size()) {
  1589. case 1:
  1590. reduced = (int32_t)args[0];
  1591. break;
  1592. case 2:
  1593. reduced = Vector2i(args[0], args[1]);
  1594. break;
  1595. case 3:
  1596. reduced = Vector3i(args[0], args[1], args[2]);
  1597. break;
  1598. }
  1599. p_for->list->is_constant = true;
  1600. p_for->list->reduced_value = reduced;
  1601. }
  1602. }
  1603. if (p_for->list->is_constant) {
  1604. p_for->list->set_datatype(type_from_variant(p_for->list->reduced_value, p_for->list));
  1605. } else {
  1606. GDScriptParser::DataType list_type;
  1607. list_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1608. list_type.kind = GDScriptParser::DataType::BUILTIN;
  1609. list_type.builtin_type = Variant::ARRAY;
  1610. p_for->list->set_datatype(list_type);
  1611. }
  1612. }
  1613. }
  1614. }
  1615. GDScriptParser::DataType variable_type;
  1616. if (list_resolved) {
  1617. variable_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  1618. variable_type.kind = GDScriptParser::DataType::BUILTIN;
  1619. variable_type.builtin_type = Variant::INT;
  1620. } else if (p_for->list) {
  1621. resolve_node(p_for->list, false);
  1622. GDScriptParser::DataType list_type = p_for->list->get_datatype();
  1623. if (!list_type.is_hard_type()) {
  1624. mark_node_unsafe(p_for->list);
  1625. }
  1626. if (list_type.is_variant()) {
  1627. variable_type.kind = GDScriptParser::DataType::VARIANT;
  1628. mark_node_unsafe(p_for->list);
  1629. } else if (list_type.has_container_element_type()) {
  1630. variable_type = list_type.get_container_element_type();
  1631. variable_type.type_source = list_type.type_source;
  1632. } else if (list_type.is_typed_container_type()) {
  1633. variable_type = list_type.get_typed_container_type();
  1634. variable_type.type_source = list_type.type_source;
  1635. } else if (list_type.builtin_type == Variant::INT || list_type.builtin_type == Variant::FLOAT || list_type.builtin_type == Variant::STRING) {
  1636. variable_type.type_source = list_type.type_source;
  1637. variable_type.kind = GDScriptParser::DataType::BUILTIN;
  1638. variable_type.builtin_type = list_type.builtin_type;
  1639. } else if (list_type.builtin_type == Variant::VECTOR2I || list_type.builtin_type == Variant::VECTOR3I) {
  1640. variable_type.type_source = list_type.type_source;
  1641. variable_type.kind = GDScriptParser::DataType::BUILTIN;
  1642. variable_type.builtin_type = Variant::INT;
  1643. } else if (list_type.builtin_type == Variant::VECTOR2 || list_type.builtin_type == Variant::VECTOR3) {
  1644. variable_type.type_source = list_type.type_source;
  1645. variable_type.kind = GDScriptParser::DataType::BUILTIN;
  1646. variable_type.builtin_type = Variant::FLOAT;
  1647. } else if (list_type.builtin_type == Variant::OBJECT) {
  1648. GDScriptParser::DataType return_type;
  1649. List<GDScriptParser::DataType> par_types;
  1650. int default_arg_count = 0;
  1651. bool is_static = false;
  1652. bool is_vararg = false;
  1653. if (get_function_signature(p_for->list, false, list_type, CoreStringNames::get_singleton()->_iter_get, return_type, par_types, default_arg_count, is_static, is_vararg)) {
  1654. variable_type = return_type;
  1655. variable_type.type_source = list_type.type_source;
  1656. } else if (!list_type.is_hard_type()) {
  1657. variable_type.kind = GDScriptParser::DataType::VARIANT;
  1658. } else {
  1659. push_error(vformat(R"(Unable to iterate on object of type "%s".)", list_type.to_string()), p_for->list);
  1660. }
  1661. } else if (list_type.builtin_type == Variant::ARRAY || list_type.builtin_type == Variant::DICTIONARY || !list_type.is_hard_type()) {
  1662. variable_type.kind = GDScriptParser::DataType::VARIANT;
  1663. } else {
  1664. push_error(vformat(R"(Unable to iterate on value of type "%s".)", list_type.to_string()), p_for->list);
  1665. }
  1666. }
  1667. if (p_for->variable) {
  1668. p_for->variable->set_datatype(variable_type);
  1669. }
  1670. resolve_suite(p_for->loop);
  1671. p_for->set_datatype(p_for->loop->get_datatype());
  1672. #ifdef DEBUG_ENABLED
  1673. if (p_for->variable) {
  1674. is_shadowing(p_for->variable, R"("for" iterator variable)");
  1675. }
  1676. #endif
  1677. }
  1678. void GDScriptAnalyzer::resolve_while(GDScriptParser::WhileNode *p_while) {
  1679. resolve_node(p_while->condition, false);
  1680. resolve_suite(p_while->loop);
  1681. p_while->set_datatype(p_while->loop->get_datatype());
  1682. }
  1683. void GDScriptAnalyzer::resolve_assert(GDScriptParser::AssertNode *p_assert) {
  1684. reduce_expression(p_assert->condition);
  1685. if (p_assert->message != nullptr) {
  1686. reduce_expression(p_assert->message);
  1687. if (!p_assert->message->get_datatype().has_no_type() && (p_assert->message->get_datatype().kind != GDScriptParser::DataType::BUILTIN || p_assert->message->get_datatype().builtin_type != Variant::STRING)) {
  1688. push_error(R"(Expected string for assert error message.)", p_assert->message);
  1689. }
  1690. }
  1691. p_assert->set_datatype(p_assert->condition->get_datatype());
  1692. #ifdef DEBUG_ENABLED
  1693. if (p_assert->condition->is_constant) {
  1694. if (p_assert->condition->reduced_value.booleanize()) {
  1695. parser->push_warning(p_assert->condition, GDScriptWarning::ASSERT_ALWAYS_TRUE);
  1696. } else {
  1697. parser->push_warning(p_assert->condition, GDScriptWarning::ASSERT_ALWAYS_FALSE);
  1698. }
  1699. }
  1700. #endif
  1701. }
  1702. void GDScriptAnalyzer::resolve_match(GDScriptParser::MatchNode *p_match) {
  1703. reduce_expression(p_match->test);
  1704. for (int i = 0; i < p_match->branches.size(); i++) {
  1705. resolve_match_branch(p_match->branches[i], p_match->test);
  1706. decide_suite_type(p_match, p_match->branches[i]);
  1707. }
  1708. }
  1709. void GDScriptAnalyzer::resolve_match_branch(GDScriptParser::MatchBranchNode *p_match_branch, GDScriptParser::ExpressionNode *p_match_test) {
  1710. for (int i = 0; i < p_match_branch->patterns.size(); i++) {
  1711. resolve_match_pattern(p_match_branch->patterns[i], p_match_test);
  1712. }
  1713. resolve_suite(p_match_branch->block);
  1714. decide_suite_type(p_match_branch, p_match_branch->block);
  1715. }
  1716. void GDScriptAnalyzer::resolve_match_pattern(GDScriptParser::PatternNode *p_match_pattern, GDScriptParser::ExpressionNode *p_match_test) {
  1717. if (p_match_pattern == nullptr) {
  1718. return;
  1719. }
  1720. GDScriptParser::DataType result;
  1721. switch (p_match_pattern->pattern_type) {
  1722. case GDScriptParser::PatternNode::PT_LITERAL:
  1723. if (p_match_pattern->literal) {
  1724. reduce_literal(p_match_pattern->literal);
  1725. result = p_match_pattern->literal->get_datatype();
  1726. }
  1727. break;
  1728. case GDScriptParser::PatternNode::PT_EXPRESSION:
  1729. if (p_match_pattern->expression) {
  1730. GDScriptParser::ExpressionNode *expr = p_match_pattern->expression;
  1731. reduce_expression(expr);
  1732. result = expr->get_datatype();
  1733. if (!expr->is_constant) {
  1734. while (expr && expr->type == GDScriptParser::Node::SUBSCRIPT) {
  1735. GDScriptParser::SubscriptNode *sub = static_cast<GDScriptParser::SubscriptNode *>(expr);
  1736. if (!sub->is_attribute) {
  1737. expr = nullptr;
  1738. } else {
  1739. expr = sub->base;
  1740. }
  1741. }
  1742. if (!expr || expr->type != GDScriptParser::Node::IDENTIFIER) {
  1743. push_error(R"(Expression in match pattern must be a constant expression, an identifier, or an attribute access ("A.B").)", expr);
  1744. }
  1745. }
  1746. }
  1747. break;
  1748. case GDScriptParser::PatternNode::PT_BIND:
  1749. if (p_match_test != nullptr) {
  1750. result = p_match_test->get_datatype();
  1751. } else {
  1752. result.kind = GDScriptParser::DataType::VARIANT;
  1753. }
  1754. p_match_pattern->bind->set_datatype(result);
  1755. #ifdef DEBUG_ENABLED
  1756. is_shadowing(p_match_pattern->bind, "pattern bind");
  1757. if (p_match_pattern->bind->usages == 0 && !String(p_match_pattern->bind->name).begins_with("_")) {
  1758. parser->push_warning(p_match_pattern->bind, GDScriptWarning::UNUSED_VARIABLE, p_match_pattern->bind->name);
  1759. }
  1760. #endif
  1761. break;
  1762. case GDScriptParser::PatternNode::PT_ARRAY:
  1763. for (int i = 0; i < p_match_pattern->array.size(); i++) {
  1764. resolve_match_pattern(p_match_pattern->array[i], nullptr);
  1765. decide_suite_type(p_match_pattern, p_match_pattern->array[i]);
  1766. }
  1767. result = p_match_pattern->get_datatype();
  1768. break;
  1769. case GDScriptParser::PatternNode::PT_DICTIONARY:
  1770. for (int i = 0; i < p_match_pattern->dictionary.size(); i++) {
  1771. if (p_match_pattern->dictionary[i].key) {
  1772. reduce_expression(p_match_pattern->dictionary[i].key);
  1773. if (!p_match_pattern->dictionary[i].key->is_constant) {
  1774. push_error(R"(Expression in dictionary pattern key must be a constant.)", p_match_pattern->dictionary[i].key);
  1775. }
  1776. }
  1777. if (p_match_pattern->dictionary[i].value_pattern) {
  1778. resolve_match_pattern(p_match_pattern->dictionary[i].value_pattern, nullptr);
  1779. decide_suite_type(p_match_pattern, p_match_pattern->dictionary[i].value_pattern);
  1780. }
  1781. }
  1782. result = p_match_pattern->get_datatype();
  1783. break;
  1784. case GDScriptParser::PatternNode::PT_WILDCARD:
  1785. case GDScriptParser::PatternNode::PT_REST:
  1786. result.kind = GDScriptParser::DataType::VARIANT;
  1787. break;
  1788. }
  1789. p_match_pattern->set_datatype(result);
  1790. }
  1791. void GDScriptAnalyzer::resolve_return(GDScriptParser::ReturnNode *p_return) {
  1792. GDScriptParser::DataType result;
  1793. GDScriptParser::DataType expected_type;
  1794. bool has_expected_type = parser->current_function != nullptr;
  1795. if (has_expected_type) {
  1796. expected_type = parser->current_function->get_datatype();
  1797. }
  1798. if (p_return->return_value != nullptr) {
  1799. bool is_void_function = has_expected_type && expected_type.is_hard_type() && expected_type.kind == GDScriptParser::DataType::BUILTIN && expected_type.builtin_type == Variant::NIL;
  1800. bool is_call = p_return->return_value->type == GDScriptParser::Node::CALL;
  1801. if (is_void_function && is_call) {
  1802. // Pretend the call is a root expression to allow those that are "void".
  1803. reduce_call(static_cast<GDScriptParser::CallNode *>(p_return->return_value), false, true);
  1804. } else {
  1805. reduce_expression(p_return->return_value);
  1806. }
  1807. if (is_void_function) {
  1808. p_return->void_return = true;
  1809. const GDScriptParser::DataType &return_type = p_return->return_value->datatype;
  1810. if (is_call && !return_type.is_hard_type()) {
  1811. String function_name = parser->current_function->identifier ? parser->current_function->identifier->name.operator String() : String("<anonymous function>");
  1812. String called_function_name = static_cast<GDScriptParser::CallNode *>(p_return->return_value)->function_name.operator String();
  1813. #ifdef DEBUG_ENABLED
  1814. parser->push_warning(p_return, GDScriptWarning::UNSAFE_VOID_RETURN, function_name, called_function_name);
  1815. #endif
  1816. mark_node_unsafe(p_return);
  1817. } else if (!is_call) {
  1818. push_error("A void function cannot return a value.", p_return);
  1819. }
  1820. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1821. result.kind = GDScriptParser::DataType::BUILTIN;
  1822. result.builtin_type = Variant::NIL;
  1823. result.is_constant = true;
  1824. } else {
  1825. if (p_return->return_value->type == GDScriptParser::Node::ARRAY && has_expected_type && expected_type.has_container_element_type()) {
  1826. update_array_literal_element_type(static_cast<GDScriptParser::ArrayNode *>(p_return->return_value), expected_type.get_container_element_type());
  1827. }
  1828. if (has_expected_type && expected_type.is_hard_type() && p_return->return_value->is_constant) {
  1829. update_const_expression_builtin_type(p_return->return_value, expected_type, "return");
  1830. }
  1831. result = p_return->return_value->get_datatype();
  1832. }
  1833. } else {
  1834. // Return type is null by default.
  1835. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1836. result.kind = GDScriptParser::DataType::BUILTIN;
  1837. result.builtin_type = Variant::NIL;
  1838. result.is_constant = true;
  1839. }
  1840. if (has_expected_type && !expected_type.is_variant()) {
  1841. if (result.is_variant() || !result.is_hard_type()) {
  1842. mark_node_unsafe(p_return);
  1843. if (!is_type_compatible(expected_type, result, true, p_return)) {
  1844. downgrade_node_type_source(p_return);
  1845. }
  1846. } else if (!is_type_compatible(expected_type, result, true, p_return)) {
  1847. mark_node_unsafe(p_return);
  1848. if (!is_type_compatible(result, expected_type)) {
  1849. push_error(vformat(R"(Cannot return value of type "%s" because the function return type is "%s".)", result.to_string(), expected_type.to_string()), p_return);
  1850. }
  1851. #ifdef DEBUG_ENABLED
  1852. } else if (expected_type.builtin_type == Variant::INT && result.builtin_type == Variant::FLOAT) {
  1853. parser->push_warning(p_return, GDScriptWarning::NARROWING_CONVERSION);
  1854. #endif
  1855. }
  1856. }
  1857. p_return->set_datatype(result);
  1858. }
  1859. void GDScriptAnalyzer::reduce_expression(GDScriptParser::ExpressionNode *p_expression, bool p_is_root) {
  1860. // This one makes some magic happen.
  1861. if (p_expression == nullptr) {
  1862. return;
  1863. }
  1864. if (p_expression->reduced) {
  1865. // Don't do this more than once.
  1866. return;
  1867. }
  1868. p_expression->reduced = true;
  1869. switch (p_expression->type) {
  1870. case GDScriptParser::Node::ARRAY:
  1871. reduce_array(static_cast<GDScriptParser::ArrayNode *>(p_expression));
  1872. break;
  1873. case GDScriptParser::Node::ASSIGNMENT:
  1874. reduce_assignment(static_cast<GDScriptParser::AssignmentNode *>(p_expression));
  1875. break;
  1876. case GDScriptParser::Node::AWAIT:
  1877. reduce_await(static_cast<GDScriptParser::AwaitNode *>(p_expression));
  1878. break;
  1879. case GDScriptParser::Node::BINARY_OPERATOR:
  1880. reduce_binary_op(static_cast<GDScriptParser::BinaryOpNode *>(p_expression));
  1881. break;
  1882. case GDScriptParser::Node::CALL:
  1883. reduce_call(static_cast<GDScriptParser::CallNode *>(p_expression), false, p_is_root);
  1884. break;
  1885. case GDScriptParser::Node::CAST:
  1886. reduce_cast(static_cast<GDScriptParser::CastNode *>(p_expression));
  1887. break;
  1888. case GDScriptParser::Node::DICTIONARY:
  1889. reduce_dictionary(static_cast<GDScriptParser::DictionaryNode *>(p_expression));
  1890. break;
  1891. case GDScriptParser::Node::GET_NODE:
  1892. reduce_get_node(static_cast<GDScriptParser::GetNodeNode *>(p_expression));
  1893. break;
  1894. case GDScriptParser::Node::IDENTIFIER:
  1895. reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_expression));
  1896. break;
  1897. case GDScriptParser::Node::LAMBDA:
  1898. reduce_lambda(static_cast<GDScriptParser::LambdaNode *>(p_expression));
  1899. break;
  1900. case GDScriptParser::Node::LITERAL:
  1901. reduce_literal(static_cast<GDScriptParser::LiteralNode *>(p_expression));
  1902. break;
  1903. case GDScriptParser::Node::PRELOAD:
  1904. reduce_preload(static_cast<GDScriptParser::PreloadNode *>(p_expression));
  1905. break;
  1906. case GDScriptParser::Node::SELF:
  1907. reduce_self(static_cast<GDScriptParser::SelfNode *>(p_expression));
  1908. break;
  1909. case GDScriptParser::Node::SUBSCRIPT:
  1910. reduce_subscript(static_cast<GDScriptParser::SubscriptNode *>(p_expression));
  1911. break;
  1912. case GDScriptParser::Node::TERNARY_OPERATOR:
  1913. reduce_ternary_op(static_cast<GDScriptParser::TernaryOpNode *>(p_expression), p_is_root);
  1914. break;
  1915. case GDScriptParser::Node::UNARY_OPERATOR:
  1916. reduce_unary_op(static_cast<GDScriptParser::UnaryOpNode *>(p_expression));
  1917. break;
  1918. // Non-expressions. Here only to make sure new nodes aren't forgotten.
  1919. case GDScriptParser::Node::NONE:
  1920. case GDScriptParser::Node::ANNOTATION:
  1921. case GDScriptParser::Node::ASSERT:
  1922. case GDScriptParser::Node::BREAK:
  1923. case GDScriptParser::Node::BREAKPOINT:
  1924. case GDScriptParser::Node::CLASS:
  1925. case GDScriptParser::Node::CONSTANT:
  1926. case GDScriptParser::Node::CONTINUE:
  1927. case GDScriptParser::Node::ENUM:
  1928. case GDScriptParser::Node::FOR:
  1929. case GDScriptParser::Node::FUNCTION:
  1930. case GDScriptParser::Node::IF:
  1931. case GDScriptParser::Node::MATCH:
  1932. case GDScriptParser::Node::MATCH_BRANCH:
  1933. case GDScriptParser::Node::PARAMETER:
  1934. case GDScriptParser::Node::PASS:
  1935. case GDScriptParser::Node::PATTERN:
  1936. case GDScriptParser::Node::RETURN:
  1937. case GDScriptParser::Node::SIGNAL:
  1938. case GDScriptParser::Node::SUITE:
  1939. case GDScriptParser::Node::TYPE:
  1940. case GDScriptParser::Node::VARIABLE:
  1941. case GDScriptParser::Node::WHILE:
  1942. ERR_FAIL_MSG("Reaching unreachable case");
  1943. }
  1944. }
  1945. void GDScriptAnalyzer::reduce_array(GDScriptParser::ArrayNode *p_array) {
  1946. for (int i = 0; i < p_array->elements.size(); i++) {
  1947. GDScriptParser::ExpressionNode *element = p_array->elements[i];
  1948. reduce_expression(element);
  1949. }
  1950. // It's array in any case.
  1951. GDScriptParser::DataType arr_type;
  1952. arr_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1953. arr_type.kind = GDScriptParser::DataType::BUILTIN;
  1954. arr_type.builtin_type = Variant::ARRAY;
  1955. arr_type.is_constant = true;
  1956. p_array->set_datatype(arr_type);
  1957. }
  1958. #ifdef DEBUG_ENABLED
  1959. static bool enum_has_value(const GDScriptParser::DataType p_type, int64_t p_value) {
  1960. for (const KeyValue<StringName, int64_t> &E : p_type.enum_values) {
  1961. if (E.value == p_value) {
  1962. return true;
  1963. }
  1964. }
  1965. return false;
  1966. }
  1967. #endif
  1968. void GDScriptAnalyzer::update_const_expression_builtin_type(GDScriptParser::ExpressionNode *p_expression, const GDScriptParser::DataType &p_type, const char *p_usage, bool p_is_cast) {
  1969. if (p_expression->get_datatype() == p_type) {
  1970. return;
  1971. }
  1972. if (p_type.kind != GDScriptParser::DataType::BUILTIN && p_type.kind != GDScriptParser::DataType::ENUM) {
  1973. return;
  1974. }
  1975. GDScriptParser::DataType expression_type = p_expression->get_datatype();
  1976. bool is_enum_cast = p_is_cast && p_type.kind == GDScriptParser::DataType::ENUM && p_type.is_meta_type == false && expression_type.builtin_type == Variant::INT;
  1977. if (!is_enum_cast && !is_type_compatible(p_type, expression_type, true, p_expression)) {
  1978. push_error(vformat(R"(Cannot %s a value of type "%s" as "%s".)", p_usage, expression_type.to_string(), p_type.to_string()), p_expression);
  1979. return;
  1980. }
  1981. GDScriptParser::DataType value_type = type_from_variant(p_expression->reduced_value, p_expression);
  1982. if (expression_type.is_variant() && !is_enum_cast && !is_type_compatible(p_type, value_type, true, p_expression)) {
  1983. push_error(vformat(R"(Cannot %s a value of type "%s" as "%s".)", p_usage, value_type.to_string(), p_type.to_string()), p_expression);
  1984. return;
  1985. }
  1986. #ifdef DEBUG_ENABLED
  1987. if (p_type.kind == GDScriptParser::DataType::ENUM && value_type.builtin_type == Variant::INT && !enum_has_value(p_type, p_expression->reduced_value)) {
  1988. parser->push_warning(p_expression, GDScriptWarning::INT_AS_ENUM_WITHOUT_MATCH, p_usage, p_expression->reduced_value.stringify(), p_type.to_string());
  1989. }
  1990. #endif
  1991. if (value_type.builtin_type == p_type.builtin_type) {
  1992. p_expression->set_datatype(p_type);
  1993. return;
  1994. }
  1995. Variant converted_to;
  1996. const Variant *converted_from = &p_expression->reduced_value;
  1997. Callable::CallError call_error;
  1998. Variant::construct(p_type.builtin_type, converted_to, &converted_from, 1, call_error);
  1999. if (call_error.error) {
  2000. push_error(vformat(R"(Failed to convert a value of type "%s" to "%s".)", value_type.to_string(), p_type.to_string()), p_expression);
  2001. return;
  2002. }
  2003. #ifdef DEBUG_ENABLED
  2004. if (p_type.builtin_type == Variant::INT && value_type.builtin_type == Variant::FLOAT) {
  2005. parser->push_warning(p_expression, GDScriptWarning::NARROWING_CONVERSION);
  2006. }
  2007. #endif
  2008. p_expression->reduced_value = converted_to;
  2009. p_expression->set_datatype(p_type);
  2010. }
  2011. // When an array literal is stored (or passed as function argument) to a typed context, we then assume the array is typed.
  2012. // This function determines which type is that (if any).
  2013. void GDScriptAnalyzer::update_array_literal_element_type(GDScriptParser::ArrayNode *p_array, const GDScriptParser::DataType &p_element_type) {
  2014. for (int i = 0; i < p_array->elements.size(); i++) {
  2015. GDScriptParser::ExpressionNode *element_node = p_array->elements[i];
  2016. if (element_node->is_constant) {
  2017. update_const_expression_builtin_type(element_node, p_element_type, "include");
  2018. }
  2019. const GDScriptParser::DataType &element_type = element_node->get_datatype();
  2020. if (element_type.has_no_type() || element_type.is_variant() || !element_type.is_hard_type()) {
  2021. mark_node_unsafe(element_node);
  2022. continue;
  2023. }
  2024. if (!is_type_compatible(p_element_type, element_type, true, p_array)) {
  2025. push_error(vformat(R"(Cannot have an element of type "%s" in an array of type "Array[%s]".)", element_type.to_string(), p_element_type.to_string()), element_node);
  2026. return;
  2027. }
  2028. }
  2029. GDScriptParser::DataType array_type = p_array->get_datatype();
  2030. array_type.set_container_element_type(p_element_type);
  2031. p_array->set_datatype(array_type);
  2032. }
  2033. void GDScriptAnalyzer::reduce_assignment(GDScriptParser::AssignmentNode *p_assignment) {
  2034. reduce_expression(p_assignment->assignee);
  2035. reduce_expression(p_assignment->assigned_value);
  2036. if (p_assignment->assigned_value == nullptr || p_assignment->assignee == nullptr) {
  2037. return;
  2038. }
  2039. GDScriptParser::DataType assignee_type = p_assignment->assignee->get_datatype();
  2040. if (assignee_type.is_constant || (p_assignment->assignee->type == GDScriptParser::Node::SUBSCRIPT && static_cast<GDScriptParser::SubscriptNode *>(p_assignment->assignee)->base->is_constant)) {
  2041. push_error("Cannot assign a new value to a constant.", p_assignment->assignee);
  2042. return;
  2043. } else if (assignee_type.is_read_only) {
  2044. push_error("Cannot assign a new value to a read-only property.", p_assignment->assignee);
  2045. return;
  2046. } else if (p_assignment->assignee->type == GDScriptParser::Node::SUBSCRIPT) {
  2047. GDScriptParser::SubscriptNode *sub = static_cast<GDScriptParser::SubscriptNode *>(p_assignment->assignee);
  2048. while (sub) {
  2049. const GDScriptParser::DataType &base_type = sub->base->datatype;
  2050. if (base_type.is_hard_type() && base_type.is_read_only) {
  2051. if (base_type.kind == GDScriptParser::DataType::BUILTIN && !Variant::is_type_shared(base_type.builtin_type)) {
  2052. push_error("Cannot assign a new value to a read-only property.", p_assignment->assignee);
  2053. return;
  2054. }
  2055. } else {
  2056. break;
  2057. }
  2058. if (sub->base->type == GDScriptParser::Node::SUBSCRIPT) {
  2059. sub = static_cast<GDScriptParser::SubscriptNode *>(sub->base);
  2060. } else {
  2061. sub = nullptr;
  2062. }
  2063. }
  2064. }
  2065. // Check if assigned value is an array literal, so we can make it a typed array too if appropriate.
  2066. if (p_assignment->assigned_value->type == GDScriptParser::Node::ARRAY && assignee_type.has_container_element_type()) {
  2067. update_array_literal_element_type(static_cast<GDScriptParser::ArrayNode *>(p_assignment->assigned_value), assignee_type.get_container_element_type());
  2068. }
  2069. if (p_assignment->operation == GDScriptParser::AssignmentNode::OP_NONE && assignee_type.is_hard_type() && p_assignment->assigned_value->is_constant) {
  2070. update_const_expression_builtin_type(p_assignment->assigned_value, assignee_type, "assign");
  2071. }
  2072. GDScriptParser::DataType assigned_value_type = p_assignment->assigned_value->get_datatype();
  2073. bool assignee_is_variant = assignee_type.is_variant();
  2074. bool assignee_is_hard = assignee_type.is_hard_type();
  2075. bool assigned_is_variant = assigned_value_type.is_variant();
  2076. bool assigned_is_hard = assigned_value_type.is_hard_type();
  2077. bool compatible = true;
  2078. bool downgrades_assignee = false;
  2079. bool downgrades_assigned = false;
  2080. GDScriptParser::DataType op_type = assigned_value_type;
  2081. if (p_assignment->operation != GDScriptParser::AssignmentNode::OP_NONE && !op_type.is_variant()) {
  2082. op_type = get_operation_type(p_assignment->variant_op, assignee_type, assigned_value_type, compatible, p_assignment->assigned_value);
  2083. if (assignee_is_variant) {
  2084. // variant assignee
  2085. mark_node_unsafe(p_assignment);
  2086. } else if (!compatible) {
  2087. // incompatible hard types and non-variant assignee
  2088. mark_node_unsafe(p_assignment);
  2089. if (assigned_is_variant) {
  2090. // incompatible hard non-variant assignee and hard variant assigned
  2091. p_assignment->use_conversion_assign = true;
  2092. } else {
  2093. // incompatible hard non-variant types
  2094. push_error(vformat(R"(Invalid operands "%s" and "%s" for assignment operator.)", assignee_type.to_string(), assigned_value_type.to_string()), p_assignment);
  2095. }
  2096. } else if (op_type.type_source == GDScriptParser::DataType::UNDETECTED && !assigned_is_variant) {
  2097. // incompatible non-variant types (at least one weak)
  2098. downgrades_assignee = !assignee_is_hard;
  2099. downgrades_assigned = !assigned_is_hard;
  2100. }
  2101. }
  2102. p_assignment->set_datatype(op_type);
  2103. if (assignee_is_variant) {
  2104. if (!assignee_is_hard) {
  2105. // weak variant assignee
  2106. mark_node_unsafe(p_assignment);
  2107. }
  2108. } else {
  2109. if (assignee_is_hard && !assigned_is_hard) {
  2110. // hard non-variant assignee and weak assigned
  2111. mark_node_unsafe(p_assignment);
  2112. p_assignment->use_conversion_assign = true;
  2113. downgrades_assigned = downgrades_assigned || (!assigned_is_variant && !is_type_compatible(assignee_type, op_type, true, p_assignment->assigned_value));
  2114. } else if (compatible) {
  2115. if (op_type.is_variant()) {
  2116. // non-variant assignee and variant result
  2117. mark_node_unsafe(p_assignment);
  2118. if (assignee_is_hard) {
  2119. // hard non-variant assignee and variant result
  2120. p_assignment->use_conversion_assign = true;
  2121. } else {
  2122. // weak non-variant assignee and variant result
  2123. downgrades_assignee = true;
  2124. }
  2125. } else if (!is_type_compatible(assignee_type, op_type, assignee_is_hard, p_assignment->assigned_value)) {
  2126. // non-variant assignee and incompatible result
  2127. mark_node_unsafe(p_assignment);
  2128. if (assignee_is_hard) {
  2129. if (is_type_compatible(op_type, assignee_type)) {
  2130. // hard non-variant assignee and maybe compatible result
  2131. p_assignment->use_conversion_assign = true;
  2132. } else {
  2133. // hard non-variant assignee and incompatible result
  2134. push_error(vformat(R"(Value of type "%s" cannot be assigned to a variable of type "%s".)", assigned_value_type.to_string(), assignee_type.to_string()), p_assignment->assigned_value);
  2135. }
  2136. } else {
  2137. // weak non-variant assignee and incompatible result
  2138. downgrades_assignee = true;
  2139. }
  2140. } else if (assignee_type.has_container_element_type() && !op_type.has_container_element_type()) {
  2141. // typed array assignee and untyped array result
  2142. mark_node_unsafe(p_assignment);
  2143. }
  2144. }
  2145. }
  2146. if (downgrades_assignee) {
  2147. downgrade_node_type_source(p_assignment->assignee);
  2148. }
  2149. if (downgrades_assigned) {
  2150. downgrade_node_type_source(p_assignment->assigned_value);
  2151. }
  2152. #ifdef DEBUG_ENABLED
  2153. if (assignee_type.is_hard_type() && assignee_type.builtin_type == Variant::INT && assigned_value_type.builtin_type == Variant::FLOAT) {
  2154. parser->push_warning(p_assignment->assigned_value, GDScriptWarning::NARROWING_CONVERSION);
  2155. }
  2156. #endif
  2157. }
  2158. void GDScriptAnalyzer::reduce_await(GDScriptParser::AwaitNode *p_await) {
  2159. if (p_await->to_await == nullptr) {
  2160. GDScriptParser::DataType await_type;
  2161. await_type.kind = GDScriptParser::DataType::VARIANT;
  2162. p_await->set_datatype(await_type);
  2163. return;
  2164. }
  2165. GDScriptParser::DataType awaiting_type;
  2166. if (p_await->to_await->type == GDScriptParser::Node::CALL) {
  2167. reduce_call(static_cast<GDScriptParser::CallNode *>(p_await->to_await), true);
  2168. awaiting_type = p_await->to_await->get_datatype();
  2169. } else {
  2170. reduce_expression(p_await->to_await);
  2171. }
  2172. if (p_await->to_await->is_constant) {
  2173. p_await->is_constant = p_await->to_await->is_constant;
  2174. p_await->reduced_value = p_await->to_await->reduced_value;
  2175. awaiting_type = p_await->to_await->get_datatype();
  2176. } else {
  2177. awaiting_type.kind = GDScriptParser::DataType::VARIANT;
  2178. awaiting_type.type_source = GDScriptParser::DataType::UNDETECTED;
  2179. }
  2180. p_await->set_datatype(awaiting_type);
  2181. #ifdef DEBUG_ENABLED
  2182. awaiting_type = p_await->to_await->get_datatype();
  2183. if (!(awaiting_type.has_no_type() || awaiting_type.is_coroutine || awaiting_type.builtin_type == Variant::SIGNAL)) {
  2184. parser->push_warning(p_await, GDScriptWarning::REDUNDANT_AWAIT);
  2185. }
  2186. #endif
  2187. }
  2188. void GDScriptAnalyzer::reduce_binary_op(GDScriptParser::BinaryOpNode *p_binary_op) {
  2189. reduce_expression(p_binary_op->left_operand);
  2190. if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST && p_binary_op->right_operand && p_binary_op->right_operand->type == GDScriptParser::Node::IDENTIFIER) {
  2191. reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_binary_op->right_operand), true);
  2192. } else {
  2193. reduce_expression(p_binary_op->right_operand);
  2194. }
  2195. // TODO: Right operand must be a valid type with the `is` operator. Need to check here.
  2196. GDScriptParser::DataType left_type;
  2197. if (p_binary_op->left_operand) {
  2198. left_type = p_binary_op->left_operand->get_datatype();
  2199. }
  2200. GDScriptParser::DataType right_type;
  2201. if (p_binary_op->right_operand) {
  2202. right_type = p_binary_op->right_operand->get_datatype();
  2203. }
  2204. if (!left_type.is_set() || !right_type.is_set()) {
  2205. return;
  2206. }
  2207. #ifdef DEBUG_ENABLED
  2208. if (p_binary_op->variant_op == Variant::OP_DIVIDE && left_type.builtin_type == Variant::INT && right_type.builtin_type == Variant::INT) {
  2209. parser->push_warning(p_binary_op, GDScriptWarning::INTEGER_DIVISION);
  2210. }
  2211. #endif
  2212. if (p_binary_op->left_operand->is_constant && p_binary_op->right_operand->is_constant) {
  2213. p_binary_op->is_constant = true;
  2214. if (p_binary_op->variant_op < Variant::OP_MAX) {
  2215. bool valid = false;
  2216. Variant::evaluate(p_binary_op->variant_op, p_binary_op->left_operand->reduced_value, p_binary_op->right_operand->reduced_value, p_binary_op->reduced_value, valid);
  2217. if (!valid) {
  2218. if (p_binary_op->reduced_value.get_type() == Variant::STRING) {
  2219. push_error(vformat(R"(%s in operator %s.)", p_binary_op->reduced_value, Variant::get_operator_name(p_binary_op->variant_op)), p_binary_op);
  2220. } else {
  2221. push_error(vformat(R"(Invalid operands to operator %s, %s and %s.)",
  2222. Variant::get_operator_name(p_binary_op->variant_op),
  2223. Variant::get_type_name(p_binary_op->left_operand->reduced_value.get_type()),
  2224. Variant::get_type_name(p_binary_op->right_operand->reduced_value.get_type())),
  2225. p_binary_op);
  2226. }
  2227. }
  2228. } else {
  2229. if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST) {
  2230. GDScriptParser::DataType test_type = right_type;
  2231. test_type.is_meta_type = false;
  2232. if (!is_type_compatible(test_type, left_type)) {
  2233. push_error(vformat(R"(Expression is of type "%s" so it can't be of type "%s".)"), p_binary_op->left_operand);
  2234. p_binary_op->reduced_value = false;
  2235. } else {
  2236. p_binary_op->reduced_value = true;
  2237. }
  2238. } else {
  2239. ERR_PRINT("Parser bug: unknown binary operation.");
  2240. }
  2241. }
  2242. p_binary_op->set_datatype(type_from_variant(p_binary_op->reduced_value, p_binary_op));
  2243. return;
  2244. }
  2245. GDScriptParser::DataType result;
  2246. if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST) {
  2247. GDScriptParser::DataType test_type = right_type;
  2248. test_type.is_meta_type = false;
  2249. if (!is_type_compatible(test_type, left_type) && !is_type_compatible(left_type, test_type)) {
  2250. if (left_type.is_hard_type()) {
  2251. push_error(vformat(R"(Expression is of type "%s" so it can't be of type "%s".)", left_type.to_string(), test_type.to_string()), p_binary_op->left_operand);
  2252. } else {
  2253. // TODO: Warning.
  2254. mark_node_unsafe(p_binary_op);
  2255. }
  2256. }
  2257. // "is" operator is always a boolean anyway.
  2258. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2259. result.kind = GDScriptParser::DataType::BUILTIN;
  2260. result.builtin_type = Variant::BOOL;
  2261. } else if ((p_binary_op->variant_op == Variant::OP_EQUAL || p_binary_op->variant_op == Variant::OP_NOT_EQUAL) &&
  2262. ((left_type.kind == GDScriptParser::DataType::BUILTIN && left_type.builtin_type == Variant::NIL) || (right_type.kind == GDScriptParser::DataType::BUILTIN && right_type.builtin_type == Variant::NIL))) {
  2263. // "==" and "!=" operators always return a boolean when comparing to null.
  2264. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2265. result.kind = GDScriptParser::DataType::BUILTIN;
  2266. result.builtin_type = Variant::BOOL;
  2267. } else if (left_type.is_variant() || right_type.is_variant()) {
  2268. // Cannot infer type because one operand can be anything.
  2269. result.kind = GDScriptParser::DataType::VARIANT;
  2270. mark_node_unsafe(p_binary_op);
  2271. } else if (p_binary_op->variant_op < Variant::OP_MAX) {
  2272. bool valid = false;
  2273. result = get_operation_type(p_binary_op->variant_op, left_type, right_type, valid, p_binary_op);
  2274. if (!valid) {
  2275. push_error(vformat(R"(Invalid operands "%s" and "%s" for "%s" operator.)", left_type.to_string(), right_type.to_string(), Variant::get_operator_name(p_binary_op->variant_op)), p_binary_op);
  2276. }
  2277. } else {
  2278. ERR_PRINT("Parser bug: unknown binary operation.");
  2279. }
  2280. p_binary_op->set_datatype(result);
  2281. }
  2282. #ifdef TOOLS_ENABLED
  2283. #ifndef DISABLE_DEPRECATED
  2284. const char *GDScriptAnalyzer::get_rename_from_map(const char *map[][2], String key) {
  2285. for (int index = 0; map[index][0]; index++) {
  2286. if (map[index][0] == key) {
  2287. return map[index][1];
  2288. }
  2289. }
  2290. return nullptr;
  2291. }
  2292. // Checks if an identifier/function name has been renamed in Godot 4, uses ProjectConverter3To4 for rename map.
  2293. // Returns the new name if found, nullptr otherwise.
  2294. const char *GDScriptAnalyzer::check_for_renamed_identifier(String identifier, GDScriptParser::Node::Type type) {
  2295. switch (type) {
  2296. case GDScriptParser::Node::IDENTIFIER: {
  2297. // Check properties
  2298. const char *result = get_rename_from_map(ProjectConverter3To4::gdscript_properties_renames, identifier);
  2299. if (result) {
  2300. return result;
  2301. }
  2302. // Check enum values
  2303. result = get_rename_from_map(ProjectConverter3To4::enum_renames, identifier);
  2304. if (result) {
  2305. return result;
  2306. }
  2307. // Check color constants
  2308. result = get_rename_from_map(ProjectConverter3To4::color_renames, identifier);
  2309. if (result) {
  2310. return result;
  2311. }
  2312. // Check type names
  2313. result = get_rename_from_map(ProjectConverter3To4::class_renames, identifier);
  2314. if (result) {
  2315. return result;
  2316. }
  2317. return get_rename_from_map(ProjectConverter3To4::builtin_types_renames, identifier);
  2318. }
  2319. case GDScriptParser::Node::CALL: {
  2320. const char *result = get_rename_from_map(ProjectConverter3To4::gdscript_function_renames, identifier);
  2321. if (result) {
  2322. return result;
  2323. }
  2324. // Built-in Types are mistaken for function calls when the built-in type is not found.
  2325. // Check built-in types if function rename not found
  2326. return get_rename_from_map(ProjectConverter3To4::builtin_types_renames, identifier);
  2327. }
  2328. // Signal references don't get parsed through the GDScriptAnalyzer. No support for signal rename hints.
  2329. default:
  2330. // No rename found, return null
  2331. return nullptr;
  2332. }
  2333. }
  2334. #endif // DISABLE_DEPRECATED
  2335. #endif // TOOLS_ENABLED
  2336. void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool p_is_await, bool p_is_root) {
  2337. bool all_is_constant = true;
  2338. HashMap<int, GDScriptParser::ArrayNode *> arrays; // For array literal to potentially type when passing.
  2339. for (int i = 0; i < p_call->arguments.size(); i++) {
  2340. reduce_expression(p_call->arguments[i]);
  2341. if (p_call->arguments[i]->type == GDScriptParser::Node::ARRAY) {
  2342. arrays[i] = static_cast<GDScriptParser::ArrayNode *>(p_call->arguments[i]);
  2343. }
  2344. all_is_constant = all_is_constant && p_call->arguments[i]->is_constant;
  2345. }
  2346. GDScriptParser::Node::Type callee_type = p_call->get_callee_type();
  2347. GDScriptParser::DataType call_type;
  2348. if (!p_call->is_super && callee_type == GDScriptParser::Node::IDENTIFIER) {
  2349. // Call to name directly.
  2350. StringName function_name = p_call->function_name;
  2351. Variant::Type builtin_type = GDScriptParser::get_builtin_type(function_name);
  2352. if (builtin_type < Variant::VARIANT_MAX) {
  2353. // Is a builtin constructor.
  2354. call_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2355. call_type.kind = GDScriptParser::DataType::BUILTIN;
  2356. call_type.builtin_type = builtin_type;
  2357. if (builtin_type == Variant::OBJECT) {
  2358. call_type.kind = GDScriptParser::DataType::NATIVE;
  2359. call_type.native_type = function_name; // "Object".
  2360. }
  2361. bool safe_to_fold = true;
  2362. switch (builtin_type) {
  2363. // Those are stored by reference so not suited for compile-time construction.
  2364. // Because in this case they would be the same reference in all constructed values.
  2365. case Variant::OBJECT:
  2366. case Variant::DICTIONARY:
  2367. case Variant::ARRAY:
  2368. case Variant::PACKED_BYTE_ARRAY:
  2369. case Variant::PACKED_INT32_ARRAY:
  2370. case Variant::PACKED_INT64_ARRAY:
  2371. case Variant::PACKED_FLOAT32_ARRAY:
  2372. case Variant::PACKED_FLOAT64_ARRAY:
  2373. case Variant::PACKED_STRING_ARRAY:
  2374. case Variant::PACKED_VECTOR2_ARRAY:
  2375. case Variant::PACKED_VECTOR3_ARRAY:
  2376. case Variant::PACKED_COLOR_ARRAY:
  2377. safe_to_fold = false;
  2378. break;
  2379. default:
  2380. break;
  2381. }
  2382. if (all_is_constant && safe_to_fold) {
  2383. // Construct here.
  2384. Vector<const Variant *> args;
  2385. for (int i = 0; i < p_call->arguments.size(); i++) {
  2386. args.push_back(&(p_call->arguments[i]->reduced_value));
  2387. }
  2388. Callable::CallError err;
  2389. Variant value;
  2390. Variant::construct(builtin_type, value, (const Variant **)args.ptr(), args.size(), err);
  2391. switch (err.error) {
  2392. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:
  2393. push_error(vformat(R"(Invalid argument for %s constructor: argument %d should be "%s" but is "%s".)", Variant::get_type_name(builtin_type), err.argument + 1,
  2394. Variant::get_type_name(Variant::Type(err.expected)), p_call->arguments[err.argument]->get_datatype().to_string()),
  2395. p_call->arguments[err.argument]);
  2396. break;
  2397. case Callable::CallError::CALL_ERROR_INVALID_METHOD: {
  2398. String signature = Variant::get_type_name(builtin_type) + "(";
  2399. for (int i = 0; i < p_call->arguments.size(); i++) {
  2400. if (i > 0) {
  2401. signature += ", ";
  2402. }
  2403. signature += p_call->arguments[i]->get_datatype().to_string();
  2404. }
  2405. signature += ")";
  2406. push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call->callee);
  2407. } break;
  2408. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  2409. push_error(vformat(R"(Too many arguments for %s constructor. Received %d but expected %d.)", Variant::get_type_name(builtin_type), p_call->arguments.size(), err.expected), p_call);
  2410. break;
  2411. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  2412. push_error(vformat(R"(Too few arguments for %s constructor. Received %d but expected %d.)", Variant::get_type_name(builtin_type), p_call->arguments.size(), err.expected), p_call);
  2413. break;
  2414. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
  2415. case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
  2416. break; // Can't happen in a builtin constructor.
  2417. case Callable::CallError::CALL_OK:
  2418. p_call->is_constant = true;
  2419. p_call->reduced_value = value;
  2420. break;
  2421. }
  2422. } else {
  2423. // TODO: Check constructors without constants.
  2424. // If there's one argument, try to use copy constructor (those aren't explicitly defined).
  2425. if (p_call->arguments.size() == 1) {
  2426. GDScriptParser::DataType arg_type = p_call->arguments[0]->get_datatype();
  2427. if (arg_type.is_variant()) {
  2428. mark_node_unsafe(p_call->arguments[0]);
  2429. } else {
  2430. if (arg_type.kind == GDScriptParser::DataType::BUILTIN && arg_type.builtin_type == builtin_type) {
  2431. // Okay.
  2432. p_call->set_datatype(call_type);
  2433. return;
  2434. }
  2435. }
  2436. }
  2437. List<MethodInfo> constructors;
  2438. Variant::get_constructor_list(builtin_type, &constructors);
  2439. bool match = false;
  2440. for (const MethodInfo &info : constructors) {
  2441. if (p_call->arguments.size() < info.arguments.size() - info.default_arguments.size()) {
  2442. continue;
  2443. }
  2444. if (p_call->arguments.size() > info.arguments.size()) {
  2445. continue;
  2446. }
  2447. bool types_match = true;
  2448. for (int i = 0; i < p_call->arguments.size(); i++) {
  2449. GDScriptParser::DataType par_type = type_from_property(info.arguments[i], true);
  2450. if (!is_type_compatible(par_type, p_call->arguments[i]->get_datatype(), true)) {
  2451. types_match = false;
  2452. break;
  2453. #ifdef DEBUG_ENABLED
  2454. } else {
  2455. if (par_type.builtin_type == Variant::INT && p_call->arguments[i]->get_datatype().builtin_type == Variant::FLOAT && builtin_type != Variant::INT) {
  2456. parser->push_warning(p_call, GDScriptWarning::NARROWING_CONVERSION, p_call->function_name);
  2457. }
  2458. #endif
  2459. }
  2460. }
  2461. if (types_match) {
  2462. for (int i = 0; i < p_call->arguments.size(); i++) {
  2463. if (p_call->arguments[i]->is_constant) {
  2464. update_const_expression_builtin_type(p_call->arguments[i], type_from_property(info.arguments[i], true), "pass");
  2465. }
  2466. }
  2467. match = true;
  2468. call_type = type_from_property(info.return_val);
  2469. break;
  2470. }
  2471. }
  2472. if (!match) {
  2473. String signature = Variant::get_type_name(builtin_type) + "(";
  2474. for (int i = 0; i < p_call->arguments.size(); i++) {
  2475. if (i > 0) {
  2476. signature += ", ";
  2477. }
  2478. signature += p_call->arguments[i]->get_datatype().to_string();
  2479. }
  2480. signature += ")";
  2481. push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call);
  2482. }
  2483. }
  2484. p_call->set_datatype(call_type);
  2485. return;
  2486. } else if (GDScriptUtilityFunctions::function_exists(function_name)) {
  2487. MethodInfo function_info = GDScriptUtilityFunctions::get_function_info(function_name);
  2488. if (!p_is_root && !p_is_await && function_info.return_val.type == Variant::NIL && ((function_info.return_val.usage & PROPERTY_USAGE_NIL_IS_VARIANT) == 0)) {
  2489. push_error(vformat(R"*(Cannot get return value of call to "%s()" because it returns "void".)*", function_name), p_call);
  2490. }
  2491. if (all_is_constant && GDScriptUtilityFunctions::is_function_constant(function_name)) {
  2492. // Can call on compilation.
  2493. Vector<const Variant *> args;
  2494. for (int i = 0; i < p_call->arguments.size(); i++) {
  2495. args.push_back(&(p_call->arguments[i]->reduced_value));
  2496. }
  2497. Variant value;
  2498. Callable::CallError err;
  2499. GDScriptUtilityFunctions::get_function(function_name)(&value, (const Variant **)args.ptr(), args.size(), err);
  2500. switch (err.error) {
  2501. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT: {
  2502. PropertyInfo wrong_arg = function_info.arguments[err.argument];
  2503. push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be "%s" but is "%s".)*", function_name, err.argument + 1,
  2504. type_from_property(wrong_arg, true).to_string(), p_call->arguments[err.argument]->get_datatype().to_string()),
  2505. p_call->arguments[err.argument]);
  2506. } break;
  2507. case Callable::CallError::CALL_ERROR_INVALID_METHOD:
  2508. push_error(vformat(R"(Invalid call for function "%s".)", function_name), p_call);
  2509. break;
  2510. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  2511. push_error(vformat(R"*(Too many arguments for "%s()" call. Expected at most %d but received %d.)*", function_name, err.expected, p_call->arguments.size()), p_call);
  2512. break;
  2513. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  2514. push_error(vformat(R"*(Too few arguments for "%s()" call. Expected at least %d but received %d.)*", function_name, err.expected, p_call->arguments.size()), p_call);
  2515. break;
  2516. case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
  2517. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
  2518. break; // Can't happen in a builtin constructor.
  2519. case Callable::CallError::CALL_OK:
  2520. p_call->is_constant = true;
  2521. p_call->reduced_value = value;
  2522. break;
  2523. }
  2524. } else {
  2525. validate_call_arg(function_info, p_call);
  2526. }
  2527. p_call->set_datatype(type_from_property(function_info.return_val));
  2528. return;
  2529. } else if (Variant::has_utility_function(function_name)) {
  2530. MethodInfo function_info = info_from_utility_func(function_name);
  2531. if (!p_is_root && !p_is_await && function_info.return_val.type == Variant::NIL && ((function_info.return_val.usage & PROPERTY_USAGE_NIL_IS_VARIANT) == 0)) {
  2532. push_error(vformat(R"*(Cannot get return value of call to "%s()" because it returns "void".)*", function_name), p_call);
  2533. }
  2534. if (all_is_constant && Variant::get_utility_function_type(function_name) == Variant::UTILITY_FUNC_TYPE_MATH) {
  2535. // Can call on compilation.
  2536. Vector<const Variant *> args;
  2537. for (int i = 0; i < p_call->arguments.size(); i++) {
  2538. args.push_back(&(p_call->arguments[i]->reduced_value));
  2539. }
  2540. Variant value;
  2541. Callable::CallError err;
  2542. Variant::call_utility_function(function_name, &value, (const Variant **)args.ptr(), args.size(), err);
  2543. switch (err.error) {
  2544. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT: {
  2545. String expected_type_name;
  2546. if (err.argument < function_info.arguments.size()) {
  2547. expected_type_name = type_from_property(function_info.arguments[err.argument], true).to_string();
  2548. } else {
  2549. expected_type_name = Variant::get_type_name((Variant::Type)err.expected);
  2550. }
  2551. push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be "%s" but is "%s".)*", function_name, err.argument + 1,
  2552. expected_type_name, p_call->arguments[err.argument]->get_datatype().to_string()),
  2553. p_call->arguments[err.argument]);
  2554. } break;
  2555. case Callable::CallError::CALL_ERROR_INVALID_METHOD:
  2556. push_error(vformat(R"(Invalid call for function "%s".)", function_name), p_call);
  2557. break;
  2558. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  2559. push_error(vformat(R"*(Too many arguments for "%s()" call. Expected at most %d but received %d.)*", function_name, err.expected, p_call->arguments.size()), p_call);
  2560. break;
  2561. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  2562. push_error(vformat(R"*(Too few arguments for "%s()" call. Expected at least %d but received %d.)*", function_name, err.expected, p_call->arguments.size()), p_call);
  2563. break;
  2564. case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
  2565. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
  2566. break; // Can't happen in a builtin constructor.
  2567. case Callable::CallError::CALL_OK:
  2568. p_call->is_constant = true;
  2569. p_call->reduced_value = value;
  2570. break;
  2571. }
  2572. } else {
  2573. validate_call_arg(function_info, p_call);
  2574. }
  2575. p_call->set_datatype(type_from_property(function_info.return_val));
  2576. return;
  2577. }
  2578. }
  2579. GDScriptParser::DataType base_type;
  2580. call_type.kind = GDScriptParser::DataType::VARIANT;
  2581. bool is_self = false;
  2582. if (p_call->is_super) {
  2583. base_type = parser->current_class->base_type;
  2584. base_type.is_meta_type = false;
  2585. is_self = true;
  2586. if (p_call->callee == nullptr && !lambda_stack.is_empty()) {
  2587. push_error("Cannot use `super()` inside a lambda.", p_call);
  2588. }
  2589. } else if (callee_type == GDScriptParser::Node::IDENTIFIER) {
  2590. base_type = parser->current_class->get_datatype();
  2591. base_type.is_meta_type = false;
  2592. is_self = true;
  2593. } else if (callee_type == GDScriptParser::Node::SUBSCRIPT) {
  2594. GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee);
  2595. if (subscript->base == nullptr) {
  2596. // Invalid syntax, error already set on parser.
  2597. p_call->set_datatype(call_type);
  2598. mark_node_unsafe(p_call);
  2599. return;
  2600. }
  2601. if (!subscript->is_attribute) {
  2602. // Invalid call. Error already sent in parser.
  2603. // TODO: Could check if Callable here.
  2604. p_call->set_datatype(call_type);
  2605. mark_node_unsafe(p_call);
  2606. return;
  2607. }
  2608. if (subscript->attribute == nullptr) {
  2609. // Invalid call. Error already sent in parser.
  2610. p_call->set_datatype(call_type);
  2611. mark_node_unsafe(p_call);
  2612. return;
  2613. }
  2614. GDScriptParser::IdentifierNode *base_id = nullptr;
  2615. if (subscript->base->type == GDScriptParser::Node::IDENTIFIER) {
  2616. base_id = static_cast<GDScriptParser::IdentifierNode *>(subscript->base);
  2617. }
  2618. if (base_id && GDScriptParser::get_builtin_type(base_id->name) < Variant::VARIANT_MAX) {
  2619. base_type = make_builtin_meta_type(GDScriptParser::get_builtin_type(base_id->name));
  2620. } else {
  2621. reduce_expression(subscript->base);
  2622. base_type = subscript->base->get_datatype();
  2623. is_self = subscript->base->type == GDScriptParser::Node::SELF;
  2624. }
  2625. } else {
  2626. // Invalid call. Error already sent in parser.
  2627. // TODO: Could check if Callable here too.
  2628. p_call->set_datatype(call_type);
  2629. mark_node_unsafe(p_call);
  2630. return;
  2631. }
  2632. bool is_static = false;
  2633. bool is_vararg = false;
  2634. int default_arg_count = 0;
  2635. GDScriptParser::DataType return_type;
  2636. List<GDScriptParser::DataType> par_types;
  2637. bool is_constructor = (base_type.is_meta_type || (p_call->callee && p_call->callee->type == GDScriptParser::Node::IDENTIFIER)) && p_call->function_name == SNAME("new");
  2638. if (get_function_signature(p_call, is_constructor, base_type, p_call->function_name, return_type, par_types, default_arg_count, is_static, is_vararg)) {
  2639. // If the function require typed arrays we must make literals be typed.
  2640. for (const KeyValue<int, GDScriptParser::ArrayNode *> &E : arrays) {
  2641. int index = E.key;
  2642. if (index < par_types.size() && par_types[index].has_container_element_type()) {
  2643. update_array_literal_element_type(E.value, par_types[index].get_container_element_type());
  2644. }
  2645. }
  2646. validate_call_arg(par_types, default_arg_count, is_vararg, p_call);
  2647. if (base_type.kind == GDScriptParser::DataType::ENUM && base_type.is_meta_type) {
  2648. // Enum type is treated as a dictionary value for function calls.
  2649. base_type.is_meta_type = false;
  2650. }
  2651. if (is_self && parser->current_function != nullptr && parser->current_function->is_static && !is_static) {
  2652. // Get the parent function above any lambda.
  2653. GDScriptParser::FunctionNode *parent_function = parser->current_function;
  2654. while (parent_function->source_lambda) {
  2655. parent_function = parent_function->source_lambda->parent_function;
  2656. }
  2657. push_error(vformat(R"*(Cannot call non-static function "%s()" from static function "%s()".)*", p_call->function_name, parent_function->identifier->name), p_call);
  2658. } else if (!is_self && base_type.is_meta_type && !is_static) {
  2659. base_type.is_meta_type = false; // For `to_string()`.
  2660. push_error(vformat(R"*(Cannot call non-static function "%s()" on the class "%s" directly. Make an instance instead.)*", p_call->function_name, base_type.to_string()), p_call);
  2661. } else if (is_self && !is_static) {
  2662. mark_lambda_use_self();
  2663. }
  2664. if (!p_is_root && !p_is_await && return_type.is_hard_type() && return_type.kind == GDScriptParser::DataType::BUILTIN && return_type.builtin_type == Variant::NIL) {
  2665. push_error(vformat(R"*(Cannot get return value of call to "%s()" because it returns "void".)*", p_call->function_name), p_call);
  2666. }
  2667. #ifdef DEBUG_ENABLED
  2668. if (p_is_root && return_type.kind != GDScriptParser::DataType::UNRESOLVED && return_type.builtin_type != Variant::NIL) {
  2669. parser->push_warning(p_call, GDScriptWarning::RETURN_VALUE_DISCARDED, p_call->function_name);
  2670. }
  2671. if (is_static && !base_type.is_meta_type && !(is_self && parser->current_function != nullptr && parser->current_function->is_static)) {
  2672. String caller_type = String(base_type.native_type);
  2673. if (caller_type.is_empty()) {
  2674. caller_type = base_type.to_string();
  2675. }
  2676. parser->push_warning(p_call, GDScriptWarning::STATIC_CALLED_ON_INSTANCE, p_call->function_name, caller_type);
  2677. }
  2678. #endif // DEBUG_ENABLED
  2679. call_type = return_type;
  2680. } else {
  2681. bool found = false;
  2682. // Enums do not have functions other than the built-in dictionary ones.
  2683. if (base_type.kind == GDScriptParser::DataType::ENUM && base_type.is_meta_type) {
  2684. if (base_type.builtin_type == Variant::DICTIONARY) {
  2685. push_error(vformat(R"*(Enums only have Dictionary built-in methods. Function "%s()" does not exist for enum "%s".)*", p_call->function_name, base_type.enum_type), p_call->callee);
  2686. } else {
  2687. push_error(vformat(R"*(The native enum "%s" does not behave like Dictionary and does not have methods of its own.)*", base_type.enum_type), p_call->callee);
  2688. }
  2689. } else if (!p_call->is_super && callee_type != GDScriptParser::Node::NONE) { // Check if the name exists as something else.
  2690. GDScriptParser::IdentifierNode *callee_id;
  2691. if (callee_type == GDScriptParser::Node::IDENTIFIER) {
  2692. callee_id = static_cast<GDScriptParser::IdentifierNode *>(p_call->callee);
  2693. } else {
  2694. // Can only be attribute.
  2695. callee_id = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee)->attribute;
  2696. }
  2697. if (callee_id) {
  2698. reduce_identifier_from_base(callee_id, &base_type);
  2699. GDScriptParser::DataType callee_datatype = callee_id->get_datatype();
  2700. if (callee_datatype.is_set() && !callee_datatype.is_variant()) {
  2701. found = true;
  2702. if (callee_datatype.builtin_type == Variant::CALLABLE) {
  2703. push_error(vformat(R"*(Name "%s" is a Callable. You can call it with "%s.call()" instead.)*", p_call->function_name, p_call->function_name), p_call->callee);
  2704. } else {
  2705. push_error(vformat(R"*(Name "%s" called as a function but is a "%s".)*", p_call->function_name, callee_datatype.to_string()), p_call->callee);
  2706. }
  2707. #ifdef DEBUG_ENABLED
  2708. } else if (!is_self && !(base_type.is_hard_type() && base_type.kind == GDScriptParser::DataType::BUILTIN)) {
  2709. parser->push_warning(p_call, GDScriptWarning::UNSAFE_METHOD_ACCESS, p_call->function_name, base_type.to_string());
  2710. mark_node_unsafe(p_call);
  2711. #endif
  2712. }
  2713. }
  2714. }
  2715. if (!found && (is_self || (base_type.is_hard_type() && base_type.kind == GDScriptParser::DataType::BUILTIN))) {
  2716. String base_name = is_self && !p_call->is_super ? "self" : base_type.to_string();
  2717. #ifdef TOOLS_ENABLED
  2718. #ifndef DISABLE_DEPRECATED
  2719. String rename_hint = String();
  2720. if (GLOBAL_GET(GDScriptWarning::get_settings_path_from_code(GDScriptWarning::Code::RENAMED_IN_GD4_HINT)).booleanize()) {
  2721. const char *renamed_function_name = check_for_renamed_identifier(p_call->function_name, p_call->type);
  2722. if (renamed_function_name) {
  2723. rename_hint = " " + vformat(R"(Did you mean to use "%s"?)", String(renamed_function_name) + "()");
  2724. }
  2725. }
  2726. push_error(vformat(R"*(Function "%s()" not found in base %s.%s)*", p_call->function_name, base_name, rename_hint), p_call->is_super ? p_call : p_call->callee);
  2727. #else // !DISABLE_DEPRECATED
  2728. push_error(vformat(R"*(Function "%s()" not found in base %s.)*", p_call->function_name, base_name), p_call->is_super ? p_call : p_call->callee);
  2729. #endif // DISABLE_DEPRECATED
  2730. #else
  2731. push_error(vformat(R"*(Function "%s()" not found in base %s.)*", p_call->function_name, base_name), p_call->is_super ? p_call : p_call->callee);
  2732. #endif
  2733. } else if (!found && (!p_call->is_super && base_type.is_hard_type() && base_type.kind == GDScriptParser::DataType::NATIVE && base_type.is_meta_type)) {
  2734. push_error(vformat(R"*(Static function "%s()" not found in base "%s".)*", p_call->function_name, base_type.native_type), p_call);
  2735. }
  2736. }
  2737. if (call_type.is_coroutine && !p_is_await && !p_is_root) {
  2738. push_error(vformat(R"*(Function "%s()" is a coroutine, so it must be called with "await".)*", p_call->function_name), p_call);
  2739. }
  2740. p_call->set_datatype(call_type);
  2741. }
  2742. void GDScriptAnalyzer::reduce_cast(GDScriptParser::CastNode *p_cast) {
  2743. reduce_expression(p_cast->operand);
  2744. GDScriptParser::DataType cast_type = type_from_metatype(resolve_datatype(p_cast->cast_type));
  2745. if (!cast_type.is_set()) {
  2746. mark_node_unsafe(p_cast);
  2747. return;
  2748. }
  2749. p_cast->set_datatype(cast_type);
  2750. if (p_cast->operand->is_constant) {
  2751. update_const_expression_builtin_type(p_cast->operand, cast_type, "cast", true);
  2752. if (cast_type.is_variant() || p_cast->operand->get_datatype() == cast_type) {
  2753. p_cast->is_constant = true;
  2754. p_cast->reduced_value = p_cast->operand->reduced_value;
  2755. }
  2756. }
  2757. if (p_cast->operand->type == GDScriptParser::Node::ARRAY && cast_type.has_container_element_type()) {
  2758. update_array_literal_element_type(static_cast<GDScriptParser::ArrayNode *>(p_cast->operand), cast_type.get_container_element_type());
  2759. }
  2760. if (!cast_type.is_variant()) {
  2761. GDScriptParser::DataType op_type = p_cast->operand->get_datatype();
  2762. if (op_type.is_variant() || !op_type.is_hard_type()) {
  2763. mark_node_unsafe(p_cast);
  2764. #ifdef DEBUG_ENABLED
  2765. if (op_type.is_variant() && !op_type.is_hard_type()) {
  2766. parser->push_warning(p_cast, GDScriptWarning::UNSAFE_CAST, cast_type.to_string());
  2767. }
  2768. #endif
  2769. } else {
  2770. bool valid = false;
  2771. if (op_type.builtin_type == Variant::INT && cast_type.kind == GDScriptParser::DataType::ENUM) {
  2772. mark_node_unsafe(p_cast);
  2773. valid = true;
  2774. } else if (op_type.kind == GDScriptParser::DataType::BUILTIN && cast_type.kind == GDScriptParser::DataType::BUILTIN) {
  2775. valid = Variant::can_convert(op_type.builtin_type, cast_type.builtin_type);
  2776. } else if (op_type.kind != GDScriptParser::DataType::BUILTIN && cast_type.kind != GDScriptParser::DataType::BUILTIN) {
  2777. valid = is_type_compatible(cast_type, op_type) || is_type_compatible(op_type, cast_type);
  2778. }
  2779. if (!valid) {
  2780. push_error(vformat(R"(Invalid cast. Cannot convert from "%s" to "%s".)", op_type.to_string(), cast_type.to_string()), p_cast->cast_type);
  2781. }
  2782. }
  2783. }
  2784. }
  2785. void GDScriptAnalyzer::reduce_dictionary(GDScriptParser::DictionaryNode *p_dictionary) {
  2786. HashMap<Variant, GDScriptParser::ExpressionNode *, VariantHasher, StringLikeVariantComparator> elements;
  2787. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  2788. const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];
  2789. if (p_dictionary->style == GDScriptParser::DictionaryNode::PYTHON_DICT) {
  2790. reduce_expression(element.key);
  2791. }
  2792. reduce_expression(element.value);
  2793. if (element.key->is_constant) {
  2794. if (elements.has(element.key->reduced_value)) {
  2795. push_error(vformat(R"(Key "%s" was already used in this dictionary (at line %d).)", element.key->reduced_value, elements[element.key->reduced_value]->start_line), element.key);
  2796. } else {
  2797. elements[element.key->reduced_value] = element.value;
  2798. }
  2799. }
  2800. }
  2801. // It's dictionary in any case.
  2802. GDScriptParser::DataType dict_type;
  2803. dict_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2804. dict_type.kind = GDScriptParser::DataType::BUILTIN;
  2805. dict_type.builtin_type = Variant::DICTIONARY;
  2806. dict_type.is_constant = true;
  2807. p_dictionary->set_datatype(dict_type);
  2808. }
  2809. void GDScriptAnalyzer::reduce_get_node(GDScriptParser::GetNodeNode *p_get_node) {
  2810. GDScriptParser::DataType result;
  2811. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2812. result.kind = GDScriptParser::DataType::NATIVE;
  2813. result.native_type = SNAME("Node");
  2814. result.builtin_type = Variant::OBJECT;
  2815. if (!ClassDB::is_parent_class(parser->current_class->base_type.native_type, result.native_type)) {
  2816. push_error(R"*(Cannot use shorthand "get_node()" notation ("$") on a class that isn't a node.)*", p_get_node);
  2817. }
  2818. mark_lambda_use_self();
  2819. p_get_node->set_datatype(result);
  2820. }
  2821. GDScriptParser::DataType GDScriptAnalyzer::make_global_class_meta_type(const StringName &p_class_name, const GDScriptParser::Node *p_source) {
  2822. GDScriptParser::DataType type;
  2823. String path = ScriptServer::get_global_class_path(p_class_name);
  2824. String ext = path.get_extension();
  2825. if (ext == GDScriptLanguage::get_singleton()->get_extension()) {
  2826. Ref<GDScriptParserRef> ref = get_parser_for(path);
  2827. if (ref.is_null()) {
  2828. push_error(vformat(R"(Could not find script for class "%s".)", p_class_name), p_source);
  2829. type.type_source = GDScriptParser::DataType::UNDETECTED;
  2830. type.kind = GDScriptParser::DataType::VARIANT;
  2831. return type;
  2832. }
  2833. Error err = ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  2834. if (err) {
  2835. push_error(vformat(R"(Could not resolve class "%s", because of a parser error.)", p_class_name), p_source);
  2836. type.type_source = GDScriptParser::DataType::UNDETECTED;
  2837. type.kind = GDScriptParser::DataType::VARIANT;
  2838. return type;
  2839. }
  2840. return ref->get_parser()->head->get_datatype();
  2841. } else {
  2842. return make_script_meta_type(ResourceLoader::load(path, "Script"));
  2843. }
  2844. }
  2845. void GDScriptAnalyzer::reduce_identifier_from_base_set_class(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType p_identifier_datatype) {
  2846. ERR_FAIL_NULL(p_identifier);
  2847. p_identifier->set_datatype(p_identifier_datatype);
  2848. Error err = OK;
  2849. Ref<GDScript> scr = GDScriptCache::get_shallow_script(p_identifier_datatype.script_path, err);
  2850. if (err) {
  2851. push_error(vformat(R"(Error while getting cache for script "%s".)", p_identifier_datatype.script_path), p_identifier);
  2852. return;
  2853. }
  2854. p_identifier->reduced_value = scr->find_class(p_identifier_datatype.class_type->fqcn);
  2855. p_identifier->is_constant = true;
  2856. }
  2857. void GDScriptAnalyzer::reduce_identifier_from_base(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType *p_base) {
  2858. if (!p_identifier->get_datatype().has_no_type()) {
  2859. return;
  2860. }
  2861. GDScriptParser::DataType base;
  2862. if (p_base == nullptr) {
  2863. base = type_from_metatype(parser->current_class->get_datatype());
  2864. } else {
  2865. base = *p_base;
  2866. }
  2867. const StringName &name = p_identifier->name;
  2868. if (base.kind == GDScriptParser::DataType::ENUM) {
  2869. if (base.is_meta_type) {
  2870. if (base.enum_values.has(name)) {
  2871. p_identifier->set_datatype(type_from_metatype(base));
  2872. p_identifier->is_constant = true;
  2873. p_identifier->reduced_value = base.enum_values[name];
  2874. return;
  2875. }
  2876. // Enum does not have this value, return.
  2877. return;
  2878. } else {
  2879. push_error(R"(Cannot get property from enum value.)", p_identifier);
  2880. return;
  2881. }
  2882. }
  2883. if (base.kind == GDScriptParser::DataType::BUILTIN) {
  2884. if (base.is_meta_type) {
  2885. bool valid = true;
  2886. Variant result = Variant::get_constant_value(base.builtin_type, name, &valid);
  2887. if (valid) {
  2888. p_identifier->is_constant = true;
  2889. p_identifier->reduced_value = result;
  2890. p_identifier->set_datatype(type_from_variant(result, p_identifier));
  2891. } else if (base.is_hard_type()) {
  2892. #ifdef TOOLS_ENABLED
  2893. #ifndef DISABLE_DEPRECATED
  2894. String rename_hint = String();
  2895. if (GLOBAL_GET(GDScriptWarning::get_settings_path_from_code(GDScriptWarning::Code::RENAMED_IN_GD4_HINT)).booleanize()) {
  2896. const char *renamed_identifier_name = check_for_renamed_identifier(name, p_identifier->type);
  2897. if (renamed_identifier_name) {
  2898. rename_hint = " " + vformat(R"(Did you mean to use "%s"?)", renamed_identifier_name);
  2899. }
  2900. }
  2901. push_error(vformat(R"(Cannot find constant "%s" on base "%s".%s)", name, base.to_string(), rename_hint), p_identifier);
  2902. #else // !DISABLE_DEPRECATED
  2903. push_error(vformat(R"(Cannot find constant "%s" on base "%s".)", name, base.to_string()), p_identifier);
  2904. #endif // DISABLE_DEPRECATED
  2905. #else
  2906. push_error(vformat(R"(Cannot find constant "%s" on base "%s".)", name, base.to_string()), p_identifier);
  2907. #endif
  2908. }
  2909. } else {
  2910. switch (base.builtin_type) {
  2911. case Variant::NIL: {
  2912. if (base.is_hard_type()) {
  2913. push_error(vformat(R"(Invalid get index "%s" on base Nil)", name), p_identifier);
  2914. }
  2915. return;
  2916. }
  2917. case Variant::DICTIONARY: {
  2918. GDScriptParser::DataType dummy;
  2919. dummy.kind = GDScriptParser::DataType::VARIANT;
  2920. p_identifier->set_datatype(dummy);
  2921. return;
  2922. }
  2923. default: {
  2924. Callable::CallError temp;
  2925. Variant dummy;
  2926. Variant::construct(base.builtin_type, dummy, nullptr, 0, temp);
  2927. List<PropertyInfo> properties;
  2928. dummy.get_property_list(&properties);
  2929. for (const PropertyInfo &prop : properties) {
  2930. if (prop.name == name) {
  2931. p_identifier->set_datatype(type_from_property(prop));
  2932. return;
  2933. }
  2934. }
  2935. if (base.is_hard_type()) {
  2936. #ifdef TOOLS_ENABLED
  2937. #ifndef DISABLE_DEPRECATED
  2938. String rename_hint = String();
  2939. if (GLOBAL_GET(GDScriptWarning::get_settings_path_from_code(GDScriptWarning::Code::RENAMED_IN_GD4_HINT)).booleanize()) {
  2940. const char *renamed_identifier_name = check_for_renamed_identifier(name, p_identifier->type);
  2941. if (renamed_identifier_name) {
  2942. rename_hint = " " + vformat(R"(Did you mean to use "%s"?)", renamed_identifier_name);
  2943. }
  2944. }
  2945. push_error(vformat(R"(Cannot find property "%s" on base "%s".%s)", name, base.to_string(), rename_hint), p_identifier);
  2946. #else // !DISABLE_DEPRECATED
  2947. push_error(vformat(R"(Cannot find property "%s" on base "%s".)", name, base.to_string()), p_identifier);
  2948. #endif // DISABLE_DEPRECATED
  2949. #else
  2950. push_error(vformat(R"(Cannot find property "%s" on base "%s".)", name, base.to_string()), p_identifier);
  2951. #endif
  2952. }
  2953. }
  2954. }
  2955. }
  2956. return;
  2957. }
  2958. GDScriptParser::ClassNode *base_class = base.class_type;
  2959. List<GDScriptParser::ClassNode *> script_classes;
  2960. bool is_base = true;
  2961. if (base_class != nullptr) {
  2962. get_class_node_current_scope_classes(base_class, &script_classes);
  2963. }
  2964. for (GDScriptParser::ClassNode *script_class : script_classes) {
  2965. if (p_base == nullptr && script_class->identifier && script_class->identifier->name == name) {
  2966. reduce_identifier_from_base_set_class(p_identifier, script_class->get_datatype());
  2967. return;
  2968. }
  2969. if (script_class->has_member(name)) {
  2970. resolve_class_member(script_class, name, p_identifier);
  2971. GDScriptParser::ClassNode::Member member = script_class->get_member(name);
  2972. switch (member.type) {
  2973. case GDScriptParser::ClassNode::Member::CONSTANT: {
  2974. p_identifier->set_datatype(member.get_datatype());
  2975. p_identifier->is_constant = true;
  2976. p_identifier->reduced_value = member.constant->initializer->reduced_value;
  2977. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  2978. p_identifier->constant_source = member.constant;
  2979. return;
  2980. }
  2981. case GDScriptParser::ClassNode::Member::ENUM_VALUE: {
  2982. p_identifier->set_datatype(member.get_datatype());
  2983. p_identifier->is_constant = true;
  2984. p_identifier->reduced_value = member.enum_value.value;
  2985. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  2986. return;
  2987. }
  2988. case GDScriptParser::ClassNode::Member::ENUM: {
  2989. p_identifier->set_datatype(member.get_datatype());
  2990. p_identifier->is_constant = true;
  2991. p_identifier->reduced_value = member.m_enum->dictionary;
  2992. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  2993. return;
  2994. }
  2995. case GDScriptParser::ClassNode::Member::VARIABLE: {
  2996. if (is_base && !base.is_meta_type) {
  2997. p_identifier->set_datatype(member.get_datatype());
  2998. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_VARIABLE;
  2999. p_identifier->variable_source = member.variable;
  3000. member.variable->usages += 1;
  3001. return;
  3002. }
  3003. } break;
  3004. case GDScriptParser::ClassNode::Member::SIGNAL: {
  3005. if (is_base && !base.is_meta_type) {
  3006. p_identifier->set_datatype(member.get_datatype());
  3007. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_SIGNAL;
  3008. return;
  3009. }
  3010. } break;
  3011. case GDScriptParser::ClassNode::Member::FUNCTION: {
  3012. if (is_base && !base.is_meta_type) {
  3013. p_identifier->set_datatype(make_callable_type(member.function->info));
  3014. return;
  3015. }
  3016. } break;
  3017. case GDScriptParser::ClassNode::Member::CLASS: {
  3018. reduce_identifier_from_base_set_class(p_identifier, member.get_datatype());
  3019. return;
  3020. }
  3021. default: {
  3022. // Do nothing
  3023. }
  3024. }
  3025. }
  3026. if (is_base) {
  3027. is_base = script_class->base_type.class_type != nullptr;
  3028. if (!is_base && p_base != nullptr) {
  3029. break;
  3030. }
  3031. }
  3032. }
  3033. // Check native members. No need for native class recursion because Node exposes all Object's properties.
  3034. const StringName &native = base.native_type;
  3035. if (class_exists(native)) {
  3036. MethodInfo method_info;
  3037. if (ClassDB::has_property(native, name)) {
  3038. StringName getter_name = ClassDB::get_property_getter(native, name);
  3039. MethodBind *getter = ClassDB::get_method(native, getter_name);
  3040. if (getter != nullptr) {
  3041. bool has_setter = ClassDB::get_property_setter(native, name) != StringName();
  3042. p_identifier->set_datatype(type_from_property(getter->get_return_info(), false, !has_setter));
  3043. p_identifier->source = GDScriptParser::IdentifierNode::INHERITED_VARIABLE;
  3044. }
  3045. return;
  3046. }
  3047. if (ClassDB::get_method_info(native, name, &method_info)) {
  3048. // Method is callable.
  3049. p_identifier->set_datatype(make_callable_type(method_info));
  3050. p_identifier->source = GDScriptParser::IdentifierNode::INHERITED_VARIABLE;
  3051. return;
  3052. }
  3053. if (ClassDB::get_signal(native, name, &method_info)) {
  3054. // Signal is a type too.
  3055. p_identifier->set_datatype(make_signal_type(method_info));
  3056. p_identifier->source = GDScriptParser::IdentifierNode::INHERITED_VARIABLE;
  3057. return;
  3058. }
  3059. if (ClassDB::has_enum(native, name)) {
  3060. p_identifier->set_datatype(make_native_enum_type(name, native));
  3061. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  3062. return;
  3063. }
  3064. bool valid = false;
  3065. int64_t int_constant = ClassDB::get_integer_constant(native, name, &valid);
  3066. if (valid) {
  3067. p_identifier->is_constant = true;
  3068. p_identifier->reduced_value = int_constant;
  3069. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  3070. // Check whether this constant, which exists, belongs to an enum
  3071. StringName enum_name = ClassDB::get_integer_constant_enum(native, name);
  3072. if (enum_name != StringName()) {
  3073. p_identifier->set_datatype(make_native_enum_type(enum_name, native, false));
  3074. } else {
  3075. p_identifier->set_datatype(type_from_variant(int_constant, p_identifier));
  3076. }
  3077. }
  3078. }
  3079. }
  3080. void GDScriptAnalyzer::reduce_identifier(GDScriptParser::IdentifierNode *p_identifier, bool can_be_builtin) {
  3081. // TODO: This is an opportunity to further infer types.
  3082. // Check if we are inside an enum. This allows enum values to access other elements of the same enum.
  3083. if (current_enum) {
  3084. for (int i = 0; i < current_enum->values.size(); i++) {
  3085. const GDScriptParser::EnumNode::Value &element = current_enum->values[i];
  3086. if (element.identifier->name == p_identifier->name) {
  3087. StringName enum_name = current_enum->identifier ? current_enum->identifier->name : UNNAMED_ENUM;
  3088. GDScriptParser::DataType type = make_enum_type(enum_name, parser->current_class->fqcn, false);
  3089. if (element.parent_enum->identifier) {
  3090. type.enum_type = element.parent_enum->identifier->name;
  3091. }
  3092. p_identifier->set_datatype(type);
  3093. if (element.resolved) {
  3094. p_identifier->is_constant = true;
  3095. p_identifier->reduced_value = element.value;
  3096. } else {
  3097. push_error(R"(Cannot use another enum element before it was declared.)", p_identifier);
  3098. }
  3099. return; // Found anyway.
  3100. }
  3101. }
  3102. }
  3103. bool found_source = false;
  3104. // Check if identifier is local.
  3105. // If that's the case, the declaration already was solved before.
  3106. switch (p_identifier->source) {
  3107. case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER:
  3108. p_identifier->set_datatype(p_identifier->parameter_source->get_datatype());
  3109. found_source = true;
  3110. break;
  3111. case GDScriptParser::IdentifierNode::LOCAL_CONSTANT:
  3112. case GDScriptParser::IdentifierNode::MEMBER_CONSTANT:
  3113. p_identifier->set_datatype(p_identifier->constant_source->get_datatype());
  3114. p_identifier->is_constant = true;
  3115. // TODO: Constant should have a value on the node itself.
  3116. p_identifier->reduced_value = p_identifier->constant_source->initializer->reduced_value;
  3117. found_source = true;
  3118. break;
  3119. case GDScriptParser::IdentifierNode::MEMBER_SIGNAL:
  3120. case GDScriptParser::IdentifierNode::INHERITED_VARIABLE:
  3121. mark_lambda_use_self();
  3122. break;
  3123. case GDScriptParser::IdentifierNode::MEMBER_VARIABLE:
  3124. mark_lambda_use_self();
  3125. p_identifier->variable_source->usages++;
  3126. [[fallthrough]];
  3127. case GDScriptParser::IdentifierNode::LOCAL_VARIABLE:
  3128. p_identifier->set_datatype(p_identifier->variable_source->get_datatype());
  3129. found_source = true;
  3130. break;
  3131. case GDScriptParser::IdentifierNode::LOCAL_ITERATOR:
  3132. p_identifier->set_datatype(p_identifier->bind_source->get_datatype());
  3133. found_source = true;
  3134. break;
  3135. case GDScriptParser::IdentifierNode::LOCAL_BIND: {
  3136. GDScriptParser::DataType result = p_identifier->bind_source->get_datatype();
  3137. result.is_constant = true;
  3138. p_identifier->set_datatype(result);
  3139. found_source = true;
  3140. } break;
  3141. case GDScriptParser::IdentifierNode::UNDEFINED_SOURCE:
  3142. break;
  3143. }
  3144. // Not a local, so check members.
  3145. if (!found_source) {
  3146. reduce_identifier_from_base(p_identifier);
  3147. if (p_identifier->source != GDScriptParser::IdentifierNode::UNDEFINED_SOURCE || p_identifier->get_datatype().is_set()) {
  3148. // Found.
  3149. found_source = true;
  3150. }
  3151. }
  3152. if (found_source) {
  3153. bool source_is_variable = p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_VARIABLE || p_identifier->source == GDScriptParser::IdentifierNode::INHERITED_VARIABLE;
  3154. bool source_is_signal = p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_SIGNAL;
  3155. if ((source_is_variable || source_is_signal) && parser->current_function && parser->current_function->is_static) {
  3156. // Get the parent function above any lambda.
  3157. GDScriptParser::FunctionNode *parent_function = parser->current_function;
  3158. while (parent_function->source_lambda) {
  3159. parent_function = parent_function->source_lambda->parent_function;
  3160. }
  3161. push_error(vformat(R"*(Cannot access %s "%s" from the static function "%s()".)*", source_is_signal ? "signal" : "instance variable", p_identifier->name, parent_function->identifier->name), p_identifier);
  3162. }
  3163. if (!lambda_stack.is_empty()) {
  3164. // If the identifier is a member variable (including the native class properties) or a signal, we consider the lambda to be using `self`, so we keep a reference to the current instance.
  3165. if (source_is_variable || source_is_signal) {
  3166. mark_lambda_use_self();
  3167. return; // No need to capture.
  3168. }
  3169. // If the identifier is local, check if it's any kind of capture by comparing their source function.
  3170. // Only capture locals and enum values. Constants are still accessible from the lambda using the script reference. If not, this method is done.
  3171. if (p_identifier->source == GDScriptParser::IdentifierNode::UNDEFINED_SOURCE || p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_CONSTANT) {
  3172. return;
  3173. }
  3174. GDScriptParser::FunctionNode *function_test = lambda_stack.back()->get()->function;
  3175. // Make sure we aren't capturing variable in the same lambda.
  3176. // This also add captures for nested lambdas.
  3177. while (function_test != nullptr && function_test != p_identifier->source_function && function_test->source_lambda != nullptr && !function_test->source_lambda->captures_indices.has(p_identifier->name)) {
  3178. function_test->source_lambda->captures_indices[p_identifier->name] = function_test->source_lambda->captures.size();
  3179. function_test->source_lambda->captures.push_back(p_identifier);
  3180. function_test = function_test->source_lambda->parent_function;
  3181. }
  3182. }
  3183. return;
  3184. }
  3185. StringName name = p_identifier->name;
  3186. p_identifier->source = GDScriptParser::IdentifierNode::UNDEFINED_SOURCE;
  3187. // Check globals. We make an exception for Variant::OBJECT because it's the base class for
  3188. // non-builtin types so we allow doing e.g. Object.new()
  3189. Variant::Type builtin_type = GDScriptParser::get_builtin_type(name);
  3190. if (builtin_type != Variant::OBJECT && builtin_type < Variant::VARIANT_MAX) {
  3191. if (can_be_builtin) {
  3192. p_identifier->set_datatype(make_builtin_meta_type(builtin_type));
  3193. return;
  3194. } else {
  3195. push_error(R"(Builtin type cannot be used as a name on its own.)", p_identifier);
  3196. }
  3197. }
  3198. if (class_exists(name)) {
  3199. p_identifier->set_datatype(make_native_meta_type(name));
  3200. return;
  3201. }
  3202. if (ScriptServer::is_global_class(name)) {
  3203. p_identifier->set_datatype(make_global_class_meta_type(name, p_identifier));
  3204. return;
  3205. }
  3206. // Try singletons.
  3207. // Do this before globals because this might be a singleton loading another one before it's compiled.
  3208. if (ProjectSettings::get_singleton()->has_autoload(name)) {
  3209. const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(name);
  3210. if (autoload.is_singleton) {
  3211. // Singleton exists, so it's at least a Node.
  3212. GDScriptParser::DataType result;
  3213. result.kind = GDScriptParser::DataType::NATIVE;
  3214. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  3215. if (ResourceLoader::get_resource_type(autoload.path) == "GDScript") {
  3216. Ref<GDScriptParserRef> singl_parser = get_parser_for(autoload.path);
  3217. if (singl_parser.is_valid()) {
  3218. Error err = singl_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  3219. if (err == OK) {
  3220. result = type_from_metatype(singl_parser->get_parser()->head->get_datatype());
  3221. }
  3222. }
  3223. } else if (ResourceLoader::get_resource_type(autoload.path) == "PackedScene") {
  3224. if (GDScriptLanguage::get_singleton()->has_any_global_constant(name)) {
  3225. Variant constant = GDScriptLanguage::get_singleton()->get_any_global_constant(name);
  3226. Node *node = Object::cast_to<Node>(constant);
  3227. if (node != nullptr) {
  3228. Ref<GDScript> scr = node->get_script();
  3229. if (scr.is_valid()) {
  3230. Ref<GDScriptParserRef> singl_parser = get_parser_for(scr->get_script_path());
  3231. if (singl_parser.is_valid()) {
  3232. Error err = singl_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  3233. if (err == OK) {
  3234. result = type_from_metatype(singl_parser->get_parser()->head->get_datatype());
  3235. }
  3236. }
  3237. }
  3238. }
  3239. }
  3240. }
  3241. result.is_constant = true;
  3242. p_identifier->set_datatype(result);
  3243. return;
  3244. }
  3245. }
  3246. if (GDScriptLanguage::get_singleton()->has_any_global_constant(name)) {
  3247. Variant constant = GDScriptLanguage::get_singleton()->get_any_global_constant(name);
  3248. p_identifier->set_datatype(type_from_variant(constant, p_identifier));
  3249. p_identifier->is_constant = true;
  3250. p_identifier->reduced_value = constant;
  3251. return;
  3252. }
  3253. // Not found.
  3254. // Check if it's a builtin function.
  3255. if (GDScriptUtilityFunctions::function_exists(name)) {
  3256. push_error(vformat(R"(Built-in function "%s" cannot be used as an identifier.)", name), p_identifier);
  3257. } else {
  3258. #ifdef TOOLS_ENABLED
  3259. #ifndef DISABLE_DEPRECATED
  3260. String rename_hint = String();
  3261. if (GLOBAL_GET(GDScriptWarning::get_settings_path_from_code(GDScriptWarning::Code::RENAMED_IN_GD4_HINT)).booleanize()) {
  3262. const char *renamed_identifier_name = check_for_renamed_identifier(name, p_identifier->type);
  3263. if (renamed_identifier_name) {
  3264. rename_hint = " " + vformat(R"(Did you mean to use "%s"?)", renamed_identifier_name);
  3265. }
  3266. }
  3267. push_error(vformat(R"(Identifier "%s" not declared in the current scope.%s)", name, rename_hint), p_identifier);
  3268. #else // !DISABLE_DEPRECATED
  3269. push_error(vformat(R"(Identifier "%s" not declared in the current scope.)", name), p_identifier);
  3270. #endif // DISABLE_DEPRECATED
  3271. #else
  3272. push_error(vformat(R"(Identifier "%s" not declared in the current scope.)", name), p_identifier);
  3273. #endif
  3274. }
  3275. GDScriptParser::DataType dummy;
  3276. dummy.kind = GDScriptParser::DataType::VARIANT;
  3277. p_identifier->set_datatype(dummy); // Just so type is set to something.
  3278. }
  3279. void GDScriptAnalyzer::reduce_lambda(GDScriptParser::LambdaNode *p_lambda) {
  3280. // Lambda is always a Callable.
  3281. GDScriptParser::DataType lambda_type;
  3282. lambda_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  3283. lambda_type.kind = GDScriptParser::DataType::BUILTIN;
  3284. lambda_type.builtin_type = Variant::CALLABLE;
  3285. p_lambda->set_datatype(lambda_type);
  3286. if (p_lambda->function == nullptr) {
  3287. return;
  3288. }
  3289. lambda_stack.push_back(p_lambda);
  3290. resolve_function_signature(p_lambda->function, p_lambda, true);
  3291. resolve_function_body(p_lambda->function, true);
  3292. lambda_stack.pop_back();
  3293. int captures_amount = p_lambda->captures.size();
  3294. if (captures_amount > 0) {
  3295. // Create space for lambda parameters.
  3296. // At the beginning to not mess with optional parameters.
  3297. int param_count = p_lambda->function->parameters.size();
  3298. p_lambda->function->parameters.resize(param_count + captures_amount);
  3299. for (int i = param_count - 1; i >= 0; i--) {
  3300. p_lambda->function->parameters.write[i + captures_amount] = p_lambda->function->parameters[i];
  3301. p_lambda->function->parameters_indices[p_lambda->function->parameters[i]->identifier->name] = i + captures_amount;
  3302. }
  3303. // Add captures as extra parameters at the beginning.
  3304. for (int i = 0; i < p_lambda->captures.size(); i++) {
  3305. GDScriptParser::IdentifierNode *capture = p_lambda->captures[i];
  3306. GDScriptParser::ParameterNode *capture_param = parser->alloc_node<GDScriptParser::ParameterNode>();
  3307. capture_param->identifier = capture;
  3308. capture_param->usages = capture->usages;
  3309. capture_param->set_datatype(capture->get_datatype());
  3310. p_lambda->function->parameters.write[i] = capture_param;
  3311. p_lambda->function->parameters_indices[capture->name] = i;
  3312. }
  3313. }
  3314. }
  3315. void GDScriptAnalyzer::reduce_literal(GDScriptParser::LiteralNode *p_literal) {
  3316. p_literal->reduced_value = p_literal->value;
  3317. p_literal->is_constant = true;
  3318. p_literal->set_datatype(type_from_variant(p_literal->reduced_value, p_literal));
  3319. }
  3320. void GDScriptAnalyzer::reduce_preload(GDScriptParser::PreloadNode *p_preload) {
  3321. if (!p_preload->path) {
  3322. return;
  3323. }
  3324. reduce_expression(p_preload->path);
  3325. if (!p_preload->path->is_constant) {
  3326. push_error("Preloaded path must be a constant string.", p_preload->path);
  3327. return;
  3328. }
  3329. if (p_preload->path->reduced_value.get_type() != Variant::STRING) {
  3330. push_error("Preloaded path must be a constant string.", p_preload->path);
  3331. } else {
  3332. p_preload->resolved_path = p_preload->path->reduced_value;
  3333. // TODO: Save this as script dependency.
  3334. if (p_preload->resolved_path.is_relative_path()) {
  3335. p_preload->resolved_path = parser->script_path.get_base_dir().path_join(p_preload->resolved_path);
  3336. }
  3337. p_preload->resolved_path = p_preload->resolved_path.simplify_path();
  3338. if (!ResourceLoader::exists(p_preload->resolved_path)) {
  3339. Ref<FileAccess> file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);
  3340. if (file_check->file_exists(p_preload->resolved_path)) {
  3341. push_error(vformat(R"(Preload file "%s" has no resource loaders (unrecognized file extension).)", p_preload->resolved_path), p_preload->path);
  3342. } else {
  3343. push_error(vformat(R"(Preload file "%s" does not exist.)", p_preload->resolved_path), p_preload->path);
  3344. }
  3345. } else {
  3346. // TODO: Don't load if validating: use completion cache.
  3347. // Must load GDScript and PackedScenes separately to permit cyclic references
  3348. // as ResourceLoader::load() detect and reject those.
  3349. if (ResourceLoader::get_resource_type(p_preload->resolved_path) == "GDScript") {
  3350. Error err = OK;
  3351. Ref<GDScript> res = GDScriptCache::get_shallow_script(p_preload->resolved_path, err, parser->script_path);
  3352. p_preload->resource = res;
  3353. if (err != OK) {
  3354. push_error(vformat(R"(Could not preload resource script "%s".)", p_preload->resolved_path), p_preload->path);
  3355. }
  3356. } else if (ResourceLoader::get_resource_type(p_preload->resolved_path) == "PackedScene") {
  3357. Error err = OK;
  3358. Ref<PackedScene> res = GDScriptCache::get_packed_scene(p_preload->resolved_path, err, parser->script_path);
  3359. p_preload->resource = res;
  3360. if (err != OK) {
  3361. push_error(vformat(R"(Could not preload resource scene "%s".)", p_preload->resolved_path), p_preload->path);
  3362. }
  3363. } else {
  3364. p_preload->resource = ResourceLoader::load(p_preload->resolved_path);
  3365. if (p_preload->resource.is_null()) {
  3366. push_error(vformat(R"(Could not preload resource file "%s".)", p_preload->resolved_path), p_preload->path);
  3367. }
  3368. }
  3369. }
  3370. }
  3371. p_preload->is_constant = true;
  3372. p_preload->reduced_value = p_preload->resource;
  3373. p_preload->set_datatype(type_from_variant(p_preload->reduced_value, p_preload));
  3374. }
  3375. void GDScriptAnalyzer::reduce_self(GDScriptParser::SelfNode *p_self) {
  3376. p_self->is_constant = false;
  3377. p_self->set_datatype(type_from_metatype(parser->current_class->get_datatype()));
  3378. mark_lambda_use_self();
  3379. }
  3380. void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscript) {
  3381. if (p_subscript->base == nullptr) {
  3382. return;
  3383. }
  3384. if (p_subscript->base->type == GDScriptParser::Node::IDENTIFIER) {
  3385. reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_subscript->base), true);
  3386. } else {
  3387. reduce_expression(p_subscript->base);
  3388. }
  3389. GDScriptParser::DataType result_type;
  3390. if (p_subscript->is_attribute) {
  3391. if (p_subscript->attribute == nullptr) {
  3392. return;
  3393. }
  3394. GDScriptParser::DataType base_type = p_subscript->base->get_datatype();
  3395. bool valid = false;
  3396. // If the base is a metatype, use the analyzer instead.
  3397. if (p_subscript->base->is_constant && !base_type.is_meta_type) {
  3398. // Just try to get it.
  3399. Variant value = p_subscript->base->reduced_value.get_named(p_subscript->attribute->name, valid);
  3400. if (valid) {
  3401. p_subscript->is_constant = true;
  3402. p_subscript->reduced_value = value;
  3403. result_type = type_from_variant(value, p_subscript);
  3404. }
  3405. } else if (base_type.is_variant() || !base_type.is_hard_type()) {
  3406. valid = true;
  3407. result_type.kind = GDScriptParser::DataType::VARIANT;
  3408. mark_node_unsafe(p_subscript);
  3409. } else {
  3410. reduce_identifier_from_base(p_subscript->attribute, &base_type);
  3411. GDScriptParser::DataType attr_type = p_subscript->attribute->get_datatype();
  3412. if (attr_type.is_set()) {
  3413. valid = true;
  3414. result_type = attr_type;
  3415. p_subscript->is_constant = p_subscript->attribute->is_constant;
  3416. p_subscript->reduced_value = p_subscript->attribute->reduced_value;
  3417. } else if (!base_type.is_meta_type || !base_type.is_constant) {
  3418. valid = base_type.kind != GDScriptParser::DataType::BUILTIN;
  3419. #ifdef DEBUG_ENABLED
  3420. if (valid) {
  3421. parser->push_warning(p_subscript, GDScriptWarning::UNSAFE_PROPERTY_ACCESS, p_subscript->attribute->name, base_type.to_string());
  3422. }
  3423. #endif
  3424. result_type.kind = GDScriptParser::DataType::VARIANT;
  3425. mark_node_unsafe(p_subscript);
  3426. }
  3427. }
  3428. if (!valid) {
  3429. push_error(vformat(R"(Cannot find member "%s" in base "%s".)", p_subscript->attribute->name, type_from_metatype(base_type).to_string()), p_subscript->attribute);
  3430. result_type.kind = GDScriptParser::DataType::VARIANT;
  3431. }
  3432. } else {
  3433. if (p_subscript->index == nullptr) {
  3434. return;
  3435. }
  3436. reduce_expression(p_subscript->index);
  3437. if (p_subscript->base->is_constant && p_subscript->index->is_constant) {
  3438. // Just try to get it.
  3439. bool valid = false;
  3440. Variant value = p_subscript->base->reduced_value.get(p_subscript->index->reduced_value, &valid);
  3441. if (!valid) {
  3442. push_error(vformat(R"(Cannot get index "%s" from "%s".)", p_subscript->index->reduced_value, p_subscript->base->reduced_value), p_subscript->index);
  3443. result_type.kind = GDScriptParser::DataType::VARIANT;
  3444. } else {
  3445. p_subscript->is_constant = true;
  3446. p_subscript->reduced_value = value;
  3447. result_type = type_from_variant(value, p_subscript);
  3448. }
  3449. } else {
  3450. GDScriptParser::DataType base_type = p_subscript->base->get_datatype();
  3451. GDScriptParser::DataType index_type = p_subscript->index->get_datatype();
  3452. if (base_type.is_variant()) {
  3453. result_type.kind = GDScriptParser::DataType::VARIANT;
  3454. mark_node_unsafe(p_subscript);
  3455. } else {
  3456. if (base_type.kind == GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {
  3457. // Check if indexing is valid.
  3458. bool error = index_type.kind != GDScriptParser::DataType::BUILTIN && base_type.builtin_type != Variant::DICTIONARY;
  3459. if (!error) {
  3460. switch (base_type.builtin_type) {
  3461. // Expect int or real as index.
  3462. case Variant::PACKED_BYTE_ARRAY:
  3463. case Variant::PACKED_COLOR_ARRAY:
  3464. case Variant::PACKED_FLOAT32_ARRAY:
  3465. case Variant::PACKED_FLOAT64_ARRAY:
  3466. case Variant::PACKED_INT32_ARRAY:
  3467. case Variant::PACKED_INT64_ARRAY:
  3468. case Variant::PACKED_STRING_ARRAY:
  3469. case Variant::PACKED_VECTOR2_ARRAY:
  3470. case Variant::PACKED_VECTOR3_ARRAY:
  3471. case Variant::ARRAY:
  3472. case Variant::STRING:
  3473. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT;
  3474. break;
  3475. // Expect String only.
  3476. case Variant::RECT2:
  3477. case Variant::RECT2I:
  3478. case Variant::PLANE:
  3479. case Variant::QUATERNION:
  3480. case Variant::AABB:
  3481. case Variant::OBJECT:
  3482. error = index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME;
  3483. break;
  3484. // Expect String or number.
  3485. case Variant::BASIS:
  3486. case Variant::VECTOR2:
  3487. case Variant::VECTOR2I:
  3488. case Variant::VECTOR3:
  3489. case Variant::VECTOR3I:
  3490. case Variant::VECTOR4:
  3491. case Variant::VECTOR4I:
  3492. case Variant::TRANSFORM2D:
  3493. case Variant::TRANSFORM3D:
  3494. case Variant::PROJECTION:
  3495. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT &&
  3496. index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME;
  3497. break;
  3498. // Expect String or int.
  3499. case Variant::COLOR:
  3500. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME;
  3501. break;
  3502. // Don't support indexing, but we will check it later.
  3503. case Variant::RID:
  3504. case Variant::BOOL:
  3505. case Variant::CALLABLE:
  3506. case Variant::FLOAT:
  3507. case Variant::INT:
  3508. case Variant::NIL:
  3509. case Variant::NODE_PATH:
  3510. case Variant::SIGNAL:
  3511. case Variant::STRING_NAME:
  3512. break;
  3513. // Here for completeness.
  3514. case Variant::DICTIONARY:
  3515. case Variant::VARIANT_MAX:
  3516. break;
  3517. }
  3518. if (error) {
  3519. push_error(vformat(R"(Invalid index type "%s" for a base of type "%s".)", index_type.to_string(), base_type.to_string()), p_subscript->index);
  3520. }
  3521. }
  3522. } else if (base_type.kind != GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {
  3523. if (index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME) {
  3524. push_error(vformat(R"(Only String or StringName can be used as index for type "%s", but received a "%s".)", base_type.to_string(), index_type.to_string()), p_subscript->index);
  3525. }
  3526. }
  3527. // Check resulting type if possible.
  3528. result_type.builtin_type = Variant::NIL;
  3529. result_type.kind = GDScriptParser::DataType::BUILTIN;
  3530. result_type.type_source = base_type.is_hard_type() ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED;
  3531. if (base_type.kind != GDScriptParser::DataType::BUILTIN) {
  3532. base_type.builtin_type = Variant::OBJECT;
  3533. }
  3534. switch (base_type.builtin_type) {
  3535. // Can't index at all.
  3536. case Variant::RID:
  3537. case Variant::BOOL:
  3538. case Variant::CALLABLE:
  3539. case Variant::FLOAT:
  3540. case Variant::INT:
  3541. case Variant::NIL:
  3542. case Variant::NODE_PATH:
  3543. case Variant::SIGNAL:
  3544. case Variant::STRING_NAME:
  3545. result_type.kind = GDScriptParser::DataType::VARIANT;
  3546. push_error(vformat(R"(Cannot use subscript operator on a base of type "%s".)", base_type.to_string()), p_subscript->base);
  3547. break;
  3548. // Return int.
  3549. case Variant::PACKED_BYTE_ARRAY:
  3550. case Variant::PACKED_INT32_ARRAY:
  3551. case Variant::PACKED_INT64_ARRAY:
  3552. case Variant::VECTOR2I:
  3553. case Variant::VECTOR3I:
  3554. case Variant::VECTOR4I:
  3555. result_type.builtin_type = Variant::INT;
  3556. break;
  3557. // Return float.
  3558. case Variant::PACKED_FLOAT32_ARRAY:
  3559. case Variant::PACKED_FLOAT64_ARRAY:
  3560. case Variant::VECTOR2:
  3561. case Variant::VECTOR3:
  3562. case Variant::VECTOR4:
  3563. case Variant::QUATERNION:
  3564. result_type.builtin_type = Variant::FLOAT;
  3565. break;
  3566. // Return Color.
  3567. case Variant::PACKED_COLOR_ARRAY:
  3568. result_type.builtin_type = Variant::COLOR;
  3569. break;
  3570. // Return String.
  3571. case Variant::PACKED_STRING_ARRAY:
  3572. case Variant::STRING:
  3573. result_type.builtin_type = Variant::STRING;
  3574. break;
  3575. // Return Vector2.
  3576. case Variant::PACKED_VECTOR2_ARRAY:
  3577. case Variant::TRANSFORM2D:
  3578. case Variant::RECT2:
  3579. result_type.builtin_type = Variant::VECTOR2;
  3580. break;
  3581. // Return Vector2I.
  3582. case Variant::RECT2I:
  3583. result_type.builtin_type = Variant::VECTOR2I;
  3584. break;
  3585. // Return Vector3.
  3586. case Variant::PACKED_VECTOR3_ARRAY:
  3587. case Variant::AABB:
  3588. case Variant::BASIS:
  3589. result_type.builtin_type = Variant::VECTOR3;
  3590. break;
  3591. // Depends on the index.
  3592. case Variant::TRANSFORM3D:
  3593. case Variant::PROJECTION:
  3594. case Variant::PLANE:
  3595. case Variant::COLOR:
  3596. case Variant::DICTIONARY:
  3597. case Variant::OBJECT:
  3598. result_type.kind = GDScriptParser::DataType::VARIANT;
  3599. result_type.type_source = GDScriptParser::DataType::UNDETECTED;
  3600. break;
  3601. // Can have an element type.
  3602. case Variant::ARRAY:
  3603. if (base_type.has_container_element_type()) {
  3604. result_type = base_type.get_container_element_type();
  3605. result_type.type_source = base_type.type_source;
  3606. } else {
  3607. result_type.kind = GDScriptParser::DataType::VARIANT;
  3608. result_type.type_source = GDScriptParser::DataType::UNDETECTED;
  3609. }
  3610. break;
  3611. // Here for completeness.
  3612. case Variant::VARIANT_MAX:
  3613. break;
  3614. }
  3615. }
  3616. }
  3617. }
  3618. p_subscript->set_datatype(result_type);
  3619. }
  3620. void GDScriptAnalyzer::reduce_ternary_op(GDScriptParser::TernaryOpNode *p_ternary_op, bool p_is_root) {
  3621. reduce_expression(p_ternary_op->condition);
  3622. reduce_expression(p_ternary_op->true_expr, p_is_root);
  3623. reduce_expression(p_ternary_op->false_expr, p_is_root);
  3624. GDScriptParser::DataType result;
  3625. if (p_ternary_op->condition && p_ternary_op->condition->is_constant && p_ternary_op->true_expr->is_constant && p_ternary_op->false_expr && p_ternary_op->false_expr->is_constant) {
  3626. p_ternary_op->is_constant = true;
  3627. if (p_ternary_op->condition->reduced_value.booleanize()) {
  3628. p_ternary_op->reduced_value = p_ternary_op->true_expr->reduced_value;
  3629. } else {
  3630. p_ternary_op->reduced_value = p_ternary_op->false_expr->reduced_value;
  3631. }
  3632. }
  3633. GDScriptParser::DataType true_type;
  3634. if (p_ternary_op->true_expr) {
  3635. true_type = p_ternary_op->true_expr->get_datatype();
  3636. } else {
  3637. true_type.kind = GDScriptParser::DataType::VARIANT;
  3638. }
  3639. GDScriptParser::DataType false_type;
  3640. if (p_ternary_op->false_expr) {
  3641. false_type = p_ternary_op->false_expr->get_datatype();
  3642. } else {
  3643. false_type.kind = GDScriptParser::DataType::VARIANT;
  3644. }
  3645. if (true_type.is_variant() || false_type.is_variant()) {
  3646. result.kind = GDScriptParser::DataType::VARIANT;
  3647. } else {
  3648. result = true_type;
  3649. if (!is_type_compatible(true_type, false_type)) {
  3650. result = false_type;
  3651. if (!is_type_compatible(false_type, true_type)) {
  3652. result.kind = GDScriptParser::DataType::VARIANT;
  3653. #ifdef DEBUG_ENABLED
  3654. parser->push_warning(p_ternary_op, GDScriptWarning::INCOMPATIBLE_TERNARY);
  3655. #endif
  3656. }
  3657. }
  3658. }
  3659. result.type_source = true_type.is_hard_type() && false_type.is_hard_type() ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED;
  3660. p_ternary_op->set_datatype(result);
  3661. }
  3662. void GDScriptAnalyzer::reduce_unary_op(GDScriptParser::UnaryOpNode *p_unary_op) {
  3663. reduce_expression(p_unary_op->operand);
  3664. GDScriptParser::DataType result;
  3665. if (p_unary_op->operand == nullptr) {
  3666. result.kind = GDScriptParser::DataType::VARIANT;
  3667. p_unary_op->set_datatype(result);
  3668. return;
  3669. }
  3670. GDScriptParser::DataType operand_type = p_unary_op->operand->get_datatype();
  3671. if (p_unary_op->operand->is_constant) {
  3672. p_unary_op->is_constant = true;
  3673. p_unary_op->reduced_value = Variant::evaluate(p_unary_op->variant_op, p_unary_op->operand->reduced_value, Variant());
  3674. result = type_from_variant(p_unary_op->reduced_value, p_unary_op);
  3675. }
  3676. if (operand_type.is_variant()) {
  3677. result.kind = GDScriptParser::DataType::VARIANT;
  3678. mark_node_unsafe(p_unary_op);
  3679. } else {
  3680. bool valid = false;
  3681. result = get_operation_type(p_unary_op->variant_op, operand_type, valid, p_unary_op);
  3682. if (!valid) {
  3683. push_error(vformat(R"(Invalid operand of type "%s" for unary operator "%s".)", operand_type.to_string(), Variant::get_operator_name(p_unary_op->variant_op)), p_unary_op);
  3684. }
  3685. }
  3686. p_unary_op->set_datatype(result);
  3687. }
  3688. Variant GDScriptAnalyzer::make_expression_reduced_value(GDScriptParser::ExpressionNode *p_expression, bool &is_reduced) {
  3689. Variant value;
  3690. if (p_expression == nullptr) {
  3691. return value;
  3692. }
  3693. if (p_expression->is_constant) {
  3694. is_reduced = true;
  3695. value = p_expression->reduced_value;
  3696. } else if (p_expression->type == GDScriptParser::Node::ARRAY) {
  3697. value = make_array_reduced_value(static_cast<GDScriptParser::ArrayNode *>(p_expression), is_reduced);
  3698. } else if (p_expression->type == GDScriptParser::Node::DICTIONARY) {
  3699. value = make_dictionary_reduced_value(static_cast<GDScriptParser::DictionaryNode *>(p_expression), is_reduced);
  3700. } else if (p_expression->type == GDScriptParser::Node::SUBSCRIPT) {
  3701. value = make_subscript_reduced_value(static_cast<GDScriptParser::SubscriptNode *>(p_expression), is_reduced);
  3702. }
  3703. return value;
  3704. }
  3705. Variant GDScriptAnalyzer::make_array_reduced_value(GDScriptParser::ArrayNode *p_array, bool &is_reduced) {
  3706. Array array = p_array->get_datatype().has_container_element_type() ? make_array_from_element_datatype(p_array->get_datatype().get_container_element_type()) : Array();
  3707. array.resize(p_array->elements.size());
  3708. for (int i = 0; i < p_array->elements.size(); i++) {
  3709. GDScriptParser::ExpressionNode *element = p_array->elements[i];
  3710. bool is_element_value_reduced = false;
  3711. Variant element_value = make_expression_reduced_value(element, is_element_value_reduced);
  3712. if (!is_element_value_reduced) {
  3713. return Variant();
  3714. }
  3715. array[i] = element_value;
  3716. }
  3717. array.make_read_only();
  3718. is_reduced = true;
  3719. return array;
  3720. }
  3721. Variant GDScriptAnalyzer::make_dictionary_reduced_value(GDScriptParser::DictionaryNode *p_dictionary, bool &is_reduced) {
  3722. Dictionary dictionary;
  3723. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  3724. const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];
  3725. bool is_element_key_reduced = false;
  3726. Variant element_key = make_expression_reduced_value(element.key, is_element_key_reduced);
  3727. if (!is_element_key_reduced) {
  3728. return Variant();
  3729. }
  3730. bool is_element_value_reduced = false;
  3731. Variant element_value = make_expression_reduced_value(element.value, is_element_value_reduced);
  3732. if (!is_element_value_reduced) {
  3733. return Variant();
  3734. }
  3735. dictionary[element_key] = element_value;
  3736. }
  3737. dictionary.make_read_only();
  3738. is_reduced = true;
  3739. return dictionary;
  3740. }
  3741. Variant GDScriptAnalyzer::make_subscript_reduced_value(GDScriptParser::SubscriptNode *p_subscript, bool &is_reduced) {
  3742. if (p_subscript->base == nullptr || p_subscript->index == nullptr) {
  3743. return Variant();
  3744. }
  3745. bool is_base_value_reduced = false;
  3746. Variant base_value = make_expression_reduced_value(p_subscript->base, is_base_value_reduced);
  3747. if (!is_base_value_reduced) {
  3748. return Variant();
  3749. }
  3750. if (p_subscript->is_attribute) {
  3751. bool is_valid = false;
  3752. Variant value = base_value.get_named(p_subscript->attribute->name, is_valid);
  3753. if (is_valid) {
  3754. is_reduced = true;
  3755. return value;
  3756. } else {
  3757. return Variant();
  3758. }
  3759. } else {
  3760. bool is_index_value_reduced = false;
  3761. Variant index_value = make_expression_reduced_value(p_subscript->index, is_index_value_reduced);
  3762. if (!is_index_value_reduced) {
  3763. return Variant();
  3764. }
  3765. bool is_valid = false;
  3766. Variant value = base_value.get(index_value, &is_valid);
  3767. if (is_valid) {
  3768. is_reduced = true;
  3769. return value;
  3770. } else {
  3771. return Variant();
  3772. }
  3773. }
  3774. }
  3775. Array GDScriptAnalyzer::make_array_from_element_datatype(const GDScriptParser::DataType &p_element_datatype, const GDScriptParser::Node *p_source_node) {
  3776. Array array;
  3777. Ref<Script> script_type = p_element_datatype.script_type;
  3778. if (p_element_datatype.kind == GDScriptParser::DataType::CLASS && script_type.is_null()) {
  3779. Error err = OK;
  3780. Ref<GDScript> scr = GDScriptCache::get_shallow_script(p_element_datatype.script_path, err);
  3781. if (err) {
  3782. push_error(vformat(R"(Error while getting cache for script "%s".)", p_element_datatype.script_path), p_source_node);
  3783. return array;
  3784. }
  3785. script_type.reference_ptr(scr->find_class(p_element_datatype.class_type->fqcn));
  3786. }
  3787. array.set_typed(p_element_datatype.builtin_type, p_element_datatype.native_type, script_type);
  3788. return array;
  3789. }
  3790. Variant GDScriptAnalyzer::make_variable_default_value(GDScriptParser::VariableNode *p_variable) {
  3791. Variant result = Variant();
  3792. if (p_variable->initializer) {
  3793. bool is_initializer_value_reduced = false;
  3794. Variant initializer_value = make_expression_reduced_value(p_variable->initializer, is_initializer_value_reduced);
  3795. if (is_initializer_value_reduced) {
  3796. result = initializer_value;
  3797. }
  3798. } else {
  3799. GDScriptParser::DataType datatype = p_variable->get_datatype();
  3800. if (datatype.is_hard_type() && datatype.kind == GDScriptParser::DataType::BUILTIN && datatype.builtin_type != Variant::OBJECT) {
  3801. if (datatype.builtin_type == Variant::ARRAY && datatype.has_container_element_type()) {
  3802. result = make_array_from_element_datatype(datatype.get_container_element_type());
  3803. } else {
  3804. VariantInternal::initialize(&result, datatype.builtin_type);
  3805. }
  3806. }
  3807. }
  3808. return result;
  3809. }
  3810. GDScriptParser::DataType GDScriptAnalyzer::type_from_variant(const Variant &p_value, const GDScriptParser::Node *p_source) {
  3811. GDScriptParser::DataType result;
  3812. result.is_constant = true;
  3813. result.kind = GDScriptParser::DataType::BUILTIN;
  3814. result.builtin_type = p_value.get_type();
  3815. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; // Constant has explicit type.
  3816. if (p_value.get_type() == Variant::OBJECT) {
  3817. // Object is treated as a native type, not a builtin type.
  3818. result.kind = GDScriptParser::DataType::NATIVE;
  3819. Object *obj = p_value;
  3820. if (!obj) {
  3821. return GDScriptParser::DataType();
  3822. }
  3823. result.native_type = obj->get_class_name();
  3824. Ref<Script> scr = p_value; // Check if value is a script itself.
  3825. if (scr.is_valid()) {
  3826. result.is_meta_type = true;
  3827. } else {
  3828. result.is_meta_type = false;
  3829. scr = obj->get_script();
  3830. }
  3831. if (scr.is_valid()) {
  3832. Ref<GDScript> gds = scr;
  3833. if (gds.is_valid()) {
  3834. // This might be an inner class, so we want to get the parser for the root.
  3835. // But still get the inner class from that tree.
  3836. String script_path = gds->get_script_path();
  3837. Ref<GDScriptParserRef> ref = get_parser_for(script_path);
  3838. if (ref.is_null()) {
  3839. push_error(vformat(R"(Could not find script "%s".)", script_path), p_source);
  3840. GDScriptParser::DataType error_type;
  3841. error_type.kind = GDScriptParser::DataType::VARIANT;
  3842. return error_type;
  3843. }
  3844. Error err = ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  3845. GDScriptParser::ClassNode *found = nullptr;
  3846. if (err == OK) {
  3847. found = ref->get_parser()->find_class(gds->fully_qualified_name);
  3848. if (found != nullptr) {
  3849. err = resolve_class_inheritance(found, p_source);
  3850. }
  3851. }
  3852. if (err || found == nullptr) {
  3853. push_error(vformat(R"(Could not resolve script "%s".)", script_path), p_source);
  3854. GDScriptParser::DataType error_type;
  3855. error_type.kind = GDScriptParser::DataType::VARIANT;
  3856. return error_type;
  3857. }
  3858. result.kind = GDScriptParser::DataType::CLASS;
  3859. result.native_type = found->get_datatype().native_type;
  3860. result.class_type = found;
  3861. result.script_path = ref->get_parser()->script_path;
  3862. } else {
  3863. result.kind = GDScriptParser::DataType::SCRIPT;
  3864. result.native_type = scr->get_instance_base_type();
  3865. result.script_path = scr->get_path();
  3866. }
  3867. result.script_type = scr;
  3868. } else {
  3869. result.kind = GDScriptParser::DataType::NATIVE;
  3870. if (result.native_type == GDScriptNativeClass::get_class_static()) {
  3871. result.is_meta_type = true;
  3872. }
  3873. }
  3874. }
  3875. return result;
  3876. }
  3877. GDScriptParser::DataType GDScriptAnalyzer::type_from_metatype(const GDScriptParser::DataType &p_meta_type) {
  3878. GDScriptParser::DataType result = p_meta_type;
  3879. result.is_meta_type = false;
  3880. if (p_meta_type.kind == GDScriptParser::DataType::ENUM) {
  3881. result.builtin_type = Variant::INT;
  3882. } else {
  3883. result.is_constant = false;
  3884. }
  3885. return result;
  3886. }
  3887. GDScriptParser::DataType GDScriptAnalyzer::type_from_property(const PropertyInfo &p_property, bool p_is_arg, bool p_is_readonly) const {
  3888. GDScriptParser::DataType result;
  3889. result.is_read_only = p_is_readonly;
  3890. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  3891. if (p_property.type == Variant::NIL && (p_is_arg || (p_property.usage & PROPERTY_USAGE_NIL_IS_VARIANT))) {
  3892. // Variant
  3893. result.kind = GDScriptParser::DataType::VARIANT;
  3894. return result;
  3895. }
  3896. result.builtin_type = p_property.type;
  3897. if (p_property.type == Variant::OBJECT) {
  3898. result.kind = GDScriptParser::DataType::NATIVE;
  3899. result.native_type = p_property.class_name == StringName() ? SNAME("Object") : p_property.class_name;
  3900. } else {
  3901. result.kind = GDScriptParser::DataType::BUILTIN;
  3902. result.builtin_type = p_property.type;
  3903. if (p_property.type == Variant::ARRAY && p_property.hint == PROPERTY_HINT_ARRAY_TYPE) {
  3904. // Check element type.
  3905. StringName elem_type_name = p_property.hint_string;
  3906. GDScriptParser::DataType elem_type;
  3907. elem_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  3908. Variant::Type elem_builtin_type = GDScriptParser::get_builtin_type(elem_type_name);
  3909. if (elem_builtin_type < Variant::VARIANT_MAX) {
  3910. // Builtin type.
  3911. elem_type.kind = GDScriptParser::DataType::BUILTIN;
  3912. elem_type.builtin_type = elem_builtin_type;
  3913. } else if (class_exists(elem_type_name)) {
  3914. elem_type.kind = GDScriptParser::DataType::NATIVE;
  3915. elem_type.builtin_type = Variant::OBJECT;
  3916. elem_type.native_type = p_property.hint_string;
  3917. } else if (ScriptServer::is_global_class(elem_type_name)) {
  3918. // Just load this as it shouldn't be a GDScript.
  3919. Ref<Script> script = ResourceLoader::load(ScriptServer::get_global_class_path(elem_type_name));
  3920. elem_type.kind = GDScriptParser::DataType::SCRIPT;
  3921. elem_type.builtin_type = Variant::OBJECT;
  3922. elem_type.native_type = script->get_instance_base_type();
  3923. elem_type.script_type = script;
  3924. } else {
  3925. ERR_FAIL_V_MSG(result, "Could not find element type from property hint of a typed array.");
  3926. }
  3927. elem_type.is_constant = false;
  3928. result.set_container_element_type(elem_type);
  3929. } else if (p_property.type == Variant::INT) {
  3930. // Check if it's enum.
  3931. if (p_property.class_name != StringName()) {
  3932. Vector<String> names = String(p_property.class_name).split(".");
  3933. if (names.size() == 2) {
  3934. result = make_native_enum_type(names[1], names[0], false);
  3935. result.is_constant = false;
  3936. }
  3937. }
  3938. }
  3939. }
  3940. return result;
  3941. }
  3942. bool GDScriptAnalyzer::get_function_signature(GDScriptParser::Node *p_source, bool p_is_constructor, GDScriptParser::DataType p_base_type, const StringName &p_function, GDScriptParser::DataType &r_return_type, List<GDScriptParser::DataType> &r_par_types, int &r_default_arg_count, bool &r_static, bool &r_vararg, StringName *r_native_class) {
  3943. r_static = false;
  3944. r_vararg = false;
  3945. r_default_arg_count = 0;
  3946. if (r_native_class) {
  3947. *r_native_class = StringName();
  3948. }
  3949. StringName function_name = p_function;
  3950. bool was_enum = false;
  3951. if (p_base_type.kind == GDScriptParser::DataType::ENUM) {
  3952. was_enum = true;
  3953. if (p_base_type.is_meta_type) {
  3954. // Enum type can be treated as a dictionary value.
  3955. p_base_type.kind = GDScriptParser::DataType::BUILTIN;
  3956. p_base_type.is_meta_type = false;
  3957. } else {
  3958. push_error("Cannot call function on enum value.", p_source);
  3959. return false;
  3960. }
  3961. }
  3962. if (p_base_type.kind == GDScriptParser::DataType::BUILTIN) {
  3963. // Construct a base type to get methods.
  3964. Callable::CallError err;
  3965. Variant dummy;
  3966. Variant::construct(p_base_type.builtin_type, dummy, nullptr, 0, err);
  3967. if (err.error != Callable::CallError::CALL_OK) {
  3968. ERR_FAIL_V_MSG(false, "Could not construct base Variant type.");
  3969. }
  3970. List<MethodInfo> methods;
  3971. dummy.get_method_list(&methods);
  3972. for (const MethodInfo &E : methods) {
  3973. if (E.name == p_function) {
  3974. function_signature_from_info(E, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  3975. r_static = Variant::is_builtin_method_static(p_base_type.builtin_type, function_name);
  3976. // Cannot use non-const methods on enums.
  3977. if (!r_static && was_enum && !(E.flags & METHOD_FLAG_CONST)) {
  3978. push_error(vformat(R"*(Cannot call non-const Dictionary function "%s()" on enum "%s".)*", p_function, p_base_type.enum_type), p_source);
  3979. }
  3980. return true;
  3981. }
  3982. }
  3983. return false;
  3984. }
  3985. StringName base_native = p_base_type.native_type;
  3986. if (base_native != StringName()) {
  3987. // Empty native class might happen in some Script implementations.
  3988. // Just ignore it.
  3989. if (!class_exists(base_native)) {
  3990. push_error(vformat("Native class %s used in script doesn't exist or isn't exposed.", base_native), p_source);
  3991. return false;
  3992. } else if (p_is_constructor && !ClassDB::can_instantiate(base_native)) {
  3993. if (p_base_type.kind == GDScriptParser::DataType::CLASS) {
  3994. push_error(vformat(R"(Class "%s" cannot be constructed as it is based on abstract native class "%s".)", p_base_type.class_type->fqcn.get_file(), base_native), p_source);
  3995. } else if (p_base_type.kind == GDScriptParser::DataType::SCRIPT) {
  3996. push_error(vformat(R"(Script "%s" cannot be constructed as it is based on abstract native class "%s".)", p_base_type.script_path.get_file(), base_native), p_source);
  3997. } else {
  3998. push_error(vformat(R"(Native class "%s" cannot be constructed as it is abstract.)", base_native), p_source);
  3999. }
  4000. return false;
  4001. }
  4002. }
  4003. if (p_is_constructor) {
  4004. function_name = "_init";
  4005. r_static = true;
  4006. }
  4007. GDScriptParser::ClassNode *base_class = p_base_type.class_type;
  4008. GDScriptParser::FunctionNode *found_function = nullptr;
  4009. while (found_function == nullptr && base_class != nullptr) {
  4010. if (base_class->has_member(function_name)) {
  4011. if (base_class->get_member(function_name).type != GDScriptParser::ClassNode::Member::FUNCTION) {
  4012. // TODO: If this is Callable it can have a better error message.
  4013. push_error(vformat(R"(Member "%s" is not a function.)", function_name), p_source);
  4014. return false;
  4015. }
  4016. resolve_class_member(base_class, function_name, p_source);
  4017. found_function = base_class->get_member(function_name).function;
  4018. }
  4019. resolve_class_inheritance(base_class, p_source);
  4020. base_class = base_class->base_type.class_type;
  4021. }
  4022. if (found_function != nullptr) {
  4023. r_static = p_is_constructor || found_function->is_static;
  4024. for (int i = 0; i < found_function->parameters.size(); i++) {
  4025. r_par_types.push_back(found_function->parameters[i]->get_datatype());
  4026. if (found_function->parameters[i]->initializer != nullptr) {
  4027. r_default_arg_count++;
  4028. }
  4029. }
  4030. r_return_type = p_is_constructor ? p_base_type : found_function->get_datatype();
  4031. r_return_type.is_meta_type = false;
  4032. r_return_type.is_coroutine = found_function->is_coroutine;
  4033. return true;
  4034. }
  4035. Ref<Script> base_script = p_base_type.script_type;
  4036. while (base_script.is_valid() && base_script->has_method(function_name)) {
  4037. MethodInfo info = base_script->get_method_info(function_name);
  4038. if (!(info == MethodInfo())) {
  4039. return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  4040. }
  4041. base_script = base_script->get_base_script();
  4042. }
  4043. // If the base is a script, it might be trying to access members of the Script class itself.
  4044. if (p_base_type.is_meta_type && !p_is_constructor && (p_base_type.kind == GDScriptParser::DataType::SCRIPT || p_base_type.kind == GDScriptParser::DataType::CLASS)) {
  4045. MethodInfo info;
  4046. StringName script_class = p_base_type.kind == GDScriptParser::DataType::SCRIPT ? p_base_type.script_type->get_class_name() : StringName(GDScript::get_class_static());
  4047. if (ClassDB::get_method_info(script_class, function_name, &info)) {
  4048. return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  4049. }
  4050. }
  4051. if (p_is_constructor) {
  4052. // Native types always have a default constructor.
  4053. r_return_type = p_base_type;
  4054. r_return_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  4055. r_return_type.is_meta_type = false;
  4056. return true;
  4057. }
  4058. MethodInfo info;
  4059. if (ClassDB::get_method_info(base_native, function_name, &info)) {
  4060. bool valid = function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  4061. if (valid && Engine::get_singleton()->has_singleton(base_native)) {
  4062. r_static = true;
  4063. }
  4064. #ifdef DEBUG_ENABLED
  4065. MethodBind *native_method = ClassDB::get_method(base_native, function_name);
  4066. if (native_method && r_native_class) {
  4067. *r_native_class = native_method->get_instance_class();
  4068. }
  4069. #endif
  4070. return valid;
  4071. }
  4072. return false;
  4073. }
  4074. bool GDScriptAnalyzer::function_signature_from_info(const MethodInfo &p_info, GDScriptParser::DataType &r_return_type, List<GDScriptParser::DataType> &r_par_types, int &r_default_arg_count, bool &r_static, bool &r_vararg) {
  4075. r_return_type = type_from_property(p_info.return_val);
  4076. r_default_arg_count = p_info.default_arguments.size();
  4077. r_vararg = (p_info.flags & METHOD_FLAG_VARARG) != 0;
  4078. r_static = (p_info.flags & METHOD_FLAG_STATIC) != 0;
  4079. for (const PropertyInfo &E : p_info.arguments) {
  4080. r_par_types.push_back(type_from_property(E, true));
  4081. }
  4082. return true;
  4083. }
  4084. void GDScriptAnalyzer::validate_call_arg(const MethodInfo &p_method, const GDScriptParser::CallNode *p_call) {
  4085. List<GDScriptParser::DataType> arg_types;
  4086. for (const PropertyInfo &E : p_method.arguments) {
  4087. arg_types.push_back(type_from_property(E, true));
  4088. }
  4089. validate_call_arg(arg_types, p_method.default_arguments.size(), (p_method.flags & METHOD_FLAG_VARARG) != 0, p_call);
  4090. }
  4091. void GDScriptAnalyzer::validate_call_arg(const List<GDScriptParser::DataType> &p_par_types, int p_default_args_count, bool p_is_vararg, const GDScriptParser::CallNode *p_call) {
  4092. if (p_call->arguments.size() < p_par_types.size() - p_default_args_count) {
  4093. push_error(vformat(R"*(Too few arguments for "%s()" call. Expected at least %d but received %d.)*", p_call->function_name, p_par_types.size() - p_default_args_count, p_call->arguments.size()), p_call);
  4094. }
  4095. if (!p_is_vararg && p_call->arguments.size() > p_par_types.size()) {
  4096. push_error(vformat(R"*(Too many arguments for "%s()" call. Expected at most %d but received %d.)*", p_call->function_name, p_par_types.size(), p_call->arguments.size()), p_call->arguments[p_par_types.size()]);
  4097. }
  4098. for (int i = 0; i < p_call->arguments.size(); i++) {
  4099. if (i >= p_par_types.size()) {
  4100. // Already on vararg place.
  4101. break;
  4102. }
  4103. GDScriptParser::DataType par_type = p_par_types[i];
  4104. if (par_type.is_hard_type() && p_call->arguments[i]->is_constant) {
  4105. update_const_expression_builtin_type(p_call->arguments[i], par_type, "pass");
  4106. }
  4107. GDScriptParser::DataType arg_type = p_call->arguments[i]->get_datatype();
  4108. if ((arg_type.is_variant() || !arg_type.is_hard_type()) && !(par_type.is_hard_type() && par_type.is_variant())) {
  4109. // Argument can be anything, so this is unsafe.
  4110. mark_node_unsafe(p_call->arguments[i]);
  4111. } else if (par_type.is_hard_type() && !is_type_compatible(par_type, arg_type, true)) {
  4112. // Supertypes are acceptable for dynamic compliance, but it's unsafe.
  4113. mark_node_unsafe(p_call);
  4114. if (!is_type_compatible(arg_type, par_type)) {
  4115. push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be "%s" but is "%s".)*",
  4116. p_call->function_name, i + 1, par_type.to_string(), arg_type.to_string()),
  4117. p_call->arguments[i]);
  4118. }
  4119. #ifdef DEBUG_ENABLED
  4120. } else if (par_type.kind == GDScriptParser::DataType::BUILTIN && par_type.builtin_type == Variant::INT && arg_type.kind == GDScriptParser::DataType::BUILTIN && arg_type.builtin_type == Variant::FLOAT) {
  4121. parser->push_warning(p_call, GDScriptWarning::NARROWING_CONVERSION, p_call->function_name);
  4122. #endif
  4123. }
  4124. }
  4125. }
  4126. #ifdef DEBUG_ENABLED
  4127. bool GDScriptAnalyzer::is_shadowing(GDScriptParser::IdentifierNode *p_local, const String &p_context) {
  4128. const StringName &name = p_local->name;
  4129. GDScriptParser::DataType base = parser->current_class->get_datatype();
  4130. GDScriptParser::ClassNode *base_class = base.class_type;
  4131. {
  4132. List<MethodInfo> gdscript_funcs;
  4133. GDScriptLanguage::get_singleton()->get_public_functions(&gdscript_funcs);
  4134. for (MethodInfo &info : gdscript_funcs) {
  4135. if (info.name == name) {
  4136. parser->push_warning(p_local, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "built-in function");
  4137. return true;
  4138. }
  4139. }
  4140. if (Variant::has_utility_function(name)) {
  4141. parser->push_warning(p_local, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "built-in function");
  4142. return true;
  4143. } else if (ClassDB::class_exists(name)) {
  4144. parser->push_warning(p_local, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "global class");
  4145. return true;
  4146. }
  4147. }
  4148. while (base_class != nullptr) {
  4149. if (base_class->has_member(name)) {
  4150. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE, p_context, p_local->name, base_class->get_member(name).get_type_name(), itos(base_class->get_member(name).get_line()));
  4151. return true;
  4152. }
  4153. base_class = base_class->base_type.class_type;
  4154. }
  4155. StringName parent = base.native_type;
  4156. while (parent != StringName()) {
  4157. ERR_FAIL_COND_V_MSG(!class_exists(parent), false, "Non-existent native base class.");
  4158. if (ClassDB::has_method(parent, name, true)) {
  4159. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "method", parent);
  4160. return true;
  4161. } else if (ClassDB::has_signal(parent, name, true)) {
  4162. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "signal", parent);
  4163. return true;
  4164. } else if (ClassDB::has_property(parent, name, true)) {
  4165. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "property", parent);
  4166. return true;
  4167. } else if (ClassDB::has_integer_constant(parent, name, true)) {
  4168. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "constant", parent);
  4169. return true;
  4170. } else if (ClassDB::has_enum(parent, name, true)) {
  4171. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "enum", parent);
  4172. return true;
  4173. }
  4174. parent = ClassDB::get_parent_class(parent);
  4175. }
  4176. return false;
  4177. }
  4178. #endif
  4179. GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, bool &r_valid, const GDScriptParser::Node *p_source) {
  4180. // Unary version.
  4181. GDScriptParser::DataType nil_type;
  4182. nil_type.builtin_type = Variant::NIL;
  4183. nil_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  4184. return get_operation_type(p_operation, p_a, nil_type, r_valid, p_source);
  4185. }
  4186. GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, const GDScriptParser::DataType &p_b, bool &r_valid, const GDScriptParser::Node *p_source) {
  4187. Variant::Type a_type = p_a.builtin_type;
  4188. Variant::Type b_type = p_b.builtin_type;
  4189. if (p_a.kind == GDScriptParser::DataType::ENUM) {
  4190. if (p_a.is_meta_type) {
  4191. a_type = Variant::DICTIONARY;
  4192. } else {
  4193. a_type = Variant::INT;
  4194. }
  4195. }
  4196. if (p_b.kind == GDScriptParser::DataType::ENUM) {
  4197. if (p_b.is_meta_type) {
  4198. b_type = Variant::DICTIONARY;
  4199. } else {
  4200. b_type = Variant::INT;
  4201. }
  4202. }
  4203. Variant::ValidatedOperatorEvaluator op_eval = Variant::get_validated_operator_evaluator(p_operation, a_type, b_type);
  4204. bool hard_operation = p_a.is_hard_type() && p_b.is_hard_type();
  4205. bool validated = op_eval != nullptr;
  4206. GDScriptParser::DataType result;
  4207. if (validated) {
  4208. r_valid = true;
  4209. result.type_source = hard_operation ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED;
  4210. result.kind = GDScriptParser::DataType::BUILTIN;
  4211. result.builtin_type = Variant::get_operator_return_type(p_operation, a_type, b_type);
  4212. } else {
  4213. r_valid = !hard_operation;
  4214. result.kind = GDScriptParser::DataType::VARIANT;
  4215. }
  4216. return result;
  4217. }
  4218. // TODO: Add safe/unsafe return variable (for variant cases)
  4219. bool GDScriptAnalyzer::is_type_compatible(const GDScriptParser::DataType &p_target, const GDScriptParser::DataType &p_source, bool p_allow_implicit_conversion, const GDScriptParser::Node *p_source_node) {
  4220. // These return "true" so it doesn't affect users negatively.
  4221. ERR_FAIL_COND_V_MSG(!p_target.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset target type");
  4222. ERR_FAIL_COND_V_MSG(!p_source.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset value type");
  4223. if (p_target.kind == GDScriptParser::DataType::VARIANT) {
  4224. // Variant can receive anything.
  4225. return true;
  4226. }
  4227. if (p_source.kind == GDScriptParser::DataType::VARIANT) {
  4228. // TODO: This is acceptable but unsafe. Make sure unsafe line is set.
  4229. return true;
  4230. }
  4231. if (p_target.kind == GDScriptParser::DataType::BUILTIN) {
  4232. bool valid = p_source.kind == GDScriptParser::DataType::BUILTIN && p_target.builtin_type == p_source.builtin_type;
  4233. if (!valid && p_allow_implicit_conversion) {
  4234. valid = Variant::can_convert_strict(p_source.builtin_type, p_target.builtin_type);
  4235. }
  4236. if (!valid && p_target.builtin_type == Variant::INT && p_source.kind == GDScriptParser::DataType::ENUM && !p_source.is_meta_type) {
  4237. // Enum value is also integer.
  4238. valid = true;
  4239. }
  4240. if (valid && p_target.builtin_type == Variant::ARRAY && p_source.builtin_type == Variant::ARRAY) {
  4241. // Check the element type.
  4242. if (p_target.has_container_element_type() && p_source.has_container_element_type()) {
  4243. valid = p_target.get_container_element_type() == p_source.get_container_element_type();
  4244. }
  4245. }
  4246. return valid;
  4247. }
  4248. if (p_target.kind == GDScriptParser::DataType::ENUM) {
  4249. if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::INT) {
  4250. #ifdef DEBUG_ENABLED
  4251. if (p_source_node) {
  4252. parser->push_warning(p_source_node, GDScriptWarning::INT_AS_ENUM_WITHOUT_CAST);
  4253. }
  4254. #endif
  4255. return true;
  4256. }
  4257. if (p_source.kind == GDScriptParser::DataType::ENUM) {
  4258. if (p_source.native_type == p_target.native_type) {
  4259. return true;
  4260. }
  4261. }
  4262. return false;
  4263. }
  4264. // From here on the target type is an object, so we have to test polymorphism.
  4265. if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::NIL) {
  4266. // null is acceptable in object.
  4267. return true;
  4268. }
  4269. StringName src_native;
  4270. Ref<Script> src_script;
  4271. const GDScriptParser::ClassNode *src_class = nullptr;
  4272. switch (p_source.kind) {
  4273. case GDScriptParser::DataType::NATIVE:
  4274. if (p_target.kind != GDScriptParser::DataType::NATIVE) {
  4275. // Non-native class cannot be supertype of native.
  4276. return false;
  4277. }
  4278. if (p_source.is_meta_type) {
  4279. src_native = GDScriptNativeClass::get_class_static();
  4280. } else {
  4281. src_native = p_source.native_type;
  4282. }
  4283. break;
  4284. case GDScriptParser::DataType::SCRIPT:
  4285. if (p_target.kind == GDScriptParser::DataType::CLASS) {
  4286. // A script type cannot be a subtype of a GDScript class.
  4287. return false;
  4288. }
  4289. if (p_source.is_meta_type) {
  4290. src_native = p_source.script_type->get_class_name();
  4291. } else {
  4292. src_script = p_source.script_type;
  4293. src_native = src_script->get_instance_base_type();
  4294. }
  4295. break;
  4296. case GDScriptParser::DataType::CLASS:
  4297. if (p_source.is_meta_type) {
  4298. src_native = GDScript::get_class_static();
  4299. } else {
  4300. src_class = p_source.class_type;
  4301. const GDScriptParser::ClassNode *base = src_class;
  4302. while (base->base_type.kind == GDScriptParser::DataType::CLASS) {
  4303. base = base->base_type.class_type;
  4304. }
  4305. src_native = base->base_type.native_type;
  4306. src_script = base->base_type.script_type;
  4307. }
  4308. break;
  4309. case GDScriptParser::DataType::VARIANT:
  4310. case GDScriptParser::DataType::BUILTIN:
  4311. case GDScriptParser::DataType::ENUM:
  4312. case GDScriptParser::DataType::RESOLVING:
  4313. case GDScriptParser::DataType::UNRESOLVED:
  4314. break; // Already solved before.
  4315. }
  4316. switch (p_target.kind) {
  4317. case GDScriptParser::DataType::NATIVE: {
  4318. if (p_target.is_meta_type) {
  4319. return ClassDB::is_parent_class(src_native, GDScriptNativeClass::get_class_static());
  4320. }
  4321. return ClassDB::is_parent_class(src_native, p_target.native_type);
  4322. }
  4323. case GDScriptParser::DataType::SCRIPT:
  4324. if (p_target.is_meta_type) {
  4325. return ClassDB::is_parent_class(src_native, p_target.script_type->get_class_name());
  4326. }
  4327. while (src_script.is_valid()) {
  4328. if (src_script == p_target.script_type) {
  4329. return true;
  4330. }
  4331. src_script = src_script->get_base_script();
  4332. }
  4333. return false;
  4334. case GDScriptParser::DataType::CLASS:
  4335. if (p_target.is_meta_type) {
  4336. return ClassDB::is_parent_class(src_native, GDScript::get_class_static());
  4337. }
  4338. while (src_class != nullptr) {
  4339. if (src_class == p_target.class_type || src_class->fqcn == p_target.class_type->fqcn) {
  4340. return true;
  4341. }
  4342. src_class = src_class->base_type.class_type;
  4343. }
  4344. return false;
  4345. case GDScriptParser::DataType::VARIANT:
  4346. case GDScriptParser::DataType::BUILTIN:
  4347. case GDScriptParser::DataType::ENUM:
  4348. case GDScriptParser::DataType::RESOLVING:
  4349. case GDScriptParser::DataType::UNRESOLVED:
  4350. break; // Already solved before.
  4351. }
  4352. return false;
  4353. }
  4354. void GDScriptAnalyzer::push_error(const String &p_message, const GDScriptParser::Node *p_origin) {
  4355. mark_node_unsafe(p_origin);
  4356. parser->push_error(p_message, p_origin);
  4357. }
  4358. void GDScriptAnalyzer::mark_node_unsafe(const GDScriptParser::Node *p_node) {
  4359. #ifdef DEBUG_ENABLED
  4360. if (p_node == nullptr) {
  4361. return;
  4362. }
  4363. for (int i = p_node->start_line; i <= p_node->end_line; i++) {
  4364. parser->unsafe_lines.insert(i);
  4365. }
  4366. #endif
  4367. }
  4368. void GDScriptAnalyzer::downgrade_node_type_source(GDScriptParser::Node *p_node) {
  4369. GDScriptParser::IdentifierNode *identifier = nullptr;
  4370. if (p_node->type == GDScriptParser::Node::IDENTIFIER) {
  4371. identifier = static_cast<GDScriptParser::IdentifierNode *>(p_node);
  4372. } else if (p_node->type == GDScriptParser::Node::SUBSCRIPT) {
  4373. GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(p_node);
  4374. if (subscript->is_attribute) {
  4375. identifier = subscript->attribute;
  4376. }
  4377. }
  4378. if (identifier == nullptr) {
  4379. return;
  4380. }
  4381. GDScriptParser::Node *source = nullptr;
  4382. switch (identifier->source) {
  4383. case GDScriptParser::IdentifierNode::MEMBER_VARIABLE: {
  4384. source = identifier->variable_source;
  4385. } break;
  4386. case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER: {
  4387. source = identifier->parameter_source;
  4388. } break;
  4389. case GDScriptParser::IdentifierNode::LOCAL_VARIABLE: {
  4390. source = identifier->variable_source;
  4391. } break;
  4392. case GDScriptParser::IdentifierNode::LOCAL_ITERATOR: {
  4393. source = identifier->bind_source;
  4394. } break;
  4395. default:
  4396. break;
  4397. }
  4398. if (source == nullptr) {
  4399. return;
  4400. }
  4401. GDScriptParser::DataType datatype;
  4402. datatype.kind = GDScriptParser::DataType::VARIANT;
  4403. source->set_datatype(datatype);
  4404. }
  4405. void GDScriptAnalyzer::mark_lambda_use_self() {
  4406. for (GDScriptParser::LambdaNode *lambda : lambda_stack) {
  4407. lambda->use_self = true;
  4408. }
  4409. }
  4410. bool GDScriptAnalyzer::class_exists(const StringName &p_class) const {
  4411. return ClassDB::class_exists(p_class) && ClassDB::is_class_exposed(p_class);
  4412. }
  4413. Ref<GDScriptParserRef> GDScriptAnalyzer::get_parser_for(const String &p_path) {
  4414. Ref<GDScriptParserRef> ref;
  4415. if (depended_parsers.has(p_path)) {
  4416. ref = depended_parsers[p_path];
  4417. } else {
  4418. Error err = OK;
  4419. ref = GDScriptCache::get_parser(p_path, GDScriptParserRef::EMPTY, err, parser->script_path);
  4420. if (ref.is_valid()) {
  4421. depended_parsers[p_path] = ref;
  4422. }
  4423. }
  4424. return ref;
  4425. }
  4426. Error GDScriptAnalyzer::resolve_inheritance() {
  4427. return resolve_class_inheritance(parser->head, true);
  4428. }
  4429. Error GDScriptAnalyzer::resolve_interface() {
  4430. resolve_class_interface(parser->head, true);
  4431. return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;
  4432. }
  4433. Error GDScriptAnalyzer::resolve_body() {
  4434. resolve_class_body(parser->head, true);
  4435. return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;
  4436. }
  4437. Error GDScriptAnalyzer::resolve_dependencies() {
  4438. for (KeyValue<String, Ref<GDScriptParserRef>> &K : depended_parsers) {
  4439. if (K.value.is_null()) {
  4440. return ERR_PARSE_ERROR;
  4441. }
  4442. K.value->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  4443. }
  4444. return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;
  4445. }
  4446. Error GDScriptAnalyzer::analyze() {
  4447. parser->errors.clear();
  4448. Error err = OK;
  4449. err = resolve_inheritance();
  4450. if (err) {
  4451. return err;
  4452. }
  4453. // Apply annotations.
  4454. for (GDScriptParser::AnnotationNode *&E : parser->head->annotations) {
  4455. resolve_annotation(E);
  4456. E->apply(parser, parser->head);
  4457. }
  4458. resolve_interface();
  4459. resolve_body();
  4460. if (!parser->errors.is_empty()) {
  4461. return ERR_PARSE_ERROR;
  4462. }
  4463. return resolve_dependencies();
  4464. }
  4465. GDScriptAnalyzer::GDScriptAnalyzer(GDScriptParser *p_parser) {
  4466. parser = p_parser;
  4467. }