gdscript_compiler.cpp 96 KB

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