gdscript_analyzer.cpp 149 KB

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