gdscript_analyzer.cpp 131 KB

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