pyodide_webassembly_runtime_layer/
table.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
use pyo3::{intern, prelude::*, sync::GILOnceCell};
use wasm_runtime_layer::{
    backend::{AsContext, AsContextMut, Value, WasmTable},
    TableType, ValueType,
};

use crate::{
    conversion::{create_js_object, instanceof, ToPy, ValueExt, ValueTypeExt},
    Engine,
};

#[derive(Debug)]
/// A WASM table.
///
/// This type wraps a [`WebAssembly.Table`] from the JavaScript API.
///
/// [`WebAssembly.Table`]: https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/Table
pub struct Table {
    /// Table reference
    table: Py<PyAny>,
    /// The table signature
    ty: TableType,
}

impl Clone for Table {
    fn clone(&self) -> Self {
        Python::with_gil(|py| Self {
            table: self.table.clone_ref(py),
            ty: self.ty,
        })
    }
}

impl WasmTable<Engine> for Table {
    fn new(
        _ctx: impl AsContextMut<Engine>,
        ty: TableType,
        init: Value<Engine>,
    ) -> anyhow::Result<Self> {
        Python::with_gil(|py| -> anyhow::Result<Self> {
            #[cfg(feature = "tracing")]
            tracing::debug!(?ty, ?init, "Table::new");

            let desc = create_js_object(py)?;
            desc.setattr(intern!(py, "element"), ty.element().as_js_descriptor())?;
            desc.setattr(intern!(py, "initial"), ty.minimum())?;
            if let Some(max) = ty.maximum() {
                desc.setattr(intern!(py, "maximum"), max)?;
            }

            let init = init.to_py(py);

            let table = web_assembly_table_new(py)?.call1((desc, init))?;

            Ok(Self {
                table: table.unbind(),
                ty,
            })
        })
    }

    /// Returns the type and limits of the table.
    fn ty(&self, _ctx: impl AsContext<Engine>) -> TableType {
        self.ty
    }

    /// Returns the current size of the table.
    fn size(&self, _ctx: impl AsContext<Engine>) -> u32 {
        Python::with_gil(|py| -> Result<u32, PyErr> {
            let table = self.table.bind(py);

            #[cfg(feature = "tracing")]
            tracing::debug!(table = %table, ?self.ty, "Table::size");

            table.getattr(intern!(py, "length"))?.extract()
        })
        .expect("Table::size should not fail")
    }

    /// Grows the table by the given amount of elements.
    fn grow(
        &self,
        _ctx: impl AsContextMut<Engine>,
        delta: u32,
        init: Value<Engine>,
    ) -> anyhow::Result<u32> {
        Python::with_gil(|py| {
            let table = self.table.bind(py);

            #[cfg(feature = "tracing")]
            tracing::debug!(table = %table, ?self.ty, delta, ?init, "Table::grow");

            let init = init.to_py(py);

            let old_len = table
                .call_method1(intern!(py, "grow"), (delta, init))?
                .extract()?;

            Ok(old_len)
        })
    }

    /// Returns the table element value at `index`.
    fn get(&self, _ctx: impl AsContextMut<Engine>, index: u32) -> Option<Value<Engine>> {
        Python::with_gil(|py| {
            let table = self.table.bind(py);

            #[cfg(feature = "tracing")]
            tracing::debug!(table = %table, ?self.ty, index, "Table::get");

            let value = table.call_method1(intern!(py, "get"), (index,)).ok()?;

            Some(
                Value::from_py_typed(value, self.ty.element()).expect("Table::get should not fail"),
            )
        })
    }

    /// Sets the value of this table at `index`.
    fn set(
        &self,
        _ctx: impl AsContextMut<Engine>,
        index: u32,
        value: Value<Engine>,
    ) -> anyhow::Result<()> {
        Python::with_gil(|py| {
            let table = self.table.bind(py);

            #[cfg(feature = "tracing")]
            tracing::debug!(table = %table, ?self.ty, index, ?value, "Table::set");

            let value = value.to_py(py);

            table.call_method1(intern!(py, "set"), (index, value))?;

            Ok(())
        })
    }
}

impl ToPy for Table {
    fn to_py(&self, py: Python) -> Py<PyAny> {
        #[cfg(feature = "tracing")]
        tracing::trace!(table = %self.table, ?self.ty, "Table::to_py");

        self.table.clone_ref(py)
    }
}

impl Table {
    /// Creates a new table from a Python value
    pub(crate) fn from_exported_table(table: Bound<PyAny>, ty: TableType) -> anyhow::Result<Self> {
        if !instanceof(&table, web_assembly_table(table.py())?)? {
            anyhow::bail!("expected WebAssembly.Table but found {table}");
        }

        #[cfg(feature = "tracing")]
        tracing::debug!(table = %table, ?ty, "Table::from_exported_table");

        let table_length: u32 = table.getattr(intern!(table.py(), "length"))?.extract()?;

        assert!(table_length >= ty.minimum());
        assert_eq!(ty.element(), ValueType::FuncRef);

        Ok(Self {
            table: table.unbind(),
            ty,
        })
    }
}

fn web_assembly_table(py: Python) -> Result<&Bound<PyAny>, PyErr> {
    static WEB_ASSEMBLY_TABLE: GILOnceCell<Py<PyAny>> = GILOnceCell::new();
    WEB_ASSEMBLY_TABLE.import(py, "js.WebAssembly", "Table")
}

fn web_assembly_table_new(py: Python) -> Result<&Bound<PyAny>, PyErr> {
    static WEB_ASSEMBLY_TABLE_NEW: GILOnceCell<Py<PyAny>> = GILOnceCell::new();
    WEB_ASSEMBLY_TABLE_NEW.import(py, "js.WebAssembly.Table", "new")
}