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