gdscript_compiler.cpp 87 KB

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