gdscript_analyzer.cpp 131 KB

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