script_bindings/
settings_stack.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::marker::PhantomData;
6use std::thread;
7
8use js::jsapi::{HideScriptedCaller, UnhideScriptedCaller};
9use js::rust::Runtime;
10
11use crate::DomTypes;
12use crate::interfaces::{DomHelpers, GlobalScopeHelpers};
13use crate::root::{Dom, DomRoot};
14use crate::script_runtime::CanGc;
15
16#[derive(Debug, Eq, JSTraceable, PartialEq)]
17pub enum StackEntryKind {
18    Incumbent,
19    Entry,
20}
21
22#[cfg_attr(crown, allow(crown::unrooted_must_root))]
23#[derive(JSTraceable)]
24pub struct StackEntry<D: DomTypes> {
25    pub global: Dom<D::GlobalScope>,
26    pub kind: StackEntryKind,
27}
28
29/// RAII struct that pushes and pops entries from the script settings stack.
30pub struct GenericAutoEntryScript<D: DomTypes> {
31    global: DomRoot<D::GlobalScope>,
32    #[cfg(feature = "tracing")]
33    #[expect(dead_code)]
34    span: tracing::span::EnteredSpan,
35}
36
37impl<D: DomTypes> GenericAutoEntryScript<D> {
38    /// <https://html.spec.whatwg.org/multipage/#prepare-to-run-script>
39    pub fn new(global: &D::GlobalScope) -> Self {
40        let settings_stack = <D as DomHelpers<D>>::settings_stack();
41        settings_stack.with(|stack| {
42            trace!("Prepare to run script with {:p}", global);
43            let mut stack = stack.borrow_mut();
44            stack.push(StackEntry {
45                global: Dom::from_ref(global),
46                kind: StackEntryKind::Entry,
47            });
48            Self {
49                global: DomRoot::from_ref(global),
50                #[cfg(feature = "tracing")]
51                span: tracing::info_span!(
52                    "ScriptEvaluate",
53                    servo_profiling = true,
54                    url = global.get_url().to_string(),
55                )
56                .entered(),
57            }
58        })
59    }
60}
61
62impl<D: DomTypes> Drop for GenericAutoEntryScript<D> {
63    /// <https://html.spec.whatwg.org/multipage/#clean-up-after-running-script>
64    fn drop(&mut self) {
65        let settings_stack = <D as DomHelpers<D>>::settings_stack();
66        let mut stack_is_empty = false;
67        settings_stack.with(|stack| {
68            let mut stack = stack.borrow_mut();
69            let entry = stack.pop().unwrap();
70            assert_eq!(
71                &*entry.global as *const D::GlobalScope, &*self.global as *const D::GlobalScope,
72                "Dropped AutoEntryScript out of order."
73            );
74            assert_eq!(entry.kind, StackEntryKind::Entry);
75            trace!("Clean up after running script with {:p}", &*entry.global);
76            stack_is_empty = stack.is_empty();
77        });
78
79        // Step 5
80        if !thread::panicking() && stack_is_empty {
81            self.global.perform_a_microtask_checkpoint(CanGc::note());
82        }
83    }
84}
85
86/// RAII struct that pushes and pops entries from the script settings stack.
87pub struct GenericAutoIncumbentScript<D: DomTypes> {
88    global: usize,
89    _marker: PhantomData<D>,
90}
91
92impl<D: DomTypes> GenericAutoIncumbentScript<D> {
93    /// <https://html.spec.whatwg.org/multipage/#prepare-to-run-a-callback>
94    pub fn new(global: &D::GlobalScope) -> Self {
95        // Step 2-3.
96        unsafe {
97            let cx =
98                Runtime::get().expect("Creating a new incumbent script after runtime shutdown");
99            HideScriptedCaller(cx.as_ptr());
100        }
101        let settings_stack = <D as DomHelpers<D>>::settings_stack();
102        settings_stack.with(|stack| {
103            trace!("Prepare to run a callback with {:p}", global);
104            // Step 1.
105            let mut stack = stack.borrow_mut();
106            stack.push(StackEntry {
107                global: Dom::from_ref(global),
108                kind: StackEntryKind::Incumbent,
109            });
110            Self {
111                global: global as *const _ as usize,
112                _marker: PhantomData,
113            }
114        })
115    }
116}
117
118impl<D: DomTypes> Drop for GenericAutoIncumbentScript<D> {
119    /// <https://html.spec.whatwg.org/multipage/#clean-up-after-running-a-callback>
120    fn drop(&mut self) {
121        let settings_stack = <D as DomHelpers<D>>::settings_stack();
122        settings_stack.with(|stack| {
123            // Step 4.
124            let mut stack = stack.borrow_mut();
125            let entry = stack.pop().unwrap();
126            // Step 3.
127            assert_eq!(
128                &*entry.global as *const D::GlobalScope as usize, self.global,
129                "Dropped AutoIncumbentScript out of order."
130            );
131            assert_eq!(entry.kind, StackEntryKind::Incumbent);
132            trace!(
133                "Clean up after running a callback with {:p}",
134                &*entry.global
135            );
136        });
137        unsafe {
138            // Step 1-2.
139            if let Some(cx) = Runtime::get() {
140                UnhideScriptedCaller(cx.as_ptr());
141            }
142        }
143    }
144}