gdscript_analyzer.cpp 138 KB

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