gdscript.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028
  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. #ifdef TOOLS_ENABLED
  147. return valid && (tool || ScriptServer::is_scripting_enabled());
  148. #else
  149. return valid;
  150. #endif
  151. }
  152. Ref<Script> GDScript::get_base_script() const {
  153. if (_base) {
  154. return Ref<GDScript>(_base);
  155. } else {
  156. return Ref<Script>();
  157. }
  158. }
  159. StringName GDScript::get_instance_base_type() const {
  160. if (native.is_valid())
  161. return native->get_name();
  162. if (base.is_valid())
  163. return base->get_instance_base_type();
  164. return StringName();
  165. }
  166. struct _GDScriptMemberSort {
  167. int index;
  168. StringName name;
  169. _FORCE_INLINE_ bool operator<(const _GDScriptMemberSort &p_member) const { return index < p_member.index; }
  170. };
  171. #ifdef TOOLS_ENABLED
  172. void GDScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
  173. placeholders.erase(p_placeholder);
  174. }
  175. #endif
  176. void GDScript::get_script_method_list(List<MethodInfo> *p_list) const {
  177. for (const Map<StringName, GDScriptFunction *>::Element *E = member_functions.front(); E; E = E->next()) {
  178. GDScriptFunction *func = E->get();
  179. MethodInfo mi;
  180. mi.name = E->key();
  181. for (int i = 0; i < func->get_argument_count(); i++) {
  182. mi.arguments.push_back(func->get_argument_type(i));
  183. }
  184. mi.return_val = func->get_return_type();
  185. p_list->push_back(mi);
  186. }
  187. }
  188. void GDScript::get_script_property_list(List<PropertyInfo> *p_list) const {
  189. const GDScript *sptr = this;
  190. List<PropertyInfo> props;
  191. while (sptr) {
  192. Vector<_GDScriptMemberSort> msort;
  193. for (Map<StringName, PropertyInfo>::Element *E = sptr->member_info.front(); E; E = E->next()) {
  194. _GDScriptMemberSort ms;
  195. ERR_CONTINUE(!sptr->member_indices.has(E->key()));
  196. ms.index = sptr->member_indices[E->key()].index;
  197. ms.name = E->key();
  198. msort.push_back(ms);
  199. }
  200. msort.sort();
  201. msort.invert();
  202. for (int i = 0; i < msort.size(); i++) {
  203. props.push_front(sptr->member_info[msort[i].name]);
  204. }
  205. sptr = sptr->_base;
  206. }
  207. for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
  208. p_list->push_back(E->get());
  209. }
  210. }
  211. bool GDScript::has_method(const StringName &p_method) const {
  212. return member_functions.has(p_method);
  213. }
  214. MethodInfo GDScript::get_method_info(const StringName &p_method) const {
  215. const Map<StringName, GDScriptFunction *>::Element *E = member_functions.find(p_method);
  216. if (!E)
  217. return MethodInfo();
  218. GDScriptFunction *func = E->get();
  219. MethodInfo mi;
  220. mi.name = E->key();
  221. for (int i = 0; i < func->get_argument_count(); i++) {
  222. mi.arguments.push_back(func->get_argument_type(i));
  223. }
  224. mi.return_val = func->get_return_type();
  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. GDScript *top = this;
  247. while (top->_base)
  248. top = top->_base;
  249. if (top->native.is_valid()) {
  250. if (!ClassDB::is_parent_class(p_this->get_class_name(), top->native->get_name())) {
  251. if (ScriptDebugger::get_singleton()) {
  252. 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() + "'");
  253. }
  254. 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() + "'");
  255. ERR_FAIL_V(NULL);
  256. }
  257. }
  258. Variant::CallError unchecked_error;
  259. return _create_instance(NULL, 0, p_this, Object::cast_to<Reference>(p_this), unchecked_error);
  260. }
  261. PlaceHolderScriptInstance *GDScript::placeholder_instance_create(Object *p_this) {
  262. #ifdef TOOLS_ENABLED
  263. //instance a fake script for editing the values
  264. //plist.invert();
  265. /*print_line("CREATING PLACEHOLDER");
  266. for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
  267. print_line(E->get().name);
  268. }*/
  269. PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(GDScriptLanguage::get_singleton(), Ref<Script>(this), p_this));
  270. placeholders.insert(si);
  271. //_update_placeholder(si);
  272. _update_exports();
  273. return si;
  274. #else
  275. return NULL;
  276. #endif
  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. } else {
  373. for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) {
  374. E->get()->set_build_failed(true);
  375. }
  376. }
  377. } else {
  378. //print_line("unchanged is "+get_path());
  379. }
  380. if (base_cache.is_valid()) {
  381. if (base_cache->_update_exports()) {
  382. changed = true;
  383. }
  384. }
  385. if (/*changed &&*/ placeholders.size()) { //hm :(
  386. //print_line("updating placeholders for "+get_path());
  387. //update placeholders if any
  388. Map<StringName, Variant> values;
  389. List<PropertyInfo> propnames;
  390. _update_exports_values(values, propnames);
  391. for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) {
  392. E->get()->set_build_failed(false);
  393. E->get()->update(propnames, values);
  394. }
  395. }
  396. return changed;
  397. #else
  398. return false;
  399. #endif
  400. }
  401. void GDScript::update_exports() {
  402. #ifdef TOOLS_ENABLED
  403. _update_exports();
  404. Set<ObjectID> copy = inheriters_cache; //might get modified
  405. //print_line("update exports for "+get_path()+" ic: "+itos(copy.size()));
  406. for (Set<ObjectID>::Element *E = copy.front(); E; E = E->next()) {
  407. Object *id = ObjectDB::get_instance(E->get());
  408. GDScript *s = Object::cast_to<GDScript>(id);
  409. if (!s)
  410. continue;
  411. s->update_exports();
  412. }
  413. #endif
  414. }
  415. void GDScript::_set_subclass_path(Ref<GDScript> &p_sc, const String &p_path) {
  416. p_sc->path = p_path;
  417. for (Map<StringName, Ref<GDScript> >::Element *E = p_sc->subclasses.front(); E; E = E->next()) {
  418. _set_subclass_path(E->get(), p_path);
  419. }
  420. }
  421. Error GDScript::reload(bool p_keep_state) {
  422. #ifndef NO_THREADS
  423. GDScriptLanguage::singleton->lock->lock();
  424. #endif
  425. bool has_instances = instances.size();
  426. #ifndef NO_THREADS
  427. GDScriptLanguage::singleton->lock->unlock();
  428. #endif
  429. ERR_FAIL_COND_V(!p_keep_state && has_instances, ERR_ALREADY_IN_USE);
  430. String basedir = path;
  431. if (basedir == "")
  432. basedir = get_path();
  433. if (basedir != "")
  434. basedir = basedir.get_base_dir();
  435. if (source.find("%BASE%") != -1) {
  436. //loading a template, don't parse
  437. return OK;
  438. }
  439. valid = false;
  440. GDScriptParser parser;
  441. Error err = parser.parse(source, basedir, false, path);
  442. if (err) {
  443. if (ScriptDebugger::get_singleton()) {
  444. GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), parser.get_error_line(), "Parser Error: " + parser.get_error());
  445. }
  446. _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);
  447. ERR_FAIL_V(ERR_PARSE_ERROR);
  448. }
  449. bool can_run = ScriptServer::is_scripting_enabled() || parser.is_tool_script();
  450. GDScriptCompiler compiler;
  451. err = compiler.compile(&parser, this, p_keep_state);
  452. if (err) {
  453. if (can_run) {
  454. if (ScriptDebugger::get_singleton()) {
  455. GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), compiler.get_error_line(), "Parser Error: " + compiler.get_error());
  456. }
  457. _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);
  458. ERR_FAIL_V(ERR_COMPILATION_FAILED);
  459. } else {
  460. return err;
  461. }
  462. }
  463. valid = true;
  464. for (Map<StringName, Ref<GDScript> >::Element *E = subclasses.front(); E; E = E->next()) {
  465. _set_subclass_path(E->get(), path);
  466. }
  467. return OK;
  468. }
  469. ScriptLanguage *GDScript::get_language() const {
  470. return GDScriptLanguage::get_singleton();
  471. }
  472. void GDScript::get_constants(Map<StringName, Variant> *p_constants) {
  473. if (p_constants) {
  474. for (Map<StringName, Variant>::Element *E = constants.front(); E; E = E->next()) {
  475. (*p_constants)[E->key()] = E->value();
  476. }
  477. }
  478. }
  479. void GDScript::get_members(Set<StringName> *p_members) {
  480. if (p_members) {
  481. for (Set<StringName>::Element *E = members.front(); E; E = E->next()) {
  482. p_members->insert(E->get());
  483. }
  484. }
  485. }
  486. Variant GDScript::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  487. GDScript *top = this;
  488. while (top) {
  489. Map<StringName, GDScriptFunction *>::Element *E = top->member_functions.find(p_method);
  490. if (E) {
  491. if (!E->get()->is_static()) {
  492. WARN_PRINT(String("Can't call non-static function: '" + String(p_method) + "' in script.").utf8().get_data());
  493. }
  494. return E->get()->call(NULL, p_args, p_argcount, r_error);
  495. }
  496. top = top->_base;
  497. }
  498. //none found, regular
  499. return Script::call(p_method, p_args, p_argcount, r_error);
  500. }
  501. bool GDScript::_get(const StringName &p_name, Variant &r_ret) const {
  502. {
  503. const GDScript *top = this;
  504. while (top) {
  505. {
  506. const Map<StringName, Variant>::Element *E = top->constants.find(p_name);
  507. if (E) {
  508. r_ret = E->get();
  509. return true;
  510. }
  511. }
  512. {
  513. const Map<StringName, Ref<GDScript> >::Element *E = subclasses.find(p_name);
  514. if (E) {
  515. r_ret = E->get();
  516. return true;
  517. }
  518. }
  519. top = top->_base;
  520. }
  521. if (p_name == GDScriptLanguage::get_singleton()->strings._script_source) {
  522. r_ret = get_source_code();
  523. return true;
  524. }
  525. }
  526. return false;
  527. }
  528. bool GDScript::_set(const StringName &p_name, const Variant &p_value) {
  529. if (p_name == GDScriptLanguage::get_singleton()->strings._script_source) {
  530. set_source_code(p_value);
  531. reload();
  532. } else
  533. return false;
  534. return true;
  535. }
  536. void GDScript::_get_property_list(List<PropertyInfo> *p_properties) const {
  537. p_properties->push_back(PropertyInfo(Variant::STRING, "script/source", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL));
  538. }
  539. void GDScript::_bind_methods() {
  540. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &GDScript::_new, MethodInfo(Variant::OBJECT, "new"));
  541. ClassDB::bind_method(D_METHOD("get_as_byte_code"), &GDScript::get_as_byte_code);
  542. }
  543. Vector<uint8_t> GDScript::get_as_byte_code() const {
  544. GDScriptTokenizerBuffer tokenizer;
  545. return tokenizer.parse_code_string(source);
  546. };
  547. Error GDScript::load_byte_code(const String &p_path) {
  548. Vector<uint8_t> bytecode;
  549. if (p_path.ends_with("gde")) {
  550. FileAccess *fa = FileAccess::open(p_path, FileAccess::READ);
  551. ERR_FAIL_COND_V(!fa, ERR_CANT_OPEN);
  552. FileAccessEncrypted *fae = memnew(FileAccessEncrypted);
  553. ERR_FAIL_COND_V(!fae, ERR_CANT_OPEN);
  554. Vector<uint8_t> key;
  555. key.resize(32);
  556. for (int i = 0; i < key.size(); i++) {
  557. key.write[i] = script_encryption_key[i];
  558. }
  559. Error err = fae->open_and_parse(fa, key, FileAccessEncrypted::MODE_READ);
  560. ERR_FAIL_COND_V(err, err);
  561. bytecode.resize(fae->get_len());
  562. fae->get_buffer(bytecode.ptrw(), bytecode.size());
  563. memdelete(fae);
  564. } else {
  565. bytecode = FileAccess::get_file_as_array(p_path);
  566. }
  567. ERR_FAIL_COND_V(bytecode.size() == 0, ERR_PARSE_ERROR);
  568. path = p_path;
  569. String basedir = path;
  570. if (basedir == "")
  571. basedir = get_path();
  572. if (basedir != "")
  573. basedir = basedir.get_base_dir();
  574. valid = false;
  575. GDScriptParser parser;
  576. Error err = parser.parse_bytecode(bytecode, basedir, get_path());
  577. if (err) {
  578. _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);
  579. ERR_FAIL_V(ERR_PARSE_ERROR);
  580. }
  581. GDScriptCompiler compiler;
  582. err = compiler.compile(&parser, this);
  583. if (err) {
  584. _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);
  585. ERR_FAIL_V(ERR_COMPILATION_FAILED);
  586. }
  587. valid = true;
  588. for (Map<StringName, Ref<GDScript> >::Element *E = subclasses.front(); E; E = E->next()) {
  589. _set_subclass_path(E->get(), path);
  590. }
  591. return OK;
  592. }
  593. Error GDScript::load_source_code(const String &p_path) {
  594. PoolVector<uint8_t> sourcef;
  595. Error err;
  596. FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
  597. if (err) {
  598. ERR_FAIL_COND_V(err, err);
  599. }
  600. int len = f->get_len();
  601. sourcef.resize(len + 1);
  602. PoolVector<uint8_t>::Write w = sourcef.write();
  603. int r = f->get_buffer(w.ptr(), len);
  604. f->close();
  605. memdelete(f);
  606. ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN);
  607. w[len] = 0;
  608. String s;
  609. if (s.parse_utf8((const char *)w.ptr())) {
  610. 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.");
  611. ERR_FAIL_V(ERR_INVALID_DATA);
  612. }
  613. source = s;
  614. #ifdef TOOLS_ENABLED
  615. source_changed_cache = true;
  616. #endif
  617. //print_line("LSC :"+get_path());
  618. path = p_path;
  619. return OK;
  620. }
  621. const Map<StringName, GDScriptFunction *> &GDScript::debug_get_member_functions() const {
  622. return member_functions;
  623. }
  624. StringName GDScript::debug_get_member_by_index(int p_idx) const {
  625. for (const Map<StringName, MemberInfo>::Element *E = member_indices.front(); E; E = E->next()) {
  626. if (E->get().index == p_idx)
  627. return E->key();
  628. }
  629. return "<error>";
  630. }
  631. Ref<GDScript> GDScript::get_base() const {
  632. return base;
  633. }
  634. bool GDScript::has_script_signal(const StringName &p_signal) const {
  635. if (_signals.has(p_signal))
  636. return true;
  637. if (base.is_valid()) {
  638. return base->has_script_signal(p_signal);
  639. }
  640. #ifdef TOOLS_ENABLED
  641. else if (base_cache.is_valid()) {
  642. return base_cache->has_script_signal(p_signal);
  643. }
  644. #endif
  645. return false;
  646. }
  647. void GDScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
  648. for (const Map<StringName, Vector<StringName> >::Element *E = _signals.front(); E; E = E->next()) {
  649. MethodInfo mi;
  650. mi.name = E->key();
  651. for (int i = 0; i < E->get().size(); i++) {
  652. PropertyInfo arg;
  653. arg.name = E->get()[i];
  654. mi.arguments.push_back(arg);
  655. }
  656. r_signals->push_back(mi);
  657. }
  658. if (base.is_valid()) {
  659. base->get_script_signal_list(r_signals);
  660. }
  661. #ifdef TOOLS_ENABLED
  662. else if (base_cache.is_valid()) {
  663. base_cache->get_script_signal_list(r_signals);
  664. }
  665. #endif
  666. }
  667. GDScript::GDScript() :
  668. script_list(this) {
  669. _static_ref = this;
  670. valid = false;
  671. subclass_count = 0;
  672. initializer = NULL;
  673. _base = NULL;
  674. _owner = NULL;
  675. tool = false;
  676. #ifdef TOOLS_ENABLED
  677. source_changed_cache = false;
  678. #endif
  679. #ifdef DEBUG_ENABLED
  680. if (GDScriptLanguage::get_singleton()->lock) {
  681. GDScriptLanguage::get_singleton()->lock->lock();
  682. }
  683. GDScriptLanguage::get_singleton()->script_list.add(&script_list);
  684. if (GDScriptLanguage::get_singleton()->lock) {
  685. GDScriptLanguage::get_singleton()->lock->unlock();
  686. }
  687. #endif
  688. }
  689. GDScript::~GDScript() {
  690. for (Map<StringName, GDScriptFunction *>::Element *E = member_functions.front(); E; E = E->next()) {
  691. memdelete(E->get());
  692. }
  693. for (Map<StringName, Ref<GDScript> >::Element *E = subclasses.front(); E; E = E->next()) {
  694. E->get()->_owner = NULL; //bye, you are no longer owned cause I died
  695. }
  696. #ifdef DEBUG_ENABLED
  697. if (GDScriptLanguage::get_singleton()->lock) {
  698. GDScriptLanguage::get_singleton()->lock->lock();
  699. }
  700. GDScriptLanguage::get_singleton()->script_list.remove(&script_list);
  701. if (GDScriptLanguage::get_singleton()->lock) {
  702. GDScriptLanguage::get_singleton()->lock->unlock();
  703. }
  704. #endif
  705. }
  706. //////////////////////////////
  707. // INSTANCE //
  708. //////////////////////////////
  709. bool GDScriptInstance::set(const StringName &p_name, const Variant &p_value) {
  710. //member
  711. {
  712. const Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name);
  713. if (E) {
  714. if (E->get().setter) {
  715. const Variant *val = &p_value;
  716. Variant::CallError err;
  717. call(E->get().setter, &val, 1, err);
  718. if (err.error == Variant::CallError::CALL_OK) {
  719. return true; //function exists, call was successful
  720. }
  721. } else {
  722. if (!E->get().data_type.is_type(p_value)) {
  723. return false; // Type mismatch
  724. }
  725. members.write[E->get().index] = p_value;
  726. }
  727. return true;
  728. }
  729. }
  730. GDScript *sptr = script.ptr();
  731. while (sptr) {
  732. Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._set);
  733. if (E) {
  734. Variant name = p_name;
  735. const Variant *args[2] = { &name, &p_value };
  736. Variant::CallError err;
  737. Variant ret = E->get()->call(this, (const Variant **)args, 2, err);
  738. if (err.error == Variant::CallError::CALL_OK && ret.get_type() == Variant::BOOL && ret.operator bool())
  739. return true;
  740. }
  741. sptr = sptr->_base;
  742. }
  743. return false;
  744. }
  745. bool GDScriptInstance::get(const StringName &p_name, Variant &r_ret) const {
  746. const GDScript *sptr = script.ptr();
  747. while (sptr) {
  748. {
  749. const Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name);
  750. if (E) {
  751. if (E->get().getter) {
  752. Variant::CallError err;
  753. r_ret = const_cast<GDScriptInstance *>(this)->call(E->get().getter, NULL, 0, err);
  754. if (err.error == Variant::CallError::CALL_OK) {
  755. return true;
  756. }
  757. }
  758. r_ret = members[E->get().index];
  759. return true; //index found
  760. }
  761. }
  762. {
  763. const GDScript *sl = sptr;
  764. while (sl) {
  765. const Map<StringName, Variant>::Element *E = sl->constants.find(p_name);
  766. if (E) {
  767. r_ret = E->get();
  768. return true; //index found
  769. }
  770. sl = sl->_base;
  771. }
  772. }
  773. {
  774. const Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get);
  775. if (E) {
  776. Variant name = p_name;
  777. const Variant *args[1] = { &name };
  778. Variant::CallError err;
  779. Variant ret = const_cast<GDScriptFunction *>(E->get())->call(const_cast<GDScriptInstance *>(this), (const Variant **)args, 1, err);
  780. if (err.error == Variant::CallError::CALL_OK && ret.get_type() != Variant::NIL) {
  781. r_ret = ret;
  782. return true;
  783. }
  784. }
  785. }
  786. sptr = sptr->_base;
  787. }
  788. return false;
  789. }
  790. Variant::Type GDScriptInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
  791. const GDScript *sptr = script.ptr();
  792. while (sptr) {
  793. if (sptr->member_info.has(p_name)) {
  794. if (r_is_valid)
  795. *r_is_valid = true;
  796. return sptr->member_info[p_name].type;
  797. }
  798. sptr = sptr->_base;
  799. }
  800. if (r_is_valid)
  801. *r_is_valid = false;
  802. return Variant::NIL;
  803. }
  804. void GDScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const {
  805. // exported members, not doen yet!
  806. const GDScript *sptr = script.ptr();
  807. List<PropertyInfo> props;
  808. while (sptr) {
  809. const Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get_property_list);
  810. if (E) {
  811. Variant::CallError err;
  812. Variant ret = const_cast<GDScriptFunction *>(E->get())->call(const_cast<GDScriptInstance *>(this), NULL, 0, err);
  813. if (err.error == Variant::CallError::CALL_OK) {
  814. if (ret.get_type() != Variant::ARRAY) {
  815. ERR_EXPLAIN("Wrong type for _get_property list, must be an array of dictionaries.");
  816. ERR_FAIL();
  817. }
  818. Array arr = ret;
  819. for (int i = 0; i < arr.size(); i++) {
  820. Dictionary d = arr[i];
  821. ERR_CONTINUE(!d.has("name"));
  822. ERR_CONTINUE(!d.has("type"));
  823. PropertyInfo pinfo;
  824. pinfo.type = Variant::Type(d["type"].operator int());
  825. ERR_CONTINUE(pinfo.type < 0 || pinfo.type >= Variant::VARIANT_MAX);
  826. pinfo.name = d["name"];
  827. ERR_CONTINUE(pinfo.name == "");
  828. if (d.has("hint"))
  829. pinfo.hint = PropertyHint(d["hint"].operator int());
  830. if (d.has("hint_string"))
  831. pinfo.hint_string = d["hint_string"];
  832. if (d.has("usage"))
  833. pinfo.usage = d["usage"];
  834. props.push_back(pinfo);
  835. }
  836. }
  837. }
  838. //instance a fake script for editing the values
  839. Vector<_GDScriptMemberSort> msort;
  840. for (Map<StringName, PropertyInfo>::Element *E = sptr->member_info.front(); E; E = E->next()) {
  841. _GDScriptMemberSort ms;
  842. ERR_CONTINUE(!sptr->member_indices.has(E->key()));
  843. ms.index = sptr->member_indices[E->key()].index;
  844. ms.name = E->key();
  845. msort.push_back(ms);
  846. }
  847. msort.sort();
  848. msort.invert();
  849. for (int i = 0; i < msort.size(); i++) {
  850. props.push_front(sptr->member_info[msort[i].name]);
  851. }
  852. sptr = sptr->_base;
  853. }
  854. for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
  855. p_properties->push_back(E->get());
  856. }
  857. }
  858. void GDScriptInstance::get_method_list(List<MethodInfo> *p_list) const {
  859. const GDScript *sptr = script.ptr();
  860. while (sptr) {
  861. for (Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.front(); E; E = E->next()) {
  862. MethodInfo mi;
  863. mi.name = E->key();
  864. mi.flags |= METHOD_FLAG_FROM_SCRIPT;
  865. for (int i = 0; i < E->get()->get_argument_count(); i++)
  866. mi.arguments.push_back(PropertyInfo(Variant::NIL, "arg" + itos(i)));
  867. p_list->push_back(mi);
  868. }
  869. sptr = sptr->_base;
  870. }
  871. }
  872. bool GDScriptInstance::has_method(const StringName &p_method) const {
  873. const GDScript *sptr = script.ptr();
  874. while (sptr) {
  875. const Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(p_method);
  876. if (E)
  877. return true;
  878. sptr = sptr->_base;
  879. }
  880. return false;
  881. }
  882. Variant GDScriptInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  883. //printf("calling %ls:%i method %ls\n", script->get_path().c_str(), -1, String(p_method).c_str());
  884. GDScript *sptr = script.ptr();
  885. while (sptr) {
  886. Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(p_method);
  887. if (E) {
  888. return E->get()->call(this, p_args, p_argcount, r_error);
  889. }
  890. sptr = sptr->_base;
  891. }
  892. r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
  893. return Variant();
  894. }
  895. void GDScriptInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) {
  896. GDScript *sptr = script.ptr();
  897. Variant::CallError ce;
  898. while (sptr) {
  899. Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(p_method);
  900. if (E) {
  901. E->get()->call(this, p_args, p_argcount, ce);
  902. }
  903. sptr = sptr->_base;
  904. }
  905. }
  906. void GDScriptInstance::_ml_call_reversed(GDScript *sptr, const StringName &p_method, const Variant **p_args, int p_argcount) {
  907. if (sptr->_base)
  908. _ml_call_reversed(sptr->_base, p_method, p_args, p_argcount);
  909. Variant::CallError ce;
  910. Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(p_method);
  911. if (E) {
  912. E->get()->call(this, p_args, p_argcount, ce);
  913. }
  914. }
  915. void GDScriptInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) {
  916. if (script.ptr()) {
  917. _ml_call_reversed(script.ptr(), p_method, p_args, p_argcount);
  918. }
  919. }
  920. void GDScriptInstance::notification(int p_notification) {
  921. //notification is not virtual, it gets called at ALL levels just like in C.
  922. Variant value = p_notification;
  923. const Variant *args[1] = { &value };
  924. GDScript *sptr = script.ptr();
  925. while (sptr) {
  926. Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._notification);
  927. if (E) {
  928. Variant::CallError err;
  929. E->get()->call(this, args, 1, err);
  930. if (err.error != Variant::CallError::CALL_OK) {
  931. //print error about notification call
  932. }
  933. }
  934. sptr = sptr->_base;
  935. }
  936. }
  937. Ref<Script> GDScriptInstance::get_script() const {
  938. return script;
  939. }
  940. ScriptLanguage *GDScriptInstance::get_language() {
  941. return GDScriptLanguage::get_singleton();
  942. }
  943. MultiplayerAPI::RPCMode GDScriptInstance::get_rpc_mode(const StringName &p_method) const {
  944. const GDScript *cscript = script.ptr();
  945. while (cscript) {
  946. const Map<StringName, GDScriptFunction *>::Element *E = cscript->member_functions.find(p_method);
  947. if (E) {
  948. if (E->get()->get_rpc_mode() != MultiplayerAPI::RPC_MODE_DISABLED) {
  949. return E->get()->get_rpc_mode();
  950. }
  951. }
  952. cscript = cscript->_base;
  953. }
  954. return MultiplayerAPI::RPC_MODE_DISABLED;
  955. }
  956. MultiplayerAPI::RPCMode GDScriptInstance::get_rset_mode(const StringName &p_variable) const {
  957. const GDScript *cscript = script.ptr();
  958. while (cscript) {
  959. const Map<StringName, GDScript::MemberInfo>::Element *E = cscript->member_indices.find(p_variable);
  960. if (E) {
  961. if (E->get().rpc_mode) {
  962. return E->get().rpc_mode;
  963. }
  964. }
  965. cscript = cscript->_base;
  966. }
  967. return MultiplayerAPI::RPC_MODE_DISABLED;
  968. }
  969. void GDScriptInstance::reload_members() {
  970. #ifdef DEBUG_ENABLED
  971. members.resize(script->member_indices.size()); //resize
  972. Vector<Variant> new_members;
  973. new_members.resize(script->member_indices.size());
  974. //pass the values to the new indices
  975. for (Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.front(); E; E = E->next()) {
  976. if (member_indices_cache.has(E->key())) {
  977. Variant value = members[member_indices_cache[E->key()]];
  978. new_members.write[E->get().index] = value;
  979. }
  980. }
  981. //apply
  982. members = new_members;
  983. //pass the values to the new indices
  984. member_indices_cache.clear();
  985. for (Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.front(); E; E = E->next()) {
  986. member_indices_cache[E->key()] = E->get().index;
  987. }
  988. #endif
  989. }
  990. GDScriptInstance::GDScriptInstance() {
  991. owner = NULL;
  992. base_ref = false;
  993. }
  994. GDScriptInstance::~GDScriptInstance() {
  995. if (script.is_valid() && owner) {
  996. #ifndef NO_THREADS
  997. GDScriptLanguage::singleton->lock->lock();
  998. #endif
  999. script->instances.erase(owner);
  1000. #ifndef NO_THREADS
  1001. GDScriptLanguage::singleton->lock->unlock();
  1002. #endif
  1003. }
  1004. }
  1005. /************* SCRIPT LANGUAGE **************/
  1006. GDScriptLanguage *GDScriptLanguage::singleton = NULL;
  1007. String GDScriptLanguage::get_name() const {
  1008. return "GDScript";
  1009. }
  1010. /* LANGUAGE FUNCTIONS */
  1011. void GDScriptLanguage::_add_global(const StringName &p_name, const Variant &p_value) {
  1012. if (globals.has(p_name)) {
  1013. //overwrite existing
  1014. global_array.write[globals[p_name]] = p_value;
  1015. return;
  1016. }
  1017. globals[p_name] = global_array.size();
  1018. global_array.push_back(p_value);
  1019. _global_array = global_array.ptrw();
  1020. }
  1021. void GDScriptLanguage::add_global_constant(const StringName &p_variable, const Variant &p_value) {
  1022. _add_global(p_variable, p_value);
  1023. }
  1024. void GDScriptLanguage::add_named_global_constant(const StringName &p_name, const Variant &p_value) {
  1025. named_globals[p_name] = p_value;
  1026. }
  1027. void GDScriptLanguage::remove_named_global_constant(const StringName &p_name) {
  1028. ERR_FAIL_COND(!named_globals.has(p_name));
  1029. named_globals.erase(p_name);
  1030. }
  1031. void GDScriptLanguage::init() {
  1032. //populate global constants
  1033. int gcc = GlobalConstants::get_global_constant_count();
  1034. for (int i = 0; i < gcc; i++) {
  1035. _add_global(StaticCString::create(GlobalConstants::get_global_constant_name(i)), GlobalConstants::get_global_constant_value(i));
  1036. }
  1037. _add_global(StaticCString::create("PI"), Math_PI);
  1038. _add_global(StaticCString::create("TAU"), Math_TAU);
  1039. _add_global(StaticCString::create("INF"), Math_INF);
  1040. _add_global(StaticCString::create("NAN"), Math_NAN);
  1041. //populate native classes
  1042. List<StringName> class_list;
  1043. ClassDB::get_class_list(&class_list);
  1044. for (List<StringName>::Element *E = class_list.front(); E; E = E->next()) {
  1045. StringName n = E->get();
  1046. String s = String(n);
  1047. if (s.begins_with("_"))
  1048. n = s.substr(1, s.length());
  1049. if (globals.has(n))
  1050. continue;
  1051. Ref<GDScriptNativeClass> nc = memnew(GDScriptNativeClass(E->get()));
  1052. _add_global(n, nc);
  1053. }
  1054. //populate singletons
  1055. List<Engine::Singleton> singletons;
  1056. Engine::get_singleton()->get_singletons(&singletons);
  1057. for (List<Engine::Singleton>::Element *E = singletons.front(); E; E = E->next()) {
  1058. _add_global(E->get().name, E->get().ptr);
  1059. }
  1060. }
  1061. String GDScriptLanguage::get_type() const {
  1062. return "GDScript";
  1063. }
  1064. String GDScriptLanguage::get_extension() const {
  1065. return "gd";
  1066. }
  1067. Error GDScriptLanguage::execute_file(const String &p_path) {
  1068. // ??
  1069. return OK;
  1070. }
  1071. void GDScriptLanguage::finish() {
  1072. }
  1073. void GDScriptLanguage::profiling_start() {
  1074. #ifdef DEBUG_ENABLED
  1075. if (lock) {
  1076. lock->lock();
  1077. }
  1078. SelfList<GDScriptFunction> *elem = function_list.first();
  1079. while (elem) {
  1080. elem->self()->profile.call_count = 0;
  1081. elem->self()->profile.self_time = 0;
  1082. elem->self()->profile.total_time = 0;
  1083. elem->self()->profile.frame_call_count = 0;
  1084. elem->self()->profile.frame_self_time = 0;
  1085. elem->self()->profile.frame_total_time = 0;
  1086. elem->self()->profile.last_frame_call_count = 0;
  1087. elem->self()->profile.last_frame_self_time = 0;
  1088. elem->self()->profile.last_frame_total_time = 0;
  1089. elem = elem->next();
  1090. }
  1091. profiling = true;
  1092. if (lock) {
  1093. lock->unlock();
  1094. }
  1095. #endif
  1096. }
  1097. void GDScriptLanguage::profiling_stop() {
  1098. #ifdef DEBUG_ENABLED
  1099. if (lock) {
  1100. lock->lock();
  1101. }
  1102. profiling = false;
  1103. if (lock) {
  1104. lock->unlock();
  1105. }
  1106. #endif
  1107. }
  1108. int GDScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) {
  1109. int current = 0;
  1110. #ifdef DEBUG_ENABLED
  1111. if (lock) {
  1112. lock->lock();
  1113. }
  1114. SelfList<GDScriptFunction> *elem = function_list.first();
  1115. while (elem) {
  1116. if (current >= p_info_max)
  1117. break;
  1118. p_info_arr[current].call_count = elem->self()->profile.call_count;
  1119. p_info_arr[current].self_time = elem->self()->profile.self_time;
  1120. p_info_arr[current].total_time = elem->self()->profile.total_time;
  1121. p_info_arr[current].signature = elem->self()->profile.signature;
  1122. elem = elem->next();
  1123. current++;
  1124. }
  1125. if (lock) {
  1126. lock->unlock();
  1127. }
  1128. #endif
  1129. return current;
  1130. }
  1131. int GDScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) {
  1132. int current = 0;
  1133. #ifdef DEBUG_ENABLED
  1134. if (lock) {
  1135. lock->lock();
  1136. }
  1137. SelfList<GDScriptFunction> *elem = function_list.first();
  1138. while (elem) {
  1139. if (current >= p_info_max)
  1140. break;
  1141. if (elem->self()->profile.last_frame_call_count > 0) {
  1142. p_info_arr[current].call_count = elem->self()->profile.last_frame_call_count;
  1143. p_info_arr[current].self_time = elem->self()->profile.last_frame_self_time;
  1144. p_info_arr[current].total_time = elem->self()->profile.last_frame_total_time;
  1145. p_info_arr[current].signature = elem->self()->profile.signature;
  1146. //print_line(String(elem->self()->profile.signature)+": "+itos(elem->self()->profile.last_frame_call_count));
  1147. current++;
  1148. }
  1149. elem = elem->next();
  1150. }
  1151. if (lock) {
  1152. lock->unlock();
  1153. }
  1154. #endif
  1155. return current;
  1156. }
  1157. struct GDScriptDepSort {
  1158. //must support sorting so inheritance works properly (parent must be reloaded first)
  1159. bool operator()(const Ref<GDScript> &A, const Ref<GDScript> &B) const {
  1160. if (A == B)
  1161. return false; //shouldn't happen but..
  1162. const GDScript *I = B->get_base().ptr();
  1163. while (I) {
  1164. if (I == A.ptr()) {
  1165. // A is a base of B
  1166. return true;
  1167. }
  1168. I = I->get_base().ptr();
  1169. }
  1170. return false; //not a base
  1171. }
  1172. };
  1173. void GDScriptLanguage::reload_all_scripts() {
  1174. #ifdef DEBUG_ENABLED
  1175. print_line("RELOAD ALL SCRIPTS");
  1176. if (lock) {
  1177. lock->lock();
  1178. }
  1179. List<Ref<GDScript> > scripts;
  1180. SelfList<GDScript> *elem = script_list.first();
  1181. while (elem) {
  1182. if (elem->self()->get_path().is_resource_file()) {
  1183. print_line("FOUND: " + elem->self()->get_path());
  1184. scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident
  1185. }
  1186. elem = elem->next();
  1187. }
  1188. if (lock) {
  1189. lock->unlock();
  1190. }
  1191. //as scripts are going to be reloaded, must proceed without locking here
  1192. scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order
  1193. for (List<Ref<GDScript> >::Element *E = scripts.front(); E; E = E->next()) {
  1194. print_line("RELOADING: " + E->get()->get_path());
  1195. E->get()->load_source_code(E->get()->get_path());
  1196. E->get()->reload(true);
  1197. }
  1198. #endif
  1199. }
  1200. void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
  1201. #ifdef DEBUG_ENABLED
  1202. if (lock) {
  1203. lock->lock();
  1204. }
  1205. List<Ref<GDScript> > scripts;
  1206. SelfList<GDScript> *elem = script_list.first();
  1207. while (elem) {
  1208. if (elem->self()->get_path().is_resource_file()) {
  1209. scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident
  1210. }
  1211. elem = elem->next();
  1212. }
  1213. if (lock) {
  1214. lock->unlock();
  1215. }
  1216. //when someone asks you why dynamically typed languages are easier to write....
  1217. Map<Ref<GDScript>, Map<ObjectID, List<Pair<StringName, Variant> > > > to_reload;
  1218. //as scripts are going to be reloaded, must proceed without locking here
  1219. scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order
  1220. for (List<Ref<GDScript> >::Element *E = scripts.front(); E; E = E->next()) {
  1221. bool reload = E->get() == p_script || to_reload.has(E->get()->get_base());
  1222. if (!reload)
  1223. continue;
  1224. to_reload.insert(E->get(), Map<ObjectID, List<Pair<StringName, Variant> > >());
  1225. if (!p_soft_reload) {
  1226. //save state and remove script from instances
  1227. Map<ObjectID, List<Pair<StringName, Variant> > > &map = to_reload[E->get()];
  1228. while (E->get()->instances.front()) {
  1229. Object *obj = E->get()->instances.front()->get();
  1230. //save instance info
  1231. List<Pair<StringName, Variant> > state;
  1232. if (obj->get_script_instance()) {
  1233. obj->get_script_instance()->get_property_state(state);
  1234. map[obj->get_instance_id()] = state;
  1235. obj->set_script(RefPtr());
  1236. }
  1237. }
  1238. //same thing for placeholders
  1239. #ifdef TOOLS_ENABLED
  1240. while (E->get()->placeholders.size()) {
  1241. Object *obj = E->get()->placeholders.front()->get()->get_owner();
  1242. //save instance info
  1243. if (obj->get_script_instance()) {
  1244. map.insert(obj->get_instance_id(), List<Pair<StringName, Variant> >());
  1245. List<Pair<StringName, Variant> > &state = map[obj->get_instance_id()];
  1246. obj->get_script_instance()->get_property_state(state);
  1247. obj->set_script(RefPtr());
  1248. } else {
  1249. // no instance found. Let's remove it so we don't loop forever
  1250. E->get()->placeholders.erase(E->get()->placeholders.front()->get());
  1251. }
  1252. }
  1253. #endif
  1254. for (Map<ObjectID, List<Pair<StringName, Variant> > >::Element *F = E->get()->pending_reload_state.front(); F; F = F->next()) {
  1255. map[F->key()] = F->get(); //pending to reload, use this one instead
  1256. }
  1257. }
  1258. }
  1259. for (Map<Ref<GDScript>, Map<ObjectID, List<Pair<StringName, Variant> > > >::Element *E = to_reload.front(); E; E = E->next()) {
  1260. Ref<GDScript> scr = E->key();
  1261. scr->reload(p_soft_reload);
  1262. //restore state if saved
  1263. for (Map<ObjectID, List<Pair<StringName, Variant> > >::Element *F = E->get().front(); F; F = F->next()) {
  1264. Object *obj = ObjectDB::get_instance(F->key());
  1265. if (!obj)
  1266. continue;
  1267. if (!p_soft_reload) {
  1268. //clear it just in case (may be a pending reload state)
  1269. obj->set_script(RefPtr());
  1270. }
  1271. obj->set_script(scr.get_ref_ptr());
  1272. if (!obj->get_script_instance()) {
  1273. //failed, save reload state for next time if not saved
  1274. if (!scr->pending_reload_state.has(obj->get_instance_id())) {
  1275. scr->pending_reload_state[obj->get_instance_id()] = F->get();
  1276. }
  1277. continue;
  1278. }
  1279. for (List<Pair<StringName, Variant> >::Element *G = F->get().front(); G; G = G->next()) {
  1280. obj->get_script_instance()->set(G->get().first, G->get().second);
  1281. }
  1282. scr->pending_reload_state.erase(obj->get_instance_id()); //as it reloaded, remove pending state
  1283. }
  1284. //if instance states were saved, set them!
  1285. }
  1286. #endif
  1287. }
  1288. void GDScriptLanguage::frame() {
  1289. //print_line("calls: "+itos(calls));
  1290. calls = 0;
  1291. #ifdef DEBUG_ENABLED
  1292. if (profiling) {
  1293. if (lock) {
  1294. lock->lock();
  1295. }
  1296. SelfList<GDScriptFunction> *elem = function_list.first();
  1297. while (elem) {
  1298. elem->self()->profile.last_frame_call_count = elem->self()->profile.frame_call_count;
  1299. elem->self()->profile.last_frame_self_time = elem->self()->profile.frame_self_time;
  1300. elem->self()->profile.last_frame_total_time = elem->self()->profile.frame_total_time;
  1301. elem->self()->profile.frame_call_count = 0;
  1302. elem->self()->profile.frame_self_time = 0;
  1303. elem->self()->profile.frame_total_time = 0;
  1304. elem = elem->next();
  1305. }
  1306. if (lock) {
  1307. lock->unlock();
  1308. }
  1309. }
  1310. #endif
  1311. }
  1312. /* EDITOR FUNCTIONS */
  1313. void GDScriptLanguage::get_reserved_words(List<String> *p_words) const {
  1314. static const char *_reserved_words[] = {
  1315. // operators
  1316. "and",
  1317. "in",
  1318. "not",
  1319. "or",
  1320. // types and values
  1321. "false",
  1322. "float",
  1323. "int",
  1324. "bool",
  1325. "null",
  1326. "PI",
  1327. "TAU",
  1328. "INF",
  1329. "NAN",
  1330. "self",
  1331. "true",
  1332. "void",
  1333. // functions
  1334. "as",
  1335. "assert",
  1336. "breakpoint",
  1337. "class",
  1338. "class_name",
  1339. "extends",
  1340. "is",
  1341. "func",
  1342. "preload",
  1343. "setget",
  1344. "signal",
  1345. "tool",
  1346. "yield",
  1347. // var
  1348. "const",
  1349. "enum",
  1350. "export",
  1351. "onready",
  1352. "static",
  1353. "var",
  1354. // control flow
  1355. "break",
  1356. "continue",
  1357. "if",
  1358. "elif",
  1359. "else",
  1360. "for",
  1361. "pass",
  1362. "return",
  1363. "match",
  1364. "while",
  1365. "remote",
  1366. "sync",
  1367. "master",
  1368. "slave",
  1369. "remotesync",
  1370. "mastersync",
  1371. "slavesync",
  1372. 0
  1373. };
  1374. const char **w = _reserved_words;
  1375. while (*w) {
  1376. p_words->push_back(*w);
  1377. w++;
  1378. }
  1379. for (int i = 0; i < GDScriptFunctions::FUNC_MAX; i++) {
  1380. p_words->push_back(GDScriptFunctions::get_func_name(GDScriptFunctions::Function(i)));
  1381. }
  1382. }
  1383. bool GDScriptLanguage::handles_global_class_type(const String &p_type) const {
  1384. return p_type == "GDScript";
  1385. }
  1386. String GDScriptLanguage::get_global_class_name(const String &p_path, String *r_base_type) const {
  1387. PoolVector<uint8_t> sourcef;
  1388. Error err;
  1389. FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
  1390. if (err) {
  1391. return String();
  1392. }
  1393. int len = f->get_len();
  1394. sourcef.resize(len + 1);
  1395. PoolVector<uint8_t>::Write w = sourcef.write();
  1396. int r = f->get_buffer(w.ptr(), len);
  1397. f->close();
  1398. memdelete(f);
  1399. ERR_FAIL_COND_V(r != len, String());
  1400. w[len] = 0;
  1401. String s;
  1402. if (s.parse_utf8((const char *)w.ptr())) {
  1403. return String();
  1404. }
  1405. GDScriptParser parser;
  1406. parser.parse(s, p_path.get_base_dir(), true, p_path);
  1407. if (parser.get_parse_tree() && parser.get_parse_tree()->type == GDScriptParser::Node::TYPE_CLASS) {
  1408. const GDScriptParser::ClassNode *c = static_cast<const GDScriptParser::ClassNode *>(parser.get_parse_tree());
  1409. if (r_base_type) {
  1410. GDScriptParser::DataType base_type;
  1411. if (c->base_type.has_type) {
  1412. base_type = c->base_type;
  1413. while (base_type.has_type && base_type.kind != GDScriptParser::DataType::NATIVE) {
  1414. switch (base_type.kind) {
  1415. case GDScriptParser::DataType::CLASS: {
  1416. base_type = base_type.class_type->base_type;
  1417. } break;
  1418. case GDScriptParser::DataType::GDSCRIPT: {
  1419. Ref<GDScript> gds = base_type.script_type;
  1420. if (gds.is_valid()) {
  1421. base_type.kind = GDScriptParser::DataType::NATIVE;
  1422. base_type.native_type = gds->get_instance_base_type();
  1423. } else {
  1424. base_type = GDScriptParser::DataType();
  1425. }
  1426. } break;
  1427. default: {
  1428. base_type = GDScriptParser::DataType();
  1429. } break;
  1430. }
  1431. }
  1432. }
  1433. if (base_type.has_type) {
  1434. *r_base_type = base_type.native_type;
  1435. } else {
  1436. // Fallback
  1437. if (c->extends_used && c->extends_class.size() == 1) {
  1438. *r_base_type = c->extends_class[0];
  1439. } else if (!c->extends_used) {
  1440. *r_base_type = "Reference";
  1441. }
  1442. }
  1443. }
  1444. return c->name;
  1445. }
  1446. return String();
  1447. }
  1448. GDScriptLanguage::GDScriptLanguage() {
  1449. calls = 0;
  1450. ERR_FAIL_COND(singleton);
  1451. singleton = this;
  1452. strings._init = StaticCString::create("_init");
  1453. strings._notification = StaticCString::create("_notification");
  1454. strings._set = StaticCString::create("_set");
  1455. strings._get = StaticCString::create("_get");
  1456. strings._get_property_list = StaticCString::create("_get_property_list");
  1457. strings._script_source = StaticCString::create("script/source");
  1458. _debug_parse_err_line = -1;
  1459. _debug_parse_err_file = "";
  1460. #ifdef NO_THREADS
  1461. lock = NULL;
  1462. #else
  1463. lock = Mutex::create();
  1464. #endif
  1465. profiling = false;
  1466. script_frame_time = 0;
  1467. _debug_call_stack_pos = 0;
  1468. int dmcs = GLOBAL_DEF("debug/settings/gdscript/max_call_stack", 1024);
  1469. if (ScriptDebugger::get_singleton()) {
  1470. //debugging enabled!
  1471. _debug_max_call_stack = dmcs;
  1472. if (_debug_max_call_stack < 1024)
  1473. _debug_max_call_stack = 1024;
  1474. _call_stack = memnew_arr(CallLevel, _debug_max_call_stack + 1);
  1475. } else {
  1476. _debug_max_call_stack = 0;
  1477. _call_stack = NULL;
  1478. }
  1479. }
  1480. GDScriptLanguage::~GDScriptLanguage() {
  1481. if (lock) {
  1482. memdelete(lock);
  1483. lock = NULL;
  1484. }
  1485. if (_call_stack) {
  1486. memdelete_arr(_call_stack);
  1487. }
  1488. singleton = NULL;
  1489. }
  1490. /*************** RESOURCE ***************/
  1491. RES ResourceFormatLoaderGDScript::load(const String &p_path, const String &p_original_path, Error *r_error) {
  1492. if (r_error)
  1493. *r_error = ERR_FILE_CANT_OPEN;
  1494. GDScript *script = memnew(GDScript);
  1495. Ref<GDScript> scriptres(script);
  1496. if (p_path.ends_with(".gde") || p_path.ends_with(".gdc")) {
  1497. script->set_script_path(p_original_path); // script needs this.
  1498. script->set_path(p_original_path);
  1499. Error err = script->load_byte_code(p_path);
  1500. if (err != OK) {
  1501. ERR_FAIL_COND_V(err != OK, RES());
  1502. }
  1503. } else {
  1504. Error err = script->load_source_code(p_path);
  1505. if (err != OK) {
  1506. ERR_FAIL_COND_V(err != OK, RES());
  1507. }
  1508. script->set_script_path(p_original_path); // script needs this.
  1509. script->set_path(p_original_path);
  1510. //script->set_name(p_path.get_file());
  1511. script->reload();
  1512. }
  1513. if (r_error)
  1514. *r_error = OK;
  1515. return scriptres;
  1516. }
  1517. void ResourceFormatLoaderGDScript::get_recognized_extensions(List<String> *p_extensions) const {
  1518. p_extensions->push_back("gd");
  1519. p_extensions->push_back("gdc");
  1520. p_extensions->push_back("gde");
  1521. }
  1522. bool ResourceFormatLoaderGDScript::handles_type(const String &p_type) const {
  1523. return (p_type == "Script" || p_type == "GDScript");
  1524. }
  1525. String ResourceFormatLoaderGDScript::get_resource_type(const String &p_path) const {
  1526. String el = p_path.get_extension().to_lower();
  1527. if (el == "gd" || el == "gdc" || el == "gde")
  1528. return "GDScript";
  1529. return "";
  1530. }
  1531. Error ResourceFormatSaverGDScript::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
  1532. Ref<GDScript> sqscr = p_resource;
  1533. ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
  1534. String source = sqscr->get_source_code();
  1535. Error err;
  1536. FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  1537. if (err) {
  1538. ERR_FAIL_COND_V(err, err);
  1539. }
  1540. file->store_string(source);
  1541. if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
  1542. memdelete(file);
  1543. return ERR_CANT_CREATE;
  1544. }
  1545. file->close();
  1546. memdelete(file);
  1547. if (ScriptServer::is_reload_scripts_on_save_enabled()) {
  1548. GDScriptLanguage::get_singleton()->reload_tool_script(p_resource, false);
  1549. }
  1550. return OK;
  1551. }
  1552. void ResourceFormatSaverGDScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
  1553. if (Object::cast_to<GDScript>(*p_resource)) {
  1554. p_extensions->push_back("gd");
  1555. }
  1556. }
  1557. bool ResourceFormatSaverGDScript::recognize(const RES &p_resource) const {
  1558. return Object::cast_to<GDScript>(*p_resource) != NULL;
  1559. }