gdscript_analyzer.cpp 110 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885
  1. /*************************************************************************/
  2. /* gdscript_analyzer.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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/class_db.h"
  32. #include "core/hash_map.h"
  33. #include "core/io/resource_loader.h"
  34. #include "core/project_settings.h"
  35. #include "core/script_language.h"
  36. #include "gdscript.h"
  37. // TODO: Move this to a central location (maybe core?).
  38. static HashMap<StringName, StringName> underscore_map;
  39. static const char *underscore_classes[] = {
  40. "ClassDB",
  41. "Directory",
  42. "Engine",
  43. "File",
  44. "Geometry",
  45. "GodotSharp",
  46. "JSON",
  47. "Marshalls",
  48. "Mutex",
  49. "OS",
  50. "ResourceLoader",
  51. "ResourceSaver",
  52. "Semaphore",
  53. "Thread",
  54. "VisualScriptEditor",
  55. nullptr,
  56. };
  57. static StringName get_real_class_name(const StringName &p_source) {
  58. if (underscore_map.empty()) {
  59. const char **class_name = underscore_classes;
  60. while (*class_name != nullptr) {
  61. underscore_map[*class_name] = String("_") + *class_name;
  62. class_name++;
  63. }
  64. }
  65. if (underscore_map.has(p_source)) {
  66. return underscore_map[p_source];
  67. }
  68. return p_source;
  69. }
  70. static GDScriptParser::DataType make_callable_type(const MethodInfo &p_info) {
  71. GDScriptParser::DataType type;
  72. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  73. type.kind = GDScriptParser::DataType::BUILTIN;
  74. type.builtin_type = Variant::CALLABLE;
  75. type.is_constant = true;
  76. type.method_info = p_info;
  77. return type;
  78. }
  79. static GDScriptParser::DataType make_signal_type(const MethodInfo &p_info) {
  80. GDScriptParser::DataType type;
  81. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  82. type.kind = GDScriptParser::DataType::BUILTIN;
  83. type.builtin_type = Variant::SIGNAL;
  84. type.is_constant = true;
  85. type.method_info = p_info;
  86. return type;
  87. }
  88. static GDScriptParser::DataType make_native_meta_type(const StringName &p_class_name) {
  89. GDScriptParser::DataType type;
  90. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  91. type.kind = GDScriptParser::DataType::NATIVE;
  92. type.builtin_type = Variant::OBJECT;
  93. type.is_constant = true;
  94. type.native_type = p_class_name;
  95. type.is_meta_type = true;
  96. return type;
  97. }
  98. static GDScriptParser::DataType make_native_enum_type(const StringName &p_native_class, const StringName &p_enum_name) {
  99. GDScriptParser::DataType type;
  100. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  101. type.kind = GDScriptParser::DataType::ENUM;
  102. type.builtin_type = Variant::OBJECT;
  103. type.is_constant = true;
  104. type.is_meta_type = true;
  105. List<StringName> enum_values;
  106. StringName real_native_name = get_real_class_name(p_native_class);
  107. ClassDB::get_enum_constants(real_native_name, p_enum_name, &enum_values);
  108. for (const List<StringName>::Element *E = enum_values.front(); E != nullptr; E = E->next()) {
  109. type.enum_values[E->get()] = ClassDB::get_integer_constant(real_native_name, E->get());
  110. }
  111. return type;
  112. }
  113. static GDScriptParser::DataType make_builtin_meta_type(Variant::Type p_type) {
  114. GDScriptParser::DataType type;
  115. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  116. type.kind = GDScriptParser::DataType::BUILTIN;
  117. type.builtin_type = p_type;
  118. type.is_constant = true;
  119. type.is_meta_type = true;
  120. return type;
  121. }
  122. Error GDScriptAnalyzer::resolve_inheritance(GDScriptParser::ClassNode *p_class, bool p_recursive) {
  123. if (p_class->base_type.is_set()) {
  124. // Already resolved
  125. return OK;
  126. }
  127. if (p_class == parser->head) {
  128. if (p_class->identifier) {
  129. p_class->fqcn = p_class->identifier->name;
  130. } else {
  131. p_class->fqcn = parser->script_path;
  132. }
  133. } else {
  134. p_class->fqcn = p_class->outer->fqcn + "." + String(p_class->identifier->name);
  135. }
  136. GDScriptParser::DataType result;
  137. // Set datatype for class.
  138. GDScriptParser::DataType class_type;
  139. class_type.is_constant = true;
  140. class_type.is_meta_type = true;
  141. class_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  142. class_type.kind = GDScriptParser::DataType::CLASS;
  143. class_type.class_type = p_class;
  144. p_class->set_datatype(class_type);
  145. if (!p_class->extends_used) {
  146. result.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  147. result.kind = GDScriptParser::DataType::NATIVE;
  148. result.native_type = "Reference";
  149. } else {
  150. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  151. GDScriptParser::DataType base;
  152. int extends_index = 0;
  153. if (!p_class->extends_path.empty()) {
  154. Ref<GDScriptParserRef> parser = get_parser_for(p_class->extends_path);
  155. if (parser.is_null()) {
  156. push_error(vformat(R"(Could not resolve super class path "%s".)", p_class->extends_path), p_class);
  157. return ERR_PARSE_ERROR;
  158. }
  159. Error err = parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  160. if (err != OK) {
  161. push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", p_class->extends_path), p_class);
  162. return err;
  163. }
  164. base = parser->get_parser()->head->get_datatype();
  165. } else {
  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. Ref<GDScriptParserRef> parser = get_parser_for(base_path);
  171. if (parser.is_null()) {
  172. push_error(vformat(R"(Could not resolve super class "%s".)", name), p_class);
  173. return ERR_PARSE_ERROR;
  174. }
  175. Error err = parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  176. if (err != OK) {
  177. push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), p_class);
  178. return err;
  179. }
  180. } else if (ProjectSettings::get_singleton()->has_autoload(name) && ProjectSettings::get_singleton()->get_autoload(name).is_singleton) {
  181. const ProjectSettings::AutoloadInfo &info = ProjectSettings::get_singleton()->get_autoload(name);
  182. if (info.path.get_extension().to_lower() != ".gd") {
  183. push_error(vformat(R"(Singleton %s is not a GDScript.)", info.name), p_class);
  184. return ERR_PARSE_ERROR;
  185. }
  186. Ref<GDScriptParserRef> parser = get_parser_for(info.path);
  187. if (parser.is_null()) {
  188. push_error(vformat(R"(Could not parse singleton from "%s".)", info.path), p_class);
  189. return ERR_PARSE_ERROR;
  190. }
  191. Error err = parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  192. if (err != OK) {
  193. push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), p_class);
  194. return err;
  195. }
  196. } else if (class_exists(name) && ClassDB::can_instance(get_real_class_name(name))) {
  197. base.kind = GDScriptParser::DataType::NATIVE;
  198. base.native_type = name;
  199. } else {
  200. // Look for other classes in script.
  201. const GDScriptParser::ClassNode *look_class = p_class;
  202. bool found = false;
  203. while (look_class != nullptr) {
  204. if (p_class->members_indices.has(name) && p_class->get_member(name).type == GDScriptParser::ClassNode::Member::CLASS) {
  205. GDScriptParser::ClassNode::Member member = p_class->get_member(name);
  206. base.kind = GDScriptParser::DataType::CLASS;
  207. base.class_type = member.m_class;
  208. found = true;
  209. break;
  210. }
  211. look_class = look_class->outer;
  212. }
  213. if (!found) {
  214. push_error(vformat(R"(Could not find base class "%s".)", name), p_class);
  215. return ERR_PARSE_ERROR;
  216. }
  217. }
  218. }
  219. for (int index = extends_index; index < p_class->extends.size(); index++) {
  220. if (base.kind != GDScriptParser::DataType::CLASS) {
  221. push_error(R"(Super type "%s" is not a GDScript. Cannot get nested types.)", p_class);
  222. return ERR_PARSE_ERROR;
  223. }
  224. // TODO: Extends could use identifier nodes. That way errors can be pointed out properly and it can be used here.
  225. GDScriptParser::IdentifierNode *id = parser->alloc_node<GDScriptParser::IdentifierNode>();
  226. id->name = p_class->extends[index];
  227. reduce_identifier_from_base(id, &base);
  228. GDScriptParser::DataType id_type = id->get_datatype();
  229. if (!id_type.is_set()) {
  230. push_error(vformat(R"(Could not find type "%s" under base "%s".)", id->name, base.to_string()), p_class);
  231. }
  232. base = id_type;
  233. }
  234. result = base;
  235. }
  236. if (!result.is_set()) {
  237. // TODO: More specific error messages.
  238. push_error(vformat(R"(Could not resolve inheritance for class "%s".)", p_class->identifier == nullptr ? "<main>" : p_class->identifier->name), p_class);
  239. return ERR_PARSE_ERROR;
  240. }
  241. p_class->base_type = result;
  242. class_type.native_type = result.native_type;
  243. p_class->set_datatype(class_type);
  244. if (p_recursive) {
  245. for (int i = 0; i < p_class->members.size(); i++) {
  246. if (p_class->members[i].type == GDScriptParser::ClassNode::Member::CLASS) {
  247. resolve_inheritance(p_class->members[i].m_class, true);
  248. }
  249. }
  250. }
  251. return OK;
  252. }
  253. GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::TypeNode *p_type) {
  254. GDScriptParser::DataType result;
  255. if (p_type == nullptr) {
  256. result.kind = GDScriptParser::DataType::VARIANT;
  257. return result;
  258. }
  259. result.type_source = result.ANNOTATED_EXPLICIT;
  260. result.builtin_type = Variant::OBJECT;
  261. if (p_type->type_chain.empty()) {
  262. // void.
  263. result.kind = GDScriptParser::DataType::BUILTIN;
  264. result.builtin_type = Variant::NIL;
  265. p_type->set_datatype(result);
  266. return result;
  267. }
  268. StringName first = p_type->type_chain[0]->name;
  269. if (first == "Variant") {
  270. result.kind = GDScriptParser::DataType::VARIANT;
  271. if (p_type->type_chain.size() > 1) {
  272. push_error(R"("Variant" type don't contain nested types.)", p_type->type_chain[1]);
  273. return GDScriptParser::DataType();
  274. }
  275. return result;
  276. }
  277. if (GDScriptParser::get_builtin_type(first) < Variant::VARIANT_MAX) {
  278. // Built-in types.
  279. if (p_type->type_chain.size() > 1) {
  280. push_error(R"(Built-in types don't contain nested types.)", p_type->type_chain[1]);
  281. return GDScriptParser::DataType();
  282. }
  283. result.kind = GDScriptParser::DataType::BUILTIN;
  284. result.builtin_type = GDScriptParser::get_builtin_type(first);
  285. } else if (class_exists(first)) {
  286. // Native engine classes.
  287. result.kind = GDScriptParser::DataType::NATIVE;
  288. result.native_type = first;
  289. } else if (ScriptServer::is_global_class(first)) {
  290. Ref<GDScriptParserRef> ref = get_parser_for(ScriptServer::get_global_class_path(first));
  291. if (ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED) != OK) {
  292. push_error(vformat(R"(Could not parse global class "%s" from "%s".)", first, ScriptServer::get_global_class_path(first)), p_type);
  293. return GDScriptParser::DataType();
  294. }
  295. result = ref->get_parser()->head->get_datatype();
  296. } else if (ProjectSettings::get_singleton()->has_autoload(first) && ProjectSettings::get_singleton()->get_autoload(first).is_singleton) {
  297. const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(first);
  298. Ref<GDScriptParserRef> ref = get_parser_for(autoload.path);
  299. if (ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED) != OK) {
  300. push_error(vformat(R"(Could not parse singleton "%s" from "%s".)", first, autoload.path), p_type);
  301. return GDScriptParser::DataType();
  302. }
  303. result = ref->get_parser()->head->get_datatype();
  304. } else if (ClassDB::has_enum(get_real_class_name(parser->current_class->base_type.native_type), first)) {
  305. // Native enum in current class.
  306. result = make_native_enum_type(parser->current_class->base_type.native_type, first);
  307. } else {
  308. // Classes in current scope.
  309. GDScriptParser::ClassNode *script_class = parser->current_class;
  310. bool found = false;
  311. while (!found && script_class != nullptr) {
  312. if (script_class->members_indices.has(first)) {
  313. GDScriptParser::ClassNode::Member member = script_class->members[script_class->members_indices[first]];
  314. switch (member.type) {
  315. case GDScriptParser::ClassNode::Member::CLASS:
  316. result.kind = GDScriptParser::DataType::CLASS;
  317. result.class_type = member.m_class;
  318. found = true;
  319. break;
  320. case GDScriptParser::ClassNode::Member::ENUM:
  321. result = member.m_enum->get_datatype();
  322. found = true;
  323. break;
  324. case GDScriptParser::ClassNode::Member::CONSTANT:
  325. if (member.constant->get_datatype().is_meta_type) {
  326. result = member.constant->get_datatype();
  327. found = true;
  328. break;
  329. }
  330. [[fallthrough]];
  331. default:
  332. push_error(vformat(R"("%s" is a %s but does not contain a type.)", first, member.get_type_name()), p_type);
  333. return GDScriptParser::DataType();
  334. }
  335. }
  336. script_class = script_class->outer;
  337. }
  338. }
  339. if (!result.is_set()) {
  340. push_error(vformat(R"("%s" was not found in the current scope.)", first), p_type);
  341. return GDScriptParser::DataType();
  342. }
  343. if (p_type->type_chain.size() > 1) {
  344. if (result.kind == GDScriptParser::DataType::CLASS) {
  345. for (int i = 1; i < p_type->type_chain.size(); i++) {
  346. GDScriptParser::DataType base = result;
  347. reduce_identifier_from_base(p_type->type_chain[i], &base);
  348. result = p_type->type_chain[i]->get_datatype();
  349. if (!result.is_set()) {
  350. 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]);
  351. return GDScriptParser::DataType();
  352. } else if (!result.is_meta_type) {
  353. 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]);
  354. return GDScriptParser::DataType();
  355. }
  356. }
  357. } else if (result.kind == GDScriptParser::DataType::NATIVE) {
  358. // Only enums allowed for native.
  359. if (ClassDB::has_enum(get_real_class_name(result.native_type), p_type->type_chain[1]->name)) {
  360. if (p_type->type_chain.size() > 2) {
  361. push_error(R"(Enums cannot contain nested types.)", p_type->type_chain[2]);
  362. } else {
  363. result = make_native_enum_type(result.native_type, p_type->type_chain[1]->name);
  364. }
  365. }
  366. } else {
  367. 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]);
  368. return GDScriptParser::DataType();
  369. }
  370. }
  371. p_type->set_datatype(result);
  372. return result;
  373. }
  374. void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_class) {
  375. if (p_class->resolved_interface) {
  376. return;
  377. }
  378. p_class->resolved_interface = true;
  379. GDScriptParser::ClassNode *previous_class = parser->current_class;
  380. parser->current_class = p_class;
  381. for (int i = 0; i < p_class->members.size(); i++) {
  382. GDScriptParser::ClassNode::Member member = p_class->members[i];
  383. switch (member.type) {
  384. case GDScriptParser::ClassNode::Member::VARIABLE: {
  385. GDScriptParser::DataType datatype;
  386. datatype.kind = GDScriptParser::DataType::VARIANT;
  387. datatype.type_source = GDScriptParser::DataType::UNDETECTED;
  388. if (member.variable->initializer != nullptr) {
  389. member.variable->set_datatype(datatype); // Allow recursive usage.
  390. reduce_expression(member.variable->initializer);
  391. datatype = member.variable->initializer->get_datatype();
  392. }
  393. if (member.variable->datatype_specifier != nullptr) {
  394. datatype = resolve_datatype(member.variable->datatype_specifier);
  395. if (member.variable->initializer != nullptr) {
  396. if (!is_type_compatible(datatype, member.variable->initializer->get_datatype(), true)) {
  397. push_error(vformat(R"(Value of type "%s" cannot be assigned to variable of type "%s".)", member.variable->initializer->get_datatype().to_string(), datatype.to_string()), member.variable->initializer);
  398. } else if (datatype.builtin_type == Variant::INT && member.variable->initializer->get_datatype().builtin_type == Variant::FLOAT) {
  399. parser->push_warning(member.variable->initializer, GDScriptWarning::NARROWING_CONVERSION);
  400. }
  401. if (member.variable->initializer->get_datatype().is_variant()) {
  402. // TODO: Warn unsafe assign.
  403. mark_node_unsafe(member.variable->initializer);
  404. }
  405. }
  406. } else if (member.variable->infer_datatype) {
  407. if (member.variable->initializer == nullptr) {
  408. push_error(vformat(R"(Cannot infer the type of "%s" variable because there's no default value.)", member.variable->identifier->name), member.variable->identifier);
  409. } else if (!datatype.is_set() || datatype.has_no_type()) {
  410. 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);
  411. } else if (datatype.is_variant()) {
  412. 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);
  413. } else if (datatype.builtin_type == Variant::NIL) {
  414. push_error(vformat(R"(Cannot infer the type of "%s" variable because the initial value is "null".)", member.variable->identifier->name), member.variable->initializer);
  415. }
  416. }
  417. datatype.is_constant = false;
  418. member.variable->set_datatype(datatype);
  419. if (!datatype.has_no_type()) {
  420. // TODO: Move this out into a routine specific to validate annotations.
  421. if (member.variable->export_info.hint == PROPERTY_HINT_TYPE_STRING) {
  422. // @export annotation.
  423. switch (datatype.kind) {
  424. case GDScriptParser::DataType::BUILTIN:
  425. member.variable->export_info.hint_string = Variant::get_type_name(datatype.builtin_type);
  426. break;
  427. case GDScriptParser::DataType::NATIVE:
  428. if (ClassDB::is_parent_class(get_real_class_name(datatype.native_type), "Resource")) {
  429. member.variable->export_info.hint_string = get_real_class_name(datatype.native_type);
  430. } else {
  431. push_error(R"(Export type can only be built-in or a resource.)", member.variable);
  432. }
  433. break;
  434. default:
  435. // TODO: Allow custom user resources.
  436. push_error(R"(Export type can only be built-in or a resource.)", member.variable);
  437. break;
  438. }
  439. }
  440. }
  441. } break;
  442. case GDScriptParser::ClassNode::Member::CONSTANT: {
  443. reduce_expression(member.constant->initializer);
  444. if (!member.constant->initializer->is_constant) {
  445. push_error(R"(Initializer for a constant must be a constant expression.)", member.constant->initializer);
  446. }
  447. GDScriptParser::DataType datatype = member.constant->get_datatype();
  448. if (member.constant->datatype_specifier != nullptr) {
  449. datatype = resolve_datatype(member.constant->datatype_specifier);
  450. if (!is_type_compatible(datatype, member.constant->initializer->get_datatype(), true)) {
  451. 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);
  452. } else if (datatype.builtin_type == Variant::INT && member.constant->initializer->get_datatype().builtin_type == Variant::FLOAT) {
  453. parser->push_warning(member.constant->initializer, GDScriptWarning::NARROWING_CONVERSION);
  454. }
  455. }
  456. datatype.is_constant = true;
  457. member.constant->set_datatype(datatype);
  458. } break;
  459. case GDScriptParser::ClassNode::Member::SIGNAL: {
  460. for (int j = 0; j < member.signal->parameters.size(); j++) {
  461. member.signal->parameters[j]->set_datatype(resolve_datatype(member.signal->parameters[j]->datatype_specifier));
  462. }
  463. // TODO: Make MethodInfo from signal.
  464. GDScriptParser::DataType signal_type;
  465. signal_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  466. signal_type.kind = GDScriptParser::DataType::BUILTIN;
  467. signal_type.builtin_type = Variant::SIGNAL;
  468. member.signal->set_datatype(signal_type);
  469. } break;
  470. case GDScriptParser::ClassNode::Member::ENUM: {
  471. GDScriptParser::DataType enum_type;
  472. enum_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  473. enum_type.kind = GDScriptParser::DataType::ENUM;
  474. enum_type.builtin_type = Variant::DICTIONARY;
  475. enum_type.enum_type = member.m_enum->identifier->name;
  476. enum_type.native_type = p_class->fqcn + "." + member.m_enum->identifier->name;
  477. enum_type.is_meta_type = true;
  478. enum_type.is_constant = true;
  479. for (int i = 0; i < member.m_enum->values.size(); i++) {
  480. enum_type.enum_values[member.m_enum->values[i].identifier->name] = member.m_enum->values[i].value;
  481. }
  482. member.m_enum->set_datatype(enum_type);
  483. } break;
  484. case GDScriptParser::ClassNode::Member::FUNCTION:
  485. resolve_function_signature(member.function);
  486. break;
  487. case GDScriptParser::ClassNode::Member::ENUM_VALUE:
  488. break; // Nothing to do, type and value set in parser.
  489. case GDScriptParser::ClassNode::Member::CLASS:
  490. break; // Done later.
  491. case GDScriptParser::ClassNode::Member::UNDEFINED:
  492. ERR_PRINT("Trying to resolve undefined member.");
  493. break;
  494. }
  495. }
  496. // Recurse nested classes.
  497. for (int i = 0; i < p_class->members.size(); i++) {
  498. GDScriptParser::ClassNode::Member member = p_class->members[i];
  499. if (member.type != GDScriptParser::ClassNode::Member::CLASS) {
  500. continue;
  501. }
  502. resolve_class_interface(member.m_class);
  503. }
  504. parser->current_class = previous_class;
  505. }
  506. void GDScriptAnalyzer::resolve_class_body(GDScriptParser::ClassNode *p_class) {
  507. if (p_class->resolved_body) {
  508. return;
  509. }
  510. p_class->resolved_body = true;
  511. GDScriptParser::ClassNode *previous_class = parser->current_class;
  512. parser->current_class = p_class;
  513. // Do functions now.
  514. for (int i = 0; i < p_class->members.size(); i++) {
  515. GDScriptParser::ClassNode::Member member = p_class->members[i];
  516. if (member.type != GDScriptParser::ClassNode::Member::FUNCTION) {
  517. continue;
  518. }
  519. resolve_function_body(member.function);
  520. }
  521. parser->current_class = previous_class;
  522. // Recurse nested classes.
  523. for (int i = 0; i < p_class->members.size(); i++) {
  524. GDScriptParser::ClassNode::Member member = p_class->members[i];
  525. if (member.type != GDScriptParser::ClassNode::Member::CLASS) {
  526. continue;
  527. }
  528. resolve_class_body(member.m_class);
  529. }
  530. // Check unused variables.
  531. for (int i = 0; i < p_class->members.size(); i++) {
  532. GDScriptParser::ClassNode::Member member = p_class->members[i];
  533. if (member.type != GDScriptParser::ClassNode::Member::VARIABLE) {
  534. continue;
  535. }
  536. if (member.variable->usages == 0 && String(member.variable->identifier->name).begins_with("_")) {
  537. parser->push_warning(member.variable->identifier, GDScriptWarning::UNUSED_PRIVATE_CLASS_VARIABLE, member.variable->identifier->name);
  538. }
  539. }
  540. }
  541. void GDScriptAnalyzer::resolve_node(GDScriptParser::Node *p_node) {
  542. ERR_FAIL_COND_MSG(p_node == nullptr, "Trying to resolve type of a null node.");
  543. switch (p_node->type) {
  544. case GDScriptParser::Node::NONE:
  545. break; // Unreachable.
  546. case GDScriptParser::Node::CLASS:
  547. resolve_class_interface(static_cast<GDScriptParser::ClassNode *>(p_node));
  548. resolve_class_body(static_cast<GDScriptParser::ClassNode *>(p_node));
  549. break;
  550. case GDScriptParser::Node::CONSTANT:
  551. resolve_constant(static_cast<GDScriptParser::ConstantNode *>(p_node));
  552. break;
  553. case GDScriptParser::Node::FOR:
  554. resolve_for(static_cast<GDScriptParser::ForNode *>(p_node));
  555. break;
  556. case GDScriptParser::Node::FUNCTION:
  557. resolve_function_signature(static_cast<GDScriptParser::FunctionNode *>(p_node));
  558. resolve_function_body(static_cast<GDScriptParser::FunctionNode *>(p_node));
  559. break;
  560. case GDScriptParser::Node::IF:
  561. resolve_if(static_cast<GDScriptParser::IfNode *>(p_node));
  562. break;
  563. case GDScriptParser::Node::SUITE:
  564. resolve_suite(static_cast<GDScriptParser::SuiteNode *>(p_node));
  565. break;
  566. case GDScriptParser::Node::VARIABLE:
  567. resolve_variable(static_cast<GDScriptParser::VariableNode *>(p_node));
  568. break;
  569. case GDScriptParser::Node::WHILE:
  570. resolve_while(static_cast<GDScriptParser::WhileNode *>(p_node));
  571. break;
  572. case GDScriptParser::Node::ANNOTATION:
  573. resolve_annotation(static_cast<GDScriptParser::AnnotationNode *>(p_node));
  574. break;
  575. case GDScriptParser::Node::ASSERT:
  576. resolve_assert(static_cast<GDScriptParser::AssertNode *>(p_node));
  577. break;
  578. case GDScriptParser::Node::MATCH:
  579. resolve_match(static_cast<GDScriptParser::MatchNode *>(p_node));
  580. break;
  581. case GDScriptParser::Node::MATCH_BRANCH:
  582. resolve_match_branch(static_cast<GDScriptParser::MatchBranchNode *>(p_node), nullptr);
  583. break;
  584. case GDScriptParser::Node::PARAMETER:
  585. resolve_pararameter(static_cast<GDScriptParser::ParameterNode *>(p_node));
  586. break;
  587. case GDScriptParser::Node::PATTERN:
  588. resolve_match_pattern(static_cast<GDScriptParser::PatternNode *>(p_node), nullptr);
  589. break;
  590. case GDScriptParser::Node::RETURN:
  591. resolve_return(static_cast<GDScriptParser::ReturnNode *>(p_node));
  592. break;
  593. case GDScriptParser::Node::TYPE:
  594. resolve_datatype(static_cast<GDScriptParser::TypeNode *>(p_node));
  595. break;
  596. // Resolving expression is the same as reducing them.
  597. case GDScriptParser::Node::ARRAY:
  598. case GDScriptParser::Node::ASSIGNMENT:
  599. case GDScriptParser::Node::AWAIT:
  600. case GDScriptParser::Node::BINARY_OPERATOR:
  601. case GDScriptParser::Node::CALL:
  602. case GDScriptParser::Node::CAST:
  603. case GDScriptParser::Node::DICTIONARY:
  604. case GDScriptParser::Node::GET_NODE:
  605. case GDScriptParser::Node::IDENTIFIER:
  606. case GDScriptParser::Node::LITERAL:
  607. case GDScriptParser::Node::PRELOAD:
  608. case GDScriptParser::Node::SELF:
  609. case GDScriptParser::Node::SUBSCRIPT:
  610. case GDScriptParser::Node::TERNARY_OPERATOR:
  611. case GDScriptParser::Node::UNARY_OPERATOR:
  612. reduce_expression(static_cast<GDScriptParser::ExpressionNode *>(p_node));
  613. break;
  614. case GDScriptParser::Node::BREAK:
  615. case GDScriptParser::Node::BREAKPOINT:
  616. case GDScriptParser::Node::CONTINUE:
  617. case GDScriptParser::Node::ENUM:
  618. case GDScriptParser::Node::PASS:
  619. case GDScriptParser::Node::SIGNAL:
  620. // Nothing to do.
  621. break;
  622. }
  623. }
  624. void GDScriptAnalyzer::resolve_annotation(GDScriptParser::AnnotationNode *p_annotation) {
  625. // TODO: Add second validation function for annotations, so they can use checked types.
  626. }
  627. void GDScriptAnalyzer::resolve_function_signature(GDScriptParser::FunctionNode *p_function) {
  628. if (p_function->resolved_signature) {
  629. return;
  630. }
  631. p_function->resolved_signature = true;
  632. GDScriptParser::FunctionNode *previous_function = parser->current_function;
  633. parser->current_function = p_function;
  634. for (int i = 0; i < p_function->parameters.size(); i++) {
  635. resolve_pararameter(p_function->parameters[i]);
  636. if (p_function->parameters[i]->usages == 0 && !String(p_function->parameters[i]->identifier->name).begins_with("_")) {
  637. parser->push_warning(p_function->parameters[i]->identifier, GDScriptWarning::UNUSED_PARAMETER, p_function->identifier->name, p_function->parameters[i]->identifier->name);
  638. }
  639. is_shadowing(p_function->parameters[i]->identifier, "function parameter");
  640. }
  641. p_function->set_datatype(resolve_datatype(p_function->return_type));
  642. parser->current_function = previous_function;
  643. }
  644. void GDScriptAnalyzer::resolve_function_body(GDScriptParser::FunctionNode *p_function) {
  645. if (p_function->resolved_body) {
  646. return;
  647. }
  648. p_function->resolved_body = true;
  649. GDScriptParser::FunctionNode *previous_function = parser->current_function;
  650. parser->current_function = p_function;
  651. resolve_suite(p_function->body);
  652. GDScriptParser::DataType return_type = p_function->body->get_datatype();
  653. if (p_function->get_datatype().has_no_type() && return_type.is_set()) {
  654. // Use the suite inferred type if return isn't explicitly set.
  655. return_type.type_source = GDScriptParser::DataType::INFERRED;
  656. p_function->set_datatype(p_function->body->get_datatype());
  657. } 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)) {
  658. if (!p_function->body->has_return) {
  659. push_error(R"(Not all code paths return a value.)", p_function);
  660. }
  661. }
  662. parser->current_function = previous_function;
  663. }
  664. void GDScriptAnalyzer::decide_suite_type(GDScriptParser::Node *p_suite, GDScriptParser::Node *p_statement) {
  665. switch (p_statement->type) {
  666. case GDScriptParser::Node::IF:
  667. case GDScriptParser::Node::FOR:
  668. case GDScriptParser::Node::MATCH:
  669. case GDScriptParser::Node::PATTERN:
  670. case GDScriptParser::Node::RETURN:
  671. case GDScriptParser::Node::WHILE:
  672. // Use return or nested suite type as this suite type.
  673. if (p_suite->get_datatype().is_set() && (p_suite->get_datatype() != p_statement->get_datatype())) {
  674. // Mixed types.
  675. // TODO: This could use the common supertype instead.
  676. p_suite->datatype.kind = GDScriptParser::DataType::VARIANT;
  677. p_suite->datatype.type_source = GDScriptParser::DataType::UNDETECTED;
  678. } else {
  679. p_suite->set_datatype(p_statement->get_datatype());
  680. }
  681. break;
  682. default:
  683. break;
  684. }
  685. }
  686. void GDScriptAnalyzer::resolve_suite(GDScriptParser::SuiteNode *p_suite) {
  687. for (int i = 0; i < p_suite->statements.size(); i++) {
  688. GDScriptParser::Node *stmt = p_suite->statements[i];
  689. resolve_node(stmt);
  690. decide_suite_type(p_suite, stmt);
  691. }
  692. }
  693. void GDScriptAnalyzer::resolve_if(GDScriptParser::IfNode *p_if) {
  694. reduce_expression(p_if->condition);
  695. resolve_suite(p_if->true_block);
  696. p_if->set_datatype(p_if->true_block->get_datatype());
  697. if (p_if->false_block != nullptr) {
  698. resolve_suite(p_if->false_block);
  699. decide_suite_type(p_if, p_if->false_block);
  700. }
  701. }
  702. void GDScriptAnalyzer::resolve_for(GDScriptParser::ForNode *p_for) {
  703. bool list_resolved = false;
  704. // Optimize constant range() call to not allocate an array.
  705. // Use int, Vector2, Vector3 instead, which also can be used as range iterators.
  706. if (p_for->list->type == GDScriptParser::Node::CALL) {
  707. GDScriptParser::CallNode *call = static_cast<GDScriptParser::CallNode *>(p_for->list);
  708. if (call->callee->type == GDScriptParser::Node::IDENTIFIER) {
  709. GDScriptParser::IdentifierNode *callee = static_cast<GDScriptParser::IdentifierNode *>(call->callee);
  710. if (callee->name == "range") {
  711. list_resolved = true;
  712. if (call->arguments.size() < 1) {
  713. push_error(R"*(Invalid call for "range()" function. Expected at least 1 argument, none given.)*", call->callee);
  714. } else if (call->arguments.size() > 3) {
  715. push_error(vformat(R"*(Invalid call for "range()" function. Expected at most 3 arguments, %d given.)*", call->arguments.size()), call->callee);
  716. } else {
  717. // Now we can optimize it.
  718. bool all_is_constant = true;
  719. Vector<Variant> args;
  720. args.resize(call->arguments.size());
  721. for (int i = 0; i < call->arguments.size(); i++) {
  722. reduce_expression(call->arguments[i]);
  723. if (!call->arguments[i]->is_constant) {
  724. all_is_constant = false;
  725. } else {
  726. args.write[i] = call->arguments[i]->reduced_value;
  727. }
  728. GDScriptParser::DataType arg_type = call->arguments[i]->get_datatype();
  729. if (arg_type.kind != GDScriptParser::DataType::BUILTIN) {
  730. all_is_constant = false;
  731. 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]);
  732. } else if (arg_type.builtin_type != Variant::INT && arg_type.builtin_type != Variant::FLOAT) {
  733. all_is_constant = false;
  734. 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]);
  735. }
  736. }
  737. Variant reduced;
  738. if (all_is_constant) {
  739. switch (args.size()) {
  740. case 1:
  741. reduced = args[0];
  742. break;
  743. case 2:
  744. reduced = Vector2i(args[0], args[1]);
  745. break;
  746. case 3:
  747. reduced = Vector3i(args[0], args[1], args[2]);
  748. break;
  749. }
  750. p_for->list->is_constant = true;
  751. p_for->list->reduced_value = reduced;
  752. }
  753. }
  754. GDScriptParser::DataType list_type;
  755. list_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  756. list_type.kind = GDScriptParser::DataType::BUILTIN;
  757. list_type.builtin_type = Variant::ARRAY;
  758. p_for->list->set_datatype(list_type);
  759. }
  760. }
  761. }
  762. if (!list_resolved) {
  763. resolve_node(p_for->list);
  764. }
  765. // TODO: If list is a typed array, the variable should be an element.
  766. // Also applicable for constant range() (so variable is int or float).
  767. resolve_suite(p_for->loop);
  768. p_for->set_datatype(p_for->loop->get_datatype());
  769. is_shadowing(p_for->variable, R"("for" iterator variable)");
  770. }
  771. void GDScriptAnalyzer::resolve_while(GDScriptParser::WhileNode *p_while) {
  772. resolve_node(p_while->condition);
  773. resolve_suite(p_while->loop);
  774. p_while->set_datatype(p_while->loop->get_datatype());
  775. }
  776. void GDScriptAnalyzer::resolve_variable(GDScriptParser::VariableNode *p_variable) {
  777. GDScriptParser::DataType type;
  778. type.kind = GDScriptParser::DataType::VARIANT; // By default.
  779. if (p_variable->initializer != nullptr) {
  780. reduce_expression(p_variable->initializer);
  781. type = p_variable->initializer->get_datatype();
  782. if (p_variable->infer_datatype) {
  783. type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  784. if (type.has_no_type()) {
  785. 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);
  786. } else if (type.is_variant()) {
  787. 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);
  788. } else if (type.builtin_type == Variant::NIL) {
  789. 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);
  790. }
  791. } else {
  792. type.type_source = GDScriptParser::DataType::INFERRED;
  793. }
  794. if (p_variable->initializer->type == GDScriptParser::Node::CALL && type.kind == GDScriptParser::DataType::BUILTIN && type.builtin_type == Variant::NIL) {
  795. parser->push_warning(p_variable->initializer, GDScriptWarning::VOID_ASSIGNMENT, static_cast<GDScriptParser::CallNode *>(p_variable->initializer)->function_name);
  796. }
  797. }
  798. if (p_variable->datatype_specifier != nullptr) {
  799. type = resolve_datatype(p_variable->datatype_specifier);
  800. if (p_variable->initializer != nullptr) {
  801. if (!is_type_compatible(type, p_variable->initializer->get_datatype(), true)) {
  802. push_error(vformat(R"(Value of type "%s" cannot be assigned to variable of type "%s".)", p_variable->initializer->get_datatype().to_string(), type.to_string()), p_variable->initializer);
  803. } else if (type.builtin_type == Variant::INT && p_variable->initializer->get_datatype().builtin_type == Variant::FLOAT) {
  804. parser->push_warning(p_variable->initializer, GDScriptWarning::NARROWING_CONVERSION);
  805. }
  806. if (p_variable->initializer->get_datatype().is_variant()) {
  807. // TODO: Warn unsafe assign.
  808. mark_node_unsafe(p_variable->initializer);
  809. }
  810. }
  811. } else if (p_variable->infer_datatype) {
  812. if (type.has_no_type()) {
  813. 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);
  814. }
  815. type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  816. }
  817. type.is_constant = false;
  818. p_variable->set_datatype(type);
  819. if (p_variable->usages == 0 && !String(p_variable->identifier->name).begins_with("_")) {
  820. parser->push_warning(p_variable, GDScriptWarning::UNUSED_VARIABLE, p_variable->identifier->name);
  821. } else if (p_variable->assignments == 0) {
  822. parser->push_warning(p_variable, GDScriptWarning::UNASSIGNED_VARIABLE, p_variable->identifier->name);
  823. }
  824. is_shadowing(p_variable->identifier, "variable");
  825. }
  826. void GDScriptAnalyzer::resolve_constant(GDScriptParser::ConstantNode *p_constant) {
  827. GDScriptParser::DataType type;
  828. reduce_expression(p_constant->initializer);
  829. if (!p_constant->initializer->is_constant) {
  830. push_error(vformat(R"(Assigned value for constant "%s" isn't a constant expression.)", p_constant->identifier->name), p_constant->initializer);
  831. }
  832. type = p_constant->initializer->get_datatype();
  833. if (p_constant->initializer->type == GDScriptParser::Node::CALL && type.kind == GDScriptParser::DataType::BUILTIN && type.builtin_type == Variant::NIL) {
  834. parser->push_warning(p_constant->initializer, GDScriptWarning::VOID_ASSIGNMENT, static_cast<GDScriptParser::CallNode *>(p_constant->initializer)->function_name);
  835. }
  836. if (p_constant->datatype_specifier != nullptr) {
  837. GDScriptParser::DataType explicit_type = resolve_datatype(p_constant->datatype_specifier);
  838. if (!is_type_compatible(explicit_type, type)) {
  839. 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);
  840. } else if (explicit_type.builtin_type == Variant::INT && type.builtin_type == Variant::FLOAT) {
  841. parser->push_warning(p_constant->initializer, GDScriptWarning::NARROWING_CONVERSION);
  842. }
  843. type = explicit_type;
  844. } else if (p_constant->infer_datatype) {
  845. if (type.has_no_type()) {
  846. 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);
  847. }
  848. type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  849. }
  850. type.is_constant = true;
  851. p_constant->set_datatype(type);
  852. if (p_constant->usages == 0) {
  853. parser->push_warning(p_constant, GDScriptWarning::UNUSED_LOCAL_CONSTANT, p_constant->identifier->name);
  854. }
  855. is_shadowing(p_constant->identifier, "constant");
  856. }
  857. void GDScriptAnalyzer::resolve_assert(GDScriptParser::AssertNode *p_assert) {
  858. reduce_expression(p_assert->condition);
  859. if (p_assert->message != nullptr) {
  860. reduce_literal(p_assert->message);
  861. }
  862. p_assert->set_datatype(p_assert->condition->get_datatype());
  863. if (p_assert->condition->is_constant) {
  864. if (p_assert->condition->reduced_value.booleanize()) {
  865. parser->push_warning(p_assert->condition, GDScriptWarning::ASSERT_ALWAYS_TRUE);
  866. } else {
  867. parser->push_warning(p_assert->condition, GDScriptWarning::ASSERT_ALWAYS_FALSE);
  868. }
  869. }
  870. }
  871. void GDScriptAnalyzer::resolve_match(GDScriptParser::MatchNode *p_match) {
  872. reduce_expression(p_match->test);
  873. for (int i = 0; i < p_match->branches.size(); i++) {
  874. resolve_match_branch(p_match->branches[i], p_match->test);
  875. decide_suite_type(p_match, p_match->branches[i]);
  876. }
  877. }
  878. void GDScriptAnalyzer::resolve_match_branch(GDScriptParser::MatchBranchNode *p_match_branch, GDScriptParser::ExpressionNode *p_match_test) {
  879. for (int i = 0; i < p_match_branch->patterns.size(); i++) {
  880. resolve_match_pattern(p_match_branch->patterns[i], p_match_test);
  881. }
  882. resolve_suite(p_match_branch->block);
  883. decide_suite_type(p_match_branch, p_match_branch->block);
  884. }
  885. void GDScriptAnalyzer::resolve_match_pattern(GDScriptParser::PatternNode *p_match_pattern, GDScriptParser::ExpressionNode *p_match_test) {
  886. GDScriptParser::DataType result;
  887. switch (p_match_pattern->pattern_type) {
  888. case GDScriptParser::PatternNode::PT_LITERAL:
  889. reduce_literal(p_match_pattern->literal);
  890. result = p_match_pattern->literal->get_datatype();
  891. break;
  892. case GDScriptParser::PatternNode::PT_EXPRESSION:
  893. reduce_expression(p_match_pattern->expression);
  894. if (!p_match_pattern->expression->is_constant) {
  895. push_error(R"(Expression in match pattern must be a constant.)", p_match_pattern->expression);
  896. }
  897. result = p_match_pattern->expression->get_datatype();
  898. break;
  899. case GDScriptParser::PatternNode::PT_BIND:
  900. if (p_match_test != nullptr) {
  901. result = p_match_test->get_datatype();
  902. } else {
  903. result.kind = GDScriptParser::DataType::VARIANT;
  904. }
  905. p_match_pattern->bind->set_datatype(result);
  906. is_shadowing(p_match_pattern->bind, "pattern bind");
  907. if (p_match_pattern->bind->usages == 0) {
  908. parser->push_warning(p_match_pattern->bind, GDScriptWarning::UNASSIGNED_VARIABLE, p_match_pattern->bind->name);
  909. }
  910. break;
  911. case GDScriptParser::PatternNode::PT_ARRAY:
  912. for (int i = 0; i < p_match_pattern->array.size(); i++) {
  913. resolve_match_pattern(p_match_pattern->array[i], nullptr);
  914. decide_suite_type(p_match_pattern, p_match_pattern->array[i]);
  915. }
  916. result = p_match_pattern->get_datatype();
  917. break;
  918. case GDScriptParser::PatternNode::PT_DICTIONARY:
  919. for (int i = 0; i < p_match_pattern->dictionary.size(); i++) {
  920. reduce_expression(p_match_pattern->dictionary[i].key);
  921. if (!p_match_pattern->dictionary[i].key->is_constant) {
  922. push_error(R"(Expression in dictionary pattern key must be a constant.)", p_match_pattern->expression);
  923. }
  924. resolve_match_pattern(p_match_pattern->dictionary[i].value_pattern, nullptr);
  925. decide_suite_type(p_match_pattern, p_match_pattern->dictionary[i].value_pattern);
  926. }
  927. result = p_match_pattern->get_datatype();
  928. break;
  929. case GDScriptParser::PatternNode::PT_WILDCARD:
  930. case GDScriptParser::PatternNode::PT_REST:
  931. result.kind = GDScriptParser::DataType::VARIANT;
  932. break;
  933. }
  934. p_match_pattern->set_datatype(result);
  935. }
  936. void GDScriptAnalyzer::resolve_pararameter(GDScriptParser::ParameterNode *p_parameter) {
  937. GDScriptParser::DataType result;
  938. result.kind = GDScriptParser::DataType::VARIANT;
  939. if (p_parameter->default_value != nullptr) {
  940. reduce_expression(p_parameter->default_value);
  941. result = p_parameter->default_value->get_datatype();
  942. result.type_source = GDScriptParser::DataType::INFERRED;
  943. }
  944. if (p_parameter->datatype_specifier != nullptr) {
  945. resolve_datatype(p_parameter->datatype_specifier);
  946. if (p_parameter->default_value != nullptr) {
  947. if (!is_type_compatible(p_parameter->datatype_specifier->get_datatype(), p_parameter->default_value->get_datatype())) {
  948. push_error(vformat(R"(Type of default value for parameter "%s" (%s) is not compatible with paremeter 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);
  949. }
  950. }
  951. result = p_parameter->datatype_specifier->get_datatype();
  952. }
  953. p_parameter->set_datatype(result);
  954. }
  955. void GDScriptAnalyzer::resolve_return(GDScriptParser::ReturnNode *p_return) {
  956. GDScriptParser::DataType result;
  957. if (p_return->return_value != nullptr) {
  958. reduce_expression(p_return->return_value);
  959. result = p_return->return_value->get_datatype();
  960. } else {
  961. // Return type is null by default.
  962. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  963. result.kind = GDScriptParser::DataType::BUILTIN;
  964. result.builtin_type = Variant::NIL;
  965. result.is_constant = true;
  966. }
  967. GDScriptParser::DataType function_type = parser->current_function->get_datatype();
  968. if (function_type.is_hard_type()) {
  969. if (!is_type_compatible(function_type, result)) {
  970. // Try other way. Okay but not safe.
  971. if (!is_type_compatible(result, function_type)) {
  972. 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);
  973. } else {
  974. // TODO: Add warning.
  975. mark_node_unsafe(p_return);
  976. }
  977. } else if (function_type.builtin_type == Variant::INT && result.builtin_type == Variant::FLOAT) {
  978. parser->push_warning(p_return, GDScriptWarning::NARROWING_CONVERSION);
  979. } else if (result.is_variant()) {
  980. mark_node_unsafe(p_return);
  981. }
  982. }
  983. p_return->set_datatype(result);
  984. }
  985. void GDScriptAnalyzer::reduce_expression(GDScriptParser::ExpressionNode *p_expression) {
  986. // This one makes some magic happen.
  987. if (p_expression->reduced) {
  988. // Don't do this more than once.
  989. return;
  990. }
  991. p_expression->reduced = true;
  992. switch (p_expression->type) {
  993. case GDScriptParser::Node::ARRAY:
  994. reduce_array(static_cast<GDScriptParser::ArrayNode *>(p_expression));
  995. break;
  996. case GDScriptParser::Node::ASSIGNMENT:
  997. reduce_assignment(static_cast<GDScriptParser::AssignmentNode *>(p_expression));
  998. break;
  999. case GDScriptParser::Node::AWAIT:
  1000. reduce_await(static_cast<GDScriptParser::AwaitNode *>(p_expression));
  1001. break;
  1002. case GDScriptParser::Node::BINARY_OPERATOR:
  1003. reduce_binary_op(static_cast<GDScriptParser::BinaryOpNode *>(p_expression));
  1004. break;
  1005. case GDScriptParser::Node::CALL:
  1006. reduce_call(static_cast<GDScriptParser::CallNode *>(p_expression));
  1007. break;
  1008. case GDScriptParser::Node::CAST:
  1009. reduce_cast(static_cast<GDScriptParser::CastNode *>(p_expression));
  1010. break;
  1011. case GDScriptParser::Node::DICTIONARY:
  1012. reduce_dictionary(static_cast<GDScriptParser::DictionaryNode *>(p_expression));
  1013. break;
  1014. case GDScriptParser::Node::GET_NODE:
  1015. reduce_get_node(static_cast<GDScriptParser::GetNodeNode *>(p_expression));
  1016. break;
  1017. case GDScriptParser::Node::IDENTIFIER:
  1018. reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_expression));
  1019. break;
  1020. case GDScriptParser::Node::LITERAL:
  1021. reduce_literal(static_cast<GDScriptParser::LiteralNode *>(p_expression));
  1022. break;
  1023. case GDScriptParser::Node::PRELOAD:
  1024. reduce_preload(static_cast<GDScriptParser::PreloadNode *>(p_expression));
  1025. break;
  1026. case GDScriptParser::Node::SELF:
  1027. reduce_self(static_cast<GDScriptParser::SelfNode *>(p_expression));
  1028. break;
  1029. case GDScriptParser::Node::SUBSCRIPT:
  1030. reduce_subscript(static_cast<GDScriptParser::SubscriptNode *>(p_expression));
  1031. break;
  1032. case GDScriptParser::Node::TERNARY_OPERATOR:
  1033. reduce_ternary_op(static_cast<GDScriptParser::TernaryOpNode *>(p_expression));
  1034. break;
  1035. case GDScriptParser::Node::UNARY_OPERATOR:
  1036. reduce_unary_op(static_cast<GDScriptParser::UnaryOpNode *>(p_expression));
  1037. break;
  1038. // Non-expressions. Here only to make sure new nodes aren't forgotten.
  1039. case GDScriptParser::Node::NONE:
  1040. case GDScriptParser::Node::ANNOTATION:
  1041. case GDScriptParser::Node::ASSERT:
  1042. case GDScriptParser::Node::BREAK:
  1043. case GDScriptParser::Node::BREAKPOINT:
  1044. case GDScriptParser::Node::CLASS:
  1045. case GDScriptParser::Node::CONSTANT:
  1046. case GDScriptParser::Node::CONTINUE:
  1047. case GDScriptParser::Node::ENUM:
  1048. case GDScriptParser::Node::FOR:
  1049. case GDScriptParser::Node::FUNCTION:
  1050. case GDScriptParser::Node::IF:
  1051. case GDScriptParser::Node::MATCH:
  1052. case GDScriptParser::Node::MATCH_BRANCH:
  1053. case GDScriptParser::Node::PARAMETER:
  1054. case GDScriptParser::Node::PASS:
  1055. case GDScriptParser::Node::PATTERN:
  1056. case GDScriptParser::Node::RETURN:
  1057. case GDScriptParser::Node::SIGNAL:
  1058. case GDScriptParser::Node::SUITE:
  1059. case GDScriptParser::Node::TYPE:
  1060. case GDScriptParser::Node::VARIABLE:
  1061. case GDScriptParser::Node::WHILE:
  1062. ERR_FAIL_MSG("Reaching unreachable case");
  1063. }
  1064. }
  1065. void GDScriptAnalyzer::reduce_array(GDScriptParser::ArrayNode *p_array) {
  1066. bool all_is_constant = true;
  1067. for (int i = 0; i < p_array->elements.size(); i++) {
  1068. GDScriptParser::ExpressionNode *element = p_array->elements[i];
  1069. reduce_expression(element);
  1070. all_is_constant = all_is_constant && element->is_constant;
  1071. }
  1072. if (all_is_constant) {
  1073. Array array;
  1074. array.resize(p_array->elements.size());
  1075. for (int i = 0; i < p_array->elements.size(); i++) {
  1076. array[i] = p_array->elements[i]->reduced_value;
  1077. }
  1078. p_array->is_constant = true;
  1079. p_array->reduced_value = array;
  1080. }
  1081. // It's array in any case.
  1082. GDScriptParser::DataType arr_type;
  1083. arr_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1084. arr_type.kind = GDScriptParser::DataType::BUILTIN;
  1085. arr_type.builtin_type = Variant::ARRAY;
  1086. arr_type.is_constant = true;
  1087. p_array->set_datatype(arr_type);
  1088. }
  1089. void GDScriptAnalyzer::reduce_assignment(GDScriptParser::AssignmentNode *p_assignment) {
  1090. reduce_expression(p_assignment->assignee);
  1091. reduce_expression(p_assignment->assigned_value);
  1092. if (p_assignment->assignee->get_datatype().is_constant) {
  1093. push_error("Cannot assign a new value to a constant.", p_assignment->assignee);
  1094. }
  1095. if (!is_type_compatible(p_assignment->assignee->get_datatype(), p_assignment->assigned_value->get_datatype())) {
  1096. if (p_assignment->assignee->get_datatype().is_hard_type()) {
  1097. push_error(vformat(R"(Cannot assign a value of type "%s" to a target of type "%s".)", p_assignment->assigned_value->get_datatype().to_string(), p_assignment->assignee->get_datatype().to_string()), p_assignment->assigned_value);
  1098. } else {
  1099. // TODO: Warning in this case.
  1100. }
  1101. }
  1102. if (p_assignment->assignee->get_datatype().has_no_type() || p_assignment->assigned_value->get_datatype().is_variant()) {
  1103. mark_node_unsafe(p_assignment);
  1104. }
  1105. if (p_assignment->assignee->type == GDScriptParser::Node::IDENTIFIER) {
  1106. // Change source type so it's not wrongly detected later.
  1107. GDScriptParser::IdentifierNode *identifier = static_cast<GDScriptParser::IdentifierNode *>(p_assignment->assignee);
  1108. switch (identifier->source) {
  1109. case GDScriptParser::IdentifierNode::MEMBER_VARIABLE: {
  1110. GDScriptParser::DataType id_type = identifier->variable_source->get_datatype();
  1111. if (!id_type.is_hard_type()) {
  1112. id_type.kind = GDScriptParser::DataType::VARIANT;
  1113. id_type.type_source = GDScriptParser::DataType::UNDETECTED;
  1114. identifier->variable_source->set_datatype(id_type);
  1115. }
  1116. } break;
  1117. case GDScriptParser::IdentifierNode::LOCAL_VARIABLE: {
  1118. GDScriptParser::DataType id_type = identifier->variable_source->get_datatype();
  1119. if (!id_type.is_hard_type()) {
  1120. id_type = p_assignment->assigned_value->get_datatype();
  1121. id_type.type_source = GDScriptParser::DataType::INFERRED;
  1122. id_type.is_constant = false;
  1123. identifier->variable_source->set_datatype(id_type);
  1124. }
  1125. } break;
  1126. case GDScriptParser::IdentifierNode::LOCAL_ITERATOR: {
  1127. GDScriptParser::DataType id_type = identifier->bind_source->get_datatype();
  1128. if (!id_type.is_hard_type()) {
  1129. id_type = p_assignment->assigned_value->get_datatype();
  1130. id_type.type_source = GDScriptParser::DataType::INFERRED;
  1131. id_type.is_constant = false;
  1132. identifier->variable_source->set_datatype(id_type);
  1133. }
  1134. } break;
  1135. default:
  1136. // Nothing to do.
  1137. break;
  1138. }
  1139. }
  1140. GDScriptParser::DataType assignee_type = p_assignment->assignee->get_datatype();
  1141. GDScriptParser::DataType assigned_type = p_assignment->assigned_value->get_datatype();
  1142. if (p_assignment->assigned_value->type == GDScriptParser::Node::CALL && assigned_type.kind == GDScriptParser::DataType::BUILTIN && assigned_type.builtin_type == Variant::NIL) {
  1143. parser->push_warning(p_assignment->assigned_value, GDScriptWarning::VOID_ASSIGNMENT, static_cast<GDScriptParser::CallNode *>(p_assignment->assigned_value)->function_name);
  1144. } else if (assignee_type.is_hard_type() && assignee_type.builtin_type == Variant::INT && assigned_type.builtin_type == Variant::FLOAT) {
  1145. parser->push_warning(p_assignment->assigned_value, GDScriptWarning::NARROWING_CONVERSION);
  1146. }
  1147. }
  1148. void GDScriptAnalyzer::reduce_await(GDScriptParser::AwaitNode *p_await) {
  1149. if (p_await->to_await->type == GDScriptParser::Node::CALL) {
  1150. reduce_call(static_cast<GDScriptParser::CallNode *>(p_await->to_await), true);
  1151. } else {
  1152. reduce_expression(p_await->to_await);
  1153. }
  1154. p_await->is_constant = p_await->to_await->is_constant;
  1155. p_await->reduced_value = p_await->to_await->reduced_value;
  1156. GDScriptParser::DataType awaiting_type = p_await->to_await->get_datatype();
  1157. p_await->set_datatype(awaiting_type);
  1158. if (!awaiting_type.is_coroutine && awaiting_type.builtin_type != Variant::SIGNAL) {
  1159. parser->push_warning(p_await, GDScriptWarning::REDUNDANT_AWAIT);
  1160. }
  1161. }
  1162. void GDScriptAnalyzer::reduce_binary_op(GDScriptParser::BinaryOpNode *p_binary_op) {
  1163. reduce_expression(p_binary_op->left_operand);
  1164. if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST && p_binary_op->right_operand->type == GDScriptParser::Node::IDENTIFIER) {
  1165. reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_binary_op->right_operand), true);
  1166. } else {
  1167. reduce_expression(p_binary_op->right_operand);
  1168. }
  1169. // TODO: Right operand must be a valid type with the `is` operator. Need to check here.
  1170. GDScriptParser::DataType left_type = p_binary_op->left_operand->get_datatype();
  1171. GDScriptParser::DataType right_type = p_binary_op->right_operand->get_datatype();
  1172. if (p_binary_op->variant_op == Variant::OP_DIVIDE && left_type.builtin_type == Variant::INT && right_type.builtin_type == Variant::INT) {
  1173. parser->push_warning(p_binary_op, GDScriptWarning::INTEGER_DIVISION);
  1174. }
  1175. if (p_binary_op->left_operand->is_constant && p_binary_op->right_operand->is_constant) {
  1176. p_binary_op->is_constant = true;
  1177. if (p_binary_op->variant_op < Variant::OP_MAX) {
  1178. p_binary_op->reduced_value = Variant::evaluate(p_binary_op->variant_op, p_binary_op->left_operand->reduced_value, p_binary_op->right_operand->reduced_value);
  1179. } else {
  1180. if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST) {
  1181. GDScriptParser::DataType test_type = right_type;
  1182. test_type.is_meta_type = false;
  1183. if (!is_type_compatible(test_type, p_binary_op->left_operand->get_datatype(), false)) {
  1184. push_error(vformat(R"(Expression is of type "%s" so it can't be of type "%s".)"), p_binary_op->left_operand);
  1185. p_binary_op->reduced_value = false;
  1186. } else {
  1187. p_binary_op->reduced_value = true;
  1188. }
  1189. } else {
  1190. ERR_PRINT("Parser bug: unknown binary operation.");
  1191. }
  1192. }
  1193. p_binary_op->set_datatype(type_from_variant(p_binary_op->reduced_value));
  1194. return;
  1195. }
  1196. GDScriptParser::DataType result;
  1197. if (left_type.is_variant() || right_type.is_variant()) {
  1198. // Cannot infer type because one operand can be anything.
  1199. result.kind = GDScriptParser::DataType::VARIANT;
  1200. mark_node_unsafe(p_binary_op);
  1201. } else {
  1202. if (p_binary_op->variant_op < Variant::OP_MAX) {
  1203. bool valid = false;
  1204. result = get_operation_type(p_binary_op->variant_op, p_binary_op->left_operand->get_datatype(), right_type, valid);
  1205. if (!valid) {
  1206. push_error(vformat(R"(Invalid operands "%s" and "%s" for "%s" operator.)", p_binary_op->left_operand->get_datatype().to_string(), right_type.to_string(), Variant::get_operator_name(p_binary_op->variant_op)), p_binary_op);
  1207. }
  1208. } else {
  1209. if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST) {
  1210. GDScriptParser::DataType test_type = right_type;
  1211. test_type.is_meta_type = false;
  1212. if (!is_type_compatible(test_type, p_binary_op->left_operand->get_datatype(), false)) {
  1213. if (p_binary_op->left_operand->get_datatype().is_hard_type()) {
  1214. 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);
  1215. } else {
  1216. // TODO: Warning.
  1217. mark_node_unsafe(p_binary_op);
  1218. }
  1219. }
  1220. // "is" operator is always a boolean anyway.
  1221. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1222. result.kind = GDScriptParser::DataType::BUILTIN;
  1223. result.builtin_type = Variant::BOOL;
  1224. } else {
  1225. ERR_PRINT("Parser bug: unknown binary operation.");
  1226. }
  1227. }
  1228. }
  1229. p_binary_op->set_datatype(result);
  1230. }
  1231. void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool is_await) {
  1232. bool all_is_constant = true;
  1233. for (int i = 0; i < p_call->arguments.size(); i++) {
  1234. reduce_expression(p_call->arguments[i]);
  1235. all_is_constant = all_is_constant && p_call->arguments[i]->is_constant;
  1236. }
  1237. GDScriptParser::DataType call_type;
  1238. if (!p_call->is_super && p_call->callee->type == GDScriptParser::Node::IDENTIFIER) {
  1239. // Call to name directly.
  1240. StringName function_name = p_call->function_name;
  1241. Variant::Type builtin_type = GDScriptParser::get_builtin_type(function_name);
  1242. GDScriptFunctions::Function builtin_function = GDScriptParser::get_builtin_function(function_name);
  1243. if (builtin_type < Variant::VARIANT_MAX) {
  1244. // Is a builtin constructor.
  1245. call_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1246. call_type.kind = GDScriptParser::DataType::BUILTIN;
  1247. call_type.builtin_type = builtin_type;
  1248. if (builtin_type == Variant::OBJECT) {
  1249. call_type.kind = GDScriptParser::DataType::NATIVE;
  1250. call_type.native_type = function_name; // "Object".
  1251. }
  1252. if (all_is_constant) {
  1253. // Construct here.
  1254. Vector<const Variant *> args;
  1255. for (int i = 0; i < p_call->arguments.size(); i++) {
  1256. args.push_back(&(p_call->arguments[i]->reduced_value));
  1257. }
  1258. Callable::CallError err;
  1259. Variant value = Variant::construct(builtin_type, (const Variant **)args.ptr(), args.size(), err);
  1260. switch (err.error) {
  1261. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:
  1262. 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,
  1263. Variant::get_type_name(Variant::Type(err.expected)), p_call->arguments[err.argument]->get_datatype().to_string()),
  1264. p_call->arguments[err.argument]);
  1265. break;
  1266. case Callable::CallError::CALL_ERROR_INVALID_METHOD: {
  1267. String signature = Variant::get_type_name(builtin_type) + "(";
  1268. for (int i = 0; i < p_call->arguments.size(); i++) {
  1269. if (i > 0) {
  1270. signature += ", ";
  1271. }
  1272. signature += p_call->arguments[i]->get_datatype().to_string();
  1273. }
  1274. push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call->callee);
  1275. } break;
  1276. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  1277. 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);
  1278. break;
  1279. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  1280. 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);
  1281. break;
  1282. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
  1283. break; // Can't happen in a builtin constructor.
  1284. case Callable::CallError::CALL_OK:
  1285. p_call->is_constant = true;
  1286. p_call->reduced_value = value;
  1287. break;
  1288. }
  1289. } else {
  1290. // TODO: Check constructors without constants.
  1291. // If there's one argument, try to use copy constructor (those aren't explicitly defined).
  1292. if (p_call->arguments.size() == 1) {
  1293. GDScriptParser::DataType arg_type = p_call->arguments[0]->get_datatype();
  1294. if (arg_type.is_variant()) {
  1295. mark_node_unsafe(p_call->arguments[0]);
  1296. } else {
  1297. if (arg_type.kind == GDScriptParser::DataType::BUILTIN && arg_type.builtin_type == builtin_type) {
  1298. // Okay.
  1299. p_call->set_datatype(call_type);
  1300. return;
  1301. }
  1302. }
  1303. }
  1304. List<MethodInfo> constructors;
  1305. Variant::get_constructor_list(builtin_type, &constructors);
  1306. bool match = false;
  1307. for (const List<MethodInfo>::Element *E = constructors.front(); E != nullptr; E = E->next()) {
  1308. const MethodInfo &info = E->get();
  1309. if (p_call->arguments.size() < info.arguments.size() - info.default_arguments.size()) {
  1310. continue;
  1311. }
  1312. if (p_call->arguments.size() > info.arguments.size()) {
  1313. continue;
  1314. }
  1315. bool types_match = true;
  1316. for (int i = 0; i < p_call->arguments.size(); i++) {
  1317. GDScriptParser::DataType par_type = type_from_property(info.arguments[i]);
  1318. if (!is_type_compatible(par_type, p_call->arguments[i]->get_datatype())) {
  1319. types_match = false;
  1320. break;
  1321. } else {
  1322. if (par_type.builtin_type == Variant::INT && p_call->arguments[i]->get_datatype().builtin_type == Variant::FLOAT) {
  1323. parser->push_warning(p_call, GDScriptWarning::NARROWING_CONVERSION, p_call->function_name);
  1324. }
  1325. }
  1326. }
  1327. if (types_match) {
  1328. match = true;
  1329. call_type = type_from_property(info.return_val);
  1330. break;
  1331. }
  1332. }
  1333. if (!match) {
  1334. String signature = Variant::get_type_name(builtin_type) + "(";
  1335. for (int i = 0; i < p_call->arguments.size(); i++) {
  1336. if (i > 0) {
  1337. signature += ", ";
  1338. }
  1339. signature += p_call->arguments[i]->get_datatype().to_string();
  1340. }
  1341. push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call);
  1342. }
  1343. }
  1344. p_call->set_datatype(call_type);
  1345. return;
  1346. } else if (builtin_function < GDScriptFunctions::FUNC_MAX) {
  1347. MethodInfo function_info = GDScriptFunctions::get_info(builtin_function);
  1348. if (all_is_constant && GDScriptFunctions::is_deterministic(builtin_function)) {
  1349. // Can call on compilation.
  1350. Vector<const Variant *> args;
  1351. for (int i = 0; i < p_call->arguments.size(); i++) {
  1352. args.push_back(&(p_call->arguments[i]->reduced_value));
  1353. }
  1354. Variant value;
  1355. Callable::CallError err;
  1356. GDScriptFunctions::call(builtin_function, (const Variant **)args.ptr(), args.size(), value, err);
  1357. switch (err.error) {
  1358. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT: {
  1359. PropertyInfo wrong_arg = function_info.arguments[err.argument];
  1360. push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be %s but is %s.)*", GDScriptFunctions::get_func_name(builtin_function), err.argument + 1,
  1361. type_from_property(wrong_arg).to_string(), p_call->arguments[err.argument]->get_datatype().to_string()),
  1362. p_call->arguments[err.argument]);
  1363. } break;
  1364. case Callable::CallError::CALL_ERROR_INVALID_METHOD:
  1365. push_error(vformat(R"(Invalid call for function "%s".)", GDScriptFunctions::get_func_name(builtin_function)), p_call);
  1366. break;
  1367. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  1368. push_error(vformat(R"*(Too many arguments for "%s()" call. Expected at most %d but received %d.)*", GDScriptFunctions::get_func_name(builtin_function), err.expected, p_call->arguments.size()), p_call);
  1369. break;
  1370. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  1371. push_error(vformat(R"*(Too few arguments for "%s()" call. Expected at least %d but received %d.)*", GDScriptFunctions::get_func_name(builtin_function), err.expected, p_call->arguments.size()), p_call);
  1372. break;
  1373. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
  1374. break; // Can't happen in a builtin constructor.
  1375. case Callable::CallError::CALL_OK:
  1376. p_call->is_constant = true;
  1377. p_call->reduced_value = value;
  1378. break;
  1379. }
  1380. } else {
  1381. validate_call_arg(function_info, p_call);
  1382. }
  1383. p_call->set_datatype(type_from_property(function_info.return_val));
  1384. return;
  1385. }
  1386. }
  1387. GDScriptParser::DataType base_type;
  1388. call_type.kind = GDScriptParser::DataType::VARIANT;
  1389. bool is_self = false;
  1390. if (p_call->is_super) {
  1391. base_type = parser->current_class->base_type;
  1392. is_self = true;
  1393. } else if (p_call->callee->type == GDScriptParser::Node::IDENTIFIER) {
  1394. base_type = parser->current_class->get_datatype();
  1395. is_self = true;
  1396. } else if (p_call->callee->type == GDScriptParser::Node::SUBSCRIPT) {
  1397. GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee);
  1398. if (!subscript->is_attribute) {
  1399. // Invalid call. Error already sent in parser.
  1400. // TODO: Could check if Callable here.
  1401. p_call->set_datatype(call_type);
  1402. mark_node_unsafe(p_call);
  1403. return;
  1404. }
  1405. reduce_expression(subscript->base);
  1406. base_type = subscript->base->get_datatype();
  1407. } else {
  1408. // Invalid call. Error already sent in parser.
  1409. // TODO: Could check if Callable here too.
  1410. p_call->set_datatype(call_type);
  1411. mark_node_unsafe(p_call);
  1412. return;
  1413. }
  1414. bool is_static = false;
  1415. bool is_vararg = false;
  1416. int default_arg_count = 0;
  1417. GDScriptParser::DataType return_type;
  1418. List<GDScriptParser::DataType> par_types;
  1419. if (get_function_signature(p_call, base_type, p_call->function_name, return_type, par_types, default_arg_count, is_static, is_vararg)) {
  1420. validate_call_arg(par_types, default_arg_count, is_vararg, p_call);
  1421. if (is_self && parser->current_function != nullptr && parser->current_function->is_static && !is_static) {
  1422. 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);
  1423. }
  1424. call_type = return_type;
  1425. } else {
  1426. // Check if the name exists as something else.
  1427. bool found = false;
  1428. if (!p_call->is_super) {
  1429. GDScriptParser::IdentifierNode *callee_id;
  1430. if (p_call->callee->type == GDScriptParser::Node::IDENTIFIER) {
  1431. callee_id = static_cast<GDScriptParser::IdentifierNode *>(p_call->callee);
  1432. } else {
  1433. // Can only be attribute.
  1434. callee_id = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee)->attribute;
  1435. }
  1436. reduce_identifier_from_base(callee_id, &base_type);
  1437. GDScriptParser::DataType callee_type = callee_id->get_datatype();
  1438. if (callee_type.is_set() && !callee_type.is_variant()) {
  1439. found = true;
  1440. if (callee_type.builtin_type == Variant::CALLABLE) {
  1441. 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);
  1442. } else {
  1443. push_error(vformat(R"*(Name "%s" called as a function but is a "%s".)*", p_call->function_name, callee_type.to_string()), p_call->callee);
  1444. }
  1445. } else if (!is_self) {
  1446. parser->push_warning(p_call, GDScriptWarning::UNSAFE_METHOD_ACCESS, p_call->function_name, base_type.to_string());
  1447. mark_node_unsafe(p_call);
  1448. }
  1449. }
  1450. if (!found && is_self) {
  1451. String base_name = is_self && !p_call->is_super ? "self" : base_type.to_string();
  1452. 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);
  1453. }
  1454. }
  1455. if (call_type.is_coroutine && !is_await) {
  1456. push_error(vformat(R"*(Function "%s()" is a coroutine, so it must be called with "await".)*", p_call->function_name), p_call->callee);
  1457. }
  1458. p_call->set_datatype(call_type);
  1459. }
  1460. void GDScriptAnalyzer::reduce_cast(GDScriptParser::CastNode *p_cast) {
  1461. reduce_expression(p_cast->operand);
  1462. GDScriptParser::DataType cast_type = resolve_datatype(p_cast->cast_type);
  1463. if (!cast_type.is_set()) {
  1464. return;
  1465. }
  1466. p_cast->set_datatype(cast_type);
  1467. if (!cast_type.is_variant()) {
  1468. if (!cast_type.is_meta_type) {
  1469. push_error(vformat(R"(Cast type "%s" isn't a valid type.)", cast_type.to_string()), p_cast->cast_type);
  1470. } else {
  1471. cast_type.is_meta_type = false; // For compatibility check purpose.
  1472. GDScriptParser::DataType op_type = p_cast->operand->get_datatype();
  1473. if (!op_type.is_variant()) {
  1474. bool valid = false;
  1475. if (op_type.kind == GDScriptParser::DataType::BUILTIN && cast_type.kind == GDScriptParser::DataType::BUILTIN) {
  1476. valid = Variant::can_convert(op_type.builtin_type, cast_type.builtin_type);
  1477. } else if (op_type.kind != GDScriptParser::DataType::BUILTIN && cast_type.kind != GDScriptParser::DataType::BUILTIN) {
  1478. valid = is_type_compatible(cast_type, op_type) || is_type_compatible(op_type, cast_type);
  1479. }
  1480. if (!valid) {
  1481. push_error(vformat(R"(Invalid cast. Cannot convert from "%s" to "%s".)", op_type.to_string(), cast_type.to_string()), p_cast->cast_type);
  1482. }
  1483. }
  1484. }
  1485. }
  1486. if (p_cast->operand->get_datatype().is_variant()) {
  1487. parser->push_warning(p_cast, GDScriptWarning::UNSAFE_CAST, cast_type.to_string());
  1488. mark_node_unsafe(p_cast);
  1489. }
  1490. // TODO: Perform cast on constants.
  1491. }
  1492. void GDScriptAnalyzer::reduce_dictionary(GDScriptParser::DictionaryNode *p_dictionary) {
  1493. bool all_is_constant = true;
  1494. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  1495. const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];
  1496. reduce_expression(element.key);
  1497. reduce_expression(element.value);
  1498. all_is_constant = all_is_constant && element.key->is_constant && element.value->is_constant;
  1499. }
  1500. if (all_is_constant) {
  1501. Dictionary dict;
  1502. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  1503. const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];
  1504. dict[element.key->reduced_value] = element.value->reduced_value;
  1505. }
  1506. p_dictionary->is_constant = true;
  1507. p_dictionary->reduced_value = dict;
  1508. }
  1509. // It's dictionary in any case.
  1510. GDScriptParser::DataType dict_type;
  1511. dict_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1512. dict_type.kind = GDScriptParser::DataType::BUILTIN;
  1513. dict_type.builtin_type = Variant::DICTIONARY;
  1514. dict_type.is_constant = true;
  1515. p_dictionary->set_datatype(dict_type);
  1516. }
  1517. void GDScriptAnalyzer::reduce_get_node(GDScriptParser::GetNodeNode *p_get_node) {
  1518. GDScriptParser::DataType result;
  1519. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1520. result.kind = GDScriptParser::DataType::NATIVE;
  1521. result.native_type = "Node";
  1522. result.builtin_type = Variant::OBJECT;
  1523. if (!ClassDB::is_parent_class(get_real_class_name(parser->current_class->base_type.native_type), result.native_type)) {
  1524. push_error(R"*(Cannot use shorthand "get_node()" notation ("$") on a class that isn't a node.)*", p_get_node);
  1525. }
  1526. p_get_node->set_datatype(result);
  1527. }
  1528. GDScriptParser::DataType GDScriptAnalyzer::make_global_class_meta_type(const StringName &p_class_name) {
  1529. Ref<GDScriptParserRef> ref = get_parser_for(ScriptServer::get_global_class_path(p_class_name));
  1530. ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED);
  1531. GDScriptParser::DataType type;
  1532. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1533. type.kind = GDScriptParser::DataType::CLASS;
  1534. type.builtin_type = Variant::OBJECT;
  1535. type.native_type = ScriptServer::get_global_class_native_base(p_class_name);
  1536. type.class_type = ref->get_parser()->head;
  1537. type.is_constant = true;
  1538. return type;
  1539. }
  1540. void GDScriptAnalyzer::reduce_identifier_from_base(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType *p_base) {
  1541. GDScriptParser::DataType base;
  1542. if (p_base == nullptr) {
  1543. base = type_from_metatype(parser->current_class->get_datatype());
  1544. } else {
  1545. base = *p_base;
  1546. }
  1547. const StringName &name = p_identifier->name;
  1548. if (base.kind == GDScriptParser::DataType::BUILTIN) {
  1549. if (base.is_meta_type) {
  1550. bool valid = true;
  1551. Variant result = Variant::get_constant_value(base.builtin_type, name, &valid);
  1552. if (valid) {
  1553. p_identifier->is_constant = true;
  1554. p_identifier->reduced_value = result;
  1555. p_identifier->set_datatype(type_from_variant(result));
  1556. } else {
  1557. push_error(vformat(R"(Cannot find constant "%s" on type "%s".)", name, base.to_string()), p_identifier);
  1558. }
  1559. } else {
  1560. Callable::CallError temp;
  1561. Variant dummy = Variant::construct(base.builtin_type, nullptr, 0, temp);
  1562. List<PropertyInfo> properties;
  1563. dummy.get_property_list(&properties);
  1564. for (const List<PropertyInfo>::Element *E = properties.front(); E != nullptr; E = E->next()) {
  1565. const PropertyInfo &prop = E->get();
  1566. if (prop.name == name) {
  1567. p_identifier->set_datatype(type_from_property(prop));
  1568. return;
  1569. }
  1570. }
  1571. push_error(vformat(R"(Cannot find property "%s" on base "%s".)", name, base.to_string()), p_identifier);
  1572. }
  1573. return;
  1574. }
  1575. if (base.kind == GDScriptParser::DataType::ENUM) {
  1576. if (base.is_meta_type) {
  1577. if (base.enum_values.has(name)) {
  1578. p_identifier->is_constant = true;
  1579. p_identifier->reduced_value = base.enum_values[name];
  1580. GDScriptParser::DataType result;
  1581. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1582. result.kind = GDScriptParser::DataType::ENUM_VALUE;
  1583. result.native_type = base.native_type;
  1584. result.enum_type = name;
  1585. p_identifier->set_datatype(result);
  1586. } else {
  1587. push_error(vformat(R"(Cannot find value "%s" in "%s".)", name, base.to_string()), p_identifier);
  1588. }
  1589. } else {
  1590. push_error(R"(Cannot get property from enum value.)", p_identifier);
  1591. }
  1592. return;
  1593. }
  1594. GDScriptParser::ClassNode *base_class = base.class_type;
  1595. // TODO: Switch current class/function/suite here to avoid misrepresenting identifiers (in recursive reduce calls).
  1596. while (base_class != nullptr) {
  1597. if (base_class->has_member(name)) {
  1598. const GDScriptParser::ClassNode::Member &member = base_class->get_member(name);
  1599. p_identifier->set_datatype(member.get_datatype());
  1600. switch (member.type) {
  1601. case GDScriptParser::ClassNode::Member::CONSTANT:
  1602. // For out-of-order resolution:
  1603. reduce_expression(member.constant->initializer);
  1604. p_identifier->is_constant = true;
  1605. p_identifier->reduced_value = member.constant->initializer->reduced_value;
  1606. p_identifier->set_datatype(member.constant->initializer->get_datatype());
  1607. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  1608. p_identifier->constant_source = member.constant;
  1609. break;
  1610. case GDScriptParser::ClassNode::Member::ENUM_VALUE:
  1611. p_identifier->is_constant = true;
  1612. p_identifier->reduced_value = member.enum_value.value;
  1613. break;
  1614. case GDScriptParser::ClassNode::Member::VARIABLE:
  1615. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_VARIABLE;
  1616. p_identifier->variable_source = member.variable;
  1617. break;
  1618. case GDScriptParser::ClassNode::Member::FUNCTION:
  1619. resolve_function_signature(member.function);
  1620. p_identifier->set_datatype(make_callable_type(member.function->info));
  1621. break;
  1622. default:
  1623. break; // Type already set.
  1624. }
  1625. return;
  1626. }
  1627. // Check outer constants.
  1628. // TODO: Allow outer static functions.
  1629. GDScriptParser::ClassNode *outer = base_class->outer;
  1630. while (outer != nullptr) {
  1631. if (outer->has_member(name)) {
  1632. const GDScriptParser::ClassNode::Member &member = base_class->get_member(name);
  1633. if (member.type == GDScriptParser::ClassNode::Member::CONSTANT) {
  1634. // TODO: Make sure loops won't cause problem. And make special error message for those.
  1635. // For out-of-order resolution:
  1636. reduce_expression(member.constant->initializer);
  1637. p_identifier->set_datatype(member.get_datatype());
  1638. p_identifier->is_constant = true;
  1639. p_identifier->reduced_value = member.constant->initializer->reduced_value;
  1640. return;
  1641. }
  1642. }
  1643. outer = outer->outer;
  1644. }
  1645. base_class = base_class->base_type.class_type;
  1646. }
  1647. // Check native members.
  1648. const StringName &native = get_real_class_name(base.native_type);
  1649. if (class_exists(native)) {
  1650. PropertyInfo prop_info;
  1651. MethodInfo method_info;
  1652. if (ClassDB::get_property_info(native, name, &prop_info)) {
  1653. p_identifier->set_datatype(type_from_property(prop_info));
  1654. return;
  1655. }
  1656. if (ClassDB::get_method_info(native, name, &method_info)) {
  1657. // Method is callable.
  1658. p_identifier->set_datatype(make_callable_type(method_info));
  1659. return;
  1660. }
  1661. if (ClassDB::get_signal(native, name, &method_info)) {
  1662. // Signal is a type too.
  1663. p_identifier->set_datatype(make_signal_type(method_info));
  1664. return;
  1665. }
  1666. if (ClassDB::has_enum(native, name)) {
  1667. p_identifier->set_datatype(make_native_enum_type(native, name));
  1668. return;
  1669. }
  1670. bool valid = false;
  1671. int int_constant = ClassDB::get_integer_constant(native, name, &valid);
  1672. if (valid) {
  1673. p_identifier->is_constant = true;
  1674. p_identifier->reduced_value = int_constant;
  1675. p_identifier->set_datatype(type_from_variant(int_constant));
  1676. return;
  1677. }
  1678. }
  1679. }
  1680. void GDScriptAnalyzer::reduce_identifier(GDScriptParser::IdentifierNode *p_identifier, bool can_be_builtin) {
  1681. // TODO: This is opportunity to further infer types.
  1682. // Check if identifier is local.
  1683. // If that's the case, the declaration already was solved before.
  1684. switch (p_identifier->source) {
  1685. case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER:
  1686. p_identifier->set_datatype(p_identifier->parameter_source->get_datatype());
  1687. return;
  1688. case GDScriptParser::IdentifierNode::LOCAL_CONSTANT:
  1689. case GDScriptParser::IdentifierNode::MEMBER_CONSTANT:
  1690. p_identifier->set_datatype(p_identifier->constant_source->get_datatype());
  1691. p_identifier->is_constant = true;
  1692. // TODO: Constant should have a value on the node itself.
  1693. p_identifier->reduced_value = p_identifier->constant_source->initializer->reduced_value;
  1694. return;
  1695. case GDScriptParser::IdentifierNode::MEMBER_VARIABLE:
  1696. p_identifier->variable_source->usages++;
  1697. [[fallthrough]];
  1698. case GDScriptParser::IdentifierNode::LOCAL_VARIABLE:
  1699. p_identifier->set_datatype(p_identifier->variable_source->get_datatype());
  1700. return;
  1701. case GDScriptParser::IdentifierNode::LOCAL_ITERATOR:
  1702. p_identifier->set_datatype(p_identifier->bind_source->get_datatype());
  1703. return;
  1704. case GDScriptParser::IdentifierNode::LOCAL_BIND: {
  1705. GDScriptParser::DataType result = p_identifier->bind_source->get_datatype();
  1706. result.is_constant = true;
  1707. p_identifier->set_datatype(result);
  1708. return;
  1709. }
  1710. case GDScriptParser::IdentifierNode::UNDEFINED_SOURCE:
  1711. break;
  1712. }
  1713. // Not a local, so check members.
  1714. reduce_identifier_from_base(p_identifier);
  1715. if (p_identifier->get_datatype().is_set()) {
  1716. // Found.
  1717. return;
  1718. }
  1719. StringName name = p_identifier->name;
  1720. p_identifier->source = GDScriptParser::IdentifierNode::UNDEFINED_SOURCE;
  1721. // Check globals.
  1722. if (GDScriptParser::get_builtin_type(name) < Variant::VARIANT_MAX) {
  1723. if (can_be_builtin) {
  1724. p_identifier->set_datatype(make_builtin_meta_type(GDScriptParser::get_builtin_type(name)));
  1725. return;
  1726. } else {
  1727. push_error(R"(Builtin type cannot be used as a name on its own.)", p_identifier);
  1728. }
  1729. }
  1730. if (class_exists(name)) {
  1731. p_identifier->set_datatype(make_native_meta_type(name));
  1732. return;
  1733. }
  1734. if (ScriptServer::is_global_class(name)) {
  1735. p_identifier->set_datatype(make_global_class_meta_type(name));
  1736. return;
  1737. }
  1738. if (GDScriptLanguage::get_singleton()->get_global_map().has(name)) {
  1739. int idx = GDScriptLanguage::get_singleton()->get_global_map()[name];
  1740. Variant constant = GDScriptLanguage::get_singleton()->get_global_array()[idx];
  1741. p_identifier->set_datatype(type_from_variant(constant));
  1742. p_identifier->is_constant = true;
  1743. p_identifier->reduced_value = constant;
  1744. return;
  1745. }
  1746. if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(name)) {
  1747. Variant constant = GDScriptLanguage::get_singleton()->get_named_globals_map()[name];
  1748. p_identifier->set_datatype(type_from_variant(constant));
  1749. p_identifier->is_constant = true;
  1750. p_identifier->reduced_value = constant;
  1751. return;
  1752. }
  1753. // Not found.
  1754. // Check if it's a builtin function.
  1755. if (parser->get_builtin_function(name) < GDScriptFunctions::FUNC_MAX) {
  1756. push_error(vformat(R"(Built-in function "%s" cannot be used as an identifier.)", name), p_identifier);
  1757. } else {
  1758. push_error(vformat(R"(Identifier "%s" not declared in the current scope.)", name), p_identifier);
  1759. }
  1760. GDScriptParser::DataType dummy;
  1761. dummy.kind = GDScriptParser::DataType::VARIANT;
  1762. p_identifier->set_datatype(dummy); // Just so type is set to something.
  1763. }
  1764. void GDScriptAnalyzer::reduce_literal(GDScriptParser::LiteralNode *p_literal) {
  1765. p_literal->reduced_value = p_literal->value;
  1766. p_literal->is_constant = true;
  1767. p_literal->set_datatype(type_from_variant(p_literal->reduced_value));
  1768. }
  1769. void GDScriptAnalyzer::reduce_preload(GDScriptParser::PreloadNode *p_preload) {
  1770. p_preload->is_constant = true;
  1771. p_preload->reduced_value = p_preload->resource;
  1772. p_preload->set_datatype(type_from_variant(p_preload->reduced_value));
  1773. }
  1774. void GDScriptAnalyzer::reduce_self(GDScriptParser::SelfNode *p_self) {
  1775. p_self->is_constant = false;
  1776. p_self->set_datatype(type_from_metatype(parser->current_class->get_datatype()));
  1777. }
  1778. void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscript) {
  1779. if (p_subscript->base->type == GDScriptParser::Node::IDENTIFIER) {
  1780. reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_subscript->base), true);
  1781. } else {
  1782. reduce_expression(p_subscript->base);
  1783. }
  1784. GDScriptParser::DataType result_type;
  1785. // Reduce index first. If it's a constant StringName, use attribute instead.
  1786. if (!p_subscript->is_attribute) {
  1787. reduce_expression(p_subscript->index);
  1788. if (p_subscript->index->is_constant && p_subscript->index->reduced_value.get_type() == Variant::STRING_NAME) {
  1789. GDScriptParser::IdentifierNode *attribute = parser->alloc_node<GDScriptParser::IdentifierNode>();
  1790. // Copy location for better error message.
  1791. attribute->start_line = p_subscript->index->start_line;
  1792. attribute->end_line = p_subscript->index->end_line;
  1793. attribute->leftmost_column = p_subscript->index->leftmost_column;
  1794. attribute->rightmost_column = p_subscript->index->rightmost_column;
  1795. p_subscript->is_attribute = true;
  1796. p_subscript->attribute = attribute;
  1797. }
  1798. }
  1799. if (p_subscript->is_attribute) {
  1800. if (p_subscript->base->is_constant) {
  1801. // Just try to get it.
  1802. bool valid = false;
  1803. Variant value = p_subscript->base->reduced_value.get_named(p_subscript->attribute->name, &valid);
  1804. if (!valid) {
  1805. push_error(vformat(R"(Cannot get member "%s" from "%s".)", p_subscript->attribute->name, p_subscript->base->reduced_value), p_subscript->index);
  1806. } else {
  1807. p_subscript->is_constant = true;
  1808. p_subscript->reduced_value = value;
  1809. result_type = type_from_variant(value);
  1810. }
  1811. result_type.kind = GDScriptParser::DataType::VARIANT;
  1812. } else {
  1813. GDScriptParser::DataType base_type = p_subscript->base->get_datatype();
  1814. if (base_type.is_variant()) {
  1815. result_type.kind = GDScriptParser::DataType::VARIANT;
  1816. mark_node_unsafe(p_subscript);
  1817. } else {
  1818. reduce_identifier_from_base(p_subscript->attribute, &base_type);
  1819. GDScriptParser::DataType attr_type = p_subscript->attribute->get_datatype();
  1820. if (attr_type.is_set()) {
  1821. result_type = attr_type;
  1822. p_subscript->is_constant = p_subscript->attribute->is_constant;
  1823. p_subscript->reduced_value = p_subscript->attribute->reduced_value;
  1824. } else {
  1825. if (base_type.kind == GDScriptParser::DataType::BUILTIN) {
  1826. push_error(vformat(R"(Cannot find member "%s" in base "%s".)", p_subscript->attribute->name, base_type.to_string()), p_subscript->attribute);
  1827. } else {
  1828. parser->push_warning(p_subscript, GDScriptWarning::UNSAFE_PROPERTY_ACCESS, p_subscript->attribute->name, base_type.to_string());
  1829. }
  1830. result_type.kind = GDScriptParser::DataType::VARIANT;
  1831. }
  1832. }
  1833. }
  1834. } else {
  1835. // Index was already reduced before.
  1836. if (p_subscript->base->is_constant && p_subscript->index->is_constant) {
  1837. // Just try to get it.
  1838. bool valid = false;
  1839. Variant value = p_subscript->base->reduced_value.get(p_subscript->index->reduced_value, &valid);
  1840. if (!valid) {
  1841. push_error(vformat(R"(Cannot get index "%s" from "%s".)", p_subscript->index->reduced_value, p_subscript->base->reduced_value), p_subscript->index);
  1842. } else {
  1843. p_subscript->is_constant = true;
  1844. p_subscript->reduced_value = value;
  1845. result_type = type_from_variant(value);
  1846. }
  1847. result_type.kind = GDScriptParser::DataType::VARIANT;
  1848. } else {
  1849. GDScriptParser::DataType base_type = p_subscript->base->get_datatype();
  1850. GDScriptParser::DataType index_type = p_subscript->index->get_datatype();
  1851. if (base_type.is_variant()) {
  1852. result_type.kind = GDScriptParser::DataType::VARIANT;
  1853. mark_node_unsafe(p_subscript);
  1854. } else {
  1855. if (base_type.kind == GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {
  1856. // Check if indexing is valid.
  1857. bool error = index_type.kind != GDScriptParser::DataType::BUILTIN && base_type.builtin_type != Variant::DICTIONARY;
  1858. if (!error) {
  1859. switch (base_type.builtin_type) {
  1860. // Expect int or real as index.
  1861. case Variant::PACKED_BYTE_ARRAY:
  1862. case Variant::PACKED_COLOR_ARRAY:
  1863. case Variant::PACKED_FLOAT32_ARRAY:
  1864. case Variant::PACKED_FLOAT64_ARRAY:
  1865. case Variant::PACKED_INT32_ARRAY:
  1866. case Variant::PACKED_INT64_ARRAY:
  1867. case Variant::PACKED_STRING_ARRAY:
  1868. case Variant::PACKED_VECTOR2_ARRAY:
  1869. case Variant::PACKED_VECTOR3_ARRAY:
  1870. case Variant::ARRAY:
  1871. case Variant::STRING:
  1872. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT;
  1873. break;
  1874. // Expect String only.
  1875. case Variant::RECT2:
  1876. case Variant::RECT2I:
  1877. case Variant::PLANE:
  1878. case Variant::QUAT:
  1879. case Variant::AABB:
  1880. case Variant::OBJECT:
  1881. error = index_type.builtin_type != Variant::STRING;
  1882. break;
  1883. // Expect String or number.
  1884. case Variant::BASIS:
  1885. case Variant::VECTOR2:
  1886. case Variant::VECTOR2I:
  1887. case Variant::VECTOR3:
  1888. case Variant::VECTOR3I:
  1889. case Variant::TRANSFORM:
  1890. case Variant::TRANSFORM2D:
  1891. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT &&
  1892. index_type.builtin_type != Variant::STRING;
  1893. break;
  1894. // Expect String or int.
  1895. case Variant::COLOR:
  1896. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::STRING;
  1897. break;
  1898. // Don't support indexing, but we will check it later.
  1899. case Variant::_RID:
  1900. case Variant::BOOL:
  1901. case Variant::CALLABLE:
  1902. case Variant::FLOAT:
  1903. case Variant::INT:
  1904. case Variant::NIL:
  1905. case Variant::NODE_PATH:
  1906. case Variant::SIGNAL:
  1907. case Variant::STRING_NAME:
  1908. break;
  1909. // Here for completeness.
  1910. case Variant::DICTIONARY:
  1911. case Variant::VARIANT_MAX:
  1912. break;
  1913. }
  1914. if (error) {
  1915. 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);
  1916. }
  1917. }
  1918. } else if (base_type.kind != GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {
  1919. if (index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME) {
  1920. 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);
  1921. }
  1922. }
  1923. // Check resulting type if possible.
  1924. result_type.builtin_type = Variant::NIL;
  1925. result_type.kind = GDScriptParser::DataType::BUILTIN;
  1926. result_type.type_source = GDScriptParser::DataType::INFERRED;
  1927. switch (base_type.builtin_type) {
  1928. // Can't index at all.
  1929. case Variant::_RID:
  1930. case Variant::BOOL:
  1931. case Variant::CALLABLE:
  1932. case Variant::FLOAT:
  1933. case Variant::INT:
  1934. case Variant::NIL:
  1935. case Variant::NODE_PATH:
  1936. case Variant::SIGNAL:
  1937. case Variant::STRING_NAME:
  1938. result_type.kind = GDScriptParser::DataType::VARIANT;
  1939. push_error(vformat(R"(Cannot use subscript operator on a base of type "%s".)", base_type.to_string()), p_subscript->base);
  1940. break;
  1941. // Return int.
  1942. case Variant::PACKED_BYTE_ARRAY:
  1943. case Variant::PACKED_INT32_ARRAY:
  1944. case Variant::PACKED_INT64_ARRAY:
  1945. case Variant::VECTOR2I:
  1946. case Variant::VECTOR3I:
  1947. result_type.builtin_type = Variant::INT;
  1948. break;
  1949. // Return float.
  1950. case Variant::PACKED_FLOAT32_ARRAY:
  1951. case Variant::PACKED_FLOAT64_ARRAY:
  1952. case Variant::VECTOR2:
  1953. case Variant::VECTOR3:
  1954. case Variant::QUAT:
  1955. result_type.builtin_type = Variant::FLOAT;
  1956. break;
  1957. // Return Color.
  1958. case Variant::PACKED_COLOR_ARRAY:
  1959. result_type.builtin_type = Variant::COLOR;
  1960. break;
  1961. // Return String.
  1962. case Variant::PACKED_STRING_ARRAY:
  1963. case Variant::STRING:
  1964. result_type.builtin_type = Variant::STRING;
  1965. break;
  1966. // Return Vector2.
  1967. case Variant::PACKED_VECTOR2_ARRAY:
  1968. case Variant::TRANSFORM2D:
  1969. case Variant::RECT2:
  1970. result_type.builtin_type = Variant::VECTOR2;
  1971. break;
  1972. // Return Vector2I.
  1973. case Variant::RECT2I:
  1974. result_type.builtin_type = Variant::VECTOR2I;
  1975. break;
  1976. // Return Vector3.
  1977. case Variant::PACKED_VECTOR3_ARRAY:
  1978. case Variant::AABB:
  1979. case Variant::BASIS:
  1980. result_type.builtin_type = Variant::VECTOR3;
  1981. break;
  1982. // Depends on the index.
  1983. case Variant::TRANSFORM:
  1984. case Variant::PLANE:
  1985. case Variant::COLOR:
  1986. case Variant::ARRAY:
  1987. case Variant::DICTIONARY:
  1988. result_type.kind = GDScriptParser::DataType::VARIANT;
  1989. result_type.type_source = GDScriptParser::DataType::UNDETECTED;
  1990. break;
  1991. // Here for completeness.
  1992. case Variant::OBJECT:
  1993. case Variant::VARIANT_MAX:
  1994. break;
  1995. }
  1996. }
  1997. }
  1998. }
  1999. p_subscript->set_datatype(result_type);
  2000. }
  2001. void GDScriptAnalyzer::reduce_ternary_op(GDScriptParser::TernaryOpNode *p_ternary_op) {
  2002. reduce_expression(p_ternary_op->condition);
  2003. reduce_expression(p_ternary_op->true_expr);
  2004. reduce_expression(p_ternary_op->false_expr);
  2005. GDScriptParser::DataType result;
  2006. if (p_ternary_op->condition->is_constant && p_ternary_op->true_expr->is_constant && p_ternary_op->false_expr->is_constant) {
  2007. p_ternary_op->is_constant = true;
  2008. if (p_ternary_op->condition->reduced_value.booleanize()) {
  2009. p_ternary_op->reduced_value = p_ternary_op->true_expr->reduced_value;
  2010. } else {
  2011. p_ternary_op->reduced_value = p_ternary_op->false_expr->reduced_value;
  2012. }
  2013. }
  2014. GDScriptParser::DataType true_type = p_ternary_op->true_expr->get_datatype();
  2015. GDScriptParser::DataType false_type = p_ternary_op->false_expr->get_datatype();
  2016. if (true_type.is_variant() || false_type.is_variant()) {
  2017. result.kind = GDScriptParser::DataType::VARIANT;
  2018. } else {
  2019. result = true_type;
  2020. if (!is_type_compatible(true_type, false_type)) {
  2021. result = false_type;
  2022. if (!is_type_compatible(false_type, true_type)) {
  2023. result.type_source = GDScriptParser::DataType::UNDETECTED;
  2024. result.kind = GDScriptParser::DataType::VARIANT;
  2025. parser->push_warning(p_ternary_op, GDScriptWarning::INCOMPATIBLE_TERNARY);
  2026. }
  2027. }
  2028. }
  2029. p_ternary_op->set_datatype(result);
  2030. }
  2031. void GDScriptAnalyzer::reduce_unary_op(GDScriptParser::UnaryOpNode *p_unary_op) {
  2032. reduce_expression(p_unary_op->operand);
  2033. GDScriptParser::DataType result;
  2034. if (p_unary_op->operand->is_constant) {
  2035. p_unary_op->is_constant = true;
  2036. p_unary_op->reduced_value = Variant::evaluate(p_unary_op->variant_op, p_unary_op->operand->reduced_value, Variant());
  2037. result = type_from_variant(p_unary_op->reduced_value);
  2038. } else if (p_unary_op->operand->get_datatype().is_variant()) {
  2039. result.kind = GDScriptParser::DataType::VARIANT;
  2040. mark_node_unsafe(p_unary_op);
  2041. } else {
  2042. bool valid = false;
  2043. result = get_operation_type(p_unary_op->variant_op, p_unary_op->operand->get_datatype(), p_unary_op->operand->get_datatype(), valid);
  2044. if (!valid) {
  2045. 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);
  2046. }
  2047. }
  2048. p_unary_op->set_datatype(result);
  2049. }
  2050. GDScriptParser::DataType GDScriptAnalyzer::type_from_variant(const Variant &p_value) {
  2051. GDScriptParser::DataType result;
  2052. result.is_constant = true;
  2053. result.kind = GDScriptParser::DataType::BUILTIN;
  2054. result.builtin_type = p_value.get_type();
  2055. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; // Constant has explicit type.
  2056. if (p_value.get_type() == Variant::OBJECT) {
  2057. Object *obj = p_value;
  2058. if (!obj) {
  2059. return GDScriptParser::DataType();
  2060. }
  2061. result.native_type = obj->get_class_name();
  2062. Ref<Script> scr = p_value; // Check if value is a script itself.
  2063. if (scr.is_valid()) {
  2064. result.is_meta_type = true;
  2065. } else {
  2066. result.is_meta_type = false;
  2067. scr = obj->get_script();
  2068. }
  2069. if (scr.is_valid()) {
  2070. result.script_type = scr;
  2071. Ref<GDScript> gds = scr;
  2072. if (gds.is_valid()) {
  2073. result.kind = GDScriptParser::DataType::CLASS;
  2074. Ref<GDScriptParserRef> ref = get_parser_for(gds->get_path());
  2075. ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED);
  2076. result.class_type = ref->get_parser()->head;
  2077. } else {
  2078. result.kind = GDScriptParser::DataType::SCRIPT;
  2079. }
  2080. result.native_type = scr->get_instance_base_type();
  2081. } else {
  2082. result.kind = GDScriptParser::DataType::NATIVE;
  2083. if (result.native_type == GDScriptNativeClass::get_class_static()) {
  2084. result.is_meta_type = true;
  2085. }
  2086. }
  2087. }
  2088. return result;
  2089. }
  2090. GDScriptParser::DataType GDScriptAnalyzer::type_from_metatype(const GDScriptParser::DataType &p_meta_type) const {
  2091. GDScriptParser::DataType result = p_meta_type;
  2092. result.is_meta_type = false;
  2093. result.is_constant = false;
  2094. return result;
  2095. }
  2096. GDScriptParser::DataType GDScriptAnalyzer::type_from_property(const PropertyInfo &p_property) const {
  2097. GDScriptParser::DataType result;
  2098. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2099. if (p_property.type == Variant::NIL && (p_property.usage & PROPERTY_USAGE_NIL_IS_VARIANT)) {
  2100. // Variant
  2101. result.kind = GDScriptParser::DataType::VARIANT;
  2102. return result;
  2103. }
  2104. result.builtin_type = p_property.type;
  2105. if (p_property.type == Variant::OBJECT) {
  2106. result.kind = GDScriptParser::DataType::NATIVE;
  2107. result.native_type = p_property.class_name == StringName() ? "Object" : p_property.class_name;
  2108. } else {
  2109. result.kind = GDScriptParser::DataType::BUILTIN;
  2110. }
  2111. return result;
  2112. }
  2113. bool GDScriptAnalyzer::get_function_signature(GDScriptParser::Node *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) {
  2114. r_static = false;
  2115. r_vararg = false;
  2116. r_default_arg_count = 0;
  2117. if (p_base_type.kind == GDScriptParser::DataType::BUILTIN) {
  2118. // Construct a base type to get methods.
  2119. Callable::CallError err;
  2120. Variant dummy = Variant::construct(p_base_type.builtin_type, nullptr, 0, err);
  2121. if (err.error != Callable::CallError::CALL_OK) {
  2122. ERR_FAIL_V_MSG(false, "Could not construct base Variant type.");
  2123. }
  2124. List<MethodInfo> methods;
  2125. dummy.get_method_list(&methods);
  2126. for (const List<MethodInfo>::Element *E = methods.front(); E != nullptr; E = E->next()) {
  2127. if (E->get().name == p_function) {
  2128. return function_signature_from_info(E->get(), r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  2129. }
  2130. }
  2131. return false;
  2132. }
  2133. GDScriptParser::ClassNode *base_class = p_base_type.class_type;
  2134. GDScriptParser::FunctionNode *found_function = nullptr;
  2135. while (found_function == nullptr && base_class != nullptr) {
  2136. if (base_class->has_member(p_function)) {
  2137. if (base_class->get_member(p_function).type != GDScriptParser::ClassNode::Member::FUNCTION) {
  2138. // TODO: If this is Callable it can have a better error message.
  2139. push_error(vformat(R"(Member "%s" is not a function.)", p_function), p_source);
  2140. return false;
  2141. }
  2142. found_function = base_class->get_member(p_function).function;
  2143. }
  2144. base_class = base_class->base_type.class_type;
  2145. }
  2146. if (found_function != nullptr) {
  2147. r_static = found_function->is_static;
  2148. for (int i = 0; i < found_function->parameters.size(); i++) {
  2149. r_par_types.push_back(found_function->parameters[i]->get_datatype());
  2150. if (found_function->parameters[i]->default_value != nullptr) {
  2151. r_default_arg_count++;
  2152. }
  2153. }
  2154. r_return_type = found_function->get_datatype();
  2155. r_return_type.is_coroutine = found_function->is_coroutine;
  2156. return true;
  2157. }
  2158. // TODO: Check here the "new" function in GDScript class when metatype, as it needs to look the constructor.
  2159. Ref<Script> base_script = p_base_type.script_type;
  2160. while (base_script.is_valid() && base_script->is_valid()) {
  2161. MethodInfo info = base_script->get_method_info(p_function);
  2162. if (!(info == MethodInfo())) {
  2163. return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  2164. }
  2165. base_script = base_script->get_base_script();
  2166. }
  2167. // If the base is a script, it might be trying to access members of the Script class itself.
  2168. if (p_base_type.is_meta_type && !(p_function == "new") && (p_base_type.kind == GDScriptParser::DataType::SCRIPT || p_base_type.kind == GDScriptParser::DataType::CLASS)) {
  2169. MethodInfo info;
  2170. StringName script_class = p_base_type.kind == GDScriptParser::DataType::SCRIPT ? p_base_type.script_type->get_class_name() : StringName(GDScript::get_class_static());
  2171. if (ClassDB::get_method_info(script_class, p_function, &info)) {
  2172. return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  2173. }
  2174. }
  2175. StringName base_native = p_base_type.native_type;
  2176. if (base_native == StringName()) {
  2177. // Empty native class, might happen in some Script implementations.
  2178. // Just ignore it.
  2179. return false;
  2180. }
  2181. #ifdef DEBUG_ENABLED
  2182. if (!class_exists(base_native)) {
  2183. ERR_FAIL_V_MSG(false, vformat("Native class %s used in script doesn't exist or isn't exposed.", base_native));
  2184. }
  2185. #endif
  2186. StringName real_native = get_real_class_name(base_native);
  2187. MethodInfo info;
  2188. if (ClassDB::get_method_info(real_native, p_function, &info)) {
  2189. return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  2190. }
  2191. return false;
  2192. }
  2193. 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) {
  2194. r_return_type = type_from_property(p_info.return_val);
  2195. r_default_arg_count = p_info.default_arguments.size();
  2196. r_vararg = (p_info.flags & METHOD_FLAG_VARARG) != 0;
  2197. for (const List<PropertyInfo>::Element *E = p_info.arguments.front(); E != nullptr; E = E->next()) {
  2198. r_par_types.push_back(type_from_property(E->get()));
  2199. }
  2200. return true;
  2201. }
  2202. bool GDScriptAnalyzer::validate_call_arg(const MethodInfo &p_method, const GDScriptParser::CallNode *p_call) {
  2203. List<GDScriptParser::DataType> arg_types;
  2204. for (const List<PropertyInfo>::Element *E = p_method.arguments.front(); E != nullptr; E = E->next()) {
  2205. arg_types.push_back(type_from_property(E->get()));
  2206. }
  2207. return validate_call_arg(arg_types, p_method.default_arguments.size(), (p_method.flags & METHOD_FLAG_VARARG) != 0, p_call);
  2208. }
  2209. 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) {
  2210. bool valid = true;
  2211. if (p_call->arguments.size() < p_par_types.size() - p_default_args_count) {
  2212. 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);
  2213. valid = false;
  2214. }
  2215. if (!p_is_vararg && p_call->arguments.size() > p_par_types.size()) {
  2216. 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()]);
  2217. valid = false;
  2218. }
  2219. for (int i = 0; i < p_call->arguments.size(); i++) {
  2220. if (i >= p_par_types.size()) {
  2221. // Already on vararg place.
  2222. break;
  2223. }
  2224. GDScriptParser::DataType par_type = p_par_types[i];
  2225. GDScriptParser::DataType arg_type = p_call->arguments[i]->get_datatype();
  2226. if (arg_type.is_variant()) {
  2227. // Argument can be anything, so this is unsafe.
  2228. mark_node_unsafe(p_call->arguments[i]);
  2229. } else if (!is_type_compatible(par_type, arg_type, true)) {
  2230. // Supertypes are acceptable for dynamic compliance, but it's unsafe.
  2231. mark_node_unsafe(p_call);
  2232. if (!is_type_compatible(arg_type, par_type)) {
  2233. push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be %s but is %s.)*",
  2234. p_call->function_name, i + 1, par_type.to_string(), arg_type.to_string()),
  2235. p_call->arguments[i]);
  2236. valid = false;
  2237. }
  2238. } else {
  2239. 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) {
  2240. parser->push_warning(p_call, GDScriptWarning::NARROWING_CONVERSION, p_call->function_name);
  2241. }
  2242. }
  2243. }
  2244. return valid;
  2245. }
  2246. bool GDScriptAnalyzer::is_shadowing(GDScriptParser::IdentifierNode *p_local, const String &p_context) {
  2247. const StringName &name = p_local->name;
  2248. GDScriptParser::DataType base = parser->current_class->get_datatype();
  2249. GDScriptParser::ClassNode *base_class = base.class_type;
  2250. while (base_class != nullptr) {
  2251. if (base_class->has_member(name)) {
  2252. 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()));
  2253. return true;
  2254. }
  2255. base_class = base_class->base_type.class_type;
  2256. }
  2257. StringName base_native = base.native_type;
  2258. ERR_FAIL_COND_V_MSG(!class_exists(base_native), false, "Non-existent native base class.");
  2259. StringName parent = base_native;
  2260. while (parent != StringName()) {
  2261. StringName real_class_name = get_real_class_name(parent);
  2262. if (ClassDB::has_method(real_class_name, name, true)) {
  2263. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "method", parent);
  2264. return true;
  2265. } else if (ClassDB::has_signal(real_class_name, name, true)) {
  2266. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "signal", parent);
  2267. return true;
  2268. } else if (ClassDB::has_property(real_class_name, name, true)) {
  2269. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "property", parent);
  2270. return true;
  2271. } else if (ClassDB::has_integer_constant(real_class_name, name, true)) {
  2272. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "constant", parent);
  2273. return true;
  2274. } else if (ClassDB::has_enum(real_class_name, name, true)) {
  2275. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "enum", parent);
  2276. return true;
  2277. }
  2278. parent = ClassDB::get_parent_class(real_class_name);
  2279. }
  2280. return false;
  2281. }
  2282. GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, const GDScriptParser::DataType &p_b, bool &r_valid) {
  2283. // This function creates dummy variant values and apply the operation to those. Less error-prone than keeping a table of valid operations.
  2284. GDScriptParser::DataType result;
  2285. result.kind = GDScriptParser::DataType::VARIANT;
  2286. Variant::Type a_type = p_a.builtin_type;
  2287. Variant::Type b_type = p_b.builtin_type;
  2288. Variant a;
  2289. REF a_ref;
  2290. if (a_type == Variant::OBJECT) {
  2291. a_ref.instance();
  2292. a = a_ref;
  2293. } else {
  2294. Callable::CallError err;
  2295. a = Variant::construct(a_type, nullptr, 0, err);
  2296. if (err.error != Callable::CallError::CALL_OK) {
  2297. r_valid = false;
  2298. ERR_FAIL_V_MSG(result, vformat("Could not construct value of type %s", Variant::get_type_name(a_type)));
  2299. }
  2300. }
  2301. Variant b;
  2302. REF b_ref;
  2303. if (b_type == Variant::OBJECT) {
  2304. b_ref.instance();
  2305. b = b_ref;
  2306. } else {
  2307. Callable::CallError err;
  2308. b = Variant::construct(b_type, nullptr, 0, err);
  2309. if (err.error != Callable::CallError::CALL_OK) {
  2310. r_valid = false;
  2311. ERR_FAIL_V_MSG(result, vformat("Could not construct value of type %s", Variant::get_type_name(b_type)));
  2312. }
  2313. }
  2314. // Avoid division by zero.
  2315. switch (b_type) {
  2316. case Variant::INT:
  2317. b = 1;
  2318. break;
  2319. case Variant::FLOAT:
  2320. b = 1.0;
  2321. break;
  2322. case Variant::VECTOR2:
  2323. b = Vector2(1.0, 1.0);
  2324. break;
  2325. case Variant::VECTOR2I:
  2326. b = Vector2i(1, 1);
  2327. break;
  2328. case Variant::VECTOR3:
  2329. b = Vector3(1.0, 1.0, 1.0);
  2330. break;
  2331. case Variant::VECTOR3I:
  2332. b = Vector3i(1, 1, 1);
  2333. break;
  2334. case Variant::COLOR:
  2335. b = Color(1.0, 1.0, 1.0, 1.0);
  2336. break;
  2337. default:
  2338. // No change needed.
  2339. break;
  2340. }
  2341. // Avoid error in formatting operator (%) where it doesn't find a placeholder.
  2342. if (a_type == Variant::STRING) {
  2343. a = String("%s");
  2344. }
  2345. Variant ret;
  2346. Variant::evaluate(p_operation, a, b, ret, r_valid);
  2347. if (r_valid) {
  2348. return type_from_variant(ret);
  2349. }
  2350. return result;
  2351. }
  2352. // TODO: Add safe/unsafe return variable (for variant cases)
  2353. bool GDScriptAnalyzer::is_type_compatible(const GDScriptParser::DataType &p_target, const GDScriptParser::DataType &p_source, bool p_allow_implicit_conversion) const {
  2354. // These return "true" so it doesn't affect users negatively.
  2355. ERR_FAIL_COND_V_MSG(!p_target.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset target type");
  2356. ERR_FAIL_COND_V_MSG(!p_source.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset value type");
  2357. if (p_target.kind == GDScriptParser::DataType::VARIANT) {
  2358. // Variant can receive anything.
  2359. return true;
  2360. }
  2361. if (p_source.kind == GDScriptParser::DataType::VARIANT) {
  2362. // TODO: This is acceptable but unsafe. Make sure unsafe line is set.
  2363. return true;
  2364. }
  2365. if (p_target.kind == GDScriptParser::DataType::BUILTIN) {
  2366. bool valid = p_source.kind == GDScriptParser::DataType::BUILTIN && p_target.builtin_type == p_source.builtin_type;
  2367. if (!valid && p_allow_implicit_conversion) {
  2368. valid = Variant::can_convert_strict(p_source.builtin_type, p_target.builtin_type);
  2369. }
  2370. if (!valid && p_target.builtin_type == Variant::INT && p_source.kind == GDScriptParser::DataType::ENUM_VALUE) {
  2371. // Enum value is also integer.
  2372. valid = true;
  2373. }
  2374. return valid;
  2375. }
  2376. if (p_target.kind == GDScriptParser::DataType::ENUM) {
  2377. if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::INT) {
  2378. return true;
  2379. }
  2380. if (p_source.kind == GDScriptParser::DataType::ENUM_VALUE) {
  2381. if (p_source.native_type == p_target.native_type && p_target.enum_values.has(p_source.enum_type)) {
  2382. return true;
  2383. }
  2384. }
  2385. return false;
  2386. }
  2387. // From here on the target type is an object, so we have to test polymorphism.
  2388. if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::NIL) {
  2389. // null is acceptable in object.
  2390. return true;
  2391. }
  2392. StringName src_native;
  2393. Ref<Script> src_script;
  2394. const GDScriptParser::ClassNode *src_class = nullptr;
  2395. switch (p_source.kind) {
  2396. case GDScriptParser::DataType::NATIVE:
  2397. if (p_target.kind != GDScriptParser::DataType::NATIVE) {
  2398. // Non-native class cannot be supertype of native.
  2399. return false;
  2400. }
  2401. if (p_source.is_meta_type) {
  2402. src_native = GDScriptNativeClass::get_class_static();
  2403. } else {
  2404. src_native = p_source.native_type;
  2405. }
  2406. break;
  2407. case GDScriptParser::DataType::SCRIPT:
  2408. if (p_target.kind == GDScriptParser::DataType::CLASS) {
  2409. // A script type cannot be a subtype of a GDScript class.
  2410. return false;
  2411. }
  2412. if (p_source.is_meta_type) {
  2413. src_native = p_source.script_type->get_class_name();
  2414. } else {
  2415. src_script = p_source.script_type;
  2416. src_native = src_script->get_instance_base_type();
  2417. }
  2418. break;
  2419. case GDScriptParser::DataType::CLASS:
  2420. if (p_source.is_meta_type) {
  2421. src_native = GDScript::get_class_static();
  2422. } else {
  2423. src_class = p_source.class_type;
  2424. const GDScriptParser::ClassNode *base = src_class;
  2425. while (base->base_type.kind == GDScriptParser::DataType::CLASS) {
  2426. base = base->base_type.class_type;
  2427. }
  2428. src_native = base->base_type.native_type;
  2429. src_script = base->base_type.script_type;
  2430. }
  2431. break;
  2432. case GDScriptParser::DataType::VARIANT:
  2433. case GDScriptParser::DataType::BUILTIN:
  2434. case GDScriptParser::DataType::ENUM:
  2435. case GDScriptParser::DataType::ENUM_VALUE:
  2436. case GDScriptParser::DataType::UNRESOLVED:
  2437. break; // Already solved before.
  2438. }
  2439. // Get underscore-prefixed version for some classes.
  2440. src_native = get_real_class_name(src_native);
  2441. switch (p_target.kind) {
  2442. case GDScriptParser::DataType::NATIVE: {
  2443. if (p_target.is_meta_type) {
  2444. return ClassDB::is_parent_class(src_native, GDScriptNativeClass::get_class_static());
  2445. }
  2446. StringName tgt_native = get_real_class_name(p_target.native_type);
  2447. return ClassDB::is_parent_class(src_native, tgt_native);
  2448. }
  2449. case GDScriptParser::DataType::SCRIPT:
  2450. if (p_target.is_meta_type) {
  2451. return ClassDB::is_parent_class(src_native, p_target.script_type->get_class_name());
  2452. }
  2453. while (src_script.is_valid()) {
  2454. if (src_script == p_target.script_type) {
  2455. return true;
  2456. }
  2457. src_script = src_script->get_base_script();
  2458. }
  2459. return false;
  2460. case GDScriptParser::DataType::CLASS:
  2461. if (p_target.is_meta_type) {
  2462. return ClassDB::is_parent_class(src_native, GDScript::get_class_static());
  2463. }
  2464. while (src_class != nullptr) {
  2465. if (src_class->fqcn == p_target.class_type->fqcn) {
  2466. return true;
  2467. }
  2468. src_class = src_class->base_type.class_type;
  2469. }
  2470. return false;
  2471. case GDScriptParser::DataType::VARIANT:
  2472. case GDScriptParser::DataType::BUILTIN:
  2473. case GDScriptParser::DataType::ENUM:
  2474. case GDScriptParser::DataType::ENUM_VALUE:
  2475. case GDScriptParser::DataType::UNRESOLVED:
  2476. break; // Already solved before.
  2477. }
  2478. return false;
  2479. }
  2480. void GDScriptAnalyzer::push_error(const String &p_message, const GDScriptParser::Node *p_origin) {
  2481. mark_node_unsafe(p_origin);
  2482. parser->push_error(p_message, p_origin);
  2483. }
  2484. void GDScriptAnalyzer::mark_node_unsafe(const GDScriptParser::Node *p_node) {
  2485. for (int i = p_node->start_line; i <= p_node->end_line; i++) {
  2486. parser->unsafe_lines.insert(i);
  2487. }
  2488. }
  2489. bool GDScriptAnalyzer::class_exists(const StringName &p_class) {
  2490. StringName real_name = get_real_class_name(p_class);
  2491. return ClassDB::class_exists(real_name) && ClassDB::is_class_exposed(real_name);
  2492. }
  2493. Ref<GDScriptParserRef> GDScriptAnalyzer::get_parser_for(const String &p_path) {
  2494. Ref<GDScriptParserRef> ref;
  2495. if (depended_parsers.has(p_path)) {
  2496. ref = depended_parsers[p_path];
  2497. } else {
  2498. Error err = OK;
  2499. ref = GDScriptCache::get_parser(p_path, GDScriptParserRef::EMPTY, err);
  2500. depended_parsers[p_path] = ref;
  2501. }
  2502. return ref;
  2503. }
  2504. Error GDScriptAnalyzer::resolve_inheritance() {
  2505. return resolve_inheritance(parser->head);
  2506. }
  2507. Error GDScriptAnalyzer::resolve_interface() {
  2508. resolve_class_interface(parser->head);
  2509. return parser->errors.empty() ? OK : ERR_PARSE_ERROR;
  2510. }
  2511. Error GDScriptAnalyzer::resolve_body() {
  2512. resolve_class_body(parser->head);
  2513. return parser->errors.empty() ? OK : ERR_PARSE_ERROR;
  2514. }
  2515. Error GDScriptAnalyzer::resolve_program() {
  2516. resolve_class_interface(parser->head);
  2517. resolve_class_body(parser->head);
  2518. List<String> parser_keys;
  2519. depended_parsers.get_key_list(&parser_keys);
  2520. for (const List<String>::Element *E = parser_keys.front(); E != nullptr; E = E->next()) {
  2521. depended_parsers[E->get()]->raise_status(GDScriptParserRef::FULLY_SOLVED);
  2522. }
  2523. depended_parsers.clear();
  2524. return parser->errors.empty() ? OK : ERR_PARSE_ERROR;
  2525. }
  2526. Error GDScriptAnalyzer::analyze() {
  2527. parser->errors.clear();
  2528. Error err = resolve_inheritance(parser->head);
  2529. if (err) {
  2530. return err;
  2531. }
  2532. return resolve_program();
  2533. }
  2534. GDScriptAnalyzer::GDScriptAnalyzer(GDScriptParser *p_parser) {
  2535. parser = p_parser;
  2536. }