gdscript.cpp 50 KB

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