Path: blob/master/modules/gdscript/gdscript_cache.cpp
10277 views
/**************************************************************************/1/* gdscript_cache.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "gdscript_cache.h"3132#include "gdscript.h"33#include "gdscript_analyzer.h"34#include "gdscript_compiler.h"35#include "gdscript_parser.h"3637#include "core/io/file_access.h"38#include "core/templates/vector.h"3940GDScriptParserRef::Status GDScriptParserRef::get_status() const {41return status;42}4344String GDScriptParserRef::get_path() const {45return path;46}4748uint32_t GDScriptParserRef::get_source_hash() const {49return source_hash;50}5152GDScriptParser *GDScriptParserRef::get_parser() {53if (parser == nullptr) {54parser = memnew(GDScriptParser);55}56return parser;57}5859GDScriptAnalyzer *GDScriptParserRef::get_analyzer() {60if (analyzer == nullptr) {61analyzer = memnew(GDScriptAnalyzer(get_parser()));62}63return analyzer;64}6566Error GDScriptParserRef::raise_status(Status p_new_status) {67ERR_FAIL_COND_V(clearing, ERR_BUG);68ERR_FAIL_COND_V(parser == nullptr && status != EMPTY, ERR_BUG);6970while (result == OK && p_new_status > status) {71switch (status) {72case EMPTY: {73// 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.74// It's ok if its the first thing done here.75get_parser()->clear();76status = PARSED;77String remapped_path = ResourceLoader::path_remap(path);78if (remapped_path.get_extension().to_lower() == "gdc") {79Vector<uint8_t> tokens = GDScriptCache::get_binary_tokens(remapped_path);80source_hash = hash_djb2_buffer(tokens.ptr(), tokens.size());81result = get_parser()->parse_binary(tokens, path);82} else {83String source = GDScriptCache::get_source_code(remapped_path);84source_hash = source.hash();85result = get_parser()->parse(source, path, false);86}87} break;88case PARSED: {89status = INHERITANCE_SOLVED;90result = get_analyzer()->resolve_inheritance();91} break;92case INHERITANCE_SOLVED: {93status = INTERFACE_SOLVED;94result = get_analyzer()->resolve_interface();95} break;96case INTERFACE_SOLVED: {97status = FULLY_SOLVED;98result = get_analyzer()->resolve_body();99} break;100case FULLY_SOLVED: {101return result;102}103}104}105106return result;107}108109void GDScriptParserRef::clear() {110if (clearing) {111return;112}113clearing = true;114115GDScriptParser *lparser = parser;116GDScriptAnalyzer *lanalyzer = analyzer;117118parser = nullptr;119analyzer = nullptr;120status = EMPTY;121result = OK;122source_hash = 0;123124clearing = false;125126if (lanalyzer != nullptr) {127memdelete(lanalyzer);128}129130if (lparser != nullptr) {131memdelete(lparser);132}133}134135GDScriptParserRef::~GDScriptParserRef() {136clear();137138if (!abandoned) {139MutexLock lock(GDScriptCache::singleton->mutex);140GDScriptCache::singleton->parser_map.erase(path);141}142}143144GDScriptCache *GDScriptCache::singleton = nullptr;145146SafeBinaryMutex<GDScriptCache::BINARY_MUTEX_TAG> &_get_gdscript_cache_mutex() {147return GDScriptCache::mutex;148}149150template <>151thread_local SafeBinaryMutex<GDScriptCache::BINARY_MUTEX_TAG>::TLSData SafeBinaryMutex<GDScriptCache::BINARY_MUTEX_TAG>::tls_data(_get_gdscript_cache_mutex());152SafeBinaryMutex<GDScriptCache::BINARY_MUTEX_TAG> GDScriptCache::mutex;153154void GDScriptCache::move_script(const String &p_from, const String &p_to) {155if (singleton == nullptr || p_from == p_to) {156return;157}158159MutexLock lock(singleton->mutex);160161if (singleton->cleared) {162return;163}164165remove_parser(p_from);166167if (singleton->shallow_gdscript_cache.has(p_from) && !p_from.is_empty()) {168singleton->shallow_gdscript_cache[p_to] = singleton->shallow_gdscript_cache[p_from];169}170singleton->shallow_gdscript_cache.erase(p_from);171172if (singleton->full_gdscript_cache.has(p_from) && !p_from.is_empty()) {173singleton->full_gdscript_cache[p_to] = singleton->full_gdscript_cache[p_from];174}175singleton->full_gdscript_cache.erase(p_from);176}177178void GDScriptCache::remove_script(const String &p_path) {179if (singleton == nullptr) {180return;181}182183MutexLock lock(singleton->mutex);184185if (singleton->cleared) {186return;187}188189if (HashMap<String, Vector<ObjectID>>::Iterator E = singleton->abandoned_parser_map.find(p_path)) {190for (ObjectID parser_ref_id : E->value) {191Ref<GDScriptParserRef> parser_ref = { ObjectDB::get_instance(parser_ref_id) };192if (parser_ref.is_valid()) {193parser_ref->clear();194}195}196}197198singleton->abandoned_parser_map.erase(p_path);199200if (singleton->parser_map.has(p_path)) {201singleton->parser_map[p_path]->clear();202}203204remove_parser(p_path);205206singleton->dependencies.erase(p_path);207singleton->shallow_gdscript_cache.erase(p_path);208singleton->full_gdscript_cache.erase(p_path);209}210211Ref<GDScriptParserRef> GDScriptCache::get_parser(const String &p_path, GDScriptParserRef::Status p_status, Error &r_error, const String &p_owner) {212MutexLock lock(singleton->mutex);213Ref<GDScriptParserRef> ref;214if (!p_owner.is_empty()) {215singleton->dependencies[p_owner].insert(p_path);216singleton->parser_inverse_dependencies[p_path].insert(p_owner);217}218if (singleton->parser_map.has(p_path)) {219ref = Ref<GDScriptParserRef>(singleton->parser_map[p_path]);220if (ref.is_null()) {221r_error = ERR_INVALID_DATA;222return ref;223}224} else {225String remapped_path = ResourceLoader::path_remap(p_path);226if (!FileAccess::exists(remapped_path)) {227r_error = ERR_FILE_NOT_FOUND;228return ref;229}230ref.instantiate();231ref->path = p_path;232singleton->parser_map[p_path] = ref.ptr();233}234r_error = ref->raise_status(p_status);235236return ref;237}238239bool GDScriptCache::has_parser(const String &p_path) {240MutexLock lock(singleton->mutex);241return singleton->parser_map.has(p_path);242}243244void GDScriptCache::remove_parser(const String &p_path) {245MutexLock lock(singleton->mutex);246247if (singleton->parser_map.has(p_path)) {248GDScriptParserRef *parser_ref = singleton->parser_map[p_path];249parser_ref->abandoned = true;250singleton->abandoned_parser_map[p_path].push_back(parser_ref->get_instance_id());251}252253// Can't clear the parser because some other parser might be currently using it in the chain of calls.254singleton->parser_map.erase(p_path);255256// Have to copy while iterating, because parser_inverse_dependencies is modified.257HashSet<String> ideps = singleton->parser_inverse_dependencies[p_path];258singleton->parser_inverse_dependencies.erase(p_path);259for (String idep_path : ideps) {260remove_parser(idep_path);261}262}263264String GDScriptCache::get_source_code(const String &p_path) {265Vector<uint8_t> source_file;266Error err;267Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);268ERR_FAIL_COND_V(err, "");269270uint64_t len = f->get_length();271source_file.resize(len + 1);272uint64_t r = f->get_buffer(source_file.ptrw(), len);273ERR_FAIL_COND_V(r != len, "");274source_file.write[len] = 0;275276String source;277if (source.append_utf8((const char *)source_file.ptr(), len) != OK) {278ERR_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.");279}280return source;281}282283Vector<uint8_t> GDScriptCache::get_binary_tokens(const String &p_path) {284Vector<uint8_t> buffer;285Error err = OK;286Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);287ERR_FAIL_COND_V_MSG(err != OK, buffer, "Failed to open binary GDScript file '" + p_path + "'.");288289uint64_t len = f->get_length();290buffer.resize(len);291uint64_t read = f->get_buffer(buffer.ptrw(), buffer.size());292ERR_FAIL_COND_V_MSG(read != len, Vector<uint8_t>(), "Failed to read binary GDScript file '" + p_path + "'.");293294return buffer;295}296297Ref<GDScript> GDScriptCache::get_shallow_script(const String &p_path, Error &r_error, const String &p_owner) {298MutexLock lock(singleton->mutex);299300if (!p_owner.is_empty()) {301singleton->dependencies[p_owner].insert(p_path);302}303if (singleton->full_gdscript_cache.has(p_path)) {304return singleton->full_gdscript_cache[p_path];305}306if (singleton->shallow_gdscript_cache.has(p_path)) {307return singleton->shallow_gdscript_cache[p_path];308}309310const String remapped_path = ResourceLoader::path_remap(p_path);311312Ref<GDScript> script;313script.instantiate();314script->set_path(p_path, true);315if (remapped_path.get_extension().to_lower() == "gdc") {316Vector<uint8_t> buffer = get_binary_tokens(remapped_path);317if (buffer.is_empty()) {318r_error = ERR_FILE_CANT_READ;319}320script->set_binary_tokens_source(buffer);321} else {322r_error = script->load_source_code(remapped_path);323}324325if (r_error) {326return Ref<GDScript>(); // Returns null and does not cache when the script fails to load.327}328329Ref<GDScriptParserRef> parser_ref = get_parser(p_path, GDScriptParserRef::PARSED, r_error);330if (r_error == OK) {331GDScriptCompiler::make_scripts(script.ptr(), parser_ref->get_parser()->get_tree(), true);332}333334singleton->shallow_gdscript_cache[p_path] = script;335336return script;337}338339Ref<GDScript> GDScriptCache::get_full_script(const String &p_path, Error &r_error, const String &p_owner, bool p_update_from_disk) {340MutexLock lock(singleton->mutex);341342if (!p_owner.is_empty()) {343singleton->dependencies[p_owner].insert(p_path);344}345346Ref<GDScript> script;347r_error = OK;348if (singleton->full_gdscript_cache.has(p_path)) {349script = singleton->full_gdscript_cache[p_path];350if (!p_update_from_disk) {351return script;352}353}354355if (script.is_null()) {356script = get_shallow_script(p_path, r_error);357// Only exit early if script failed to load, otherwise let reload report errors.358if (script.is_null()) {359return script;360}361}362363const String remapped_path = ResourceLoader::path_remap(p_path);364365if (p_update_from_disk) {366if (remapped_path.get_extension().to_lower() == "gdc") {367Vector<uint8_t> buffer = get_binary_tokens(remapped_path);368if (buffer.is_empty()) {369r_error = ERR_FILE_CANT_READ;370return script;371}372script->set_binary_tokens_source(buffer);373} else {374r_error = script->load_source_code(remapped_path);375if (r_error) {376return script;377}378}379}380381// Allowing lifting the lock might cause a script to be reloaded multiple times,382// which, as a last resort deadlock prevention strategy, is a good tradeoff.383uint32_t allowance_id = WorkerThreadPool::thread_enter_unlock_allowance_zone(singleton->mutex);384r_error = script->reload(true);385WorkerThreadPool::thread_exit_unlock_allowance_zone(allowance_id);386if (r_error) {387return script;388}389390singleton->full_gdscript_cache[p_path] = script;391singleton->shallow_gdscript_cache.erase(p_path);392393return script;394}395396Ref<GDScript> GDScriptCache::get_cached_script(const String &p_path) {397MutexLock lock(singleton->mutex);398399if (singleton->full_gdscript_cache.has(p_path)) {400return singleton->full_gdscript_cache[p_path];401}402403if (singleton->shallow_gdscript_cache.has(p_path)) {404return singleton->shallow_gdscript_cache[p_path];405}406407return Ref<GDScript>();408}409410Error GDScriptCache::finish_compiling(const String &p_owner) {411MutexLock lock(singleton->mutex);412413// Mark this as compiled.414Ref<GDScript> script = get_cached_script(p_owner);415singleton->full_gdscript_cache[p_owner] = script;416singleton->shallow_gdscript_cache.erase(p_owner);417418HashSet<String> depends = singleton->dependencies[p_owner];419420Error err = OK;421for (const String &E : depends) {422Error this_err = OK;423// No need to save the script. We assume it's already referenced in the owner.424get_full_script(E, this_err);425426if (this_err != OK) {427err = this_err;428}429}430431singleton->dependencies.erase(p_owner);432433return err;434}435436void GDScriptCache::add_static_script(Ref<GDScript> p_script) {437ERR_FAIL_COND_MSG(p_script.is_null(), "Trying to cache empty script as static.");438ERR_FAIL_COND_MSG(!p_script->is_valid(), "Trying to cache non-compiled script as static.");439singleton->static_gdscript_cache[p_script->get_fully_qualified_name()] = p_script;440}441442void GDScriptCache::remove_static_script(const String &p_fqcn) {443singleton->static_gdscript_cache.erase(p_fqcn);444}445446void GDScriptCache::clear() {447if (singleton == nullptr) {448return;449}450451MutexLock lock(singleton->mutex);452453if (singleton->cleared) {454return;455}456singleton->cleared = true;457458singleton->parser_inverse_dependencies.clear();459460for (const KeyValue<String, Vector<ObjectID>> &KV : singleton->abandoned_parser_map) {461for (ObjectID parser_ref_id : KV.value) {462Ref<GDScriptParserRef> parser_ref = { ObjectDB::get_instance(parser_ref_id) };463if (parser_ref.is_valid()) {464parser_ref->clear();465}466}467}468469singleton->abandoned_parser_map.clear();470471RBSet<Ref<GDScriptParserRef>> parser_map_refs;472for (KeyValue<String, GDScriptParserRef *> &E : singleton->parser_map) {473parser_map_refs.insert(E.value);474}475476singleton->parser_map.clear();477478for (Ref<GDScriptParserRef> &E : parser_map_refs) {479if (E.is_valid()) {480E->clear();481}482}483484parser_map_refs.clear();485singleton->shallow_gdscript_cache.clear();486singleton->full_gdscript_cache.clear();487singleton->static_gdscript_cache.clear();488}489490GDScriptCache::GDScriptCache() {491singleton = this;492}493494GDScriptCache::~GDScriptCache() {495if (!cleared) {496clear();497}498singleton = nullptr;499}500501502