forked from boa-dev/boa
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest262.rs
More file actions
379 lines (327 loc) · 12.3 KB
/
test262.rs
File metadata and controls
379 lines (327 loc) · 12.3 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
use std::{
cell::RefCell,
rc::Rc,
sync::mpsc::{self, Sender},
thread::JoinHandle,
time::Duration,
};
#[cfg(feature = "annex-b")]
use boa_engine::builtins::is_html_dda::IsHTMLDDA;
use boa_engine::{
Context, JsArgs, JsNativeError, JsResult, JsValue, Source,
builtins::array_buffer::{ArrayBuffer, SharedArrayBuffer},
js_string,
native_function::NativeFunction,
object::{JsObject, ObjectInitializer, builtins::JsSharedArrayBuffer},
property::Attribute,
};
use bus::BusReader;
/// Result of a worker thread execution.
#[derive(Debug)]
pub enum WorkerResult {
/// The worker completed successfully.
Ok,
/// The worker returned an error.
Err(String),
/// The worker panicked.
Panic(String),
}
type WorkerHandle = JoinHandle<Result<(), String>>;
/// Handles for worker threads spawned by `$262.agent.start()`.
#[derive(Debug, Clone)]
pub struct WorkerHandles(Rc<RefCell<Vec<WorkerHandle>>>);
impl Default for WorkerHandles {
fn default() -> Self {
Self::new()
}
}
impl WorkerHandles {
/// Creates a new empty set of worker handles.
#[must_use]
pub fn new() -> Self {
Self(Rc::default())
}
/// Joins all worker threads and returns their results.
#[allow(clippy::print_stderr)]
pub fn join_all(&mut self) -> Vec<WorkerResult> {
let handles = std::mem::take(&mut *self.0.borrow_mut());
handles
.into_iter()
.map(|h| {
let result = h.join();
match result {
Ok(Ok(())) => WorkerResult::Ok,
Ok(Err(msg)) => {
eprintln!("Detected error on worker thread: {msg}");
WorkerResult::Err(msg)
}
Err(e) => {
let msg = e
.downcast_ref::<&str>()
.map(|&s| String::from(s))
.unwrap_or_default();
eprintln!("Detected panic on worker thread: {msg}");
WorkerResult::Panic(msg)
}
}
})
.collect()
}
}
impl Drop for WorkerHandles {
fn drop(&mut self) {
self.join_all();
}
}
/// Creates the object `$262` in the context.
///
/// # Panics
///
/// Panics if any of the expected global properties cannot be defined.
pub fn register_js262(handles: WorkerHandles, console: bool, context: &mut Context) -> JsObject {
let global_obj = context.global_object();
let agent = agent_obj(handles, console, context);
let js262 = ObjectInitializer::new(context)
.function(
NativeFunction::from_fn_ptr(create_realm),
js_string!("createRealm"),
0,
)
.function(
NativeFunction::from_fn_ptr(detach_array_buffer),
js_string!("detachArrayBuffer"),
2,
)
.function(
NativeFunction::from_fn_ptr(eval_script),
js_string!("evalScript"),
1,
)
.function(NativeFunction::from_fn_ptr(gc), js_string!("gc"), 0)
.property(
js_string!("global"),
global_obj,
Attribute::WRITABLE | Attribute::CONFIGURABLE,
)
.property(
js_string!("agent"),
agent,
Attribute::WRITABLE | Attribute::CONFIGURABLE,
)
.build();
#[cfg(feature = "annex-b")]
js262
.create_data_property_or_throw(
js_string!("IsHTMLDDA"),
JsObject::from_proto_and_data(None, IsHTMLDDA),
context,
)
.expect("the IsHTMLDDA property must be definable");
context
.register_global_property(
js_string!("$262"),
js262.clone(),
Attribute::WRITABLE | Attribute::CONFIGURABLE,
)
.expect("shouldn't fail with the default global");
js262
}
/// The `$262.createRealm()` function.
///
/// Creates a new ECMAScript Realm, defines this API on the new realm's global object, and
/// returns the `$262` property of the new realm's global object.
#[allow(clippy::unnecessary_wraps)]
fn create_realm(_: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
let mut realm = context.create_realm()?;
realm = context.enter_realm(realm);
let js262 = register_js262(WorkerHandles::new(), false, context);
context.enter_realm(realm);
Ok(JsValue::new(js262))
}
/// The `$262.detachArrayBuffer()` function.
///
/// Implements the `DetachArrayBuffer` abstract operation.
fn detach_array_buffer(_: &JsValue, args: &[JsValue], _: &mut Context) -> JsResult<JsValue> {
fn type_err() -> JsNativeError {
JsNativeError::typ().with_message("The provided object was not an ArrayBuffer")
}
// 1. Assert: IsSharedArrayBuffer(arrayBuffer) is false.
let object = args.first().and_then(JsValue::as_object);
let mut array_buffer = object
.as_ref()
.and_then(|o| o.downcast_mut::<ArrayBuffer>())
.ok_or_else(type_err)?;
// 2. If key is not present, set key to undefined.
let key = args.get_or_undefined(1);
// 3. If SameValue(arrayBuffer.[[ArrayBufferDetachKey]], key) is false, throw a TypeError exception.
// 4. Set arrayBuffer.[[ArrayBufferData]] to null.
// 5. Set arrayBuffer.[[ArrayBufferByteLength]] to 0.
array_buffer.detach(key)?;
// 6. Return NormalCompletion(null).
Ok(JsValue::null())
}
/// The `$262.evalScript()` function.
///
/// Accepts a string value as its first argument and executes it as an ECMAScript script.
fn eval_script(_this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
args.first().and_then(JsValue::as_string).map_or_else(
|| Ok(JsValue::undefined()),
|source_text| context.eval(Source::from_bytes(&source_text.to_std_string_escaped())),
)
}
/// The `$262.gc()` function.
///
/// Wraps the host's garbage collection invocation mechanism, if such a capability exists.
/// Must throw an exception if no capability exists. This is necessary for testing the
/// semantics of any feature that relies on garbage collection, e.g. the `WeakRef` API.
#[allow(clippy::unnecessary_wraps)]
fn gc(_this: &JsValue, _: &[JsValue], _context: &mut Context) -> JsResult<JsValue> {
boa_gc::force_collect();
Ok(JsValue::undefined())
}
/// The `$262.agent.sleep()` function.
fn sleep(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
let ms = args.get_or_undefined(0).to_number(context)? / 1000.0;
std::thread::sleep(Duration::from_secs_f64(ms));
Ok(JsValue::undefined())
}
/// The `$262.agent.monotonicNow()` function.
#[allow(clippy::unnecessary_wraps)]
fn monotonic_now(_: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
#[allow(clippy::cast_precision_loss)]
Ok(JsValue::from(
context.clock().now().millis_since_epoch() as f64
))
}
/// Initializes the `$262.agent` object in the main agent.
fn agent_obj(handles: WorkerHandles, console: bool, context: &mut Context) -> JsObject {
// TODO: improve initialization of this by using a `[[HostDefined]]` field on `Context`.
let bus = Rc::new(RefCell::new(bus::Bus::new(1)));
let (reports_tx, reports_rx) = mpsc::channel();
let start = unsafe {
let bus = bus.clone();
NativeFunction::from_closure(move |_, args, context| {
let script = args
.get_or_undefined(0)
.to_string(context)?
.to_std_string()
.map_err(|e| JsNativeError::typ().with_message(e.to_string()))?;
let rx = bus.borrow_mut().add_rx();
let tx = reports_tx.clone();
handles.0.borrow_mut().push(std::thread::spawn(move || {
let context = &mut Context::builder()
.can_block(true)
.build()
.map_err(|e| e.to_string())?;
register_js262_worker(rx, tx, context);
if console {
let console = crate::Console::init(context);
context
.register_global_property(crate::Console::NAME, console, Attribute::all())
.expect("the console builtin shouldn't exist");
}
let src = Source::from_bytes(&script);
context.eval(src).map_err(|e| e.to_string())?;
context.run_jobs().map_err(|e| e.to_string())?;
Ok(())
}));
Ok(JsValue::undefined())
})
};
let broadcast = unsafe {
// should technically also have a second numeric argument, but the test262 never uses it.
NativeFunction::from_closure(move |_, args, _| {
let buffer = args.get_or_undefined(0).as_object().ok_or_else(|| {
JsNativeError::typ().with_message("argument was not a shared array")
})?;
let buffer = buffer
.downcast_ref::<SharedArrayBuffer>()
.ok_or_else(|| {
JsNativeError::typ().with_message("argument was not a shared array")
})?
.clone();
bus.borrow_mut().broadcast(buffer);
Ok(JsValue::undefined())
})
};
let get_report = unsafe {
NativeFunction::from_closure(move |_, _, _| {
let Ok(msg) = reports_rx.try_recv() else {
return Ok(JsValue::null());
};
Ok(js_string!(&msg[..]).into())
})
};
ObjectInitializer::new(context)
.function(start, js_string!("start"), 1)
.function(broadcast, js_string!("broadcast"), 2)
.function(get_report, js_string!("getReport"), 0)
.function(NativeFunction::from_fn_ptr(sleep), js_string!("sleep"), 1)
.function(
NativeFunction::from_fn_ptr(monotonic_now),
js_string!("monotonicNow"),
0,
)
.build()
}
/// Initializes the `$262` object in a worker agent.
fn register_js262_worker(
rx: BusReader<SharedArrayBuffer>,
tx: Sender<Vec<u16>>,
context: &mut Context,
) {
let rx = RefCell::new(rx);
let receive_broadcast = unsafe {
// should technically also have a second numeric argument, but the test262 never uses it.
NativeFunction::from_closure(move |_, args, context| {
let array = rx.borrow_mut().recv().map_err(|err| {
JsNativeError::typ().with_message(format!("failed to receive buffer: {err}"))
})?;
let callable = args
.get_or_undefined(0)
.as_callable()
.ok_or_else(|| JsNativeError::typ().with_message("argument is not callable"))?;
let buffer = JsSharedArrayBuffer::from_buffer(array, context);
callable.call(&JsValue::undefined(), &[buffer.into()], context)
})
};
let report = unsafe {
NativeFunction::from_closure(move |_, args, context| {
let string = args.get_or_undefined(0).to_string(context)?.to_vec();
tx.send(string)
.map_err(|e| JsNativeError::typ().with_message(e.to_string()))?;
Ok(JsValue::undefined())
})
};
let agent = ObjectInitializer::new(context)
.function(receive_broadcast, js_string!("receiveBroadcast"), 1)
.function(report, js_string!("report"), 1)
.function(NativeFunction::from_fn_ptr(sleep), js_string!("sleep"), 1)
// Don't need to signal leaving, the main thread will join with the worker
// threads anyways.
.function(
NativeFunction::from_fn_ptr(|_, _, _| Ok(JsValue::undefined())),
js_string!("leaving"),
0,
)
.function(
NativeFunction::from_fn_ptr(monotonic_now),
js_string!("monotonicNow"),
0,
)
.build();
let js262 = ObjectInitializer::new(context)
.property(
js_string!("agent"),
agent,
Attribute::WRITABLE | Attribute::CONFIGURABLE,
)
.build();
context
.register_global_property(
js_string!("$262"),
js262,
Attribute::WRITABLE | Attribute::CONFIGURABLE,
)
.expect("shouldn't fail with the default global");
}