forked from boa-dev/boa
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
415 lines (393 loc) · 14.2 KB
/
lib.rs
File metadata and controls
415 lines (393 loc) · 14.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
//! Boa's **boa_runtime** crate contains an example runtime and basic runtime features and
//! functionality for the `boa_engine` crate for runtime implementors.
//!
//! # Example: Adding Web API's Console Object
//!
//! 1. Add **boa_runtime** as a dependency to your project along with **boa_engine**.
//!
//! ```
//! use boa_engine::{js_string, property::Attribute, Context, Source};
//! use boa_runtime::Console;
//! use boa_runtime::console::DefaultLogger;
//!
//! // Create the context.
//! let mut context = Context::default();
//!
//! // Register the Console object to the context. The DefaultLogger simply
//! // write errors to STDERR and all other logs to STDOUT.
//! Console::register_with_logger(DefaultLogger, &mut context)
//! .expect("the console object shouldn't exist yet");
//!
//! // JavaScript source for parsing.
//! let js_code = "console.log('Hello World from a JS code string!')";
//!
//! // Parse the source code
//! match context.eval(Source::from_bytes(js_code)) {
//! Ok(res) => {
//! println!(
//! "{}",
//! res.to_string(&mut context).unwrap().to_std_string_escaped()
//! );
//! }
//! Err(e) => {
//! // Pretty print the error
//! eprintln!("Uncaught {e}");
//! # panic!("An error occurred in boa_runtime's js_code");
//! }
//! };
//! ```
//!
//! # Example: Add all supported Boa's Runtime Web API to your context
//!
//! ```no_run
//! use boa_engine::{js_string, property::Attribute, Context, Source};
//!
//! // Create the context.
//! let mut context = Context::default();
//!
//! // Register all objects in the context. To conditionally register extensions,
//! // call `register()` directly on the extension.
//! boa_runtime::register(
//! (
//! // Register the default logger.
//! boa_runtime::extensions::ConsoleExtension::default(),
//! // A fetcher can be added if the `fetch` feature flag is enabled.
//! // This fetcher uses the Reqwest blocking API to allow fetching using HTTP.
//! # #[cfg(feature = "reqwest-blocking")]
//! boa_runtime::extensions::FetchExtension(
//! boa_runtime::fetch::BlockingReqwestFetcher::default()
//! ),
//! ),
//! None,
//! &mut context,
//! );
//!
//! // JavaScript source for parsing.
//! let js_code = r#"
//! fetch("https://google.com/")
//! .then(response => response.text())
//! .then(html => console.log(html))
//! "#;
//!
//! // Parse the source code
//! match context.eval(Source::from_bytes(js_code)) {
//! Ok(res) => {
//! // The result is a promise, so we need to await it.
//! res
//! .as_promise()
//! .expect("Should be a promise")
//! .await_blocking(&mut context)
//! .expect("Should resolve()");
//! println!(
//! "{}",
//! res.to_string(&mut context).unwrap().to_std_string_escaped()
//! );
//! }
//! Err(e) => {
//! // Pretty print the error
//! eprintln!("Uncaught {e}");
//! # panic!("An error occurred in boa_runtime's js_code");
//! }
//! };
//! ```
#![doc = include_str!("../ABOUT.md")]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/boa-dev/boa/main/assets/logo_black.svg",
html_favicon_url = "https://raw.githubusercontent.com/boa-dev/boa/main/assets/logo_black.svg"
)]
#![cfg_attr(test, allow(clippy::needless_raw_string_hashes))] // Makes strings a bit more copy-pastable
#![cfg_attr(not(test), forbid(clippy::unwrap_used))]
// Currently throws a false positive regarding dependencies that are only used in tests.
#![allow(unused_crate_dependencies)]
#![allow(
clippy::module_name_repetitions,
clippy::redundant_pub_crate,
clippy::let_unit_value
)]
pub mod base64;
pub mod console;
#[doc(inline)]
pub use console::{Console, ConsoleState, DefaultLogger, Logger, NullLogger};
#[cfg(feature = "fetch")]
pub mod abort;
pub mod clone;
pub mod extensions;
#[cfg(feature = "fetch")]
pub mod fetch;
pub mod interval;
pub mod message;
pub mod microtask;
#[cfg(feature = "process")]
pub mod process;
pub mod store;
/// Support for the `$262` test262 harness object.
#[cfg(feature = "test262")]
pub mod test262;
pub mod text;
#[cfg(feature = "url")]
pub mod url;
#[cfg(feature = "process")]
use crate::extensions::ProcessExtension;
use crate::extensions::{
Base64Extension, EncodingExtension, MicrotaskExtension, StructuredCloneExtension,
TimeoutExtension,
};
pub use extensions::RuntimeExtension;
/// Register all the built-in objects and functions of the `WebAPI` runtime, plus
/// any extensions defined.
///
/// # Errors
/// This will error if any of the built-in objects or functions cannot be registered.
pub fn register(
extensions: impl RuntimeExtension,
realm: Option<boa_engine::realm::Realm>,
ctx: &mut boa_engine::Context,
) -> boa_engine::JsResult<()> {
(
Base64Extension,
TimeoutExtension,
EncodingExtension,
MicrotaskExtension,
StructuredCloneExtension,
#[cfg(feature = "url")]
extensions::UrlExtension,
#[cfg(feature = "process")]
ProcessExtension,
#[cfg(feature = "fetch")]
extensions::AbortControllerExtension,
extensions,
)
.register(realm, ctx)?;
Ok(())
}
/// Register only the extensions provided. An application can use this to register
/// extensions that it previously hadn't registered.
///
/// # Errors
/// This will error if any of the built-in objects or functions cannot be registered.
pub fn register_extensions(
extensions: impl RuntimeExtension,
realm: Option<boa_engine::realm::Realm>,
ctx: &mut boa_engine::Context,
) -> boa_engine::JsResult<()> {
extensions.register(realm, ctx)?;
Ok(())
}
#[cfg(test)]
pub(crate) mod test {
use crate::extensions::ConsoleExtension;
use crate::register;
use boa_engine::{Context, JsError, JsResult, JsValue, Source, builtins};
use std::borrow::Cow;
use std::path::{Path, PathBuf};
use std::pin::Pin;
/// A test action executed in a test function.
#[allow(missing_debug_implementations)]
pub(crate) struct TestAction(Inner);
#[allow(dead_code)]
#[allow(clippy::type_complexity)]
enum Inner {
RunHarness,
Run {
source: Cow<'static, str>,
},
RunFile {
path: PathBuf,
},
RunJobs,
InspectContext {
op: Box<dyn FnOnce(&mut Context)>,
},
InspectContextAsync {
op: Box<dyn for<'a> FnOnce(&'a mut Context) -> Pin<Box<dyn Future<Output = ()> + 'a>>>,
},
Assert {
source: Cow<'static, str>,
},
AssertEq {
source: Cow<'static, str>,
expected: JsValue,
},
AssertWithOp {
source: Cow<'static, str>,
op: fn(JsValue, &mut Context) -> bool,
},
AssertOpaqueError {
source: Cow<'static, str>,
expected: JsValue,
},
AssertNativeError {
source: Cow<'static, str>,
kind: builtins::error::ErrorKind,
message: &'static str,
},
AssertContext {
op: fn(&mut Context) -> bool,
},
}
impl TestAction {
#[allow(unused)]
pub(crate) fn harness() -> Self {
Self(Inner::RunHarness)
}
/// Runs `source`, panicking if the execution throws.
pub(crate) fn run(source: impl Into<Cow<'static, str>>) -> Self {
Self(Inner::Run {
source: source.into(),
})
}
/// Executes `op` with the currently active context.
///
/// Useful to make custom assertions that must be done from Rust code.
pub(crate) fn inspect_context(op: impl FnOnce(&mut Context) + 'static) -> Self {
Self(Inner::InspectContext { op: Box::new(op) })
}
/// Executes `op` with the currently active context in an async environment.
pub(crate) fn inspect_context_async(op: impl AsyncFnOnce(&mut Context) + 'static) -> Self {
Self(Inner::InspectContextAsync {
op: Box::new(move |ctx| Box::pin(op(ctx))),
})
}
}
/// Executes a list of test actions on a new, default context.
#[track_caller]
pub(crate) fn run_test_actions(actions: impl IntoIterator<Item = TestAction>) {
let context = &mut Context::default();
register(ConsoleExtension::default(), None, context)
.expect("failed to register WebAPI objects");
run_test_actions_with(actions, context);
}
/// Executes a list of test actions on the provided context.
#[track_caller]
#[allow(clippy::too_many_lines, clippy::missing_panics_doc)]
pub(crate) fn run_test_actions_with(
actions: impl IntoIterator<Item = TestAction>,
context: &mut Context,
) {
#[track_caller]
fn forward_val(context: &mut Context, source: &str) -> JsResult<JsValue> {
context.eval(Source::from_bytes(source))
}
#[track_caller]
fn forward_file(context: &mut Context, path: impl AsRef<Path>) -> JsResult<JsValue> {
let p = path.as_ref();
context.eval(Source::from_filepath(p).map_err(JsError::from_rust)?)
}
#[track_caller]
fn fmt_test(source: &str, test: usize) -> String {
format!(
"\n\nTest case {test}: \n```\n{}\n```",
textwrap::indent(source, " ")
)
}
// Some unwrapping patterns look weird because they're replaceable
// by simpler patterns like `unwrap_or_else` or `unwrap_err
let mut i = 1;
for action in actions.into_iter().map(|a| a.0) {
match action {
Inner::RunHarness => {
if let Err(e) = forward_file(context, "./assets/harness.js") {
panic!("Uncaught {e} in the test harness");
}
}
Inner::Run { source } => {
if let Err(e) = forward_val(context, &source) {
panic!("{}\nUncaught {e}", fmt_test(&source, i));
}
}
Inner::RunFile { path } => {
if let Err(e) = forward_file(context, &path) {
panic!("Uncaught {e} in file {path:?}");
}
}
Inner::RunJobs => {
if let Err(e) = context.run_jobs() {
panic!("Uncaught {e} in a job");
}
}
Inner::InspectContext { op } => {
op(context);
}
Inner::InspectContextAsync { op } => futures_lite::future::block_on(op(context)),
Inner::Assert { source } => {
let val = match forward_val(context, &source) {
Err(e) => panic!("{}\nUncaught {e}", fmt_test(&source, i)),
Ok(v) => v,
};
let Some(val) = val.as_boolean() else {
panic!(
"{}\nTried to assert with the non-boolean value `{}`",
fmt_test(&source, i),
val.display()
)
};
assert!(val, "{}", fmt_test(&source, i));
i += 1;
}
Inner::AssertEq { source, expected } => {
let val = match forward_val(context, &source) {
Err(e) => panic!("{}\nUncaught {e}", fmt_test(&source, i)),
Ok(v) => v,
};
assert_eq!(val, expected, "{}", fmt_test(&source, i));
i += 1;
}
Inner::AssertWithOp { source, op } => {
let val = match forward_val(context, &source) {
Err(e) => panic!("{}\nUncaught {e}", fmt_test(&source, i)),
Ok(v) => v,
};
assert!(op(val, context), "{}", fmt_test(&source, i));
i += 1;
}
Inner::AssertOpaqueError { source, expected } => {
let err = match forward_val(context, &source) {
Ok(v) => panic!(
"{}\nExpected error, got value `{}`",
fmt_test(&source, i),
v.display()
),
Err(e) => e,
};
let Some(err) = err.as_opaque() else {
panic!(
"{}\nExpected opaque error, got native error `{}`",
fmt_test(&source, i),
err
)
};
assert_eq!(err, &expected, "{}", fmt_test(&source, i));
i += 1;
}
Inner::AssertNativeError {
source,
kind,
message,
} => {
let err = match forward_val(context, &source) {
Ok(v) => panic!(
"{}\nExpected error, got value `{}`",
fmt_test(&source, i),
v.display()
),
Err(e) => e,
};
let native = match err.try_native(context) {
Ok(err) => err,
Err(e) => panic!(
"{}\nCouldn't obtain a native error: {e}",
fmt_test(&source, i)
),
};
assert_eq!(native.kind(), &kind, "{}", fmt_test(&source, i));
assert_eq!(native.message(), message, "{}", fmt_test(&source, i));
i += 1;
}
Inner::AssertContext { op } => {
assert!(op(context), "Test case {i}");
i += 1;
}
}
}
}
}