gdscript_compiler.cpp 83 KB

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