gdscript_analyzer.cpp 127 KB

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