Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/modules/gdscript/gdscript_cache.cpp
20844 views
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
31
#include "gdscript_cache.h"
32
33
#include "gdscript.h"
34
#include "gdscript_analyzer.h"
35
#include "gdscript_compiler.h"
36
#include "gdscript_parser.h"
37
38
#include "core/io/file_access.h"
39
#include "core/templates/vector.h"
40
41
GDScriptParserRef::Status GDScriptParserRef::get_status() const {
42
return status;
43
}
44
45
String GDScriptParserRef::get_path() const {
46
return path;
47
}
48
49
uint32_t GDScriptParserRef::get_source_hash() const {
50
return source_hash;
51
}
52
53
GDScriptParser *GDScriptParserRef::get_parser() {
54
if (parser == nullptr) {
55
parser = memnew(GDScriptParser);
56
}
57
return parser;
58
}
59
60
GDScriptAnalyzer *GDScriptParserRef::get_analyzer() {
61
if (analyzer == nullptr) {
62
analyzer = memnew(GDScriptAnalyzer(get_parser()));
63
}
64
return analyzer;
65
}
66
67
Error GDScriptParserRef::raise_status(Status p_new_status) {
68
ERR_FAIL_COND_V(clearing, ERR_BUG);
69
ERR_FAIL_COND_V(parser == nullptr && status != EMPTY, ERR_BUG);
70
71
if (p_new_status < status) {
72
return OK;
73
}
74
75
while (result == OK && p_new_status > status) {
76
switch (status) {
77
case EMPTY: {
78
// 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.
79
// It's ok if its the first thing done here.
80
get_parser()->clear();
81
status = PARSED;
82
String remapped_path = ResourceLoader::path_remap(path);
83
if (remapped_path.has_extension("gdc")) {
84
Vector<uint8_t> tokens = GDScriptCache::get_binary_tokens(remapped_path);
85
source_hash = hash_djb2_buffer(tokens.ptr(), tokens.size());
86
result = get_parser()->parse_binary(tokens, path);
87
} else {
88
String source = GDScriptCache::get_source_code(remapped_path);
89
source_hash = source.hash();
90
result = get_parser()->parse(source, path, false);
91
}
92
} break;
93
case PARSED: {
94
status = INHERITANCE_SOLVED;
95
result = get_analyzer()->resolve_inheritance();
96
} break;
97
case INHERITANCE_SOLVED: {
98
status = INTERFACE_SOLVED;
99
result = get_analyzer()->resolve_interface();
100
} break;
101
case INTERFACE_SOLVED: {
102
status = FULLY_SOLVED;
103
result = get_analyzer()->resolve_body();
104
} break;
105
case FULLY_SOLVED: {
106
return result;
107
}
108
}
109
}
110
111
return result;
112
}
113
114
void GDScriptParserRef::clear() {
115
if (clearing) {
116
return;
117
}
118
clearing = true;
119
120
GDScriptParser *lparser = parser;
121
GDScriptAnalyzer *lanalyzer = analyzer;
122
123
parser = nullptr;
124
analyzer = nullptr;
125
status = EMPTY;
126
result = OK;
127
source_hash = 0;
128
129
clearing = false;
130
131
if (lanalyzer != nullptr) {
132
memdelete(lanalyzer);
133
}
134
135
if (lparser != nullptr) {
136
memdelete(lparser);
137
}
138
}
139
140
GDScriptParserRef::~GDScriptParserRef() {
141
clear();
142
143
if (!abandoned) {
144
MutexLock lock(GDScriptCache::singleton->mutex);
145
GDScriptCache::singleton->parser_map.erase(path);
146
}
147
}
148
149
GDScriptCache *GDScriptCache::singleton = nullptr;
150
151
SafeBinaryMutex<GDScriptCache::BINARY_MUTEX_TAG> &_get_gdscript_cache_mutex() {
152
return GDScriptCache::mutex;
153
}
154
155
template <>
156
thread_local SafeBinaryMutex<GDScriptCache::BINARY_MUTEX_TAG>::TLSData SafeBinaryMutex<GDScriptCache::BINARY_MUTEX_TAG>::tls_data(_get_gdscript_cache_mutex());
157
SafeBinaryMutex<GDScriptCache::BINARY_MUTEX_TAG> GDScriptCache::mutex;
158
159
void GDScriptCache::move_script(const String &p_from, const String &p_to) {
160
if (singleton == nullptr || p_from == p_to || p_from.is_empty()) {
161
return;
162
}
163
164
MutexLock lock(singleton->mutex);
165
166
if (singleton->cleared) {
167
return;
168
}
169
170
remove_parser(p_from);
171
172
if (singleton->shallow_gdscript_cache.has(p_from) && !p_from.is_empty()) {
173
singleton->shallow_gdscript_cache[p_to] = singleton->shallow_gdscript_cache[p_from];
174
}
175
singleton->shallow_gdscript_cache.erase(p_from);
176
177
if (singleton->full_gdscript_cache.has(p_from) && !p_from.is_empty()) {
178
singleton->full_gdscript_cache[p_to] = singleton->full_gdscript_cache[p_from];
179
}
180
singleton->full_gdscript_cache.erase(p_from);
181
}
182
183
void GDScriptCache::remove_script(const String &p_path) {
184
if (singleton == nullptr) {
185
return;
186
}
187
188
MutexLock lock(singleton->mutex);
189
190
if (singleton->cleared) {
191
return;
192
}
193
194
if (HashMap<String, Vector<ObjectID>>::Iterator E = singleton->abandoned_parser_map.find(p_path)) {
195
for (ObjectID parser_ref_id : E->value) {
196
Ref<GDScriptParserRef> parser_ref = { ObjectDB::get_instance(parser_ref_id) };
197
if (parser_ref.is_valid()) {
198
parser_ref->clear();
199
}
200
}
201
}
202
203
singleton->abandoned_parser_map.erase(p_path);
204
205
if (singleton->parser_map.has(p_path)) {
206
singleton->parser_map[p_path]->clear();
207
}
208
209
remove_parser(p_path);
210
211
singleton->dependencies.erase(p_path);
212
singleton->shallow_gdscript_cache.erase(p_path);
213
singleton->full_gdscript_cache.erase(p_path);
214
}
215
216
Ref<GDScriptParserRef> GDScriptCache::get_parser(const String &p_path, GDScriptParserRef::Status p_status, Error &r_error, const String &p_owner) {
217
MutexLock lock(singleton->mutex);
218
Ref<GDScriptParserRef> ref;
219
if (!p_owner.is_empty() && p_path != p_owner) {
220
singleton->dependencies[p_owner].insert(p_path);
221
singleton->parser_inverse_dependencies[p_path].insert(p_owner);
222
}
223
if (singleton->parser_map.has(p_path)) {
224
ref = Ref<GDScriptParserRef>(singleton->parser_map[p_path]);
225
if (ref.is_null()) {
226
r_error = ERR_INVALID_DATA;
227
return ref;
228
}
229
} else {
230
String remapped_path = ResourceLoader::path_remap(p_path);
231
if (!FileAccess::exists(remapped_path)) {
232
r_error = ERR_FILE_NOT_FOUND;
233
return ref;
234
}
235
ref.instantiate();
236
ref->path = p_path;
237
singleton->parser_map[p_path] = ref.ptr();
238
}
239
r_error = ref->raise_status(p_status);
240
241
return ref;
242
}
243
244
bool GDScriptCache::has_parser(const String &p_path) {
245
MutexLock lock(singleton->mutex);
246
return singleton->parser_map.has(p_path);
247
}
248
249
void GDScriptCache::remove_parser(const String &p_path) {
250
MutexLock lock(singleton->mutex);
251
252
if (singleton->parser_map.has(p_path)) {
253
GDScriptParserRef *parser_ref = singleton->parser_map[p_path];
254
parser_ref->abandoned = true;
255
singleton->abandoned_parser_map[p_path].push_back(parser_ref->get_instance_id());
256
}
257
258
// Can't clear the parser because some other parser might be currently using it in the chain of calls.
259
singleton->parser_map.erase(p_path);
260
261
// Have to copy while iterating, because parser_inverse_dependencies is modified.
262
HashSet<String> ideps = singleton->parser_inverse_dependencies[p_path];
263
singleton->parser_inverse_dependencies.erase(p_path);
264
for (String idep_path : ideps) {
265
remove_parser(idep_path);
266
}
267
}
268
269
String GDScriptCache::get_source_code(const String &p_path) {
270
Vector<uint8_t> source_file;
271
Error err;
272
Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);
273
ERR_FAIL_COND_V(err, "");
274
275
uint64_t len = f->get_length();
276
source_file.resize(len + 1);
277
uint64_t r = f->get_buffer(source_file.ptrw(), len);
278
ERR_FAIL_COND_V(r != len, "");
279
source_file.write[len] = 0;
280
281
String source;
282
if (source.append_utf8((const char *)source_file.ptr(), len) != OK) {
283
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.");
284
}
285
return source;
286
}
287
288
Vector<uint8_t> GDScriptCache::get_binary_tokens(const String &p_path) {
289
Vector<uint8_t> buffer;
290
Error err = OK;
291
Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);
292
ERR_FAIL_COND_V_MSG(err != OK, buffer, "Failed to open binary GDScript file '" + p_path + "'.");
293
294
uint64_t len = f->get_length();
295
buffer.resize(len);
296
uint64_t read = f->get_buffer(buffer.ptrw(), buffer.size());
297
ERR_FAIL_COND_V_MSG(read != len, Vector<uint8_t>(), "Failed to read binary GDScript file '" + p_path + "'.");
298
299
return buffer;
300
}
301
302
Ref<GDScript> GDScriptCache::get_shallow_script(const String &p_path, Error &r_error, const String &p_owner) {
303
MutexLock lock(singleton->mutex);
304
305
if (!p_owner.is_empty() && p_path != p_owner) {
306
singleton->dependencies[p_owner].insert(p_path);
307
}
308
if (singleton->full_gdscript_cache.has(p_path)) {
309
return singleton->full_gdscript_cache[p_path];
310
}
311
if (singleton->shallow_gdscript_cache.has(p_path)) {
312
return singleton->shallow_gdscript_cache[p_path];
313
}
314
315
const String remapped_path = ResourceLoader::path_remap(p_path);
316
317
Ref<GDScript> script;
318
script.instantiate();
319
320
script->set_path_cache(p_path);
321
if (remapped_path.has_extension("gdc")) {
322
Vector<uint8_t> buffer = get_binary_tokens(remapped_path);
323
if (buffer.is_empty()) {
324
r_error = ERR_FILE_CANT_READ;
325
}
326
script->set_binary_tokens_source(buffer);
327
} else {
328
r_error = script->load_source_code(remapped_path);
329
}
330
331
if (r_error) {
332
return Ref<GDScript>(); // Returns null and does not cache when the script fails to load.
333
}
334
335
Ref<GDScriptParserRef> parser_ref = get_parser(p_path, GDScriptParserRef::PARSED, r_error);
336
if (r_error == OK) {
337
GDScriptCompiler::make_scripts(script.ptr(), parser_ref->get_parser()->get_tree(), true);
338
}
339
340
singleton->shallow_gdscript_cache[p_path] = script;
341
342
return script;
343
}
344
345
Ref<GDScript> GDScriptCache::get_full_script(const String &p_path, Error &r_error, const String &p_owner, bool p_update_from_disk) {
346
MutexLock lock(singleton->mutex);
347
348
if (!p_owner.is_empty() && p_path != p_owner) {
349
singleton->dependencies[p_owner].insert(p_path);
350
}
351
352
Ref<GDScript> script;
353
r_error = OK;
354
if (singleton->full_gdscript_cache.has(p_path)) {
355
script = singleton->full_gdscript_cache[p_path];
356
if (!p_update_from_disk) {
357
return script;
358
}
359
}
360
361
if (script.is_null()) {
362
script = get_shallow_script(p_path, r_error);
363
// Only exit early if script failed to load, otherwise let reload report errors.
364
if (script.is_null()) {
365
return script;
366
}
367
}
368
369
const String remapped_path = ResourceLoader::path_remap(p_path);
370
371
if (p_update_from_disk) {
372
if (remapped_path.has_extension("gdc")) {
373
Vector<uint8_t> buffer = get_binary_tokens(remapped_path);
374
if (buffer.is_empty()) {
375
r_error = ERR_FILE_CANT_READ;
376
goto finish;
377
}
378
script->set_binary_tokens_source(buffer);
379
} else {
380
r_error = script->load_source_code(remapped_path);
381
if (r_error) {
382
goto finish;
383
}
384
}
385
}
386
387
// Allowing lifting the lock might cause a script to be reloaded multiple times,
388
// which, as a last resort deadlock prevention strategy, is a good tradeoff.
389
{
390
uint32_t allowance_id = WorkerThreadPool::thread_enter_unlock_allowance_zone(singleton->mutex);
391
r_error = script->reload(true);
392
WorkerThreadPool::thread_exit_unlock_allowance_zone(allowance_id);
393
}
394
395
finish:
396
singleton->full_gdscript_cache[p_path] = script;
397
singleton->shallow_gdscript_cache.erase(p_path);
398
399
// Add the script to the resource cache. Usually ResourceLoader would take care of it, but cyclic references can break that sometimes so we do it ourselves.
400
// Resources don't know whether they are cached, so using `set_path()` after `set_path_cache()` does not add the resource to the cache if the path is the same.
401
// We reset the cached path from `get_shallow_script()` so that the subsequent call to `set_path()` caches everything correctly.
402
script->set_path_cache(String());
403
script->set_path(p_path, true);
404
405
return script;
406
}
407
408
Ref<GDScript> GDScriptCache::get_cached_script(const String &p_path) {
409
MutexLock lock(singleton->mutex);
410
411
if (singleton->full_gdscript_cache.has(p_path)) {
412
return singleton->full_gdscript_cache[p_path];
413
}
414
415
if (singleton->shallow_gdscript_cache.has(p_path)) {
416
return singleton->shallow_gdscript_cache[p_path];
417
}
418
419
return Ref<GDScript>();
420
}
421
422
Error GDScriptCache::finish_compiling(const String &p_owner) {
423
MutexLock lock(singleton->mutex);
424
425
// Mark this as compiled.
426
Ref<GDScript> script = get_cached_script(p_owner);
427
singleton->full_gdscript_cache[p_owner] = script;
428
singleton->shallow_gdscript_cache.erase(p_owner);
429
430
HashSet<String> depends = singleton->dependencies[p_owner];
431
432
Error err = OK;
433
for (const String &E : depends) {
434
Error this_err = OK;
435
// No need to save the script. We assume it's already referenced in the owner.
436
get_full_script(E, this_err);
437
438
if (this_err != OK) {
439
err = this_err;
440
}
441
}
442
443
singleton->dependencies.erase(p_owner);
444
445
return err;
446
}
447
448
void GDScriptCache::add_static_script(Ref<GDScript> p_script) {
449
ERR_FAIL_COND_MSG(p_script.is_null(), "Trying to cache empty script as static.");
450
ERR_FAIL_COND_MSG(!p_script->is_valid(), "Trying to cache non-compiled script as static.");
451
singleton->static_gdscript_cache[p_script->get_fully_qualified_name()] = p_script;
452
}
453
454
void GDScriptCache::remove_static_script(const String &p_fqcn) {
455
singleton->static_gdscript_cache.erase(p_fqcn);
456
}
457
458
void GDScriptCache::clear() {
459
if (singleton == nullptr) {
460
return;
461
}
462
463
MutexLock lock(singleton->mutex);
464
465
if (singleton->cleared) {
466
return;
467
}
468
singleton->cleared = true;
469
470
singleton->parser_inverse_dependencies.clear();
471
472
for (const KeyValue<String, Vector<ObjectID>> &KV : singleton->abandoned_parser_map) {
473
for (ObjectID parser_ref_id : KV.value) {
474
Ref<GDScriptParserRef> parser_ref = { ObjectDB::get_instance(parser_ref_id) };
475
if (parser_ref.is_valid()) {
476
parser_ref->clear();
477
}
478
}
479
}
480
481
singleton->abandoned_parser_map.clear();
482
483
RBSet<Ref<GDScriptParserRef>> parser_map_refs;
484
for (KeyValue<String, GDScriptParserRef *> &E : singleton->parser_map) {
485
parser_map_refs.insert(E.value);
486
}
487
488
singleton->parser_map.clear();
489
490
for (Ref<GDScriptParserRef> &E : parser_map_refs) {
491
if (E.is_valid()) {
492
E->clear();
493
}
494
}
495
496
parser_map_refs.clear();
497
singleton->shallow_gdscript_cache.clear();
498
singleton->full_gdscript_cache.clear();
499
singleton->static_gdscript_cache.clear();
500
}
501
502
GDScriptCache::GDScriptCache() {
503
singleton = this;
504
}
505
506
GDScriptCache::~GDScriptCache() {
507
if (!cleared) {
508
clear();
509
}
510
singleton = nullptr;
511
}
512
513