-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathscript.rs
More file actions
2025 lines (1812 loc) · 78.1 KB
/
Copy pathscript.rs
File metadata and controls
2025 lines (1812 loc) · 78.1 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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! ## [16.1 Scripts](https://tc39.es/ecma262/#sec-scripts)
use crate::{
ecmascript::{
AbstractModule, Agent, BUILTIN_STRING_MEMORY, ECMAScriptCode, Environment, ExceptionType,
ExecutionContext, GlobalEnvironment, JsResult, LexicallyScopedDeclaration, LoadedModules,
ModuleRequest, ParseResult, PropertyLookupCache, Realm, ScriptOrModule, SourceCode,
SourceCodeType, String, Value, VarScopedDeclaration, instantiate_function_object,
script_lexically_declared_names, script_lexically_scoped_declarations,
script_var_declared_names, script_var_scoped_declarations,
},
engine::{Bindable, Executable, GcScope, NoGcScope, Scopable, Vm, bindable_handle},
heap::{
ArenaAccess, ArenaAccessMut, BaseIndex, CompactionLists, CreateHeapData, Heap,
HeapIndexHandle, HeapMarkAndSweep, WorkQueues, arena_vec_access, index_handle,
},
ndt,
};
use ahash::AHashSet;
use core::any::Any;
use oxc_ast::ast;
use oxc_diagnostics::OxcDiagnostic;
use oxc_ecmascript::BoundNames;
use std::{ptr::NonNull, rc::Rc};
/// Host defined data for an ECMAScript Agent, Script, or Module.
pub type HostDefined = Rc<dyn Any>;
/// ## [16.1 Scripts](https://tc39.es/ecma262/#sec-scripts)
///
/// Scripts are the most common way of executing synchronous JavaScript code. A
/// _Script_ can be created by parsing a source [`String`] using the
/// [`parse_script`] function, and Script can then be run using the
/// [`script_evaluation`] function.
///
/// Consider favouring [ECMAScript Modules] instead whenever possible.
///
/// [`String`]: crate::ecmascript::String
/// [`parse_script`]: crate::ecmascript::parse_script
/// [`script_evaluation`]: crate::ecmascript::script_evaluation
/// [ECMAScript Modules]: crate::ecmascript::SourceTextModule
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
pub struct Script<'a>(BaseIndex<'a, ScriptRecord<'static>>);
index_handle!(Script);
arena_vec_access!(Script, 'a, ScriptRecord, scripts);
impl core::fmt::Debug for Script<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "Script({:?})", self.get_index_u32())
}
}
impl Script<'_> {
/// Get the script statements as a slice.
pub(crate) fn get_statements<'a>(
self,
agent: &Agent,
_: NoGcScope<'a, '_>,
) -> &'a [ast::Statement<'a>] {
// SAFETY: Caller promises that SourceTextModule is rooted while the
// statements slice is held: the SourceTextModuleRecord may move during
// GC but the statements it points to do not move. Hence the reference
// is valid while the self SourceTextModule is held (the parent call).
unsafe {
core::mem::transmute::<&[ast::Statement], &'a [ast::Statement<'a>]>(
self.get(agent).ecmascript_code.as_ref(),
)
}
}
/// Get the script SourceCode.
pub(crate) fn get_source_code<'a>(
self,
agent: &Agent,
gc: NoGcScope<'a, '_>,
) -> SourceCode<'a> {
self.get(agent).source_code.bind(gc)
}
/// ### \[\[Realm]]
pub(crate) fn realm<'a>(self, agent: &Agent, gc: NoGcScope<'a, '_>) -> Realm<'a> {
self.get(agent).realm.bind(gc)
}
/// \[\[\HostDefined]]
pub(crate) fn host_defined(self, agent: &Agent) -> Option<HostDefined> {
self.get(agent).host_defined.clone()
}
pub(crate) fn insert_loaded_module(
self,
agent: &mut Agent,
request: ModuleRequest,
module: AbstractModule,
) {
let requests = &agent.heap.module_request_records;
self.get_mut(&mut agent.heap.scripts)
.loaded_modules
.insert_loaded_module(requests, request, module);
}
}
impl HeapMarkAndSweep for Script<'static> {
fn mark_values(&self, queues: &mut WorkQueues) {
queues.scripts.push(*self);
}
fn sweep_values(&mut self, compactions: &CompactionLists) {
compactions.scripts.shift_index(&mut self.0);
}
}
impl<'a> CreateHeapData<ScriptRecord<'a>, Script<'a>> for Heap {
fn create(&mut self, data: ScriptRecord<'a>) -> Script<'a> {
self.scripts.push(data.unbind());
self.alloc_counter += core::mem::size_of::<ScriptRecord<'static>>();
Script(BaseIndex::last(&self.scripts))
}
}
/// ### [16.1.4 Script Records](https://tc39.es/ecma262/#sec-script-records)
///
/// A Script Record encapsulates information about a script being evaluated.
#[derive(Debug)]
pub(crate) struct ScriptRecord<'a> {
/// ### \[\[Realm]]
///
/// The realm within which this script was created. undefined if not yet
/// assigned.
realm: Realm<'a>,
/// ### \[\[ECMAScriptCode]]
///
/// The result of parsing the source text of this script.
///
/// Note: The slice and its contents live in the SourceCode heap data in
/// its contained Allocator. The SourceCode is thus in charge of dropping
/// the ECMAScriptCode, and we ensure it doesn't drop prematurely by
/// holding the SourceCode reference.
pub(crate) ecmascript_code: NonNull<[ast::Statement<'a>]>,
pub(crate) is_strict: bool,
/// ### \[\[LoadedModules]]
///
/// A map from the specifier strings imported by this script to the
/// resolved Module Record. The list does not contain two different Records
/// with the same \[\[Specifier]].
loaded_modules: LoadedModules<'a>,
/// ### \[\[HostDefined]]
///
/// Field reserved for use by host environments that need to associate
/// additional information with a script.
pub(crate) host_defined: Option<HostDefined>,
/// Source text of the script
///
/// The source text is kept in the heap strings vector, through the
/// SourceCode struct.
pub(crate) source_code: SourceCode<'a>,
}
// SAFETY: [[ECMAScriptCode]] does not permit mutable access, and points to
// data considered (and used as) immutable. It is safe to send the pointer to
// other threads.
unsafe impl Send for ScriptRecord<'_> {}
bindable_handle!(ScriptRecord);
impl HeapMarkAndSweep for ScriptRecord<'static> {
fn mark_values(&self, queues: &mut WorkQueues) {
let Self {
realm,
ecmascript_code: _,
is_strict: _,
loaded_modules,
host_defined: _,
source_code,
} = self;
realm.mark_values(queues);
loaded_modules.mark_values(queues);
source_code.mark_values(queues);
}
fn sweep_values(&mut self, compactions: &CompactionLists) {
let Self {
realm,
ecmascript_code: _,
is_strict: _,
loaded_modules,
host_defined: _,
source_code,
} = self;
realm.sweep_values(compactions);
loaded_modules.sweep_values(compactions);
source_code.sweep_values(compactions);
}
}
/// ### [16.1.5 ParseScript ( sourceText, realm, hostDefined )](https://tc39.es/ecma262/#sec-parse-script)
///
/// The abstract operation ParseScript takes arguments _sourceText_ ([ECMAScript
/// source text]), _realm_ (a [Realm Record]), and _hostDefined_ ([anything])
/// and returns a Script Record or a non-empty List of SyntaxError objects. It
/// creates a Script Record based upon the result of parsing _sourceText_ as a
/// Script. The `strict` boolean is an additional parameter that can be used to
/// parse the _sourceText_ in strict mode: it is recommended to use strict mode
/// unless non-strict mode is required.
///
/// The resulting [`Script`] can be executed using the [`script_evaluation`]
/// function.
///
/// [`Script`]: crate::ecmascript::Script
/// [`script_evaluation`]: crate::ecmascript::script_evaluation
/// [ECMAScript source text]: crate::ecmascript::String
/// [Realm Record]: crate::ecmascript::Realm
/// [anything]: crate::ecmascript::HostDefined
pub fn parse_script<'a>(
agent: &mut Agent,
source_text: String,
realm: Realm,
strict: bool,
host_defined: Option<HostDefined>,
gc: NoGcScope<'a, '_>,
) -> Result<Script<'a>, Vec<OxcDiagnostic>> {
// 1. Let script be ParseText(sourceText, Script).
let source_type = SourceCodeType::Script { strict };
// SAFETY: Script keeps the SourceCode reference alive in the Heap, thus
// making the Program's references point to a live Allocator.
let parse_result = unsafe {
SourceCode::parse_source(
agent,
source_text,
source_type,
#[cfg(feature = "typescript")]
true,
gc,
)
};
let ParseResult {
source_code,
body,
directives: _,
is_strict,
} = match parse_result {
// 2. If script is a List of errors, return script.
Ok(result) => result,
Err(errors) => {
return Err(errors);
}
};
// 3. Return Script Record {
let script_record = ScriptRecord {
// [[Realm]]: realm,
realm: realm.unbind(),
// [[ECMAScriptCode]]: script,
// SAFETY: We are moving the statements slice onto the heap together
// with the SourceCode reference: the latter will keep alive the
// allocation that Statements point to. Hence, we can unbind the
// Statements from the garbage collector lifetime here.
ecmascript_code: NonNull::from(body),
is_strict,
// [[LoadedModules]]: « »,
loaded_modules: Default::default(),
// [[HostDefined]]: hostDefined,
host_defined,
source_code: source_code.unbind(),
};
// }
Ok(agent.heap.create(script_record).bind(gc))
}
/// ### [16.1.6 ScriptEvaluation ( scriptRecord )](https://tc39.es/ecma262/#sec-runtime-semantics-scriptevaluation)
///
/// The abstract operation ScriptEvaluation takes argument scriptRecord (a
/// Script Record) and returns either a normal completion containing an
/// ECMAScript language value or an abrupt completion.
pub fn script_evaluation<'a>(
agent: &mut Agent,
script: Script,
mut gc: GcScope<'a, '_>,
) -> JsResult<'a, Value<'a>> {
let script = script.bind(gc.nogc());
let mut id = 0;
ndt::script_evaluation_start!(|| {
id = create_id(agent, script, gc.nogc());
id
});
let script_record = script.get(agent);
let realm_id = script_record.realm;
let is_strict_mode = script_record.is_strict;
let source_code = script_record.source_code;
let realm = agent.get_realm_record_by_id(realm_id);
// 1. Let globalEnv be scriptRecord.[[Realm]].[[GlobalEnv]].
let global_env = realm.global_env.unwrap().bind(gc.nogc());
// 2. Let scriptContext be a new ECMAScript code execution context.
let script_context = ExecutionContext {
// 3. Set the Function of scriptContext to null.
function: None,
// 4. Set the Realm of scriptContext to scriptRecord.[[Realm]].
realm: realm_id.unbind(),
// 5. Set the ScriptOrModule of scriptContext to scriptRecord.
script_or_module: Some(ScriptOrModule::Script(script.unbind())),
ecmascript_code: Some(ECMAScriptCode {
// 6. Set the VariableEnvironment of scriptContext to globalEnv.
variable_environment: Environment::Global(global_env.unbind()),
// 7. Set the LexicalEnvironment of scriptContext to globalEnv.
lexical_environment: Environment::Global(global_env.unbind()),
// 8. Set the PrivateEnvironment of scriptContext to null.
private_environment: None,
is_strict_mode,
source_code: source_code.unbind(),
}),
};
// TODO: 9. Suspend the running execution context.
// 10. Push scriptContext onto the execution context stack; scriptContext is now the running execution context.
agent.push_execution_context(script_context);
// NOTE: Nova extension: if a wall-clock execution timeout is configured
// and no deadline is already active (i.e. this is the outermost script
// call), record the absolute deadline now so the bytecode dispatch loop
// can enforce it. Nested re-entrant calls intentionally inherit the
// already-running deadline rather than resetting it.
let set_deadline = agent.execution_deadline.is_none();
if set_deadline && let Some(timeout) = agent.options.execution_timeout {
agent.execution_deadline = std::time::Instant::now().checked_add(timeout);
}
// 11. Let script be scriptRecord.[[ECMAScriptCode]].
// NOTE: We cannot define the script here due to reference safety.
// 12. Let result be Completion(GlobalDeclarationInstantiation(script, globalEnv)).
// SAFETY: script is currently on the execution stack and is thus
// indirectly rooted.
let result = unsafe {
global_declaration_instantiation(agent, script.unbind(), global_env.unbind(), gc.reborrow())
.unbind()
.bind(gc.nogc())
};
let Some(ScriptOrModule::Script(script)) = agent.running_execution_context().script_or_module
else {
panic!("Expected Script");
};
let script = script.bind(gc.nogc());
// 13. If result.[[Type]] is normal, then
let result: JsResult<Value> = match result {
Ok(_) => {
let bytecode =
Executable::compile_script(agent, script, gc.nogc()).scope(agent, gc.nogc());
// a. Set result to Completion(Evaluation of script).
// b. If result.[[Type]] is normal and result.[[Value]] is empty, then
// i. Set result to NormalCompletion(undefined).
let result = Vm::execute(agent, bytecode.clone(), None, gc.reborrow())
.into_js_result()
.unbind()
.bind(gc.into_nogc());
// SAFETY: The bytecode is not accessible by anyone anymore and no one
// will try to re-run it.
unsafe { bytecode.take(agent).try_drop(agent) };
result
}
Err(err) => Err(err.unbind().bind(gc.into_nogc())),
};
// 14. Suspend scriptContext and remove it from the execution context stack.
_ = agent.pop_execution_context();
// NOTE: Nova extension: clear the deadline we set so it does not leak
// into future executions.
if set_deadline {
agent.execution_deadline = None;
}
// TODO: 15. Assert: The execution context stack is not empty.
// This is not currently true as we do not push an "empty" context stack to the root before running script evaluation.
// debug_assert!(!agent.execution_context_stack.is_empty());
// 16. Resume the context that is now on the top of the execution context stack as the
// running execution context.
// NOTE: This is done automatically.
ndt::script_evaluation_done!(|| id);
// 17. Return ? result.
result
}
#[inline(never)]
fn create_id(agent: &Agent, script: Script, gc: NoGcScope) -> u64 {
u64::try_from(script.get_statements(agent, gc).as_ptr().addr()).unwrap()
}
/// ### [16.1.7 GlobalDeclarationInstantiation ( script, env )](https://tc39.es/ecma262/#sec-globaldeclarationinstantiation)
///
/// The abstract operation GlobalDeclarationInstantiation takes arguments
/// script (a Script Parse Node) and env (a Global Environment Record) and
/// returns either a normal completion containing UNUSED or a throw completion.
/// script is the Script for which the execution context is being established.
/// env is the global environment in which bindings are to be created.
///
/// ## Safety
///
/// Script must be rooted for the duration of this call.
unsafe fn global_declaration_instantiation<'a>(
agent: &mut Agent,
script: Script,
env: GlobalEnvironment,
mut gc: GcScope<'a, '_>,
) -> JsResult<'a, ()> {
let script = script.bind(gc.nogc());
let env = env.bind(gc.nogc());
let scoped_env = env.scope(agent, gc.nogc());
// 11. Let script be scriptRecord.[[ECMAScriptCode]].
let (lex_names, var_names, var_declarations, lex_declarations) = {
// SAFETY: The caller promises that Script is rooted, meaning that its
// backing SourceCode cannot be dropped during this call. Hence, we can
// take the body slice reference and keep it alive for the duration of
// this call.
let body = unsafe { script.unbind().get(agent).ecmascript_code.as_ref() };
// 1. Let lexNames be the LexicallyDeclaredNames of script.
let lex_names = script_lexically_declared_names(body);
// 2. Let varNames be the VarDeclaredNames of script.
let var_names = script_var_declared_names(body);
// 5. Let varDeclarations be the VarScopedDeclarations of script.
let var_declarations = script_var_scoped_declarations(body);
// 13. Let lexDeclarations be the LexicallyScopedDeclarations of script.
let lex_declarations = script_lexically_scoped_declarations(body);
(lex_names, var_names, var_declarations, lex_declarations)
};
// 3. For each element name of lexNames, do
for name in lex_names {
let env = scoped_env.get(agent).bind(gc.nogc());
let name_atom = name;
let name = String::from_str(agent, name.as_str(), gc.nogc());
if
// a. If env.HasVarDeclaration(name) is true, throw a SyntaxError exception.
env.has_var_declaration(agent, name)
// b. If env.HasLexicalDeclaration(name) is true, throw a SyntaxError exception.
|| env.has_lexical_declaration(agent, name)
// c. Let hasRestrictedGlobal be ? env.HasRestrictedGlobalProperty(name).
// d. If hasRestrictedGlobal is true, throw a SyntaxError exception.
|| env.unbind().has_restricted_global_property(agent, name.unbind(), gc.reborrow()).unbind()?.bind(gc.nogc())
{
let error_message = format!(
"Redeclaration of restricted global property '{}'.",
name_atom.as_str()
);
return Err(agent.throw_exception(
ExceptionType::SyntaxError,
error_message,
gc.into_nogc(),
));
}
}
let env = scoped_env.get(agent).bind(gc.nogc());
// 4. For each element name of varNames, do
for name in &var_names {
// a. If env.HasLexicalDeclaration(name) is true, throw a SyntaxError exception.
let name = String::from_str(agent, name.as_str(), gc.nogc());
if env.has_lexical_declaration(agent, name) {
let error_message = format!(
"Redeclaration of lexical binding '{}'.",
name.to_string_lossy_(agent)
);
return Err(agent.throw_exception(
ExceptionType::SyntaxError,
error_message,
gc.into_nogc(),
));
}
}
// 6. Let functionsToInitialize be a new empty List.
let mut functions_to_initialize = vec![];
// 7. Let declaredFunctionNames be a new empty List.
let mut declared_function_names = AHashSet::default();
// 8. For each element d of varDeclarations, in reverse List order, do
for d in var_declarations.iter().rev() {
// a. If d is not either a VariableDeclaration, a ForBinding, or a BindingIdentifier, then
if let VarScopedDeclaration::Function(d) = *d {
// i. Assert: d is either a FunctionDeclaration, a GeneratorDeclaration, an AsyncFunctionDeclaration, or an AsyncGeneratorDeclaration.
// ii. NOTE: If there are multiple function declarations for the same name, the last declaration is used.
// iii. Let fn be the sole element of the BoundNames of d.
let mut function_name = None;
d.bound_names(&mut |identifier| {
assert!(function_name.is_none());
function_name = Some(identifier.name);
});
let function_name = function_name.unwrap();
// iv. If declaredFunctionNames does not contain fn, then
if declared_function_names.insert(function_name) {
// 1. Let fnDefinable be ? env.CanDeclareGlobalFunction(fn).
let fn_name = String::from_str(agent, function_name.as_str(), gc.nogc());
let fn_definable = scoped_env
.get(agent)
.can_declare_global_function(agent, fn_name.unbind(), gc.reborrow())
.unbind()?
.bind(gc.nogc());
// 2. If fnDefinable is false, throw a TypeError exception.
if !fn_definable {
let error_message = format!(
"Cannot declare of global function '{}'.",
function_name.as_str()
);
return Err(agent.throw_exception(
ExceptionType::TypeError,
error_message,
gc.into_nogc(),
));
}
// 3. Append fn to declaredFunctionNames.
// 4. Insert d as the first element of functionsToInitialize.
functions_to_initialize.push(d);
}
}
}
// 9. Let declaredVarNames be a new empty List.
let mut declared_var_names = AHashSet::default();
// 10. For each element d of varDeclarations, do
for d in var_declarations {
// a. If d is either a VariableDeclaration, a ForBinding, or a BindingIdentifier, then
if let VarScopedDeclaration::Variable(d) = d {
// i. For each String vn of the BoundNames of d, do
let mut bound_names = vec![];
d.id.bound_names(&mut |identifier| {
bound_names.push(identifier.name);
});
for vn in bound_names {
// 1. If declaredFunctionNames does not contain vn, then
if !declared_function_names.contains(&vn) {
// a. Let vnDefinable be ? env.CanDeclareGlobalVar(vn).
// TODO: This is a very problematic area for lifetimes.
// CanDeclareGlobalVar can trigger GC, but we also need to
// hash the strings to eliminate duplicates...
let vn = String::from_str(agent, vn.as_str(), gc.nogc()).unbind();
let vn_definable = scoped_env
.get(agent)
.can_declare_global_var(agent, vn, gc.reborrow())
.unbind()?
.bind(gc.nogc());
// b. If vnDefinable is false, throw a TypeError exception.
if !vn_definable {
let error_message = format!(
"Cannot declare global variable '{}'.",
vn.to_string_lossy_(agent)
);
return Err(agent.throw_exception(
ExceptionType::TypeError,
error_message,
gc.into_nogc(),
));
}
// c. If declaredVarNames does not contain vn, then
// i. Append vn to declaredVarNames.
declared_var_names.insert(vn);
}
}
}
}
// 11. NOTE: No abnormal terminations occur after this algorithm step if the
// global object is an ordinary object. However, if the global object is
// a Proxy exotic object it may exhibit behaviours that cause abnormal
// terminations in some of the following steps.
// 12. NOTE: Annex B.3.2.2 adds additional steps at this point.
// 14. Let privateEnv be null.
let private_env = None;
let env = scoped_env.get(agent).bind(gc.nogc());
// 15. For each element d of lexDeclarations, do
for d in lex_declarations {
// a. NOTE: Lexically declared names are only instantiated here but not initialized.
let mut bound_names = vec![];
let mut const_bound_names = vec![];
let mut closure = |identifier: &ast::BindingIdentifier| {
bound_names.push(String::from_str(agent, identifier.name.as_str(), gc.nogc()));
};
match d {
LexicallyScopedDeclaration::Variable(decl) => {
if decl.kind == ast::VariableDeclarationKind::Const {
decl.id.bound_names(&mut |identifier| {
const_bound_names.push(String::from_str(
agent,
identifier.name.as_str(),
gc.nogc(),
))
});
} else {
decl.id.bound_names(&mut closure)
}
}
LexicallyScopedDeclaration::Function(decl) => decl.bound_names(&mut closure),
LexicallyScopedDeclaration::Class(decl) => decl.bound_names(&mut closure),
#[cfg(feature = "typescript")]
LexicallyScopedDeclaration::TSEnum(decl) => decl.id.bound_names(&mut closure),
LexicallyScopedDeclaration::DefaultExport => {
bound_names.push(BUILTIN_STRING_MEMORY._default_)
}
}
// b. For each element dn of the BoundNames of d, do
for dn in const_bound_names {
// i. If IsConstantDeclaration of d is true, then
// 1. Perform ? env.CreateImmutableBinding(dn, true).
env.create_immutable_binding(agent, dn, true, gc.nogc())
.unbind()?
.bind(gc.nogc());
}
for dn in bound_names {
// ii. Else,
// 1. Perform ? env.CreateMutableBinding(dn, false).
env.create_mutable_binding(agent, dn, false, gc.nogc())
.unbind()?
.bind(gc.nogc());
}
}
// 16. For each Parse Node f of functionsToInitialize, do
for f in functions_to_initialize {
// a. Let fn be the sole element of the BoundNames of f.
let mut function_name = None;
f.bound_names(&mut |identifier| {
assert!(function_name.is_none());
function_name = Some(identifier.name);
});
let env = scoped_env.get(agent).bind(gc.nogc());
// b. Let fo be InstantiateFunctionObject of f with arguments env and privateEnv.
let fo =
instantiate_function_object(agent, f, Environment::Global(env), private_env, gc.nogc());
let function_name = String::from_str(agent, function_name.unwrap().as_str(), gc.nogc());
// c. Perform ? env.CreateGlobalFunctionBinding(fn, fo, false).
env.unbind()
.create_global_function_binding(
agent,
function_name.unbind(),
fo.unbind().into(),
false,
gc.reborrow(),
)
.unbind()?
.bind(gc.nogc());
}
// 17. For each String vn of declaredVarNames, do
for vn in declared_var_names {
// a. Perform ? env.CreateGlobalVarBinding(vn, false).
let cache = PropertyLookupCache::new(agent, vn.to_property_key());
scoped_env
.get(agent)
.create_global_var_binding(agent, vn, cache, false, gc.reborrow())
.unbind()?
.bind(gc.nogc());
}
// 18. Return UNUSED.
Ok(())
}
#[cfg(test)]
mod test {
use std::ops::ControlFlow;
use crate::{
ecmascript::{
Agent, AgentOptions, ArgumentsList, Array, BUILTIN_STRING_MEMORY, Behaviour,
BuiltinFunctionArgs, DefaultHostHooks, ExceptionType, InternalMethods, JsResult,
Number, Object, PropertyKey, SmallInteger, String, TryHasBindingContinue, TryHasResult,
Value, create_builtin_function, create_data_property_or_throw,
initialize_default_realm, parse_script, script_evaluation, unwrap_try,
},
engine::{Bindable, GcScope, Scopable},
heap::ArenaAccess,
};
#[test]
fn empty_script() {
let (mut gc, mut scope) = unsafe { GcScope::create_root() };
let mut gc = GcScope::new(&mut gc, &mut scope);
let mut agent = Agent::new(AgentOptions::default(), &DefaultHostHooks);
initialize_default_realm(&mut agent, gc.reborrow());
let source_text = String::from_static_str(&mut agent, "", gc.nogc());
let result = agent
.run_script(source_text.unbind(), gc.reborrow())
.unwrap();
assert_eq!(result, Value::Undefined);
}
#[test]
fn basic_constants() {
let (mut gc, mut scope) = unsafe { GcScope::create_root() };
let mut gc = GcScope::new(&mut gc, &mut scope);
let mut agent = Agent::new(AgentOptions::default(), &DefaultHostHooks);
initialize_default_realm(&mut agent, gc.reborrow());
let source_text = String::from_static_str(&mut agent, "true", gc.nogc());
let result = agent
.run_script(source_text.unbind(), gc.reborrow())
.unwrap();
assert_eq!(result, true.into());
}
#[test]
fn unary_minus() {
let (mut gc, mut scope) = unsafe { GcScope::create_root() };
let mut gc = GcScope::new(&mut gc, &mut scope);
let mut agent = Agent::new(AgentOptions::default(), &DefaultHostHooks);
initialize_default_realm(&mut agent, gc.reborrow());
let source_text = String::from_static_str(&mut agent, "-2", gc.nogc());
let result = agent
.run_script(source_text.unbind(), gc.reborrow())
.unwrap();
assert_eq!(result, (-2).into());
}
#[test]
fn unary_void() {
let (mut gc, mut scope) = unsafe { GcScope::create_root() };
let mut gc = GcScope::new(&mut gc, &mut scope);
let mut agent = Agent::new(AgentOptions::default(), &DefaultHostHooks);
initialize_default_realm(&mut agent, gc.reborrow());
let source_text = String::from_static_str(&mut agent, "void (2 + 2 + 6)", gc.nogc());
let result = agent
.run_script(source_text.unbind(), gc.reborrow())
.unwrap();
assert_eq!(result, Value::Undefined);
}
#[test]
fn unary_plus() {
let (mut gc, mut scope) = unsafe { GcScope::create_root() };
let mut gc = GcScope::new(&mut gc, &mut scope);
let mut agent = Agent::new(AgentOptions::default(), &DefaultHostHooks);
initialize_default_realm(&mut agent, gc.reborrow());
let source_text = String::from_static_str(&mut agent, "+(54)", gc.nogc());
let result = agent
.run_script(source_text.unbind(), gc.reborrow())
.unwrap();
assert_eq!(result, (54).into());
}
#[test]
fn logical_not() {
let (mut gc, mut scope) = unsafe { GcScope::create_root() };
let mut gc = GcScope::new(&mut gc, &mut scope);
let mut agent = Agent::new(AgentOptions::default(), &DefaultHostHooks);
initialize_default_realm(&mut agent, gc.reborrow());
let source_text = String::from_static_str(&mut agent, "!true", gc.nogc());
let result = agent
.run_script(source_text.unbind(), gc.reborrow())
.unwrap();
assert_eq!(result, (false).into());
}
#[test]
fn bitwise_not() {
let (mut gc, mut scope) = unsafe { GcScope::create_root() };
let mut gc = GcScope::new(&mut gc, &mut scope);
let mut agent = Agent::new(AgentOptions::default(), &DefaultHostHooks);
initialize_default_realm(&mut agent, gc.reborrow());
let source_text = String::from_static_str(&mut agent, "~0b1111", gc.nogc());
let result = agent
.run_script(source_text.unbind(), gc.reborrow())
.unwrap();
assert_eq!(result, (-16).into());
}
#[test]
fn unary_typeof() {
let (mut gc, mut scope) = unsafe { GcScope::create_root() };
let mut gc = GcScope::new(&mut gc, &mut scope);
let mut agent = Agent::new(AgentOptions::default(), &DefaultHostHooks);
initialize_default_realm(&mut agent, gc.reborrow());
// let realm = agent.current_realm_id(gc.nogc());
let source_text = String::from_static_str(&mut agent, "typeof undefined", gc.nogc());
let result = agent
.run_script(source_text.unbind(), gc.reborrow())
.unwrap();
assert_eq!(
result.unbind(),
Value::from_static_str(&mut agent, "undefined", gc.nogc())
);
let source_text = String::from_static_str(&mut agent, "typeof null", gc.nogc());
let result = agent
.run_script(source_text.unbind(), gc.reborrow())
.unwrap();
assert_eq!(
result.unbind(),
Value::from_static_str(&mut agent, "object", gc.nogc())
);
let source_text = String::from_static_str(&mut agent, "typeof \"string\"", gc.nogc());
let result = agent
.run_script(source_text.unbind(), gc.reborrow())
.unwrap();
assert_eq!(
result.unbind(),
Value::from_static_str(&mut agent, "string", gc.nogc())
);
let source_text = String::from_static_str(&mut agent, "typeof Symbol()", gc.nogc());
let result = agent
.run_script(source_text.unbind(), gc.reborrow())
.unwrap();
assert_eq!(
result.unbind(),
Value::from_static_str(&mut agent, "symbol", gc.nogc())
);
let source_text = String::from_static_str(&mut agent, "typeof true", gc.nogc());
let result = agent
.run_script(source_text.unbind(), gc.reborrow())
.unwrap();
assert_eq!(
result.unbind(),
Value::from_static_str(&mut agent, "boolean", gc.nogc())
);
let source_text = String::from_static_str(&mut agent, "typeof 3", gc.nogc());
let result = agent
.run_script(source_text.unbind(), gc.reborrow())
.unwrap();
assert_eq!(
result.unbind(),
Value::from_static_str(&mut agent, "number", gc.nogc())
);
let source_text = String::from_static_str(&mut agent, "typeof 3n", gc.nogc());
let result = agent
.run_script(source_text.unbind(), gc.reborrow())
.unwrap();
assert_eq!(
result.unbind(),
Value::from_static_str(&mut agent, "bigint", gc.nogc())
);
let source_text = String::from_static_str(&mut agent, "typeof {}", gc.nogc());
let result = agent
.run_script(source_text.unbind(), gc.reborrow())
.unwrap();
assert_eq!(
result.unbind(),
Value::from_static_str(&mut agent, "object", gc.nogc())
);
let source_text = String::from_static_str(&mut agent, "typeof (function() {})", gc.nogc());
let result = agent
.run_script(source_text.unbind(), gc.reborrow())
.unwrap();
assert_eq!(
result.unbind(),
Value::from_static_str(&mut agent, "function", gc.nogc())
);
}
#[test]
fn binary_add() {
let (mut gc, mut scope) = unsafe { GcScope::create_root() };
let mut gc = GcScope::new(&mut gc, &mut scope);
let mut agent = Agent::new(AgentOptions::default(), &DefaultHostHooks);
initialize_default_realm(&mut agent, gc.reborrow());
let source_text = String::from_static_str(&mut agent, "2 + 2 + 6", gc.nogc());
let result = agent
.run_script(source_text.unbind(), gc.reborrow())
.unwrap();
assert_eq!(result, (10).into());
}
#[test]
fn var_assign() {
let (mut gc, mut scope) = unsafe { GcScope::create_root() };
let mut gc = GcScope::new(&mut gc, &mut scope);
let mut agent = Agent::new(AgentOptions::default(), &DefaultHostHooks);
initialize_default_realm(&mut agent, gc.reborrow());
let source_text = String::from_static_str(&mut agent, "var foo = 3;", gc.nogc());
let result = agent
.run_script(source_text.unbind(), gc.reborrow())
.unwrap();
assert_eq!(result, Value::Undefined);
}
#[test]
fn empty_object() {
let (mut gc, mut scope) = unsafe { GcScope::create_root() };
let mut gc = GcScope::new(&mut gc, &mut scope);
let mut agent = Agent::new(AgentOptions::default(), &DefaultHostHooks);
initialize_default_realm(&mut agent, gc.reborrow());
let source_text = String::from_static_str(&mut agent, "var foo = {};", gc.nogc());
let result = agent
.run_script(source_text.unbind(), gc.reborrow())
.unwrap();
assert!(result.is_undefined());
let key = PropertyKey::from_static_str(&mut agent, "foo", gc.nogc());
let foo = unwrap_try(agent.current_global_object(gc.nogc()).try_get_own_property(
&mut agent,
key,
None,
gc.nogc(),
))
.unwrap()
.value
.unwrap();
assert!(foo.is_object());
let result = Object::try_from(foo).unwrap();
assert!(
result
.unbind()
.internal_own_property_keys(&mut agent, gc)
.unwrap()
.is_empty()
);
}
#[test]
fn non_empty_object() {
let (mut gc, mut scope) = unsafe { GcScope::create_root() };
let mut gc = GcScope::new(&mut gc, &mut scope);
let mut agent = Agent::new(AgentOptions::default(), &DefaultHostHooks);
initialize_default_realm(&mut agent, gc.reborrow());
let source_text = String::from_static_str(&mut agent, "var foo = { a: 3 };", gc.nogc());
let result = agent
.run_script(source_text.unbind(), gc.reborrow())
.unwrap();
assert!(result.is_undefined());
let key = PropertyKey::from_static_str(&mut agent, "foo", gc.nogc());
let foo = unwrap_try(agent.current_global_object(gc.nogc()).try_get_own_property(
&mut agent,
key,
None,
gc.nogc(),
))
.unwrap()
.value
.unwrap();
assert!(foo.is_object());
let result = Object::try_from(foo).unwrap();
let key = PropertyKey::from_static_str(&mut agent, "a", gc.nogc());
assert_eq!(
result.try_has_property(&mut agent, key, None, gc.nogc()),
ControlFlow::Continue(TryHasResult::Offset(0, result))
);
assert_eq!(
unwrap_try(result.try_get_own_property(&mut agent, key, None, gc.nogc()))
.unwrap()
.value,
Some(Value::from(3))
);
}
#[test]
fn empty_array() {
let (mut gc, mut scope) = unsafe { GcScope::create_root() };
let mut gc = GcScope::new(&mut gc, &mut scope);
let mut agent = Agent::new(AgentOptions::default(), &DefaultHostHooks);
initialize_default_realm(&mut agent, gc.reborrow());
let source_text = String::from_static_str(&mut agent, "var foo = [];", gc.nogc());
let result = agent