gdscript.cpp 48 KB

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