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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
use super::{FuncIdx, GlobalIdx};
use crate::{errors::ModuleError, ExternRef, FuncRef, Value};
use wasmi_core::{ValueType, F32, F64};
/// An initializer expression.
///
/// # Note
///
/// This is used by global variables, table element segments and
/// linear memory data segments.
#[derive(Debug)]
pub struct InitExpr {
/// The operand of the initializer expression.
///
/// # Note
///
/// The Wasm MVP only supports initializer expressions with a single
/// operand (besides the `End` operand). In later Wasm proposals this
/// might change but until then we keep it as simple as possible.
op: InitExprOperand,
}
impl InitExpr {
/// Creates a new [`InitExpr`] from the given Wasm constant expression.
pub fn new(expr: wasmparser::ConstExpr<'_>) -> Self {
let mut reader = expr.get_operators_reader();
let wasm_op = reader.read().unwrap_or_else(|error| {
panic!("expected valid Wasm const expression operand: {error}")
});
let op = InitExprOperand::new(wasm_op);
let end_op = reader.read();
assert!(
matches!(end_op, Ok(wasmparser::Operator::End)),
"expected the Wasm end operator but found {end_op:?}",
);
assert!(
reader.ensure_end().is_ok(),
"expected no more Wasm operands"
);
Self { op }
}
/// Create a new `ref.func x` [`InitExpr`].
pub fn new_funcref(func_index: u32) -> Self {
Self {
op: InitExprOperand::FuncRef(func_index),
}
}
/// Convert the [`InitExpr`] into a Wasm `funcexpr` index if possible.
///
/// Returns `None` if the function reference is `null`.
///
/// # Panics
///
/// If the [`InitExpr`] cannot be interpreted as `funcref` index.
pub fn as_funcref(&self) -> Option<FuncIdx> {
match self.op {
InitExprOperand::RefNull => None,
InitExprOperand::FuncRef(func_index) => Some(FuncIdx(func_index)),
InitExprOperand::Const(_) | InitExprOperand::GlobalGet(_) => {
panic!("encountered non-funcref Wasm expression {:?}", self.op)
}
}
}
/// Converts the [`InitExpr`] into an `externref`.
///
/// # Panics
///
/// If the [`InitExpr`] cannot be interpreted as `externref`.
pub fn as_externref(&self) -> ExternRef {
match self.op {
InitExprOperand::RefNull => ExternRef::null(),
_ => panic!("encountered non-externref Wasm expression: {:?}", self.op),
}
}
/// Return the `Const` [`InitExpr`] if any.
///
/// Returns `None` if the underlying operand is not `Const`.
///
/// # Panics
///
/// If a non-const expression operand is encountered.
pub fn to_const(&self, ty: ValueType) -> Option<Value> {
match &self.op {
InitExprOperand::Const(value) => Some(value.clone()),
InitExprOperand::RefNull => match ty {
ValueType::FuncRef => Some(Value::from(FuncRef::null())),
ValueType::ExternRef => Some(Value::from(ExternRef::null())),
_ => panic!("cannot have null reference for non-reftype but found {ty:?}"),
},
InitExprOperand::GlobalGet(_) => {
// Note: We do not need to handle `global.get` since
// that is only allowed for imported non-mutable
// global variables which have a value that is only
// known post-instantiation time.
None
}
InitExprOperand::FuncRef(_) => {
// Note: We do not need to handle `global.get` here
// since we can do this somewhere else where we
// can properly handle the constant `func.ref`.
// In the function builder we want to replace
// `global.get` of constant `FuncRef(x)` with
// the Wasm `ref.func x` instruction.
None
}
}
}
/// Returns `Some(index)` if the [`InitExpr`] is a `FuncRef(index)`.
///
/// Otherwise returns `None`.
pub fn func_ref(&self) -> Option<FuncIdx> {
if let InitExprOperand::FuncRef(index) = self.op {
return Some(FuncIdx(index));
}
None
}
/// Evaluates the [`InitExpr`] given the context for global variables.
///
/// # Panics
///
/// If a non-const expression operand is encountered.
pub fn to_const_with_context(
&self,
value_type: ValueType,
global_get: impl Fn(u32) -> Value,
func_get: impl Fn(u32) -> Value,
) -> Value {
let value = match &self.op {
InitExprOperand::Const(value) => value.clone(),
InitExprOperand::GlobalGet(index) => global_get(index.into_u32()),
InitExprOperand::RefNull => match value_type {
ValueType::FuncRef => Value::from(FuncRef::null()),
ValueType::ExternRef => Value::from(ExternRef::null()),
_ => panic!("expected reftype for InitExpr but found {value_type:?}"),
},
InitExprOperand::FuncRef(index) => func_get(*index),
};
assert_eq!(value.ty(), value_type);
value
}
}
/// A single operand of an initializer expression.
///
/// # Note
///
/// The Wasm MVP only supports `const` and `global.get` expressions
/// inside initializer expressions. In later Wasm proposals this might
/// change but until then we keep it as simple as possible.
#[derive(Debug)]
pub enum InitExprOperand {
/// A constant value.
Const(Value),
/// The value of a global variable at the time of evaluation.
///
/// # Note
///
/// In the Wasm MVP only immutable globals are allowed to be evaluated.
GlobalGet(GlobalIdx),
/// A Wasm `ref.null` value.
RefNull,
/// A Wasm `ref.func index` value.
FuncRef(u32),
}
impl InitExprOperand {
/// Creates a new [`InitExprOperand`] from the given Wasm operator.
///
/// # Panics
///
/// If the Wasm operator is not a valid [`InitExprOperand`].
fn new(operator: wasmparser::Operator<'_>) -> Self {
match operator {
wasmparser::Operator::I32Const { value } => Self::constant(value),
wasmparser::Operator::I64Const { value } => Self::constant(value),
wasmparser::Operator::F32Const { value } => Self::constant(F32::from(value.bits())),
wasmparser::Operator::F64Const { value } => Self::constant(F64::from(value.bits())),
wasmparser::Operator::GlobalGet { global_index } => {
Self::GlobalGet(GlobalIdx(global_index))
}
wasmparser::Operator::RefNull { .. } => Self::RefNull,
wasmparser::Operator::RefFunc { function_index } => Self::FuncRef(function_index),
operator => {
panic!("encountered unsupported const expression operator: {operator:?}")
}
}
}
/// Creates a new constant [`InitExprOperand`].
fn constant<T>(value: T) -> Self
where
T: Into<Value>,
{
Self::Const(value.into())
}
}
impl TryFrom<wasmparser::Operator<'_>> for InitExprOperand {
type Error = ModuleError;
fn try_from(operator: wasmparser::Operator<'_>) -> Result<Self, Self::Error> {
match operator {
wasmparser::Operator::I32Const { value } => Ok(InitExprOperand::constant(value)),
wasmparser::Operator::I64Const { value } => Ok(InitExprOperand::constant(value)),
wasmparser::Operator::F32Const { value } => {
Ok(InitExprOperand::constant(F32::from(value.bits())))
}
wasmparser::Operator::F64Const { value } => {
Ok(InitExprOperand::constant(F64::from(value.bits())))
}
wasmparser::Operator::GlobalGet { global_index } => {
Ok(InitExprOperand::GlobalGet(GlobalIdx(global_index)))
}
wasmparser::Operator::RefNull { .. } => Ok(InitExprOperand::RefNull),
wasmparser::Operator::RefFunc { function_index } => {
Ok(InitExprOperand::FuncRef(function_index))
}
operator => {
panic!("encountered unsupported const expression operator: {operator:?}")
}
}
}
}