Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

feat(webidl): add clamped long long conversion and derive support

ldm0e41e51102e69
diff --git a/moli-webidl-derive/src/converter.rs b/moli-webidl-derive/src/converter.rs
index 20ba3a29d..93e1dc52b 100644
--- a/moli-webidl-derive/src/converter.rs
+++ b/moli-webidl-derive/src/converter.rs
@@ -17,6 +17,7 @@ pub(crate) enum ConverterKind {
Octet,
Long,
LongLong,
+ ClampedLongLong,
EnforceRangeLong,
Short,
UnsignedShort,
@@ -56,6 +57,7 @@ impl ConverterKind {
"octet" => Ok(Self::Octet),
"long" => Ok(Self::Long),
"long_long" => Ok(Self::LongLong),
+ "clamped_long_long" => Ok(Self::ClampedLongLong),
"enforce_range_long" => Ok(Self::EnforceRangeLong),
"short" => Ok(Self::Short),
"unsigned_short" => Ok(Self::UnsignedShort),
@@ -93,6 +95,7 @@ impl ConverterKind {
Self::Octet => quote!(::moli_webidl::Octet),
Self::Long => quote!(::moli_webidl::Long),
Self::LongLong => quote!(::moli_webidl::LongLong),
+ Self::ClampedLongLong => quote!(::moli_webidl::ClampedLongLong),
Self::EnforceRangeLong => quote!(::moli_webidl::EnforceRangeLong),
Self::Short => quote!(::moli_webidl::Short),
Self::UnsignedShort => quote!(::moli_webidl::UnsignedShort),
@@ -140,6 +143,7 @@ impl ConverterKind {
Self::Octet => quote!(::moli_webidl::Octet(#expr)),
Self::Long => quote!(::moli_webidl::Long(#expr)),
Self::LongLong => quote!(::moli_webidl::LongLong(#expr)),
+ Self::ClampedLongLong => quote!(::moli_webidl::ClampedLongLong(#expr)),
Self::EnforceRangeLong => quote!(::moli_webidl::EnforceRangeLong(#expr)),
Self::Short => quote!(::moli_webidl::Short(#expr)),
Self::UnsignedShort => quote!(::moli_webidl::UnsignedShort(#expr)),
@@ -182,6 +186,7 @@ impl ConverterKind {
| Self::Octet
| Self::Long
| Self::LongLong
+ | Self::ClampedLongLong
| Self::EnforceRangeLong
| Self::Short
| Self::UnsignedShort
diff --git a/moli-webidl/src/convert.rs b/moli-webidl/src/convert.rs
index e36f93736..d27822de1 100644
--- a/moli-webidl/src/convert.rs
+++ b/moli-webidl/src/convert.rs
@@ -379,6 +379,25 @@ impl<'s> WebIdlConverter<'s> for crate::LongLong {
}
}
+impl<'s> WebIdlConverter<'s> for crate::ClampedLongLong {
+ type Options = ();
+
+ fn convert(
+ scope: &mut v8::PinScope<'s, '_>,
+ value: v8::Local<'s, v8::Value>,
+ context: Context,
+ _options: &Self::Options,
+ ) -> Result<Self, WebIdlError> {
+ let value = number_value(scope, value, context, "[Clamp] long long")?;
+ if value.is_nan() {
+ return Ok(Self(0));
+ }
+ // ConvertToInt restricts annotated 64-bit integers to exact Numbers.
+ let value = value.clamp(-9_007_199_254_740_991.0, 9_007_199_254_740_991.0);
+ Ok(Self(value.round_ties_even() as i64))
+ }
+}
+
impl<'s> WebIdlConverter<'s> for EnforceRangeLongLong {
type Options = ();
diff --git a/moli-webidl/src/lib.rs b/moli-webidl/src/lib.rs
index 01ed24805..ee5ecc477 100644
--- a/moli-webidl/src/lib.rs
+++ b/moli-webidl/src/lib.rs
@@ -121,11 +121,12 @@ pub mod __private {
}
pub use traits::{ParseOutcome, WebIdlArguments, WebIdlConverter, WebIdlDictionary, WebIdlEnum};
pub use types::{
- Boolean, BufferSource, ByteString, ClampedUnsignedShort, Dictionary, DomString, DomString16,
- Double, EnforceRangeLong, EnforceRangeUnsignedLong, EnforceRangeUnsignedLongLong, EnumValue,
- EventListenerOptions, InterfaceObject, InterfaceOptions, Long, LongLong, Octet, Record,
- Sequence, Short, StringOptions, UnrestrictedDouble, UnrestrictedFloat, UnsignedLong,
- UnsignedLongLong, UnsignedShort, UsvString,
+ Boolean, BufferSource, ByteString, ClampedLongLong, ClampedUnsignedShort, Dictionary,
+ DomString, DomString16, Double, EnforceRangeLong, EnforceRangeUnsignedLong,
+ EnforceRangeUnsignedLongLong, EnumValue, EventListenerOptions, InterfaceObject,
+ InterfaceOptions, Long, LongLong, Octet, Record, Sequence, Short, StringOptions,
+ UnrestrictedDouble, UnrestrictedFloat, UnsignedLong, UnsignedLongLong, UnsignedShort,
+ UsvString,
};
/// Restricted WebIDL float represented as a finite binary32 value.
diff --git a/moli-webidl/src/snapshot/value.rs b/moli-webidl/src/snapshot/value.rs
index 8065bf4c4..eead5b386 100644
--- a/moli-webidl/src/snapshot/value.rs
+++ b/moli-webidl/src/snapshot/value.rs
@@ -77,6 +77,7 @@ wrapper_snapshot!(
crate::UnsignedShort,
crate::ClampedUnsignedShort,
crate::LongLong,
+ crate::ClampedLongLong,
crate::UnsignedLongLong,
crate::EnforceRangeLongLong,
crate::DomString,
diff --git a/moli-webidl/src/types.rs b/moli-webidl/src/types.rs
index 7ee194f97..2fcebeb3d 100644
--- a/moli-webidl/src/types.rs
+++ b/moli-webidl/src/types.rs
@@ -266,6 +266,16 @@ impl From<UnsignedLong> for u32 {
}
}
+/// WebIDL `[Clamp] long long`, bounded by JavaScript's exact integer range.
+#[derive(Debug, Clone, Copy, Eq, PartialEq)]
+pub struct ClampedLongLong(pub i64);
+
+impl From<ClampedLongLong> for i64 {
+ fn from(value: ClampedLongLong) -> Self {
+ value.0
+ }
+}
+
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct EnforceRangeUnsignedLong(pub u32);
diff --git a/moli-webidl/tests/clamped_long_long.rs b/moli-webidl/tests/clamped_long_long.rs
new file mode 100644
index 000000000..7f10baa8b
--- /dev/null
+++ b/moli-webidl/tests/clamped_long_long.rs
@@ -0,0 +1,128 @@
+use moli_webapi_declare::WebApiValue;
+use moli_webidl::{Context, WebIdlArgs, WebIdlDictionary};
+
+#[derive(WebIdlArgs)]
+#[webidl(prefix = "Test.clamp")]
+struct Args {
+ #[webidl(required, converter = "clamped_long_long")]
+ value: i64,
+}
+
+#[derive(WebIdlDictionary)]
+#[webidl(prefix = "Test.ClampInit")]
+struct Init {
+ #[webidl(sequence, converter = "clamped_long_long", default = Vec::new())]
+ codes: Vec<i64>,
+ #[webidl(converter = "clamped_long_long", default = -2)]
+ fallback: i64,
+ #[webidl(converter = "clamped_long_long", nullable)]
+ value: Option<i64>,
+}
+
+fn argument<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'s>,
+) {
+ if let Some(parsed) = moli_webidl::parse_args::<Args>(scope, &args) {
+ rv.set(
+ moli_webidl::ClampedLongLong(parsed.value)
+ .to_v8_value(scope)
+ .expect("clamped numeric output"),
+ );
+ }
+}
+
+fn dictionary<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'s>,
+) {
+ let parsed = match moli_webidl::convert::<moli_webidl::Dictionary<Init>>(
+ scope,
+ args.get(0),
+ Context::argument("Test.dictionary", 1),
+ ) {
+ Ok(parsed) => parsed.0,
+ Err(error) => {
+ moli_webidl::throw_error(scope, &error);
+ return;
+ }
+ };
+ let codes: Vec<_> = parsed
+ .codes
+ .into_iter()
+ .map(|value| v8::Number::new(scope, value as f64).into())
+ .collect();
+ let codes = v8::Array::new_with_elements(scope, &codes);
+ let fallback = v8::Number::new(scope, parsed.fallback as f64);
+ let value = parsed
+ .value
+ .map(|value| v8::Number::new(scope, value as f64).into())
+ .unwrap_or_else(|| v8::null(scope).into());
+ rv.set(v8::Array::new_with_elements(scope, &[codes.into(), fallback.into(), value]).into());
+}
+
+#[test]
+fn clamped_long_long_preserves_numeric_conversion_and_derive_policies() {
+ assert!(matches!(
+ <moli_webidl::ClampedLongLong as moli_webidl::WebIdlSnapshotValue>::SNAPSHOT_KIND,
+ moli_webidl::SnapshotKind::Scalar
+ ));
+ moli_v8_test_util::ensure_v8();
+ let mut isolate = v8::Isolate::new(v8::CreateParams::default());
+ let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate));
+ let scope = &mut scope.init();
+ let callee = v8::Context::new(scope, Default::default());
+ let values = {
+ let scope = &mut v8::ContextScope::new(scope, callee);
+ let convert = v8::Function::new(scope, argument).unwrap();
+ let dictionary = v8::Function::new(scope, dictionary).unwrap();
+ let key = v8::String::new(scope, "TypeError").unwrap();
+ let error = callee.global(scope).get(scope, key.into()).unwrap();
+ [
+ ("clamp", convert.into()),
+ ("dictionary", dictionary.into()),
+ ("CalleeTypeError", error),
+ ]
+ };
+ let caller = v8::Context::new(scope, Default::default());
+ let scope = &mut v8::ContextScope::new(scope, caller);
+ for (name, value) in values {
+ let key = v8::String::new(scope, name).unwrap();
+ assert_eq!(
+ caller.global(scope).set(scope, key.into(), value),
+ Some(true)
+ );
+ }
+ let source = v8::String::new(scope, r#"
+ (() => {
+ const assert=(ok, message)=>{if(!ok)throw Error(message);};
+ const max = Number.MAX_SAFE_INTEGER;
+ const matrix=[[undefined,0],[null,0],[NaN,0],[Infinity,max],[-Infinity,-max],[-0,0],[0,0],
+ [0.5,0],[-0.5,0],[1.5,2],[-1.5,-2],[2.5,2],[-2.5,-2],[3.5,4],[-3.5,-4],
+ [max,max],[-max,-max],[2**53,max],[-(2**53),-max],[2**63,max],[-(2**63),-max],
+ [Number.MAX_VALUE,max],[-Number.MAX_VALUE,-max],['3.5',4],['x',0],[true,1]];
+ for(const [value,expected]of matrix)assert(Object.is(clamp(value),expected),'clamp '+value);
+ for(const value of [1n,Symbol()]){let error;try{clamp(value);}catch(caught){error=caught;}
+ assert(error instanceof CalleeTypeError&&!(error instanceof TypeError),'callee realm');}
+ let calls=0;
+ assert(clamp({[Symbol.toPrimitive](hint){calls++;assert(hint==='number','hint');return 2.5;}})===2&&calls===1,'one conversion');
+ const sentinel={};let error;try{clamp({valueOf(){throw sentinel;}});}catch(caught){error=caught;}assert(error===sentinel,'exception');
+ try{clamp();}catch(caught){error=caught;}assert(error instanceof CalleeTypeError,'arity');
+ assert(JSON.stringify(dictionary({}))==='[[],-2,null]','defaults');
+ assert(JSON.stringify(dictionary({codes:new Set([1.5,-1.5,Infinity,-Infinity]),fallback:-3.5,value:null}))===JSON.stringify([[2,-2,max,-max],-4,null]),'sequence and nullable');
+ assert(JSON.stringify(dictionary({fallback:null,value:NaN}))==='[[],0,0]','null default distinction');
+ const reads=[];const init=new Proxy({}, {get(target,name){reads.push(name);return name==='codes'?[0.5,2.5]:undefined;}});
+ assert(JSON.stringify(dictionary(init))==='[[0,2],-2,null]'&&JSON.stringify(reads)==='["codes","fallback","value"]','dictionary order');
+ return true;
+ })()
+ "#).unwrap();
+ assert!(
+ v8::Script::compile(scope, source, None)
+ .unwrap()
+ .run(scope)
+ .expect("[Clamp] long long conversion matrix")
+ .is_true()
+ );
+}