gd_script.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839
  1. /*************************************************************************/
  2. /* gd_script.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "gd_script.h"
  31. #include "gd_compiler.h"
  32. #include "global_constants.h"
  33. #include "globals.h"
  34. #include "io/file_access_encrypted.h"
  35. #include "os/file_access.h"
  36. #include "os/os.h"
  37. ///////////////////////////
  38. GDNativeClass::GDNativeClass(const StringName &p_name) {
  39. name = p_name;
  40. }
  41. /*void GDNativeClass::call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount){
  42. }*/
  43. bool GDNativeClass::_get(const StringName &p_name, Variant &r_ret) const {
  44. bool ok;
  45. int v = ObjectTypeDB::get_integer_constant(name, p_name, &ok);
  46. if (ok) {
  47. r_ret = v;
  48. return true;
  49. } else {
  50. return false;
  51. }
  52. }
  53. void GDNativeClass::_bind_methods() {
  54. ObjectTypeDB::bind_method(_MD("new"), &GDNativeClass::_new);
  55. }
  56. Variant GDNativeClass::_new() {
  57. Object *o = instance();
  58. if (!o) {
  59. ERR_EXPLAIN("Class type: '" + String(name) + "' is not instantiable.");
  60. ERR_FAIL_COND_V(!o, Variant());
  61. }
  62. Reference *ref = o->cast_to<Reference>();
  63. if (ref) {
  64. return REF(ref);
  65. } else {
  66. return o;
  67. }
  68. }
  69. Object *GDNativeClass::instance() {
  70. return ObjectTypeDB::instance(name);
  71. }
  72. GDInstance *GDScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Variant::CallError &r_error) {
  73. /* STEP 1, CREATE */
  74. GDInstance *instance = memnew(GDInstance);
  75. instance->base_ref = p_isref;
  76. instance->members.resize(member_indices.size());
  77. instance->script = Ref<GDScript>(this);
  78. instance->owner = p_owner;
  79. #ifdef DEBUG_ENABLED
  80. //needed for hot reloading
  81. for (Map<StringName, MemberInfo>::Element *E = member_indices.front(); E; E = E->next()) {
  82. instance->member_indices_cache[E->key()] = E->get().index;
  83. }
  84. #endif
  85. instance->owner->set_script_instance(instance);
  86. /* STEP 2, INITIALIZE AND CONSRTUCT */
  87. instances.insert(instance->owner);
  88. initializer->call(instance, p_args, p_argcount, r_error);
  89. if (r_error.error != Variant::CallError::CALL_OK) {
  90. instance->script = Ref<GDScript>();
  91. instance->owner->set_script_instance(NULL);
  92. instances.erase(p_owner);
  93. ERR_FAIL_COND_V(r_error.error != Variant::CallError::CALL_OK, NULL); //error constructing
  94. }
  95. //@TODO make thread safe
  96. return instance;
  97. }
  98. Variant GDScript::_new(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  99. /* STEP 1, CREATE */
  100. if (!valid) {
  101. r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
  102. return Variant();
  103. }
  104. r_error.error = Variant::CallError::CALL_OK;
  105. REF ref;
  106. Object *owner = NULL;
  107. GDScript *_baseptr = this;
  108. while (_baseptr->_base) {
  109. _baseptr = _baseptr->_base;
  110. }
  111. if (_baseptr->native.ptr()) {
  112. owner = _baseptr->native->instance();
  113. } else {
  114. owner = memnew(Reference); //by default, no base means use reference
  115. }
  116. Reference *r = owner->cast_to<Reference>();
  117. if (r) {
  118. ref = REF(r);
  119. }
  120. GDInstance *instance = _create_instance(p_args, p_argcount, owner, r != NULL, r_error);
  121. if (!instance) {
  122. if (ref.is_null()) {
  123. memdelete(owner); //no owner, sorry
  124. }
  125. return Variant();
  126. }
  127. if (ref.is_valid()) {
  128. return ref;
  129. } else {
  130. return owner;
  131. }
  132. }
  133. bool GDScript::can_instance() const {
  134. //return valid; //any script in GDscript can instance
  135. return valid || (!tool && !ScriptServer::is_scripting_enabled());
  136. }
  137. StringName GDScript::get_instance_base_type() const {
  138. if (native.is_valid())
  139. return native->get_name();
  140. if (base.is_valid())
  141. return base->get_instance_base_type();
  142. return StringName();
  143. }
  144. struct _GDScriptMemberSort {
  145. int index;
  146. StringName name;
  147. _FORCE_INLINE_ bool operator<(const _GDScriptMemberSort &p_member) const { return index < p_member.index; }
  148. };
  149. #ifdef TOOLS_ENABLED
  150. void GDScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
  151. placeholders.erase(p_placeholder);
  152. }
  153. /*
  154. void GDScript::_update_placeholder(PlaceHolderScriptInstance *p_placeholder) {
  155. List<PropertyInfo> plist;
  156. GDScript *scr=this;
  157. Map<StringName,Variant> default_values;
  158. while(scr) {
  159. Vector<_GDScriptMemberSort> msort;
  160. for(Map<StringName,PropertyInfo>::Element *E=scr->member_info.front();E;E=E->next()) {
  161. _GDScriptMemberSort ms;
  162. ERR_CONTINUE(!scr->member_indices.has(E->key()));
  163. ms.index=scr->member_indices[E->key()].index;
  164. ms.name=E->key();
  165. msort.push_back(ms);
  166. }
  167. msort.sort();
  168. msort.invert();
  169. for(int i=0;i<msort.size();i++) {
  170. plist.push_front(scr->member_info[msort[i].name]);
  171. if (scr->member_default_values.has(msort[i].name))
  172. default_values[msort[i].name]=scr->member_default_values[msort[i].name];
  173. else {
  174. Variant::CallError err;
  175. default_values[msort[i].name]=Variant::construct(scr->member_info[msort[i].name].type,NULL,0,err);
  176. }
  177. }
  178. scr=scr->_base;
  179. }
  180. p_placeholder->update(plist,default_values);
  181. }*/
  182. #endif
  183. bool GDScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
  184. #ifdef TOOLS_ENABLED
  185. //for (const Map<StringName,Variant>::Element *I=member_default_values.front();I;I=I->next()) {
  186. // print_line("\t"+String(String(I->key())+":"+String(I->get())));
  187. //}
  188. const Map<StringName, Variant>::Element *E = member_default_values_cache.find(p_property);
  189. if (E) {
  190. r_value = E->get();
  191. return true;
  192. }
  193. if (base_cache.is_valid()) {
  194. return base_cache->get_property_default_value(p_property, r_value);
  195. }
  196. #endif
  197. return false;
  198. }
  199. ScriptInstance *GDScript::instance_create(Object *p_this) {
  200. if (!tool && !ScriptServer::is_scripting_enabled()) {
  201. #ifdef TOOLS_ENABLED
  202. //instance a fake script for editing the values
  203. //plist.invert();
  204. /*print_line("CREATING PLACEHOLDER");
  205. for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
  206. print_line(E->get().name);
  207. }*/
  208. PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(GDScriptLanguage::get_singleton(), Ref<Script>(this), p_this));
  209. placeholders.insert(si);
  210. //_update_placeholder(si);
  211. _update_exports();
  212. return si;
  213. #else
  214. return NULL;
  215. #endif
  216. }
  217. GDScript *top = this;
  218. while (top->_base)
  219. top = top->_base;
  220. if (top->native.is_valid()) {
  221. if (!ObjectTypeDB::is_type(p_this->get_type_name(), top->native->get_name())) {
  222. if (ScriptDebugger::get_singleton()) {
  223. GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), 0, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be instanced in object of type: '" + p_this->get_type() + "'");
  224. }
  225. ERR_EXPLAIN("Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be instanced in object of type: '" + p_this->get_type() + "'");
  226. ERR_FAIL_V(NULL);
  227. }
  228. }
  229. Variant::CallError unchecked_error;
  230. return _create_instance(NULL, 0, p_this, p_this->cast_to<Reference>(), unchecked_error);
  231. }
  232. bool GDScript::instance_has(const Object *p_this) const {
  233. return instances.has((Object *)p_this);
  234. }
  235. bool GDScript::has_source_code() const {
  236. return source != "";
  237. }
  238. String GDScript::get_source_code() const {
  239. return source;
  240. }
  241. void GDScript::set_source_code(const String &p_code) {
  242. if (source == p_code)
  243. return;
  244. source = p_code;
  245. #ifdef TOOLS_ENABLED
  246. source_changed_cache = true;
  247. //print_line("SC CHANGED "+get_path());
  248. #endif
  249. }
  250. #ifdef TOOLS_ENABLED
  251. void GDScript::_update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames) {
  252. if (base_cache.is_valid()) {
  253. base_cache->_update_exports_values(values, propnames);
  254. }
  255. for (Map<StringName, Variant>::Element *E = member_default_values_cache.front(); E; E = E->next()) {
  256. values[E->key()] = E->get();
  257. }
  258. for (List<PropertyInfo>::Element *E = members_cache.front(); E; E = E->next()) {
  259. propnames.push_back(E->get());
  260. }
  261. }
  262. #endif
  263. bool GDScript::_update_exports() {
  264. #ifdef TOOLS_ENABLED
  265. bool changed = false;
  266. if (source_changed_cache) {
  267. //print_line("updating source for "+get_path());
  268. source_changed_cache = false;
  269. changed = true;
  270. String basedir = path;
  271. if (basedir == "")
  272. basedir = get_path();
  273. if (basedir != "")
  274. basedir = basedir.get_base_dir();
  275. GDParser parser;
  276. Error err = parser.parse(source, basedir, true, path);
  277. if (err == OK) {
  278. const GDParser::Node *root = parser.get_parse_tree();
  279. ERR_FAIL_COND_V(root->type != GDParser::Node::TYPE_CLASS, false);
  280. const GDParser::ClassNode *c = static_cast<const GDParser::ClassNode *>(root);
  281. if (base_cache.is_valid()) {
  282. base_cache->inheriters_cache.erase(get_instance_ID());
  283. base_cache = Ref<GDScript>();
  284. }
  285. if (c->extends_used && String(c->extends_file) != "" && String(c->extends_file) != get_path()) {
  286. String path = c->extends_file;
  287. if (path.is_rel_path()) {
  288. String base = get_path();
  289. if (base == "" || base.is_rel_path()) {
  290. ERR_PRINT(("Could not resolve relative path for parent class: " + path).utf8().get_data());
  291. } else {
  292. path = base.get_base_dir().plus_file(path);
  293. }
  294. }
  295. if (path != get_path()) {
  296. Ref<GDScript> bf = ResourceLoader::load(path);
  297. if (bf.is_valid()) {
  298. //print_line("parent is: "+bf->get_path());
  299. base_cache = bf;
  300. bf->inheriters_cache.insert(get_instance_ID());
  301. //bf->_update_exports(p_instances,true,false);
  302. }
  303. } else {
  304. ERR_PRINT(("Path extending itself in " + path).utf8().get_data());
  305. }
  306. }
  307. members_cache.clear();
  308. member_default_values_cache.clear();
  309. for (int i = 0; i < c->variables.size(); i++) {
  310. if (c->variables[i]._export.type == Variant::NIL)
  311. continue;
  312. members_cache.push_back(c->variables[i]._export);
  313. //print_line("found "+c->variables[i]._export.name);
  314. member_default_values_cache[c->variables[i].identifier] = c->variables[i].default_value;
  315. }
  316. _signals.clear();
  317. for (int i = 0; i < c->_signals.size(); i++) {
  318. _signals[c->_signals[i].name] = c->_signals[i].arguments;
  319. }
  320. }
  321. } else {
  322. //print_line("unchaged is "+get_path());
  323. }
  324. if (base_cache.is_valid()) {
  325. if (base_cache->_update_exports()) {
  326. changed = true;
  327. }
  328. }
  329. if (/*changed &&*/ placeholders.size()) { //hm :(
  330. //print_line("updating placeholders for "+get_path());
  331. //update placeholders if any
  332. Map<StringName, Variant> values;
  333. List<PropertyInfo> propnames;
  334. _update_exports_values(values, propnames);
  335. for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) {
  336. E->get()->update(propnames, values);
  337. }
  338. }
  339. return changed;
  340. #endif
  341. return false;
  342. }
  343. void GDScript::update_exports() {
  344. #ifdef TOOLS_ENABLED
  345. _update_exports();
  346. Set<ObjectID> copy = inheriters_cache; //might get modified
  347. //print_line("update exports for "+get_path()+" ic: "+itos(copy.size()));
  348. for (Set<ObjectID>::Element *E = copy.front(); E; E = E->next()) {
  349. Object *id = ObjectDB::get_instance(E->get());
  350. if (!id)
  351. continue;
  352. GDScript *s = id->cast_to<GDScript>();
  353. if (!s)
  354. continue;
  355. s->update_exports();
  356. }
  357. #endif
  358. }
  359. void GDScript::_set_subclass_path(Ref<GDScript> &p_sc, const String &p_path) {
  360. p_sc->path = p_path;
  361. for (Map<StringName, Ref<GDScript> >::Element *E = p_sc->subclasses.front(); E; E = E->next()) {
  362. _set_subclass_path(E->get(), p_path);
  363. }
  364. }
  365. Error GDScript::reload(bool p_keep_state) {
  366. ERR_FAIL_COND_V(!p_keep_state && instances.size(), ERR_ALREADY_IN_USE);
  367. String basedir = path;
  368. if (basedir == "")
  369. basedir = get_path();
  370. if (basedir != "")
  371. basedir = basedir.get_base_dir();
  372. valid = false;
  373. GDParser parser;
  374. Error err = parser.parse(source, basedir, false, path);
  375. if (err) {
  376. if (ScriptDebugger::get_singleton()) {
  377. GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), parser.get_error_line(), "Parser Error: " + parser.get_error());
  378. }
  379. _err_print_error("GDScript::reload", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), parser.get_error_line(), ("Parse Error: " + parser.get_error()).utf8().get_data(), ERR_HANDLER_SCRIPT);
  380. ERR_FAIL_V(ERR_PARSE_ERROR);
  381. }
  382. bool can_run = ScriptServer::is_scripting_enabled() || parser.is_tool_script();
  383. GDCompiler compiler;
  384. err = compiler.compile(&parser, this, p_keep_state);
  385. if (err) {
  386. if (can_run) {
  387. if (ScriptDebugger::get_singleton()) {
  388. GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), compiler.get_error_line(), "Parser Error: " + compiler.get_error());
  389. }
  390. _err_print_error("GDScript::reload", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), compiler.get_error_line(), ("Compile Error: " + compiler.get_error()).utf8().get_data(), ERR_HANDLER_SCRIPT);
  391. ERR_FAIL_V(ERR_COMPILATION_FAILED);
  392. } else {
  393. return err;
  394. }
  395. }
  396. valid = true;
  397. for (Map<StringName, Ref<GDScript> >::Element *E = subclasses.front(); E; E = E->next()) {
  398. _set_subclass_path(E->get(), path);
  399. }
  400. #ifdef TOOLS_ENABLED
  401. /*for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) {
  402. _update_placeholder(E->get());
  403. }*/
  404. #endif
  405. return OK;
  406. }
  407. String GDScript::get_node_type() const {
  408. return ""; // ?
  409. }
  410. ScriptLanguage *GDScript::get_language() const {
  411. return GDScriptLanguage::get_singleton();
  412. }
  413. Variant GDScript::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  414. GDScript *top = this;
  415. while (top) {
  416. Map<StringName, GDFunction *>::Element *E = top->member_functions.find(p_method);
  417. if (E) {
  418. if (!E->get()->is_static()) {
  419. WARN_PRINT(String("Can't call non-static function: '" + String(p_method) + "' in script.").utf8().get_data());
  420. }
  421. return E->get()->call(NULL, p_args, p_argcount, r_error);
  422. }
  423. top = top->_base;
  424. }
  425. //none found, regular
  426. return Script::call(p_method, p_args, p_argcount, r_error);
  427. }
  428. bool GDScript::_get(const StringName &p_name, Variant &r_ret) const {
  429. {
  430. const GDScript *top = this;
  431. while (top) {
  432. {
  433. const Map<StringName, Variant>::Element *E = top->constants.find(p_name);
  434. if (E) {
  435. r_ret = E->get();
  436. return true;
  437. }
  438. }
  439. {
  440. const Map<StringName, Ref<GDScript> >::Element *E = subclasses.find(p_name);
  441. if (E) {
  442. r_ret = E->get();
  443. return true;
  444. }
  445. }
  446. top = top->_base;
  447. }
  448. if (p_name == GDScriptLanguage::get_singleton()->strings._script_source) {
  449. r_ret = get_source_code();
  450. return true;
  451. }
  452. }
  453. return false;
  454. }
  455. bool GDScript::_set(const StringName &p_name, const Variant &p_value) {
  456. if (p_name == GDScriptLanguage::get_singleton()->strings._script_source) {
  457. set_source_code(p_value);
  458. reload();
  459. } else
  460. return false;
  461. return true;
  462. }
  463. void GDScript::_get_property_list(List<PropertyInfo> *p_properties) const {
  464. p_properties->push_back(PropertyInfo(Variant::STRING, "script/source", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
  465. }
  466. void GDScript::_bind_methods() {
  467. ObjectTypeDB::bind_native_method(METHOD_FLAGS_DEFAULT, "new", &GDScript::_new, MethodInfo("new"));
  468. ObjectTypeDB::bind_method(_MD("get_as_byte_code"), &GDScript::get_as_byte_code);
  469. }
  470. Vector<uint8_t> GDScript::get_as_byte_code() const {
  471. GDTokenizerBuffer tokenizer;
  472. return tokenizer.parse_code_string(source);
  473. };
  474. Error GDScript::load_byte_code(const String &p_path) {
  475. Vector<uint8_t> bytecode;
  476. if (p_path.ends_with("gde")) {
  477. FileAccess *fa = FileAccess::open(p_path, FileAccess::READ);
  478. ERR_FAIL_COND_V(!fa, ERR_CANT_OPEN);
  479. FileAccessEncrypted *fae = memnew(FileAccessEncrypted);
  480. ERR_FAIL_COND_V(!fae, ERR_CANT_OPEN);
  481. Vector<uint8_t> key;
  482. key.resize(32);
  483. for (int i = 0; i < key.size(); i++) {
  484. key[i] = script_encryption_key[i];
  485. }
  486. Error err = fae->open_and_parse(fa, key, FileAccessEncrypted::MODE_READ);
  487. ERR_FAIL_COND_V(err, err);
  488. bytecode.resize(fae->get_len());
  489. fae->get_buffer(bytecode.ptr(), bytecode.size());
  490. memdelete(fae);
  491. } else {
  492. bytecode = FileAccess::get_file_as_array(p_path);
  493. }
  494. ERR_FAIL_COND_V(bytecode.size() == 0, ERR_PARSE_ERROR);
  495. path = p_path;
  496. String basedir = path;
  497. if (basedir == "")
  498. basedir = get_path();
  499. if (basedir != "")
  500. basedir = basedir.get_base_dir();
  501. valid = false;
  502. GDParser parser;
  503. Error err = parser.parse_bytecode(bytecode, basedir, get_path());
  504. if (err) {
  505. _err_print_error("GDScript::load_byte_code", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), parser.get_error_line(), ("Parse Error: " + parser.get_error()).utf8().get_data(), ERR_HANDLER_SCRIPT);
  506. ERR_FAIL_V(ERR_PARSE_ERROR);
  507. }
  508. GDCompiler compiler;
  509. err = compiler.compile(&parser, this);
  510. if (err) {
  511. _err_print_error("GDScript::load_byte_code", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), compiler.get_error_line(), ("Compile Error: " + compiler.get_error()).utf8().get_data(), ERR_HANDLER_SCRIPT);
  512. ERR_FAIL_V(ERR_COMPILATION_FAILED);
  513. }
  514. valid = true;
  515. for (Map<StringName, Ref<GDScript> >::Element *E = subclasses.front(); E; E = E->next()) {
  516. _set_subclass_path(E->get(), path);
  517. }
  518. return OK;
  519. }
  520. Error GDScript::load_source_code(const String &p_path) {
  521. DVector<uint8_t> sourcef;
  522. Error err;
  523. FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
  524. if (err) {
  525. ERR_FAIL_COND_V(err, err);
  526. }
  527. int len = f->get_len();
  528. sourcef.resize(len + 1);
  529. DVector<uint8_t>::Write w = sourcef.write();
  530. int r = f->get_buffer(w.ptr(), len);
  531. f->close();
  532. memdelete(f);
  533. ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN);
  534. w[len] = 0;
  535. String s;
  536. if (s.parse_utf8((const char *)w.ptr())) {
  537. ERR_EXPLAIN("Script '" + p_path + "' contains invalid unicode (utf-8), so it was not loaded. Please ensure that scripts are saved in valid utf-8 unicode.");
  538. ERR_FAIL_V(ERR_INVALID_DATA);
  539. }
  540. source = s;
  541. #ifdef TOOLS_ENABLED
  542. source_changed_cache = true;
  543. #endif
  544. //print_line("LSC :"+get_path());
  545. path = p_path;
  546. return OK;
  547. }
  548. const Map<StringName, GDFunction *> &GDScript::debug_get_member_functions() const {
  549. return member_functions;
  550. }
  551. StringName GDScript::debug_get_member_by_index(int p_idx) const {
  552. for (const Map<StringName, MemberInfo>::Element *E = member_indices.front(); E; E = E->next()) {
  553. if (E->get().index == p_idx)
  554. return E->key();
  555. }
  556. return "<error>";
  557. }
  558. Ref<GDScript> GDScript::get_base() const {
  559. return base;
  560. }
  561. bool GDScript::has_script_signal(const StringName &p_signal) const {
  562. if (_signals.has(p_signal))
  563. return true;
  564. if (base.is_valid()) {
  565. return base->has_script_signal(p_signal);
  566. }
  567. #ifdef TOOLS_ENABLED
  568. else if (base_cache.is_valid()) {
  569. return base_cache->has_script_signal(p_signal);
  570. }
  571. #endif
  572. return false;
  573. }
  574. void GDScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
  575. for (const Map<StringName, Vector<StringName> >::Element *E = _signals.front(); E; E = E->next()) {
  576. MethodInfo mi;
  577. mi.name = E->key();
  578. for (int i = 0; i < E->get().size(); i++) {
  579. PropertyInfo arg;
  580. arg.name = E->get()[i];
  581. mi.arguments.push_back(arg);
  582. }
  583. r_signals->push_back(mi);
  584. }
  585. if (base.is_valid()) {
  586. base->get_script_signal_list(r_signals);
  587. }
  588. #ifdef TOOLS_ENABLED
  589. else if (base_cache.is_valid()) {
  590. base_cache->get_script_signal_list(r_signals);
  591. }
  592. #endif
  593. }
  594. GDScript::GDScript() :
  595. script_list(this) {
  596. _static_ref = this;
  597. valid = false;
  598. subclass_count = 0;
  599. initializer = NULL;
  600. _base = NULL;
  601. _owner = NULL;
  602. tool = false;
  603. #ifdef TOOLS_ENABLED
  604. source_changed_cache = false;
  605. #endif
  606. #ifdef DEBUG_ENABLED
  607. if (GDScriptLanguage::get_singleton()->lock) {
  608. GDScriptLanguage::get_singleton()->lock->lock();
  609. }
  610. GDScriptLanguage::get_singleton()->script_list.add(&script_list);
  611. if (GDScriptLanguage::get_singleton()->lock) {
  612. GDScriptLanguage::get_singleton()->lock->unlock();
  613. }
  614. #endif
  615. }
  616. GDScript::~GDScript() {
  617. for (Map<StringName, GDFunction *>::Element *E = member_functions.front(); E; E = E->next()) {
  618. memdelete(E->get());
  619. }
  620. for (Map<StringName, Ref<GDScript> >::Element *E = subclasses.front(); E; E = E->next()) {
  621. E->get()->_owner = NULL; //bye, you are no longer owned cause I died
  622. }
  623. #ifdef DEBUG_ENABLED
  624. if (GDScriptLanguage::get_singleton()->lock) {
  625. GDScriptLanguage::get_singleton()->lock->lock();
  626. }
  627. GDScriptLanguage::get_singleton()->script_list.remove(&script_list);
  628. if (GDScriptLanguage::get_singleton()->lock) {
  629. GDScriptLanguage::get_singleton()->lock->unlock();
  630. }
  631. #endif
  632. }
  633. //////////////////////////////
  634. // INSTANCE //
  635. //////////////////////////////
  636. bool GDInstance::set(const StringName &p_name, const Variant &p_value) {
  637. //member
  638. {
  639. const Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name);
  640. if (E) {
  641. if (E->get().setter) {
  642. const Variant *val = &p_value;
  643. Variant::CallError err;
  644. call(E->get().setter, &val, 1, err);
  645. if (err.error == Variant::CallError::CALL_OK) {
  646. return true; //function exists, call was successful
  647. }
  648. } else
  649. members[E->get().index] = p_value;
  650. return true;
  651. }
  652. }
  653. GDScript *sptr = script.ptr();
  654. while (sptr) {
  655. Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._set);
  656. if (E) {
  657. Variant name = p_name;
  658. const Variant *args[2] = { &name, &p_value };
  659. Variant::CallError err;
  660. Variant ret = E->get()->call(this, (const Variant **)args, 2, err);
  661. if (err.error == Variant::CallError::CALL_OK && ret.get_type() == Variant::BOOL && ret.operator bool())
  662. return true;
  663. }
  664. sptr = sptr->_base;
  665. }
  666. return false;
  667. }
  668. bool GDInstance::get(const StringName &p_name, Variant &r_ret) const {
  669. const GDScript *sptr = script.ptr();
  670. while (sptr) {
  671. {
  672. const Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name);
  673. if (E) {
  674. if (E->get().getter) {
  675. Variant::CallError err;
  676. r_ret = const_cast<GDInstance *>(this)->call(E->get().getter, NULL, 0, err);
  677. if (err.error == Variant::CallError::CALL_OK) {
  678. return true;
  679. }
  680. }
  681. r_ret = members[E->get().index];
  682. return true; //index found
  683. }
  684. }
  685. {
  686. const GDScript *sl = sptr;
  687. while (sl) {
  688. const Map<StringName, Variant>::Element *E = sl->constants.find(p_name);
  689. if (E) {
  690. r_ret = E->get();
  691. return true; //index found
  692. }
  693. sl = sl->_base;
  694. }
  695. }
  696. {
  697. const Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get);
  698. if (E) {
  699. Variant name = p_name;
  700. const Variant *args[1] = { &name };
  701. Variant::CallError err;
  702. Variant ret = const_cast<GDFunction *>(E->get())->call(const_cast<GDInstance *>(this), (const Variant **)args, 1, err);
  703. if (err.error == Variant::CallError::CALL_OK && ret.get_type() != Variant::NIL) {
  704. r_ret = ret;
  705. return true;
  706. }
  707. }
  708. }
  709. sptr = sptr->_base;
  710. }
  711. return false;
  712. }
  713. Variant::Type GDInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
  714. const GDScript *sptr = script.ptr();
  715. while (sptr) {
  716. if (sptr->member_info.has(p_name)) {
  717. if (r_is_valid)
  718. *r_is_valid = true;
  719. return sptr->member_info[p_name].type;
  720. }
  721. sptr = sptr->_base;
  722. }
  723. if (r_is_valid)
  724. *r_is_valid = false;
  725. return Variant::NIL;
  726. }
  727. void GDInstance::get_property_list(List<PropertyInfo> *p_properties) const {
  728. // exported members, not doen yet!
  729. const GDScript *sptr = script.ptr();
  730. List<PropertyInfo> props;
  731. while (sptr) {
  732. const Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get_property_list);
  733. if (E) {
  734. Variant::CallError err;
  735. Variant ret = const_cast<GDFunction *>(E->get())->call(const_cast<GDInstance *>(this), NULL, 0, err);
  736. if (err.error == Variant::CallError::CALL_OK) {
  737. if (ret.get_type() != Variant::ARRAY) {
  738. ERR_EXPLAIN("Wrong type for _get_property list, must be an array of dictionaries.");
  739. ERR_FAIL();
  740. }
  741. Array arr = ret;
  742. for (int i = 0; i < arr.size(); i++) {
  743. Dictionary d = arr[i];
  744. ERR_CONTINUE(!d.has("name"));
  745. ERR_CONTINUE(!d.has("type"));
  746. PropertyInfo pinfo;
  747. pinfo.type = Variant::Type(d["type"].operator int());
  748. ERR_CONTINUE(pinfo.type < 0 || pinfo.type >= Variant::VARIANT_MAX);
  749. pinfo.name = d["name"];
  750. ERR_CONTINUE(pinfo.name == "");
  751. if (d.has("hint"))
  752. pinfo.hint = PropertyHint(d["hint"].operator int());
  753. if (d.has("hint_string"))
  754. pinfo.hint_string = d["hint_string"];
  755. if (d.has("usage"))
  756. pinfo.usage = d["usage"];
  757. props.push_back(pinfo);
  758. }
  759. }
  760. }
  761. //instance a fake script for editing the values
  762. Vector<_GDScriptMemberSort> msort;
  763. for (Map<StringName, PropertyInfo>::Element *E = sptr->member_info.front(); E; E = E->next()) {
  764. _GDScriptMemberSort ms;
  765. ERR_CONTINUE(!sptr->member_indices.has(E->key()));
  766. ms.index = sptr->member_indices[E->key()].index;
  767. ms.name = E->key();
  768. msort.push_back(ms);
  769. }
  770. msort.sort();
  771. msort.invert();
  772. for (int i = 0; i < msort.size(); i++) {
  773. props.push_front(sptr->member_info[msort[i].name]);
  774. }
  775. #if 0
  776. if (sptr->member_functions.has("_get_property_list")) {
  777. Variant::CallError err;
  778. GDFunction *f = const_cast<GDFunction*>(sptr->member_functions["_get_property_list"]);
  779. Variant plv = f->call(const_cast<GDInstance*>(this),NULL,0,err);
  780. if (plv.get_type()!=Variant::ARRAY) {
  781. ERR_PRINT("_get_property_list: expected array returned");
  782. } else {
  783. Array pl=plv;
  784. for(int i=0;i<pl.size();i++) {
  785. Dictionary p = pl[i];
  786. PropertyInfo pinfo;
  787. if (!p.has("name")) {
  788. ERR_PRINT("_get_property_list: expected 'name' key of type string.")
  789. continue;
  790. }
  791. if (!p.has("type")) {
  792. ERR_PRINT("_get_property_list: expected 'type' key of type integer.")
  793. continue;
  794. }
  795. pinfo.name=p["name"];
  796. pinfo.type=Variant::Type(int(p["type"]));
  797. if (p.has("hint"))
  798. pinfo.hint=PropertyHint(int(p["hint"]));
  799. if (p.has("hint_string"))
  800. pinfo.hint_string=p["hint_string"];
  801. if (p.has("usage"))
  802. pinfo.usage=p["usage"];
  803. props.push_back(pinfo);
  804. }
  805. }
  806. }
  807. #endif
  808. sptr = sptr->_base;
  809. }
  810. //props.invert();
  811. for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
  812. p_properties->push_back(E->get());
  813. }
  814. }
  815. void GDInstance::get_method_list(List<MethodInfo> *p_list) const {
  816. const GDScript *sptr = script.ptr();
  817. while (sptr) {
  818. for (Map<StringName, GDFunction *>::Element *E = sptr->member_functions.front(); E; E = E->next()) {
  819. MethodInfo mi;
  820. mi.name = E->key();
  821. mi.flags |= METHOD_FLAG_FROM_SCRIPT;
  822. for (int i = 0; i < E->get()->get_argument_count(); i++)
  823. mi.arguments.push_back(PropertyInfo(Variant::NIL, "arg" + itos(i)));
  824. p_list->push_back(mi);
  825. }
  826. sptr = sptr->_base;
  827. }
  828. }
  829. bool GDInstance::has_method(const StringName &p_method) const {
  830. const GDScript *sptr = script.ptr();
  831. while (sptr) {
  832. const Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method);
  833. if (E)
  834. return true;
  835. sptr = sptr->_base;
  836. }
  837. return false;
  838. }
  839. Variant GDInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  840. //printf("calling %ls:%i method %ls\n", script->get_path().c_str(), -1, String(p_method).c_str());
  841. GDScript *sptr = script.ptr();
  842. while (sptr) {
  843. Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method);
  844. if (E) {
  845. return E->get()->call(this, p_args, p_argcount, r_error);
  846. }
  847. sptr = sptr->_base;
  848. }
  849. r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
  850. return Variant();
  851. }
  852. void GDInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) {
  853. GDScript *sptr = script.ptr();
  854. Variant::CallError ce;
  855. while (sptr) {
  856. Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method);
  857. if (E) {
  858. E->get()->call(this, p_args, p_argcount, ce);
  859. }
  860. sptr = sptr->_base;
  861. }
  862. }
  863. void GDInstance::_ml_call_reversed(GDScript *sptr, const StringName &p_method, const Variant **p_args, int p_argcount) {
  864. if (sptr->_base)
  865. _ml_call_reversed(sptr->_base, p_method, p_args, p_argcount);
  866. Variant::CallError ce;
  867. Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method);
  868. if (E) {
  869. E->get()->call(this, p_args, p_argcount, ce);
  870. }
  871. }
  872. void GDInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) {
  873. if (script.ptr()) {
  874. _ml_call_reversed(script.ptr(), p_method, p_args, p_argcount);
  875. }
  876. }
  877. void GDInstance::notification(int p_notification) {
  878. //notification is not virutal, it gets called at ALL levels just like in C.
  879. Variant value = p_notification;
  880. const Variant *args[1] = { &value };
  881. GDScript *sptr = script.ptr();
  882. while (sptr) {
  883. Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._notification);
  884. if (E) {
  885. Variant::CallError err;
  886. E->get()->call(this, args, 1, err);
  887. if (err.error != Variant::CallError::CALL_OK) {
  888. //print error about notification call
  889. }
  890. }
  891. sptr = sptr->_base;
  892. }
  893. }
  894. Ref<Script> GDInstance::get_script() const {
  895. return script;
  896. }
  897. ScriptLanguage *GDInstance::get_language() {
  898. return GDScriptLanguage::get_singleton();
  899. }
  900. void GDInstance::reload_members() {
  901. #ifdef DEBUG_ENABLED
  902. members.resize(script->member_indices.size()); //resize
  903. Vector<Variant> new_members;
  904. new_members.resize(script->member_indices.size());
  905. //pass the values to the new indices
  906. for (Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.front(); E; E = E->next()) {
  907. if (member_indices_cache.has(E->key())) {
  908. Variant value = members[member_indices_cache[E->key()]];
  909. new_members[E->get().index] = value;
  910. }
  911. }
  912. //apply
  913. members = new_members;
  914. //pass the values to the new indices
  915. member_indices_cache.clear();
  916. for (Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.front(); E; E = E->next()) {
  917. member_indices_cache[E->key()] = E->get().index;
  918. }
  919. #endif
  920. }
  921. GDInstance::GDInstance() {
  922. owner = NULL;
  923. base_ref = false;
  924. }
  925. GDInstance::~GDInstance() {
  926. if (script.is_valid() && owner) {
  927. script->instances.erase(owner);
  928. }
  929. }
  930. /************* SCRIPT LANGUAGE **************/
  931. /************* SCRIPT LANGUAGE **************/
  932. /************* SCRIPT LANGUAGE **************/
  933. /************* SCRIPT LANGUAGE **************/
  934. /************* SCRIPT LANGUAGE **************/
  935. GDScriptLanguage *GDScriptLanguage::singleton = NULL;
  936. String GDScriptLanguage::get_name() const {
  937. return "GDScript";
  938. }
  939. /* LANGUAGE FUNCTIONS */
  940. void GDScriptLanguage::_add_global(const StringName &p_name, const Variant &p_value) {
  941. if (globals.has(p_name)) {
  942. //overwrite existing
  943. global_array[globals[p_name]] = p_value;
  944. return;
  945. }
  946. globals[p_name] = global_array.size();
  947. global_array.push_back(p_value);
  948. _global_array = global_array.ptr();
  949. }
  950. void GDScriptLanguage::add_global_constant(const StringName &p_variable, const Variant &p_value) {
  951. _add_global(p_variable, p_value);
  952. }
  953. void GDScriptLanguage::init() {
  954. //populate global constants
  955. int gcc = GlobalConstants::get_global_constant_count();
  956. for (int i = 0; i < gcc; i++) {
  957. _add_global(StaticCString::create(GlobalConstants::get_global_constant_name(i)), GlobalConstants::get_global_constant_value(i));
  958. }
  959. _add_global(StaticCString::create("PI"), Math_PI);
  960. //populate native classes
  961. List<StringName> class_list;
  962. ObjectTypeDB::get_type_list(&class_list);
  963. for (List<StringName>::Element *E = class_list.front(); E; E = E->next()) {
  964. StringName n = E->get();
  965. String s = String(n);
  966. if (s.begins_with("_"))
  967. n = s.substr(1, s.length());
  968. if (globals.has(n))
  969. continue;
  970. Ref<GDNativeClass> nc = memnew(GDNativeClass(E->get()));
  971. _add_global(n, nc);
  972. }
  973. //populate singletons
  974. List<Globals::Singleton> singletons;
  975. Globals::get_singleton()->get_singletons(&singletons);
  976. for (List<Globals::Singleton>::Element *E = singletons.front(); E; E = E->next()) {
  977. _add_global(E->get().name, E->get().ptr);
  978. }
  979. }
  980. String GDScriptLanguage::get_type() const {
  981. return "GDScript";
  982. }
  983. String GDScriptLanguage::get_extension() const {
  984. return "gd";
  985. }
  986. Error GDScriptLanguage::execute_file(const String &p_path) {
  987. // ??
  988. return OK;
  989. }
  990. void GDScriptLanguage::finish() {
  991. }
  992. void GDScriptLanguage::profiling_start() {
  993. #ifdef DEBUG_ENABLED
  994. if (lock) {
  995. lock->lock();
  996. }
  997. SelfList<GDFunction> *elem = function_list.first();
  998. while (elem) {
  999. elem->self()->profile.call_count = 0;
  1000. elem->self()->profile.self_time = 0;
  1001. elem->self()->profile.total_time = 0;
  1002. elem->self()->profile.frame_call_count = 0;
  1003. elem->self()->profile.frame_self_time = 0;
  1004. elem->self()->profile.frame_total_time = 0;
  1005. elem->self()->profile.last_frame_call_count = 0;
  1006. elem->self()->profile.last_frame_self_time = 0;
  1007. elem->self()->profile.last_frame_total_time = 0;
  1008. elem = elem->next();
  1009. }
  1010. profiling = true;
  1011. if (lock) {
  1012. lock->unlock();
  1013. }
  1014. #endif
  1015. }
  1016. void GDScriptLanguage::profiling_stop() {
  1017. #ifdef DEBUG_ENABLED
  1018. if (lock) {
  1019. lock->lock();
  1020. }
  1021. profiling = false;
  1022. if (lock) {
  1023. lock->unlock();
  1024. }
  1025. #endif
  1026. }
  1027. int GDScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) {
  1028. int current = 0;
  1029. #ifdef DEBUG_ENABLED
  1030. if (lock) {
  1031. lock->lock();
  1032. }
  1033. SelfList<GDFunction> *elem = function_list.first();
  1034. while (elem) {
  1035. if (current >= p_info_max)
  1036. break;
  1037. p_info_arr[current].call_count = elem->self()->profile.call_count;
  1038. p_info_arr[current].self_time = elem->self()->profile.self_time;
  1039. p_info_arr[current].total_time = elem->self()->profile.total_time;
  1040. p_info_arr[current].signature = elem->self()->profile.signature;
  1041. elem = elem->next();
  1042. current++;
  1043. }
  1044. if (lock) {
  1045. lock->unlock();
  1046. }
  1047. #endif
  1048. return current;
  1049. }
  1050. int GDScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) {
  1051. int current = 0;
  1052. #ifdef DEBUG_ENABLED
  1053. if (lock) {
  1054. lock->lock();
  1055. }
  1056. SelfList<GDFunction> *elem = function_list.first();
  1057. while (elem) {
  1058. if (current >= p_info_max)
  1059. break;
  1060. if (elem->self()->profile.last_frame_call_count > 0) {
  1061. p_info_arr[current].call_count = elem->self()->profile.last_frame_call_count;
  1062. p_info_arr[current].self_time = elem->self()->profile.last_frame_self_time;
  1063. p_info_arr[current].total_time = elem->self()->profile.last_frame_total_time;
  1064. p_info_arr[current].signature = elem->self()->profile.signature;
  1065. //print_line(String(elem->self()->profile.signature)+": "+itos(elem->self()->profile.last_frame_call_count));
  1066. current++;
  1067. }
  1068. elem = elem->next();
  1069. }
  1070. if (lock) {
  1071. lock->unlock();
  1072. }
  1073. #endif
  1074. return current;
  1075. }
  1076. struct GDScriptDepSort {
  1077. //must support sorting so inheritance works properly (parent must be reloaded first)
  1078. bool operator()(const Ref<GDScript> &A, const Ref<GDScript> &B) const {
  1079. if (A == B)
  1080. return false; //shouldn't happen but..
  1081. const GDScript *I = B->get_base().ptr();
  1082. while (I) {
  1083. if (I == A.ptr()) {
  1084. // A is a base of B
  1085. return true;
  1086. }
  1087. I = I->get_base().ptr();
  1088. }
  1089. return false; //not a base
  1090. }
  1091. };
  1092. void GDScriptLanguage::reload_all_scripts() {
  1093. #ifdef DEBUG_ENABLED
  1094. print_line("RELOAD ALL SCRIPTS");
  1095. if (lock) {
  1096. lock->lock();
  1097. }
  1098. List<Ref<GDScript> > scripts;
  1099. SelfList<GDScript> *elem = script_list.first();
  1100. while (elem) {
  1101. if (elem->self()->get_path().is_resource_file()) {
  1102. print_line("FOUND: " + elem->self()->get_path());
  1103. scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident
  1104. }
  1105. elem = elem->next();
  1106. }
  1107. if (lock) {
  1108. lock->unlock();
  1109. }
  1110. //as scripts are going to be reloaded, must proceed without locking here
  1111. scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order
  1112. for (List<Ref<GDScript> >::Element *E = scripts.front(); E; E = E->next()) {
  1113. print_line("RELOADING: " + E->get()->get_path());
  1114. E->get()->load_source_code(E->get()->get_path());
  1115. E->get()->reload(true);
  1116. }
  1117. #endif
  1118. }
  1119. void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
  1120. #ifdef DEBUG_ENABLED
  1121. if (lock) {
  1122. lock->lock();
  1123. }
  1124. List<Ref<GDScript> > scripts;
  1125. SelfList<GDScript> *elem = script_list.first();
  1126. while (elem) {
  1127. if (elem->self()->get_path().is_resource_file()) {
  1128. scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident
  1129. }
  1130. elem = elem->next();
  1131. }
  1132. if (lock) {
  1133. lock->unlock();
  1134. }
  1135. //when someone asks you why dynamically typed languages are easier to write....
  1136. Map<Ref<GDScript>, Map<ObjectID, List<Pair<StringName, Variant> > > > to_reload;
  1137. //as scripts are going to be reloaded, must proceed without locking here
  1138. scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order
  1139. for (List<Ref<GDScript> >::Element *E = scripts.front(); E; E = E->next()) {
  1140. bool reload = E->get() == p_script || to_reload.has(E->get()->get_base());
  1141. if (!reload)
  1142. continue;
  1143. to_reload.insert(E->get(), Map<ObjectID, List<Pair<StringName, Variant> > >());
  1144. if (!p_soft_reload) {
  1145. //save state and remove script from instances
  1146. Map<ObjectID, List<Pair<StringName, Variant> > > &map = to_reload[E->get()];
  1147. while (E->get()->instances.front()) {
  1148. Object *obj = E->get()->instances.front()->get();
  1149. //save instance info
  1150. List<Pair<StringName, Variant> > state;
  1151. if (obj->get_script_instance()) {
  1152. obj->get_script_instance()->get_property_state(state);
  1153. map[obj->get_instance_ID()] = state;
  1154. obj->set_script(RefPtr());
  1155. }
  1156. }
  1157. //same thing for placeholders
  1158. #ifdef TOOLS_ENABLED
  1159. while (E->get()->placeholders.size()) {
  1160. Object *obj = E->get()->placeholders.front()->get()->get_owner();
  1161. //save instance info
  1162. List<Pair<StringName, Variant> > state;
  1163. if (obj->get_script_instance()) {
  1164. obj->get_script_instance()->get_property_state(state);
  1165. map[obj->get_instance_ID()] = state;
  1166. obj->set_script(RefPtr());
  1167. } else {
  1168. // no instance found. Let's remove it so we don't loop forever
  1169. E->get()->placeholders.erase(E->get()->placeholders.front()->get());
  1170. }
  1171. }
  1172. #endif
  1173. for (Map<ObjectID, List<Pair<StringName, Variant> > >::Element *F = E->get()->pending_reload_state.front(); F; F = F->next()) {
  1174. map[F->key()] = F->get(); //pending to reload, use this one instead
  1175. }
  1176. }
  1177. }
  1178. for (Map<Ref<GDScript>, Map<ObjectID, List<Pair<StringName, Variant> > > >::Element *E = to_reload.front(); E; E = E->next()) {
  1179. Ref<GDScript> scr = E->key();
  1180. scr->reload(p_soft_reload);
  1181. //restore state if saved
  1182. for (Map<ObjectID, List<Pair<StringName, Variant> > >::Element *F = E->get().front(); F; F = F->next()) {
  1183. Object *obj = ObjectDB::get_instance(F->key());
  1184. if (!obj)
  1185. continue;
  1186. if (!p_soft_reload) {
  1187. //clear it just in case (may be a pending reload state)
  1188. obj->set_script(RefPtr());
  1189. }
  1190. obj->set_script(scr.get_ref_ptr());
  1191. if (!obj->get_script_instance()) {
  1192. //failed, save reload state for next time if not saved
  1193. if (!scr->pending_reload_state.has(obj->get_instance_ID())) {
  1194. scr->pending_reload_state[obj->get_instance_ID()] = F->get();
  1195. }
  1196. continue;
  1197. }
  1198. for (List<Pair<StringName, Variant> >::Element *G = F->get().front(); G; G = G->next()) {
  1199. obj->get_script_instance()->set(G->get().first, G->get().second);
  1200. }
  1201. scr->pending_reload_state.erase(obj->get_instance_ID()); //as it reloaded, remove pending state
  1202. }
  1203. //if instance states were saved, set them!
  1204. }
  1205. #endif
  1206. }
  1207. void GDScriptLanguage::frame() {
  1208. // print_line("calls: "+itos(calls));
  1209. calls = 0;
  1210. #ifdef DEBUG_ENABLED
  1211. if (profiling) {
  1212. if (lock) {
  1213. lock->lock();
  1214. }
  1215. SelfList<GDFunction> *elem = function_list.first();
  1216. while (elem) {
  1217. elem->self()->profile.last_frame_call_count = elem->self()->profile.frame_call_count;
  1218. elem->self()->profile.last_frame_self_time = elem->self()->profile.frame_self_time;
  1219. elem->self()->profile.last_frame_total_time = elem->self()->profile.frame_total_time;
  1220. elem->self()->profile.frame_call_count = 0;
  1221. elem->self()->profile.frame_self_time = 0;
  1222. elem->self()->profile.frame_total_time = 0;
  1223. elem = elem->next();
  1224. }
  1225. if (lock) {
  1226. lock->unlock();
  1227. }
  1228. }
  1229. #endif
  1230. }
  1231. /* EDITOR FUNCTIONS */
  1232. void GDScriptLanguage::get_reserved_words(List<String> *p_words) const {
  1233. static const char *_reserved_words[] = {
  1234. // operators
  1235. "and",
  1236. "in",
  1237. "not",
  1238. "or",
  1239. // types and values
  1240. "false",
  1241. "float",
  1242. "int",
  1243. "bool",
  1244. "null",
  1245. "PI",
  1246. "self",
  1247. "true",
  1248. // functions
  1249. "assert",
  1250. "breakpoint",
  1251. "class",
  1252. "extends",
  1253. "func",
  1254. "preload",
  1255. "setget",
  1256. "signal",
  1257. "tool",
  1258. "yield",
  1259. // var
  1260. "const",
  1261. "enum",
  1262. "export",
  1263. "onready",
  1264. "static",
  1265. "var",
  1266. // control flow
  1267. "break",
  1268. "continue",
  1269. "if",
  1270. "elif",
  1271. "else",
  1272. "for",
  1273. "pass",
  1274. "return",
  1275. "while",
  1276. 0
  1277. };
  1278. const char **w = _reserved_words;
  1279. while (*w) {
  1280. p_words->push_back(*w);
  1281. w++;
  1282. }
  1283. for (int i = 0; i < GDFunctions::FUNC_MAX; i++) {
  1284. p_words->push_back(GDFunctions::get_func_name(GDFunctions::Function(i)));
  1285. }
  1286. }
  1287. GDScriptLanguage::GDScriptLanguage() {
  1288. calls = 0;
  1289. ERR_FAIL_COND(singleton);
  1290. singleton = this;
  1291. strings._init = StaticCString::create("_init");
  1292. strings._notification = StaticCString::create("_notification");
  1293. strings._set = StaticCString::create("_set");
  1294. strings._get = StaticCString::create("_get");
  1295. strings._get_property_list = StaticCString::create("_get_property_list");
  1296. strings._script_source = StaticCString::create("script/source");
  1297. _debug_parse_err_line = -1;
  1298. _debug_parse_err_file = "";
  1299. #ifdef NO_THREADS
  1300. lock = NULL;
  1301. #else
  1302. lock = Mutex::create();
  1303. #endif
  1304. profiling = false;
  1305. script_frame_time = 0;
  1306. _debug_call_stack_pos = 0;
  1307. int dmcs = GLOBAL_DEF("debug/script_max_call_stack", 1024);
  1308. if (ScriptDebugger::get_singleton()) {
  1309. //debugging enabled!
  1310. _debug_max_call_stack = dmcs;
  1311. if (_debug_max_call_stack < 1024)
  1312. _debug_max_call_stack = 1024;
  1313. _call_stack = memnew_arr(CallLevel, _debug_max_call_stack + 1);
  1314. } else {
  1315. _debug_max_call_stack = 0;
  1316. _call_stack = NULL;
  1317. }
  1318. }
  1319. GDScriptLanguage::~GDScriptLanguage() {
  1320. if (lock) {
  1321. memdelete(lock);
  1322. lock = NULL;
  1323. }
  1324. if (_call_stack) {
  1325. memdelete_arr(_call_stack);
  1326. }
  1327. singleton = NULL;
  1328. }
  1329. /*************** RESOURCE ***************/
  1330. RES ResourceFormatLoaderGDScript::load(const String &p_path, const String &p_original_path, Error *r_error) {
  1331. if (r_error)
  1332. *r_error = ERR_FILE_CANT_OPEN;
  1333. GDScript *script = memnew(GDScript);
  1334. Ref<GDScript> scriptres(script);
  1335. if (p_path.ends_with(".gde") || p_path.ends_with(".gdc")) {
  1336. script->set_script_path(p_original_path); // script needs this.
  1337. script->set_path(p_original_path);
  1338. Error err = script->load_byte_code(p_path);
  1339. if (err != OK) {
  1340. ERR_FAIL_COND_V(err != OK, RES());
  1341. }
  1342. } else {
  1343. Error err = script->load_source_code(p_path);
  1344. if (err != OK) {
  1345. ERR_FAIL_COND_V(err != OK, RES());
  1346. }
  1347. script->set_script_path(p_original_path); // script needs this.
  1348. script->set_path(p_original_path);
  1349. //script->set_name(p_path.get_file());
  1350. script->reload();
  1351. }
  1352. if (r_error)
  1353. *r_error = OK;
  1354. return scriptres;
  1355. }
  1356. void ResourceFormatLoaderGDScript::get_recognized_extensions(List<String> *p_extensions) const {
  1357. p_extensions->push_back("gd");
  1358. p_extensions->push_back("gdc");
  1359. p_extensions->push_back("gde");
  1360. }
  1361. bool ResourceFormatLoaderGDScript::handles_type(const String &p_type) const {
  1362. return (p_type == "Script" || p_type == "GDScript");
  1363. }
  1364. String ResourceFormatLoaderGDScript::get_resource_type(const String &p_path) const {
  1365. String el = p_path.extension().to_lower();
  1366. if (el == "gd" || el == "gdc" || el == "gde")
  1367. return "GDScript";
  1368. return "";
  1369. }
  1370. Error ResourceFormatSaverGDScript::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
  1371. Ref<GDScript> sqscr = p_resource;
  1372. ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
  1373. String source = sqscr->get_source_code();
  1374. Error err;
  1375. FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  1376. if (err) {
  1377. ERR_FAIL_COND_V(err, err);
  1378. }
  1379. file->store_string(source);
  1380. if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
  1381. memdelete(file);
  1382. return ERR_CANT_CREATE;
  1383. }
  1384. file->close();
  1385. memdelete(file);
  1386. if (ScriptServer::is_reload_scripts_on_save_enabled()) {
  1387. GDScriptLanguage::get_singleton()->reload_tool_script(p_resource, false);
  1388. }
  1389. return OK;
  1390. }
  1391. void ResourceFormatSaverGDScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
  1392. if (p_resource->cast_to<GDScript>()) {
  1393. p_extensions->push_back("gd");
  1394. }
  1395. }
  1396. bool ResourceFormatSaverGDScript::recognize(const RES &p_resource) const {
  1397. return p_resource->cast_to<GDScript>() != NULL;
  1398. }