gd_script.cpp 47 KB

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