gdscript_compiler.cpp 115 KB

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