script: Reduce usage of Trusted in Node::insert. (#37762)

These changes introduce a new kind of task that uses a variation of the
`task!` syntax. Existing `task!` usages create task structs that have a
`Send` bound, which requires the use of `Trusted<T>` to reference a DOM
object T inside of the task closure. The new syntax replaces the `Send`
bound with a `JSTraceable` bound, which requires explicit capture
clauses with types. This looks like:
```rust
task!(ScriptPrepare: {script: DomRoot<HTMLScriptElement>} |script| {
    script.prepare(CanGc::note());
}),
```

The capture clauses must list every value that will be referenced from
the closure's environment—these values are moved into fields in the
generated task structure, which allows them to be traced by the GC as
part of a generated JSTraceable implementation. Since the closure itself
is not a `move` closure, any attempts to reference values not explicitly
captured will generate a borrow checker error since the closure requires
the `'static` lifetime.

Testing: Existing WPT tests exercise these code paths. I also attempted
to write incorrect tasks that capture references or use values not
explicitly captured, and the compiler correctly errors out.
Fixes: part of #35517

Signed-off-by: Josh Matthews <josh@joshmatthews.net>
This commit is contained in:
Josh Matthews 2025-07-14 21:11:12 -04:00 committed by GitHub
parent f5b0165e54
commit 9e2ee0029a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 74 additions and 27 deletions

View file

@ -212,7 +212,7 @@ use crate::realms::{AlreadyInRealm, InRealm, enter_realm};
use crate::script_runtime::{CanGc, ScriptThreadEventCategory};
use crate::script_thread::{ScriptThread, with_script_thread};
use crate::stylesheet_set::StylesheetSetRef;
use crate::task::TaskBox;
use crate::task::NonSendTaskBox;
use crate::task_source::TaskSourceName;
use crate::timers::OneshotTimerCallback;
@ -477,7 +477,7 @@ pub(crate) struct Document {
script_and_layout_blockers: Cell<u32>,
/// List of tasks to execute as soon as last script/layout blocker is removed.
#[ignore_malloc_size_of = "Measuring trait objects is hard"]
delayed_tasks: DomRefCell<Vec<Box<dyn TaskBox>>>,
delayed_tasks: DomRefCell<Vec<Box<dyn NonSendTaskBox>>>,
/// <https://html.spec.whatwg.org/multipage/#completely-loaded>
completely_loaded: Cell<bool>,
/// Set of shadow roots connected to the document tree.
@ -4338,7 +4338,7 @@ impl Document {
}
/// Enqueue a task to run as soon as any JS and layout blockers are removed.
pub(crate) fn add_delayed_task<T: 'static + TaskBox>(&self, task: T) {
pub(crate) fn add_delayed_task<T: 'static + NonSendTaskBox>(&self, task: T) {
self.delayed_tasks.borrow_mut().push(Box::new(task));
}