refactor: add CanGc as argument to methods in Document (#36392)

Add CanGc as arguments in methods in Document

Testing: These changes do not require tests because they are a refactor.
Addressed part of https://github.com/servo/servo/issues/34573.

Signed-off-by: Yerkebulan Tulibergenov <yerkebulan@gmail.com>
This commit is contained in:
Yerkebulan Tulibergenov 2025-04-07 16:15:23 -07:00 committed by GitHub
parent 9bdc46d66b
commit 76e0b8ec06
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 61 additions and 55 deletions

View file

@ -2964,9 +2964,14 @@ impl Document {
/// <https://html.spec.whatwg.org/multipage/#the-end> step 3. /// <https://html.spec.whatwg.org/multipage/#the-end> step 3.
/// <https://html.spec.whatwg.org/multipage/#prepare-a-script> step 22.d. /// <https://html.spec.whatwg.org/multipage/#prepare-a-script> step 22.d.
pub(crate) fn deferred_script_loaded(&self, element: &HTMLScriptElement, result: ScriptResult) { pub(crate) fn deferred_script_loaded(
&self,
element: &HTMLScriptElement,
result: ScriptResult,
can_gc: CanGc,
) {
self.deferred_scripts.loaded(element, result); self.deferred_scripts.loaded(element, result);
self.process_deferred_scripts(CanGc::note()); self.process_deferred_scripts(can_gc);
} }
/// <https://html.spec.whatwg.org/multipage/#the-end> step 3. /// <https://html.spec.whatwg.org/multipage/#the-end> step 3.
@ -4855,20 +4860,20 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
} }
// https://drafts.csswg.org/cssom/#dom-document-stylesheets // https://drafts.csswg.org/cssom/#dom-document-stylesheets
fn StyleSheets(&self) -> DomRoot<StyleSheetList> { fn StyleSheets(&self, can_gc: CanGc) -> DomRoot<StyleSheetList> {
self.stylesheet_list.or_init(|| { self.stylesheet_list.or_init(|| {
StyleSheetList::new( StyleSheetList::new(
&self.window, &self.window,
StyleSheetListOwner::Document(Dom::from_ref(self)), StyleSheetListOwner::Document(Dom::from_ref(self)),
CanGc::note(), can_gc,
) )
}) })
} }
// https://dom.spec.whatwg.org/#dom-document-implementation // https://dom.spec.whatwg.org/#dom-document-implementation
fn Implementation(&self) -> DomRoot<DOMImplementation> { fn Implementation(&self, can_gc: CanGc) -> DomRoot<DOMImplementation> {
self.implementation self.implementation
.or_init(|| DOMImplementation::new(self, CanGc::note())) .or_init(|| DOMImplementation::new(self, can_gc))
} }
// https://dom.spec.whatwg.org/#dom-document-url // https://dom.spec.whatwg.org/#dom-document-url
@ -4996,7 +5001,11 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
} }
// https://dom.spec.whatwg.org/#dom-document-getelementsbytagname // https://dom.spec.whatwg.org/#dom-document-getelementsbytagname
fn GetElementsByTagName(&self, qualified_name: DOMString) -> DomRoot<HTMLCollection> { fn GetElementsByTagName(
&self,
qualified_name: DOMString,
can_gc: CanGc,
) -> DomRoot<HTMLCollection> {
let qualified_name = LocalName::from(&*qualified_name); let qualified_name = LocalName::from(&*qualified_name);
if let Some(entry) = self.tag_map.borrow_mut().get(&qualified_name) { if let Some(entry) = self.tag_map.borrow_mut().get(&qualified_name) {
return DomRoot::from_ref(entry); return DomRoot::from_ref(entry);
@ -5005,7 +5014,7 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
&self.window, &self.window,
self.upcast(), self.upcast(),
qualified_name.clone(), qualified_name.clone(),
CanGc::note(), can_gc,
); );
self.tag_map self.tag_map
.borrow_mut() .borrow_mut()
@ -5018,6 +5027,7 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
&self, &self,
maybe_ns: Option<DOMString>, maybe_ns: Option<DOMString>,
tag_name: DOMString, tag_name: DOMString,
can_gc: CanGc,
) -> DomRoot<HTMLCollection> { ) -> DomRoot<HTMLCollection> {
let ns = namespace_from_domstring(maybe_ns); let ns = namespace_from_domstring(maybe_ns);
let local = LocalName::from(tag_name); let local = LocalName::from(tag_name);
@ -5025,12 +5035,8 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
if let Some(collection) = self.tagns_map.borrow().get(&qname) { if let Some(collection) = self.tagns_map.borrow().get(&qname) {
return DomRoot::from_ref(collection); return DomRoot::from_ref(collection);
} }
let result = HTMLCollection::by_qual_tag_name( let result =
&self.window, HTMLCollection::by_qual_tag_name(&self.window, self.upcast(), qname.clone(), can_gc);
self.upcast(),
qname.clone(),
CanGc::note(),
);
self.tagns_map self.tagns_map
.borrow_mut() .borrow_mut()
.insert(qname, Dom::from_ref(&*result)); .insert(qname, Dom::from_ref(&*result));
@ -5038,7 +5044,7 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
} }
// https://dom.spec.whatwg.org/#dom-document-getelementsbyclassname // https://dom.spec.whatwg.org/#dom-document-getelementsbyclassname
fn GetElementsByClassName(&self, classes: DOMString) -> DomRoot<HTMLCollection> { fn GetElementsByClassName(&self, classes: DOMString, can_gc: CanGc) -> DomRoot<HTMLCollection> {
let class_atoms: Vec<Atom> = split_html_space_chars(&classes).map(Atom::from).collect(); let class_atoms: Vec<Atom> = split_html_space_chars(&classes).map(Atom::from).collect();
if let Some(collection) = self.classes_map.borrow().get(&class_atoms) { if let Some(collection) = self.classes_map.borrow().get(&class_atoms) {
return DomRoot::from_ref(collection); return DomRoot::from_ref(collection);
@ -5047,7 +5053,7 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
&self.window, &self.window,
self.upcast(), self.upcast(),
class_atoms.clone(), class_atoms.clone(),
CanGc::note(), can_gc,
); );
self.classes_map self.classes_map
.borrow_mut() .borrow_mut()
@ -5257,7 +5263,7 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
} }
// https://dom.spec.whatwg.org/#dom-document-adoptnode // https://dom.spec.whatwg.org/#dom-document-adoptnode
fn AdoptNode(&self, node: &Node) -> Fallible<DomRoot<Node>> { fn AdoptNode(&self, node: &Node, can_gc: CanGc) -> Fallible<DomRoot<Node>> {
// Step 1. // Step 1.
if node.is::<Document>() { if node.is::<Document>() {
return Err(Error::NotSupported); return Err(Error::NotSupported);
@ -5269,7 +5275,7 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
} }
// Step 3. // Step 3.
Node::adopt(node, self, CanGc::note()); Node::adopt(node, self, can_gc);
// Step 4. // Step 4.
Ok(DomRoot::from_ref(node)) Ok(DomRoot::from_ref(node))
@ -5358,8 +5364,9 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
root: &Node, root: &Node,
what_to_show: u32, what_to_show: u32,
filter: Option<Rc<NodeFilter>>, filter: Option<Rc<NodeFilter>>,
can_gc: CanGc,
) -> DomRoot<NodeIterator> { ) -> DomRoot<NodeIterator> {
NodeIterator::new(self, root, what_to_show, filter, CanGc::note()) NodeIterator::new(self, root, what_to_show, filter, can_gc)
} }
// https://dom.spec.whatwg.org/#dom-document-createtreewalker // https://dom.spec.whatwg.org/#dom-document-createtreewalker
@ -5476,7 +5483,7 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
} }
// https://html.spec.whatwg.org/multipage/#dom-document-body // https://html.spec.whatwg.org/multipage/#dom-document-body
fn SetBody(&self, new_body: Option<&HTMLElement>) -> ErrorResult { fn SetBody(&self, new_body: Option<&HTMLElement>, can_gc: CanGc) -> ErrorResult {
// Step 1. // Step 1.
let new_body = match new_body { let new_body = match new_body {
Some(new_body) => new_body, Some(new_body) => new_body,
@ -5502,7 +5509,7 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
// Step 3. // Step 3.
(Some(ref root), Some(child)) => { (Some(ref root), Some(child)) => {
let root = root.upcast::<Node>(); let root = root.upcast::<Node>();
root.ReplaceChild(new_body.upcast(), child.upcast(), CanGc::note()) root.ReplaceChild(new_body.upcast(), child.upcast(), can_gc)
.unwrap(); .unwrap();
}, },
@ -5512,48 +5519,48 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
// Step 5. // Step 5.
(Some(ref root), &None) => { (Some(ref root), &None) => {
let root = root.upcast::<Node>(); let root = root.upcast::<Node>();
root.AppendChild(new_body.upcast(), CanGc::note()).unwrap(); root.AppendChild(new_body.upcast(), can_gc).unwrap();
}, },
} }
Ok(()) Ok(())
} }
// https://html.spec.whatwg.org/multipage/#dom-document-getelementsbyname // https://html.spec.whatwg.org/multipage/#dom-document-getelementsbyname
fn GetElementsByName(&self, name: DOMString) -> DomRoot<NodeList> { fn GetElementsByName(&self, name: DOMString, can_gc: CanGc) -> DomRoot<NodeList> {
NodeList::new_elements_by_name_list(self.window(), self, name, CanGc::note()) NodeList::new_elements_by_name_list(self.window(), self, name, can_gc)
} }
// https://html.spec.whatwg.org/multipage/#dom-document-images // https://html.spec.whatwg.org/multipage/#dom-document-images
fn Images(&self) -> DomRoot<HTMLCollection> { fn Images(&self, can_gc: CanGc) -> DomRoot<HTMLCollection> {
self.images.or_init(|| { self.images.or_init(|| {
HTMLCollection::new_with_filter_fn( HTMLCollection::new_with_filter_fn(
&self.window, &self.window,
self.upcast(), self.upcast(),
|element, _| element.is::<HTMLImageElement>(), |element, _| element.is::<HTMLImageElement>(),
CanGc::note(), can_gc,
) )
}) })
} }
// https://html.spec.whatwg.org/multipage/#dom-document-embeds // https://html.spec.whatwg.org/multipage/#dom-document-embeds
fn Embeds(&self) -> DomRoot<HTMLCollection> { fn Embeds(&self, can_gc: CanGc) -> DomRoot<HTMLCollection> {
self.embeds.or_init(|| { self.embeds.or_init(|| {
HTMLCollection::new_with_filter_fn( HTMLCollection::new_with_filter_fn(
&self.window, &self.window,
self.upcast(), self.upcast(),
|element, _| element.is::<HTMLEmbedElement>(), |element, _| element.is::<HTMLEmbedElement>(),
CanGc::note(), can_gc,
) )
}) })
} }
// https://html.spec.whatwg.org/multipage/#dom-document-plugins // https://html.spec.whatwg.org/multipage/#dom-document-plugins
fn Plugins(&self) -> DomRoot<HTMLCollection> { fn Plugins(&self, can_gc: CanGc) -> DomRoot<HTMLCollection> {
self.Embeds() self.Embeds(can_gc)
} }
// https://html.spec.whatwg.org/multipage/#dom-document-links // https://html.spec.whatwg.org/multipage/#dom-document-links
fn Links(&self) -> DomRoot<HTMLCollection> { fn Links(&self, can_gc: CanGc) -> DomRoot<HTMLCollection> {
self.links.or_init(|| { self.links.or_init(|| {
HTMLCollection::new_with_filter_fn( HTMLCollection::new_with_filter_fn(
&self.window, &self.window,
@ -5562,37 +5569,37 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
(element.is::<HTMLAnchorElement>() || element.is::<HTMLAreaElement>()) && (element.is::<HTMLAnchorElement>() || element.is::<HTMLAreaElement>()) &&
element.has_attribute(&local_name!("href")) element.has_attribute(&local_name!("href"))
}, },
CanGc::note(), can_gc,
) )
}) })
} }
// https://html.spec.whatwg.org/multipage/#dom-document-forms // https://html.spec.whatwg.org/multipage/#dom-document-forms
fn Forms(&self) -> DomRoot<HTMLCollection> { fn Forms(&self, can_gc: CanGc) -> DomRoot<HTMLCollection> {
self.forms.or_init(|| { self.forms.or_init(|| {
HTMLCollection::new_with_filter_fn( HTMLCollection::new_with_filter_fn(
&self.window, &self.window,
self.upcast(), self.upcast(),
|element, _| element.is::<HTMLFormElement>(), |element, _| element.is::<HTMLFormElement>(),
CanGc::note(), can_gc,
) )
}) })
} }
// https://html.spec.whatwg.org/multipage/#dom-document-scripts // https://html.spec.whatwg.org/multipage/#dom-document-scripts
fn Scripts(&self) -> DomRoot<HTMLCollection> { fn Scripts(&self, can_gc: CanGc) -> DomRoot<HTMLCollection> {
self.scripts.or_init(|| { self.scripts.or_init(|| {
HTMLCollection::new_with_filter_fn( HTMLCollection::new_with_filter_fn(
&self.window, &self.window,
self.upcast(), self.upcast(),
|element, _| element.is::<HTMLScriptElement>(), |element, _| element.is::<HTMLScriptElement>(),
CanGc::note(), can_gc,
) )
}) })
} }
// https://html.spec.whatwg.org/multipage/#dom-document-anchors // https://html.spec.whatwg.org/multipage/#dom-document-anchors
fn Anchors(&self) -> DomRoot<HTMLCollection> { fn Anchors(&self, can_gc: CanGc) -> DomRoot<HTMLCollection> {
self.anchors.or_init(|| { self.anchors.or_init(|| {
HTMLCollection::new_with_filter_fn( HTMLCollection::new_with_filter_fn(
&self.window, &self.window,
@ -5600,15 +5607,15 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
|element, _| { |element, _| {
element.is::<HTMLAnchorElement>() && element.has_attribute(&local_name!("href")) element.is::<HTMLAnchorElement>() && element.has_attribute(&local_name!("href"))
}, },
CanGc::note(), can_gc,
) )
}) })
} }
// https://html.spec.whatwg.org/multipage/#dom-document-applets // https://html.spec.whatwg.org/multipage/#dom-document-applets
fn Applets(&self) -> DomRoot<HTMLCollection> { fn Applets(&self, can_gc: CanGc) -> DomRoot<HTMLCollection> {
self.applets self.applets
.or_init(|| HTMLCollection::always_empty(&self.window, self.upcast(), CanGc::note())) .or_init(|| HTMLCollection::always_empty(&self.window, self.upcast(), can_gc))
} }
// https://html.spec.whatwg.org/multipage/#dom-document-location // https://html.spec.whatwg.org/multipage/#dom-document-location
@ -5621,8 +5628,8 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
} }
// https://dom.spec.whatwg.org/#dom-parentnode-children // https://dom.spec.whatwg.org/#dom-parentnode-children
fn Children(&self) -> DomRoot<HTMLCollection> { fn Children(&self, can_gc: CanGc) -> DomRoot<HTMLCollection> {
HTMLCollection::children(&self.window, self.upcast(), CanGc::note()) HTMLCollection::children(&self.window, self.upcast(), can_gc)
} }
// https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild // https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild
@ -6192,12 +6199,9 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
} }
// https://w3c.github.io/selection-api/#dom-document-getselection // https://w3c.github.io/selection-api/#dom-document-getselection
fn GetSelection(&self) -> Option<DomRoot<Selection>> { fn GetSelection(&self, can_gc: CanGc) -> Option<DomRoot<Selection>> {
if self.has_browsing_context { if self.has_browsing_context {
Some( Some(self.selection.or_init(|| Selection::new(self, can_gc)))
self.selection
.or_init(|| Selection::new(self, CanGc::note())),
)
} else { } else {
None None
} }

View file

@ -360,7 +360,7 @@ fn finish_fetching_a_classic_script(
}, },
ExternalScriptKind::Deferred => { ExternalScriptKind::Deferred => {
document = elem.parser_document.as_rooted(); document = elem.parser_document.as_rooted();
document.deferred_script_loaded(elem, load); document.deferred_script_loaded(elem, load, can_gc);
}, },
ExternalScriptKind::ParsingBlocking => { ExternalScriptKind::ParsingBlocking => {
document = elem.parser_document.as_rooted(); document = elem.parser_document.as_rooted();

View file

@ -1523,7 +1523,9 @@ impl WindowMethods<crate::DomTypeHolder> for Window {
// https://w3c.github.io/selection-api/#dom-window-getselection // https://w3c.github.io/selection-api/#dom-window-getselection
fn GetSelection(&self) -> Option<DomRoot<Selection>> { fn GetSelection(&self) -> Option<DomRoot<Selection>> {
self.document.get().and_then(|d| d.GetSelection()) self.document
.get()
.and_then(|d| d.GetSelection(CanGc::note()))
} }
// https://dom.spec.whatwg.org/#dom-window-event // https://dom.spec.whatwg.org/#dom-window-event

View file

@ -992,7 +992,7 @@ impl ModuleOwner {
.has_attribute(&local_name!("async")); .has_attribute(&local_name!("async"));
if !asynch && (*script.root()).get_parser_inserted() { if !asynch && (*script.root()).get_parser_inserted() {
document.deferred_script_loaded(&script.root(), load); document.deferred_script_loaded(&script.root(), load, can_gc);
} else if !asynch && !(*script.root()).get_non_blocking() { } else if !asynch && !(*script.root()).get_non_blocking() {
document.asap_in_order_script_loaded(&script.root(), load, can_gc); document.asap_in_order_script_loaded(&script.root(), load, can_gc);
} else { } else {

View file

@ -553,7 +553,7 @@ pub(crate) fn handle_find_element_tag_name(
pipeline: PipelineId, pipeline: PipelineId,
selector: String, selector: String,
reply: IpcSender<Result<Option<String>, ErrorStatus>>, reply: IpcSender<Result<Option<String>, ErrorStatus>>,
_can_gc: CanGc, can_gc: CanGc,
) { ) {
reply reply
.send( .send(
@ -562,7 +562,7 @@ pub(crate) fn handle_find_element_tag_name(
.ok_or(ErrorStatus::UnknownError) .ok_or(ErrorStatus::UnknownError)
.map(|document| { .map(|document| {
document document
.GetElementsByTagName(DOMString::from(selector)) .GetElementsByTagName(DOMString::from(selector), can_gc)
.elements_iter() .elements_iter()
.next() .next()
}) })
@ -621,14 +621,14 @@ pub(crate) fn handle_find_elements_tag_name(
pipeline: PipelineId, pipeline: PipelineId,
selector: String, selector: String,
reply: IpcSender<Result<Vec<String>, ErrorStatus>>, reply: IpcSender<Result<Vec<String>, ErrorStatus>>,
_can_gc: CanGc, can_gc: CanGc,
) { ) {
reply reply
.send( .send(
documents documents
.find_document(pipeline) .find_document(pipeline)
.ok_or(ErrorStatus::UnknownError) .ok_or(ErrorStatus::UnknownError)
.map(|document| document.GetElementsByTagName(DOMString::from(selector))) .map(|document| document.GetElementsByTagName(DOMString::from(selector), can_gc))
.map(|nodes| { .map(|nodes| {
nodes nodes
.elements_iter() .elements_iter()

View file

@ -158,7 +158,7 @@ DOMInterfaces = {
'Document': { 'Document': {
'additionalTraits': ["crate::interfaces::DocumentHelpers"], 'additionalTraits': ["crate::interfaces::DocumentHelpers"],
'canGc': ['Close', 'CreateElement', 'CreateElementNS', 'ImportNode', 'SetTitle', 'Write', 'Writeln', 'CreateEvent', 'CreateRange', 'Open', 'Open_', 'CreateComment', 'CreateAttribute', 'CreateAttributeNS', 'CreateDocumentFragment', 'CreateTextNode', 'CreateCDATASection', 'CreateProcessingInstruction', 'Prepend', 'Append', 'ReplaceChildren', 'SetBgColor', 'SetFgColor', 'Fonts', 'ElementFromPoint', 'ElementsFromPoint', 'ExitFullscreen', 'CreateExpression', 'CreateNSResolver', 'Evaluate'], 'canGc': ['Close', 'CreateElement', 'CreateElementNS', 'ImportNode', 'SetTitle', 'Write', 'Writeln', 'CreateEvent', 'CreateRange', 'Open', 'Open_', 'CreateComment', 'CreateAttribute', 'CreateAttributeNS', 'CreateDocumentFragment', 'CreateTextNode', 'CreateCDATASection', 'CreateProcessingInstruction', 'Prepend', 'Append', 'ReplaceChildren', 'SetBgColor', 'SetFgColor', 'Fonts', 'ElementFromPoint', 'ElementsFromPoint', 'ExitFullscreen', 'CreateExpression', 'CreateNSResolver', 'Evaluate', 'StyleSheets', 'Implementation', 'GetElementsByTagName', 'GetElementsByTagNameNS', 'GetElementsByClassName', 'AdoptNode', 'CreateNodeIterator', 'SetBody', 'GetElementsByName', 'Images', 'Embeds', 'Plugins', 'Links', 'Forms', 'Scripts', 'Anchors', 'Applets', 'Children', 'GetSelection'],
}, },
'DocumentFragment': { 'DocumentFragment': {