gdscript_analyzer.cpp 146 KB

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