gdscript_compiler.cpp 86 KB

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