baedeker-core 0.1.0

WebAssembly runtime core — decode, validate, execute (no_std)
Documentation
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
// Copyright (C) 2026 Industrial Algebra
// SPDX-License-Identifier: Apache-2.0

//! Validation error types.
//!
//! Validation runs after binary decoding and reports type/index/control-flow problems
//! against the decoded module structure.

use alloc::vec::Vec;
use core::fmt;

use crate::error::{ByteOffset, DecodeContext, DecodeError, DecodeErrorKind};
use crate::types::{
    BlockType, DataIdx, ElemIdx, FuncIdx, GlobalIdx, LabelIdx, LocalIdx, MemIdx, RefType, TableIdx,
    TypeIdx, ValType,
};

/// A validation error with byte offset and function context.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationError {
    pub offset: ByteOffset,
    pub function: Option<FuncIdx>,
    pub kind: ValidationErrorKind,
}

/// Specific categories of validation errors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationErrorKind {
    UnknownTypeIdx {
        idx: TypeIdx,
    },
    UnknownFuncIdx {
        idx: FuncIdx,
    },
    UndeclaredFuncRef {
        idx: FuncIdx,
    },
    UnknownLocalIdx {
        idx: LocalIdx,
    },
    UninitializedLocal {
        idx: LocalIdx,
    },
    UnknownGlobalIdx {
        idx: GlobalIdx,
        available: u32,
    },
    UnknownTableIdx {
        idx: TableIdx,
        available: u32,
    },
    UnknownMemIdx {
        idx: MemIdx,
        available: u32,
    },
    UnknownDataIdx {
        idx: DataIdx,
        available: u32,
    },
    UnknownElemIdx {
        idx: ElemIdx,
        available: u32,
    },
    InvalidMemArgAlign {
        op: &'static str,
        max: u32,
        found: u32,
    },
    InvalidSimdLaneIdx {
        op: &'static str,
        max: u8,
        found: u8,
    },
    UnknownLabelIdx {
        idx: LabelIdx,
    },
    Decode {
        context: DecodeContext,
        kind: DecodeErrorKind,
    },
    InvalidGlobalInitExpr,
    NonConstantGlobalInitExpr,
    MutableGlobalInInitExpr {
        idx: GlobalIdx,
    },
    ImmutableGlobalSet {
        idx: GlobalIdx,
    },
    GlobalInitTypeMismatch {
        expected: ValType,
        found: ValType,
    },
    BranchTypeMismatch {
        label: LabelIdx,
        expected: Vec<ValType>,
        found: Vec<ValType>,
    },
    InvalidBrOnNonNullTarget {
        label: LabelIdx,
        found: Vec<ValType>,
    },
    InconsistentBranchTypes {
        expected: Vec<ValType>,
        found: Vec<ValType>,
    },
    UnexpectedElse,
    UnexpectedEnd,
    UnterminatedControlFrames,
    ElseOutsideIf,
    MissingElseForResult,
    InvalidBlockType {
        block_type: BlockType,
    },
    ControlResultTypeMismatch {
        expected: Vec<ValType>,
        found: Vec<ValType>,
    },
    InvalidSelectResultArity {
        found: usize,
    },
    SelectOperandTypeMismatch {
        expected: ValType,
        found: Vec<ValType>,
    },
    StackUnderflow {
        op: &'static str,
        expected: Vec<ValType>,
        available: Vec<ValType>,
    },
    TypeMismatch {
        op: &'static str,
        expected: ValType,
        found: ValType,
    },
    FunctionResultTypeMismatch {
        expected: Vec<ValType>,
        found: Vec<ValType>,
        full_stack: Vec<ValType>,
    },
    ResultTypeMismatch {
        expected: Vec<ValType>,
        found: Vec<ValType>,
    },
    InvalidStartFunctionType {
        params: Vec<ValType>,
        results: Vec<ValType>,
    },
    InvalidElementExpr,
    NonConstantElementExpr,
    ElementExprTypeMismatch {
        expected: ValType,
        found: ValType,
    },
    ElementTableTypeMismatch {
        expected: RefType,
        found: RefType,
    },
    InvalidCallIndirectTableType {
        expected: RefType,
        found: RefType,
    },
    MissingDataCountSection {
        op: &'static str,
    },
    MemorySizeOutOfRange,
    MemoryMinExceedsMax,
    /// A non-nullable-element table without an initializer.
    TableTypeMismatch,
    DuplicateExportName {
        name: alloc::string::String,
    },
}

impl fmt::Display for ValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.function {
            Some(func) => write!(
                f,
                "validation error at byte {} in function {}: {}",
                self.offset.0, func.0, self.kind
            ),
            None => write!(
                f,
                "validation error at byte {}: {}",
                self.offset.0, self.kind
            ),
        }
    }
}

impl fmt::Display for ValidationErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ValidationErrorKind::UnknownTypeIdx { idx } => {
                write!(f, "unknown type index {}", idx.0)
            }
            ValidationErrorKind::UnknownFuncIdx { idx } => {
                write!(f, "unknown function index {}", idx.0)
            }
            ValidationErrorKind::UndeclaredFuncRef { idx } => {
                write!(f, "undeclared function reference {}", idx.0)
            }
            ValidationErrorKind::UnknownLocalIdx { idx } => {
                write!(f, "unknown local index {}", idx.0)
            }
            ValidationErrorKind::UninitializedLocal { idx } => {
                write!(f, "uninitialized local {}", idx.0)
            }
            ValidationErrorKind::UnknownGlobalIdx { idx, available } => {
                write!(
                    f,
                    "unknown global index {} (available globals: {})",
                    idx.0, available
                )
            }
            ValidationErrorKind::UnknownTableIdx { idx, available } => {
                write!(
                    f,
                    "unknown table index {} (available tables: {})",
                    idx.0, available
                )
            }
            ValidationErrorKind::UnknownMemIdx { idx, available } => {
                write!(
                    f,
                    "unknown memory index {} (available memories: {})",
                    idx.0, available
                )
            }
            ValidationErrorKind::UnknownDataIdx { idx, available } => {
                write!(
                    f,
                    "unknown data index {} (available data segments: {})",
                    idx.0, available
                )
            }
            ValidationErrorKind::UnknownElemIdx { idx, available } => {
                write!(
                    f,
                    "unknown element index {} (available element segments: {})",
                    idx.0, available
                )
            }
            ValidationErrorKind::InvalidMemArgAlign { op, max, found } => {
                write!(
                    f,
                    "invalid memarg alignment in {}: found {}, maximum natural alignment exponent {}",
                    op, found, max
                )
            }
            ValidationErrorKind::InvalidSimdLaneIdx { op, max, found } => {
                write!(
                    f,
                    "invalid SIMD lane index in {}: found {}, maximum lane {}",
                    op, found, max
                )
            }
            ValidationErrorKind::UnknownLabelIdx { idx } => {
                write!(f, "unknown label index {}", idx.0)
            }
            ValidationErrorKind::Decode { context, kind } => {
                write!(f, "instruction decode error in {}: {}", context, kind)
            }
            ValidationErrorKind::InvalidGlobalInitExpr => {
                write!(f, "invalid global initializer expression")
            }
            ValidationErrorKind::NonConstantGlobalInitExpr => {
                write!(f, "global initializer must be a constant expression")
            }
            ValidationErrorKind::MutableGlobalInInitExpr { idx } => {
                write!(
                    f,
                    "global initializer references mutable imported global {}",
                    idx.0
                )
            }
            ValidationErrorKind::ImmutableGlobalSet { idx } => {
                write!(f, "cannot assign to immutable global {}", idx.0)
            }
            ValidationErrorKind::GlobalInitTypeMismatch { expected, found } => {
                write!(
                    f,
                    "global initializer type mismatch: expected {:?}, found {:?}",
                    expected, found
                )
            }
            ValidationErrorKind::BranchTypeMismatch {
                label,
                expected,
                found,
            } => {
                write!(
                    f,
                    "branch to label {} has type mismatch: expected {:?}, found {:?}",
                    label.0, expected, found
                )
            }
            ValidationErrorKind::InvalidBrOnNonNullTarget { label, found } => {
                write!(
                    f,
                    "br_on_non_null target label {} must end in a reference type, found {:?}",
                    label.0, found
                )
            }
            ValidationErrorKind::InconsistentBranchTypes { expected, found } => {
                write!(
                    f,
                    "branch targets have inconsistent types: expected {:?}, found {:?}",
                    expected, found
                )
            }
            ValidationErrorKind::UnexpectedElse => write!(f, "unexpected else"),
            ValidationErrorKind::UnexpectedEnd => write!(f, "unexpected end"),
            ValidationErrorKind::UnterminatedControlFrames => {
                write!(f, "unterminated control frames")
            }
            ValidationErrorKind::ElseOutsideIf => write!(f, "else outside if block"),
            ValidationErrorKind::MissingElseForResult => {
                write!(f, "if block with result type requires else branch")
            }
            ValidationErrorKind::InvalidBlockType { block_type } => {
                write!(f, "invalid block type {:?}", block_type)
            }
            ValidationErrorKind::ControlResultTypeMismatch { expected, found } => {
                write!(
                    f,
                    "control frame result type mismatch: expected {:?}, found {:?}",
                    expected, found
                )
            }
            ValidationErrorKind::InvalidSelectResultArity { found } => {
                write!(
                    f,
                    "typed select requires exactly one result type, found {}",
                    found
                )
            }
            ValidationErrorKind::SelectOperandTypeMismatch { expected, found } => {
                write!(
                    f,
                    "select operands must match {:?}, found {:?}",
                    expected, found
                )
            }
            ValidationErrorKind::StackUnderflow {
                op,
                expected,
                available,
            } => {
                write!(
                    f,
                    "operand stack underflow in {}: expected {:?}, available {:?}",
                    op, expected, available
                )
            }
            ValidationErrorKind::TypeMismatch {
                op,
                expected,
                found,
            } => {
                write!(
                    f,
                    "type mismatch in {}: expected {:?}, found {:?}",
                    op, expected, found
                )
            }
            ValidationErrorKind::FunctionResultTypeMismatch {
                expected,
                found,
                full_stack,
            } => {
                write!(
                    f,
                    "function result type mismatch: expected {:?}, found {:?} at stack top (full stack {:?})",
                    expected, found, full_stack
                )
            }
            ValidationErrorKind::ResultTypeMismatch { expected, found } => {
                write!(
                    f,
                    "result type mismatch: expected {:?}, found {:?}",
                    expected, found
                )
            }
            ValidationErrorKind::InvalidStartFunctionType { params, results } => {
                write!(
                    f,
                    "start function must have type [] -> [], found {:?} -> {:?}",
                    params, results
                )
            }
            ValidationErrorKind::InvalidElementExpr => {
                write!(f, "invalid element initializer expression")
            }
            ValidationErrorKind::NonConstantElementExpr => {
                write!(f, "element initializer must be a constant expression")
            }
            ValidationErrorKind::ElementExprTypeMismatch { expected, found } => {
                write!(
                    f,
                    "element initializer type mismatch: expected {:?}, found {:?}",
                    expected, found
                )
            }
            ValidationErrorKind::ElementTableTypeMismatch { expected, found } => {
                write!(
                    f,
                    "active element segment table type mismatch: expected {:?}, found {:?}",
                    expected, found
                )
            }
            ValidationErrorKind::InvalidCallIndirectTableType { expected, found } => {
                write!(
                    f,
                    "call_indirect requires table element type {:?}, found {:?}",
                    expected, found
                )
            }
            ValidationErrorKind::MissingDataCountSection { op } => {
                write!(f, "{} requires a data count section", op)
            }
            ValidationErrorKind::MemorySizeOutOfRange => write!(f, "memory size"),
            ValidationErrorKind::MemoryMinExceedsMax => {
                write!(f, "size minimum must not be greater than maximum")
            }
            ValidationErrorKind::TableTypeMismatch => write!(f, "type mismatch"),
            ValidationErrorKind::DuplicateExportName { name } => {
                write!(f, "duplicate export name {:?}", name)
            }
        }
    }
}

impl From<DecodeError> for ValidationErrorKind {
    fn from(error: DecodeError) -> Self {
        Self::Decode {
            context: error.context,
            kind: error.kind,
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for ValidationError {}

#[cfg(not(feature = "std"))]
impl core::error::Error for ValidationError {}