-
-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathjsb_script_language.cpp
More file actions
808 lines (698 loc) · 25.9 KB
/
Copy pathjsb_script_language.cpp
File metadata and controls
808 lines (698 loc) · 25.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
#include "jsb_script_language.h"
#include <iterator>
#include "jsb_monitor.h"
#include "../jsb_project_preset.h"
#include "../internal/jsb_internal.h"
#include "../bridge/jsb_worker.h"
#include "jsb_script.h"
#ifdef TOOLS_ENABLED
#include "../weaver-editor/templates/templates.gen.h"
#endif
GodotJSScriptLanguage* GodotJSScriptLanguage::singleton_ = nullptr;
namespace jsb
{
void JSEnvironment::init()
{
if (is_shadow_ && !target_)
{
target_ = GodotJSScriptLanguage::get_singleton()->create_shadow_environment();
}
}
JSEnvironment::JSEnvironment(const String& p_path_hint, bool p_is_shadow_allowed)
{
target_ = jsb::Environment::_access();
if (target_)
{
is_shadow_ = false;
}
else
{
jsb_ensuref(p_is_shadow_allowed, "no available Environment on thread %d for %s: %s", Thread::get_caller_id(), jsb_typename(GodotJSScript), p_path_hint);
is_shadow_ = true;
}
}
JSEnvironment::~JSEnvironment()
{
if (is_shadow_ && target_)
{
GodotJSScriptLanguage::get_singleton()->destroy_shadow_environment(target_);
}
}
}
GodotJSScriptLanguage::GodotJSScriptLanguage()
{
JSB_BENCHMARK_SCOPE(GodotJSScriptLanguage, Construct);
jsb_check(!singleton_);
singleton_ = this;
js_class_name_matcher1_ = RegEx::create_from_string(R"(\s*exports.default\s*=\s*class\s*(\w+)\s+extends\s+(\w+))");
js_class_name_matcher2_ = RegEx::create_from_string(R"(\s*exports.default\s*=\s*(\w+)\s*;?)");
ts_class_name_matcher_ = RegEx::create_from_string(R"(\s*(@[tT]ool\s*\(\s*\)\s*\n*\s*)?export\s+default\s+class\s+(\w+)(\s*<)?[^\n]*(?:>|\s+)extends\s+(\w+))");
jsb::internal::StringNames::create();
}
GodotJSScriptLanguage::~GodotJSScriptLanguage()
{
jsb::internal::StringNames::free();
jsb_check(singleton_ == this);
singleton_ = nullptr;
//TODO manage script list in a safer way (access and ref with script.id)
MutexLock lock(mutex_);
while (SelfList<GodotJSScript>* script_el = script_list_.first())
{
script_el->remove_from_list();
}
}
void GodotJSScriptLanguage::init()
{
if (once_inited_) return;
JSB_BENCHMARK_SCOPE(GodotJSScriptLanguage, init);
once_inited_ = true;
JSB_LOG(Verbose, "Runtime: %s", JSB_IMPL_VERSION_STRING);
JSB_LOG(VeryVerbose, "jsb lang init");
jsb::Environment::CreateParams params;
params.initial_class_slots = (int) ClassDB::classes.size() + JSB_MASTER_INITIAL_CLASS_EXTRA_SLOTS;
params.initial_object_slots = JSB_MASTER_INITIAL_OBJECT_SLOTS;
params.initial_script_slots = JSB_MASTER_INITIAL_SCRIPT_SLOTS;
params.debugger_port = jsb::internal::Settings::get_debugger_port();
params.thread_id = Thread::get_caller_id();
// main environment
environment_ = std::make_shared<jsb::Environment>(params);
environment_->init();
if (const String entry_script_path = jsb::internal::Settings::get_entry_script_path();
!entry_script_path.is_empty())
{
environment_->load(entry_script_path);
}
#if JSB_DEBUG
if (jsb::compat::Performance::get_singleton()) monitor_ = memnew(GodotJSMonitor);
#endif
}
void GodotJSScriptLanguage::finish()
{
jsb_check(once_inited_);
#if JSB_DEBUG
if (monitor_) memdelete(monitor_);
#endif
once_inited_ = false;
environment_->dispose();
environment_.reset();
#if !JSB_WITH_WEB && !JSB_WITH_JAVASCRIPTCORE
jsb::Worker::finish();
#endif
{
std::vector<ShadowEnvironment> shadow_environments;
{
MutexLock shadow_lock(shadow_mutex_);
shadow_environments = shadow_environments_;
shadow_environments_.clear();
}
for (const ShadowEnvironment& env : shadow_environments)
{
env.holder->dispose();
}
}
JSB_LOG(VeryVerbose, "jsb lang finish");
}
void GodotJSScriptLanguage::frame()
{
const uint64_t base_ticks = Engine::get_singleton()->get_frame_ticks();
const uint64_t elapsed_milli = (base_ticks - last_ticks_) / 1000ULL; // milliseconds
last_ticks_ = base_ticks;
environment_->update(elapsed_milli);
#if JSB_DEBUG
{
MutexLock lock(mutex_);
if (profile_info_map_.enabled)
{
for (auto& class_kv : profile_info_map_.classes)
{
for (auto& method_kv : class_kv.value.methods)
{
method_kv.value.last_frame_calls = method_kv.value.frame_calls;
method_kv.value.last_frame_time = method_kv.value.frame_time;
method_kv.value.frame_calls = 0;
method_kv.value.frame_time = 0;
}
}
}
}
#endif
}
struct JavaScriptControlFlowKeywords
{
HashSet<String> values;
jsb_force_inline JavaScriptControlFlowKeywords()
{
constexpr static const char* _keywords[] =
{
"if", "else", "switch", "case", "do", "while", "for", "foreach",
"return", "break", "continue",
"try", "throw", "catch", "finally",
};
for (size_t index = 0; index < ::std::size(_keywords); ++index)
{
values.insert(_keywords[index]);
}
}
};
bool GodotJSScriptLanguage::is_control_flow_keyword(ConstStringRefCompat p_keyword) const
{
static JavaScriptControlFlowKeywords collection;
return collection.values.has(p_keyword);
}
Vector<String> GodotJSScriptLanguage::get_reserved_words() const
{
return Vector<String> {
"return", "function", "interface", "class", "let", "break", "as", "any", "switch", "case", "if", "enum",
"throw", "else", "var", "number", "string", "get", "module", "instanceof", "typeof", "public", "private",
"while", "void", "null", "super", "this", "new", "in", "await", "async", "extends", "static",
"package", "implements", "interface", "continue", "yield", "const", "export", "finally", "for",
"import", "byte", "delete", "goto",
"default",
};
}
#if GODOT_4_5_OR_NEWER
Vector<String> GodotJSScriptLanguage::get_doc_comment_delimiters() const
{
return Vector<String> { "///" };
}
Vector<String> GodotJSScriptLanguage::get_comment_delimiters() const
{
return Vector<String> { "//", "/* */" };
}
Vector<String> GodotJSScriptLanguage::get_string_delimiters() const
{
return Vector<String> { "' '", "\" \"", "` `" };
}
#else
void GodotJSScriptLanguage::get_reserved_words(List<String>* p_words) const
{
for (String keyword : get_reserved_words())
{
p_words->push_back(keyword);
}
}
void GodotJSScriptLanguage::get_doc_comment_delimiters(List<String>* p_delimiters) const
{
p_delimiters->push_back("///");
}
void GodotJSScriptLanguage::get_comment_delimiters(List<String>* p_delimiters) const
{
p_delimiters->push_back("//");
p_delimiters->push_back("/* */");
}
void GodotJSScriptLanguage::get_string_delimiters(List<String>* p_delimiters) const
{
p_delimiters->push_back("' '");
p_delimiters->push_back("\" \"");
p_delimiters->push_back("` `");
}
#endif
//TODO this virtual method seems never used in godot?
Script* GodotJSScriptLanguage::create_script() const
{
return memnew(GodotJSScript);
}
bool GodotJSScriptLanguage::validate(const String& p_script, const String& p_path, List<String>* r_functions, List<ScriptError>* r_errors, List<Warning>* r_warnings, HashSet<int>* r_safe_lines) const
{
if (environment_->validate_script(p_path))
{
return true;
}
//TODO parse error info
ScriptError err;
err.line = 0;
err.column = 0;
err.message = "NOT_IMPLEMENTED";
r_errors->push_back(err);
return false;
}
Ref<Script> GodotJSScriptLanguage::make_template(const String& p_template, const String& p_class_name, const String& p_base_class_name) const
{
Ref<GodotJSScript> spt;
spt.instantiate();
String processed_template = p_template;
processed_template = processed_template.replace("_BASE_", p_base_class_name)
.replace("_CLASS_SNAKE_CASE_", jsb::internal::VariantUtil::to_snake_case_id(p_class_name))
.replace("_CLASS_", jsb::internal::VariantUtil::to_pascal_case_id(p_class_name))
.replace("_TS_", jsb::internal::Settings::get_indentation());
spt->set_source_code(processed_template);
return spt;
}
Vector<ScriptLanguage::ScriptTemplate> GodotJSScriptLanguage::get_built_in_templates(ConstStringNameRefCompat p_object)
{
Vector<ScriptTemplate> templates;
#ifdef TOOLS_ENABLED
for (int i = 0; i < TEMPLATES_ARRAY_SIZE; i++) {
if (TEMPLATES[i].inherit == p_object) {
templates.append(TEMPLATES[i]);
}
}
#endif
return templates;
}
#if GODOT_4_3_OR_NEWER
struct GodotJSScriptDepSort {
//must support sorting so inheritance works properly (parent must be reloaded first)
bool operator()(const Ref<GodotJSScript> &A, const Ref<GodotJSScript> &B) const {
if (A == B) {
return false; //shouldn't happen but..
}
const GodotJSScript *I = static_cast<const GodotJSScript *>(B->get_base_script().ptr());
while (I) {
if (I == A.ptr()) {
// A is a base of B
return true;
}
I = static_cast<const GodotJSScript *>(I->get_base_script().ptr());
}
return false; //not a base
}
};
void GodotJSScriptLanguage::reload_scripts(const Array& p_scripts, bool p_soft_reload)
{
reload_scripts_internal(p_scripts, p_soft_reload);
}
void GodotJSScriptLanguage::profiling_set_save_native_calls(bool p_enable)
{
JSB_LOG(Verbose, "TODO [GodotJSScriptLanguage::profiling_set_save_native_calls] NOT IMPLEMENTED");
}
#endif
void GodotJSScriptLanguage::reload_all_scripts()
{
#ifdef DEBUG_ENABLED
print_verbose("GodotJSScript: Reloading all scripts");
Array scripts;
{
MutexLock lock(mutex_);
SelfList<GodotJSScript> *elem = script_list_.first();
while (elem) {
if (elem->self()->get_path().is_resource_file()) {
print_verbose("GodotJSScript: Found: " + elem->self()->get_path());
scripts.push_back(Ref<GodotJSScript>(elem->self())); //cast to gdscript to avoid being erased by accident
}
elem = elem->next();
}
#ifdef TOOLS_ENABLED
// TODO: Implement global mechanism.
#endif // TOOLS_ENABLED
}
reload_scripts_internal(scripts, true);
#endif // DEBUG_ENABLED
}
void GodotJSScriptLanguage::reload_tool_script(const Ref<Script>& p_script, bool p_soft_reload)
{
Array scripts;
scripts.push_back(p_script);
reload_scripts_internal(scripts, p_soft_reload);
}
void GodotJSScriptLanguage::get_recognized_extensions(List<String>* p_extensions) const
{
#if JSB_USE_TYPESCRIPT
p_extensions->push_back(JSB_TYPESCRIPT_EXT);
#endif
p_extensions->push_back(JSB_JAVASCRIPT_EXT);
p_extensions->push_back(JSB_COMMONJS_EXT);
p_extensions->push_back(JSB_MODULE_EXT);
}
#if GODOT_4_4_OR_NEWER
String GodotJSScriptLanguage::get_global_class_name(const String &p_path, String *r_base_type, String *r_icon_path, bool *r_is_abstract, bool *r_is_tool) const
#else
String GodotJSScriptLanguage::get_global_class_name(const String& p_path, String* r_base_type, String* r_icon_path) const
#endif
{
// GodotJSScript implementation do not really support threaded access for now.
// So, we can not load the script module in-place because `get_global_class_name` could be called from EditorFileSystem (background) scan.
// And for simplicity, we use regex to extract the class name from the source code instead of using ANTLR or similar.
// Please follow the rules of the class name declaration in the source code.
// * .ts files: `export default class ClassName extends BaseClassName`
// * .js files: `class ClassName extends BaseClassName` and `exports.default = ClassName` (with or without `;`)
// And, we do not support `r_is_abstract` here, please define all abstract class by not exporting it as `default`.
// It should be equivalent and enough for TS/JS since we do not rely on GodotJSScript to use abstract classes in TS/JS sources.
Error err;
const Ref<FileAccess> file_access = FileAccess::open(p_path, FileAccess::READ, &err);
if (err)
{
return String();
}
const String source = file_access->get_as_utf8_string();
if (jsb::internal::PathUtil::is_recognized_javascript_extension(p_path))
{
// check if the class id defined in a single line (export default class ClassName extends BaseClassName)
jsb_check(!js_class_name_matcher1_.is_null());
const Ref<RegExMatch> match1 = js_class_name_matcher1_->search(source);
if (match1.is_valid() && match1->get_group_count() == 2)
{
const String class_name = match1->get_string(1);
if (r_base_type) *r_base_type = match1->get_string(2);
return class_name;
}
// otherwise, it probably defined in separated lines (firstly, check 'class ClassName extends BaseClassName')
jsb_check(!js_class_name_matcher2_.is_null());
const Ref<RegExMatch> match2 = js_class_name_matcher2_->search(source);
if (match2.is_valid() && match2->get_group_count() == 1)
{
const String class_name = match2->get_string(1);
if (r_base_type)
{
// then, check 'exports.default = ClassName'
const Ref<RegEx> base_matcher = RegEx::create_from_string(jsb::internal::format(R"(\s*class\s*%s\s*extends\s*(\w+)\s*\{?)", class_name));
const Ref<RegExMatch> base_match = base_matcher->search(source);
if (base_match.is_valid() && base_match->get_group_count() == 1)
{
*r_base_type = base_match->get_string(1);
}
}
return class_name;
}
}
else
{
// hope it's a typescript file
jsb_check(!ts_class_name_matcher_.is_null());
Ref<RegExMatch> match = ts_class_name_matcher_->search(source);
if (match.is_valid() && match->get_group_count() == 4)
{
#if GODOT_4_4_OR_NEWER
if (r_is_tool) *r_is_tool = match->get_string(1).size() > 0;
#endif
const String class_name = match->get_string(2);
if (r_base_type) *r_base_type = match->get_string(4);
return class_name;
}
}
return {};
}
bool GodotJSScriptLanguage::handles_global_class_type(const String& p_type) const
{
return p_type == jsb_typename(GodotJSScript);
}
String GodotJSScriptLanguage::get_name() const
{
return jsb_typename(GodotJSScript);
}
String GodotJSScriptLanguage::get_type() const
{
return jsb_typename(GodotJSScript);
}
void GodotJSScriptLanguage::scan_external_changes()
{
environment_->scan_external_changes();
#ifdef TOOLS_ENABLED
// fix scripts with no .js counterpart found (only missing scripts)
{
MutexLock lock(mutex_);
const SelfList<GodotJSScript>* elem = script_list_.first();
while (elem)
{
elem->self()->load_module_if_missing();
elem = elem->next();
}
}
#endif
}
void GodotJSScriptLanguage::thread_enter()
{
#if !JSB_WITH_WEB && !JSB_WITH_JAVASCRIPTCORE
jsb::Worker::on_thread_enter();
#endif
}
void GodotJSScriptLanguage::thread_exit()
{
#if !JSB_WITH_WEB && !JSB_WITH_JAVASCRIPTCORE
jsb::Worker::on_thread_exit();
#endif
}
void GodotJSScriptLanguage::profiling_start()
{
#if JSB_DEBUG
MutexLock lock(mutex_);
profile_info_map_.enabled = true;
#endif
}
void GodotJSScriptLanguage::profiling_stop()
{
#if JSB_DEBUG
MutexLock lock(mutex_);
profile_info_map_.enabled = false;
#endif
}
void GodotJSScriptLanguage::add_script_call_profile_info(const String& p_path, const StringName& p_class, const StringName& p_method, uint64_t p_time)
{
// we only collect GodotJSScriptInstance function profiling data instead of the deep profiling data from JS runtime.
// please use Chrome DevTools for deep JS profiling.
#if JSB_DEBUG
MutexLock lock(mutex_);
if (!profile_info_map_.enabled) return;
ScriptClassProfileInfo& prof = profile_info_map_.classes[p_class];
prof.path = p_path;
prof.methods[p_method].frame_calls++;
prof.methods[p_method].frame_time += p_time;
prof.methods[p_method].total_calls++;
prof.methods[p_method].total_time += p_time;
#endif
}
bool GodotJSScriptLanguage::is_global_class_generic(const String &p_path) const
{
Error err;
const Ref<FileAccess> file_access = FileAccess::open(p_path, FileAccess::READ, &err);
if (err)
{
return false;
}
const String source = file_access->get_as_utf8_string();
if (jsb::internal::PathUtil::is_recognized_javascript_extension(p_path))
{
return false;
}
jsb_check(!ts_class_name_matcher_.is_null());
Ref<RegExMatch> match = ts_class_name_matcher_->search(source);
return match.is_valid() && match->get_group_count() == 4 && match->get_string(3).length() > 0;
}
namespace
{
String to_signature(const String& p_path, const StringName& p_class, const StringName& p_method)
{
// path :: line :: class :: method
return jsb_format("%s::0::%s::%s", p_path, p_class, p_method);
}
}
int GodotJSScriptLanguage::profiling_get_accumulated_data(ProfilingInfo* p_info_arr, int p_info_max)
{
#if JSB_DEBUG
MutexLock lock(mutex_);
if (!profile_info_map_.enabled) return 0;
int current = 0;
for (const auto& class_kv : profile_info_map_.classes)
{
for (const auto& method_kv : class_kv.value.methods)
{
if (current >= p_info_max)
{
return current;
}
p_info_arr[current].signature = to_signature(class_kv.value.path, class_kv.key, method_kv.key);
p_info_arr[current].self_time = method_kv.value.total_time;
p_info_arr[current].total_time = method_kv.value.total_time;
p_info_arr[current].call_count = method_kv.value.total_calls;
current++;
}
}
return current;
#else
return 0;
#endif
}
int GodotJSScriptLanguage::profiling_get_frame_data(ProfilingInfo* p_info_arr, int p_info_max)
{
#if JSB_DEBUG
MutexLock lock(mutex_);
if (!profile_info_map_.enabled) return 0;
int current = 0;
for (const auto& class_kv : profile_info_map_.classes)
{
for (const auto& method_kv : class_kv.value.methods)
{
if (current >= p_info_max)
{
return current;
}
p_info_arr[current].signature = to_signature(class_kv.value.path, class_kv.key, method_kv.key);
p_info_arr[current].self_time = method_kv.value.last_frame_time;
p_info_arr[current].total_time = method_kv.value.last_frame_time;
p_info_arr[current].call_count = method_kv.value.last_frame_calls;
current++;
}
}
return current;
#else
return 0;
#endif
}
std::shared_ptr<jsb::Environment> GodotJSScriptLanguage::create_shadow_environment()
{
const Thread::ID caller_id = Thread::get_caller_id();
{
MutexLock shadow_lock(shadow_mutex_);
for (ShadowEnvironment& shadow : shadow_environments_)
{
if (shadow.rc == 0 || shadow.thread_id == caller_id)
{
shadow.rc++;
return shadow.holder;
}
}
}
jsb::Environment::CreateParams params;
params.initial_class_slots = 128;
params.initial_object_slots = 512;
params.initial_script_slots = 32;
params.type = jsb::Environment::Type::Shadow;
params.thread_id = Thread::UNASSIGNED_ID;
std::shared_ptr<jsb::Environment> env = std::make_shared<jsb::Environment>(params);
JSB_LOG(Log, "creating a shadow Environment on thread %d for %s [env %s]",
Thread::get_caller_id(),
jsb_typename(GodotJSScript),
(uintptr_t) env->id());
env->init();
{
MutexLock shadow_lock(shadow_mutex_);
shadow_environments_.push_back({caller_id, env, 1});
}
return env;
}
void GodotJSScriptLanguage::destroy_shadow_environment(const std::shared_ptr<jsb::Environment>& p_env)
{
bool found = false;
bool should_dispose = false;
{
MutexLock shadow_lock(shadow_mutex_);
const size_t num = shadow_environments_.size();
for (auto it = shadow_environments_.begin();
it != shadow_environments_.end();
++it)
{
if (it->holder == p_env)
{
found = true;
if (--it->rc == 0 && num > JSB_MAX_CACHED_SHADOW_ENVIRONMENTS)
{
should_dispose = true;
shadow_environments_.erase(it);
}
break;
}
}
}
jsb_checkf(found, "not a registered shadow environment");
if (should_dispose) p_env->dispose();
}
void GodotJSScriptLanguage::reload_scripts_internal(const Array& p_scripts, bool p_soft_reload)
{
#ifdef DEBUG_ENABLED
List<Ref<GodotJSScript>> scripts;
{
MutexLock lock(mutex_);
SelfList<GodotJSScript> *elem = script_list_.first();
while (elem) {
// Scripts will reload all subclasses, so only reload root scripts.
if (elem->self()->is_root_script() && !elem->self()->get_path().is_empty()) {
scripts.push_back(Ref<GodotJSScript>(elem->self())); //cast to gdscript to avoid being erased by accident
}
elem = elem->next();
}
}
//when someone asks you why dynamically typed languages are easier to write....
HashMap<Ref<GodotJSScript>, HashMap<ObjectID, List<Pair<StringName, Variant>>>> to_reload;
//as scripts are going to be reloaded, must proceed without locking here
scripts.sort_custom<GodotJSScriptDepSort>(); //update in inheritance dependency order
for (Ref<GodotJSScript> &scr : scripts) {
bool reload = p_scripts.has(scr) || to_reload.has(scr->get_base_script());
if (!reload) {
continue;
}
to_reload.insert(scr, HashMap<ObjectID, List<Pair<StringName, Variant>>>());
if (!p_soft_reload) {
//save state and remove script from instances
HashMap<ObjectID, List<Pair<StringName, Variant>>> &map = to_reload[scr];
while (scr->instances_.front()) {
Object *obj = scr->instances_.front()->get();
//save instance info
List<Pair<StringName, Variant>> state;
if (obj->get_script_instance()) {
obj->get_script_instance()->get_property_state(state);
map[obj->get_instance_id()] = state;
obj->set_script(Variant());
}
}
//same thing for placeholders
#ifdef TOOLS_ENABLED
while (scr->placeholders.size()) {
Object *obj = (*scr->placeholders.begin())->get_owner();
//save instance info
if (obj->get_script_instance()) {
map.insert(obj->get_instance_id(), List<Pair<StringName, Variant>>());
List<Pair<StringName, Variant>> &state = map[obj->get_instance_id()];
obj->get_script_instance()->get_property_state(state);
obj->set_script(Variant());
} else {
// no instance found. Let's remove it so we don't loop forever
scr->placeholders.erase(*scr->placeholders.begin());
}
}
#endif // TOOLS_ENABLED
for (const KeyValue<ObjectID, List<Pair<StringName, Variant>>> &F : scr->pending_reload_state_) {
map[F.key] = F.value; //pending to reload, use this one instead
}
}
}
for (KeyValue<Ref<GodotJSScript>, HashMap<ObjectID, List<Pair<StringName, Variant>>>> &E : to_reload) {
Ref<GodotJSScript> scr = E.key;
print_verbose("GodotJSScript: Reloading: " + scr->get_path());
if (scr->is_built_in()) {
// TODO: It would be nice to do it more efficiently than loading the whole scene again.
Ref<PackedScene> scene = ResourceLoader::load(scr->get_path().get_slice("::", 0), "", ResourceFormatLoader::CACHE_MODE_IGNORE_DEEP);
ERR_CONTINUE(scene.is_null());
Ref<SceneState> state = scene->get_state();
Ref<GodotJSScript> fresh = state->get_sub_resource(scr->get_path());
ERR_CONTINUE(fresh.is_null());
scr->set_source_code(fresh->get_source_code());
} else {
scr->load_source_code(scr->get_path());
}
scr->reload(p_soft_reload);
//restore state if saved
for (KeyValue<ObjectID, List<Pair<StringName, Variant>>> &F : E.value) {
List<Pair<StringName, Variant>> &saved_state = F.value;
Object *obj = ObjectDB::get_instance(F.key);
if (!obj) {
continue;
}
if (!p_soft_reload) {
//clear it just in case (may be a pending reload state)
obj->set_script(Variant());
}
obj->set_script(scr);
ScriptInstance *script_inst = obj->get_script_instance();
if (!script_inst) {
//failed, save reload state for next time if not saved
if (!scr->pending_reload_state_.has(obj->get_instance_id())) {
scr->pending_reload_state_[obj->get_instance_id()] = saved_state;
}
continue;
}
if (script_inst->is_placeholder() && scr->is_placeholder_fallback_enabled()) {
PlaceHolderScriptInstance *placeholder = static_cast<PlaceHolderScriptInstance *>(script_inst);
for (List<Pair<StringName, Variant>>::Element *G = saved_state.front(); G; G = G->next()) {
placeholder->property_set_fallback(G->get().first, G->get().second);
}
} else {
for (List<Pair<StringName, Variant>>::Element *G = saved_state.front(); G; G = G->next()) {
script_inst->set(G->get().first, G->get().second);
}
}
scr->pending_reload_state_.erase(obj->get_instance_id()); //as it reloaded, remove pending state
}
//if instance states were saved, set them!
}
#endif // DEBUG_ENABLED
}