gdscript_analyzer.cpp 146 KB

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