gdscript_analyzer.cpp 146 KB

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