gdscript_analyzer.cpp 175 KB

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