gdscript_analyzer.cpp 149 KB

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