gdscript_cache.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. /**************************************************************************/
  2. /* gdscript_cache.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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_cache.h"
  31. #include "gdscript.h"
  32. #include "gdscript_analyzer.h"
  33. #include "gdscript_compiler.h"
  34. #include "gdscript_parser.h"
  35. #include "core/io/file_access.h"
  36. #include "core/templates/vector.h"
  37. GDScriptParserRef::Status GDScriptParserRef::get_status() const {
  38. return status;
  39. }
  40. String GDScriptParserRef::get_path() const {
  41. return path;
  42. }
  43. uint32_t GDScriptParserRef::get_source_hash() const {
  44. return source_hash;
  45. }
  46. GDScriptParser *GDScriptParserRef::get_parser() {
  47. if (parser == nullptr) {
  48. parser = memnew(GDScriptParser);
  49. }
  50. return parser;
  51. }
  52. GDScriptAnalyzer *GDScriptParserRef::get_analyzer() {
  53. if (analyzer == nullptr) {
  54. analyzer = memnew(GDScriptAnalyzer(get_parser()));
  55. }
  56. return analyzer;
  57. }
  58. Error GDScriptParserRef::raise_status(Status p_new_status) {
  59. ERR_FAIL_COND_V(clearing, ERR_BUG);
  60. ERR_FAIL_COND_V(parser == nullptr && status != EMPTY, ERR_BUG);
  61. while (result == OK && p_new_status > status) {
  62. switch (status) {
  63. case EMPTY: {
  64. // Calling parse will clear the parser, which can destruct another GDScriptParserRef which can clear the last reference to the script with this path, calling remove_script, which clears this GDScriptParserRef.
  65. // It's ok if its the first thing done here.
  66. get_parser()->clear();
  67. status = PARSED;
  68. String remapped_path = ResourceLoader::path_remap(path);
  69. if (remapped_path.get_extension().to_lower() == "gdc") {
  70. Vector<uint8_t> tokens = GDScriptCache::get_binary_tokens(remapped_path);
  71. source_hash = hash_djb2_buffer(tokens.ptr(), tokens.size());
  72. result = get_parser()->parse_binary(tokens, path);
  73. } else {
  74. String source = GDScriptCache::get_source_code(remapped_path);
  75. source_hash = source.hash();
  76. result = get_parser()->parse(source, path, false);
  77. }
  78. } break;
  79. case PARSED: {
  80. status = INHERITANCE_SOLVED;
  81. result = get_analyzer()->resolve_inheritance();
  82. } break;
  83. case INHERITANCE_SOLVED: {
  84. status = INTERFACE_SOLVED;
  85. result = get_analyzer()->resolve_interface();
  86. } break;
  87. case INTERFACE_SOLVED: {
  88. status = FULLY_SOLVED;
  89. result = get_analyzer()->resolve_body();
  90. } break;
  91. case FULLY_SOLVED: {
  92. return result;
  93. }
  94. }
  95. }
  96. return result;
  97. }
  98. void GDScriptParserRef::clear() {
  99. if (clearing) {
  100. return;
  101. }
  102. clearing = true;
  103. GDScriptParser *lparser = parser;
  104. GDScriptAnalyzer *lanalyzer = analyzer;
  105. parser = nullptr;
  106. analyzer = nullptr;
  107. status = EMPTY;
  108. result = OK;
  109. source_hash = 0;
  110. clearing = false;
  111. if (lanalyzer != nullptr) {
  112. memdelete(lanalyzer);
  113. }
  114. if (lparser != nullptr) {
  115. memdelete(lparser);
  116. }
  117. }
  118. GDScriptParserRef::~GDScriptParserRef() {
  119. clear();
  120. if (!abandoned) {
  121. MutexLock lock(GDScriptCache::singleton->mutex);
  122. GDScriptCache::singleton->parser_map.erase(path);
  123. }
  124. }
  125. GDScriptCache *GDScriptCache::singleton = nullptr;
  126. SafeBinaryMutex<GDScriptCache::BINARY_MUTEX_TAG> &_get_gdscript_cache_mutex() {
  127. return GDScriptCache::mutex;
  128. }
  129. template <>
  130. thread_local SafeBinaryMutex<GDScriptCache::BINARY_MUTEX_TAG>::TLSData SafeBinaryMutex<GDScriptCache::BINARY_MUTEX_TAG>::tls_data(_get_gdscript_cache_mutex());
  131. SafeBinaryMutex<GDScriptCache::BINARY_MUTEX_TAG> GDScriptCache::mutex;
  132. void GDScriptCache::move_script(const String &p_from, const String &p_to) {
  133. if (singleton == nullptr || p_from == p_to) {
  134. return;
  135. }
  136. MutexLock lock(singleton->mutex);
  137. if (singleton->cleared) {
  138. return;
  139. }
  140. remove_parser(p_from);
  141. if (singleton->shallow_gdscript_cache.has(p_from) && !p_from.is_empty()) {
  142. singleton->shallow_gdscript_cache[p_to] = singleton->shallow_gdscript_cache[p_from];
  143. }
  144. singleton->shallow_gdscript_cache.erase(p_from);
  145. if (singleton->full_gdscript_cache.has(p_from) && !p_from.is_empty()) {
  146. singleton->full_gdscript_cache[p_to] = singleton->full_gdscript_cache[p_from];
  147. }
  148. singleton->full_gdscript_cache.erase(p_from);
  149. }
  150. void GDScriptCache::remove_script(const String &p_path) {
  151. if (singleton == nullptr) {
  152. return;
  153. }
  154. MutexLock lock(singleton->mutex);
  155. if (singleton->cleared) {
  156. return;
  157. }
  158. if (HashMap<String, Vector<ObjectID>>::Iterator E = singleton->abandoned_parser_map.find(p_path)) {
  159. for (ObjectID parser_ref_id : E->value) {
  160. Ref<GDScriptParserRef> parser_ref{ ObjectDB::get_instance(parser_ref_id) };
  161. if (parser_ref.is_valid()) {
  162. parser_ref->clear();
  163. }
  164. }
  165. }
  166. singleton->abandoned_parser_map.erase(p_path);
  167. if (singleton->parser_map.has(p_path)) {
  168. singleton->parser_map[p_path]->clear();
  169. }
  170. remove_parser(p_path);
  171. singleton->dependencies.erase(p_path);
  172. singleton->shallow_gdscript_cache.erase(p_path);
  173. singleton->full_gdscript_cache.erase(p_path);
  174. }
  175. Ref<GDScriptParserRef> GDScriptCache::get_parser(const String &p_path, GDScriptParserRef::Status p_status, Error &r_error, const String &p_owner) {
  176. MutexLock lock(singleton->mutex);
  177. Ref<GDScriptParserRef> ref;
  178. if (!p_owner.is_empty()) {
  179. singleton->dependencies[p_owner].insert(p_path);
  180. singleton->parser_inverse_dependencies[p_path].insert(p_owner);
  181. }
  182. if (singleton->parser_map.has(p_path)) {
  183. ref = Ref<GDScriptParserRef>(singleton->parser_map[p_path]);
  184. if (ref.is_null()) {
  185. r_error = ERR_INVALID_DATA;
  186. return ref;
  187. }
  188. } else {
  189. String remapped_path = ResourceLoader::path_remap(p_path);
  190. if (!FileAccess::exists(remapped_path)) {
  191. r_error = ERR_FILE_NOT_FOUND;
  192. return ref;
  193. }
  194. ref.instantiate();
  195. ref->path = p_path;
  196. singleton->parser_map[p_path] = ref.ptr();
  197. }
  198. r_error = ref->raise_status(p_status);
  199. return ref;
  200. }
  201. bool GDScriptCache::has_parser(const String &p_path) {
  202. MutexLock lock(singleton->mutex);
  203. return singleton->parser_map.has(p_path);
  204. }
  205. void GDScriptCache::remove_parser(const String &p_path) {
  206. MutexLock lock(singleton->mutex);
  207. if (singleton->parser_map.has(p_path)) {
  208. GDScriptParserRef *parser_ref = singleton->parser_map[p_path];
  209. parser_ref->abandoned = true;
  210. singleton->abandoned_parser_map[p_path].push_back(parser_ref->get_instance_id());
  211. }
  212. // Can't clear the parser because some other parser might be currently using it in the chain of calls.
  213. singleton->parser_map.erase(p_path);
  214. // Have to copy while iterating, because parser_inverse_dependencies is modified.
  215. HashSet<String> ideps = singleton->parser_inverse_dependencies[p_path];
  216. singleton->parser_inverse_dependencies.erase(p_path);
  217. for (String idep_path : ideps) {
  218. remove_parser(idep_path);
  219. }
  220. }
  221. String GDScriptCache::get_source_code(const String &p_path) {
  222. Vector<uint8_t> source_file;
  223. Error err;
  224. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);
  225. ERR_FAIL_COND_V(err, "");
  226. uint64_t len = f->get_length();
  227. source_file.resize(len + 1);
  228. uint64_t r = f->get_buffer(source_file.ptrw(), len);
  229. ERR_FAIL_COND_V(r != len, "");
  230. source_file.write[len] = 0;
  231. String source;
  232. if (source.parse_utf8((const char *)source_file.ptr(), len) != OK) {
  233. ERR_FAIL_V_MSG("", "Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded. Please ensure that scripts are saved in valid UTF-8 unicode.");
  234. }
  235. return source;
  236. }
  237. Vector<uint8_t> GDScriptCache::get_binary_tokens(const String &p_path) {
  238. Vector<uint8_t> buffer;
  239. Error err = OK;
  240. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);
  241. ERR_FAIL_COND_V_MSG(err != OK, buffer, "Failed to open binary GDScript file '" + p_path + "'.");
  242. uint64_t len = f->get_length();
  243. buffer.resize(len);
  244. uint64_t read = f->get_buffer(buffer.ptrw(), buffer.size());
  245. ERR_FAIL_COND_V_MSG(read != len, Vector<uint8_t>(), "Failed to read binary GDScript file '" + p_path + "'.");
  246. return buffer;
  247. }
  248. Ref<GDScript> GDScriptCache::get_shallow_script(const String &p_path, Error &r_error, const String &p_owner) {
  249. MutexLock lock(singleton->mutex);
  250. if (!p_owner.is_empty()) {
  251. singleton->dependencies[p_owner].insert(p_path);
  252. }
  253. if (singleton->full_gdscript_cache.has(p_path)) {
  254. return singleton->full_gdscript_cache[p_path];
  255. }
  256. if (singleton->shallow_gdscript_cache.has(p_path)) {
  257. return singleton->shallow_gdscript_cache[p_path];
  258. }
  259. const String remapped_path = ResourceLoader::path_remap(p_path);
  260. Ref<GDScript> script;
  261. script.instantiate();
  262. script->set_path_cache(p_path);
  263. if (remapped_path.get_extension().to_lower() == "gdc") {
  264. Vector<uint8_t> buffer = get_binary_tokens(remapped_path);
  265. if (buffer.is_empty()) {
  266. r_error = ERR_FILE_CANT_READ;
  267. }
  268. script->set_binary_tokens_source(buffer);
  269. } else {
  270. r_error = script->load_source_code(remapped_path);
  271. }
  272. if (r_error) {
  273. return Ref<GDScript>(); // Returns null and does not cache when the script fails to load.
  274. }
  275. Ref<GDScriptParserRef> parser_ref = get_parser(p_path, GDScriptParserRef::PARSED, r_error);
  276. if (r_error == OK) {
  277. GDScriptCompiler::make_scripts(script.ptr(), parser_ref->get_parser()->get_tree(), true);
  278. }
  279. singleton->shallow_gdscript_cache[p_path] = script;
  280. return script;
  281. }
  282. Ref<GDScript> GDScriptCache::get_full_script(const String &p_path, Error &r_error, const String &p_owner, bool p_update_from_disk) {
  283. MutexLock lock(singleton->mutex);
  284. if (!p_owner.is_empty()) {
  285. singleton->dependencies[p_owner].insert(p_path);
  286. }
  287. Ref<GDScript> script;
  288. r_error = OK;
  289. if (singleton->full_gdscript_cache.has(p_path)) {
  290. script = singleton->full_gdscript_cache[p_path];
  291. if (!p_update_from_disk) {
  292. return script;
  293. }
  294. }
  295. if (script.is_null()) {
  296. script = get_shallow_script(p_path, r_error);
  297. // Only exit early if script failed to load, otherwise let reload report errors.
  298. if (script.is_null()) {
  299. return script;
  300. }
  301. }
  302. script->set_path(p_path, true);
  303. const String remapped_path = ResourceLoader::path_remap(p_path);
  304. if (p_update_from_disk) {
  305. if (remapped_path.get_extension().to_lower() == "gdc") {
  306. Vector<uint8_t> buffer = get_binary_tokens(remapped_path);
  307. if (buffer.is_empty()) {
  308. r_error = ERR_FILE_CANT_READ;
  309. return script;
  310. }
  311. script->set_binary_tokens_source(buffer);
  312. } else {
  313. r_error = script->load_source_code(remapped_path);
  314. if (r_error) {
  315. return script;
  316. }
  317. }
  318. }
  319. // Allowing lifting the lock might cause a script to be reloaded multiple times,
  320. // which, as a last resort deadlock prevention strategy, is a good tradeoff.
  321. uint32_t allowance_id = WorkerThreadPool::thread_enter_unlock_allowance_zone(singleton->mutex);
  322. r_error = script->reload(true);
  323. WorkerThreadPool::thread_exit_unlock_allowance_zone(allowance_id);
  324. if (r_error) {
  325. return script;
  326. }
  327. singleton->full_gdscript_cache[p_path] = script;
  328. singleton->shallow_gdscript_cache.erase(p_path);
  329. return script;
  330. }
  331. Ref<GDScript> GDScriptCache::get_cached_script(const String &p_path) {
  332. MutexLock lock(singleton->mutex);
  333. if (singleton->full_gdscript_cache.has(p_path)) {
  334. return singleton->full_gdscript_cache[p_path];
  335. }
  336. if (singleton->shallow_gdscript_cache.has(p_path)) {
  337. return singleton->shallow_gdscript_cache[p_path];
  338. }
  339. return Ref<GDScript>();
  340. }
  341. Error GDScriptCache::finish_compiling(const String &p_owner) {
  342. MutexLock lock(singleton->mutex);
  343. // Mark this as compiled.
  344. Ref<GDScript> script = get_cached_script(p_owner);
  345. singleton->full_gdscript_cache[p_owner] = script;
  346. singleton->shallow_gdscript_cache.erase(p_owner);
  347. HashSet<String> depends = singleton->dependencies[p_owner];
  348. Error err = OK;
  349. for (const String &E : depends) {
  350. Error this_err = OK;
  351. // No need to save the script. We assume it's already referenced in the owner.
  352. get_full_script(E, this_err);
  353. if (this_err != OK) {
  354. err = this_err;
  355. }
  356. }
  357. singleton->dependencies.erase(p_owner);
  358. return err;
  359. }
  360. void GDScriptCache::add_static_script(Ref<GDScript> p_script) {
  361. ERR_FAIL_COND_MSG(p_script.is_null(), "Trying to cache empty script as static.");
  362. ERR_FAIL_COND_MSG(!p_script->is_valid(), "Trying to cache non-compiled script as static.");
  363. singleton->static_gdscript_cache[p_script->get_fully_qualified_name()] = p_script;
  364. }
  365. void GDScriptCache::remove_static_script(const String &p_fqcn) {
  366. singleton->static_gdscript_cache.erase(p_fqcn);
  367. }
  368. void GDScriptCache::clear() {
  369. if (singleton == nullptr) {
  370. return;
  371. }
  372. MutexLock lock(singleton->mutex);
  373. if (singleton->cleared) {
  374. return;
  375. }
  376. singleton->cleared = true;
  377. singleton->parser_inverse_dependencies.clear();
  378. for (const KeyValue<String, Vector<ObjectID>> &KV : singleton->abandoned_parser_map) {
  379. for (ObjectID parser_ref_id : KV.value) {
  380. Ref<GDScriptParserRef> parser_ref{ ObjectDB::get_instance(parser_ref_id) };
  381. if (parser_ref.is_valid()) {
  382. parser_ref->clear();
  383. }
  384. }
  385. }
  386. singleton->abandoned_parser_map.clear();
  387. RBSet<Ref<GDScriptParserRef>> parser_map_refs;
  388. for (KeyValue<String, GDScriptParserRef *> &E : singleton->parser_map) {
  389. parser_map_refs.insert(E.value);
  390. }
  391. singleton->parser_map.clear();
  392. for (Ref<GDScriptParserRef> &E : parser_map_refs) {
  393. if (E.is_valid()) {
  394. E->clear();
  395. }
  396. }
  397. parser_map_refs.clear();
  398. singleton->shallow_gdscript_cache.clear();
  399. singleton->full_gdscript_cache.clear();
  400. }
  401. GDScriptCache::GDScriptCache() {
  402. singleton = this;
  403. }
  404. GDScriptCache::~GDScriptCache() {
  405. if (!cleared) {
  406. clear();
  407. }
  408. singleton = nullptr;
  409. }