|
|
|
@ -1,9 +1,13 @@
|
|
|
|
|
use boa_engine::{Context, Source}; |
|
|
|
|
use boa_engine::{Context, JsValue, Source}; |
|
|
|
|
|
|
|
|
|
fn main() { |
|
|
|
|
// Create the JavaScript context.
|
|
|
|
|
let mut context = Context::default(); |
|
|
|
|
|
|
|
|
|
// -----------------------------------------
|
|
|
|
|
// Loop Iteration Limit
|
|
|
|
|
// -----------------------------------------
|
|
|
|
|
|
|
|
|
|
// Set the context's runtime limit on loops to 10 iterations.
|
|
|
|
|
context.runtime_limits_mut().set_loop_iteration_limit(10); |
|
|
|
|
|
|
|
|
@ -13,7 +17,7 @@ fn main() {
|
|
|
|
|
for (let i = 0; i < 5; ++i) { } |
|
|
|
|
", |
|
|
|
|
)); |
|
|
|
|
result.expect("no error should be thrown"); |
|
|
|
|
assert!(result.is_ok()); |
|
|
|
|
|
|
|
|
|
// Here we exceed the limit by 1 iteration and a `RuntimeLimit` error is thrown.
|
|
|
|
|
//
|
|
|
|
@ -27,7 +31,7 @@ fn main() {
|
|
|
|
|
} |
|
|
|
|
", |
|
|
|
|
)); |
|
|
|
|
result.expect_err("should have throw an error"); |
|
|
|
|
assert!(result.is_err()); |
|
|
|
|
|
|
|
|
|
// Preventing an infinity loops
|
|
|
|
|
let result = context.eval_script(Source::from_bytes( |
|
|
|
@ -35,7 +39,7 @@ fn main() {
|
|
|
|
|
while (true) { } |
|
|
|
|
", |
|
|
|
|
)); |
|
|
|
|
result.expect_err("should have throw an error"); |
|
|
|
|
assert!(result.is_err()); |
|
|
|
|
|
|
|
|
|
// The limit applies to all types of loops.
|
|
|
|
|
let result = context.eval_script(Source::from_bytes( |
|
|
|
@ -43,5 +47,38 @@ fn main() {
|
|
|
|
|
for (let e of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) { } |
|
|
|
|
", |
|
|
|
|
)); |
|
|
|
|
result.expect_err("should have throw an error"); |
|
|
|
|
assert!(result.is_err()); |
|
|
|
|
|
|
|
|
|
// -----------------------------------------
|
|
|
|
|
// Recursion Limit
|
|
|
|
|
// -----------------------------------------
|
|
|
|
|
|
|
|
|
|
// Create and register `factorial` function.
|
|
|
|
|
let result = context.eval_script(Source::from_bytes( |
|
|
|
|
r" |
|
|
|
|
function factorial(n) { |
|
|
|
|
if (n == 0) { |
|
|
|
|
return 1; |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
return n * factorial(n - 1); |
|
|
|
|
} |
|
|
|
|
", |
|
|
|
|
)); |
|
|
|
|
assert!(result.is_ok()); |
|
|
|
|
|
|
|
|
|
// Run function before setting the limit and assert that it works.
|
|
|
|
|
let result = context.eval_script(Source::from_bytes("factorial(11)")); |
|
|
|
|
assert_eq!(result, Ok(JsValue::new(39_916_800))); |
|
|
|
|
|
|
|
|
|
// Setting runtime limit for recustion to 10.
|
|
|
|
|
context.runtime_limits_mut().set_recursion_limit(10); |
|
|
|
|
|
|
|
|
|
// Run without exceeding recursion limit and assert that it works.
|
|
|
|
|
let result = context.eval_script(Source::from_bytes("factorial(8)")); |
|
|
|
|
assert_eq!(result, Ok(JsValue::new(40_320))); |
|
|
|
|
|
|
|
|
|
// Run exceeding limit by 1 and assert that it fails.
|
|
|
|
|
let result = context.eval_script(Source::from_bytes("factorial(11)")); |
|
|
|
|
assert!(result.is_err()); |
|
|
|
|
} |
|
|
|
|