gdscript_analyzer.cpp 180 KB

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