2
0

gdscript_analyzer.cpp 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899
  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 == nullptr) {
  988. return;
  989. }
  990. if (p_expression->reduced) {
  991. // Don't do this more than once.
  992. return;
  993. }
  994. p_expression->reduced = true;
  995. switch (p_expression->type) {
  996. case GDScriptParser::Node::ARRAY:
  997. reduce_array(static_cast<GDScriptParser::ArrayNode *>(p_expression));
  998. break;
  999. case GDScriptParser::Node::ASSIGNMENT:
  1000. reduce_assignment(static_cast<GDScriptParser::AssignmentNode *>(p_expression));
  1001. break;
  1002. case GDScriptParser::Node::AWAIT:
  1003. reduce_await(static_cast<GDScriptParser::AwaitNode *>(p_expression));
  1004. break;
  1005. case GDScriptParser::Node::BINARY_OPERATOR:
  1006. reduce_binary_op(static_cast<GDScriptParser::BinaryOpNode *>(p_expression));
  1007. break;
  1008. case GDScriptParser::Node::CALL:
  1009. reduce_call(static_cast<GDScriptParser::CallNode *>(p_expression));
  1010. break;
  1011. case GDScriptParser::Node::CAST:
  1012. reduce_cast(static_cast<GDScriptParser::CastNode *>(p_expression));
  1013. break;
  1014. case GDScriptParser::Node::DICTIONARY:
  1015. reduce_dictionary(static_cast<GDScriptParser::DictionaryNode *>(p_expression));
  1016. break;
  1017. case GDScriptParser::Node::GET_NODE:
  1018. reduce_get_node(static_cast<GDScriptParser::GetNodeNode *>(p_expression));
  1019. break;
  1020. case GDScriptParser::Node::IDENTIFIER:
  1021. reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_expression));
  1022. break;
  1023. case GDScriptParser::Node::LITERAL:
  1024. reduce_literal(static_cast<GDScriptParser::LiteralNode *>(p_expression));
  1025. break;
  1026. case GDScriptParser::Node::PRELOAD:
  1027. reduce_preload(static_cast<GDScriptParser::PreloadNode *>(p_expression));
  1028. break;
  1029. case GDScriptParser::Node::SELF:
  1030. reduce_self(static_cast<GDScriptParser::SelfNode *>(p_expression));
  1031. break;
  1032. case GDScriptParser::Node::SUBSCRIPT:
  1033. reduce_subscript(static_cast<GDScriptParser::SubscriptNode *>(p_expression));
  1034. break;
  1035. case GDScriptParser::Node::TERNARY_OPERATOR:
  1036. reduce_ternary_op(static_cast<GDScriptParser::TernaryOpNode *>(p_expression));
  1037. break;
  1038. case GDScriptParser::Node::UNARY_OPERATOR:
  1039. reduce_unary_op(static_cast<GDScriptParser::UnaryOpNode *>(p_expression));
  1040. break;
  1041. // Non-expressions. Here only to make sure new nodes aren't forgotten.
  1042. case GDScriptParser::Node::NONE:
  1043. case GDScriptParser::Node::ANNOTATION:
  1044. case GDScriptParser::Node::ASSERT:
  1045. case GDScriptParser::Node::BREAK:
  1046. case GDScriptParser::Node::BREAKPOINT:
  1047. case GDScriptParser::Node::CLASS:
  1048. case GDScriptParser::Node::CONSTANT:
  1049. case GDScriptParser::Node::CONTINUE:
  1050. case GDScriptParser::Node::ENUM:
  1051. case GDScriptParser::Node::FOR:
  1052. case GDScriptParser::Node::FUNCTION:
  1053. case GDScriptParser::Node::IF:
  1054. case GDScriptParser::Node::MATCH:
  1055. case GDScriptParser::Node::MATCH_BRANCH:
  1056. case GDScriptParser::Node::PARAMETER:
  1057. case GDScriptParser::Node::PASS:
  1058. case GDScriptParser::Node::PATTERN:
  1059. case GDScriptParser::Node::RETURN:
  1060. case GDScriptParser::Node::SIGNAL:
  1061. case GDScriptParser::Node::SUITE:
  1062. case GDScriptParser::Node::TYPE:
  1063. case GDScriptParser::Node::VARIABLE:
  1064. case GDScriptParser::Node::WHILE:
  1065. ERR_FAIL_MSG("Reaching unreachable case");
  1066. }
  1067. }
  1068. void GDScriptAnalyzer::reduce_array(GDScriptParser::ArrayNode *p_array) {
  1069. bool all_is_constant = true;
  1070. for (int i = 0; i < p_array->elements.size(); i++) {
  1071. GDScriptParser::ExpressionNode *element = p_array->elements[i];
  1072. reduce_expression(element);
  1073. all_is_constant = all_is_constant && element->is_constant;
  1074. }
  1075. if (all_is_constant) {
  1076. Array array;
  1077. array.resize(p_array->elements.size());
  1078. for (int i = 0; i < p_array->elements.size(); i++) {
  1079. array[i] = p_array->elements[i]->reduced_value;
  1080. }
  1081. p_array->is_constant = true;
  1082. p_array->reduced_value = array;
  1083. }
  1084. // It's array in any case.
  1085. GDScriptParser::DataType arr_type;
  1086. arr_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1087. arr_type.kind = GDScriptParser::DataType::BUILTIN;
  1088. arr_type.builtin_type = Variant::ARRAY;
  1089. arr_type.is_constant = true;
  1090. p_array->set_datatype(arr_type);
  1091. }
  1092. void GDScriptAnalyzer::reduce_assignment(GDScriptParser::AssignmentNode *p_assignment) {
  1093. reduce_expression(p_assignment->assignee);
  1094. reduce_expression(p_assignment->assigned_value);
  1095. if (p_assignment->assigned_value == nullptr || p_assignment->assignee == nullptr) {
  1096. return;
  1097. }
  1098. if (p_assignment->assignee->get_datatype().is_constant) {
  1099. push_error("Cannot assign a new value to a constant.", p_assignment->assignee);
  1100. }
  1101. if (!is_type_compatible(p_assignment->assignee->get_datatype(), p_assignment->assigned_value->get_datatype())) {
  1102. if (p_assignment->assignee->get_datatype().is_hard_type()) {
  1103. 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);
  1104. } else {
  1105. // TODO: Warning in this case.
  1106. }
  1107. }
  1108. if (p_assignment->assignee->get_datatype().has_no_type() || p_assignment->assigned_value->get_datatype().is_variant()) {
  1109. mark_node_unsafe(p_assignment);
  1110. }
  1111. if (p_assignment->assignee->type == GDScriptParser::Node::IDENTIFIER) {
  1112. // Change source type so it's not wrongly detected later.
  1113. GDScriptParser::IdentifierNode *identifier = static_cast<GDScriptParser::IdentifierNode *>(p_assignment->assignee);
  1114. switch (identifier->source) {
  1115. case GDScriptParser::IdentifierNode::MEMBER_VARIABLE: {
  1116. GDScriptParser::DataType id_type = identifier->variable_source->get_datatype();
  1117. if (!id_type.is_hard_type()) {
  1118. id_type.kind = GDScriptParser::DataType::VARIANT;
  1119. id_type.type_source = GDScriptParser::DataType::UNDETECTED;
  1120. identifier->variable_source->set_datatype(id_type);
  1121. }
  1122. } break;
  1123. case GDScriptParser::IdentifierNode::LOCAL_VARIABLE: {
  1124. GDScriptParser::DataType id_type = identifier->variable_source->get_datatype();
  1125. if (!id_type.is_hard_type()) {
  1126. id_type = p_assignment->assigned_value->get_datatype();
  1127. id_type.type_source = GDScriptParser::DataType::INFERRED;
  1128. id_type.is_constant = false;
  1129. identifier->variable_source->set_datatype(id_type);
  1130. }
  1131. } break;
  1132. case GDScriptParser::IdentifierNode::LOCAL_ITERATOR: {
  1133. GDScriptParser::DataType id_type = identifier->bind_source->get_datatype();
  1134. if (!id_type.is_hard_type()) {
  1135. id_type = p_assignment->assigned_value->get_datatype();
  1136. id_type.type_source = GDScriptParser::DataType::INFERRED;
  1137. id_type.is_constant = false;
  1138. identifier->variable_source->set_datatype(id_type);
  1139. }
  1140. } break;
  1141. default:
  1142. // Nothing to do.
  1143. break;
  1144. }
  1145. }
  1146. GDScriptParser::DataType assignee_type = p_assignment->assignee->get_datatype();
  1147. GDScriptParser::DataType assigned_type = p_assignment->assigned_value->get_datatype();
  1148. if (p_assignment->assigned_value->type == GDScriptParser::Node::CALL && assigned_type.kind == GDScriptParser::DataType::BUILTIN && assigned_type.builtin_type == Variant::NIL) {
  1149. parser->push_warning(p_assignment->assigned_value, GDScriptWarning::VOID_ASSIGNMENT, static_cast<GDScriptParser::CallNode *>(p_assignment->assigned_value)->function_name);
  1150. } else if (assignee_type.is_hard_type() && assignee_type.builtin_type == Variant::INT && assigned_type.builtin_type == Variant::FLOAT) {
  1151. parser->push_warning(p_assignment->assigned_value, GDScriptWarning::NARROWING_CONVERSION);
  1152. }
  1153. }
  1154. void GDScriptAnalyzer::reduce_await(GDScriptParser::AwaitNode *p_await) {
  1155. if (p_await->to_await->type == GDScriptParser::Node::CALL) {
  1156. reduce_call(static_cast<GDScriptParser::CallNode *>(p_await->to_await), true);
  1157. } else {
  1158. reduce_expression(p_await->to_await);
  1159. }
  1160. p_await->is_constant = p_await->to_await->is_constant;
  1161. p_await->reduced_value = p_await->to_await->reduced_value;
  1162. GDScriptParser::DataType awaiting_type = p_await->to_await->get_datatype();
  1163. p_await->set_datatype(awaiting_type);
  1164. if (!awaiting_type.is_coroutine && awaiting_type.builtin_type != Variant::SIGNAL) {
  1165. parser->push_warning(p_await, GDScriptWarning::REDUNDANT_AWAIT);
  1166. }
  1167. }
  1168. void GDScriptAnalyzer::reduce_binary_op(GDScriptParser::BinaryOpNode *p_binary_op) {
  1169. reduce_expression(p_binary_op->left_operand);
  1170. if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST && p_binary_op->right_operand->type == GDScriptParser::Node::IDENTIFIER) {
  1171. reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_binary_op->right_operand), true);
  1172. } else {
  1173. reduce_expression(p_binary_op->right_operand);
  1174. }
  1175. // TODO: Right operand must be a valid type with the `is` operator. Need to check here.
  1176. GDScriptParser::DataType left_type = p_binary_op->left_operand->get_datatype();
  1177. GDScriptParser::DataType right_type = p_binary_op->right_operand->get_datatype();
  1178. if (p_binary_op->variant_op == Variant::OP_DIVIDE && left_type.builtin_type == Variant::INT && right_type.builtin_type == Variant::INT) {
  1179. parser->push_warning(p_binary_op, GDScriptWarning::INTEGER_DIVISION);
  1180. }
  1181. if (p_binary_op->left_operand->is_constant && p_binary_op->right_operand->is_constant) {
  1182. p_binary_op->is_constant = true;
  1183. if (p_binary_op->variant_op < Variant::OP_MAX) {
  1184. 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);
  1185. } else {
  1186. if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST) {
  1187. GDScriptParser::DataType test_type = right_type;
  1188. test_type.is_meta_type = false;
  1189. if (!is_type_compatible(test_type, p_binary_op->left_operand->get_datatype(), false)) {
  1190. push_error(vformat(R"(Expression is of type "%s" so it can't be of type "%s".)"), p_binary_op->left_operand);
  1191. p_binary_op->reduced_value = false;
  1192. } else {
  1193. p_binary_op->reduced_value = true;
  1194. }
  1195. } else {
  1196. ERR_PRINT("Parser bug: unknown binary operation.");
  1197. }
  1198. }
  1199. p_binary_op->set_datatype(type_from_variant(p_binary_op->reduced_value));
  1200. return;
  1201. }
  1202. GDScriptParser::DataType result;
  1203. if (left_type.is_variant() || right_type.is_variant()) {
  1204. // Cannot infer type because one operand can be anything.
  1205. result.kind = GDScriptParser::DataType::VARIANT;
  1206. mark_node_unsafe(p_binary_op);
  1207. } else {
  1208. if (p_binary_op->variant_op < Variant::OP_MAX) {
  1209. bool valid = false;
  1210. result = get_operation_type(p_binary_op->variant_op, p_binary_op->left_operand->get_datatype(), right_type, valid);
  1211. if (!valid) {
  1212. 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);
  1213. }
  1214. } else {
  1215. if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST) {
  1216. GDScriptParser::DataType test_type = right_type;
  1217. test_type.is_meta_type = false;
  1218. if (!is_type_compatible(test_type, p_binary_op->left_operand->get_datatype(), false)) {
  1219. if (p_binary_op->left_operand->get_datatype().is_hard_type()) {
  1220. 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);
  1221. } else {
  1222. // TODO: Warning.
  1223. mark_node_unsafe(p_binary_op);
  1224. }
  1225. }
  1226. // "is" operator is always a boolean anyway.
  1227. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1228. result.kind = GDScriptParser::DataType::BUILTIN;
  1229. result.builtin_type = Variant::BOOL;
  1230. } else {
  1231. ERR_PRINT("Parser bug: unknown binary operation.");
  1232. }
  1233. }
  1234. }
  1235. p_binary_op->set_datatype(result);
  1236. }
  1237. void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool is_await) {
  1238. bool all_is_constant = true;
  1239. for (int i = 0; i < p_call->arguments.size(); i++) {
  1240. reduce_expression(p_call->arguments[i]);
  1241. all_is_constant = all_is_constant && p_call->arguments[i]->is_constant;
  1242. }
  1243. GDScriptParser::DataType call_type;
  1244. if (!p_call->is_super && p_call->callee->type == GDScriptParser::Node::IDENTIFIER) {
  1245. // Call to name directly.
  1246. StringName function_name = p_call->function_name;
  1247. Variant::Type builtin_type = GDScriptParser::get_builtin_type(function_name);
  1248. GDScriptFunctions::Function builtin_function = GDScriptParser::get_builtin_function(function_name);
  1249. if (builtin_type < Variant::VARIANT_MAX) {
  1250. // Is a builtin constructor.
  1251. call_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1252. call_type.kind = GDScriptParser::DataType::BUILTIN;
  1253. call_type.builtin_type = builtin_type;
  1254. if (builtin_type == Variant::OBJECT) {
  1255. call_type.kind = GDScriptParser::DataType::NATIVE;
  1256. call_type.native_type = function_name; // "Object".
  1257. }
  1258. if (all_is_constant) {
  1259. // Construct here.
  1260. Vector<const Variant *> args;
  1261. for (int i = 0; i < p_call->arguments.size(); i++) {
  1262. args.push_back(&(p_call->arguments[i]->reduced_value));
  1263. }
  1264. Callable::CallError err;
  1265. Variant value = Variant::construct(builtin_type, (const Variant **)args.ptr(), args.size(), err);
  1266. switch (err.error) {
  1267. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:
  1268. 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,
  1269. Variant::get_type_name(Variant::Type(err.expected)), p_call->arguments[err.argument]->get_datatype().to_string()),
  1270. p_call->arguments[err.argument]);
  1271. break;
  1272. case Callable::CallError::CALL_ERROR_INVALID_METHOD: {
  1273. String signature = Variant::get_type_name(builtin_type) + "(";
  1274. for (int i = 0; i < p_call->arguments.size(); i++) {
  1275. if (i > 0) {
  1276. signature += ", ";
  1277. }
  1278. signature += p_call->arguments[i]->get_datatype().to_string();
  1279. }
  1280. push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call->callee);
  1281. } break;
  1282. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  1283. 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);
  1284. break;
  1285. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  1286. 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);
  1287. break;
  1288. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
  1289. break; // Can't happen in a builtin constructor.
  1290. case Callable::CallError::CALL_OK:
  1291. p_call->is_constant = true;
  1292. p_call->reduced_value = value;
  1293. break;
  1294. }
  1295. } else {
  1296. // TODO: Check constructors without constants.
  1297. // If there's one argument, try to use copy constructor (those aren't explicitly defined).
  1298. if (p_call->arguments.size() == 1) {
  1299. GDScriptParser::DataType arg_type = p_call->arguments[0]->get_datatype();
  1300. if (arg_type.is_variant()) {
  1301. mark_node_unsafe(p_call->arguments[0]);
  1302. } else {
  1303. if (arg_type.kind == GDScriptParser::DataType::BUILTIN && arg_type.builtin_type == builtin_type) {
  1304. // Okay.
  1305. p_call->set_datatype(call_type);
  1306. return;
  1307. }
  1308. }
  1309. }
  1310. List<MethodInfo> constructors;
  1311. Variant::get_constructor_list(builtin_type, &constructors);
  1312. bool match = false;
  1313. for (const List<MethodInfo>::Element *E = constructors.front(); E != nullptr; E = E->next()) {
  1314. const MethodInfo &info = E->get();
  1315. if (p_call->arguments.size() < info.arguments.size() - info.default_arguments.size()) {
  1316. continue;
  1317. }
  1318. if (p_call->arguments.size() > info.arguments.size()) {
  1319. continue;
  1320. }
  1321. bool types_match = true;
  1322. for (int i = 0; i < p_call->arguments.size(); i++) {
  1323. GDScriptParser::DataType par_type = type_from_property(info.arguments[i]);
  1324. if (!is_type_compatible(par_type, p_call->arguments[i]->get_datatype())) {
  1325. types_match = false;
  1326. break;
  1327. } else {
  1328. if (par_type.builtin_type == Variant::INT && p_call->arguments[i]->get_datatype().builtin_type == Variant::FLOAT) {
  1329. parser->push_warning(p_call, GDScriptWarning::NARROWING_CONVERSION, p_call->function_name);
  1330. }
  1331. }
  1332. }
  1333. if (types_match) {
  1334. match = true;
  1335. call_type = type_from_property(info.return_val);
  1336. break;
  1337. }
  1338. }
  1339. if (!match) {
  1340. String signature = Variant::get_type_name(builtin_type) + "(";
  1341. for (int i = 0; i < p_call->arguments.size(); i++) {
  1342. if (i > 0) {
  1343. signature += ", ";
  1344. }
  1345. signature += p_call->arguments[i]->get_datatype().to_string();
  1346. }
  1347. push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call);
  1348. }
  1349. }
  1350. p_call->set_datatype(call_type);
  1351. return;
  1352. } else if (builtin_function < GDScriptFunctions::FUNC_MAX) {
  1353. MethodInfo function_info = GDScriptFunctions::get_info(builtin_function);
  1354. if (all_is_constant && GDScriptFunctions::is_deterministic(builtin_function)) {
  1355. // Can call on compilation.
  1356. Vector<const Variant *> args;
  1357. for (int i = 0; i < p_call->arguments.size(); i++) {
  1358. args.push_back(&(p_call->arguments[i]->reduced_value));
  1359. }
  1360. Variant value;
  1361. Callable::CallError err;
  1362. GDScriptFunctions::call(builtin_function, (const Variant **)args.ptr(), args.size(), value, err);
  1363. switch (err.error) {
  1364. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT: {
  1365. PropertyInfo wrong_arg = function_info.arguments[err.argument];
  1366. 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,
  1367. type_from_property(wrong_arg).to_string(), p_call->arguments[err.argument]->get_datatype().to_string()),
  1368. p_call->arguments[err.argument]);
  1369. } break;
  1370. case Callable::CallError::CALL_ERROR_INVALID_METHOD:
  1371. push_error(vformat(R"(Invalid call for function "%s".)", GDScriptFunctions::get_func_name(builtin_function)), p_call);
  1372. break;
  1373. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  1374. 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);
  1375. break;
  1376. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  1377. 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);
  1378. break;
  1379. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
  1380. break; // Can't happen in a builtin constructor.
  1381. case Callable::CallError::CALL_OK:
  1382. p_call->is_constant = true;
  1383. p_call->reduced_value = value;
  1384. break;
  1385. }
  1386. } else {
  1387. validate_call_arg(function_info, p_call);
  1388. }
  1389. p_call->set_datatype(type_from_property(function_info.return_val));
  1390. return;
  1391. }
  1392. }
  1393. GDScriptParser::DataType base_type;
  1394. call_type.kind = GDScriptParser::DataType::VARIANT;
  1395. bool is_self = false;
  1396. if (p_call->is_super) {
  1397. base_type = parser->current_class->base_type;
  1398. is_self = true;
  1399. } else if (p_call->callee->type == GDScriptParser::Node::IDENTIFIER) {
  1400. base_type = parser->current_class->get_datatype();
  1401. is_self = true;
  1402. } else if (p_call->callee->type == GDScriptParser::Node::SUBSCRIPT) {
  1403. GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee);
  1404. if (!subscript->is_attribute) {
  1405. // Invalid call. Error already sent in parser.
  1406. // TODO: Could check if Callable here.
  1407. p_call->set_datatype(call_type);
  1408. mark_node_unsafe(p_call);
  1409. return;
  1410. }
  1411. reduce_expression(subscript->base);
  1412. base_type = subscript->base->get_datatype();
  1413. } else {
  1414. // Invalid call. Error already sent in parser.
  1415. // TODO: Could check if Callable here too.
  1416. p_call->set_datatype(call_type);
  1417. mark_node_unsafe(p_call);
  1418. return;
  1419. }
  1420. bool is_static = false;
  1421. bool is_vararg = false;
  1422. int default_arg_count = 0;
  1423. GDScriptParser::DataType return_type;
  1424. List<GDScriptParser::DataType> par_types;
  1425. if (get_function_signature(p_call, base_type, p_call->function_name, return_type, par_types, default_arg_count, is_static, is_vararg)) {
  1426. validate_call_arg(par_types, default_arg_count, is_vararg, p_call);
  1427. if (is_self && parser->current_function != nullptr && parser->current_function->is_static && !is_static) {
  1428. 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);
  1429. }
  1430. call_type = return_type;
  1431. } else {
  1432. // Check if the name exists as something else.
  1433. bool found = false;
  1434. if (!p_call->is_super) {
  1435. GDScriptParser::IdentifierNode *callee_id;
  1436. if (p_call->callee->type == GDScriptParser::Node::IDENTIFIER) {
  1437. callee_id = static_cast<GDScriptParser::IdentifierNode *>(p_call->callee);
  1438. } else {
  1439. // Can only be attribute.
  1440. callee_id = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee)->attribute;
  1441. }
  1442. reduce_identifier_from_base(callee_id, &base_type);
  1443. GDScriptParser::DataType callee_type = callee_id->get_datatype();
  1444. if (callee_type.is_set() && !callee_type.is_variant()) {
  1445. found = true;
  1446. if (callee_type.builtin_type == Variant::CALLABLE) {
  1447. 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);
  1448. } else {
  1449. 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);
  1450. }
  1451. } else if (!is_self) {
  1452. parser->push_warning(p_call, GDScriptWarning::UNSAFE_METHOD_ACCESS, p_call->function_name, base_type.to_string());
  1453. mark_node_unsafe(p_call);
  1454. }
  1455. }
  1456. if (!found && is_self) {
  1457. String base_name = is_self && !p_call->is_super ? "self" : base_type.to_string();
  1458. 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);
  1459. }
  1460. }
  1461. if (call_type.is_coroutine && !is_await) {
  1462. push_error(vformat(R"*(Function "%s()" is a coroutine, so it must be called with "await".)*", p_call->function_name), p_call->callee);
  1463. }
  1464. p_call->set_datatype(call_type);
  1465. }
  1466. void GDScriptAnalyzer::reduce_cast(GDScriptParser::CastNode *p_cast) {
  1467. reduce_expression(p_cast->operand);
  1468. GDScriptParser::DataType cast_type = resolve_datatype(p_cast->cast_type);
  1469. if (!cast_type.is_set()) {
  1470. return;
  1471. }
  1472. p_cast->set_datatype(cast_type);
  1473. if (!cast_type.is_variant()) {
  1474. if (!cast_type.is_meta_type) {
  1475. push_error(vformat(R"(Cast type "%s" isn't a valid type.)", cast_type.to_string()), p_cast->cast_type);
  1476. } else {
  1477. cast_type.is_meta_type = false; // For compatibility check purpose.
  1478. GDScriptParser::DataType op_type = p_cast->operand->get_datatype();
  1479. if (!op_type.is_variant()) {
  1480. bool valid = false;
  1481. if (op_type.kind == GDScriptParser::DataType::BUILTIN && cast_type.kind == GDScriptParser::DataType::BUILTIN) {
  1482. valid = Variant::can_convert(op_type.builtin_type, cast_type.builtin_type);
  1483. } else if (op_type.kind != GDScriptParser::DataType::BUILTIN && cast_type.kind != GDScriptParser::DataType::BUILTIN) {
  1484. valid = is_type_compatible(cast_type, op_type) || is_type_compatible(op_type, cast_type);
  1485. }
  1486. if (!valid) {
  1487. push_error(vformat(R"(Invalid cast. Cannot convert from "%s" to "%s".)", op_type.to_string(), cast_type.to_string()), p_cast->cast_type);
  1488. }
  1489. }
  1490. }
  1491. }
  1492. if (p_cast->operand->get_datatype().is_variant()) {
  1493. parser->push_warning(p_cast, GDScriptWarning::UNSAFE_CAST, cast_type.to_string());
  1494. mark_node_unsafe(p_cast);
  1495. }
  1496. // TODO: Perform cast on constants.
  1497. }
  1498. void GDScriptAnalyzer::reduce_dictionary(GDScriptParser::DictionaryNode *p_dictionary) {
  1499. bool all_is_constant = true;
  1500. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  1501. const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];
  1502. reduce_expression(element.key);
  1503. reduce_expression(element.value);
  1504. all_is_constant = all_is_constant && element.key->is_constant && element.value->is_constant;
  1505. }
  1506. if (all_is_constant) {
  1507. Dictionary dict;
  1508. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  1509. const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];
  1510. dict[element.key->reduced_value] = element.value->reduced_value;
  1511. }
  1512. p_dictionary->is_constant = true;
  1513. p_dictionary->reduced_value = dict;
  1514. }
  1515. // It's dictionary in any case.
  1516. GDScriptParser::DataType dict_type;
  1517. dict_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1518. dict_type.kind = GDScriptParser::DataType::BUILTIN;
  1519. dict_type.builtin_type = Variant::DICTIONARY;
  1520. dict_type.is_constant = true;
  1521. p_dictionary->set_datatype(dict_type);
  1522. }
  1523. void GDScriptAnalyzer::reduce_get_node(GDScriptParser::GetNodeNode *p_get_node) {
  1524. GDScriptParser::DataType result;
  1525. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1526. result.kind = GDScriptParser::DataType::NATIVE;
  1527. result.native_type = "Node";
  1528. result.builtin_type = Variant::OBJECT;
  1529. if (!ClassDB::is_parent_class(get_real_class_name(parser->current_class->base_type.native_type), result.native_type)) {
  1530. push_error(R"*(Cannot use shorthand "get_node()" notation ("$") on a class that isn't a node.)*", p_get_node);
  1531. }
  1532. p_get_node->set_datatype(result);
  1533. }
  1534. GDScriptParser::DataType GDScriptAnalyzer::make_global_class_meta_type(const StringName &p_class_name) {
  1535. Ref<GDScriptParserRef> ref = get_parser_for(ScriptServer::get_global_class_path(p_class_name));
  1536. ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED);
  1537. GDScriptParser::DataType type;
  1538. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1539. type.kind = GDScriptParser::DataType::CLASS;
  1540. type.builtin_type = Variant::OBJECT;
  1541. type.native_type = ScriptServer::get_global_class_native_base(p_class_name);
  1542. type.class_type = ref->get_parser()->head;
  1543. type.is_constant = true;
  1544. return type;
  1545. }
  1546. void GDScriptAnalyzer::reduce_identifier_from_base(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType *p_base) {
  1547. GDScriptParser::DataType base;
  1548. if (p_base == nullptr) {
  1549. base = type_from_metatype(parser->current_class->get_datatype());
  1550. } else {
  1551. base = *p_base;
  1552. }
  1553. const StringName &name = p_identifier->name;
  1554. if (base.kind == GDScriptParser::DataType::BUILTIN) {
  1555. if (base.is_meta_type) {
  1556. bool valid = true;
  1557. Variant result = Variant::get_constant_value(base.builtin_type, name, &valid);
  1558. if (valid) {
  1559. p_identifier->is_constant = true;
  1560. p_identifier->reduced_value = result;
  1561. p_identifier->set_datatype(type_from_variant(result));
  1562. } else {
  1563. push_error(vformat(R"(Cannot find constant "%s" on type "%s".)", name, base.to_string()), p_identifier);
  1564. }
  1565. } else {
  1566. Callable::CallError temp;
  1567. Variant dummy = Variant::construct(base.builtin_type, nullptr, 0, temp);
  1568. List<PropertyInfo> properties;
  1569. dummy.get_property_list(&properties);
  1570. for (const List<PropertyInfo>::Element *E = properties.front(); E != nullptr; E = E->next()) {
  1571. const PropertyInfo &prop = E->get();
  1572. if (prop.name == name) {
  1573. p_identifier->set_datatype(type_from_property(prop));
  1574. return;
  1575. }
  1576. }
  1577. push_error(vformat(R"(Cannot find property "%s" on base "%s".)", name, base.to_string()), p_identifier);
  1578. }
  1579. return;
  1580. }
  1581. if (base.kind == GDScriptParser::DataType::ENUM) {
  1582. if (base.is_meta_type) {
  1583. if (base.enum_values.has(name)) {
  1584. p_identifier->is_constant = true;
  1585. p_identifier->reduced_value = base.enum_values[name];
  1586. GDScriptParser::DataType result;
  1587. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1588. result.kind = GDScriptParser::DataType::ENUM_VALUE;
  1589. result.native_type = base.native_type;
  1590. result.enum_type = name;
  1591. p_identifier->set_datatype(result);
  1592. } else {
  1593. push_error(vformat(R"(Cannot find value "%s" in "%s".)", name, base.to_string()), p_identifier);
  1594. }
  1595. } else {
  1596. push_error(R"(Cannot get property from enum value.)", p_identifier);
  1597. }
  1598. return;
  1599. }
  1600. GDScriptParser::ClassNode *base_class = base.class_type;
  1601. // TODO: Switch current class/function/suite here to avoid misrepresenting identifiers (in recursive reduce calls).
  1602. while (base_class != nullptr) {
  1603. if (base_class->has_member(name)) {
  1604. const GDScriptParser::ClassNode::Member &member = base_class->get_member(name);
  1605. p_identifier->set_datatype(member.get_datatype());
  1606. switch (member.type) {
  1607. case GDScriptParser::ClassNode::Member::CONSTANT:
  1608. // For out-of-order resolution:
  1609. reduce_expression(member.constant->initializer);
  1610. p_identifier->is_constant = true;
  1611. p_identifier->reduced_value = member.constant->initializer->reduced_value;
  1612. p_identifier->set_datatype(member.constant->initializer->get_datatype());
  1613. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  1614. p_identifier->constant_source = member.constant;
  1615. break;
  1616. case GDScriptParser::ClassNode::Member::ENUM_VALUE:
  1617. p_identifier->is_constant = true;
  1618. p_identifier->reduced_value = member.enum_value.value;
  1619. break;
  1620. case GDScriptParser::ClassNode::Member::VARIABLE:
  1621. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_VARIABLE;
  1622. p_identifier->variable_source = member.variable;
  1623. break;
  1624. case GDScriptParser::ClassNode::Member::FUNCTION:
  1625. resolve_function_signature(member.function);
  1626. p_identifier->set_datatype(make_callable_type(member.function->info));
  1627. break;
  1628. default:
  1629. break; // Type already set.
  1630. }
  1631. return;
  1632. }
  1633. // Check outer constants.
  1634. // TODO: Allow outer static functions.
  1635. GDScriptParser::ClassNode *outer = base_class->outer;
  1636. while (outer != nullptr) {
  1637. if (outer->has_member(name)) {
  1638. const GDScriptParser::ClassNode::Member &member = base_class->get_member(name);
  1639. if (member.type == GDScriptParser::ClassNode::Member::CONSTANT) {
  1640. // TODO: Make sure loops won't cause problem. And make special error message for those.
  1641. // For out-of-order resolution:
  1642. reduce_expression(member.constant->initializer);
  1643. p_identifier->set_datatype(member.get_datatype());
  1644. p_identifier->is_constant = true;
  1645. p_identifier->reduced_value = member.constant->initializer->reduced_value;
  1646. return;
  1647. }
  1648. }
  1649. outer = outer->outer;
  1650. }
  1651. base_class = base_class->base_type.class_type;
  1652. }
  1653. // Check native members.
  1654. const StringName &native = get_real_class_name(base.native_type);
  1655. if (class_exists(native)) {
  1656. PropertyInfo prop_info;
  1657. MethodInfo method_info;
  1658. if (ClassDB::get_property_info(native, name, &prop_info)) {
  1659. p_identifier->set_datatype(type_from_property(prop_info));
  1660. return;
  1661. }
  1662. if (ClassDB::get_method_info(native, name, &method_info)) {
  1663. // Method is callable.
  1664. p_identifier->set_datatype(make_callable_type(method_info));
  1665. return;
  1666. }
  1667. if (ClassDB::get_signal(native, name, &method_info)) {
  1668. // Signal is a type too.
  1669. p_identifier->set_datatype(make_signal_type(method_info));
  1670. return;
  1671. }
  1672. if (ClassDB::has_enum(native, name)) {
  1673. p_identifier->set_datatype(make_native_enum_type(native, name));
  1674. return;
  1675. }
  1676. bool valid = false;
  1677. int int_constant = ClassDB::get_integer_constant(native, name, &valid);
  1678. if (valid) {
  1679. p_identifier->is_constant = true;
  1680. p_identifier->reduced_value = int_constant;
  1681. p_identifier->set_datatype(type_from_variant(int_constant));
  1682. return;
  1683. }
  1684. }
  1685. }
  1686. void GDScriptAnalyzer::reduce_identifier(GDScriptParser::IdentifierNode *p_identifier, bool can_be_builtin) {
  1687. // TODO: This is opportunity to further infer types.
  1688. // Check if identifier is local.
  1689. // If that's the case, the declaration already was solved before.
  1690. switch (p_identifier->source) {
  1691. case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER:
  1692. p_identifier->set_datatype(p_identifier->parameter_source->get_datatype());
  1693. return;
  1694. case GDScriptParser::IdentifierNode::LOCAL_CONSTANT:
  1695. case GDScriptParser::IdentifierNode::MEMBER_CONSTANT:
  1696. p_identifier->set_datatype(p_identifier->constant_source->get_datatype());
  1697. p_identifier->is_constant = true;
  1698. // TODO: Constant should have a value on the node itself.
  1699. p_identifier->reduced_value = p_identifier->constant_source->initializer->reduced_value;
  1700. return;
  1701. case GDScriptParser::IdentifierNode::MEMBER_VARIABLE:
  1702. p_identifier->variable_source->usages++;
  1703. [[fallthrough]];
  1704. case GDScriptParser::IdentifierNode::LOCAL_VARIABLE:
  1705. p_identifier->set_datatype(p_identifier->variable_source->get_datatype());
  1706. return;
  1707. case GDScriptParser::IdentifierNode::LOCAL_ITERATOR:
  1708. p_identifier->set_datatype(p_identifier->bind_source->get_datatype());
  1709. return;
  1710. case GDScriptParser::IdentifierNode::LOCAL_BIND: {
  1711. GDScriptParser::DataType result = p_identifier->bind_source->get_datatype();
  1712. result.is_constant = true;
  1713. p_identifier->set_datatype(result);
  1714. return;
  1715. }
  1716. case GDScriptParser::IdentifierNode::UNDEFINED_SOURCE:
  1717. break;
  1718. }
  1719. // Not a local, so check members.
  1720. reduce_identifier_from_base(p_identifier);
  1721. if (p_identifier->get_datatype().is_set()) {
  1722. // Found.
  1723. return;
  1724. }
  1725. StringName name = p_identifier->name;
  1726. p_identifier->source = GDScriptParser::IdentifierNode::UNDEFINED_SOURCE;
  1727. // Check globals.
  1728. if (GDScriptParser::get_builtin_type(name) < Variant::VARIANT_MAX) {
  1729. if (can_be_builtin) {
  1730. p_identifier->set_datatype(make_builtin_meta_type(GDScriptParser::get_builtin_type(name)));
  1731. return;
  1732. } else {
  1733. push_error(R"(Builtin type cannot be used as a name on its own.)", p_identifier);
  1734. }
  1735. }
  1736. if (class_exists(name)) {
  1737. p_identifier->set_datatype(make_native_meta_type(name));
  1738. return;
  1739. }
  1740. if (ScriptServer::is_global_class(name)) {
  1741. p_identifier->set_datatype(make_global_class_meta_type(name));
  1742. return;
  1743. }
  1744. if (GDScriptLanguage::get_singleton()->get_global_map().has(name)) {
  1745. int idx = GDScriptLanguage::get_singleton()->get_global_map()[name];
  1746. Variant constant = GDScriptLanguage::get_singleton()->get_global_array()[idx];
  1747. p_identifier->set_datatype(type_from_variant(constant));
  1748. p_identifier->is_constant = true;
  1749. p_identifier->reduced_value = constant;
  1750. return;
  1751. }
  1752. if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(name)) {
  1753. Variant constant = GDScriptLanguage::get_singleton()->get_named_globals_map()[name];
  1754. p_identifier->set_datatype(type_from_variant(constant));
  1755. p_identifier->is_constant = true;
  1756. p_identifier->reduced_value = constant;
  1757. return;
  1758. }
  1759. // Not found.
  1760. // Check if it's a builtin function.
  1761. if (parser->get_builtin_function(name) < GDScriptFunctions::FUNC_MAX) {
  1762. push_error(vformat(R"(Built-in function "%s" cannot be used as an identifier.)", name), p_identifier);
  1763. } else {
  1764. push_error(vformat(R"(Identifier "%s" not declared in the current scope.)", name), p_identifier);
  1765. }
  1766. GDScriptParser::DataType dummy;
  1767. dummy.kind = GDScriptParser::DataType::VARIANT;
  1768. p_identifier->set_datatype(dummy); // Just so type is set to something.
  1769. }
  1770. void GDScriptAnalyzer::reduce_literal(GDScriptParser::LiteralNode *p_literal) {
  1771. p_literal->reduced_value = p_literal->value;
  1772. p_literal->is_constant = true;
  1773. p_literal->set_datatype(type_from_variant(p_literal->reduced_value));
  1774. }
  1775. void GDScriptAnalyzer::reduce_preload(GDScriptParser::PreloadNode *p_preload) {
  1776. p_preload->is_constant = true;
  1777. p_preload->reduced_value = p_preload->resource;
  1778. p_preload->set_datatype(type_from_variant(p_preload->reduced_value));
  1779. }
  1780. void GDScriptAnalyzer::reduce_self(GDScriptParser::SelfNode *p_self) {
  1781. p_self->is_constant = false;
  1782. p_self->set_datatype(type_from_metatype(parser->current_class->get_datatype()));
  1783. }
  1784. void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscript) {
  1785. if (p_subscript->base->type == GDScriptParser::Node::IDENTIFIER) {
  1786. reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_subscript->base), true);
  1787. } else {
  1788. reduce_expression(p_subscript->base);
  1789. }
  1790. GDScriptParser::DataType result_type;
  1791. // Reduce index first. If it's a constant StringName, use attribute instead.
  1792. if (!p_subscript->is_attribute) {
  1793. if (p_subscript->index == nullptr) {
  1794. return;
  1795. }
  1796. reduce_expression(p_subscript->index);
  1797. if (p_subscript->index->is_constant && p_subscript->index->reduced_value.get_type() == Variant::STRING_NAME) {
  1798. GDScriptParser::IdentifierNode *attribute = parser->alloc_node<GDScriptParser::IdentifierNode>();
  1799. // Copy location for better error message.
  1800. attribute->start_line = p_subscript->index->start_line;
  1801. attribute->end_line = p_subscript->index->end_line;
  1802. attribute->leftmost_column = p_subscript->index->leftmost_column;
  1803. attribute->rightmost_column = p_subscript->index->rightmost_column;
  1804. p_subscript->is_attribute = true;
  1805. p_subscript->attribute = attribute;
  1806. }
  1807. }
  1808. if (p_subscript->is_attribute) {
  1809. if (p_subscript->attribute == nullptr) {
  1810. return;
  1811. }
  1812. if (p_subscript->base->is_constant) {
  1813. // Just try to get it.
  1814. bool valid = false;
  1815. Variant value = p_subscript->base->reduced_value.get_named(p_subscript->attribute->name, &valid);
  1816. if (!valid) {
  1817. push_error(vformat(R"(Cannot get member "%s" from "%s".)", p_subscript->attribute->name, p_subscript->base->reduced_value), p_subscript->index);
  1818. } else {
  1819. p_subscript->is_constant = true;
  1820. p_subscript->reduced_value = value;
  1821. result_type = type_from_variant(value);
  1822. }
  1823. result_type.kind = GDScriptParser::DataType::VARIANT;
  1824. } else {
  1825. GDScriptParser::DataType base_type = p_subscript->base->get_datatype();
  1826. if (base_type.is_variant()) {
  1827. result_type.kind = GDScriptParser::DataType::VARIANT;
  1828. mark_node_unsafe(p_subscript);
  1829. } else {
  1830. reduce_identifier_from_base(p_subscript->attribute, &base_type);
  1831. GDScriptParser::DataType attr_type = p_subscript->attribute->get_datatype();
  1832. if (attr_type.is_set()) {
  1833. result_type = attr_type;
  1834. p_subscript->is_constant = p_subscript->attribute->is_constant;
  1835. p_subscript->reduced_value = p_subscript->attribute->reduced_value;
  1836. } else {
  1837. if (base_type.kind == GDScriptParser::DataType::BUILTIN) {
  1838. push_error(vformat(R"(Cannot find member "%s" in base "%s".)", p_subscript->attribute->name, base_type.to_string()), p_subscript->attribute);
  1839. } else {
  1840. parser->push_warning(p_subscript, GDScriptWarning::UNSAFE_PROPERTY_ACCESS, p_subscript->attribute->name, base_type.to_string());
  1841. }
  1842. result_type.kind = GDScriptParser::DataType::VARIANT;
  1843. }
  1844. }
  1845. }
  1846. } else {
  1847. // Index was already reduced before.
  1848. if (p_subscript->base->is_constant && p_subscript->index->is_constant) {
  1849. // Just try to get it.
  1850. bool valid = false;
  1851. Variant value = p_subscript->base->reduced_value.get(p_subscript->index->reduced_value, &valid);
  1852. if (!valid) {
  1853. push_error(vformat(R"(Cannot get index "%s" from "%s".)", p_subscript->index->reduced_value, p_subscript->base->reduced_value), p_subscript->index);
  1854. } else {
  1855. p_subscript->is_constant = true;
  1856. p_subscript->reduced_value = value;
  1857. result_type = type_from_variant(value);
  1858. }
  1859. result_type.kind = GDScriptParser::DataType::VARIANT;
  1860. } else {
  1861. GDScriptParser::DataType base_type = p_subscript->base->get_datatype();
  1862. GDScriptParser::DataType index_type = p_subscript->index->get_datatype();
  1863. if (base_type.is_variant()) {
  1864. result_type.kind = GDScriptParser::DataType::VARIANT;
  1865. mark_node_unsafe(p_subscript);
  1866. } else {
  1867. if (base_type.kind == GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {
  1868. // Check if indexing is valid.
  1869. bool error = index_type.kind != GDScriptParser::DataType::BUILTIN && base_type.builtin_type != Variant::DICTIONARY;
  1870. if (!error) {
  1871. switch (base_type.builtin_type) {
  1872. // Expect int or real as index.
  1873. case Variant::PACKED_BYTE_ARRAY:
  1874. case Variant::PACKED_COLOR_ARRAY:
  1875. case Variant::PACKED_FLOAT32_ARRAY:
  1876. case Variant::PACKED_FLOAT64_ARRAY:
  1877. case Variant::PACKED_INT32_ARRAY:
  1878. case Variant::PACKED_INT64_ARRAY:
  1879. case Variant::PACKED_STRING_ARRAY:
  1880. case Variant::PACKED_VECTOR2_ARRAY:
  1881. case Variant::PACKED_VECTOR3_ARRAY:
  1882. case Variant::ARRAY:
  1883. case Variant::STRING:
  1884. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT;
  1885. break;
  1886. // Expect String only.
  1887. case Variant::RECT2:
  1888. case Variant::RECT2I:
  1889. case Variant::PLANE:
  1890. case Variant::QUAT:
  1891. case Variant::AABB:
  1892. case Variant::OBJECT:
  1893. error = index_type.builtin_type != Variant::STRING;
  1894. break;
  1895. // Expect String or number.
  1896. case Variant::BASIS:
  1897. case Variant::VECTOR2:
  1898. case Variant::VECTOR2I:
  1899. case Variant::VECTOR3:
  1900. case Variant::VECTOR3I:
  1901. case Variant::TRANSFORM:
  1902. case Variant::TRANSFORM2D:
  1903. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT &&
  1904. index_type.builtin_type != Variant::STRING;
  1905. break;
  1906. // Expect String or int.
  1907. case Variant::COLOR:
  1908. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::STRING;
  1909. break;
  1910. // Don't support indexing, but we will check it later.
  1911. case Variant::_RID:
  1912. case Variant::BOOL:
  1913. case Variant::CALLABLE:
  1914. case Variant::FLOAT:
  1915. case Variant::INT:
  1916. case Variant::NIL:
  1917. case Variant::NODE_PATH:
  1918. case Variant::SIGNAL:
  1919. case Variant::STRING_NAME:
  1920. break;
  1921. // Here for completeness.
  1922. case Variant::DICTIONARY:
  1923. case Variant::VARIANT_MAX:
  1924. break;
  1925. }
  1926. if (error) {
  1927. 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);
  1928. }
  1929. }
  1930. } else if (base_type.kind != GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {
  1931. if (index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME) {
  1932. 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);
  1933. }
  1934. }
  1935. // Check resulting type if possible.
  1936. result_type.builtin_type = Variant::NIL;
  1937. result_type.kind = GDScriptParser::DataType::BUILTIN;
  1938. result_type.type_source = GDScriptParser::DataType::INFERRED;
  1939. switch (base_type.builtin_type) {
  1940. // Can't index at all.
  1941. case Variant::_RID:
  1942. case Variant::BOOL:
  1943. case Variant::CALLABLE:
  1944. case Variant::FLOAT:
  1945. case Variant::INT:
  1946. case Variant::NIL:
  1947. case Variant::NODE_PATH:
  1948. case Variant::SIGNAL:
  1949. case Variant::STRING_NAME:
  1950. result_type.kind = GDScriptParser::DataType::VARIANT;
  1951. push_error(vformat(R"(Cannot use subscript operator on a base of type "%s".)", base_type.to_string()), p_subscript->base);
  1952. break;
  1953. // Return int.
  1954. case Variant::PACKED_BYTE_ARRAY:
  1955. case Variant::PACKED_INT32_ARRAY:
  1956. case Variant::PACKED_INT64_ARRAY:
  1957. case Variant::VECTOR2I:
  1958. case Variant::VECTOR3I:
  1959. result_type.builtin_type = Variant::INT;
  1960. break;
  1961. // Return float.
  1962. case Variant::PACKED_FLOAT32_ARRAY:
  1963. case Variant::PACKED_FLOAT64_ARRAY:
  1964. case Variant::VECTOR2:
  1965. case Variant::VECTOR3:
  1966. case Variant::QUAT:
  1967. result_type.builtin_type = Variant::FLOAT;
  1968. break;
  1969. // Return Color.
  1970. case Variant::PACKED_COLOR_ARRAY:
  1971. result_type.builtin_type = Variant::COLOR;
  1972. break;
  1973. // Return String.
  1974. case Variant::PACKED_STRING_ARRAY:
  1975. case Variant::STRING:
  1976. result_type.builtin_type = Variant::STRING;
  1977. break;
  1978. // Return Vector2.
  1979. case Variant::PACKED_VECTOR2_ARRAY:
  1980. case Variant::TRANSFORM2D:
  1981. case Variant::RECT2:
  1982. result_type.builtin_type = Variant::VECTOR2;
  1983. break;
  1984. // Return Vector2I.
  1985. case Variant::RECT2I:
  1986. result_type.builtin_type = Variant::VECTOR2I;
  1987. break;
  1988. // Return Vector3.
  1989. case Variant::PACKED_VECTOR3_ARRAY:
  1990. case Variant::AABB:
  1991. case Variant::BASIS:
  1992. result_type.builtin_type = Variant::VECTOR3;
  1993. break;
  1994. // Depends on the index.
  1995. case Variant::TRANSFORM:
  1996. case Variant::PLANE:
  1997. case Variant::COLOR:
  1998. case Variant::ARRAY:
  1999. case Variant::DICTIONARY:
  2000. result_type.kind = GDScriptParser::DataType::VARIANT;
  2001. result_type.type_source = GDScriptParser::DataType::UNDETECTED;
  2002. break;
  2003. // Here for completeness.
  2004. case Variant::OBJECT:
  2005. case Variant::VARIANT_MAX:
  2006. break;
  2007. }
  2008. }
  2009. }
  2010. }
  2011. p_subscript->set_datatype(result_type);
  2012. }
  2013. void GDScriptAnalyzer::reduce_ternary_op(GDScriptParser::TernaryOpNode *p_ternary_op) {
  2014. reduce_expression(p_ternary_op->condition);
  2015. reduce_expression(p_ternary_op->true_expr);
  2016. reduce_expression(p_ternary_op->false_expr);
  2017. GDScriptParser::DataType result;
  2018. if (p_ternary_op->condition->is_constant && p_ternary_op->true_expr->is_constant && p_ternary_op->false_expr->is_constant) {
  2019. p_ternary_op->is_constant = true;
  2020. if (p_ternary_op->condition->reduced_value.booleanize()) {
  2021. p_ternary_op->reduced_value = p_ternary_op->true_expr->reduced_value;
  2022. } else {
  2023. p_ternary_op->reduced_value = p_ternary_op->false_expr->reduced_value;
  2024. }
  2025. }
  2026. GDScriptParser::DataType true_type = p_ternary_op->true_expr->get_datatype();
  2027. GDScriptParser::DataType false_type = p_ternary_op->false_expr->get_datatype();
  2028. if (true_type.is_variant() || false_type.is_variant()) {
  2029. result.kind = GDScriptParser::DataType::VARIANT;
  2030. } else {
  2031. result = true_type;
  2032. if (!is_type_compatible(true_type, false_type)) {
  2033. result = false_type;
  2034. if (!is_type_compatible(false_type, true_type)) {
  2035. result.type_source = GDScriptParser::DataType::UNDETECTED;
  2036. result.kind = GDScriptParser::DataType::VARIANT;
  2037. parser->push_warning(p_ternary_op, GDScriptWarning::INCOMPATIBLE_TERNARY);
  2038. }
  2039. }
  2040. }
  2041. p_ternary_op->set_datatype(result);
  2042. }
  2043. void GDScriptAnalyzer::reduce_unary_op(GDScriptParser::UnaryOpNode *p_unary_op) {
  2044. reduce_expression(p_unary_op->operand);
  2045. GDScriptParser::DataType result;
  2046. if (p_unary_op->operand->is_constant) {
  2047. p_unary_op->is_constant = true;
  2048. p_unary_op->reduced_value = Variant::evaluate(p_unary_op->variant_op, p_unary_op->operand->reduced_value, Variant());
  2049. result = type_from_variant(p_unary_op->reduced_value);
  2050. } else if (p_unary_op->operand->get_datatype().is_variant()) {
  2051. result.kind = GDScriptParser::DataType::VARIANT;
  2052. mark_node_unsafe(p_unary_op);
  2053. } else {
  2054. bool valid = false;
  2055. result = get_operation_type(p_unary_op->variant_op, p_unary_op->operand->get_datatype(), p_unary_op->operand->get_datatype(), valid);
  2056. if (!valid) {
  2057. 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);
  2058. }
  2059. }
  2060. p_unary_op->set_datatype(result);
  2061. }
  2062. GDScriptParser::DataType GDScriptAnalyzer::type_from_variant(const Variant &p_value) {
  2063. GDScriptParser::DataType result;
  2064. result.is_constant = true;
  2065. result.kind = GDScriptParser::DataType::BUILTIN;
  2066. result.builtin_type = p_value.get_type();
  2067. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; // Constant has explicit type.
  2068. if (p_value.get_type() == Variant::OBJECT) {
  2069. Object *obj = p_value;
  2070. if (!obj) {
  2071. return GDScriptParser::DataType();
  2072. }
  2073. result.native_type = obj->get_class_name();
  2074. Ref<Script> scr = p_value; // Check if value is a script itself.
  2075. if (scr.is_valid()) {
  2076. result.is_meta_type = true;
  2077. } else {
  2078. result.is_meta_type = false;
  2079. scr = obj->get_script();
  2080. }
  2081. if (scr.is_valid()) {
  2082. result.script_type = scr;
  2083. Ref<GDScript> gds = scr;
  2084. if (gds.is_valid()) {
  2085. result.kind = GDScriptParser::DataType::CLASS;
  2086. Ref<GDScriptParserRef> ref = get_parser_for(gds->get_path());
  2087. ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED);
  2088. result.class_type = ref->get_parser()->head;
  2089. } else {
  2090. result.kind = GDScriptParser::DataType::SCRIPT;
  2091. }
  2092. result.native_type = scr->get_instance_base_type();
  2093. } else {
  2094. result.kind = GDScriptParser::DataType::NATIVE;
  2095. if (result.native_type == GDScriptNativeClass::get_class_static()) {
  2096. result.is_meta_type = true;
  2097. }
  2098. }
  2099. }
  2100. return result;
  2101. }
  2102. GDScriptParser::DataType GDScriptAnalyzer::type_from_metatype(const GDScriptParser::DataType &p_meta_type) const {
  2103. GDScriptParser::DataType result = p_meta_type;
  2104. result.is_meta_type = false;
  2105. result.is_constant = false;
  2106. return result;
  2107. }
  2108. GDScriptParser::DataType GDScriptAnalyzer::type_from_property(const PropertyInfo &p_property) const {
  2109. GDScriptParser::DataType result;
  2110. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2111. if (p_property.type == Variant::NIL && (p_property.usage & PROPERTY_USAGE_NIL_IS_VARIANT)) {
  2112. // Variant
  2113. result.kind = GDScriptParser::DataType::VARIANT;
  2114. return result;
  2115. }
  2116. result.builtin_type = p_property.type;
  2117. if (p_property.type == Variant::OBJECT) {
  2118. result.kind = GDScriptParser::DataType::NATIVE;
  2119. result.native_type = p_property.class_name == StringName() ? "Object" : p_property.class_name;
  2120. } else {
  2121. result.kind = GDScriptParser::DataType::BUILTIN;
  2122. }
  2123. return result;
  2124. }
  2125. 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) {
  2126. r_static = false;
  2127. r_vararg = false;
  2128. r_default_arg_count = 0;
  2129. if (p_base_type.kind == GDScriptParser::DataType::BUILTIN) {
  2130. // Construct a base type to get methods.
  2131. Callable::CallError err;
  2132. Variant dummy = Variant::construct(p_base_type.builtin_type, nullptr, 0, err);
  2133. if (err.error != Callable::CallError::CALL_OK) {
  2134. ERR_FAIL_V_MSG(false, "Could not construct base Variant type.");
  2135. }
  2136. List<MethodInfo> methods;
  2137. dummy.get_method_list(&methods);
  2138. for (const List<MethodInfo>::Element *E = methods.front(); E != nullptr; E = E->next()) {
  2139. if (E->get().name == p_function) {
  2140. return function_signature_from_info(E->get(), r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  2141. }
  2142. }
  2143. return false;
  2144. }
  2145. GDScriptParser::ClassNode *base_class = p_base_type.class_type;
  2146. GDScriptParser::FunctionNode *found_function = nullptr;
  2147. while (found_function == nullptr && base_class != nullptr) {
  2148. if (base_class->has_member(p_function)) {
  2149. if (base_class->get_member(p_function).type != GDScriptParser::ClassNode::Member::FUNCTION) {
  2150. // TODO: If this is Callable it can have a better error message.
  2151. push_error(vformat(R"(Member "%s" is not a function.)", p_function), p_source);
  2152. return false;
  2153. }
  2154. found_function = base_class->get_member(p_function).function;
  2155. }
  2156. base_class = base_class->base_type.class_type;
  2157. }
  2158. if (found_function != nullptr) {
  2159. r_static = found_function->is_static;
  2160. for (int i = 0; i < found_function->parameters.size(); i++) {
  2161. r_par_types.push_back(found_function->parameters[i]->get_datatype());
  2162. if (found_function->parameters[i]->default_value != nullptr) {
  2163. r_default_arg_count++;
  2164. }
  2165. }
  2166. r_return_type = found_function->get_datatype();
  2167. r_return_type.is_coroutine = found_function->is_coroutine;
  2168. return true;
  2169. }
  2170. // TODO: Check here the "new" function in GDScript class when metatype, as it needs to look the constructor.
  2171. Ref<Script> base_script = p_base_type.script_type;
  2172. while (base_script.is_valid() && base_script->is_valid()) {
  2173. MethodInfo info = base_script->get_method_info(p_function);
  2174. if (!(info == MethodInfo())) {
  2175. return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  2176. }
  2177. base_script = base_script->get_base_script();
  2178. }
  2179. // If the base is a script, it might be trying to access members of the Script class itself.
  2180. if (p_base_type.is_meta_type && !(p_function == "new") && (p_base_type.kind == GDScriptParser::DataType::SCRIPT || p_base_type.kind == GDScriptParser::DataType::CLASS)) {
  2181. MethodInfo info;
  2182. StringName script_class = p_base_type.kind == GDScriptParser::DataType::SCRIPT ? p_base_type.script_type->get_class_name() : StringName(GDScript::get_class_static());
  2183. if (ClassDB::get_method_info(script_class, p_function, &info)) {
  2184. return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  2185. }
  2186. }
  2187. StringName base_native = p_base_type.native_type;
  2188. if (base_native == StringName()) {
  2189. // Empty native class, might happen in some Script implementations.
  2190. // Just ignore it.
  2191. return false;
  2192. }
  2193. #ifdef DEBUG_ENABLED
  2194. if (!class_exists(base_native)) {
  2195. ERR_FAIL_V_MSG(false, vformat("Native class %s used in script doesn't exist or isn't exposed.", base_native));
  2196. }
  2197. #endif
  2198. StringName real_native = get_real_class_name(base_native);
  2199. MethodInfo info;
  2200. if (ClassDB::get_method_info(real_native, p_function, &info)) {
  2201. return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  2202. }
  2203. return false;
  2204. }
  2205. 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) {
  2206. r_return_type = type_from_property(p_info.return_val);
  2207. r_default_arg_count = p_info.default_arguments.size();
  2208. r_vararg = (p_info.flags & METHOD_FLAG_VARARG) != 0;
  2209. for (const List<PropertyInfo>::Element *E = p_info.arguments.front(); E != nullptr; E = E->next()) {
  2210. r_par_types.push_back(type_from_property(E->get()));
  2211. }
  2212. return true;
  2213. }
  2214. bool GDScriptAnalyzer::validate_call_arg(const MethodInfo &p_method, const GDScriptParser::CallNode *p_call) {
  2215. List<GDScriptParser::DataType> arg_types;
  2216. for (const List<PropertyInfo>::Element *E = p_method.arguments.front(); E != nullptr; E = E->next()) {
  2217. arg_types.push_back(type_from_property(E->get()));
  2218. }
  2219. return validate_call_arg(arg_types, p_method.default_arguments.size(), (p_method.flags & METHOD_FLAG_VARARG) != 0, p_call);
  2220. }
  2221. 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) {
  2222. bool valid = true;
  2223. if (p_call->arguments.size() < p_par_types.size() - p_default_args_count) {
  2224. 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);
  2225. valid = false;
  2226. }
  2227. if (!p_is_vararg && p_call->arguments.size() > p_par_types.size()) {
  2228. 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()]);
  2229. valid = false;
  2230. }
  2231. for (int i = 0; i < p_call->arguments.size(); i++) {
  2232. if (i >= p_par_types.size()) {
  2233. // Already on vararg place.
  2234. break;
  2235. }
  2236. GDScriptParser::DataType par_type = p_par_types[i];
  2237. GDScriptParser::DataType arg_type = p_call->arguments[i]->get_datatype();
  2238. if (arg_type.is_variant()) {
  2239. // Argument can be anything, so this is unsafe.
  2240. mark_node_unsafe(p_call->arguments[i]);
  2241. } else if (!is_type_compatible(par_type, arg_type, true)) {
  2242. // Supertypes are acceptable for dynamic compliance, but it's unsafe.
  2243. mark_node_unsafe(p_call);
  2244. if (!is_type_compatible(arg_type, par_type)) {
  2245. push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be %s but is %s.)*",
  2246. p_call->function_name, i + 1, par_type.to_string(), arg_type.to_string()),
  2247. p_call->arguments[i]);
  2248. valid = false;
  2249. }
  2250. } else {
  2251. 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) {
  2252. parser->push_warning(p_call, GDScriptWarning::NARROWING_CONVERSION, p_call->function_name);
  2253. }
  2254. }
  2255. }
  2256. return valid;
  2257. }
  2258. bool GDScriptAnalyzer::is_shadowing(GDScriptParser::IdentifierNode *p_local, const String &p_context) {
  2259. const StringName &name = p_local->name;
  2260. GDScriptParser::DataType base = parser->current_class->get_datatype();
  2261. GDScriptParser::ClassNode *base_class = base.class_type;
  2262. while (base_class != nullptr) {
  2263. if (base_class->has_member(name)) {
  2264. 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()));
  2265. return true;
  2266. }
  2267. base_class = base_class->base_type.class_type;
  2268. }
  2269. StringName base_native = base.native_type;
  2270. ERR_FAIL_COND_V_MSG(!class_exists(base_native), false, "Non-existent native base class.");
  2271. StringName parent = base_native;
  2272. while (parent != StringName()) {
  2273. StringName real_class_name = get_real_class_name(parent);
  2274. if (ClassDB::has_method(real_class_name, name, true)) {
  2275. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "method", parent);
  2276. return true;
  2277. } else if (ClassDB::has_signal(real_class_name, name, true)) {
  2278. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "signal", parent);
  2279. return true;
  2280. } else if (ClassDB::has_property(real_class_name, name, true)) {
  2281. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "property", parent);
  2282. return true;
  2283. } else if (ClassDB::has_integer_constant(real_class_name, name, true)) {
  2284. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "constant", parent);
  2285. return true;
  2286. } else if (ClassDB::has_enum(real_class_name, name, true)) {
  2287. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "enum", parent);
  2288. return true;
  2289. }
  2290. parent = ClassDB::get_parent_class(real_class_name);
  2291. }
  2292. return false;
  2293. }
  2294. GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, const GDScriptParser::DataType &p_b, bool &r_valid) {
  2295. // This function creates dummy variant values and apply the operation to those. Less error-prone than keeping a table of valid operations.
  2296. GDScriptParser::DataType result;
  2297. result.kind = GDScriptParser::DataType::VARIANT;
  2298. Variant::Type a_type = p_a.builtin_type;
  2299. Variant::Type b_type = p_b.builtin_type;
  2300. Variant a;
  2301. REF a_ref;
  2302. if (a_type == Variant::OBJECT) {
  2303. a_ref.instance();
  2304. a = a_ref;
  2305. } else {
  2306. Callable::CallError err;
  2307. a = Variant::construct(a_type, nullptr, 0, err);
  2308. if (err.error != Callable::CallError::CALL_OK) {
  2309. r_valid = false;
  2310. ERR_FAIL_V_MSG(result, vformat("Could not construct value of type %s", Variant::get_type_name(a_type)));
  2311. }
  2312. }
  2313. Variant b;
  2314. REF b_ref;
  2315. if (b_type == Variant::OBJECT) {
  2316. b_ref.instance();
  2317. b = b_ref;
  2318. } else {
  2319. Callable::CallError err;
  2320. b = Variant::construct(b_type, nullptr, 0, err);
  2321. if (err.error != Callable::CallError::CALL_OK) {
  2322. r_valid = false;
  2323. ERR_FAIL_V_MSG(result, vformat("Could not construct value of type %s", Variant::get_type_name(b_type)));
  2324. }
  2325. }
  2326. // Avoid division by zero.
  2327. switch (b_type) {
  2328. case Variant::INT:
  2329. b = 1;
  2330. break;
  2331. case Variant::FLOAT:
  2332. b = 1.0;
  2333. break;
  2334. case Variant::VECTOR2:
  2335. b = Vector2(1.0, 1.0);
  2336. break;
  2337. case Variant::VECTOR2I:
  2338. b = Vector2i(1, 1);
  2339. break;
  2340. case Variant::VECTOR3:
  2341. b = Vector3(1.0, 1.0, 1.0);
  2342. break;
  2343. case Variant::VECTOR3I:
  2344. b = Vector3i(1, 1, 1);
  2345. break;
  2346. case Variant::COLOR:
  2347. b = Color(1.0, 1.0, 1.0, 1.0);
  2348. break;
  2349. default:
  2350. // No change needed.
  2351. break;
  2352. }
  2353. // Avoid error in formatting operator (%) where it doesn't find a placeholder.
  2354. if (a_type == Variant::STRING) {
  2355. a = String("%s");
  2356. }
  2357. Variant ret;
  2358. Variant::evaluate(p_operation, a, b, ret, r_valid);
  2359. if (r_valid) {
  2360. return type_from_variant(ret);
  2361. }
  2362. return result;
  2363. }
  2364. // TODO: Add safe/unsafe return variable (for variant cases)
  2365. bool GDScriptAnalyzer::is_type_compatible(const GDScriptParser::DataType &p_target, const GDScriptParser::DataType &p_source, bool p_allow_implicit_conversion) const {
  2366. // These return "true" so it doesn't affect users negatively.
  2367. ERR_FAIL_COND_V_MSG(!p_target.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset target type");
  2368. ERR_FAIL_COND_V_MSG(!p_source.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset value type");
  2369. if (p_target.kind == GDScriptParser::DataType::VARIANT) {
  2370. // Variant can receive anything.
  2371. return true;
  2372. }
  2373. if (p_source.kind == GDScriptParser::DataType::VARIANT) {
  2374. // TODO: This is acceptable but unsafe. Make sure unsafe line is set.
  2375. return true;
  2376. }
  2377. if (p_target.kind == GDScriptParser::DataType::BUILTIN) {
  2378. bool valid = p_source.kind == GDScriptParser::DataType::BUILTIN && p_target.builtin_type == p_source.builtin_type;
  2379. if (!valid && p_allow_implicit_conversion) {
  2380. valid = Variant::can_convert_strict(p_source.builtin_type, p_target.builtin_type);
  2381. }
  2382. if (!valid && p_target.builtin_type == Variant::INT && p_source.kind == GDScriptParser::DataType::ENUM_VALUE) {
  2383. // Enum value is also integer.
  2384. valid = true;
  2385. }
  2386. return valid;
  2387. }
  2388. if (p_target.kind == GDScriptParser::DataType::ENUM) {
  2389. if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::INT) {
  2390. return true;
  2391. }
  2392. if (p_source.kind == GDScriptParser::DataType::ENUM_VALUE) {
  2393. if (p_source.native_type == p_target.native_type && p_target.enum_values.has(p_source.enum_type)) {
  2394. return true;
  2395. }
  2396. }
  2397. return false;
  2398. }
  2399. // From here on the target type is an object, so we have to test polymorphism.
  2400. if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::NIL) {
  2401. // null is acceptable in object.
  2402. return true;
  2403. }
  2404. StringName src_native;
  2405. Ref<Script> src_script;
  2406. const GDScriptParser::ClassNode *src_class = nullptr;
  2407. switch (p_source.kind) {
  2408. case GDScriptParser::DataType::NATIVE:
  2409. if (p_target.kind != GDScriptParser::DataType::NATIVE) {
  2410. // Non-native class cannot be supertype of native.
  2411. return false;
  2412. }
  2413. if (p_source.is_meta_type) {
  2414. src_native = GDScriptNativeClass::get_class_static();
  2415. } else {
  2416. src_native = p_source.native_type;
  2417. }
  2418. break;
  2419. case GDScriptParser::DataType::SCRIPT:
  2420. if (p_target.kind == GDScriptParser::DataType::CLASS) {
  2421. // A script type cannot be a subtype of a GDScript class.
  2422. return false;
  2423. }
  2424. if (p_source.is_meta_type) {
  2425. src_native = p_source.script_type->get_class_name();
  2426. } else {
  2427. src_script = p_source.script_type;
  2428. src_native = src_script->get_instance_base_type();
  2429. }
  2430. break;
  2431. case GDScriptParser::DataType::CLASS:
  2432. if (p_source.is_meta_type) {
  2433. src_native = GDScript::get_class_static();
  2434. } else {
  2435. src_class = p_source.class_type;
  2436. const GDScriptParser::ClassNode *base = src_class;
  2437. while (base->base_type.kind == GDScriptParser::DataType::CLASS) {
  2438. base = base->base_type.class_type;
  2439. }
  2440. src_native = base->base_type.native_type;
  2441. src_script = base->base_type.script_type;
  2442. }
  2443. break;
  2444. case GDScriptParser::DataType::VARIANT:
  2445. case GDScriptParser::DataType::BUILTIN:
  2446. case GDScriptParser::DataType::ENUM:
  2447. case GDScriptParser::DataType::ENUM_VALUE:
  2448. case GDScriptParser::DataType::UNRESOLVED:
  2449. break; // Already solved before.
  2450. }
  2451. // Get underscore-prefixed version for some classes.
  2452. src_native = get_real_class_name(src_native);
  2453. switch (p_target.kind) {
  2454. case GDScriptParser::DataType::NATIVE: {
  2455. if (p_target.is_meta_type) {
  2456. return ClassDB::is_parent_class(src_native, GDScriptNativeClass::get_class_static());
  2457. }
  2458. StringName tgt_native = get_real_class_name(p_target.native_type);
  2459. return ClassDB::is_parent_class(src_native, tgt_native);
  2460. }
  2461. case GDScriptParser::DataType::SCRIPT:
  2462. if (p_target.is_meta_type) {
  2463. return ClassDB::is_parent_class(src_native, p_target.script_type->get_class_name());
  2464. }
  2465. while (src_script.is_valid()) {
  2466. if (src_script == p_target.script_type) {
  2467. return true;
  2468. }
  2469. src_script = src_script->get_base_script();
  2470. }
  2471. return false;
  2472. case GDScriptParser::DataType::CLASS:
  2473. if (p_target.is_meta_type) {
  2474. return ClassDB::is_parent_class(src_native, GDScript::get_class_static());
  2475. }
  2476. while (src_class != nullptr) {
  2477. if (src_class->fqcn == p_target.class_type->fqcn) {
  2478. return true;
  2479. }
  2480. src_class = src_class->base_type.class_type;
  2481. }
  2482. return false;
  2483. case GDScriptParser::DataType::VARIANT:
  2484. case GDScriptParser::DataType::BUILTIN:
  2485. case GDScriptParser::DataType::ENUM:
  2486. case GDScriptParser::DataType::ENUM_VALUE:
  2487. case GDScriptParser::DataType::UNRESOLVED:
  2488. break; // Already solved before.
  2489. }
  2490. return false;
  2491. }
  2492. void GDScriptAnalyzer::push_error(const String &p_message, const GDScriptParser::Node *p_origin) {
  2493. mark_node_unsafe(p_origin);
  2494. parser->push_error(p_message, p_origin);
  2495. }
  2496. void GDScriptAnalyzer::mark_node_unsafe(const GDScriptParser::Node *p_node) {
  2497. for (int i = p_node->start_line; i <= p_node->end_line; i++) {
  2498. parser->unsafe_lines.insert(i);
  2499. }
  2500. }
  2501. bool GDScriptAnalyzer::class_exists(const StringName &p_class) {
  2502. StringName real_name = get_real_class_name(p_class);
  2503. return ClassDB::class_exists(real_name) && ClassDB::is_class_exposed(real_name);
  2504. }
  2505. Ref<GDScriptParserRef> GDScriptAnalyzer::get_parser_for(const String &p_path) {
  2506. Ref<GDScriptParserRef> ref;
  2507. if (depended_parsers.has(p_path)) {
  2508. ref = depended_parsers[p_path];
  2509. } else {
  2510. Error err = OK;
  2511. ref = GDScriptCache::get_parser(p_path, GDScriptParserRef::EMPTY, err);
  2512. depended_parsers[p_path] = ref;
  2513. }
  2514. return ref;
  2515. }
  2516. Error GDScriptAnalyzer::resolve_inheritance() {
  2517. return resolve_inheritance(parser->head);
  2518. }
  2519. Error GDScriptAnalyzer::resolve_interface() {
  2520. resolve_class_interface(parser->head);
  2521. return parser->errors.empty() ? OK : ERR_PARSE_ERROR;
  2522. }
  2523. Error GDScriptAnalyzer::resolve_body() {
  2524. resolve_class_body(parser->head);
  2525. return parser->errors.empty() ? OK : ERR_PARSE_ERROR;
  2526. }
  2527. Error GDScriptAnalyzer::resolve_program() {
  2528. resolve_class_interface(parser->head);
  2529. resolve_class_body(parser->head);
  2530. List<String> parser_keys;
  2531. depended_parsers.get_key_list(&parser_keys);
  2532. for (const List<String>::Element *E = parser_keys.front(); E != nullptr; E = E->next()) {
  2533. depended_parsers[E->get()]->raise_status(GDScriptParserRef::FULLY_SOLVED);
  2534. }
  2535. depended_parsers.clear();
  2536. return parser->errors.empty() ? OK : ERR_PARSE_ERROR;
  2537. }
  2538. Error GDScriptAnalyzer::analyze() {
  2539. parser->errors.clear();
  2540. Error err = resolve_inheritance(parser->head);
  2541. if (err) {
  2542. return err;
  2543. }
  2544. return resolve_program();
  2545. }
  2546. GDScriptAnalyzer::GDScriptAnalyzer(GDScriptParser *p_parser) {
  2547. parser = p_parser;
  2548. }