gdscript_compiler.cpp 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636
  1. /*************************************************************************/
  2. /* gdscript_compiler.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 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_compiler.h"
  31. #include "gdscript.h"
  32. #include "gdscript_byte_codegen.h"
  33. #include "gdscript_cache.h"
  34. #include "gdscript_utility_functions.h"
  35. #include "core/config/project_settings.h"
  36. bool GDScriptCompiler::_is_class_member_property(CodeGen &codegen, const StringName &p_name) {
  37. if (codegen.function_node && codegen.function_node->is_static) {
  38. return false;
  39. }
  40. if (codegen.locals.has(p_name)) {
  41. return false; //shadowed
  42. }
  43. return _is_class_member_property(codegen.script, p_name);
  44. }
  45. bool GDScriptCompiler::_is_class_member_property(GDScript *owner, const StringName &p_name) {
  46. GDScript *scr = owner;
  47. GDScriptNativeClass *nc = nullptr;
  48. while (scr) {
  49. if (scr->native.is_valid()) {
  50. nc = scr->native.ptr();
  51. }
  52. scr = scr->_base;
  53. }
  54. ERR_FAIL_COND_V(!nc, false);
  55. return ClassDB::has_property(nc->get_name(), p_name);
  56. }
  57. void GDScriptCompiler::_set_error(const String &p_error, const GDScriptParser::Node *p_node) {
  58. if (!error.is_empty()) {
  59. return;
  60. }
  61. error = p_error;
  62. if (p_node) {
  63. err_line = p_node->start_line;
  64. err_column = p_node->leftmost_column;
  65. } else {
  66. err_line = 0;
  67. err_column = 0;
  68. }
  69. }
  70. GDScriptDataType GDScriptCompiler::_gdtype_from_datatype(const GDScriptParser::DataType &p_datatype, GDScript *p_owner) const {
  71. if (!p_datatype.is_set() || !p_datatype.is_hard_type()) {
  72. return GDScriptDataType();
  73. }
  74. GDScriptDataType result;
  75. result.has_type = true;
  76. switch (p_datatype.kind) {
  77. case GDScriptParser::DataType::VARIANT: {
  78. result.has_type = false;
  79. } break;
  80. case GDScriptParser::DataType::BUILTIN: {
  81. result.kind = GDScriptDataType::BUILTIN;
  82. result.builtin_type = p_datatype.builtin_type;
  83. } break;
  84. case GDScriptParser::DataType::NATIVE: {
  85. result.kind = GDScriptDataType::NATIVE;
  86. result.native_type = p_datatype.native_type;
  87. result.builtin_type = p_datatype.builtin_type;
  88. } break;
  89. case GDScriptParser::DataType::SCRIPT: {
  90. result.kind = GDScriptDataType::SCRIPT;
  91. result.script_type_ref = Ref<Script>(p_datatype.script_type);
  92. result.script_type = result.script_type_ref.ptr();
  93. result.native_type = result.script_type->get_instance_base_type();
  94. } break;
  95. case GDScriptParser::DataType::CLASS: {
  96. // Locate class by constructing the path to it and following that path
  97. GDScriptParser::ClassNode *class_type = p_datatype.class_type;
  98. if (class_type) {
  99. const bool is_inner_by_path = (!main_script->path.is_empty()) && (class_type->fqcn.split("::")[0] == main_script->path);
  100. const bool is_inner_by_name = (!main_script->name.is_empty()) && (class_type->fqcn.split("::")[0] == main_script->name);
  101. if (is_inner_by_path || is_inner_by_name) {
  102. // Local class.
  103. List<StringName> names;
  104. while (class_type->outer) {
  105. names.push_back(class_type->identifier->name);
  106. class_type = class_type->outer;
  107. }
  108. Ref<GDScript> script = Ref<GDScript>(main_script);
  109. while (names.back()) {
  110. if (!script->subclasses.has(names.back()->get())) {
  111. ERR_PRINT("Parser bug: Cannot locate datatype class.");
  112. result.has_type = false;
  113. return GDScriptDataType();
  114. }
  115. script = script->subclasses[names.back()->get()];
  116. names.pop_back();
  117. }
  118. result.kind = GDScriptDataType::GDSCRIPT;
  119. result.script_type = script.ptr();
  120. result.native_type = script->get_instance_base_type();
  121. } else {
  122. result.kind = GDScriptDataType::GDSCRIPT;
  123. result.script_type_ref = GDScriptCache::get_shallow_script(p_datatype.script_path, main_script->path);
  124. result.script_type = result.script_type_ref.ptr();
  125. result.native_type = p_datatype.native_type;
  126. }
  127. }
  128. } break;
  129. case GDScriptParser::DataType::ENUM:
  130. result.has_type = true;
  131. result.kind = GDScriptDataType::BUILTIN;
  132. if (p_datatype.is_meta_type) {
  133. result.builtin_type = Variant::DICTIONARY;
  134. } else {
  135. result.builtin_type = Variant::INT;
  136. }
  137. break;
  138. case GDScriptParser::DataType::UNRESOLVED: {
  139. ERR_PRINT("Parser bug: converting unresolved type.");
  140. return GDScriptDataType();
  141. }
  142. }
  143. if (p_datatype.has_container_element_type()) {
  144. result.set_container_element_type(_gdtype_from_datatype(p_datatype.get_container_element_type()));
  145. }
  146. // Only hold strong reference to the script if it's not the owner of the
  147. // element qualified with this type, to avoid cyclic references (leaks).
  148. if (result.script_type && result.script_type == p_owner) {
  149. result.script_type_ref = Ref<Script>();
  150. }
  151. return result;
  152. }
  153. static bool _is_exact_type(const PropertyInfo &p_par_type, const GDScriptDataType &p_arg_type) {
  154. if (!p_arg_type.has_type) {
  155. return false;
  156. }
  157. if (p_par_type.type == Variant::NIL) {
  158. return false;
  159. }
  160. if (p_par_type.type == Variant::OBJECT) {
  161. if (p_arg_type.kind == GDScriptDataType::BUILTIN) {
  162. return false;
  163. }
  164. StringName class_name;
  165. if (p_arg_type.kind == GDScriptDataType::NATIVE) {
  166. class_name = p_arg_type.native_type;
  167. } else {
  168. class_name = p_arg_type.native_type == StringName() ? p_arg_type.script_type->get_instance_base_type() : p_arg_type.native_type;
  169. }
  170. return p_par_type.class_name == class_name || ClassDB::is_parent_class(class_name, p_par_type.class_name);
  171. } else {
  172. if (p_arg_type.kind != GDScriptDataType::BUILTIN) {
  173. return false;
  174. }
  175. return p_par_type.type == p_arg_type.builtin_type;
  176. }
  177. }
  178. static bool _have_exact_arguments(const MethodBind *p_method, const Vector<GDScriptCodeGenerator::Address> &p_arguments) {
  179. if (p_method->get_argument_count() != p_arguments.size()) {
  180. // ptrcall won't work with default arguments.
  181. return false;
  182. }
  183. MethodInfo info;
  184. ClassDB::get_method_info(p_method->get_instance_class(), p_method->get_name(), &info);
  185. for (int i = 0; i < p_arguments.size(); i++) {
  186. const PropertyInfo &prop = info.arguments[i];
  187. if (!_is_exact_type(prop, p_arguments[i].type)) {
  188. return false;
  189. }
  190. }
  191. return true;
  192. }
  193. GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &codegen, Error &r_error, const GDScriptParser::ExpressionNode *p_expression, bool p_root, bool p_initializer, const GDScriptCodeGenerator::Address &p_index_addr) {
  194. if (p_expression->is_constant) {
  195. return codegen.add_constant(p_expression->reduced_value);
  196. }
  197. GDScriptCodeGenerator *gen = codegen.generator;
  198. switch (p_expression->type) {
  199. case GDScriptParser::Node::IDENTIFIER: {
  200. // Look for identifiers in current scope.
  201. const GDScriptParser::IdentifierNode *in = static_cast<const GDScriptParser::IdentifierNode *>(p_expression);
  202. StringName identifier = in->name;
  203. // Try function parameters.
  204. if (codegen.parameters.has(identifier)) {
  205. return codegen.parameters[identifier];
  206. }
  207. // Try local variables and constants.
  208. if (!p_initializer && codegen.locals.has(identifier)) {
  209. return codegen.locals[identifier];
  210. }
  211. // Try class members.
  212. if (_is_class_member_property(codegen, identifier)) {
  213. // Get property.
  214. GDScriptCodeGenerator::Address temp = codegen.add_temporary(); // TODO: Could get the type of the class member here.
  215. gen->write_get_member(temp, identifier);
  216. return temp;
  217. }
  218. // Try members.
  219. if (!codegen.function_node || !codegen.function_node->is_static) {
  220. // Try member variables.
  221. if (codegen.script->member_indices.has(identifier)) {
  222. if (codegen.script->member_indices[identifier].getter != StringName() && codegen.script->member_indices[identifier].getter != codegen.function_name) {
  223. // Perform getter.
  224. GDScriptCodeGenerator::Address temp = codegen.add_temporary();
  225. Vector<GDScriptCodeGenerator::Address> args; // No argument needed.
  226. gen->write_call_self(temp, codegen.script->member_indices[identifier].getter, args);
  227. return temp;
  228. } else {
  229. // No getter or inside getter: direct member access.,
  230. int idx = codegen.script->member_indices[identifier].index;
  231. return GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::MEMBER, idx, codegen.script->get_member_type(identifier));
  232. }
  233. }
  234. }
  235. // Try class constants.
  236. {
  237. GDScript *owner = codegen.script;
  238. while (owner) {
  239. GDScript *scr = owner;
  240. GDScriptNativeClass *nc = nullptr;
  241. while (scr) {
  242. if (scr->constants.has(identifier)) {
  243. return codegen.add_constant(scr->constants[identifier]); // TODO: Get type here.
  244. }
  245. if (scr->native.is_valid()) {
  246. nc = scr->native.ptr();
  247. }
  248. scr = scr->_base;
  249. }
  250. // Class C++ integer constant.
  251. if (nc) {
  252. bool success = false;
  253. int constant = ClassDB::get_integer_constant(nc->get_name(), identifier, &success);
  254. if (success) {
  255. return codegen.add_constant(constant);
  256. }
  257. }
  258. owner = owner->_owner;
  259. }
  260. }
  261. // Try signals and methods (can be made callables).
  262. {
  263. if (codegen.class_node->members_indices.has(identifier)) {
  264. const GDScriptParser::ClassNode::Member &member = codegen.class_node->members[codegen.class_node->members_indices[identifier]];
  265. if (member.type == GDScriptParser::ClassNode::Member::FUNCTION || member.type == GDScriptParser::ClassNode::Member::SIGNAL) {
  266. // Get like it was a property.
  267. GDScriptCodeGenerator::Address temp = codegen.add_temporary(); // TODO: Get type here.
  268. GDScriptCodeGenerator::Address self(GDScriptCodeGenerator::Address::SELF);
  269. gen->write_get_named(temp, identifier, self);
  270. return temp;
  271. }
  272. }
  273. // Try in native base.
  274. GDScript *scr = codegen.script;
  275. GDScriptNativeClass *nc = nullptr;
  276. while (scr) {
  277. if (scr->native.is_valid()) {
  278. nc = scr->native.ptr();
  279. }
  280. scr = scr->_base;
  281. }
  282. if (nc && (ClassDB::has_signal(nc->get_name(), identifier) || ClassDB::has_method(nc->get_name(), identifier))) {
  283. // Get like it was a property.
  284. GDScriptCodeGenerator::Address temp = codegen.add_temporary(); // TODO: Get type here.
  285. GDScriptCodeGenerator::Address self(GDScriptCodeGenerator::Address::SELF);
  286. gen->write_get_named(temp, identifier, self);
  287. return temp;
  288. }
  289. }
  290. // Try globals.
  291. if (GDScriptLanguage::get_singleton()->get_global_map().has(identifier)) {
  292. // If it's an autoload singleton, we postpone to load it at runtime.
  293. // This is so one autoload doesn't try to load another before it's compiled.
  294. OrderedHashMap<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
  295. if (autoloads.has(identifier) && autoloads[identifier].is_singleton) {
  296. GDScriptCodeGenerator::Address global = codegen.add_temporary(_gdtype_from_datatype(in->get_datatype()));
  297. int idx = GDScriptLanguage::get_singleton()->get_global_map()[identifier];
  298. gen->write_store_global(global, idx);
  299. return global;
  300. } else {
  301. int idx = GDScriptLanguage::get_singleton()->get_global_map()[identifier];
  302. Variant global = GDScriptLanguage::get_singleton()->get_global_array()[idx];
  303. return codegen.add_constant(global);
  304. }
  305. }
  306. // Try global classes.
  307. if (ScriptServer::is_global_class(identifier)) {
  308. const GDScriptParser::ClassNode *class_node = codegen.class_node;
  309. while (class_node->outer) {
  310. class_node = class_node->outer;
  311. }
  312. RES res;
  313. if (class_node->identifier && class_node->identifier->name == identifier) {
  314. res = Ref<GDScript>(main_script);
  315. } else {
  316. res = ResourceLoader::load(ScriptServer::get_global_class_path(identifier));
  317. if (res.is_null()) {
  318. _set_error("Can't load global class " + String(identifier) + ", cyclic reference?", p_expression);
  319. r_error = ERR_COMPILATION_FAILED;
  320. return GDScriptCodeGenerator::Address();
  321. }
  322. }
  323. return codegen.add_constant(res);
  324. }
  325. #ifdef TOOLS_ENABLED
  326. if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(identifier)) {
  327. GDScriptCodeGenerator::Address global = codegen.add_temporary(); // TODO: Get type.
  328. gen->write_store_named_global(global, identifier);
  329. return global;
  330. }
  331. #endif
  332. // Not found, error.
  333. _set_error("Identifier not found: " + String(identifier), p_expression);
  334. r_error = ERR_COMPILATION_FAILED;
  335. return GDScriptCodeGenerator::Address();
  336. } break;
  337. case GDScriptParser::Node::LITERAL: {
  338. // Return constant.
  339. const GDScriptParser::LiteralNode *cn = static_cast<const GDScriptParser::LiteralNode *>(p_expression);
  340. return codegen.add_constant(cn->value);
  341. } break;
  342. case GDScriptParser::Node::SELF: {
  343. //return constant
  344. if (codegen.function_node && codegen.function_node->is_static) {
  345. _set_error("'self' not present in static function!", p_expression);
  346. r_error = ERR_COMPILATION_FAILED;
  347. return GDScriptCodeGenerator::Address();
  348. }
  349. return GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::SELF);
  350. } break;
  351. case GDScriptParser::Node::ARRAY: {
  352. const GDScriptParser::ArrayNode *an = static_cast<const GDScriptParser::ArrayNode *>(p_expression);
  353. Vector<GDScriptCodeGenerator::Address> values;
  354. // Create the result temporary first since it's the last to be killed.
  355. GDScriptDataType array_type = _gdtype_from_datatype(an->get_datatype());
  356. GDScriptCodeGenerator::Address result = codegen.add_temporary(array_type);
  357. for (int i = 0; i < an->elements.size(); i++) {
  358. GDScriptCodeGenerator::Address val = _parse_expression(codegen, r_error, an->elements[i]);
  359. if (r_error) {
  360. return GDScriptCodeGenerator::Address();
  361. }
  362. values.push_back(val);
  363. }
  364. if (array_type.has_container_element_type()) {
  365. gen->write_construct_typed_array(result, array_type.get_container_element_type(), values);
  366. } else {
  367. gen->write_construct_array(result, values);
  368. }
  369. for (int i = 0; i < values.size(); i++) {
  370. if (values[i].mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  371. gen->pop_temporary();
  372. }
  373. }
  374. return result;
  375. } break;
  376. case GDScriptParser::Node::DICTIONARY: {
  377. const GDScriptParser::DictionaryNode *dn = static_cast<const GDScriptParser::DictionaryNode *>(p_expression);
  378. Vector<GDScriptCodeGenerator::Address> elements;
  379. // Create the result temporary first since it's the last to be killed.
  380. GDScriptDataType dict_type;
  381. dict_type.has_type = true;
  382. dict_type.kind = GDScriptDataType::BUILTIN;
  383. dict_type.builtin_type = Variant::DICTIONARY;
  384. GDScriptCodeGenerator::Address result = codegen.add_temporary(dict_type);
  385. for (int i = 0; i < dn->elements.size(); i++) {
  386. // Key.
  387. GDScriptCodeGenerator::Address element;
  388. switch (dn->style) {
  389. case GDScriptParser::DictionaryNode::PYTHON_DICT:
  390. // Python-style: key is any expression.
  391. element = _parse_expression(codegen, r_error, dn->elements[i].key);
  392. if (r_error) {
  393. return GDScriptCodeGenerator::Address();
  394. }
  395. break;
  396. case GDScriptParser::DictionaryNode::LUA_TABLE:
  397. // Lua-style: key is an identifier interpreted as StringName.
  398. StringName key = dn->elements[i].key->reduced_value.operator StringName();
  399. element = codegen.add_constant(key);
  400. break;
  401. }
  402. elements.push_back(element);
  403. element = _parse_expression(codegen, r_error, dn->elements[i].value);
  404. if (r_error) {
  405. return GDScriptCodeGenerator::Address();
  406. }
  407. elements.push_back(element);
  408. }
  409. gen->write_construct_dictionary(result, elements);
  410. for (int i = 0; i < elements.size(); i++) {
  411. if (elements[i].mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  412. gen->pop_temporary();
  413. }
  414. }
  415. return result;
  416. } break;
  417. case GDScriptParser::Node::CAST: {
  418. const GDScriptParser::CastNode *cn = static_cast<const GDScriptParser::CastNode *>(p_expression);
  419. GDScriptParser::DataType og_cast_type = cn->cast_type->get_datatype();
  420. GDScriptDataType cast_type = _gdtype_from_datatype(og_cast_type);
  421. if (og_cast_type.kind == GDScriptParser::DataType::ENUM) {
  422. // Enum types are usually treated as dictionaries, but in this case we want to cast to an integer.
  423. cast_type.kind = GDScriptDataType::BUILTIN;
  424. cast_type.builtin_type = Variant::INT;
  425. }
  426. // Create temporary for result first since it will be deleted last.
  427. GDScriptCodeGenerator::Address result = codegen.add_temporary(cast_type);
  428. GDScriptCodeGenerator::Address source = _parse_expression(codegen, r_error, cn->operand);
  429. gen->write_cast(result, source, cast_type);
  430. if (source.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  431. gen->pop_temporary();
  432. }
  433. return result;
  434. } break;
  435. case GDScriptParser::Node::CALL: {
  436. const GDScriptParser::CallNode *call = static_cast<const GDScriptParser::CallNode *>(p_expression);
  437. GDScriptDataType type = _gdtype_from_datatype(call->get_datatype());
  438. GDScriptCodeGenerator::Address result = codegen.add_temporary(type);
  439. GDScriptCodeGenerator::Address nil = GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::NIL);
  440. GDScriptCodeGenerator::Address return_addr = p_root ? nil : result;
  441. Vector<GDScriptCodeGenerator::Address> arguments;
  442. for (int i = 0; i < call->arguments.size(); i++) {
  443. GDScriptCodeGenerator::Address arg = _parse_expression(codegen, r_error, call->arguments[i]);
  444. if (r_error) {
  445. return GDScriptCodeGenerator::Address();
  446. }
  447. arguments.push_back(arg);
  448. }
  449. if (!call->is_super && call->callee->type == GDScriptParser::Node::IDENTIFIER && GDScriptParser::get_builtin_type(call->function_name) != Variant::VARIANT_MAX) {
  450. // Construct a built-in type.
  451. Variant::Type vtype = GDScriptParser::get_builtin_type(static_cast<GDScriptParser::IdentifierNode *>(call->callee)->name);
  452. gen->write_construct(result, vtype, arguments);
  453. } else if (!call->is_super && call->callee->type == GDScriptParser::Node::IDENTIFIER && Variant::has_utility_function(call->function_name)) {
  454. // Variant utility function.
  455. gen->write_call_utility(result, call->function_name, arguments);
  456. } else if (!call->is_super && call->callee->type == GDScriptParser::Node::IDENTIFIER && GDScriptUtilityFunctions::function_exists(call->function_name)) {
  457. // GDScript utility function.
  458. gen->write_call_gdscript_utility(result, GDScriptUtilityFunctions::get_function(call->function_name), arguments);
  459. } else {
  460. // Regular function.
  461. const GDScriptParser::ExpressionNode *callee = call->callee;
  462. if (call->is_super) {
  463. // Super call.
  464. gen->write_super_call(result, call->function_name, arguments);
  465. } else {
  466. if (callee->type == GDScriptParser::Node::IDENTIFIER) {
  467. // Self function call.
  468. if (ClassDB::has_method(codegen.script->native->get_name(), call->function_name)) {
  469. // Native method, use faster path.
  470. GDScriptCodeGenerator::Address self;
  471. self.mode = GDScriptCodeGenerator::Address::SELF;
  472. MethodBind *method = ClassDB::get_method(codegen.script->native->get_name(), call->function_name);
  473. if (_have_exact_arguments(method, arguments)) {
  474. // Exact arguments, use ptrcall.
  475. gen->write_call_ptrcall(result, self, method, arguments);
  476. } else {
  477. // Not exact arguments, but still can use method bind call.
  478. gen->write_call_method_bind(result, self, method, arguments);
  479. }
  480. } else if ((codegen.function_node && codegen.function_node->is_static) || call->function_name == "new") {
  481. GDScriptCodeGenerator::Address self;
  482. self.mode = GDScriptCodeGenerator::Address::CLASS;
  483. if (within_await) {
  484. gen->write_call_async(result, self, call->function_name, arguments);
  485. } else {
  486. gen->write_call(return_addr, self, call->function_name, arguments);
  487. }
  488. } else {
  489. if (within_await) {
  490. gen->write_call_self_async(result, call->function_name, arguments);
  491. } else {
  492. gen->write_call_self(return_addr, call->function_name, arguments);
  493. }
  494. }
  495. } else if (callee->type == GDScriptParser::Node::SUBSCRIPT) {
  496. const GDScriptParser::SubscriptNode *subscript = static_cast<const GDScriptParser::SubscriptNode *>(call->callee);
  497. if (subscript->is_attribute) {
  498. // May be static built-in method call.
  499. if (!call->is_super && subscript->base->type == GDScriptParser::Node::IDENTIFIER && GDScriptParser::get_builtin_type(static_cast<GDScriptParser::IdentifierNode *>(subscript->base)->name) < Variant::VARIANT_MAX) {
  500. gen->write_call_builtin_type_static(result, GDScriptParser::get_builtin_type(static_cast<GDScriptParser::IdentifierNode *>(subscript->base)->name), subscript->attribute->name, arguments);
  501. } else {
  502. GDScriptCodeGenerator::Address base = _parse_expression(codegen, r_error, subscript->base);
  503. if (r_error) {
  504. return GDScriptCodeGenerator::Address();
  505. }
  506. if (within_await) {
  507. gen->write_call_async(result, base, call->function_name, arguments);
  508. } else if (base.type.has_type && base.type.kind != GDScriptDataType::BUILTIN) {
  509. // Native method, use faster path.
  510. StringName class_name;
  511. if (base.type.kind == GDScriptDataType::NATIVE) {
  512. class_name = base.type.native_type;
  513. } else {
  514. class_name = base.type.native_type == StringName() ? base.type.script_type->get_instance_base_type() : base.type.native_type;
  515. }
  516. if (ClassDB::class_exists(class_name) && ClassDB::has_method(class_name, call->function_name)) {
  517. MethodBind *method = ClassDB::get_method(class_name, call->function_name);
  518. if (_have_exact_arguments(method, arguments)) {
  519. // Exact arguments, use ptrcall.
  520. gen->write_call_ptrcall(result, base, method, arguments);
  521. } else {
  522. // Not exact arguments, but still can use method bind call.
  523. gen->write_call_method_bind(result, base, method, arguments);
  524. }
  525. } else {
  526. gen->write_call(return_addr, base, call->function_name, arguments);
  527. }
  528. } else if (base.type.has_type && base.type.kind == GDScriptDataType::BUILTIN) {
  529. gen->write_call_builtin_type(result, base, base.type.builtin_type, call->function_name, arguments);
  530. } else {
  531. gen->write_call(return_addr, base, call->function_name, arguments);
  532. }
  533. if (base.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  534. gen->pop_temporary();
  535. }
  536. }
  537. } else {
  538. _set_error("Cannot call something that isn't a function.", call->callee);
  539. r_error = ERR_COMPILATION_FAILED;
  540. return GDScriptCodeGenerator::Address();
  541. }
  542. } else {
  543. r_error = ERR_COMPILATION_FAILED;
  544. return GDScriptCodeGenerator::Address();
  545. }
  546. }
  547. }
  548. for (int i = 0; i < arguments.size(); i++) {
  549. if (arguments[i].mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  550. gen->pop_temporary();
  551. }
  552. }
  553. return result;
  554. } break;
  555. case GDScriptParser::Node::GET_NODE: {
  556. const GDScriptParser::GetNodeNode *get_node = static_cast<const GDScriptParser::GetNodeNode *>(p_expression);
  557. String node_name;
  558. if (get_node->string != nullptr) {
  559. node_name += String(get_node->string->value);
  560. } else {
  561. for (int i = 0; i < get_node->chain.size(); i++) {
  562. if (i > 0) {
  563. node_name += "/";
  564. }
  565. node_name += get_node->chain[i]->name;
  566. }
  567. }
  568. Vector<GDScriptCodeGenerator::Address> args;
  569. args.push_back(codegen.add_constant(NodePath(node_name)));
  570. GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(get_node->get_datatype()));
  571. MethodBind *get_node_method = ClassDB::get_method("Node", "get_node");
  572. gen->write_call_ptrcall(result, GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::SELF), get_node_method, args);
  573. return result;
  574. } break;
  575. case GDScriptParser::Node::PRELOAD: {
  576. const GDScriptParser::PreloadNode *preload = static_cast<const GDScriptParser::PreloadNode *>(p_expression);
  577. // Add resource as constant.
  578. return codegen.add_constant(preload->resource);
  579. } break;
  580. case GDScriptParser::Node::AWAIT: {
  581. const GDScriptParser::AwaitNode *await = static_cast<const GDScriptParser::AwaitNode *>(p_expression);
  582. GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(p_expression->get_datatype()));
  583. within_await = true;
  584. GDScriptCodeGenerator::Address argument = _parse_expression(codegen, r_error, await->to_await);
  585. within_await = false;
  586. if (r_error) {
  587. return GDScriptCodeGenerator::Address();
  588. }
  589. gen->write_await(result, argument);
  590. if (argument.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  591. gen->pop_temporary();
  592. }
  593. return result;
  594. } break;
  595. // Indexing operator.
  596. case GDScriptParser::Node::SUBSCRIPT: {
  597. const GDScriptParser::SubscriptNode *subscript = static_cast<const GDScriptParser::SubscriptNode *>(p_expression);
  598. GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(subscript->get_datatype()));
  599. GDScriptCodeGenerator::Address base = _parse_expression(codegen, r_error, subscript->base);
  600. if (r_error) {
  601. return GDScriptCodeGenerator::Address();
  602. }
  603. bool named = subscript->is_attribute;
  604. StringName name;
  605. GDScriptCodeGenerator::Address index;
  606. if (p_index_addr.mode != GDScriptCodeGenerator::Address::NIL) {
  607. index = p_index_addr;
  608. } else if (subscript->is_attribute) {
  609. if (subscript->base->type == GDScriptParser::Node::SELF && codegen.script) {
  610. GDScriptParser::IdentifierNode *identifier = subscript->attribute;
  611. const Map<StringName, GDScript::MemberInfo>::Element *MI = codegen.script->member_indices.find(identifier->name);
  612. #ifdef DEBUG_ENABLED
  613. if (MI && MI->get().getter == codegen.function_name) {
  614. String n = identifier->name;
  615. _set_error("Must use '" + n + "' instead of 'self." + n + "' in getter.", identifier);
  616. r_error = ERR_COMPILATION_FAILED;
  617. return GDScriptCodeGenerator::Address();
  618. }
  619. #endif
  620. if (MI && MI->get().getter == "") {
  621. // Remove result temp as we don't need it.
  622. gen->pop_temporary();
  623. // Faster than indexing self (as if no self. had been used).
  624. return GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::MEMBER, MI->get().index, _gdtype_from_datatype(subscript->get_datatype()));
  625. }
  626. }
  627. name = subscript->attribute->name;
  628. named = true;
  629. } else {
  630. if (subscript->index->is_constant && subscript->index->reduced_value.get_type() == Variant::STRING_NAME) {
  631. // Also, somehow, named (speed up anyway).
  632. name = subscript->index->reduced_value;
  633. named = true;
  634. } else {
  635. // Regular indexing.
  636. index = _parse_expression(codegen, r_error, subscript->index);
  637. if (r_error) {
  638. return GDScriptCodeGenerator::Address();
  639. }
  640. }
  641. }
  642. if (named) {
  643. gen->write_get_named(result, name, base);
  644. } else {
  645. gen->write_get(result, index, base);
  646. }
  647. if (index.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  648. gen->pop_temporary();
  649. }
  650. if (base.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  651. gen->pop_temporary();
  652. }
  653. return result;
  654. } break;
  655. case GDScriptParser::Node::UNARY_OPERATOR: {
  656. const GDScriptParser::UnaryOpNode *unary = static_cast<const GDScriptParser::UnaryOpNode *>(p_expression);
  657. GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(unary->get_datatype()));
  658. GDScriptCodeGenerator::Address operand = _parse_expression(codegen, r_error, unary->operand);
  659. if (r_error) {
  660. return GDScriptCodeGenerator::Address();
  661. }
  662. gen->write_unary_operator(result, unary->variant_op, operand);
  663. if (operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  664. gen->pop_temporary();
  665. }
  666. return result;
  667. }
  668. case GDScriptParser::Node::BINARY_OPERATOR: {
  669. const GDScriptParser::BinaryOpNode *binary = static_cast<const GDScriptParser::BinaryOpNode *>(p_expression);
  670. GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(binary->get_datatype()));
  671. switch (binary->operation) {
  672. case GDScriptParser::BinaryOpNode::OP_LOGIC_AND: {
  673. // AND operator with early out on failure.
  674. GDScriptCodeGenerator::Address left_operand = _parse_expression(codegen, r_error, binary->left_operand);
  675. gen->write_and_left_operand(left_operand);
  676. GDScriptCodeGenerator::Address right_operand = _parse_expression(codegen, r_error, binary->right_operand);
  677. gen->write_and_right_operand(right_operand);
  678. gen->write_end_and(result);
  679. if (right_operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  680. gen->pop_temporary();
  681. }
  682. if (left_operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  683. gen->pop_temporary();
  684. }
  685. } break;
  686. case GDScriptParser::BinaryOpNode::OP_LOGIC_OR: {
  687. // OR operator with early out on success.
  688. GDScriptCodeGenerator::Address left_operand = _parse_expression(codegen, r_error, binary->left_operand);
  689. gen->write_or_left_operand(left_operand);
  690. GDScriptCodeGenerator::Address right_operand = _parse_expression(codegen, r_error, binary->right_operand);
  691. gen->write_or_right_operand(right_operand);
  692. gen->write_end_or(result);
  693. if (right_operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  694. gen->pop_temporary();
  695. }
  696. if (left_operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  697. gen->pop_temporary();
  698. }
  699. } break;
  700. case GDScriptParser::BinaryOpNode::OP_TYPE_TEST: {
  701. GDScriptCodeGenerator::Address operand = _parse_expression(codegen, r_error, binary->left_operand);
  702. if (binary->right_operand->type == GDScriptParser::Node::IDENTIFIER && GDScriptParser::get_builtin_type(static_cast<const GDScriptParser::IdentifierNode *>(binary->right_operand)->name) != Variant::VARIANT_MAX) {
  703. // `is` with builtin type)
  704. Variant::Type type = GDScriptParser::get_builtin_type(static_cast<const GDScriptParser::IdentifierNode *>(binary->right_operand)->name);
  705. gen->write_type_test_builtin(result, operand, type);
  706. } else {
  707. GDScriptCodeGenerator::Address type = _parse_expression(codegen, r_error, binary->right_operand);
  708. if (r_error) {
  709. return GDScriptCodeGenerator::Address();
  710. }
  711. gen->write_type_test(result, operand, type);
  712. if (type.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  713. gen->pop_temporary();
  714. }
  715. }
  716. if (operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  717. gen->pop_temporary();
  718. }
  719. } break;
  720. default: {
  721. GDScriptCodeGenerator::Address left_operand = _parse_expression(codegen, r_error, binary->left_operand);
  722. GDScriptCodeGenerator::Address right_operand = _parse_expression(codegen, r_error, binary->right_operand);
  723. gen->write_binary_operator(result, binary->variant_op, left_operand, right_operand);
  724. if (right_operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  725. gen->pop_temporary();
  726. }
  727. if (left_operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  728. gen->pop_temporary();
  729. }
  730. }
  731. }
  732. return result;
  733. } break;
  734. case GDScriptParser::Node::TERNARY_OPERATOR: {
  735. // x IF a ELSE y operator with early out on failure.
  736. const GDScriptParser::TernaryOpNode *ternary = static_cast<const GDScriptParser::TernaryOpNode *>(p_expression);
  737. GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(ternary->get_datatype()));
  738. gen->write_start_ternary(result);
  739. GDScriptCodeGenerator::Address condition = _parse_expression(codegen, r_error, ternary->condition);
  740. if (r_error) {
  741. return GDScriptCodeGenerator::Address();
  742. }
  743. gen->write_ternary_condition(condition);
  744. if (condition.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  745. gen->pop_temporary();
  746. }
  747. GDScriptCodeGenerator::Address true_expr = _parse_expression(codegen, r_error, ternary->true_expr);
  748. if (r_error) {
  749. return GDScriptCodeGenerator::Address();
  750. }
  751. gen->write_ternary_true_expr(true_expr);
  752. if (true_expr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  753. gen->pop_temporary();
  754. }
  755. GDScriptCodeGenerator::Address false_expr = _parse_expression(codegen, r_error, ternary->false_expr);
  756. if (r_error) {
  757. return GDScriptCodeGenerator::Address();
  758. }
  759. gen->write_ternary_false_expr(false_expr);
  760. if (false_expr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  761. gen->pop_temporary();
  762. }
  763. gen->write_end_ternary();
  764. return result;
  765. } break;
  766. case GDScriptParser::Node::ASSIGNMENT: {
  767. const GDScriptParser::AssignmentNode *assignment = static_cast<const GDScriptParser::AssignmentNode *>(p_expression);
  768. if (assignment->assignee->type == GDScriptParser::Node::SUBSCRIPT) {
  769. // SET (chained) MODE!
  770. const GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(assignment->assignee);
  771. #ifdef DEBUG_ENABLED
  772. if (subscript->is_attribute && subscript->base->type == GDScriptParser::Node::SELF && codegen.script) {
  773. const Map<StringName, GDScript::MemberInfo>::Element *MI = codegen.script->member_indices.find(subscript->attribute->name);
  774. if (MI && MI->get().setter == codegen.function_name) {
  775. String n = subscript->attribute->name;
  776. _set_error("Must use '" + n + "' instead of 'self." + n + "' in setter.", subscript);
  777. r_error = ERR_COMPILATION_FAILED;
  778. return GDScriptCodeGenerator::Address();
  779. }
  780. }
  781. #endif
  782. /* Find chain of sets */
  783. StringName assign_class_member_property;
  784. GDScriptCodeGenerator::Address target_member_property;
  785. bool is_member_property = false;
  786. bool member_property_has_setter = false;
  787. bool member_property_is_in_setter = false;
  788. StringName member_property_setter_function;
  789. List<const GDScriptParser::SubscriptNode *> chain;
  790. {
  791. // Create get/set chain.
  792. const GDScriptParser::SubscriptNode *n = subscript;
  793. while (true) {
  794. chain.push_back(n);
  795. if (n->base->type != GDScriptParser::Node::SUBSCRIPT) {
  796. // Check for a property.
  797. if (n->base->type == GDScriptParser::Node::IDENTIFIER) {
  798. GDScriptParser::IdentifierNode *identifier = static_cast<GDScriptParser::IdentifierNode *>(n->base);
  799. StringName var_name = identifier->name;
  800. if (_is_class_member_property(codegen, var_name)) {
  801. assign_class_member_property = var_name;
  802. } else if (!codegen.locals.has(var_name) && codegen.script->member_indices.has(var_name)) {
  803. is_member_property = true;
  804. member_property_setter_function = codegen.script->member_indices[var_name].setter;
  805. member_property_has_setter = member_property_setter_function != StringName();
  806. member_property_is_in_setter = member_property_has_setter && member_property_setter_function == codegen.function_name;
  807. target_member_property.mode = GDScriptCodeGenerator::Address::MEMBER;
  808. target_member_property.address = codegen.script->member_indices[var_name].index;
  809. target_member_property.type = codegen.script->member_indices[var_name].data_type;
  810. }
  811. }
  812. break;
  813. }
  814. n = static_cast<const GDScriptParser::SubscriptNode *>(n->base);
  815. }
  816. }
  817. /* Chain of gets */
  818. // Get at (potential) root stack pos, so it can be returned.
  819. GDScriptCodeGenerator::Address base = _parse_expression(codegen, r_error, chain.back()->get()->base);
  820. if (r_error) {
  821. return GDScriptCodeGenerator::Address();
  822. }
  823. GDScriptCodeGenerator::Address prev_base = base;
  824. struct ChainInfo {
  825. bool is_named = false;
  826. GDScriptCodeGenerator::Address base;
  827. GDScriptCodeGenerator::Address key;
  828. StringName name;
  829. };
  830. List<ChainInfo> set_chain;
  831. for (List<const GDScriptParser::SubscriptNode *>::Element *E = chain.back(); E; E = E->prev()) {
  832. if (E == chain.front()) {
  833. // Skip the main subscript, since we'll assign to that.
  834. break;
  835. }
  836. const GDScriptParser::SubscriptNode *subscript_elem = E->get();
  837. GDScriptCodeGenerator::Address value = codegen.add_temporary(_gdtype_from_datatype(subscript_elem->get_datatype()));
  838. GDScriptCodeGenerator::Address key;
  839. StringName name;
  840. if (subscript_elem->is_attribute) {
  841. name = subscript_elem->attribute->name;
  842. gen->write_get_named(value, name, prev_base);
  843. } else {
  844. key = _parse_expression(codegen, r_error, subscript_elem->index);
  845. if (r_error) {
  846. return GDScriptCodeGenerator::Address();
  847. }
  848. gen->write_get(value, key, prev_base);
  849. }
  850. // Store base and key for setting it back later.
  851. set_chain.push_front({ subscript_elem->is_attribute, prev_base, key, name }); // Push to front to invert the list.
  852. prev_base = value;
  853. }
  854. // Get value to assign.
  855. GDScriptCodeGenerator::Address assigned = _parse_expression(codegen, r_error, assignment->assigned_value);
  856. if (r_error) {
  857. return GDScriptCodeGenerator::Address();
  858. }
  859. // Get the key if needed.
  860. GDScriptCodeGenerator::Address key;
  861. StringName name;
  862. if (subscript->is_attribute) {
  863. name = subscript->attribute->name;
  864. } else {
  865. key = _parse_expression(codegen, r_error, subscript->index);
  866. if (r_error) {
  867. return GDScriptCodeGenerator::Address();
  868. }
  869. }
  870. // Perform operator if any.
  871. if (assignment->operation != GDScriptParser::AssignmentNode::OP_NONE) {
  872. GDScriptCodeGenerator::Address op_result = codegen.add_temporary(_gdtype_from_datatype(assignment->get_datatype()));
  873. GDScriptCodeGenerator::Address value = codegen.add_temporary(_gdtype_from_datatype(subscript->get_datatype()));
  874. if (subscript->is_attribute) {
  875. gen->write_get_named(value, name, prev_base);
  876. } else {
  877. gen->write_get(value, key, prev_base);
  878. }
  879. gen->write_binary_operator(op_result, assignment->variant_op, value, assigned);
  880. gen->pop_temporary();
  881. if (assigned.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  882. gen->pop_temporary();
  883. }
  884. assigned = op_result;
  885. }
  886. // Perform assignment.
  887. if (subscript->is_attribute) {
  888. gen->write_set_named(prev_base, name, assigned);
  889. } else {
  890. gen->write_set(prev_base, key, assigned);
  891. }
  892. if (key.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  893. gen->pop_temporary();
  894. }
  895. if (assigned.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  896. gen->pop_temporary();
  897. }
  898. assigned = prev_base;
  899. // Set back the values into their bases.
  900. for (const ChainInfo &info : set_chain) {
  901. if (!info.is_named) {
  902. gen->write_set(info.base, info.key, assigned);
  903. if (info.key.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  904. gen->pop_temporary();
  905. }
  906. } else {
  907. gen->write_set_named(info.base, info.name, assigned);
  908. }
  909. if (assigned.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  910. gen->pop_temporary();
  911. }
  912. assigned = info.base;
  913. }
  914. // If this is a class member property, also assign to it.
  915. // This allow things like: position.x += 2.0
  916. if (assign_class_member_property != StringName()) {
  917. gen->write_set_member(assigned, assign_class_member_property);
  918. }
  919. // Same as above but for members
  920. if (is_member_property) {
  921. if (member_property_has_setter && !member_property_is_in_setter) {
  922. Vector<GDScriptCodeGenerator::Address> args;
  923. args.push_back(assigned);
  924. gen->write_call(GDScriptCodeGenerator::Address(), GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::SELF), member_property_setter_function, args);
  925. } else {
  926. gen->write_assign(target_member_property, assigned);
  927. }
  928. }
  929. if (assigned.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  930. gen->pop_temporary();
  931. }
  932. } else if (assignment->assignee->type == GDScriptParser::Node::IDENTIFIER && _is_class_member_property(codegen, static_cast<GDScriptParser::IdentifierNode *>(assignment->assignee)->name)) {
  933. // Assignment to member property.
  934. GDScriptCodeGenerator::Address assigned_value = _parse_expression(codegen, r_error, assignment->assigned_value);
  935. if (r_error) {
  936. return GDScriptCodeGenerator::Address();
  937. }
  938. GDScriptCodeGenerator::Address to_assign = assigned_value;
  939. bool has_operation = assignment->operation != GDScriptParser::AssignmentNode::OP_NONE;
  940. StringName name = static_cast<GDScriptParser::IdentifierNode *>(assignment->assignee)->name;
  941. if (has_operation) {
  942. GDScriptCodeGenerator::Address op_result = codegen.add_temporary(_gdtype_from_datatype(assignment->get_datatype()));
  943. GDScriptCodeGenerator::Address member = codegen.add_temporary(_gdtype_from_datatype(assignment->assignee->get_datatype()));
  944. gen->write_get_member(member, name);
  945. gen->write_binary_operator(op_result, assignment->variant_op, member, assigned_value);
  946. gen->pop_temporary(); // Pop member temp.
  947. to_assign = op_result;
  948. }
  949. gen->write_set_member(to_assign, name);
  950. if (to_assign.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  951. gen->pop_temporary(); // Pop the assigned expression or the temp result if it has operation.
  952. }
  953. if (has_operation && assigned_value.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  954. gen->pop_temporary(); // Pop the assigned expression if not done before.
  955. }
  956. } else {
  957. // Regular assignment.
  958. ERR_FAIL_COND_V_MSG(assignment->assignee->type != GDScriptParser::Node::IDENTIFIER, GDScriptCodeGenerator::Address(), "Expected the assignee to be an identifier here.");
  959. GDScriptCodeGenerator::Address member;
  960. bool is_member = false;
  961. bool has_setter = false;
  962. bool is_in_setter = false;
  963. StringName setter_function;
  964. StringName var_name = static_cast<const GDScriptParser::IdentifierNode *>(assignment->assignee)->name;
  965. if (!codegen.locals.has(var_name) && codegen.script->member_indices.has(var_name)) {
  966. is_member = true;
  967. setter_function = codegen.script->member_indices[var_name].setter;
  968. has_setter = setter_function != StringName();
  969. is_in_setter = has_setter && setter_function == codegen.function_name;
  970. member.mode = GDScriptCodeGenerator::Address::MEMBER;
  971. member.address = codegen.script->member_indices[var_name].index;
  972. member.type = codegen.script->member_indices[var_name].data_type;
  973. }
  974. GDScriptCodeGenerator::Address target;
  975. if (is_member) {
  976. target = member; // _parse_expression could call its getter, but we want to know the actual address
  977. } else {
  978. target = _parse_expression(codegen, r_error, assignment->assignee);
  979. if (r_error) {
  980. return GDScriptCodeGenerator::Address();
  981. }
  982. }
  983. GDScriptCodeGenerator::Address assigned_value = _parse_expression(codegen, r_error, assignment->assigned_value);
  984. if (r_error) {
  985. return GDScriptCodeGenerator::Address();
  986. }
  987. GDScriptCodeGenerator::Address to_assign;
  988. bool has_operation = assignment->operation != GDScriptParser::AssignmentNode::OP_NONE;
  989. if (has_operation) {
  990. // Perform operation.
  991. GDScriptCodeGenerator::Address op_result = codegen.add_temporary(_gdtype_from_datatype(assignment->get_datatype()));
  992. GDScriptCodeGenerator::Address og_value = _parse_expression(codegen, r_error, assignment->assignee);
  993. gen->write_binary_operator(op_result, assignment->variant_op, og_value, assigned_value);
  994. to_assign = op_result;
  995. if (og_value.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  996. gen->pop_temporary();
  997. }
  998. } else {
  999. to_assign = assigned_value;
  1000. }
  1001. GDScriptDataType assign_type = _gdtype_from_datatype(assignment->assignee->get_datatype());
  1002. if (has_setter && !is_in_setter) {
  1003. // Call setter.
  1004. Vector<GDScriptCodeGenerator::Address> args;
  1005. args.push_back(to_assign);
  1006. gen->write_call(GDScriptCodeGenerator::Address(), GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::SELF), setter_function, args);
  1007. } else {
  1008. // Just assign.
  1009. if (assignment->use_conversion_assign) {
  1010. gen->write_assign_with_conversion(target, to_assign);
  1011. } else {
  1012. gen->write_assign(target, to_assign);
  1013. }
  1014. }
  1015. if (to_assign.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  1016. gen->pop_temporary(); // Pop assigned value or temp operation result.
  1017. }
  1018. if (has_operation && assigned_value.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  1019. gen->pop_temporary(); // Pop assigned value if not done before.
  1020. }
  1021. if (target.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  1022. gen->pop_temporary(); // Pop the target to assignment.
  1023. }
  1024. }
  1025. return GDScriptCodeGenerator::Address(); // Assignment does not return a value.
  1026. } break;
  1027. case GDScriptParser::Node::LAMBDA: {
  1028. const GDScriptParser::LambdaNode *lambda = static_cast<const GDScriptParser::LambdaNode *>(p_expression);
  1029. GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(lambda->get_datatype()));
  1030. Vector<GDScriptCodeGenerator::Address> captures;
  1031. captures.resize(lambda->captures.size());
  1032. for (int i = 0; i < lambda->captures.size(); i++) {
  1033. captures.write[i] = _parse_expression(codegen, r_error, lambda->captures[i]);
  1034. if (r_error) {
  1035. return GDScriptCodeGenerator::Address();
  1036. }
  1037. }
  1038. GDScriptFunction *function = _parse_function(r_error, codegen.script, codegen.class_node, lambda->function, false, true);
  1039. if (r_error) {
  1040. return GDScriptCodeGenerator::Address();
  1041. }
  1042. gen->write_lambda(result, function, captures);
  1043. for (int i = 0; i < captures.size(); i++) {
  1044. if (captures[i].mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  1045. gen->pop_temporary();
  1046. }
  1047. }
  1048. return result;
  1049. } break;
  1050. default: {
  1051. ERR_FAIL_V_MSG(GDScriptCodeGenerator::Address(), "Bug in bytecode compiler, unexpected node in parse tree while parsing expression."); // Unreachable code.
  1052. } break;
  1053. }
  1054. }
  1055. GDScriptCodeGenerator::Address GDScriptCompiler::_parse_match_pattern(CodeGen &codegen, Error &r_error, const GDScriptParser::PatternNode *p_pattern, const GDScriptCodeGenerator::Address &p_value_addr, const GDScriptCodeGenerator::Address &p_type_addr, const GDScriptCodeGenerator::Address &p_previous_test, bool p_is_first, bool p_is_nested) {
  1056. switch (p_pattern->pattern_type) {
  1057. case GDScriptParser::PatternNode::PT_LITERAL: {
  1058. if (p_is_nested) {
  1059. codegen.generator->write_and_left_operand(p_previous_test);
  1060. } else if (!p_is_first) {
  1061. codegen.generator->write_or_left_operand(p_previous_test);
  1062. }
  1063. // Get literal type into constant map.
  1064. GDScriptCodeGenerator::Address literal_type_addr = codegen.add_constant((int)p_pattern->literal->value.get_type());
  1065. // Equality is always a boolean.
  1066. GDScriptDataType equality_type;
  1067. equality_type.has_type = true;
  1068. equality_type.kind = GDScriptDataType::BUILTIN;
  1069. equality_type.builtin_type = Variant::BOOL;
  1070. // Check type equality.
  1071. GDScriptCodeGenerator::Address type_equality_addr = codegen.add_temporary(equality_type);
  1072. codegen.generator->write_binary_operator(type_equality_addr, Variant::OP_EQUAL, p_type_addr, literal_type_addr);
  1073. codegen.generator->write_and_left_operand(type_equality_addr);
  1074. // Get literal.
  1075. GDScriptCodeGenerator::Address literal_addr = _parse_expression(codegen, r_error, p_pattern->literal);
  1076. if (r_error) {
  1077. return GDScriptCodeGenerator::Address();
  1078. }
  1079. // Check value equality.
  1080. GDScriptCodeGenerator::Address equality_addr = codegen.add_temporary(equality_type);
  1081. codegen.generator->write_binary_operator(equality_addr, Variant::OP_EQUAL, p_value_addr, literal_addr);
  1082. codegen.generator->write_and_right_operand(equality_addr);
  1083. // AND both together (reuse temporary location).
  1084. codegen.generator->write_end_and(type_equality_addr);
  1085. codegen.generator->pop_temporary(); // Remove equality_addr from stack.
  1086. if (literal_addr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  1087. codegen.generator->pop_temporary();
  1088. }
  1089. // If this isn't the first, we need to OR with the previous pattern. If it's nested, we use AND instead.
  1090. if (p_is_nested) {
  1091. // Use the previous value as target, since we only need one temporary variable.
  1092. codegen.generator->write_and_right_operand(type_equality_addr);
  1093. codegen.generator->write_end_and(p_previous_test);
  1094. } else if (!p_is_first) {
  1095. // Use the previous value as target, since we only need one temporary variable.
  1096. codegen.generator->write_or_right_operand(type_equality_addr);
  1097. codegen.generator->write_end_or(p_previous_test);
  1098. } else {
  1099. // Just assign this value to the accumulator temporary.
  1100. codegen.generator->write_assign(p_previous_test, type_equality_addr);
  1101. }
  1102. codegen.generator->pop_temporary(); // Remove type_equality_addr.
  1103. return p_previous_test;
  1104. } break;
  1105. case GDScriptParser::PatternNode::PT_EXPRESSION: {
  1106. if (p_is_nested) {
  1107. codegen.generator->write_and_left_operand(p_previous_test);
  1108. } else if (!p_is_first) {
  1109. codegen.generator->write_or_left_operand(p_previous_test);
  1110. }
  1111. // Create the result temps first since it's the last to go away.
  1112. GDScriptCodeGenerator::Address result_addr = codegen.add_temporary();
  1113. GDScriptCodeGenerator::Address equality_test_addr = codegen.add_temporary();
  1114. // Evaluate expression.
  1115. GDScriptCodeGenerator::Address expr_addr;
  1116. expr_addr = _parse_expression(codegen, r_error, p_pattern->expression);
  1117. if (r_error) {
  1118. return GDScriptCodeGenerator::Address();
  1119. }
  1120. // Evaluate expression type.
  1121. Vector<GDScriptCodeGenerator::Address> typeof_args;
  1122. typeof_args.push_back(expr_addr);
  1123. codegen.generator->write_call_utility(result_addr, "typeof", typeof_args);
  1124. // Check type equality.
  1125. codegen.generator->write_binary_operator(result_addr, Variant::OP_EQUAL, p_type_addr, result_addr);
  1126. codegen.generator->write_and_left_operand(result_addr);
  1127. // Check value equality.
  1128. codegen.generator->write_binary_operator(equality_test_addr, Variant::OP_EQUAL, p_value_addr, expr_addr);
  1129. codegen.generator->write_and_right_operand(equality_test_addr);
  1130. // AND both type and value equality.
  1131. codegen.generator->write_end_and(result_addr);
  1132. // We don't need the expression temporary anymore.
  1133. if (expr_addr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  1134. codegen.generator->pop_temporary();
  1135. }
  1136. codegen.generator->pop_temporary(); // Remove type equality temporary.
  1137. // If this isn't the first, we need to OR with the previous pattern. If it's nested, we use AND instead.
  1138. if (p_is_nested) {
  1139. // Use the previous value as target, since we only need one temporary variable.
  1140. codegen.generator->write_and_right_operand(result_addr);
  1141. codegen.generator->write_end_and(p_previous_test);
  1142. } else if (!p_is_first) {
  1143. // Use the previous value as target, since we only need one temporary variable.
  1144. codegen.generator->write_or_right_operand(result_addr);
  1145. codegen.generator->write_end_or(p_previous_test);
  1146. } else {
  1147. // Just assign this value to the accumulator temporary.
  1148. codegen.generator->write_assign(p_previous_test, result_addr);
  1149. }
  1150. codegen.generator->pop_temporary(); // Remove temp result addr.
  1151. return p_previous_test;
  1152. } break;
  1153. case GDScriptParser::PatternNode::PT_ARRAY: {
  1154. if (p_is_nested) {
  1155. codegen.generator->write_and_left_operand(p_previous_test);
  1156. } else if (!p_is_first) {
  1157. codegen.generator->write_or_left_operand(p_previous_test);
  1158. }
  1159. // Get array type into constant map.
  1160. GDScriptCodeGenerator::Address array_type_addr = codegen.add_constant((int)Variant::ARRAY);
  1161. // Equality is always a boolean.
  1162. GDScriptDataType temp_type;
  1163. temp_type.has_type = true;
  1164. temp_type.kind = GDScriptDataType::BUILTIN;
  1165. temp_type.builtin_type = Variant::BOOL;
  1166. // Check type equality.
  1167. GDScriptCodeGenerator::Address result_addr = codegen.add_temporary(temp_type);
  1168. codegen.generator->write_binary_operator(result_addr, Variant::OP_EQUAL, p_type_addr, array_type_addr);
  1169. codegen.generator->write_and_left_operand(result_addr);
  1170. // Store pattern length in constant map.
  1171. GDScriptCodeGenerator::Address array_length_addr = codegen.add_constant(p_pattern->rest_used ? p_pattern->array.size() - 1 : p_pattern->array.size());
  1172. // Get value length.
  1173. temp_type.builtin_type = Variant::INT;
  1174. GDScriptCodeGenerator::Address value_length_addr = codegen.add_temporary(temp_type);
  1175. Vector<GDScriptCodeGenerator::Address> len_args;
  1176. len_args.push_back(p_value_addr);
  1177. codegen.generator->write_call_gdscript_utility(value_length_addr, GDScriptUtilityFunctions::get_function("len"), len_args);
  1178. // Test length compatibility.
  1179. temp_type.builtin_type = Variant::BOOL;
  1180. GDScriptCodeGenerator::Address length_compat_addr = codegen.add_temporary(temp_type);
  1181. codegen.generator->write_binary_operator(length_compat_addr, p_pattern->rest_used ? Variant::OP_GREATER_EQUAL : Variant::OP_EQUAL, value_length_addr, array_length_addr);
  1182. codegen.generator->write_and_right_operand(length_compat_addr);
  1183. // AND type and length check.
  1184. codegen.generator->write_end_and(result_addr);
  1185. // Remove length temporaries.
  1186. codegen.generator->pop_temporary();
  1187. codegen.generator->pop_temporary();
  1188. // If this isn't the first, we need to OR with the previous pattern. If it's nested, we use AND instead.
  1189. if (p_is_nested) {
  1190. // Use the previous value as target, since we only need one temporary variable.
  1191. codegen.generator->write_and_right_operand(result_addr);
  1192. codegen.generator->write_end_and(p_previous_test);
  1193. } else if (!p_is_first) {
  1194. // Use the previous value as target, since we only need one temporary variable.
  1195. codegen.generator->write_or_right_operand(result_addr);
  1196. codegen.generator->write_end_or(p_previous_test);
  1197. } else {
  1198. // Just assign this value to the accumulator temporary.
  1199. codegen.generator->write_assign(p_previous_test, result_addr);
  1200. }
  1201. codegen.generator->pop_temporary(); // Remove temp result addr.
  1202. // Create temporaries outside the loop so they can be reused.
  1203. GDScriptCodeGenerator::Address element_addr = codegen.add_temporary();
  1204. GDScriptCodeGenerator::Address element_type_addr = codegen.add_temporary();
  1205. GDScriptCodeGenerator::Address test_addr = p_previous_test;
  1206. // Evaluate element by element.
  1207. for (int i = 0; i < p_pattern->array.size(); i++) {
  1208. if (p_pattern->array[i]->pattern_type == GDScriptParser::PatternNode::PT_REST) {
  1209. // Don't want to access an extra element of the user array.
  1210. break;
  1211. }
  1212. // Use AND here too, as we don't want to be checking elements if previous test failed (which means this might be an invalid get).
  1213. codegen.generator->write_and_left_operand(test_addr);
  1214. // Add index to constant map.
  1215. GDScriptCodeGenerator::Address index_addr = codegen.add_constant(i);
  1216. // Get the actual element from the user-sent array.
  1217. codegen.generator->write_get(element_addr, index_addr, p_value_addr);
  1218. // Also get type of element.
  1219. Vector<GDScriptCodeGenerator::Address> typeof_args;
  1220. typeof_args.push_back(element_addr);
  1221. codegen.generator->write_call_utility(element_type_addr, "typeof", typeof_args);
  1222. // Try the pattern inside the element.
  1223. test_addr = _parse_match_pattern(codegen, r_error, p_pattern->array[i], element_addr, element_type_addr, p_previous_test, false, true);
  1224. if (r_error != OK) {
  1225. return GDScriptCodeGenerator::Address();
  1226. }
  1227. codegen.generator->write_and_right_operand(test_addr);
  1228. codegen.generator->write_end_and(test_addr);
  1229. }
  1230. // Remove element temporaries.
  1231. codegen.generator->pop_temporary();
  1232. codegen.generator->pop_temporary();
  1233. return test_addr;
  1234. } break;
  1235. case GDScriptParser::PatternNode::PT_DICTIONARY: {
  1236. if (p_is_nested) {
  1237. codegen.generator->write_and_left_operand(p_previous_test);
  1238. } else if (!p_is_first) {
  1239. codegen.generator->write_or_left_operand(p_previous_test);
  1240. }
  1241. // Get dictionary type into constant map.
  1242. GDScriptCodeGenerator::Address dict_type_addr = codegen.add_constant((int)Variant::DICTIONARY);
  1243. // Equality is always a boolean.
  1244. GDScriptDataType temp_type;
  1245. temp_type.has_type = true;
  1246. temp_type.kind = GDScriptDataType::BUILTIN;
  1247. temp_type.builtin_type = Variant::BOOL;
  1248. // Check type equality.
  1249. GDScriptCodeGenerator::Address result_addr = codegen.add_temporary(temp_type);
  1250. codegen.generator->write_binary_operator(result_addr, Variant::OP_EQUAL, p_type_addr, dict_type_addr);
  1251. codegen.generator->write_and_left_operand(result_addr);
  1252. // Store pattern length in constant map.
  1253. GDScriptCodeGenerator::Address dict_length_addr = codegen.add_constant(p_pattern->rest_used ? p_pattern->dictionary.size() - 1 : p_pattern->dictionary.size());
  1254. // Get user's dictionary length.
  1255. temp_type.builtin_type = Variant::INT;
  1256. GDScriptCodeGenerator::Address value_length_addr = codegen.add_temporary(temp_type);
  1257. Vector<GDScriptCodeGenerator::Address> func_args;
  1258. func_args.push_back(p_value_addr);
  1259. codegen.generator->write_call_gdscript_utility(value_length_addr, GDScriptUtilityFunctions::get_function("len"), func_args);
  1260. // Test length compatibility.
  1261. temp_type.builtin_type = Variant::BOOL;
  1262. GDScriptCodeGenerator::Address length_compat_addr = codegen.add_temporary(temp_type);
  1263. codegen.generator->write_binary_operator(length_compat_addr, p_pattern->rest_used ? Variant::OP_GREATER_EQUAL : Variant::OP_EQUAL, value_length_addr, dict_length_addr);
  1264. codegen.generator->write_and_right_operand(length_compat_addr);
  1265. // AND type and length check.
  1266. codegen.generator->write_end_and(result_addr);
  1267. // Remove length temporaries.
  1268. codegen.generator->pop_temporary();
  1269. codegen.generator->pop_temporary();
  1270. // If this isn't the first, we need to OR with the previous pattern. If it's nested, we use AND instead.
  1271. if (p_is_nested) {
  1272. // Use the previous value as target, since we only need one temporary variable.
  1273. codegen.generator->write_and_right_operand(result_addr);
  1274. codegen.generator->write_end_and(p_previous_test);
  1275. } else if (!p_is_first) {
  1276. // Use the previous value as target, since we only need one temporary variable.
  1277. codegen.generator->write_or_right_operand(result_addr);
  1278. codegen.generator->write_end_or(p_previous_test);
  1279. } else {
  1280. // Just assign this value to the accumulator temporary.
  1281. codegen.generator->write_assign(p_previous_test, result_addr);
  1282. }
  1283. codegen.generator->pop_temporary(); // Remove temp result addr.
  1284. // Create temporaries outside the loop so they can be reused.
  1285. temp_type.builtin_type = Variant::BOOL;
  1286. GDScriptCodeGenerator::Address test_result = codegen.add_temporary(temp_type);
  1287. GDScriptCodeGenerator::Address element_addr = codegen.add_temporary();
  1288. GDScriptCodeGenerator::Address element_type_addr = codegen.add_temporary();
  1289. GDScriptCodeGenerator::Address test_addr = p_previous_test;
  1290. // Evaluate element by element.
  1291. for (int i = 0; i < p_pattern->dictionary.size(); i++) {
  1292. const GDScriptParser::PatternNode::Pair &element = p_pattern->dictionary[i];
  1293. if (element.value_pattern && element.value_pattern->pattern_type == GDScriptParser::PatternNode::PT_REST) {
  1294. // Ignore rest pattern.
  1295. break;
  1296. }
  1297. // Use AND here too, as we don't want to be checking elements if previous test failed (which means this might be an invalid get).
  1298. codegen.generator->write_and_left_operand(test_addr);
  1299. // Get the pattern key.
  1300. GDScriptCodeGenerator::Address pattern_key_addr = _parse_expression(codegen, r_error, element.key);
  1301. if (r_error) {
  1302. return GDScriptCodeGenerator::Address();
  1303. }
  1304. // Check if pattern key exists in user's dictionary. This will be AND-ed with next result.
  1305. func_args.clear();
  1306. func_args.push_back(pattern_key_addr);
  1307. codegen.generator->write_call(test_result, p_value_addr, "has", func_args);
  1308. if (element.value_pattern != nullptr) {
  1309. // Use AND here too, as we don't want to be checking elements if previous test failed (which means this might be an invalid get).
  1310. codegen.generator->write_and_left_operand(test_result);
  1311. // Get actual value from user dictionary.
  1312. codegen.generator->write_get(element_addr, pattern_key_addr, p_value_addr);
  1313. // Also get type of value.
  1314. func_args.clear();
  1315. func_args.push_back(element_addr);
  1316. codegen.generator->write_call_utility(element_type_addr, "typeof", func_args);
  1317. // Try the pattern inside the value.
  1318. test_addr = _parse_match_pattern(codegen, r_error, element.value_pattern, element_addr, element_type_addr, test_addr, false, true);
  1319. if (r_error != OK) {
  1320. return GDScriptCodeGenerator::Address();
  1321. }
  1322. codegen.generator->write_and_right_operand(test_addr);
  1323. codegen.generator->write_end_and(test_addr);
  1324. }
  1325. codegen.generator->write_and_right_operand(test_addr);
  1326. codegen.generator->write_end_and(test_addr);
  1327. // Remove pattern key temporary.
  1328. if (pattern_key_addr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  1329. codegen.generator->pop_temporary();
  1330. }
  1331. }
  1332. // Remove element temporaries.
  1333. codegen.generator->pop_temporary();
  1334. codegen.generator->pop_temporary();
  1335. codegen.generator->pop_temporary();
  1336. return test_addr;
  1337. } break;
  1338. case GDScriptParser::PatternNode::PT_REST:
  1339. // Do nothing.
  1340. return p_previous_test;
  1341. break;
  1342. case GDScriptParser::PatternNode::PT_BIND: {
  1343. if (p_is_nested) {
  1344. codegen.generator->write_and_left_operand(p_previous_test);
  1345. } else if (!p_is_first) {
  1346. codegen.generator->write_or_left_operand(p_previous_test);
  1347. }
  1348. // Get the bind address.
  1349. GDScriptCodeGenerator::Address bind = codegen.locals[p_pattern->bind->name];
  1350. // Assign value to bound variable.
  1351. codegen.generator->write_assign(bind, p_value_addr);
  1352. }
  1353. [[fallthrough]]; // Act like matching anything too.
  1354. case GDScriptParser::PatternNode::PT_WILDCARD:
  1355. // If this is a fall through we don't want to do this again.
  1356. if (p_pattern->pattern_type != GDScriptParser::PatternNode::PT_BIND) {
  1357. if (p_is_nested) {
  1358. codegen.generator->write_and_left_operand(p_previous_test);
  1359. } else if (!p_is_first) {
  1360. codegen.generator->write_or_left_operand(p_previous_test);
  1361. }
  1362. }
  1363. // This matches anything so just do the same as `if(true)`.
  1364. // If this isn't the first, we need to OR with the previous pattern. If it's nested, we use AND instead.
  1365. if (p_is_nested) {
  1366. // Use the operator with the `true` constant so it works as always matching.
  1367. GDScriptCodeGenerator::Address constant = codegen.add_constant(true);
  1368. codegen.generator->write_and_right_operand(constant);
  1369. codegen.generator->write_end_and(p_previous_test);
  1370. } else if (!p_is_first) {
  1371. // Use the operator with the `true` constant so it works as always matching.
  1372. GDScriptCodeGenerator::Address constant = codegen.add_constant(true);
  1373. codegen.generator->write_or_right_operand(constant);
  1374. codegen.generator->write_end_or(p_previous_test);
  1375. } else {
  1376. // Just assign this value to the accumulator temporary.
  1377. codegen.generator->write_assign_true(p_previous_test);
  1378. }
  1379. return p_previous_test;
  1380. }
  1381. ERR_FAIL_V_MSG(p_previous_test, "Reaching the end of pattern compilation without matching a pattern.");
  1382. }
  1383. void GDScriptCompiler::_add_locals_in_block(CodeGen &codegen, const GDScriptParser::SuiteNode *p_block) {
  1384. for (int i = 0; i < p_block->locals.size(); i++) {
  1385. if (p_block->locals[i].type == GDScriptParser::SuiteNode::Local::PARAMETER || p_block->locals[i].type == GDScriptParser::SuiteNode::Local::FOR_VARIABLE) {
  1386. // Parameters are added directly from function and loop variables are declared explicitly.
  1387. continue;
  1388. }
  1389. codegen.add_local(p_block->locals[i].name, _gdtype_from_datatype(p_block->locals[i].get_datatype()));
  1390. }
  1391. }
  1392. Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::SuiteNode *p_block, bool p_add_locals) {
  1393. Error error = OK;
  1394. GDScriptCodeGenerator *gen = codegen.generator;
  1395. codegen.start_block();
  1396. if (p_add_locals) {
  1397. _add_locals_in_block(codegen, p_block);
  1398. }
  1399. for (int i = 0; i < p_block->statements.size(); i++) {
  1400. const GDScriptParser::Node *s = p_block->statements[i];
  1401. #ifdef DEBUG_ENABLED
  1402. // Add a newline before each statement, since the debugger needs those.
  1403. gen->write_newline(s->start_line);
  1404. #endif
  1405. switch (s->type) {
  1406. case GDScriptParser::Node::MATCH: {
  1407. const GDScriptParser::MatchNode *match = static_cast<const GDScriptParser::MatchNode *>(s);
  1408. gen->start_match();
  1409. codegen.start_block();
  1410. // Evaluate the match expression.
  1411. GDScriptCodeGenerator::Address value = codegen.add_local("@match_value", _gdtype_from_datatype(match->test->get_datatype()));
  1412. GDScriptCodeGenerator::Address value_expr = _parse_expression(codegen, error, match->test);
  1413. if (error) {
  1414. return error;
  1415. }
  1416. // Assign to local.
  1417. // TODO: This can be improved by passing the target to parse_expression().
  1418. gen->write_assign(value, value_expr);
  1419. if (value_expr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  1420. codegen.generator->pop_temporary();
  1421. }
  1422. // Then, let's save the type of the value in the stack too, so we can reuse for later comparisons.
  1423. GDScriptDataType typeof_type;
  1424. typeof_type.has_type = true;
  1425. typeof_type.kind = GDScriptDataType::BUILTIN;
  1426. typeof_type.builtin_type = Variant::INT;
  1427. GDScriptCodeGenerator::Address type = codegen.add_local("@match_type", typeof_type);
  1428. Vector<GDScriptCodeGenerator::Address> typeof_args;
  1429. typeof_args.push_back(value);
  1430. gen->write_call_utility(type, "typeof", typeof_args);
  1431. // Now we can actually start testing.
  1432. // For each branch.
  1433. for (int j = 0; j < match->branches.size(); j++) {
  1434. if (j > 0) {
  1435. // Use `else` to not check the next branch after matching.
  1436. gen->write_else();
  1437. }
  1438. const GDScriptParser::MatchBranchNode *branch = match->branches[j];
  1439. gen->start_match_branch(); // Need so lower level code can patch 'continue' jumps.
  1440. codegen.start_block(); // Create an extra block around for binds.
  1441. // Add locals in block before patterns, so temporaries don't use the stack address for binds.
  1442. _add_locals_in_block(codegen, branch->block);
  1443. #ifdef DEBUG_ENABLED
  1444. // Add a newline before each branch, since the debugger needs those.
  1445. gen->write_newline(branch->start_line);
  1446. #endif
  1447. // For each pattern in branch.
  1448. GDScriptCodeGenerator::Address pattern_result = codegen.add_temporary();
  1449. for (int k = 0; k < branch->patterns.size(); k++) {
  1450. pattern_result = _parse_match_pattern(codegen, error, branch->patterns[k], value, type, pattern_result, k == 0, false);
  1451. if (error != OK) {
  1452. return error;
  1453. }
  1454. }
  1455. // Check if pattern did match.
  1456. gen->write_if(pattern_result);
  1457. // Remove the result from stack.
  1458. gen->pop_temporary();
  1459. // Parse the branch block.
  1460. error = _parse_block(codegen, branch->block, false); // Don't add locals again.
  1461. if (error) {
  1462. return error;
  1463. }
  1464. codegen.end_block(); // Get out of extra block.
  1465. }
  1466. // End all nested `if`s.
  1467. for (int j = 0; j < match->branches.size(); j++) {
  1468. gen->write_endif();
  1469. }
  1470. gen->end_match();
  1471. } break;
  1472. case GDScriptParser::Node::IF: {
  1473. const GDScriptParser::IfNode *if_n = static_cast<const GDScriptParser::IfNode *>(s);
  1474. GDScriptCodeGenerator::Address condition = _parse_expression(codegen, error, if_n->condition);
  1475. if (error) {
  1476. return error;
  1477. }
  1478. gen->write_if(condition);
  1479. if (condition.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  1480. codegen.generator->pop_temporary();
  1481. }
  1482. error = _parse_block(codegen, if_n->true_block);
  1483. if (error) {
  1484. return error;
  1485. }
  1486. if (if_n->false_block) {
  1487. gen->write_else();
  1488. error = _parse_block(codegen, if_n->false_block);
  1489. if (error) {
  1490. return error;
  1491. }
  1492. }
  1493. gen->write_endif();
  1494. } break;
  1495. case GDScriptParser::Node::FOR: {
  1496. const GDScriptParser::ForNode *for_n = static_cast<const GDScriptParser::ForNode *>(s);
  1497. codegen.start_block();
  1498. GDScriptCodeGenerator::Address iterator = codegen.add_local(for_n->variable->name, _gdtype_from_datatype(for_n->variable->get_datatype()));
  1499. gen->start_for(iterator.type, _gdtype_from_datatype(for_n->list->get_datatype()));
  1500. GDScriptCodeGenerator::Address list = _parse_expression(codegen, error, for_n->list);
  1501. if (error) {
  1502. return error;
  1503. }
  1504. gen->write_for_assignment(iterator, list);
  1505. if (list.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  1506. codegen.generator->pop_temporary();
  1507. }
  1508. gen->write_for();
  1509. error = _parse_block(codegen, for_n->loop);
  1510. if (error) {
  1511. return error;
  1512. }
  1513. gen->write_endfor();
  1514. codegen.end_block();
  1515. } break;
  1516. case GDScriptParser::Node::WHILE: {
  1517. const GDScriptParser::WhileNode *while_n = static_cast<const GDScriptParser::WhileNode *>(s);
  1518. gen->start_while_condition();
  1519. GDScriptCodeGenerator::Address condition = _parse_expression(codegen, error, while_n->condition);
  1520. if (error) {
  1521. return error;
  1522. }
  1523. gen->write_while(condition);
  1524. if (condition.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  1525. codegen.generator->pop_temporary();
  1526. }
  1527. error = _parse_block(codegen, while_n->loop);
  1528. if (error) {
  1529. return error;
  1530. }
  1531. gen->write_endwhile();
  1532. } break;
  1533. case GDScriptParser::Node::BREAK: {
  1534. gen->write_break();
  1535. } break;
  1536. case GDScriptParser::Node::CONTINUE: {
  1537. const GDScriptParser::ContinueNode *cont = static_cast<const GDScriptParser::ContinueNode *>(s);
  1538. if (cont->is_for_match) {
  1539. gen->write_continue_match();
  1540. } else {
  1541. gen->write_continue();
  1542. }
  1543. } break;
  1544. case GDScriptParser::Node::RETURN: {
  1545. const GDScriptParser::ReturnNode *return_n = static_cast<const GDScriptParser::ReturnNode *>(s);
  1546. GDScriptCodeGenerator::Address return_value;
  1547. if (return_n->return_value != nullptr) {
  1548. return_value = _parse_expression(codegen, error, return_n->return_value);
  1549. if (error) {
  1550. return error;
  1551. }
  1552. }
  1553. gen->write_return(return_value);
  1554. if (return_value.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  1555. codegen.generator->pop_temporary();
  1556. }
  1557. } break;
  1558. case GDScriptParser::Node::ASSERT: {
  1559. #ifdef DEBUG_ENABLED
  1560. const GDScriptParser::AssertNode *as = static_cast<const GDScriptParser::AssertNode *>(s);
  1561. GDScriptCodeGenerator::Address condition = _parse_expression(codegen, error, as->condition);
  1562. if (error) {
  1563. return error;
  1564. }
  1565. GDScriptCodeGenerator::Address message;
  1566. if (as->message) {
  1567. message = _parse_expression(codegen, error, as->message);
  1568. if (error) {
  1569. return error;
  1570. }
  1571. }
  1572. gen->write_assert(condition, message);
  1573. if (condition.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  1574. codegen.generator->pop_temporary();
  1575. }
  1576. if (message.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  1577. codegen.generator->pop_temporary();
  1578. }
  1579. #endif
  1580. } break;
  1581. case GDScriptParser::Node::BREAKPOINT: {
  1582. #ifdef DEBUG_ENABLED
  1583. gen->write_breakpoint();
  1584. #endif
  1585. } break;
  1586. case GDScriptParser::Node::VARIABLE: {
  1587. const GDScriptParser::VariableNode *lv = static_cast<const GDScriptParser::VariableNode *>(s);
  1588. // Should be already in stack when the block began.
  1589. GDScriptCodeGenerator::Address local = codegen.locals[lv->identifier->name];
  1590. GDScriptParser::DataType local_type = lv->get_datatype();
  1591. if (lv->initializer != nullptr) {
  1592. // For typed arrays we need to make sure this is already initialized correctly so typed assignment work.
  1593. if (local_type.is_hard_type() && local_type.builtin_type == Variant::ARRAY) {
  1594. if (local_type.has_container_element_type()) {
  1595. codegen.generator->write_construct_typed_array(local, _gdtype_from_datatype(local_type.get_container_element_type(), codegen.script), Vector<GDScriptCodeGenerator::Address>());
  1596. } else {
  1597. codegen.generator->write_construct_array(local, Vector<GDScriptCodeGenerator::Address>());
  1598. }
  1599. }
  1600. GDScriptCodeGenerator::Address src_address = _parse_expression(codegen, error, lv->initializer);
  1601. if (error) {
  1602. return error;
  1603. }
  1604. if (lv->use_conversion_assign) {
  1605. gen->write_assign_with_conversion(local, src_address);
  1606. } else {
  1607. gen->write_assign(local, src_address);
  1608. }
  1609. if (src_address.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  1610. codegen.generator->pop_temporary();
  1611. }
  1612. } else if (lv->get_datatype().is_hard_type()) {
  1613. // Initialize with default for type.
  1614. if (local_type.has_container_element_type()) {
  1615. codegen.generator->write_construct_typed_array(local, _gdtype_from_datatype(local_type.get_container_element_type(), codegen.script), Vector<GDScriptCodeGenerator::Address>());
  1616. } else if (local_type.kind == GDScriptParser::DataType::BUILTIN) {
  1617. codegen.generator->write_construct(local, local_type.builtin_type, Vector<GDScriptCodeGenerator::Address>());
  1618. }
  1619. // The `else` branch is for objects, in such case we leave it as `null`.
  1620. }
  1621. } break;
  1622. case GDScriptParser::Node::CONSTANT: {
  1623. // Local constants.
  1624. const GDScriptParser::ConstantNode *lc = static_cast<const GDScriptParser::ConstantNode *>(s);
  1625. if (!lc->initializer->is_constant) {
  1626. _set_error("Local constant must have a constant value as initializer.", lc->initializer);
  1627. return ERR_PARSE_ERROR;
  1628. }
  1629. codegen.add_local_constant(lc->identifier->name, lc->initializer->reduced_value);
  1630. } break;
  1631. case GDScriptParser::Node::PASS:
  1632. // Nothing to do.
  1633. break;
  1634. default: {
  1635. // Expression.
  1636. if (s->is_expression()) {
  1637. GDScriptCodeGenerator::Address expr = _parse_expression(codegen, error, static_cast<const GDScriptParser::ExpressionNode *>(s), true);
  1638. if (error) {
  1639. return error;
  1640. }
  1641. if (expr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  1642. codegen.generator->pop_temporary();
  1643. }
  1644. } else {
  1645. ERR_FAIL_V_MSG(ERR_INVALID_DATA, "Bug in bytecode compiler, unexpected node in parse tree while parsing statement."); // Unreachable code.
  1646. }
  1647. } break;
  1648. }
  1649. }
  1650. codegen.end_block();
  1651. return OK;
  1652. }
  1653. GDScriptFunction *GDScriptCompiler::_parse_function(Error &r_error, GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::FunctionNode *p_func, bool p_for_ready, bool p_for_lambda) {
  1654. r_error = OK;
  1655. CodeGen codegen;
  1656. codegen.generator = memnew(GDScriptByteCodeGenerator);
  1657. codegen.class_node = p_class;
  1658. codegen.script = p_script;
  1659. codegen.function_node = p_func;
  1660. StringName func_name;
  1661. bool is_static = false;
  1662. Multiplayer::RPCConfig rpc_config;
  1663. GDScriptDataType return_type;
  1664. return_type.has_type = true;
  1665. return_type.kind = GDScriptDataType::BUILTIN;
  1666. return_type.builtin_type = Variant::NIL;
  1667. if (p_func) {
  1668. if (p_func->identifier) {
  1669. func_name = p_func->identifier->name;
  1670. } else {
  1671. func_name = "<anonymous lambda>";
  1672. }
  1673. is_static = p_func->is_static;
  1674. rpc_config = p_func->rpc_config;
  1675. return_type = _gdtype_from_datatype(p_func->get_datatype(), p_script);
  1676. } else {
  1677. if (p_for_ready) {
  1678. func_name = "_ready";
  1679. } else {
  1680. func_name = "@implicit_new";
  1681. }
  1682. }
  1683. codegen.function_name = func_name;
  1684. codegen.generator->write_start(p_script, func_name, is_static, rpc_config, return_type);
  1685. int optional_parameters = 0;
  1686. if (p_func) {
  1687. for (int i = 0; i < p_func->parameters.size(); i++) {
  1688. const GDScriptParser::ParameterNode *parameter = p_func->parameters[i];
  1689. GDScriptDataType par_type = _gdtype_from_datatype(parameter->get_datatype(), p_script);
  1690. uint32_t par_addr = codegen.generator->add_parameter(parameter->identifier->name, parameter->default_value != nullptr, par_type);
  1691. codegen.parameters[parameter->identifier->name] = GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::FUNCTION_PARAMETER, par_addr, par_type);
  1692. if (p_func->parameters[i]->default_value != nullptr) {
  1693. optional_parameters++;
  1694. }
  1695. }
  1696. }
  1697. // Parse initializer if applies.
  1698. bool is_implicit_initializer = !p_for_ready && !p_func && !p_for_lambda;
  1699. bool is_initializer = p_func && !p_for_lambda && String(p_func->identifier->name) == GDScriptLanguage::get_singleton()->strings._init;
  1700. bool is_for_ready = p_for_ready || (p_func && !p_for_lambda && String(p_func->identifier->name) == "_ready");
  1701. if (!p_for_lambda && (is_implicit_initializer || is_for_ready)) {
  1702. // Initialize class fields.
  1703. for (int i = 0; i < p_class->members.size(); i++) {
  1704. if (p_class->members[i].type != GDScriptParser::ClassNode::Member::VARIABLE) {
  1705. continue;
  1706. }
  1707. const GDScriptParser::VariableNode *field = p_class->members[i].variable;
  1708. if (field->onready != is_for_ready) {
  1709. // Only initialize in _ready.
  1710. continue;
  1711. }
  1712. GDScriptParser::DataType field_type = field->get_datatype();
  1713. GDScriptCodeGenerator::Address dst_address(GDScriptCodeGenerator::Address::MEMBER, codegen.script->member_indices[field->identifier->name].index, _gdtype_from_datatype(field->get_datatype()));
  1714. if (field->initializer) {
  1715. // Emit proper line change.
  1716. codegen.generator->write_newline(field->initializer->start_line);
  1717. // For typed arrays we need to make sure this is already initialized correctly so typed assignment work.
  1718. if (field_type.is_hard_type() && field_type.builtin_type == Variant::ARRAY && field_type.has_container_element_type()) {
  1719. if (field_type.has_container_element_type()) {
  1720. codegen.generator->write_construct_typed_array(dst_address, _gdtype_from_datatype(field_type.get_container_element_type(), codegen.script), Vector<GDScriptCodeGenerator::Address>());
  1721. } else {
  1722. codegen.generator->write_construct_array(dst_address, Vector<GDScriptCodeGenerator::Address>());
  1723. }
  1724. }
  1725. GDScriptCodeGenerator::Address src_address = _parse_expression(codegen, r_error, field->initializer, false, true);
  1726. if (r_error) {
  1727. memdelete(codegen.generator);
  1728. return nullptr;
  1729. }
  1730. if (field->use_conversion_assign) {
  1731. codegen.generator->write_assign_with_conversion(dst_address, src_address);
  1732. } else {
  1733. codegen.generator->write_assign(dst_address, src_address);
  1734. }
  1735. if (src_address.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  1736. codegen.generator->pop_temporary();
  1737. }
  1738. } else if (field->get_datatype().is_hard_type()) {
  1739. codegen.generator->write_newline(field->start_line);
  1740. // Initialize with default for type.
  1741. if (field_type.has_container_element_type()) {
  1742. codegen.generator->write_construct_typed_array(dst_address, _gdtype_from_datatype(field_type.get_container_element_type(), codegen.script), Vector<GDScriptCodeGenerator::Address>());
  1743. } else if (field_type.kind == GDScriptParser::DataType::BUILTIN) {
  1744. codegen.generator->write_construct(dst_address, field_type.builtin_type, Vector<GDScriptCodeGenerator::Address>());
  1745. }
  1746. // The `else` branch is for objects, in such case we leave it as `null`.
  1747. }
  1748. }
  1749. }
  1750. // Parse default argument code if applies.
  1751. if (p_func) {
  1752. if (optional_parameters > 0) {
  1753. codegen.generator->start_parameters();
  1754. for (int i = p_func->parameters.size() - optional_parameters; i < p_func->parameters.size(); i++) {
  1755. const GDScriptParser::ParameterNode *parameter = p_func->parameters[i];
  1756. GDScriptCodeGenerator::Address src_addr = _parse_expression(codegen, r_error, parameter->default_value);
  1757. if (r_error) {
  1758. memdelete(codegen.generator);
  1759. return nullptr;
  1760. }
  1761. GDScriptCodeGenerator::Address dst_addr = codegen.parameters[parameter->identifier->name];
  1762. codegen.generator->write_assign_default_parameter(dst_addr, src_addr);
  1763. if (src_addr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
  1764. codegen.generator->pop_temporary();
  1765. }
  1766. }
  1767. codegen.generator->end_parameters();
  1768. }
  1769. r_error = _parse_block(codegen, p_func->body);
  1770. if (r_error) {
  1771. memdelete(codegen.generator);
  1772. return nullptr;
  1773. }
  1774. }
  1775. #ifdef DEBUG_ENABLED
  1776. if (EngineDebugger::is_active()) {
  1777. String signature;
  1778. // Path.
  1779. if (!p_script->get_path().is_empty()) {
  1780. signature += p_script->get_path();
  1781. }
  1782. // Location.
  1783. if (p_func) {
  1784. signature += "::" + itos(p_func->body->start_line);
  1785. } else {
  1786. signature += "::0";
  1787. }
  1788. // Function and class.
  1789. if (p_class->identifier) {
  1790. signature += "::" + String(p_class->identifier->name) + "." + String(func_name);
  1791. } else {
  1792. signature += "::" + String(func_name);
  1793. }
  1794. if (p_for_lambda) {
  1795. signature += "(lambda)";
  1796. }
  1797. codegen.generator->set_signature(signature);
  1798. }
  1799. #endif
  1800. if (p_func) {
  1801. codegen.generator->set_initial_line(p_func->start_line);
  1802. #ifdef TOOLS_ENABLED
  1803. if (!p_for_lambda) {
  1804. p_script->member_lines[func_name] = p_func->start_line;
  1805. p_script->doc_functions[func_name] = p_func->doc_description;
  1806. }
  1807. #endif
  1808. } else {
  1809. codegen.generator->set_initial_line(0);
  1810. }
  1811. GDScriptFunction *gd_function = codegen.generator->write_end();
  1812. if (is_initializer) {
  1813. p_script->initializer = gd_function;
  1814. } else if (is_implicit_initializer) {
  1815. p_script->implicit_initializer = gd_function;
  1816. }
  1817. if (p_func) {
  1818. // if no return statement -> return type is void not unresolved Variant
  1819. if (p_func->body->has_return) {
  1820. gd_function->return_type = _gdtype_from_datatype(p_func->get_datatype(), p_script);
  1821. } else {
  1822. gd_function->return_type = GDScriptDataType();
  1823. gd_function->return_type.has_type = true;
  1824. gd_function->return_type.kind = GDScriptDataType::BUILTIN;
  1825. gd_function->return_type.builtin_type = Variant::NIL;
  1826. }
  1827. #ifdef TOOLS_ENABLED
  1828. gd_function->default_arg_values = p_func->default_arg_values;
  1829. #endif
  1830. }
  1831. if (!p_for_lambda) {
  1832. p_script->member_functions[func_name] = gd_function;
  1833. }
  1834. memdelete(codegen.generator);
  1835. return gd_function;
  1836. }
  1837. Error GDScriptCompiler::_parse_setter_getter(GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::VariableNode *p_variable, bool p_is_setter) {
  1838. Error error = OK;
  1839. GDScriptParser::FunctionNode *function;
  1840. if (p_is_setter) {
  1841. function = p_variable->setter;
  1842. } else {
  1843. function = p_variable->getter;
  1844. }
  1845. _parse_function(error, p_script, p_class, function);
  1846. return error;
  1847. }
  1848. Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) {
  1849. parsing_classes.insert(p_script);
  1850. if (p_class->outer && p_class->outer->outer) {
  1851. // Owner is not root
  1852. if (!parsed_classes.has(p_script->_owner)) {
  1853. if (parsing_classes.has(p_script->_owner)) {
  1854. _set_error("Cyclic class reference for '" + String(p_class->identifier->name) + "'.", p_class);
  1855. return ERR_PARSE_ERROR;
  1856. }
  1857. Error err = _parse_class_level(p_script->_owner, p_class->outer, p_keep_state);
  1858. if (err) {
  1859. return err;
  1860. }
  1861. }
  1862. }
  1863. #ifdef TOOLS_ENABLED
  1864. p_script->doc_functions.clear();
  1865. p_script->doc_variables.clear();
  1866. p_script->doc_constants.clear();
  1867. p_script->doc_enums.clear();
  1868. p_script->doc_signals.clear();
  1869. p_script->doc_tutorials.clear();
  1870. p_script->doc_brief_description = p_class->doc_brief_description;
  1871. p_script->doc_description = p_class->doc_description;
  1872. for (int i = 0; i < p_class->doc_tutorials.size(); i++) {
  1873. DocData::TutorialDoc td;
  1874. td.title = p_class->doc_tutorials[i].first;
  1875. td.link = p_class->doc_tutorials[i].second;
  1876. p_script->doc_tutorials.append(td);
  1877. }
  1878. #endif
  1879. p_script->native = Ref<GDScriptNativeClass>();
  1880. p_script->base = Ref<GDScript>();
  1881. p_script->_base = nullptr;
  1882. p_script->members.clear();
  1883. p_script->constants.clear();
  1884. for (const KeyValue<StringName, GDScriptFunction *> &E : p_script->member_functions) {
  1885. memdelete(E.value);
  1886. }
  1887. p_script->member_functions.clear();
  1888. p_script->member_indices.clear();
  1889. p_script->member_info.clear();
  1890. p_script->_signals.clear();
  1891. p_script->initializer = nullptr;
  1892. p_script->tool = parser->is_tool();
  1893. p_script->name = p_class->identifier ? p_class->identifier->name : "";
  1894. if (!p_script->name.is_empty()) {
  1895. if (ClassDB::class_exists(p_script->name) && ClassDB::is_class_exposed(p_script->name)) {
  1896. _set_error("The class '" + p_script->name + "' shadows a native class", p_class);
  1897. return ERR_ALREADY_EXISTS;
  1898. }
  1899. }
  1900. Ref<GDScriptNativeClass> native;
  1901. GDScriptDataType base_type = _gdtype_from_datatype(p_class->base_type);
  1902. // Inheritance
  1903. switch (base_type.kind) {
  1904. case GDScriptDataType::NATIVE: {
  1905. int native_idx = GDScriptLanguage::get_singleton()->get_global_map()[base_type.native_type];
  1906. native = GDScriptLanguage::get_singleton()->get_global_array()[native_idx];
  1907. ERR_FAIL_COND_V(native.is_null(), ERR_BUG);
  1908. p_script->native = native;
  1909. } break;
  1910. case GDScriptDataType::GDSCRIPT: {
  1911. Ref<GDScript> base = Ref<GDScript>(base_type.script_type);
  1912. p_script->base = base;
  1913. p_script->_base = base.ptr();
  1914. if (p_class->base_type.kind == GDScriptParser::DataType::CLASS && p_class->base_type.class_type != nullptr) {
  1915. if (p_class->base_type.script_path == main_script->path) {
  1916. if (!parsed_classes.has(p_script->_base)) {
  1917. if (parsing_classes.has(p_script->_base)) {
  1918. String class_name = p_class->identifier ? p_class->identifier->name : "<main>";
  1919. _set_error("Cyclic class reference for '" + class_name + "'.", p_class);
  1920. return ERR_PARSE_ERROR;
  1921. }
  1922. Error err = _parse_class_level(p_script->_base, p_class->base_type.class_type, p_keep_state);
  1923. if (err) {
  1924. return err;
  1925. }
  1926. }
  1927. } else {
  1928. Error err = OK;
  1929. base = GDScriptCache::get_full_script(p_class->base_type.script_path, err, main_script->path);
  1930. if (err) {
  1931. return err;
  1932. }
  1933. if (base.is_null() || !base->is_valid()) {
  1934. return ERR_COMPILATION_FAILED;
  1935. }
  1936. }
  1937. }
  1938. p_script->member_indices = base->member_indices;
  1939. native = base->native;
  1940. p_script->native = native;
  1941. } break;
  1942. default: {
  1943. _set_error("Parser bug: invalid inheritance.", p_class);
  1944. return ERR_BUG;
  1945. } break;
  1946. }
  1947. for (int i = 0; i < p_class->members.size(); i++) {
  1948. const GDScriptParser::ClassNode::Member &member = p_class->members[i];
  1949. switch (member.type) {
  1950. case GDScriptParser::ClassNode::Member::VARIABLE: {
  1951. const GDScriptParser::VariableNode *variable = member.variable;
  1952. StringName name = variable->identifier->name;
  1953. GDScript::MemberInfo minfo;
  1954. minfo.index = p_script->member_indices.size();
  1955. switch (variable->property) {
  1956. case GDScriptParser::VariableNode::PROP_NONE:
  1957. break; // Nothing to do.
  1958. case GDScriptParser::VariableNode::PROP_SETGET:
  1959. if (variable->setter_pointer != nullptr) {
  1960. minfo.setter = variable->setter_pointer->name;
  1961. }
  1962. if (variable->getter_pointer != nullptr) {
  1963. minfo.getter = variable->getter_pointer->name;
  1964. }
  1965. break;
  1966. case GDScriptParser::VariableNode::PROP_INLINE:
  1967. if (variable->setter != nullptr) {
  1968. minfo.setter = "@" + variable->identifier->name + "_setter";
  1969. }
  1970. if (variable->getter != nullptr) {
  1971. minfo.getter = "@" + variable->identifier->name + "_getter";
  1972. }
  1973. break;
  1974. }
  1975. minfo.data_type = _gdtype_from_datatype(variable->get_datatype(), p_script);
  1976. PropertyInfo prop_info = minfo.data_type;
  1977. prop_info.name = name;
  1978. PropertyInfo export_info = variable->export_info;
  1979. if (variable->exported) {
  1980. if (!minfo.data_type.has_type) {
  1981. prop_info.type = export_info.type;
  1982. prop_info.class_name = export_info.class_name;
  1983. }
  1984. prop_info.hint = export_info.hint;
  1985. prop_info.hint_string = export_info.hint_string;
  1986. prop_info.usage = export_info.usage | PROPERTY_USAGE_SCRIPT_VARIABLE;
  1987. } else {
  1988. prop_info.usage = PROPERTY_USAGE_SCRIPT_VARIABLE;
  1989. }
  1990. #ifdef TOOLS_ENABLED
  1991. p_script->doc_variables[name] = variable->doc_description;
  1992. #endif
  1993. p_script->member_info[name] = prop_info;
  1994. p_script->member_indices[name] = minfo;
  1995. p_script->members.insert(name);
  1996. #ifdef TOOLS_ENABLED
  1997. if (variable->initializer != nullptr && variable->initializer->is_constant) {
  1998. p_script->member_default_values[name] = variable->initializer->reduced_value;
  1999. } else {
  2000. p_script->member_default_values.erase(name);
  2001. }
  2002. p_script->member_lines[name] = variable->start_line;
  2003. #endif
  2004. } break;
  2005. case GDScriptParser::ClassNode::Member::CONSTANT: {
  2006. const GDScriptParser::ConstantNode *constant = member.constant;
  2007. StringName name = constant->identifier->name;
  2008. p_script->constants.insert(name, constant->initializer->reduced_value);
  2009. #ifdef TOOLS_ENABLED
  2010. p_script->member_lines[name] = constant->start_line;
  2011. if (!constant->doc_description.is_empty()) {
  2012. p_script->doc_constants[name] = constant->doc_description;
  2013. }
  2014. #endif
  2015. } break;
  2016. case GDScriptParser::ClassNode::Member::ENUM_VALUE: {
  2017. const GDScriptParser::EnumNode::Value &enum_value = member.enum_value;
  2018. StringName name = enum_value.identifier->name;
  2019. p_script->constants.insert(name, enum_value.value);
  2020. #ifdef TOOLS_ENABLED
  2021. p_script->member_lines[name] = enum_value.identifier->start_line;
  2022. if (!p_script->doc_enums.has("@unnamed_enums")) {
  2023. p_script->doc_enums["@unnamed_enums"] = DocData::EnumDoc();
  2024. p_script->doc_enums["@unnamed_enums"].name = "@unnamed_enums";
  2025. }
  2026. DocData::ConstantDoc const_doc;
  2027. const_doc.name = enum_value.identifier->name;
  2028. const_doc.value = Variant(enum_value.value).operator String(); // TODO-DOC: enum value currently is int.
  2029. const_doc.description = enum_value.doc_description;
  2030. p_script->doc_enums["@unnamed_enums"].values.push_back(const_doc);
  2031. #endif
  2032. } break;
  2033. case GDScriptParser::ClassNode::Member::SIGNAL: {
  2034. const GDScriptParser::SignalNode *signal = member.signal;
  2035. StringName name = signal->identifier->name;
  2036. Vector<StringName> parameters_names;
  2037. parameters_names.resize(signal->parameters.size());
  2038. for (int j = 0; j < signal->parameters.size(); j++) {
  2039. parameters_names.write[j] = signal->parameters[j]->identifier->name;
  2040. }
  2041. p_script->_signals[name] = parameters_names;
  2042. #ifdef TOOLS_ENABLED
  2043. if (!signal->doc_description.is_empty()) {
  2044. p_script->doc_signals[name] = signal->doc_description;
  2045. }
  2046. #endif
  2047. } break;
  2048. case GDScriptParser::ClassNode::Member::ENUM: {
  2049. const GDScriptParser::EnumNode *enum_n = member.m_enum;
  2050. // TODO: Make enums not be just a dictionary?
  2051. Dictionary new_enum;
  2052. for (int j = 0; j < enum_n->values.size(); j++) {
  2053. int value = enum_n->values[j].value;
  2054. // Needs to be string because Variant::get will convert to String.
  2055. new_enum[String(enum_n->values[j].identifier->name)] = value;
  2056. }
  2057. p_script->constants.insert(enum_n->identifier->name, new_enum);
  2058. #ifdef TOOLS_ENABLED
  2059. p_script->member_lines[enum_n->identifier->name] = enum_n->start_line;
  2060. p_script->doc_enums[enum_n->identifier->name] = DocData::EnumDoc();
  2061. p_script->doc_enums[enum_n->identifier->name].name = enum_n->identifier->name;
  2062. p_script->doc_enums[enum_n->identifier->name].description = enum_n->doc_description;
  2063. for (int j = 0; j < enum_n->values.size(); j++) {
  2064. DocData::ConstantDoc const_doc;
  2065. const_doc.name = enum_n->values[j].identifier->name;
  2066. const_doc.value = Variant(enum_n->values[j].value).operator String();
  2067. const_doc.description = enum_n->values[j].doc_description;
  2068. p_script->doc_enums[enum_n->identifier->name].values.push_back(const_doc);
  2069. }
  2070. #endif
  2071. } break;
  2072. default:
  2073. break; // Nothing to do here.
  2074. }
  2075. }
  2076. parsed_classes.insert(p_script);
  2077. parsing_classes.erase(p_script);
  2078. //parse sub-classes
  2079. for (int i = 0; i < p_class->members.size(); i++) {
  2080. const GDScriptParser::ClassNode::Member &member = p_class->members[i];
  2081. if (member.type != member.CLASS) {
  2082. continue;
  2083. }
  2084. const GDScriptParser::ClassNode *inner_class = member.m_class;
  2085. StringName name = inner_class->identifier->name;
  2086. Ref<GDScript> &subclass = p_script->subclasses[name];
  2087. GDScript *subclass_ptr = subclass.ptr();
  2088. // Subclass might still be parsing, just skip it
  2089. if (!parsed_classes.has(subclass_ptr) && !parsing_classes.has(subclass_ptr)) {
  2090. Error err = _parse_class_level(subclass_ptr, inner_class, p_keep_state);
  2091. if (err) {
  2092. return err;
  2093. }
  2094. }
  2095. #ifdef TOOLS_ENABLED
  2096. p_script->member_lines[name] = inner_class->start_line;
  2097. #endif
  2098. p_script->constants.insert(name, subclass); //once parsed, goes to the list of constants
  2099. }
  2100. return OK;
  2101. }
  2102. Error GDScriptCompiler::_parse_class_blocks(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) {
  2103. //parse methods
  2104. bool has_ready = false;
  2105. for (int i = 0; i < p_class->members.size(); i++) {
  2106. const GDScriptParser::ClassNode::Member &member = p_class->members[i];
  2107. if (member.type == member.FUNCTION) {
  2108. const GDScriptParser::FunctionNode *function = member.function;
  2109. if (!has_ready && function->identifier->name == "_ready") {
  2110. has_ready = true;
  2111. }
  2112. Error err = OK;
  2113. _parse_function(err, p_script, p_class, function);
  2114. if (err) {
  2115. return err;
  2116. }
  2117. } else if (member.type == member.VARIABLE) {
  2118. const GDScriptParser::VariableNode *variable = member.variable;
  2119. if (variable->property == GDScriptParser::VariableNode::PROP_INLINE) {
  2120. if (variable->setter != nullptr) {
  2121. Error err = _parse_setter_getter(p_script, p_class, variable, true);
  2122. if (err) {
  2123. return err;
  2124. }
  2125. }
  2126. if (variable->getter != nullptr) {
  2127. Error err = _parse_setter_getter(p_script, p_class, variable, false);
  2128. if (err) {
  2129. return err;
  2130. }
  2131. }
  2132. }
  2133. }
  2134. }
  2135. {
  2136. // Create an implicit constructor in any case.
  2137. Error err = OK;
  2138. _parse_function(err, p_script, p_class, nullptr);
  2139. if (err) {
  2140. return err;
  2141. }
  2142. }
  2143. if (!has_ready && p_class->onready_used) {
  2144. //create a _ready constructor
  2145. Error err = OK;
  2146. _parse_function(err, p_script, p_class, nullptr, true);
  2147. if (err) {
  2148. return err;
  2149. }
  2150. }
  2151. #ifdef DEBUG_ENABLED
  2152. //validate instances if keeping state
  2153. if (p_keep_state) {
  2154. for (Set<Object *>::Element *E = p_script->instances.front(); E;) {
  2155. Set<Object *>::Element *N = E->next();
  2156. ScriptInstance *si = E->get()->get_script_instance();
  2157. if (si->is_placeholder()) {
  2158. #ifdef TOOLS_ENABLED
  2159. PlaceHolderScriptInstance *psi = static_cast<PlaceHolderScriptInstance *>(si);
  2160. if (p_script->is_tool()) {
  2161. //re-create as an instance
  2162. p_script->placeholders.erase(psi); //remove placeholder
  2163. GDScriptInstance *instance = memnew(GDScriptInstance);
  2164. instance->base_ref_counted = Object::cast_to<RefCounted>(E->get());
  2165. instance->members.resize(p_script->member_indices.size());
  2166. instance->script = Ref<GDScript>(p_script);
  2167. instance->owner = E->get();
  2168. //needed for hot reloading
  2169. for (const KeyValue<StringName, GDScript::MemberInfo> &F : p_script->member_indices) {
  2170. instance->member_indices_cache[F.key] = F.value.index;
  2171. }
  2172. instance->owner->set_script_instance(instance);
  2173. /* STEP 2, INITIALIZE AND CONSTRUCT */
  2174. Callable::CallError ce;
  2175. p_script->initializer->call(instance, nullptr, 0, ce);
  2176. if (ce.error != Callable::CallError::CALL_OK) {
  2177. //well, tough luck, not gonna do anything here
  2178. }
  2179. }
  2180. #endif
  2181. } else {
  2182. GDScriptInstance *gi = static_cast<GDScriptInstance *>(si);
  2183. gi->reload_members();
  2184. }
  2185. E = N;
  2186. }
  2187. }
  2188. #endif
  2189. for (int i = 0; i < p_class->members.size(); i++) {
  2190. if (p_class->members[i].type != GDScriptParser::ClassNode::Member::CLASS) {
  2191. continue;
  2192. }
  2193. const GDScriptParser::ClassNode *inner_class = p_class->members[i].m_class;
  2194. StringName name = inner_class->identifier->name;
  2195. GDScript *subclass = p_script->subclasses[name].ptr();
  2196. Error err = _parse_class_blocks(subclass, inner_class, p_keep_state);
  2197. if (err) {
  2198. return err;
  2199. }
  2200. }
  2201. p_script->valid = true;
  2202. return OK;
  2203. }
  2204. void GDScriptCompiler::_make_scripts(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) {
  2205. Map<StringName, Ref<GDScript>> old_subclasses;
  2206. if (p_keep_state) {
  2207. old_subclasses = p_script->subclasses;
  2208. }
  2209. p_script->subclasses.clear();
  2210. for (int i = 0; i < p_class->members.size(); i++) {
  2211. if (p_class->members[i].type != GDScriptParser::ClassNode::Member::CLASS) {
  2212. continue;
  2213. }
  2214. const GDScriptParser::ClassNode *inner_class = p_class->members[i].m_class;
  2215. StringName name = inner_class->identifier->name;
  2216. Ref<GDScript> subclass;
  2217. String fully_qualified_name = p_script->fully_qualified_name + "::" + name;
  2218. if (old_subclasses.has(name)) {
  2219. subclass = old_subclasses[name];
  2220. } else {
  2221. Ref<GDScript> orphan_subclass = GDScriptLanguage::get_singleton()->get_orphan_subclass(fully_qualified_name);
  2222. if (orphan_subclass.is_valid()) {
  2223. subclass = orphan_subclass;
  2224. } else {
  2225. subclass.instantiate();
  2226. }
  2227. }
  2228. subclass->_owner = p_script;
  2229. subclass->fully_qualified_name = fully_qualified_name;
  2230. p_script->subclasses.insert(name, subclass);
  2231. _make_scripts(subclass.ptr(), inner_class, false);
  2232. }
  2233. }
  2234. Error GDScriptCompiler::compile(const GDScriptParser *p_parser, GDScript *p_script, bool p_keep_state) {
  2235. err_line = -1;
  2236. err_column = -1;
  2237. error = "";
  2238. parser = p_parser;
  2239. main_script = p_script;
  2240. const GDScriptParser::ClassNode *root = parser->get_tree();
  2241. source = p_script->get_path();
  2242. // The best fully qualified name for a base level script is its file path
  2243. p_script->fully_qualified_name = p_script->path;
  2244. // Create scripts for subclasses beforehand so they can be referenced
  2245. _make_scripts(p_script, root, p_keep_state);
  2246. p_script->_owner = nullptr;
  2247. Error err = _parse_class_level(p_script, root, p_keep_state);
  2248. if (err) {
  2249. return err;
  2250. }
  2251. err = _parse_class_blocks(p_script, root, p_keep_state);
  2252. if (err) {
  2253. return err;
  2254. }
  2255. return GDScriptCache::finish_compiling(p_script->get_path());
  2256. }
  2257. String GDScriptCompiler::get_error() const {
  2258. return error;
  2259. }
  2260. int GDScriptCompiler::get_error_line() const {
  2261. return err_line;
  2262. }
  2263. int GDScriptCompiler::get_error_column() const {
  2264. return err_column;
  2265. }
  2266. GDScriptCompiler::GDScriptCompiler() {
  2267. }