gdscript_compiler.cpp 90 KB

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