gdscript_analyzer.cpp 142 KB

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