gdscript_compiler.cpp 96 KB

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