gdscript_compiler.cpp 98 KB

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