Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 28 additions & 9 deletions src/rust/jsg-test/tests/jsg_oneof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,14 @@ fn describe_string_or_bool(value: &StringOrBool) -> String {
/// Runs `f` with a `OneOfContext` installed as the global `cx` and a
/// `OneOfBox` holding 321 as the global `box321`.
fn with_context(f: impl for<'s, 'c> FnOnce(&mut jsg::Lock<'s>, &crate::EvalContext<'c>)) {
let harness = crate::Harness::new();
with_context_and_flags(|_| {}, f);
}

fn with_context_and_flags(
set_flags: impl FnOnce(jsg::feature_flags::compatibility_flags::Builder<'_>),
f: impl for<'s, 'c> FnOnce(&mut jsg::Lock<'s>, &crate::EvalContext<'c>),
) {
let harness = crate::Harness::with_flags(set_flags);
harness.run_in_context(|lock, ctx| {
let cx = jsg::Rc::new(lock, OneOfContext).to_js(lock)?;
ctx.set_global(lock, "cx", cx);
Expand Down Expand Up @@ -494,18 +501,30 @@ fn string_is_not_taken_as_a_sequence() {
});
}

// "kj::Maybe noSubstituteNull", whose union C++ tests with `noSubstituteNull`, as
// Rust JSG always converts `Nullable`.
// "maybes - don't substitute null" in value-test.c++: with `dont_substitute_null_on_type_error`,
// a value that no variant takes is a type error.
#[test]
fn nullable_union_rejects_a_value_no_variant_takes() {
with_context(|lock, ctx| {
assert_eq!(
expect_type_error(lock, ctx, "cx.takeMaybeStrictString({})"),
"Failed to execute 'takeMaybeStrictString' on 'OneOfContext': parameter 1 is not \
with_context_and_flags(
|mut flags| flags.set_no_substitute_null(true),
|lock, ctx| {
assert_eq!(
expect_type_error(lock, ctx, "cx.takeMaybeStrictString({})"),
"Failed to execute 'takeMaybeStrictString' on 'OneOfContext': parameter 1 is not \
of type 'string'."
);
);
expect_eval(lock, ctx, "cx.takeMaybeStrictString('a')", "string:a");
expect_eval(lock, ctx, "cx.takeMaybeStrictString(null)", "null");
},
);
}

// Without `dont_substitute_null_on_type_error`, as in C++, it is null.
#[test]
fn nullable_union_substitutes_null_without_the_flag() {
with_context(|lock, ctx| {
expect_eval(lock, ctx, "cx.takeMaybeStrictString({})", "null");
expect_eval(lock, ctx, "cx.takeMaybeStrictString('a')", "string:a");
expect_eval(lock, ctx, "cx.takeMaybeStrictString(null)", "null");
});
}

Expand Down
34 changes: 24 additions & 10 deletions src/rust/jsg-test/tests/null_or_undefined.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,17 +119,31 @@ fn conversion_preserves_all_states() {
});
}

/// Without `dont_substitute_null_on_type_error`, a value that `T` does not take is null, as for
/// C++ `jsg::Optional<kj::Maybe<T>>`; with it, it is a type error.
#[test]
fn methods_accept_omission_and_report_inner_type_errors() {
let harness = crate::Harness::new();
harness.run_in_context(|lock, ctx| {
let args = jsg::Rc::new(lock, Args {}).to_js(lock)?;
ctx.set_global(lock, "args", args);
assert!(ctx.eval::<bool>(lock, "args.echo() === undefined && args.echo(undefined) === undefined && args.echo(null) === null && args.echo('x') === 'x'").unwrap());
assert_eq!(ctx.eval::<String>(lock, "try { args.strict(123) } catch(e) { e.message }").unwrap(),
"Failed to execute 'strict' on 'Args': parameter 1 is not of type 'string'.");
Ok(())
});
for no_substitute_null in [false, true] {
let harness = crate::Harness::with_flags(|mut flags| {
flags.set_no_substitute_null(no_substitute_null);
});
harness.run_in_context(|lock, ctx| {
let args = jsg::Rc::new(lock, Args {}).to_js(lock)?;
ctx.set_global(lock, "args", args);
assert!(ctx.eval::<bool>(lock, "args.echo() === undefined && args.echo(undefined) === undefined && args.echo(null) === null && args.echo('x') === 'x'").unwrap());
let expected = if no_substitute_null {
"Failed to execute 'strict' on 'Args': parameter 1 is not of type 'string'."
} else {
"false"
};
assert_eq!(
ctx.eval::<String>(lock, "try { String(args.strict(123)) } catch(e) { e.message }")
.unwrap(),
expected
);
Ok(())
});
}
}

#[test]
Expand Down Expand Up @@ -194,7 +208,7 @@ fn struct_fields_preserve_states_with_both_wrapping_modes() {

#[test]
fn lenient_conversion_only_swallows_shallow_mismatches() {
let harness = crate::Harness::new();
let harness = crate::Harness::with_flags(|mut flags| flags.set_no_substitute_null(true));
harness.run_in_context(|lock, ctx| {
type Strict = NullOrUndefined<jsg::NonCoercible<String>>;
let input = ctx.eval_raw(lock, "123").unwrap();
Expand Down
41 changes: 41 additions & 0 deletions src/rust/jsg-test/tests/nullable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,3 +255,44 @@ fn lenient_converts_to_optional_nullable() {
Ok(())
});
}

/// As in "maybes - don't substitute null" (value-test.c++): a value that `T` does not take is
/// null for a worker without `dont_substitute_null_on_type_error`, and a type error with it.
#[test]
fn nullable_type_mismatch_follows_dont_substitute_null_on_type_error() {
type Strict = Nullable<jsg::NonCoercible<String>>;
let harness = crate::Harness::new();
harness.run_in_context(|lock, ctx| {
assert_eq!(convert::<Strict>(lock, ctx, "123")?, Nullable::Null);
// A value that `T` takes, and null, convert as before.
assert_eq!(
convert::<Strict>(lock, ctx, "'x'")?,
Nullable::Some(jsg::NonCoercible::new("x".to_owned()))
);
assert_eq!(convert::<Strict>(lock, ctx, "null")?, Nullable::Null);
// Only a top-level mismatch is null: an element of the wrong type is still an error.
let err =
convert::<Nullable<Vec<jsg::NonCoercible<String>>>>(lock, ctx, "[1]").unwrap_err();
assert_eq!(
err.message,
"Incorrect type for array element 0: the provided value is not of type 'string'."
);
// Each element of a sequence of nullables is converted the same way.
assert_eq!(
convert::<Vec<Strict>>(lock, ctx, "['a', 1]")?,
vec![
Nullable::Some(jsg::NonCoercible::new("a".to_owned())),
Nullable::Null
]
);
Ok(())
});

let harness = crate::Harness::with_flags(|mut flags| flags.set_no_substitute_null(true));
harness.run_in_context(|lock, ctx| {
let err = convert::<Strict>(lock, ctx, "123").unwrap_err();
assert_eq!(err.name, jsg::ExceptionType::TypeError);
assert_eq!(err.message, "Expected a string value but got number");
Ok(())
});
}
11 changes: 8 additions & 3 deletions src/rust/jsg/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,12 @@ Prefer it to `Option<Nullable<T>>`. Both wrappers trace their contained value.
| `Nullable<T>` | `null` or `undefined` → `Null` | `TypeError` |
| `NullOrUndefined<T>` | `null` → `Null`; `undefined` → `Undefined` | `Undefined` |

As for C++ `kj::Maybe<T>`, a value that `T` does not take, such as a number for a
`Nullable<NonCoercible<String>>` or a plain object for a `Nullable<jsg::Rc<R>>`, is `Null`
for a worker without the `dont_substitute_null_on_type_error` compatibility flag (dated
before 2022-06-01), and a `TypeError` with it. Only the top-level type counts: a
`Nullable<Vec<T>>` whose element `T` does not take is an error either way.

`NullOrUndefined::default()` is `Undefined`, without requiring `T: Default`.
`as_ref()`, `as_mut()`, and `map()` preserve `Null` and `Undefined`.
Conversions to and from `Option<Nullable<T>>` preserve all three states;
Expand Down Expand Up @@ -1395,9 +1401,8 @@ behave as they do in C++ rather than as their position suggests:
- `SystemTime`, like `kj::Date`, is not a numeric type, so it is tried in pass 2, where it
also takes a number of milliseconds, before any numeric variant does.
- `Nullable<T>`, like `kj::Maybe<T>`, is tried in pass 2 whatever `T` is: it takes `null`
and `undefined`, and converts any other value as `T` would, coercion included. A value
that `T` does not take is not taken as `null`, as in C++ JSG with the
`dont_substitute_null_on_type_error` compatibility flag, which Rust JSG always follows.
and `undefined`, and converts any other value as `T` would, coercion included, including
a [type mismatch](#nullablet-and-nullorundefinedt).
- A handle takes only a value of its type, as C++ JSG's `v8::Local<T>` does:
`v8::Local<'s, v8::String>` is a string type, but never coerces, and
`v8::Local<'s, v8::BigInt>` is a numeric type that takes only a `BigInt`.
Expand Down
3 changes: 3 additions & 0 deletions src/rust/jsg/nullable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ use crate::Result;
/// passing `undefined` produces `Nullable::Null`, but omitting the argument
/// is a `TypeError`.
///
/// Also like `kj::Maybe<T>`, a value that `T` does not take is `Nullable::Null` for a
/// worker without the `dont_substitute_null_on_type_error` compatibility flag.
///
/// Use [`NullOrUndefined<T>`](crate::NullOrUndefined) for an optional nullable
/// that keeps `undefined` distinct from `null`:
///
Expand Down
41 changes: 21 additions & 20 deletions src/rust/jsg/wrappable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1338,7 +1338,8 @@ impl<T: Type> Type for Nullable<T> {
}
}

// Like C++ `kj::Maybe<T>`, Web IDL nullable conversion reads `undefined` as `null`.
// Like C++ `kj::Maybe<T>`, Web IDL nullable conversion reads `undefined` as `null`, and a value
// that `T` does not take is `null` unless the worker has `dont_substitute_null_on_type_error`.
// Nullable arguments remain required; use `NullOrUndefined` to permit omission.
impl<'s, T: FromJS<'s>> FromJS<'s> for Nullable<T> {
type ResultType = Nullable<T::ResultType>;
Expand All @@ -1353,10 +1354,10 @@ impl<'s, T: FromJS<'s>> FromJS<'s> for Nullable<T> {
lock: &mut Lock<'s>,
value: v8::Local<'s, v8::Value>,
) -> Result<Self::ResultType, Error> {
if value.is_null_or_undefined() {
Ok(Nullable::Null)
} else {
Ok(Nullable::Some(T::from_js(lock, value)?))
match Self::try_from_js(lock, value)? {
Some(nullable) => Ok(nullable),
// `T`'s own conversion gives the error.
None => Ok(Nullable::Some(T::from_js(lock, value)?)),
}
}

Expand All @@ -1365,13 +1366,19 @@ impl<'s, T: FromJS<'s>> FromJS<'s> for Nullable<T> {
value: v8::Local<'s, v8::Value>,
) -> Result<Option<Self::ResultType>, Error> {
if value.is_null_or_undefined() {
Ok(Some(Nullable::Null))
} else {
Ok(T::try_from_js(lock, value)?.map(Nullable::Some))
return Ok(Some(Nullable::Null));
}
// The flag is read only on a mismatch.
match T::try_from_js(lock, value)? {
Some(value) => Ok(Some(Nullable::Some(value))),
None if !lock.feature_flags().get_no_substitute_null() => Ok(Some(Nullable::Null)),
None => Ok(None),
}
}
}

// Like C++ `jsg::Optional<kj::Maybe<T>>`: `undefined` is `Undefined`, and any other value
// converts as for `Nullable<T>`.
impl<'s, T: FromJS<'s>> FromJS<'s> for NullOrUndefined<T> {
type ResultType = NullOrUndefined<T::ResultType>;

Expand All @@ -1389,26 +1396,20 @@ impl<'s, T: FromJS<'s>> FromJS<'s> for NullOrUndefined<T> {
lock: &mut Lock<'s>,
value: v8::Local<'s, v8::Value>,
) -> Result<Self::ResultType, Error> {
if value.is_null() {
Ok(NullOrUndefined::Null)
} else if value.is_undefined() {
Ok(NullOrUndefined::Undefined)
} else {
Ok(NullOrUndefined::Some(T::from_js(lock, value)?))
if value.is_undefined() {
return Ok(NullOrUndefined::Undefined);
}
Ok(Nullable::<T>::from_js(lock, value)?.into())
}

fn try_from_js(
lock: &mut Lock<'s>,
value: v8::Local<'s, v8::Value>,
) -> Result<Option<Self::ResultType>, Error> {
if value.is_null() {
Ok(Some(NullOrUndefined::Null))
} else if value.is_undefined() {
Ok(Some(NullOrUndefined::Undefined))
} else {
Ok(T::try_from_js(lock, value)?.map(NullOrUndefined::Some))
if value.is_undefined() {
return Ok(Some(NullOrUndefined::Undefined));
}
Ok(Nullable::<T>::try_from_js(lock, value)?.map(NullOrUndefined::from))
}
}

Expand Down
Loading