gdscript_analyzer.cpp 166 KB

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