forked from Samsung/escargot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScript.cpp
More file actions
1337 lines (1189 loc) · 62.2 KB
/
Script.cpp
File metadata and controls
1337 lines (1189 loc) · 62.2 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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2016-present Samsung Electronics Co., Ltd
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
#include "Escargot.h"
#include "Script.h"
#include "interpreter/ByteCode.h"
#include "interpreter/ByteCodeGenerator.h"
#include "interpreter/ByteCodeInterpreter.h"
#include "parser/ast/Node.h"
#include "runtime/Context.h"
#include "runtime/Global.h"
#include "runtime/Environment.h"
#include "runtime/EnvironmentRecord.h"
#include "runtime/ErrorObject.h"
#include "runtime/ExtendedNativeFunctionObject.h"
#include "runtime/JSON.h"
#include "runtime/SandBox.h"
#include "runtime/ScriptFunctionObject.h"
#include "runtime/ScriptAsyncFunctionObject.h"
#include "runtime/ModuleNamespaceObject.h"
#include "parser/ast/AST.h"
namespace Escargot {
void* Script::operator new(size_t size)
{
static MAY_THREAD_LOCAL bool typeInited = false;
static MAY_THREAD_LOCAL GC_descr descr;
if (!typeInited) {
GC_word obj_bitmap[GC_BITMAP_SIZE(Script)] = { 0 };
GC_set_bit(obj_bitmap, GC_WORD_OFFSET(Script, m_srcName));
GC_set_bit(obj_bitmap, GC_WORD_OFFSET(Script, m_sourceCode));
GC_set_bit(obj_bitmap, GC_WORD_OFFSET(Script, m_topCodeBlock));
GC_set_bit(obj_bitmap, GC_WORD_OFFSET(Script, m_moduleData));
descr = GC_make_descriptor(obj_bitmap, GC_WORD_LEN(Script));
typeInited = true;
}
return GC_MALLOC_EXPLICITLY_TYPED(size, descr);
}
bool Script::isExecuted()
{
if (isModule()) {
return m_moduleData->m_status >= ModuleData::ModuleStatus::Evaluating;
}
return m_topCodeBlock->byteCodeBlock() == nullptr;
}
bool Script::wasThereErrorOnModuleEvaluation()
{
return m_moduleData && m_moduleData->m_evaluationError.hasValue();
}
Value Script::moduleEvaluationError()
{
if (m_moduleData && m_moduleData->m_evaluationError.hasValue()) {
return m_moduleData->m_evaluationError.value();
}
return Value();
}
Context* Script::context()
{
return m_topCodeBlock->context();
}
Script* Script::loadModuleFromScript(ExecutionState& state, ModuleRequest& request)
{
Platform::LoadModuleResult result = Global::platform()->onLoadModule(context(), this, request.m_specifier, request.m_type);
if (!result.script) {
ErrorObject::throwBuiltinError(state, (ErrorCode)result.errorCode, result.errorMessage->toNonGCUTF8StringData().data());
return nullptr;
}
if (!result.script->moduleData()->m_didCallLoadedCallback) {
Global::platform()->didLoadModule(context(), this, result.script.value());
result.script->moduleData()->m_didCallLoadedCallback = true;
}
return result.script.value();
}
size_t Script::moduleRequestsLength()
{
if (!isModule()) {
return 0;
}
return m_moduleData->m_requestedModules.size();
}
String* Script::moduleRequest(size_t i)
{
ASSERT(isModule());
return m_moduleData->m_requestedModules[i].m_specifier;
}
Value Script::moduleInstantiate(ExecutionState& state)
{
ASSERT(isModule());
if (!moduleData()->m_didCallLoadedCallback) {
Global::platform()->didLoadModule(context(), nullptr, this);
moduleData()->m_didCallLoadedCallback = true;
}
auto result = moduleLinking(state);
if (result.gotException) {
throw result.value;
}
return result.value;
}
Value Script::moduleEvaluate(ExecutionState& state)
{
ASSERT(isModule());
auto result = moduleEvaluation(state);
if (result.gotException) {
throw result.value;
}
return result.value;
}
AtomicStringVector Script::exportedNames(ExecutionState& state, std::vector<Script*>& exportStarSet)
{
// Let module be this Source Text Module Record.
Script* module = this;
// If exportStarSet contains module, then
for (size_t i = 0; i < exportStarSet.size(); i++) {
if (exportStarSet[i] == module) {
// Assert: We’ve reached the starting point of an import * circularity.
// Return a new empty List.
return AtomicStringVector();
}
}
// Append module to exportStarSet.
exportStarSet.push_back(module);
// Let exportedNames be a new empty List.
AtomicStringVector exportedNames;
// For each ExportEntry Record e in module.[[LocalExportEntries]], do
auto& localExportEntries = m_moduleData->m_localExportEntries;
for (size_t i = 0; i < localExportEntries.size(); i++) {
auto& e = localExportEntries[i];
// Assert: module provides the direct binding for this export.
// Append e.[[ExportName]] to exportedNames.
exportedNames.push_back(e.m_exportName.value());
}
// For each ExportEntry Record e in module.[[IndirectExportEntries]], do
auto& indirectExportEntries = m_moduleData->m_indirectExportEntries;
for (size_t i = 0; i < indirectExportEntries.size(); i++) {
auto& e = indirectExportEntries[i];
// Assert: module imports a specific binding for this export.
// Append e.[[ExportName]] to exportedNames.
exportedNames.push_back(e.m_exportName.value());
}
// For each ExportEntry Record e in module.[[StarExportEntries]], do
auto& starExportEntries = m_moduleData->m_starExportEntries;
for (size_t i = 0; i < starExportEntries.size(); i++) {
auto& e = starExportEntries[i];
// Let requestedModule be HostResolveImportedModule(module, e.[[ModuleRequest]]).
// ReturnIfAbrupt(requestedModule).
Script* requestedModule = loadModuleFromScript(state, e.m_moduleRequest.value());
// Let starNames be requestedModule.GetExportedNames(exportStarSet).
auto starNames = requestedModule->exportedNames(state, exportStarSet);
// For each element n of starNames, do
for (size_t i = 0; i < starNames.size(); i++) {
// If SameValue(n, "default") is false, then
if (starNames[i] != state.context()->staticStrings().stringDefault) {
// If n is not an element of exportedNames, then
bool found = false;
for (size_t j = 0; j < exportedNames.size(); j++) {
if (starNames[i] == exportedNames[j]) {
found = true;
break;
}
}
if (!found) {
// Append n to exportedNames.
exportedNames.push_back(starNames[i]);
}
}
}
}
// Return exportedNames.
return exportedNames;
}
Script::ResolveExportResult Script::resolveExport(ExecutionState& state, AtomicString exportName, std::vector<std::tuple<Script*, AtomicString>>& resolveSet)
{
ASSERT(isModule());
// Let module be this Source Text Module Record.
Script* module = this;
// For each Record {[[module]], [[exportName]]} r in resolveSet, do:
for (size_t i = 0; i < resolveSet.size(); i++) {
// If module and r.[[module]] are the same Module Record and SameValue(exportName, r.[[exportName]]) is true, then
if (std::get<0>(resolveSet[i]) == module && std::get<1>(resolveSet[i]) == exportName) {
// Assert: this is a circular import request.
// Return null.
return Script::ResolveExportResult(Script::ResolveExportResult::Null);
}
}
// Append the Record {[[module]]: module, [[exportName]]: exportName} to resolveSet.
resolveSet.push_back(std::make_tuple(this, exportName));
// For each ExportEntry Record e in module.[[LocalExportEntries]], do
auto& localExportEntries = m_moduleData->m_localExportEntries;
for (size_t i = 0; i < localExportEntries.size(); i++) {
// If SameValue(exportName, e.[[ExportName]]) is true, then
if (localExportEntries[i].m_exportName == exportName) {
// Assert: module provides the direct binding for this export.
// Return Record{[[module]]: module, [[bindingName]]: e.[[LocalName]]}.
return Script::ResolveExportResult(Script::ResolveExportResult::Record, Optional<std::tuple<Script*, AtomicString>>(std::make_tuple(module, localExportEntries[i].m_localName.value())));
}
}
if (m_topCodeBlock == nullptr) {
return Script::ResolveExportResult(Script::ResolveExportResult::Null);
}
// For each ExportEntry Record e in module.[[IndirectExportEntries]], do
auto& indirectExportEntries = m_moduleData->m_indirectExportEntries;
for (size_t i = 0; i < indirectExportEntries.size(); i++) {
auto& e = indirectExportEntries[i];
// If SameValue(exportName, e.[[ExportName]]) is true, then
if (e.m_exportName == exportName) {
// Let importedModule be ? HostResolveImportedModule(module, e.[[ModuleRequest]]).
Script* importedModule = loadModuleFromScript(state, e.m_moduleRequest.value());
// If e.[[ImportName]] is "*", then
if (e.m_importName.value() == context()->staticStrings().asciiTable[(unsigned char)'*']) {
// Assert: module does not provide the direct binding for this export.
// Return ResolvedBinding Record { [[Module]]: importedModule, [[BindingName]]: "*namespace*" }.
return Script::ResolveExportResult(Script::ResolveExportResult::Record, Optional<std::tuple<Script*, AtomicString>>(std::make_tuple(importedModule, context()->staticStrings().stringStarNamespaceStar)));
} else {
// Else,
// Assert: module imports a specific binding for this export.
// Return importedModule.ResolveExport(e.[[ImportName]], resolveSet).
return importedModule->resolveExport(state, e.m_importName.value(), resolveSet);
}
}
}
// If SameValue(exportName, "default") is true, then
if (exportName == context()->staticStrings().stringDefault) {
// Assert: A default export was not explicitly defined by this module.
// Throw a SyntaxError exception.
// NOTE A default export cannot be provided by an export *.
ErrorObject::throwBuiltinError(state, ErrorCode::SyntaxError, "The module '%s' does not provide an export named 'default'", srcName());
}
// Let starResolution be null.
Script::ResolveExportResult starResolution(Script::ResolveExportResult::Null);
// For each ExportEntry Record e in module.[[StarExportEntries]], do
auto& starExportEntries = m_moduleData->m_starExportEntries;
for (size_t i = 0; i < starExportEntries.size(); i++) {
auto& e = starExportEntries[i];
// Let importedModule be HostResolveImportedModule(module, e.[[ModuleRequest]]).
Script* importedModule = loadModuleFromScript(state, e.m_moduleRequest.value());
// Let resolution be importedModule.ResolveExport(exportName, resolveSet).
auto resolution = importedModule->resolveExport(state, exportName, resolveSet);
// If resolution is "ambiguous", return "ambiguous".
if (resolution.m_type == Script::ResolveExportResult::Ambiguous) {
return resolution;
}
// If resolution is not null, then
if (resolution.m_type != Script::ResolveExportResult::Null) {
// If starResolution is null, let starResolution be resolution.
if (starResolution.m_type == Script::ResolveExportResult::Null) {
starResolution = resolution;
} else {
// Else
// Assert: there is more than one * import that includes the requested name.
// If resolution.[[module]] and starResolution.[[module]] are not the same Module Record or SameValue(resolution.[[exportName]], starResolution.[[exportName]]) is false, return "ambiguous".
if (std::get<0>(resolution.m_record.value()) != std::get<0>(starResolution.m_record.value())
|| std::get<1>(resolution.m_record.value()) != std::get<1>(starResolution.m_record.value())) {
return Script::ResolveExportResult(Script::ResolveExportResult::Ambiguous);
}
}
}
}
return starResolution;
}
// https://www.ecma-international.org/ecma-262/9.0/#sec-candeclareglobalfunction
static bool canDeclareGlobalFunction(ExecutionState& state, Object* globalObject, AtomicString N)
{
// Let envRec be the global Environment Record for which the method was invoked.
// Let ObjRec be envRec.[[ObjectRecord]].
// Let globalObject be the binding object for ObjRec.
// Let existingProp be ? globalObject.[[GetOwnProperty]](N).
auto existingProp = globalObject->getOwnProperty(state, N);
// If existingProp is undefined, return ? IsExtensible(globalObject).
if (!existingProp.hasValue()) {
return globalObject->isExtensible(state);
}
// If existingProp.[[Configurable]] is true, return true.
if (existingProp.isConfigurable()) {
return true;
}
// If IsDataDescriptor(existingProp) is true and existingProp has attribute values { [[Writable]]: true, [[Enumerable]]: true }, return true.
if (existingProp.isDataProperty() && existingProp.isWritable() && existingProp.isEnumerable()) {
return true;
}
// Return false.
return false;
}
static void testDeclareGlobalFunctions(ExecutionState& state, InterpretedCodeBlock* topCodeBlock, Object* globalObject)
{
if (topCodeBlock->hasChildren()) {
InterpretedCodeBlockVector& childrenVector = topCodeBlock->children();
for (size_t i = 0; i < childrenVector.size(); i++) {
auto c = childrenVector[i];
if (c->isFunctionDeclaration() && c->lexicalBlockIndexFunctionLocatedIn() == 0) {
if (!canDeclareGlobalFunction(state, globalObject, c->functionName())) {
ErrorObject::throwBuiltinError(state, ErrorCode::TypeError, "Identifier '%s' has already been declared", c->functionName());
}
}
}
}
}
Value Script::execute(ExecutionState& state, bool isExecuteOnEvalFunction, bool inStrictMode)
{
if (UNLIKELY(isExecuted())) {
if (!m_canExecuteAgain) {
ESCARGOT_LOG_ERROR("You cannot re-execute this type of Script object");
RELEASE_ASSERT_NOT_REACHED();
}
m_topCodeBlock = state.context()->scriptParser().initializeScript(m_sourceCode, m_srcName, m_moduleData).script->m_topCodeBlock;
}
if (isModule()) {
if (!moduleData()->m_didCallLoadedCallback) {
Global::platform()->didLoadModule(context(), nullptr, this);
moduleData()->m_didCallLoadedCallback = true;
}
// https://www.ecma-international.org/ecma-262/#sec-toplevelmoduleevaluationjob
auto result = moduleLinking(state);
if (result.gotException) {
throw result.value;
}
result = moduleEvaluation(state);
if (result.gotException) {
throw result.value;
}
return result.value;
}
ByteCodeBlock* byteCodeBlock = m_topCodeBlock->byteCodeBlock();
ExecutionState* newState;
if (LIKELY(!m_topCodeBlock->isAsync())) {
if (byteCodeBlock->needsExtendedExecutionState()) {
newState = new (alloca(sizeof(ExtendedExecutionState))) ExtendedExecutionState(context());
} else {
newState = new (alloca(sizeof(ExecutionState))) ExecutionState(context());
}
} else {
newState = new ExtendedExecutionState(context(), nullptr, nullptr, 0, nullptr, false);
}
ExecutionState* codeExecutionState = newState;
EnvironmentRecord* globalRecord = new GlobalEnvironmentRecord(state, m_topCodeBlock, context()->globalObject(), context()->globalDeclarativeRecord(), context()->globalDeclarativeStorage());
LexicalEnvironment* globalLexicalEnvironment = new LexicalEnvironment(globalRecord, nullptr);
newState->setLexicalEnvironment(globalLexicalEnvironment, m_topCodeBlock->isStrict());
EnvironmentRecord* globalVariableRecord = globalRecord;
if (isExecuteOnEvalFunction) {
// NOTE: ES5 10.4.2.1 eval in strict mode
// + Indirect eval code creates a new declarative environment for lexically-scoped declarations (let)
EnvironmentRecord* newVariableRecord = new DeclarativeEnvironmentRecordNotIndexed(state, true);
ExecutionState* newVariableState = new ExtendedExecutionState(context());
newVariableState->setLexicalEnvironment(new LexicalEnvironment(newVariableRecord, globalLexicalEnvironment), m_topCodeBlock->isStrict());
newVariableState->setParent(newState);
codeExecutionState = newVariableState;
if (inStrictMode) {
globalVariableRecord = newVariableRecord;
}
}
testDeclareGlobalFunctions(state, m_topCodeBlock, context()->globalObject());
const InterpretedCodeBlock::IdentifierInfoVector& identifierVector = m_topCodeBlock->identifierInfos();
size_t identifierVectorLen = identifierVector.size();
const auto& globalLexicalVector = m_topCodeBlock->blockInfo(0)->identifiers();
size_t globalLexicalVectorLen = globalLexicalVector.size();
if (!isExecuteOnEvalFunction) {
if (m_topCodeBlock->hasChildren()) {
InterpretedCodeBlockVector& childrenVector = m_topCodeBlock->children();
for (size_t i = 0; i < childrenVector.size(); i++) {
InterpretedCodeBlock* child = childrenVector[i];
if (child->isFunctionDeclaration()) {
if (child->lexicalBlockIndexFunctionLocatedIn() == 0 && !state.context()->globalObject()->defineOwnProperty(state, child->functionName(), ObjectPropertyDescriptor(Value(), (ObjectPropertyDescriptor::PresentAttribute)(ObjectPropertyDescriptor::WritablePresent | ObjectStructurePropertyDescriptor::EnumerablePresent)))) {
ErrorObject::throwBuiltinError(state, ErrorCode::SyntaxError, "Identifier '%s' has already been declared", child->functionName());
}
}
}
}
// https://www.ecma-international.org/ecma-262/#sec-globaldeclarationinstantiation
IdentifierRecordVector* globalDeclarativeRecord = context()->globalDeclarativeRecord();
size_t globalDeclarativeRecordLen = globalDeclarativeRecord->size();
for (size_t i = 0; i < globalDeclarativeRecordLen; i++) {
// For each name in varNames, do
// If envRec.HasLexicalDeclaration(name) is true, throw a SyntaxError
for (size_t j = 0; j < identifierVectorLen; j++) {
if (identifierVector[j].m_isVarDeclaration && identifierVector[j].m_name == globalDeclarativeRecord->at(i).m_name) {
ErrorObject::throwBuiltinError(state, ErrorCode::SyntaxError, globalDeclarativeRecord->at(i).m_name.string(), false, String::emptyString, ErrorObject::Messages::DuplicatedIdentifier);
}
}
}
for (size_t i = 0; i < globalLexicalVectorLen; i++) {
// Let hasRestrictedGlobal be ? envRec.HasRestrictedGlobalProperty(name).
// If hasRestrictedGlobal is true, throw a SyntaxError exception.
auto desc = context()->globalObject()->getOwnProperty(state, globalLexicalVector[i].m_name);
if (desc.hasValue() && !desc.isConfigurable()) {
ErrorObject::throwBuiltinError(state, ErrorCode::SyntaxError, globalLexicalVector[i].m_name.string(), false, String::emptyString, "redeclaration of non-configurable global property %s");
}
}
}
{
VirtualIdDisabler d(context()); // we should create binding even there is virtual ID
for (size_t i = 0; i < globalLexicalVectorLen; i++) {
codeExecutionState->lexicalEnvironment()->record()->createBinding(*codeExecutionState, globalLexicalVector[i].m_name, false, globalLexicalVector[i].m_isMutable, false);
}
for (size_t i = 0; i < identifierVectorLen; i++) {
// https://www.ecma-international.org/ecma-262/5.1/#sec-10.5
// Step 2. If code is eval code, then let configurableBindings be true.
if (identifierVector[i].m_isVarDeclaration) {
globalVariableRecord->createBinding(*codeExecutionState, identifierVector[i].m_name, isExecuteOnEvalFunction, identifierVector[i].m_isMutable, true, m_topCodeBlock);
}
}
}
Value thisValue(context()->globalObjectProxy());
const size_t literalStorageSize = byteCodeBlock->m_numeralLiteralData.size();
const size_t registerFileSize = byteCodeBlock->m_requiredTotalRegisterNumber;
ASSERT(registerFileSize == byteCodeBlock->m_requiredOperandRegisterNumber + m_topCodeBlock->totalStackAllocatedVariableSize() + literalStorageSize);
Value* registerFile;
if (LIKELY(!m_topCodeBlock->isAsync())) {
registerFile = ALLOCA(registerFileSize * sizeof(Value), Value);
} else {
registerFile = CustomAllocator<Value>().allocate(registerFileSize);
// we need to reset allocated memory because customAllocator read it
memset(static_cast<void*>(registerFile), 0, sizeof(Value) * registerFileSize);
}
registerFile[0] = Value();
Value* stackStorage = registerFile + byteCodeBlock->m_requiredOperandRegisterNumber;
stackStorage[0] = thisValue;
Value* literalStorage = stackStorage + m_topCodeBlock->totalStackAllocatedVariableSize();
Value* src = byteCodeBlock->m_numeralLiteralData.data();
for (size_t i = 0; i < literalStorageSize; i++) {
literalStorage[i] = src[i];
}
Value resultValue;
if (LIKELY(!m_topCodeBlock->isAsync())) {
#ifdef ESCARGOT_DEBUGGER
// set the next(first) breakpoint to be stopped in a newer script execution
context()->setAsAlwaysStopState();
#endif
resultValue = Interpreter::interpret(codeExecutionState, byteCodeBlock, reinterpret_cast<size_t>(byteCodeBlock->m_code.data()), registerFile);
clearStack<512>();
// we give up program bytecodeblock after first excution for reducing memory usage
m_topCodeBlock->setByteCodeBlock(nullptr);
} else {
ScriptAsyncFunctionObject* fakeFunctionObject = new ScriptAsyncFunctionObject(state, state.context()->globalObject()->asyncFunctionPrototype(), m_topCodeBlock, nullptr);
auto ep = new ExecutionPauser(state, fakeFunctionObject, newState, registerFile, m_topCodeBlock->byteCodeBlock());
newState->setPauseSource(ep);
ep->m_promiseCapability = PromiseObject::newPromiseCapability(*newState, newState->context()->globalObject()->promise());
resultValue = ExecutionPauser::start(*newState, newState->pauseSource().value(), newState->pauseSource()->sourceObject(), Value(), false, false, ExecutionPauser::StartFrom::Async);
}
return resultValue;
}
// NOTE: eval by direct call
Value Script::executeLocal(ExecutionState& state, Value thisValue, InterpretedCodeBlock* parentCodeBlock, bool isStrictModeOutside, bool isEvalCodeOnFunction)
{
ByteCodeBlock* byteCodeBlock = m_topCodeBlock->byteCodeBlock();
EnvironmentRecord* record;
bool inStrict = false;
if (UNLIKELY(isStrictModeOutside)) {
// NOTE: ES5 10.4.2.1 eval in strict mode
inStrict = true;
record = new DeclarativeEnvironmentRecordNotIndexed(state, true);
} else {
record = state.lexicalEnvironment()->record();
}
const InterpretedCodeBlock::IdentifierInfoVector& vec = m_topCodeBlock->identifierInfos();
size_t vecLen = vec.size();
// test there was let on block scope
LexicalEnvironment* e = state.lexicalEnvironment();
while (e) {
if (e->record()->isDeclarativeEnvironmentRecord() && e->record()->asDeclarativeEnvironmentRecord()->isFunctionEnvironmentRecord()) {
break;
}
if (e->record()->isGlobalEnvironmentRecord()) {
break;
}
// https://www.ecma-international.org/ecma-262/10.0/#sec-variablestatements-in-catch-blocks
if (e->record()->isDeclarativeEnvironmentRecord() && e->record()->asDeclarativeEnvironmentRecord()->isDeclarativeEnvironmentRecordNotIndexed()) {
if (e->record()->asDeclarativeEnvironmentRecord()->asDeclarativeEnvironmentRecordNotIndexed()->isCatchClause()) {
e = e->outerEnvironment();
continue;
}
}
if (!m_topCodeBlock->isStrict()) {
for (size_t i = 0; i < vecLen; i++) {
if (vec[i].m_isVarDeclaration) {
auto slot = e->record()->hasBinding(state, vec[i].m_name);
if (slot.m_isLexicallyDeclared && slot.m_index != SIZE_MAX) {
ErrorObject::throwBuiltinError(state, ErrorCode::SyntaxError, vec[i].m_name.string(), false, String::emptyString, ErrorObject::Messages::DuplicatedIdentifier);
}
}
}
}
e = e->outerEnvironment();
}
EnvironmentRecord* recordToAddVariable = record;
e = state.lexicalEnvironment();
while (!recordToAddVariable->isVarDeclarationTarget()) {
e = e->outerEnvironment();
recordToAddVariable = e->record();
}
if (recordToAddVariable->isGlobalEnvironmentRecord()) {
testDeclareGlobalFunctions(state, m_topCodeBlock, context()->globalObject());
}
for (size_t i = 0; i < vecLen; i++) {
if (vec[i].m_isVarDeclaration) {
recordToAddVariable->createBinding(state, vec[i].m_name, inStrict ? false : true, true, true, m_topCodeBlock);
}
}
LexicalEnvironment* newEnvironment = new LexicalEnvironment(record, state.lexicalEnvironment());
ExtendedExecutionState newState(&state, newEnvironment, m_topCodeBlock->isStrict());
const size_t literalStorageSize = byteCodeBlock->m_numeralLiteralData.size();
const size_t registerFileSize = byteCodeBlock->m_requiredTotalRegisterNumber;
ASSERT(registerFileSize == byteCodeBlock->m_requiredOperandRegisterNumber + m_topCodeBlock->totalStackAllocatedVariableSize() + literalStorageSize);
Value* registerFile = ALLOCA(registerFileSize * sizeof(Value), Value);
registerFile[0] = Value();
Value* stackStorage = registerFile + byteCodeBlock->m_requiredOperandRegisterNumber;
stackStorage[0] = thisValue;
Value* literalStorage = stackStorage + m_topCodeBlock->totalStackAllocatedVariableSize();
Value* src = byteCodeBlock->m_numeralLiteralData.data();
for (size_t i = 0; i < literalStorageSize; i++) {
literalStorage[i] = src[i];
}
if (isEvalCodeOnFunction && m_topCodeBlock->usesArgumentsObject()) {
AtomicString arguments = state.context()->staticStrings().arguments;
FunctionEnvironmentRecord* fnRecord = nullptr;
{
LexicalEnvironment* env = state.lexicalEnvironment();
while (env) {
if (env->record()->isDeclarativeEnvironmentRecord() && env->record()->asDeclarativeEnvironmentRecord()->isFunctionEnvironmentRecord()) {
fnRecord = env->record()->asDeclarativeEnvironmentRecord()->asFunctionEnvironmentRecord();
break;
}
env = env->outerEnvironment();
}
}
ASSERT(!!fnRecord);
FunctionObject* callee = state.resolveCallee();
if (fnRecord->hasBinding(newState, arguments).m_index == SIZE_MAX && callee->isScriptFunctionObject()) {
// FIXME check if formal parameters does not contain a rest parameter, any binding patterns, or any initializers.
bool isMapped = !callee->codeBlock()->asInterpretedCodeBlock()->hasParameterOtherThanIdentifier() && !inStrict;
callee->asScriptFunctionObject()->generateArgumentsObject(newState, state.argc(), state.argv(), fnRecord, nullptr, isMapped);
}
}
// add CodeBlock to be used in exception handling process
newState.rareData()->m_codeBlock = m_topCodeBlock;
Value resultValue = Interpreter::interpret(&newState, byteCodeBlock, reinterpret_cast<size_t>(byteCodeBlock->m_code.data()), registerFile);
clearStack<512>();
return resultValue;
}
void* Script::ModuleData::ModulePromiseObject::operator new(size_t size)
{
static MAY_THREAD_LOCAL bool typeInited = false;
static MAY_THREAD_LOCAL GC_descr descr;
if (!typeInited) {
GC_word desc[GC_BITMAP_SIZE(ModulePromiseObject)] = { 0 };
PromiseObject::fillGCDescriptor(desc);
GC_set_bit(desc, GC_WORD_OFFSET(ModulePromiseObject, m_referrer));
GC_set_bit(desc, GC_WORD_OFFSET(ModulePromiseObject, m_loadedScript));
GC_set_bit(desc, GC_WORD_OFFSET(ModulePromiseObject, m_value));
descr = GC_make_descriptor(desc, GC_WORD_LEN(ModulePromiseObject));
typeInited = true;
}
return GC_MALLOC_EXPLICITLY_TYPED(size, descr);
}
Script::ModuleExecutionResult Script::moduleLinking(ExecutionState& state)
{
// On success, Instantiate transitions this module's [[Status]] from "unlinked" to "linked". On failure, an exception is thrown and this module's [[Status]] remains "unlinked".
ASSERT(isModule());
// Let module be this Cyclic Module Record.
// Assert: module.[[Status]] is not "linking" or "evaluating".
ASSERT(moduleData()->m_status != ModuleData::Linking && moduleData()->m_status != ModuleData::Evaluating);
// Let stack be a new empty List.
std::vector<Script*> stack;
// Let result be InnerModuleInstantiation(module, stack, 0).
ModuleExecutionResult result = innerModuleLinking(state, stack, 0);
// If result is an abrupt completion, then
if (result.gotException) {
// For each module m in stack, do
for (size_t i = 0; i < stack.size(); i++) {
// Assert: m.[[Status]] is "linking".
ASSERT(stack[i]->isModule());
ModuleData* m = stack[i]->moduleData();
ASSERT(m->m_status == ModuleData::Linking);
// Set m.[[Status]] to "unlinked".
m->m_status = ModuleData::Unlinked;
// Set m.[[Environment]] to undefined.
m->m_moduleRecord = nullptr;
// Set m.[[DFSIndex]] to undefined.
m->m_dfsIndex.reset();
// Set m.[[DFSAncestorIndex]] to undefined.
m->m_dfsAncestorIndex.reset();
}
// Assert: module.[[Status]] is "unlinked".
ASSERT(moduleData()->m_status == ModuleData::Unlinked);
// Return result.
return result;
}
// Assert: module.[[Status]] is "linked" or "evaluated".
ASSERT(moduleData()->m_status == ModuleData::Linked || moduleData()->m_status == ModuleData::Evaluated);
// Assert: stack is empty.
ASSERT(stack.empty());
// Return undefined.
return ModuleExecutionResult(false, Value());
}
Script::ModuleExecutionResult Script::innerModuleLinking(ExecutionState& state, std::vector<Script*>& stack, uint32_t index)
{
// If module is not a Cyclic Module Record, then
// Perform ? module.Instantiate().
// Return index.
ASSERT(isModule());
// If module.[[Status]] is "linking", "linked", or "evaluated", then
ModuleData* md = moduleData();
if (md->m_status == ModuleData::Linking || md->m_status == ModuleData::Linked || md->m_status == ModuleData::Evaluated) {
// Return index.
return Script::ModuleExecutionResult(false, Value(index));
}
// Assert: module.[[Status]] is "unlinked".
ASSERT(md->m_status == ModuleData::Unlinked);
// Set module.[[Status]] to "linking".
md->m_status = ModuleData::Linking;
// Set module.[[DFSIndex]] to index.
md->m_dfsIndex = index;
// Set module.[[DFSAncestorIndex]] to index.
md->m_dfsAncestorIndex = index;
// Increase index by 1.
index++;
// Append module to stack.
stack.push_back(this);
// For each String required that is an element of module.[[RequestedModules]], do
size_t rmLength = moduleRequestsLength();
for (size_t i = 0; i < rmLength; i++) {
// Let requiredModule be ! HostResolveImportedModule(module, required).
Script* requiredModule = loadModuleFromScript(state, m_moduleData->m_requestedModules[i]);
// NOTE: Instantiate must be completed successfully prior to invoking this method, so every requested module is guaranteed to resolve successfully.
// Set index to ? innerModuleInstantiation(requiredModule, stack, index).
auto result = requiredModule->innerModuleLinking(state, stack, index);
if (result.gotException) {
return result;
}
index = result.value.asNumber();
// Assert: requiredModule.[[Status]] is either "linking", "linked", or "evaluated".
ASSERT(requiredModule->moduleData()->m_status == ModuleData::Linking || requiredModule->moduleData()->m_status == ModuleData::Linked || requiredModule->moduleData()->m_status == ModuleData::Evaluated);
// Assert: requiredModule.[[Status]] is "linking" if and only if requiredModule is in stack.
// this assert is removed. because some users want to instantiate their module on onLoadModule
// If requiredModule.[[Status]] is "linking", then
if (requiredModule->moduleData()->m_status == ModuleData::Linking) {
// Set module.[[DFSAncestorIndex]] to min(module.[[DFSAncestorIndex]], requiredModule.[[DFSAncestorIndex]]).
md->m_dfsAncestorIndex = std::min(md->m_dfsAncestorIndex.value(), requiredModule->moduleData()->m_dfsAncestorIndex.value());
}
}
// Perform ? module.InitializeEnvironment().
auto result = moduleInitializeEnvironment(state);
if (!result.isEmpty()) {
return Script::ModuleExecutionResult(true, result);
}
// Assert: module occurs exactly once in stack.
// Assert: module.[[DFSAncestorIndex]] is less than or equal to module.[[DFSIndex]].
ASSERT(md->m_dfsAncestorIndex.value() <= md->m_dfsIndex.value());
// If module.[[DFSAncestorIndex]] equals module.[[DFSIndex]], then
if (md->m_dfsAncestorIndex.value() == md->m_dfsIndex.value()) {
// Let done be false.
bool done = false;
// Repeat, while done is false,
while (!done) {
// Let requiredModule be the last element in stack.
Script* requiredModule = stack.back();
// Remove the last element of stack.
stack.pop_back();
// Set requiredModule.[[Status]] to "linked".
requiredModule->moduleData()->m_status = ModuleData::Linked;
// If requiredModule and module are the same Module Record, set done to true.
if (requiredModule == this) {
done = true;
}
}
}
// Return index.
return Script::ModuleExecutionResult(false, Value(index));
}
Script::ModuleExecutionResult Script::moduleEvaluation(ExecutionState& state)
{
// + https://tc39.es/proposal-top-level-await/#sec-moduleevaluation
// Let module be this Cyclic Module Record.
ModuleData* md = moduleData();
// Assert: module.[[Status]] is "linked" or "evaluated".
ASSERT(md->m_status == ModuleData::Linked || md->m_status == ModuleData::Evaluated);
// If module.[[Status]] is evaluated, set module to module.[[CycleRoot]].
if (md->m_status == ModuleData::Evaluated) {
md->m_cycleRoot = this;
}
// If module.[[TopLevelCapability]] is not empty, then
if (md->m_topLevelCapability.hasValue()) {
// Return module.[[TopLevelCapability]].[[Promise]].
return Script::ModuleExecutionResult(false, md->m_topLevelCapability.value().m_promise);
}
// Let stack be a new empty List.
std::vector<Script*> stack;
// Let capability be ! NewPromiseCapability(%Promise%).
auto capability = PromiseObject::newPromiseCapability(state, state.context()->globalObject()->promise());
// Set module.[[TopLevelCapability]] to capability.
md->m_topLevelCapability = capability;
// Let result be InnerModuleEvaluation(module, stack, 0).
auto result = innerModuleEvaluation(state, stack, 0);
// If result is an abrupt completion, then
if (result.gotException) {
// For each module m in stack, do
for (size_t i = 0; i < stack.size(); i++) {
// Assert: m.[[Status]] is "evaluating".
ASSERT(stack[i]->moduleData()->m_status == ModuleData::Evaluating);
// Set m.[[Status]] to "evaluated".
// Set m.[[EvaluationError]] to result.
// Assert: module.[[Status]] is "evaluated" and module.[[EvaluationError]] is result.
stack[i]->moduleData()->m_status = ModuleData::Evaluated;
stack[i]->moduleData()->m_evaluationError = EncodedValue(result.value);
}
// Perform ! Call(capability.[[Reject]], undefined, « result.[[Value]] »).
Value arg = result.value;
Object::call(state, capability.m_rejectFunction, Value(), 1, &arg);
} else {
// Otherwise,
// Assert: module.[[Status]] is "evaluated" and module.[[EvaluationError]] is undefined.
// If module.[[AsyncEvaluating]] is false, then
if (!md->m_asyncEvaluating) {
// Perform ! Call(capability.[[Resolve]], undefined, « undefined »).
Value arg;
Object::call(state, capability.m_resolveFunction, Value(), 1, &arg);
}
// Assert: stack is empty.
}
// Return capability.[[Promise]].
// FIXME return promise
return result;
}
Script::ModuleExecutionResult Script::innerModuleEvaluation(ExecutionState& state, std::vector<Script*>& stack, uint32_t index)
{
//+ https://tc39.es/proposal-top-level-await/#sec-innermoduleevaluation
// If module is not a Cyclic Module Record, then
// Perform ? module.Evaluate().
// Return index.
ASSERT(isModule());
ModuleData* md = moduleData();
// If module.[[Status]] is "evaluated", then
if (md->m_status == ModuleData::Evaluated) {
// If module.[[EvaluationError]] is undefined, return index.
if (!md->m_evaluationError.hasValue() || Value(md->m_evaluationError.value()).isUndefined()) {
return Script::ModuleExecutionResult(false, Value(index));
}
// Otherwise return module.[[EvaluationError]].
return Script::ModuleExecutionResult(true, md->m_evaluationError.value());
}
// If module.[[Status]] is "evaluating", return index.
if (md->m_status == ModuleData::Evaluating) {
return Script::ModuleExecutionResult(false, Value(index));
}
// Assert: module.[[Status]] is "linked".
ASSERT(md->m_status == ModuleData::Linked);
// Set module.[[Status]] to "evaluating".
md->m_status = ModuleData::Evaluating;
// Set module.[[DFSIndex]] to index.
md->m_dfsIndex = index;
// Set module.[[DFSAncestorIndex]] to index.
md->m_dfsAncestorIndex = index;
// Set module.[[PendingAsyncDependencies]] to 0.
md->m_pendingAsyncDependencies = size_t(0);
// Increase index by 1.
index++;
// Append module to stack.
stack.push_back(this);
// For each String required that is an element of module.[[RequestedModules]], do
size_t rmLength = moduleRequestsLength();
for (size_t i = 0; i < rmLength; i++) {
// Let requiredModule be ! HostResolveImportedModule(module, required).
Script* requiredModule = loadModuleFromScript(state, m_moduleData->m_requestedModules[i]);
// NOTE: Instantiate must be completed successfully prior to invoking this method, so every requested module is guaranteed to resolve successfully.
// Set index to ? InnerModuleEvaluation(requiredModule, stack, index).
auto result = requiredModule->innerModuleEvaluation(state, stack, index);
if (result.gotException) {
return result;
}
index = result.value.asNumber();
// Assert: requiredModule.[[Status]] is either "evaluating" or "evaluated".
ASSERT(requiredModule->moduleData()->m_status == ModuleData::Evaluating || requiredModule->moduleData()->m_status == ModuleData::Evaluated);
// Assert: requiredModule.[[Status]] is "evaluating" if and only if requiredModule is in stack.
#if !defined(NDEBUG)
if (requiredModule->moduleData()->m_status == ModuleData::Evaluating) {
bool onStack = false;
for (size_t j = 0; j < stack.size(); j++) {
if (stack[j] == requiredModule) {
onStack = true;
break;
}
}
ASSERT(onStack);
}
#endif
// If requiredModule.[[Status]] is "evaluating", then
if (requiredModule->moduleData()->m_status == ModuleData::Evaluating) {
// Assert: requiredModule is a Cyclic Module Record.
ASSERT(requiredModule->isModule());
// Set module.[[DFSAncestorIndex]] to min(module.[[DFSAncestorIndex]], requiredModule.[[DFSAncestorIndex]]).
md->m_dfsAncestorIndex = std::min(md->m_dfsAncestorIndex.value(), requiredModule->moduleData()->m_dfsAncestorIndex.value());
} else {
// Otherwise,
// Set requiredModule to requiredModule.[[CycleRoot]].
requiredModule = requiredModule->moduleData()->m_cycleRoot.value();
// Assert: requiredModule.[[Status]] is evaluated.
ASSERT(requiredModule->moduleData()->m_status == ModuleData::Evaluated);
// If requiredModule.[[EvaluationError]] is not empty, return requiredModule.[[EvaluationError]].
if (requiredModule->moduleData()->m_evaluationError.hasValue()) {
return Script::ModuleExecutionResult(true, requiredModule->moduleData()->m_evaluationError.value());
}
}
// If requiredModule.[[AsyncEvaluating]] is true, then
if (requiredModule->moduleData()->m_asyncEvaluating) {
// Set module.[[PendingAsyncDependencies]] to module.[[PendingAsyncDependencies]] + 1.
md->m_pendingAsyncDependencies = size_t(md->m_pendingAsyncDependencies.value() + 1);
// Append module to requiredModule.[[AsyncParentModules]].
requiredModule->moduleData()->m_asyncParentModules.pushBack(this);
}
}
if (m_topCodeBlock == nullptr) {
// Synthetic module evaluation
ModuleEnvironmentRecord* moduleRecord = md->m_moduleRecord;
moduleRecord->createBinding(state, state.context()->staticStrings().stringStarDefaultStar, false, false, false);
try {
moduleRecord->initializeBinding(state, state.context()->staticStrings().stringStarDefaultStar, JSON::parse(state, sourceCode(), Value()));
} catch (const Value& e) {
md->m_evaluationError = EncodedValue(e);
}
} else if (md->m_pendingAsyncDependencies.hasValue() && md->m_pendingAsyncDependencies.value() > 0) {
// If module.[[PendingAsyncDependencies]] > 0, set module.[[AsyncEvaluating]] to true.
md->m_asyncEvaluating = true;
} else if (m_topCodeBlock->isAsync()) {
// Otherwise, if module.[[Async]] is true, perform ! ExecuteAsyncModule(module).
moduleExecuteAsyncModule(state);
} else {
// Otherwise, perform ? module.ExecuteModule().
auto result = moduleExecute(state);
if (result.gotException) {
return result;
}
}
// Assert: module occurs exactly once in stack.
// Assert: module.[[DFSAncestorIndex]] is less than or equal to module.[[DFSIndex]].
ASSERT(md->m_dfsAncestorIndex.value() <= md->m_dfsIndex.value());
// If module.[[DFSAncestorIndex]] equals module.[[DFSIndex]], then
if (md->m_dfsAncestorIndex.value() == md->m_dfsIndex.value()) {
// Let cycleRoot be module.
auto cycleRoot = this;
// Let done be false.
bool done = false;
// Repeat, while done is false,
while (!done) {
// Let requiredModule be the last element in stack.
Script* requiredModule = stack.back();
// Remove the last element of stack.
stack.pop_back();
// Set requiredModule.[[Status]] to "evaluated".
requiredModule->moduleData()->m_status = ModuleData::Evaluated;
// If requiredModule and module are the same Module Record, set done to true.
if (requiredModule == this) {
done = true;
}
// Set requiredModule.[[CycleRoot]] to cycleRoot.
requiredModule->moduleData()->m_cycleRoot = cycleRoot;
}
}
// Return index.
return Script::ModuleExecutionResult(false, Value(index));
}
Value Script::moduleInitializeEnvironment(ExecutionState& state)
{
ASSERT(m_moduleData->m_moduleRecord == nullptr);
// For each ExportEntry Record e in module.[[IndirectExportEntries]], do
auto& indirectExportEntries = m_moduleData->m_indirectExportEntries;
for (size_t i = 0; i < indirectExportEntries.size(); i++) {
auto& e = indirectExportEntries[i];
// Let resolution be ? module.ResolveExport(e.[[ExportName]], « »).
auto resolution = resolveExport(state, e.m_exportName.value());
// If resolution is null or "ambiguous", throw a SyntaxError exception.
if (resolution.m_type == ResolveExportResult::Null || resolution.m_type == ResolveExportResult::Ambiguous) {
StringBuilder builder;
builder.appendString("The export binding '");
builder.appendString(e.m_exportName.value().string());