Skip to main content

miden_mast_package/debug_info/
serialization.rs

1//! Serialization and deserialization for the debug_info section.
2
3#![allow(
4    clippy::empty_enums,
5    reason = "zerocopy derives generate uninhabited helper types"
6)]
7
8use alloc::{sync::Arc, vec::Vec};
9use core::{alloc::Layout, ptr::NonNull};
10
11use miden_assembly_syntax::ast::DebugVarLocation;
12use miden_core::{
13    Felt, Word,
14    mast::MastNodeId,
15    serde::{
16        ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable,
17        read_bounded_len,
18    },
19};
20use miden_debug_types::{ColumnIndex, LineIndex};
21use miden_utils_indexing::IndexVec;
22use zerocopy::{Immutable, IntoBytes, KnownLayout};
23
24use super::{
25    DEBUG_INFO_VERSION, DebugErrorMessage, DebugFieldInfo, DebugFileIdx, DebugFileInfo,
26    DebugFunctionIdx, DebugFunctionInfo, DebugLoc, DebugLocIdx, DebugPrimitiveType,
27    DebugSourceAsmOp, DebugSourceInlineCall, DebugSourceNode, DebugSourceNodeId, DebugSourceVar,
28    DebugStringIdx, DebugTypeIdx, DebugTypeInfo, DebugVariantInfo, MAX_DEBUG_INFO_PAYLOAD_SIZE,
29    MAX_DEBUG_INFO_STRING_ROWS, MAX_DEBUG_INFO_STRING_SIZE, MAX_DEBUG_INFO_TYPE_ROWS,
30    OptionalIndex, PackageDebugInfo,
31};
32use crate::serde_helpers::read_capped_str;
33
34/// Base alignment for copied payloads. The assertions below ensure that this is sufficient for
35/// every row type decoded directly from the payload.
36const POD_BUFFER_ALIGNMENT: usize = align_of::<u64>();
37
38const _: () = {
39    assert!(align_of::<DebugFileInfo>() <= POD_BUFFER_ALIGNMENT);
40    assert!(align_of::<DebugLoc>() <= POD_BUFFER_ALIGNMENT);
41    assert!(align_of::<WireDebugFunctionInfo>() <= POD_BUFFER_ALIGNMENT);
42    assert!(align_of::<DebugSourceNodeId>() <= POD_BUFFER_ALIGNMENT);
43    assert!(align_of::<DebugErrorMessage>() <= POD_BUFFER_ALIGNMENT);
44    assert!(align_of::<DebugSourceAsmOp>() <= POD_BUFFER_ALIGNMENT);
45};
46
47/// Wire form of [`DebugFunctionInfo`]. The domain type cannot be decoded from arbitrary bytes
48/// because its field elements must be validated before constructing a [`Word`].
49#[repr(C, align(8))]
50#[derive(Clone, Copy, zerocopy::FromBytes, Immutable, IntoBytes, KnownLayout)]
51struct WireDebugFunctionInfo {
52    mast_root: [u64; 4],
53    source_node: OptionalIndex<DebugSourceNodeId>,
54    type_idx: OptionalIndex<DebugTypeIdx>,
55    linkage_name_idx: OptionalIndex<DebugStringIdx>,
56    name_idx: DebugStringIdx,
57    file_idx: DebugFileIdx,
58    line: LineIndex,
59    column: ColumnIndex,
60}
61
62#[derive(Clone, Copy)]
63struct PackageDebugInfoDecodeLimits {
64    payload_size: usize,
65    string_rows: usize,
66    string_size: usize,
67    type_rows: usize,
68}
69
70impl PackageDebugInfoDecodeLimits {
71    const BOUNDED: Self = Self {
72        payload_size: MAX_DEBUG_INFO_PAYLOAD_SIZE,
73        string_rows: MAX_DEBUG_INFO_STRING_ROWS,
74        string_size: MAX_DEBUG_INFO_STRING_SIZE,
75        type_rows: MAX_DEBUG_INFO_TYPE_ROWS,
76    };
77
78    const UNMETERED: Self = Self {
79        payload_size: usize::MAX,
80        string_rows: usize::MAX,
81        string_size: usize::MAX,
82        type_rows: usize::MAX,
83    };
84}
85
86fn check_decode_limit(
87    resource: &'static str,
88    actual: usize,
89    limit: usize,
90) -> Result<(), super::DebugInfoEncodingError> {
91    if actual > limit {
92        return Err(super::DebugInfoEncodingError::LimitExceeded { resource, size: actual, limit });
93    }
94    Ok(())
95}
96
97// PACKAGE DEBUG INFO SERIALIZATION
98// ================================================================================================
99
100/// Fixed-size tables are padded to their row alignment and written as `zerocopy`-certified rows.
101/// Deserialization copies each payload into an aligned allocation because the padding preserves row
102/// alignment only when measured from an aligned payload base. The function table uses an explicit
103/// wire row because its field elements require validation before constructing domain values.
104#[cfg(target_endian = "little")]
105impl Serializable for PackageDebugInfo {
106    fn write_into<W: ByteWriter>(&self, target: &mut W) {
107        let mut output = Vec::<u8>::with_capacity(16 * 1024);
108
109        self.strings.write_into(&mut output);
110
111        output.write_u32(self.files().len().try_into().unwrap());
112        write_pod_slice(self.files().as_slice(), &mut output);
113
114        output.write_u32(self.locations().len().try_into().unwrap());
115        write_pod_slice(self.locations().as_slice(), &mut output);
116
117        self.types.write_into(&mut output);
118
119        output.write_u32(self.functions().len().try_into().unwrap());
120        pad_to_align::<WireDebugFunctionInfo>(&mut output);
121        write_pod_rows(
122            self.functions().iter().map(|row| {
123                let mast_root = row.mast_root.into_elements().map(|felt| felt.as_canonical_u64());
124                WireDebugFunctionInfo {
125                    mast_root,
126                    source_node: row.source_node,
127                    type_idx: row.type_idx,
128                    linkage_name_idx: row.linkage_name_idx,
129                    name_idx: row.name_idx,
130                    file_idx: row.file_idx,
131                    line: row.line,
132                    column: row.column,
133                }
134            }),
135            &mut output,
136        );
137
138        self.nodes.write_into(&mut output);
139
140        output.write_u32(self.roots().len().try_into().unwrap());
141        write_pod_slice(self.roots(), &mut output);
142
143        output.write_u32(self.error_messages().len().try_into().unwrap());
144        write_pod_slice(self.error_messages(), &mut output);
145
146        target.write_u8(self.version());
147        target.write_usize(output.len());
148        target.write_bytes(&output);
149    }
150}
151
152#[cfg(target_endian = "little")]
153impl PackageDebugInfo {
154    /// Encodes debug information after checking the standard decoder's fixed resource limits.
155    ///
156    /// This lets producers reject metadata that a normal package consumer could not read, without
157    /// decoding another copy of the tables. Ordinary serialization remains unmetered. This checks
158    /// resource limits, not table references or the package's source graph.
159    pub fn to_bytes_with_standard_limits(&self) -> Result<Vec<u8>, super::DebugInfoEncodingError> {
160        self.to_bytes_with_limits(PackageDebugInfoDecodeLimits::BOUNDED)
161    }
162
163    fn to_bytes_with_limits(
164        &self,
165        limits: PackageDebugInfoDecodeLimits,
166    ) -> Result<Vec<u8>, super::DebugInfoEncodingError> {
167        for (label, actual, limit) in [
168            ("debug_info strings count", self.strings.len(), limits.string_rows),
169            ("debug_info types count", self.types.len(), limits.type_rows),
170        ] {
171            check_decode_limit(label, actual, limit)?;
172        }
173        for string in self.strings.iter() {
174            check_decode_limit("debug string size", string.len(), limits.string_size)?;
175        }
176
177        let bytes = self.to_bytes();
178        let mut header = miden_core::serde::SliceReader::new(&bytes);
179        header.read_u8()?;
180        let payload_size = header.read_usize()?;
181        check_decode_limit("package debug info payload size", payload_size, limits.payload_size)?;
182        Ok(bytes)
183    }
184
185    /// Reads package debug information without the fixed resource limits enforced by
186    /// [`Self::read_from`].
187    ///
188    /// Use this for data from a trusted producer or in analysis tooling where the caller accepts
189    /// its memory and processing costs. This method still checks the wire format and honors the
190    /// reader's remaining input and allocation budget. Use [`Self::read_from`] for potentially
191    /// adversarial input with the standard fixed limits.
192    pub fn read_from_unmetered<R: ByteReader>(
193        source: &mut R,
194    ) -> Result<Self, DeserializationError> {
195        Self::read_from_with_limits(source, PackageDebugInfoDecodeLimits::UNMETERED)
196    }
197
198    /// Reads package debug information from `bytes` without the fixed resource limits enforced by
199    /// [`Self::read_from_bytes`].
200    ///
201    /// Use this only when the caller accepts the memory and processing costs of the encoded data.
202    /// The wire-format checks described by [`Self::read_from_unmetered`] still apply. Use
203    /// [`Self::read_from_bytes`] for potentially adversarial input with the standard fixed limits.
204    pub fn read_from_bytes_unmetered(bytes: &[u8]) -> Result<Self, DeserializationError> {
205        Self::read_from_unmetered(&mut miden_core::serde::SliceReader::new(bytes))
206    }
207
208    fn read_from_with_limits<R: ByteReader>(
209        source: &mut R,
210        limits: PackageDebugInfoDecodeLimits,
211    ) -> Result<Self, DeserializationError> {
212        use alloc::string::ToString;
213
214        let version = source.read_u8()?;
215        if version != DEBUG_INFO_VERSION {
216            return Err(DeserializationError::InvalidValue(format!(
217                "unsupported debug_info version: {version}, expected {DEBUG_INFO_VERSION}"
218            )));
219        }
220
221        let data_len = read_bounded_len(source, "package debug info", 1)?;
222        check_decode_limit("package debug info payload size", data_len, limits.payload_size)
223            .map_err(|err| DeserializationError::InvalidValue(err.to_string()))?;
224        let data = source.read_slice(data_len)?;
225        let aligned = AlignedBytes::copy_from_slice(data, POD_BUFFER_ALIGNMENT)?;
226        let mut source = PodSliceReader::new(aligned.as_slice());
227
228        let strings_len = read_bounded_len(&mut source, "debug_info strings", 1)?;
229        check_decode_limit("debug_info strings count", strings_len, limits.string_rows)
230            .map_err(|err| DeserializationError::InvalidValue(err.to_string()))?;
231        let mut strings = Vec::new();
232        for _ in 0..strings_len {
233            strings.push(read_string(&mut source, limits.string_size)?);
234        }
235        let strings = IndexVec::try_from(strings).map_err(|_| {
236            DeserializationError::InvalidValue(
237                "debug_info strings count exceeds the u32 index range".into(),
238            )
239        })?;
240
241        let files_len = source.read_u32()?;
242        let files = source.read_pod_rows::<DebugFileInfo>(files_len as usize, "debug files")?;
243
244        let locations_len = source.read_u32()?;
245        let locations =
246            source.read_pod_rows::<DebugLoc>(locations_len as usize, "debug locations")?;
247
248        let types_len = read_bounded_len(
249            &mut source,
250            "debug_info types",
251            DebugTypeInfo::min_serialized_size(),
252        )?;
253        check_decode_limit("debug_info types count", types_len, limits.type_rows)
254            .map_err(|err| DeserializationError::InvalidValue(err.to_string()))?;
255        let types = source.read_many_iter(types_len)?.collect::<Result<Vec<DebugTypeInfo>, _>>()?;
256        let types = IndexVec::try_from(types).map_err(|_| {
257            DeserializationError::InvalidValue(
258                "debug_info types count exceeds the u32 index range".into(),
259            )
260        })?;
261
262        let functions_len = source.read_u32()?;
263        let functions = source.read_pod_rows_with::<WireDebugFunctionInfo, _, _>(
264            functions_len as usize,
265            "debug functions",
266            |row| {
267                Ok(DebugFunctionInfo {
268                    mast_root: Word::new([
269                        read_wire_felt(row.mast_root[0])?,
270                        read_wire_felt(row.mast_root[1])?,
271                        read_wire_felt(row.mast_root[2])?,
272                        read_wire_felt(row.mast_root[3])?,
273                    ]),
274                    source_node: row.source_node,
275                    type_idx: row.type_idx,
276                    linkage_name_idx: row.linkage_name_idx,
277                    name_idx: row.name_idx,
278                    file_idx: row.file_idx,
279                    line: row.line,
280                    column: row.column,
281                })
282            },
283        )?;
284
285        let nodes = IndexVec::read_from_bounded(&mut source, "debug_info nodes")?;
286
287        let roots_len = source.read_u32()? as usize;
288        let roots = source.read_pod_rows::<DebugSourceNodeId>(roots_len, "debug source roots")?;
289
290        let error_messages_len = source.read_u32()? as usize;
291        let error_messages = source
292            .read_pod_rows::<DebugErrorMessage>(error_messages_len, "debug error messages")?;
293
294        let remaining_len = source.remaining_len();
295        if remaining_len != 0 {
296            return Err(DeserializationError::InvalidValue(format!(
297                "expected {data_len} bytes to have been read, but {remaining_len} remain in the buffer"
298            )));
299        }
300
301        Ok(PackageDebugInfo {
302            version,
303            strings,
304            files: IndexVec::try_from(files).unwrap(),
305            locations: IndexVec::try_from(locations).unwrap(),
306            types,
307            functions: IndexVec::try_from(functions).unwrap(),
308            nodes,
309            roots,
310            error_messages,
311        })
312    }
313}
314
315#[cfg(target_endian = "little")]
316impl Deserializable for PackageDebugInfo {
317    /// Reads package debug information using fixed resource limits for potentially adversarial
318    /// input.
319    ///
320    /// The limits cap the encoded payload, string table, individual strings, and type table. This
321    /// method also performs the normal wire-format checks. Use [`Self::read_from_unmetered`] only
322    /// when the data may exceed those limits and the caller accepts its resource costs.
323    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
324        Self::read_from_with_limits(source, PackageDebugInfoDecodeLimits::BOUNDED)
325    }
326
327    /// Reads package debug information from `bytes` using fixed resource limits for potentially
328    /// adversarial input.
329    ///
330    /// This is the byte-slice counterpart to [`Self::read_from`]. Use
331    /// [`Self::read_from_bytes_unmetered`] only when the data may exceed the standard limits and
332    /// the caller accepts its resource costs.
333    fn read_from_bytes(bytes: &[u8]) -> Result<Self, DeserializationError> {
334        Self::read_from(&mut miden_core::serde::SliceReader::new(bytes))
335    }
336}
337
338// DEBUG SOURCE NODE SERIALIZATION
339// ================================================================================================
340
341/// Fixed-size child and assembly-op tables use the same certified row format as
342/// [`PackageDebugInfo`].
343#[cfg(target_endian = "little")]
344impl Serializable for DebugSourceNode {
345    fn write_into<W: ByteWriter>(&self, target: &mut W) {
346        let mut output = Vec::<u8>::with_capacity(
347            size_of::<DebugSourceNode>()
348                + (self.asm_ops.len() * size_of::<DebugSourceAsmOp>())
349                + (self.debug_vars.len() * size_of::<DebugSourceVar>())
350                + (self.inline_calls.len() * size_of::<DebugSourceInlineCall>()),
351        );
352
353        output.write_u32(self.exec_node.into());
354
355        output.write_u32(self.children.len().try_into().unwrap());
356        write_pod_slice(self.children.as_slice(), &mut output);
357
358        output.write_u32(self.op_start);
359        output.write_u32(self.op_end);
360
361        output.write_u32(self.asm_ops.len().try_into().unwrap());
362        write_pod_slice(self.asm_ops.as_slice(), &mut output);
363
364        self.debug_vars.write_into(&mut output);
365        self.inline_calls.write_into(&mut output);
366
367        target.write_usize(output.len());
368        target.write_bytes(&output);
369    }
370}
371
372#[cfg(target_endian = "little")]
373impl Deserializable for DebugSourceNode {
374    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
375        let data_len = read_bounded_len(source, "debug source node", 1)?;
376        let data = source.read_slice(data_len)?;
377        let aligned = AlignedBytes::copy_from_slice(data, POD_BUFFER_ALIGNMENT)?;
378        let mut source = PodSliceReader::new(aligned.as_slice());
379
380        let exec_node = MastNodeId::new_unchecked(source.read_u32()?);
381
382        let children_len = source.read_u32()? as usize;
383        let children =
384            source.read_pod_rows::<DebugSourceNodeId>(children_len, "debug source children")?;
385
386        let op_start = source.read_u32()?;
387        let op_end = source.read_u32()?;
388
389        let asm_ops_len = source.read_u32()? as usize;
390        let asm_ops =
391            source.read_pod_rows::<DebugSourceAsmOp>(asm_ops_len, "debug assembly operations")?;
392        if let Some(rows) = asm_ops.windows(2).find(|rows| rows[0].op_idx >= rows[1].op_idx) {
393            return Err(DeserializationError::InvalidValue(format!(
394                "debug assembly operation indices are not strictly increasing at {} and {}",
395                rows[0].op_idx, rows[1].op_idx,
396            )));
397        }
398
399        let debug_vars = Vec::read_from(&mut source)?;
400        let inline_calls = Vec::read_from(&mut source)?;
401
402        let remaining_len = source.remaining_len();
403        if remaining_len != 0 {
404            return Err(DeserializationError::InvalidValue(format!(
405                "expected {data_len} bytes to have been read, but {remaining_len} remain in the buffer"
406            )));
407        }
408
409        Ok(Self {
410            exec_node,
411            children,
412            op_start,
413            op_end,
414            asm_ops,
415            debug_vars,
416            inline_calls,
417        })
418    }
419
420    fn min_serialized_size() -> usize {
421        1 + DebugSourceNodeId::min_serialized_size()
422            + Vec::<DebugSourceNodeId>::min_serialized_size()
423            + 8
424            + 1
425            + Vec::<DebugSourceVar>::min_serialized_size()
426            + Vec::<DebugSourceInlineCall>::min_serialized_size()
427    }
428}
429
430// DEBUG SOURCE VARIABLE SERIALIZATION
431// ================================================================================================
432
433impl Serializable for DebugSourceVar {
434    fn write_into<W: ByteWriter>(&self, target: &mut W) {
435        target.write_u32(self.op_idx);
436        self.name_idx.write_into(target);
437        self.type_id.write_into(target);
438        target.write_u32(self.arg_idx.map(core::num::NonZeroU32::get).unwrap_or_default());
439        self.location_idx.write_into(target);
440        self.value_location.write_into(target);
441    }
442}
443
444impl Deserializable for DebugSourceVar {
445    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
446        let op_idx = source.read_u32()?;
447        let name_idx = DebugStringIdx::read_from(source)?;
448        let type_id = Option::<DebugTypeIdx>::read_from(source)?;
449        let arg_idx = core::num::NonZeroU32::new(source.read_u32()?);
450        let location_idx = Option::<DebugLocIdx>::read_from(source)?;
451        let value_location = DebugVarLocation::read_from(source)?;
452        Ok(Self {
453            op_idx,
454            name_idx,
455            type_id,
456            arg_idx,
457            location_idx,
458            value_location,
459        })
460    }
461
462    fn min_serialized_size() -> usize {
463        4 + DebugStringIdx::min_serialized_size()
464            + 1
465            + 4
466            + 1
467            + DebugVarLocation::min_serialized_size()
468    }
469}
470
471// DEBUG INLINE CALL SERIALIZATION
472// ================================================================================================
473
474impl Serializable for DebugSourceInlineCall {
475    fn write_into<W: ByteWriter>(&self, target: &mut W) {
476        target.write_u32(self.op_idx);
477        target.write_u32(self.op_end);
478        self.callee_idx.write_into(target);
479        self.loc_idx.write_into(target);
480    }
481}
482
483impl Deserializable for DebugSourceInlineCall {
484    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
485        let op_idx = source.read_u32()?;
486        let op_end = source.read_u32()?;
487        if op_end < op_idx {
488            return Err(DeserializationError::InvalidValue(
489                "debug inline-call range ends before its start".into(),
490            ));
491        }
492        let callee_idx = DebugFunctionIdx::read_from(source)?;
493        let loc_idx = DebugLocIdx::read_from(source)?;
494        Ok(DebugSourceInlineCall { op_idx, op_end, callee_idx, loc_idx })
495    }
496
497    fn min_serialized_size() -> usize {
498        8 + DebugFunctionIdx::min_serialized_size() + DebugLocIdx::min_serialized_size()
499    }
500}
501
502// DEBUG TYPE INFO SERIALIZATION
503// ================================================================================================
504
505// Type tags for serialization
506const TYPE_TAG_PRIMITIVE: u8 = 0;
507const TYPE_TAG_POINTER: u8 = 1;
508const TYPE_TAG_ARRAY: u8 = 2;
509const TYPE_TAG_STRUCT: u8 = 3;
510const TYPE_TAG_FUNCTION: u8 = 4;
511const TYPE_TAG_UNKNOWN: u8 = 5;
512const TYPE_TAG_ENUM: u8 = 6;
513const TYPE_TAG_VARIADIC: u8 = 7;
514
515impl Serializable for DebugTypeInfo {
516    fn write_into<W: ByteWriter>(&self, target: &mut W) {
517        match self {
518            Self::Primitive(prim) => {
519                target.write_u8(TYPE_TAG_PRIMITIVE);
520                target.write_u8(*prim as u8);
521            },
522            Self::Pointer { pointee_type_idx } => {
523                target.write_u8(TYPE_TAG_POINTER);
524                pointee_type_idx.write_into(target);
525            },
526            Self::Array { element_type_idx, count } => {
527                target.write_u8(TYPE_TAG_ARRAY);
528                element_type_idx.write_into(target);
529                target.write_bool(count.is_some());
530                if let Some(count) = count {
531                    target.write_u32(*count);
532                }
533            },
534            Self::Struct { name_idx, size, fields } => {
535                target.write_u8(TYPE_TAG_STRUCT);
536                name_idx.write_into(target);
537                target.write_u32(*size);
538                target.write_usize(fields.len());
539                for field in fields {
540                    field.write_into(target);
541                }
542            },
543            Self::Function { return_type_idx, param_type_indices } => {
544                target.write_u8(TYPE_TAG_FUNCTION);
545                target.write_bool(return_type_idx.is_some());
546                if let Some(idx) = return_type_idx {
547                    idx.write_into(target);
548                }
549                target.write_usize(param_type_indices.len());
550                for idx in param_type_indices {
551                    idx.write_into(target);
552                }
553            },
554            Self::Enum {
555                name_idx,
556                size,
557                discriminant_type_idx,
558                variants,
559            } => {
560                target.write_u8(TYPE_TAG_ENUM);
561                name_idx.write_into(target);
562                target.write_u32(*size);
563                discriminant_type_idx.write_into(target);
564                target.write_usize(variants.len());
565                for variant in variants {
566                    variant.write_into(target);
567                }
568            },
569            Self::Unknown => {
570                target.write_u8(TYPE_TAG_UNKNOWN);
571            },
572            Self::Variadic => {
573                target.write_u8(TYPE_TAG_VARIADIC);
574            },
575        }
576    }
577}
578
579impl Deserializable for DebugTypeInfo {
580    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
581        let tag = source.read_u8()?;
582        match tag {
583            TYPE_TAG_PRIMITIVE => {
584                let prim_tag = source.read_u8()?;
585                let prim = DebugPrimitiveType::from_discriminant(prim_tag).ok_or_else(|| {
586                    DeserializationError::InvalidValue(alloc::format!(
587                        "invalid primitive type tag: {prim_tag}"
588                    ))
589                })?;
590                Ok(Self::Primitive(prim))
591            },
592            TYPE_TAG_POINTER => {
593                let pointee_type_idx = DebugTypeIdx::from(source.read_u32()?);
594                Ok(Self::Pointer { pointee_type_idx })
595            },
596            TYPE_TAG_ARRAY => {
597                let element_type_idx = DebugTypeIdx::from(source.read_u32()?);
598                let has_count = source.read_bool()?;
599                let count = if has_count { Some(source.read_u32()?) } else { None };
600                Ok(Self::Array { element_type_idx, count })
601            },
602            TYPE_TAG_STRUCT => {
603                let name_idx = DebugStringIdx::read_from(source)?;
604                let size = source.read_u32()?;
605                let fields_len = read_bounded_len(source, "debug struct fields", 1)?;
606                let fields = source.read_many_iter(fields_len)?.collect::<Result<_, _>>()?;
607                Ok(Self::Struct { name_idx, size, fields })
608            },
609            TYPE_TAG_FUNCTION => {
610                let has_return = source.read_bool()?;
611                let return_type_idx = if has_return {
612                    Some(DebugTypeIdx::from(source.read_u32()?))
613                } else {
614                    None
615                };
616                let param_type_indices =
617                    read_debug_type_indices(source, "debug function parameters")?;
618                Ok(Self::Function { return_type_idx, param_type_indices })
619            },
620            TYPE_TAG_ENUM => {
621                let name_idx = DebugStringIdx::read_from(source)?;
622                let size = source.read_u32()?;
623                let discriminant_type_idx = DebugTypeIdx::from(source.read_u32()?);
624                let variants_len = read_bounded_len(source, "debug enum variants", 1)?;
625                let variants = source.read_many_iter(variants_len)?.collect::<Result<_, _>>()?;
626                Ok(Self::Enum {
627                    name_idx,
628                    size,
629                    discriminant_type_idx,
630                    variants,
631                })
632            },
633            TYPE_TAG_UNKNOWN => Ok(Self::Unknown),
634            TYPE_TAG_VARIADIC => Ok(Self::Variadic),
635            _ => Err(DeserializationError::InvalidValue(alloc::format!("invalid type tag: {tag}"))),
636        }
637    }
638
639    fn min_serialized_size() -> usize {
640        // The unknown type consists solely of its tag. All other variants are larger.
641        1
642    }
643}
644
645// DEBUG FIELD INFO SERIALIZATION
646// ================================================================================================
647
648impl Serializable for DebugFieldInfo {
649    fn write_into<W: ByteWriter>(&self, target: &mut W) {
650        self.name_idx.write_into(target);
651        self.type_idx.write_into(target);
652        target.write_u32(self.offset);
653    }
654}
655
656impl Deserializable for DebugFieldInfo {
657    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
658        let name_idx = DebugStringIdx::read_from(source)?;
659        let type_idx = DebugTypeIdx::from(source.read_u32()?);
660        let offset = source.read_u32()?;
661        Ok(Self { name_idx, type_idx, offset })
662    }
663}
664
665// DEBUG VARIANT INFO SERIALIZATION
666// ================================================================================================
667
668impl Serializable for DebugVariantInfo {
669    fn write_into<W: ByteWriter>(&self, target: &mut W) {
670        self.name_idx.write_into(target);
671        target.write_bool(self.type_idx.is_some());
672        if let Some(type_idx) = self.type_idx {
673            type_idx.write_into(target);
674        }
675        target.write_bool(self.payload_offset.is_some());
676        if let Some(payload_offset) = self.payload_offset {
677            target.write_u32(payload_offset);
678        }
679        target.write_u64((self.discriminant >> 64) as u64);
680        target.write_u64(self.discriminant as u64);
681    }
682}
683
684impl Deserializable for DebugVariantInfo {
685    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
686        let name_idx = DebugStringIdx::read_from(source)?;
687        let type_idx = if source.read_bool()? {
688            Some(DebugTypeIdx::from(source.read_u32()?))
689        } else {
690            None
691        };
692        let payload_offset = if source.read_bool()? {
693            Some(source.read_u32()?)
694        } else {
695            None
696        };
697        let hi = source.read_u64()? as u128;
698        let lo = source.read_u64()? as u128;
699        Ok(Self {
700            name_idx,
701            type_idx,
702            payload_offset,
703            discriminant: (hi << 64) | lo,
704        })
705    }
706
707    fn min_serialized_size() -> usize {
708        // The minimum encoding has no payload type or offset: one string-table index, two
709        // one-byte option discriminants, and the two halves of the discriminant value.
710        DebugStringIdx::min_serialized_size()
711            + 2 * u8::min_serialized_size()
712            + 2 * u64::min_serialized_size()
713    }
714}
715
716// DEBUG FILE INFO SERIALIZATION
717// ================================================================================================
718
719impl Serializable for DebugFileInfo {
720    fn write_into<W: ByteWriter>(&self, target: &mut W) {
721        self.path_idx.write_into(target);
722        self.checksum.write_into(target);
723    }
724}
725
726impl Deserializable for DebugFileInfo {
727    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
728        let path_idx = DebugStringIdx::read_from(source)?;
729
730        let bytes = source.read_slice(32)?;
731        let mut checksum = [0u8; 32];
732        checksum.copy_from_slice(bytes);
733
734        Ok(Self { path_idx, checksum })
735    }
736
737    fn min_serialized_size() -> usize {
738        DebugStringIdx::min_serialized_size() + size_of::<[u8; 32]>()
739    }
740}
741
742// HELPER FUNCTIONS
743// ================================================================================================
744
745/// Owns a byte allocation with the alignment required by the certified POD row types.
746struct AlignedBytes {
747    ptr: Option<NonNull<u8>>,
748    layout: Layout,
749}
750
751impl AlignedBytes {
752    fn copy_from_slice(source: &[u8], alignment: usize) -> Result<Self, DeserializationError> {
753        let layout = Layout::from_size_align(source.len(), alignment).map_err(|_| {
754            DeserializationError::InvalidValue(format!(
755                "debug info payload size {} is too large",
756                source.len()
757            ))
758        })?;
759        if source.is_empty() {
760            return Ok(Self { ptr: None, layout });
761        }
762
763        // SAFETY: `layout` is non-zero and valid in this branch.
764        let ptr = unsafe { alloc::alloc::alloc(layout) };
765        let Some(ptr) = NonNull::new(ptr) else {
766            alloc::alloc::handle_alloc_error(layout)
767        };
768        // SAFETY: `ptr` owns `source.len()` writable bytes and does not overlap `source`.
769        unsafe {
770            ptr.as_ptr().copy_from_nonoverlapping(source.as_ptr(), source.len());
771        }
772        Ok(Self { ptr: Some(ptr), layout })
773    }
774
775    fn as_slice(&self) -> &[u8] {
776        let Some(ptr) = self.ptr else {
777            return &[];
778        };
779        // SAFETY: `ptr` was allocated with `self.layout`, every byte was initialized by the copy in
780        // `copy_from_slice`, and the allocation remains owned by `self` for the returned borrow.
781        unsafe { core::slice::from_raw_parts(ptr.as_ptr(), self.layout.size()) }
782    }
783}
784
785impl Drop for AlignedBytes {
786    fn drop(&mut self) {
787        if let Some(ptr) = self.ptr {
788            // SAFETY: `ptr` was allocated with this exact layout and has not been freed.
789            unsafe {
790                alloc::alloc::dealloc(ptr.as_ptr(), self.layout);
791            }
792        }
793    }
794}
795
796struct PodSliceReader<'a> {
797    source: &'a [u8],
798    pos: usize,
799}
800
801impl<'a> PodSliceReader<'a> {
802    fn new(source: &'a [u8]) -> Self {
803        Self { source, pos: 0 }
804    }
805
806    fn remaining_len(&self) -> usize {
807        self.source.len() - self.pos
808    }
809
810    fn read_pod_rows<T>(&mut self, len: usize, label: &str) -> Result<Vec<T>, DeserializationError>
811    where
812        T: Copy + zerocopy::FromBytes + Immutable + KnownLayout,
813    {
814        self.skip_alignment_padding::<T>()?;
815        let byte_len = len.checked_mul(size_of::<T>()).ok_or_else(|| {
816            DeserializationError::InvalidValue(alloc::format!(
817                "{label} row count {len} overflows row size {}",
818                size_of::<T>()
819            ))
820        })?;
821        let bytes = self.read_slice(byte_len)?;
822        let rows: &[T] = <[T] as zerocopy::FromBytes>::ref_from_bytes(bytes).map_err(|_| {
823            DeserializationError::InvalidValue(alloc::format!(
824                "{label} bytes do not form aligned POD rows"
825            ))
826        })?;
827        Ok(rows.to_vec())
828    }
829
830    fn read_pod_rows_with<T, U, F>(
831        &mut self,
832        len: usize,
833        label: &str,
834        map: F,
835    ) -> Result<Vec<U>, DeserializationError>
836    where
837        T: Copy + zerocopy::FromBytes + Immutable + KnownLayout,
838        F: FnMut(T) -> Result<U, DeserializationError>,
839    {
840        self.skip_alignment_padding::<T>()?;
841        let byte_len = len.checked_mul(size_of::<T>()).ok_or_else(|| {
842            DeserializationError::InvalidValue(alloc::format!(
843                "{label} row count {len} overflows row size {}",
844                size_of::<T>()
845            ))
846        })?;
847        let bytes = self.read_slice(byte_len)?;
848        let rows: &[T] = <[T] as zerocopy::FromBytes>::ref_from_bytes(bytes).map_err(|_| {
849            DeserializationError::InvalidValue(alloc::format!(
850                "{label} bytes do not form aligned POD rows"
851            ))
852        })?;
853        rows.iter().copied().map(map).collect()
854    }
855
856    fn skip_alignment_padding<T>(&mut self) -> Result<(), DeserializationError> {
857        let padding_required = self.pos.next_multiple_of(align_of::<T>()) - self.pos;
858        self.pos += padding_required;
859        if self.pos > self.source.len() {
860            Err(DeserializationError::UnexpectedEOF)
861        } else {
862            Ok(())
863        }
864    }
865}
866
867impl ByteReader for PodSliceReader<'_> {
868    fn max_alloc(&self, element_size: usize) -> usize {
869        self.remaining_len().checked_div(element_size).unwrap_or(usize::MAX)
870    }
871
872    fn read_u8(&mut self) -> Result<u8, DeserializationError> {
873        self.check_eor(1)?;
874        let result = self.source[self.pos];
875        self.pos += 1;
876        Ok(result)
877    }
878
879    fn peek_u8(&self) -> Result<u8, DeserializationError> {
880        self.check_eor(1)?;
881        Ok(self.source[self.pos])
882    }
883
884    fn read_slice(&mut self, len: usize) -> Result<&[u8], DeserializationError> {
885        self.check_eor(len)?;
886        let result = &self.source[self.pos..self.pos + len];
887        self.pos += len;
888        Ok(result)
889    }
890
891    fn read_array<const N: usize>(&mut self) -> Result<[u8; N], DeserializationError> {
892        self.check_eor(N)?;
893        let mut result = [0_u8; N];
894        result.copy_from_slice(&self.source[self.pos..self.pos + N]);
895        self.pos += N;
896        Ok(result)
897    }
898
899    fn check_eor(&self, num_bytes: usize) -> Result<(), DeserializationError> {
900        self.pos
901            .checked_add(num_bytes)
902            .filter(|end| *end <= self.source.len())
903            .map(|_| ())
904            .ok_or(DeserializationError::UnexpectedEOF)
905    }
906
907    fn has_more_bytes(&self) -> bool {
908        self.remaining_len() != 0
909    }
910}
911
912fn pad_to_align<T>(output: &mut Vec<u8>) {
913    let padding_required = output.len().next_multiple_of(align_of::<T>()) - output.len();
914    output.resize(output.len() + padding_required, 0);
915}
916
917fn write_pod_slice<T: IntoBytes + Immutable>(slice: &[T], target: &mut Vec<u8>) {
918    pad_to_align::<T>(target);
919    target.write_bytes(slice.as_bytes());
920}
921
922fn write_pod_rows<T, I>(rows: I, target: &mut Vec<u8>)
923where
924    T: IntoBytes + Immutable,
925    I: IntoIterator<Item = T>,
926{
927    let rows: Vec<T> = rows.into_iter().collect();
928    target.write_bytes(rows.as_bytes());
929}
930
931fn read_wire_felt(value: u64) -> Result<Felt, DeserializationError> {
932    Felt::new(value).map_err(|err| {
933        DeserializationError::InvalidValue(alloc::format!(
934            "invalid field element in debug function MAST root: {err}"
935        ))
936    })
937}
938
939fn read_string<R: ByteReader>(
940    source: &mut R,
941    max_size: usize,
942) -> Result<Arc<str>, DeserializationError> {
943    let value = read_capped_str(source, "debug string bytes", max_size, |len| {
944        DeserializationError::InvalidValue(alloc::format!(
945            "debug string size {len} exceeds limit {max_size}"
946        ))
947    })?;
948    Ok(Arc::from(value))
949}
950
951fn read_debug_type_indices<R: ByteReader>(
952    source: &mut R,
953    label: &str,
954) -> Result<Vec<DebugTypeIdx>, DeserializationError> {
955    let len = read_bounded_len(source, label, DebugTypeIdx::min_serialized_size())?;
956    source.read_many_iter(len)?.collect::<Result<_, _>>()
957}
958
959#[cfg(test)]
960mod tests {
961    use alloc::string::ToString;
962    use core::{assert_matches, cell::Cell};
963
964    use miden_assembly_syntax::ast::DebugVarLocation;
965    use miden_core::{Felt, Word};
966    use miden_debug_types::{ByteIndex, ColumnNumber, LineNumber, Location, Uri};
967
968    use super::*;
969    use crate::debug_info::{DebugFileIdx, PackageDebugInfoBuilder};
970
971    struct FixedBudgetReader<'a> {
972        inner: miden_core::serde::SliceReader<'a>,
973        max_bytes: usize,
974        largest_requested_element_size: Cell<usize>,
975    }
976
977    impl<'a> FixedBudgetReader<'a> {
978        fn new(bytes: &'a [u8], max_bytes: usize) -> Self {
979            Self {
980                inner: miden_core::serde::SliceReader::new(bytes),
981                max_bytes,
982                largest_requested_element_size: Cell::new(0),
983            }
984        }
985    }
986
987    impl<'a> ByteReader for FixedBudgetReader<'a> {
988        fn read_u8(&mut self) -> Result<u8, DeserializationError> {
989            self.inner.read_u8()
990        }
991
992        fn peek_u8(&self) -> Result<u8, DeserializationError> {
993            self.inner.peek_u8()
994        }
995
996        fn read_slice(&mut self, len: usize) -> Result<&[u8], DeserializationError> {
997            self.inner.read_slice(len)
998        }
999
1000        fn read_array<const N: usize>(&mut self) -> Result<[u8; N], DeserializationError> {
1001            self.inner.read_array()
1002        }
1003
1004        fn check_eor(&self, num_bytes: usize) -> Result<(), DeserializationError> {
1005            self.inner.check_eor(num_bytes)
1006        }
1007
1008        fn has_more_bytes(&self) -> bool {
1009            self.inner.has_more_bytes()
1010        }
1011
1012        fn max_alloc(&self, element_size: usize) -> usize {
1013            self.largest_requested_element_size
1014                .set(self.largest_requested_element_size.get().max(element_size));
1015            if element_size == 0 {
1016                usize::MAX
1017            } else {
1018                self.max_bytes.checked_div(element_size).unwrap_or(0)
1019            }
1020        }
1021    }
1022
1023    fn function_type_bytes(params_len: usize) -> Vec<u8> {
1024        let mut bytes = Vec::new();
1025        bytes.write_u8(TYPE_TAG_FUNCTION);
1026        bytes.write_bool(false);
1027        bytes.write_usize(params_len);
1028        for _ in 0..params_len {
1029            bytes.write_u32(0);
1030        }
1031        bytes
1032    }
1033
1034    fn roundtrip<T: Serializable + Deserializable + PartialEq + core::fmt::Debug>(value: &T) {
1035        let mut bytes = Vec::new();
1036        value.write_into(&mut bytes);
1037        let result = T::read_from(&mut miden_core::serde::SliceReader::new(&bytes)).unwrap();
1038        assert_eq!(value, &result);
1039    }
1040
1041    #[test]
1042    fn pod_row_reader_rejects_byte_length_overflow() {
1043        let mut reader = PodSliceReader::new(&[]);
1044        let result = reader.read_pod_rows::<DebugErrorMessage>(usize::MAX, "test error messages");
1045        let error = result.unwrap_err();
1046
1047        let DeserializationError::InvalidValue(message) = error else {
1048            panic!("expected InvalidValue error");
1049        };
1050        assert!(message.contains("overflows row size"));
1051    }
1052
1053    #[test]
1054    fn pod_row_reader_decodes_certified_rows() {
1055        let expected = DebugErrorMessage::new(42, DebugStringIdx::from(7));
1056        let mut aligned = [0_u64; 2];
1057        aligned.as_mut_bytes()[..size_of::<DebugErrorMessage>()]
1058            .copy_from_slice(expected.as_bytes());
1059        let mut reader = PodSliceReader::new(aligned.as_bytes());
1060        let decoded = reader.read_pod_rows::<DebugErrorMessage>(1, "test error messages").unwrap();
1061
1062        assert_eq!(decoded, [expected]);
1063    }
1064
1065    #[test]
1066    fn debug_variant_min_serialized_size_is_accepted_by_slice_reader() {
1067        let variant = DebugVariantInfo {
1068            name_idx: DebugStringIdx::from(0),
1069            type_idx: None,
1070            payload_offset: None,
1071            discriminant: 0,
1072        };
1073        let mut bytes = Vec::new();
1074        variant.write_into(&mut bytes);
1075
1076        assert_eq!(bytes.len(), DebugVariantInfo::min_serialized_size());
1077
1078        let mut reader = miden_core::serde::SliceReader::new(&bytes);
1079        let mut variants = reader.read_many_iter::<DebugVariantInfo>(1).unwrap();
1080        assert_eq!(variants.next().unwrap().unwrap(), variant);
1081        assert!(variants.next().is_none());
1082    }
1083
1084    #[test]
1085    fn debug_type_initial_capacity_is_bounded_by_in_memory_size() {
1086        const PAYLOAD_BYTES: usize = 256;
1087
1088        let mut bytes = Vec::new();
1089        bytes.write_usize(PAYLOAD_BYTES);
1090        bytes.resize(bytes.len() + PAYLOAD_BYTES, u8::MAX);
1091        let mut reader = FixedBudgetReader::new(&bytes, PAYLOAD_BYTES);
1092
1093        let result =
1094            IndexVec::<DebugTypeIdx, DebugTypeInfo>::read_from_bounded(&mut reader, "debug types");
1095
1096        assert!(result.is_err(), "the first invalid type tag should stop decoding");
1097        assert_eq!(
1098            reader.largest_requested_element_size.get(),
1099            size_of::<DebugTypeInfo>(),
1100            "the speculative capacity must be bounded using the in-memory row size",
1101        );
1102    }
1103
1104    #[test]
1105    fn package_debug_info_trailing_data_error_reports_remaining_bytes() {
1106        const TRAILING: &[u8] = &[0xaa, 0xbb, 0xcc];
1107
1108        let serialized = PackageDebugInfo::default().to_bytes();
1109        let mut reader = miden_core::serde::SliceReader::new(&serialized);
1110        let version = reader.read_u8().unwrap();
1111        let data_len = reader.read_usize().unwrap();
1112        let data = reader.read_slice(data_len).unwrap().to_vec();
1113        assert!(!reader.has_more_bytes());
1114
1115        let mut malformed = Vec::new();
1116        malformed.write_u8(version);
1117        malformed.write_usize(data_len + TRAILING.len());
1118        malformed.write_bytes(&data);
1119        malformed.write_bytes(TRAILING);
1120
1121        let error =
1122            PackageDebugInfo::read_from(&mut miden_core::serde::SliceReader::new(&malformed))
1123                .unwrap_err();
1124        let DeserializationError::InvalidValue(message) = error else {
1125            panic!("expected InvalidValue error");
1126        };
1127        assert!(message.contains("but 3 remain in the buffer"), "{message}");
1128    }
1129
1130    #[test]
1131    fn debug_source_node_trailing_data_error_reports_remaining_bytes() {
1132        const TRAILING: &[u8] = &[0xaa, 0xbb];
1133
1134        let source_node = DebugSourceNode {
1135            exec_node: MastNodeId::new_unchecked(0),
1136            children: Vec::new(),
1137            op_start: 0,
1138            op_end: 0,
1139            asm_ops: Vec::new(),
1140            debug_vars: Vec::new(),
1141            inline_calls: Vec::new(),
1142        };
1143        let serialized = source_node.to_bytes();
1144        let mut reader = miden_core::serde::SliceReader::new(&serialized);
1145        let data_len = reader.read_usize().unwrap();
1146        let data = reader.read_slice(data_len).unwrap().to_vec();
1147        assert!(!reader.has_more_bytes());
1148
1149        let mut malformed = Vec::new();
1150        malformed.write_usize(data_len + TRAILING.len());
1151        malformed.write_bytes(&data);
1152        malformed.write_bytes(TRAILING);
1153
1154        let error =
1155            DebugSourceNode::read_from(&mut miden_core::serde::SliceReader::new(&malformed))
1156                .unwrap_err();
1157        let DeserializationError::InvalidValue(message) = error else {
1158            panic!("expected InvalidValue error");
1159        };
1160        assert!(message.contains("but 2 remain in the buffer"), "{message}");
1161    }
1162
1163    fn roundtrip_debug_info(value: &PackageDebugInfo) -> PackageDebugInfo {
1164        let bytes = value.to_bytes();
1165        let result =
1166            PackageDebugInfo::read_from(&mut miden_core::serde::SliceReader::new(bytes.as_slice()))
1167                .unwrap();
1168        assert_eq!(result.version(), value.version());
1169        assert_eq!(result.strings(), value.strings());
1170        assert_eq!(result.files(), value.files());
1171        assert_eq!(result.locations(), value.locations());
1172        assert_eq!(result.types(), value.types());
1173        assert_eq!(result.functions(), value.functions());
1174        assert_eq!(result.nodes().as_slice(), value.nodes().as_slice());
1175        assert_eq!(result.roots(), value.roots());
1176        assert_eq!(result.error_messages(), value.error_messages());
1177        result
1178    }
1179
1180    #[test]
1181    fn test_debug_types_roundtrip() {
1182        let mut builder = PackageDebugInfoBuilder::default();
1183
1184        let i32_type_idx = builder.add_type(DebugTypeInfo::Primitive(DebugPrimitiveType::I32));
1185        let felt_type_idx = builder.add_type(DebugTypeInfo::Primitive(DebugPrimitiveType::Felt));
1186        builder.add_type(DebugTypeInfo::Pointer { pointee_type_idx: i32_type_idx });
1187        builder.add_type(DebugTypeInfo::Array {
1188            element_type_idx: felt_type_idx,
1189            count: Some(4),
1190        });
1191
1192        let x_idx = builder.add_string("x");
1193        let y_idx = builder.add_string("y");
1194        let point_idx = builder.add_string("Point");
1195        builder.add_type(DebugTypeInfo::Struct {
1196            name_idx: point_idx,
1197            size: 16,
1198            fields: alloc::vec![
1199                DebugFieldInfo {
1200                    name_idx: x_idx,
1201                    type_idx: felt_type_idx,
1202                    offset: 0,
1203                },
1204                DebugFieldInfo {
1205                    name_idx: y_idx,
1206                    type_idx: felt_type_idx,
1207                    offset: 8,
1208                },
1209            ],
1210        });
1211
1212        let status_idx = builder.add_string("Status");
1213        let ok_idx = builder.add_string("Ok");
1214        let err_idx = builder.add_string("Err");
1215        builder.add_type(DebugTypeInfo::Enum {
1216            name_idx: status_idx,
1217            size: 8,
1218            discriminant_type_idx: i32_type_idx,
1219            variants: alloc::vec![
1220                DebugVariantInfo {
1221                    name_idx: ok_idx,
1222                    type_idx: None,
1223                    payload_offset: None,
1224                    discriminant: 0,
1225                },
1226                DebugVariantInfo {
1227                    name_idx: err_idx,
1228                    type_idx: Some(felt_type_idx),
1229                    payload_offset: Some(8),
1230                    discriminant: 1,
1231                },
1232            ],
1233        });
1234
1235        let debug_info = *builder.build();
1236        let result = roundtrip_debug_info(&debug_info);
1237        assert_eq!(result.strings(), debug_info.strings());
1238        assert_eq!(result.types(), debug_info.types());
1239    }
1240
1241    #[test]
1242    fn test_debug_sources_roundtrip() {
1243        let mut builder = PackageDebugInfoBuilder::default();
1244        builder.add_file(Uri::new("test.rs"), None);
1245        builder.add_file(Uri::new("main.rs"), Some([42u8; 32]));
1246
1247        let debug_info = *builder.build();
1248        let result = roundtrip_debug_info(&debug_info);
1249        assert_eq!(result.strings(), debug_info.strings());
1250        assert_eq!(result.files(), debug_info.files());
1251        assert_eq!(result.files()[DebugFileIdx::from(1)].checksum(), Some(&[42u8; 32]));
1252    }
1253
1254    #[test]
1255    fn test_debug_functions_roundtrip() {
1256        let mut builder = PackageDebugInfoBuilder::default();
1257        let name_idx = builder.add_string("test_function");
1258        let file_idx = builder.add_file(Uri::new("test.masm"), None);
1259        let line = LineNumber::new(10).unwrap();
1260        let column = ColumnNumber::new(1).unwrap();
1261        builder.add_function(DebugFunctionInfo::new(
1262            None,
1263            name_idx,
1264            file_idx,
1265            line,
1266            column,
1267            Word::default(),
1268        ));
1269
1270        let debug_info = *builder.build();
1271        let result = roundtrip_debug_info(&debug_info);
1272        assert_eq!(result.functions(), debug_info.functions());
1273    }
1274
1275    #[test]
1276    fn debug_function_v4_wire_bytes_are_stable() {
1277        const EXPECTED_ROW: [u8; size_of::<WireDebugFunctionInfo>()] = [
1278            1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0,
1279            0, 0, 0, 1, 0, 0, 0, 7, 0, 0, 0, 1, 0, 0, 0, 9, 0, 0, 0, 1, 0, 0, 0, 11, 0, 0, 0, 13,
1280            0, 0, 0, 15, 0, 0, 0, 17, 0, 0, 0, 19, 0, 0, 0,
1281        ];
1282
1283        let function = DebugFunctionInfo {
1284            mast_root: Word::new([
1285                Felt::new(1).unwrap(),
1286                Felt::new(2).unwrap(),
1287                Felt::new(3).unwrap(),
1288                Felt::new(4).unwrap(),
1289            ]),
1290            source_node: Some(DebugSourceNodeId::from(7)).into(),
1291            type_idx: Some(DebugTypeIdx::from(9)).into(),
1292            linkage_name_idx: Some(DebugStringIdx::from(11)).into(),
1293            name_idx: DebugStringIdx::from(13),
1294            file_idx: DebugFileIdx::from(15),
1295            line: LineIndex::from(17),
1296            column: ColumnIndex::from(19),
1297        };
1298        let mut builder = PackageDebugInfoBuilder::default();
1299        builder.add_function(function);
1300        let debug_info = builder.build();
1301
1302        let bytes = debug_info.to_bytes();
1303        assert_eq!(bytes[0], 4);
1304        assert!(
1305            bytes.windows(EXPECTED_ROW.len()).any(|window| window == EXPECTED_ROW),
1306            "serialized debug info did not contain the expected function row",
1307        );
1308
1309        let decoded =
1310            PackageDebugInfo::read_from(&mut miden_core::serde::SliceReader::new(&bytes)).unwrap();
1311        assert_eq!(decoded.functions(), [function]);
1312    }
1313
1314    #[test]
1315    fn test_debug_source_graph_roundtrip() {
1316        let mut builder = PackageDebugInfoBuilder::default();
1317        let child = builder
1318            .add_node(DebugSourceNode {
1319                exec_node: MastNodeId::new_unchecked(0),
1320                children: alloc::vec![],
1321                op_start: 0,
1322                op_end: 1,
1323                asm_ops: alloc::vec![],
1324                debug_vars: alloc::vec![],
1325                inline_calls: alloc::vec![],
1326            })
1327            .unwrap();
1328        let root = builder
1329            .add_node(DebugSourceNode {
1330                exec_node: MastNodeId::new_unchecked(1),
1331                children: alloc::vec![child],
1332                op_start: 1,
1333                op_end: 3,
1334                asm_ops: alloc::vec![],
1335                debug_vars: alloc::vec![],
1336                inline_calls: alloc::vec![],
1337            })
1338            .unwrap();
1339        builder.add_root(root);
1340
1341        let debug_info = *builder.build();
1342        let result = roundtrip_debug_info(&debug_info);
1343        assert_eq!(result.nodes().as_slice(), debug_info.nodes().as_slice());
1344        assert_eq!(result.roots(), debug_info.roots());
1345    }
1346
1347    #[test]
1348    fn test_debug_source_metadata_roundtrip() {
1349        let mut builder = PackageDebugInfoBuilder::default();
1350        let location =
1351            Location::new(Uri::new("file://test.masm"), ByteIndex::new(10), ByteIndex::new(14));
1352        let location_idx = builder.add_location(location);
1353        let file_idx = builder.debug_info().locations()[location_idx].file_idx;
1354        let context_name_idx = builder.add_string("test::ctx");
1355        let op_name_idx = builder.add_string("add");
1356        let var_name_idx = builder.add_string("x");
1357        let function_name_idx = builder.add_string("callee");
1358        let function_idx = builder.add_function(DebugFunctionInfo::new(
1359            None,
1360            function_name_idx,
1361            file_idx,
1362            LineNumber::new(10).unwrap(),
1363            ColumnNumber::new(5).unwrap(),
1364            Word::default(),
1365        ));
1366
1367        let root = builder
1368            .add_node(DebugSourceNode {
1369                exec_node: MastNodeId::new_unchecked(0),
1370                children: alloc::vec![],
1371                op_start: 0,
1372                op_end: 3,
1373                asm_ops: alloc::vec![DebugSourceAsmOp::new(
1374                    2,
1375                    Some(location_idx),
1376                    context_name_idx,
1377                    op_name_idx,
1378                    1,
1379                )],
1380                debug_vars: alloc::vec![DebugSourceVar {
1381                    op_idx: 2,
1382                    name_idx: var_name_idx,
1383                    type_id: None,
1384                    arg_idx: None,
1385                    location_idx: None,
1386                    value_location: DebugVarLocation::Stack(0),
1387                }],
1388                inline_calls: alloc::vec![DebugSourceInlineCall {
1389                    op_idx: 2,
1390                    op_end: 3,
1391                    callee_idx: function_idx,
1392                    loc_idx: location_idx,
1393                }],
1394            })
1395            .unwrap();
1396        builder.add_root(root);
1397
1398        let debug_info = *builder.build();
1399        let result = roundtrip_debug_info(&debug_info);
1400        assert_eq!(result.nodes().as_slice(), debug_info.nodes().as_slice());
1401        assert_eq!(result.locations(), debug_info.locations());
1402        assert_eq!(result.functions(), debug_info.functions());
1403        assert_eq!(result.get_string(context_name_idx).as_deref(), Some("test::ctx"));
1404        assert_eq!(result.get_location(location_idx), debug_info.get_location(location_idx));
1405    }
1406
1407    #[test]
1408    fn test_debug_source_locations_are_deduplicated() {
1409        let mut builder = PackageDebugInfoBuilder::default();
1410        let location =
1411            Location::new(Uri::new("file://test.masm"), ByteIndex::new(10), ByteIndex::new(14));
1412        let first_location_idx = builder.add_location(location.clone());
1413        let second_location_idx = builder.add_location(location);
1414        assert_eq!(first_location_idx, second_location_idx);
1415        assert_eq!(builder.debug_info().locations().len(), 1);
1416
1417        let context_name_idx = builder.add_string("test::ctx");
1418        let push_name_idx = builder.add_string("push.1");
1419        let add_name_idx = builder.add_string("add");
1420        let root = builder
1421            .add_node(DebugSourceNode {
1422                exec_node: MastNodeId::new_unchecked(0),
1423                children: alloc::vec![],
1424                op_start: 0,
1425                op_end: 2,
1426                asm_ops: alloc::vec![
1427                    DebugSourceAsmOp::new(
1428                        0,
1429                        Some(first_location_idx),
1430                        context_name_idx,
1431                        push_name_idx,
1432                        1,
1433                    ),
1434                    DebugSourceAsmOp::new(
1435                        1,
1436                        Some(second_location_idx),
1437                        context_name_idx,
1438                        add_name_idx,
1439                        1,
1440                    ),
1441                ],
1442                debug_vars: alloc::vec![],
1443                inline_calls: alloc::vec![],
1444            })
1445            .unwrap();
1446        builder.add_root(root);
1447
1448        let debug_info = *builder.build();
1449        let result = roundtrip_debug_info(&debug_info);
1450        assert_eq!(result.locations().len(), 1);
1451        assert_eq!(
1452            result.source_node(root).unwrap().asm_ops,
1453            debug_info.source_node(root).unwrap().asm_ops
1454        );
1455    }
1456
1457    #[test]
1458    fn test_debug_source_strings_are_deduplicated() {
1459        let mut builder = PackageDebugInfoBuilder::default();
1460        let context_name_idx = builder.add_string("test::ctx");
1461        let same_context_name_idx = builder.add_string("test::ctx");
1462        let add_name_idx = builder.add_string("add");
1463        let same_add_name_idx = builder.add_string("add");
1464        let mul_name_idx = builder.add_string("mul");
1465        let other_context_idx = builder.add_string("test::other");
1466        assert_eq!(context_name_idx, same_context_name_idx);
1467        assert_eq!(add_name_idx, same_add_name_idx);
1468
1469        let root = builder
1470            .add_node(DebugSourceNode {
1471                exec_node: MastNodeId::new_unchecked(0),
1472                children: alloc::vec![],
1473                op_start: 0,
1474                op_end: 3,
1475                asm_ops: alloc::vec![
1476                    DebugSourceAsmOp::new(0, None, context_name_idx, add_name_idx, 1,),
1477                    DebugSourceAsmOp::new(1, None, same_context_name_idx, mul_name_idx, 1,),
1478                    DebugSourceAsmOp::new(2, None, other_context_idx, same_add_name_idx, 1,),
1479                ],
1480                debug_vars: alloc::vec![],
1481                inline_calls: alloc::vec![],
1482            })
1483            .unwrap();
1484        builder.add_root(root);
1485
1486        let debug_info = *builder.build();
1487        let result = roundtrip_debug_info(&debug_info);
1488        assert_eq!(result.strings(), debug_info.strings());
1489        assert_eq!(
1490            result.source_node(root).unwrap().asm_ops,
1491            debug_info.source_node(root).unwrap().asm_ops
1492        );
1493    }
1494
1495    #[test]
1496    fn test_debug_error_messages_roundtrip() {
1497        let mut builder = PackageDebugInfoBuilder::default();
1498        assert!(builder.add_error_message(42, Arc::from("assertion message")));
1499
1500        let debug_info = *builder.build();
1501        let result = roundtrip_debug_info(&debug_info);
1502        assert_eq!(result.error_messages(), debug_info.error_messages());
1503        assert_eq!(result.error_message(42).as_deref(), Some("assertion message"));
1504    }
1505
1506    #[test]
1507    fn test_empty_debug_info_roundtrip() {
1508        let debug_info = PackageDebugInfo::default();
1509        let result = roundtrip_debug_info(&debug_info);
1510        assert!(result.strings().is_empty());
1511        assert!(result.files().is_empty());
1512        assert!(result.locations().is_empty());
1513        assert!(result.types().is_empty());
1514        assert!(result.functions().is_empty());
1515        assert!(result.nodes().is_empty());
1516        assert!(result.roots().is_empty());
1517        assert!(result.error_messages().is_empty());
1518    }
1519
1520    #[test]
1521    fn test_all_primitive_types_roundtrip() {
1522        let mut builder = PackageDebugInfoBuilder::default();
1523
1524        for primitive in [
1525            DebugPrimitiveType::Void,
1526            DebugPrimitiveType::Bool,
1527            DebugPrimitiveType::I8,
1528            DebugPrimitiveType::U8,
1529            DebugPrimitiveType::I16,
1530            DebugPrimitiveType::U16,
1531            DebugPrimitiveType::I32,
1532            DebugPrimitiveType::U32,
1533            DebugPrimitiveType::I64,
1534            DebugPrimitiveType::U64,
1535            DebugPrimitiveType::I128,
1536            DebugPrimitiveType::U128,
1537            DebugPrimitiveType::F32,
1538            DebugPrimitiveType::F64,
1539            DebugPrimitiveType::Felt,
1540            DebugPrimitiveType::Word,
1541            DebugPrimitiveType::U256,
1542        ] {
1543            builder.add_type(DebugTypeInfo::Primitive(primitive));
1544        }
1545
1546        let debug_info = *builder.build();
1547        let result = roundtrip_debug_info(&debug_info);
1548        assert_eq!(result.types(), debug_info.types());
1549    }
1550
1551    #[test]
1552    fn test_function_type_roundtrip() {
1553        let ty = DebugTypeInfo::Function {
1554            return_type_idx: Some(DebugTypeIdx::from(0)),
1555            param_type_indices: alloc::vec![
1556                DebugTypeIdx::from(1),
1557                DebugTypeIdx::from(2),
1558                DebugTypeIdx::from(3)
1559            ],
1560        };
1561        roundtrip(&ty);
1562
1563        let void_fn = DebugTypeInfo::Function {
1564            return_type_idx: None,
1565            param_type_indices: alloc::vec![],
1566        };
1567        roundtrip(&void_fn);
1568    }
1569
1570    #[test]
1571    fn test_file_info_with_checksum_roundtrip() {
1572        let file = DebugFileInfo::new(DebugStringIdx::from(0)).with_checksum([42u8; 32]);
1573        roundtrip(&file);
1574    }
1575
1576    #[test]
1577    fn test_debug_info_v2_is_rejected() {
1578        let bytes = [2];
1579        let mut reader = miden_core::serde::SliceReader::new(&bytes);
1580        let error = PackageDebugInfo::read_from(&mut reader).unwrap_err();
1581        let DeserializationError::InvalidValue(message) = error else {
1582            panic!("expected InvalidValue error");
1583        };
1584        assert!(message.contains("unsupported debug_info version: 2"));
1585    }
1586
1587    #[test]
1588    fn inline_range_wire_bytes_are_stable_and_reversed_ranges_are_rejected() {
1589        let row = DebugSourceInlineCall {
1590            op_idx: 2,
1591            op_end: 100_000,
1592            callee_idx: DebugFunctionIdx::from(3),
1593            loc_idx: DebugLocIdx::from(4),
1594        };
1595        let bytes = row.to_bytes();
1596        assert_eq!(bytes, [2, 0, 0, 0, 160, 134, 1, 0, 3, 0, 0, 0, 4, 0, 0, 0]);
1597        assert_eq!(DebugSourceInlineCall::read_from_bytes(&bytes).unwrap(), row);
1598        assert!(row.contains_operation(2));
1599        assert!(row.contains_operation(99_999));
1600        assert!(!row.contains_operation(100_000));
1601        let mut invalid = bytes;
1602        invalid[4..8].copy_from_slice(&1u32.to_le_bytes());
1603        assert!(DebugSourceInlineCall::read_from_bytes(&invalid).is_err());
1604        assert!(PackageDebugInfo::read_from_bytes(&[3]).is_err());
1605    }
1606
1607    #[test]
1608    fn long_inline_ranges_roundtrip_without_expanding_into_operation_rows() {
1609        let mut builder = PackageDebugInfoBuilder::default();
1610        let source_id = builder
1611            .add_node(DebugSourceNode {
1612                exec_node: MastNodeId::new_unchecked(0),
1613                children: Vec::new(),
1614                op_start: 0,
1615                op_end: 1_000_000,
1616                asm_ops: Vec::new(),
1617                debug_vars: Vec::new(),
1618                inline_calls: (0..7)
1619                    .map(|index| DebugSourceInlineCall {
1620                        op_idx: 0,
1621                        op_end: 1_000_000,
1622                        callee_idx: DebugFunctionIdx::from(index),
1623                        loc_idx: DebugLocIdx::from(index),
1624                    })
1625                    .collect(),
1626            })
1627            .unwrap();
1628        let bytes = builder.build().to_bytes();
1629        assert!(bytes.len() < 256);
1630        let decoded = PackageDebugInfo::read_from_bytes(&bytes).unwrap();
1631        assert_eq!(decoded.source_node(source_id).unwrap().inline_calls.len(), 7);
1632        assert_eq!(decoded.inline_calls_for_operation(source_id, 999_999).count(), 7);
1633        assert_eq!(decoded.inline_calls_for_operation(source_id, 1_000_000).count(), 0);
1634    }
1635
1636    #[test]
1637    fn test_debug_info_payload_bounds() {
1638        let bytes = PackageDebugInfo::default().to_bytes();
1639
1640        let mut reader = FixedBudgetReader::new(&bytes, 1);
1641        let error = PackageDebugInfo::read_from(&mut reader).unwrap_err();
1642        let DeserializationError::InvalidValue(message) = error else {
1643            panic!("expected InvalidValue error");
1644        };
1645        assert!(message.contains("package debug info"));
1646        assert!(message.contains("exceeds budget"));
1647
1648        let mut reader = FixedBudgetReader::new(&bytes, 1);
1649        let error = PackageDebugInfo::read_from_unmetered(&mut reader).unwrap_err();
1650        let DeserializationError::InvalidValue(message) = error else {
1651            panic!("expected InvalidValue error");
1652        };
1653        assert!(message.contains("package debug info"));
1654        assert!(message.contains("exceeds budget"));
1655
1656        let mut reader = FixedBudgetReader::new(&bytes, bytes.len());
1657        let result = PackageDebugInfo::read_from(&mut reader).unwrap();
1658        assert!(result.nodes().is_empty());
1659    }
1660
1661    #[test]
1662    fn checked_encoding_matches_standard_decoder_limits() {
1663        let mut builder = PackageDebugInfoBuilder::default();
1664        builder.add_string("hello");
1665        builder.add_type(DebugTypeInfo::Primitive(DebugPrimitiveType::Felt));
1666        let debug = builder.build();
1667        let bytes = debug.to_bytes_with_standard_limits().unwrap();
1668        assert_eq!(bytes, debug.to_bytes());
1669        assert_eq!(PackageDebugInfo::read_from_bytes(&bytes).unwrap(), *debug);
1670
1671        for limits in [
1672            PackageDebugInfoDecodeLimits {
1673                payload_size: 0,
1674                ..PackageDebugInfoDecodeLimits::BOUNDED
1675            },
1676            PackageDebugInfoDecodeLimits {
1677                string_rows: 0,
1678                ..PackageDebugInfoDecodeLimits::BOUNDED
1679            },
1680            PackageDebugInfoDecodeLimits {
1681                string_size: 0,
1682                ..PackageDebugInfoDecodeLimits::BOUNDED
1683            },
1684            PackageDebugInfoDecodeLimits {
1685                type_rows: 0,
1686                ..PackageDebugInfoDecodeLimits::BOUNDED
1687            },
1688        ] {
1689            let encode_error = DeserializationError::InvalidValue(
1690                debug.to_bytes_with_limits(limits).unwrap_err().to_string(),
1691            );
1692            let mut reader = miden_core::serde::SliceReader::new(&bytes);
1693            let decode_error =
1694                PackageDebugInfo::read_from_with_limits(&mut reader, limits).unwrap_err();
1695            assert_eq!(encode_error.to_string(), decode_error.to_string());
1696        }
1697    }
1698
1699    #[test]
1700    fn package_debug_info_decodes_merged_dependency_tables() {
1701        // Dynamic exec currently imports entire dependency tables. Each dependency is readable
1702        // on its own, but their distinct strings together exceed the former 32 MiB limit.
1703        const STRING_SIZE: usize = 4096;
1704        const STRING_COUNT: usize = 18 * 1024 * 1024 / STRING_SIZE;
1705        let mut merged = PackageDebugInfoBuilder::default();
1706        for dependency in ['a', 'b'] {
1707            let mut builder = PackageDebugInfoBuilder::default();
1708            for index in 0..STRING_COUNT {
1709                let mut prefix = alloc::format!("{dependency}:{index:04}");
1710                let padding = "x".repeat(STRING_SIZE - prefix.len());
1711                prefix.push_str(&padding);
1712                builder.add_string(prefix);
1713            }
1714            let bytes = builder.build().to_bytes();
1715            let debug = PackageDebugInfo::read_from_bytes(&bytes)
1716                .expect("each dependency's debug tables must be readable");
1717            debug.merge_tables_into(&mut merged).unwrap();
1718        }
1719        let merged = merged.build();
1720        let bytes = merged.to_bytes();
1721        let decoded = PackageDebugInfo::read_from_bytes(&bytes)
1722            .expect("merged dependency debug tables must remain readable");
1723        assert_eq!(decoded.strings().len(), 2 * STRING_COUNT);
1724        assert_eq!(decoded, *merged);
1725    }
1726
1727    #[test]
1728    fn package_debug_info_decodes_merged_dependency_string_rows() {
1729        let mut merged = PackageDebugInfoBuilder::default();
1730        for dependency in ['a', 'b'] {
1731            let mut builder = PackageDebugInfoBuilder::default();
1732            for index in 0..60_000 {
1733                builder.add_string(alloc::format!("{dependency}:{index}"));
1734            }
1735            let bytes = builder.build().to_bytes();
1736            let debug = PackageDebugInfo::read_from_bytes(&bytes).unwrap();
1737            debug.merge_tables_into(&mut merged).unwrap();
1738        }
1739        let merged = merged.build();
1740        let decoded = PackageDebugInfo::read_from_bytes(&merged.to_bytes())
1741            .expect("merged string tables from readable dependencies must remain readable");
1742        assert_eq!(decoded.strings().len(), 120_000);
1743        assert_eq!(decoded, *merged);
1744    }
1745
1746    #[test]
1747    fn package_debug_info_rejects_payload_over_standard_limit() {
1748        let payload_size = MAX_DEBUG_INFO_PAYLOAD_SIZE + 1;
1749        let mut bytes = Vec::new();
1750        bytes.write_u8(DEBUG_INFO_VERSION);
1751        bytes.write_usize(payload_size);
1752        bytes.resize(bytes.len() + payload_size, 0);
1753
1754        let error = PackageDebugInfo::read_from_bytes(&bytes).unwrap_err();
1755        let DeserializationError::InvalidValue(message) = error else {
1756            panic!("expected InvalidValue error");
1757        };
1758        assert!(message.contains("package debug info payload size"), "{message}");
1759        assert!(message.contains("exceeds limit"), "{message}");
1760    }
1761
1762    #[test]
1763    fn unmetered_package_debug_info_decode_ignores_fixed_limits() {
1764        let oversized_string = "x".repeat(MAX_DEBUG_INFO_STRING_SIZE + 1);
1765        let mut builder = PackageDebugInfoBuilder::default();
1766        builder.add_string(oversized_string.clone());
1767        let bytes = builder.build().to_bytes();
1768
1769        let error = PackageDebugInfo::read_from_bytes(&bytes).unwrap_err();
1770        let DeserializationError::InvalidValue(message) = error else {
1771            panic!("expected InvalidValue error");
1772        };
1773        assert!(message.contains("debug string size"));
1774        assert!(message.contains("exceeds limit"));
1775
1776        let decoded = PackageDebugInfo::read_from_bytes_unmetered(&bytes).unwrap();
1777        assert_eq!(decoded.strings().len(), 1);
1778        assert_eq!(decoded.strings()[DebugStringIdx::from(0)].as_ref(), oversized_string);
1779    }
1780
1781    #[test]
1782    fn checked_debug_encoding_matches_normal_encoding_for_readable_data() {
1783        let mut builder = PackageDebugInfoBuilder::default();
1784        builder.add_string("source.rs");
1785        let info = builder.build();
1786        let bytes = info.to_bytes_with_standard_limits().unwrap();
1787        assert_eq!(bytes, info.to_bytes());
1788        assert!(PackageDebugInfo::read_from_bytes(&bytes).is_ok());
1789    }
1790
1791    #[test]
1792    fn checked_debug_encoding_rejects_oversized_strings() {
1793        let mut builder = PackageDebugInfoBuilder::default();
1794        builder.add_string("x".repeat(MAX_DEBUG_INFO_STRING_SIZE + 1));
1795        assert_matches!(
1796            builder.build().to_bytes_with_standard_limits(),
1797            Err(super::super::DebugInfoEncodingError::LimitExceeded {
1798                resource: "debug string size",
1799                ..
1800            })
1801        );
1802    }
1803
1804    #[test]
1805    fn checked_debug_encoding_rejects_oversized_payloads() {
1806        let mut builder = PackageDebugInfoBuilder::default();
1807        for index in 0..((MAX_DEBUG_INFO_PAYLOAD_SIZE / MAX_DEBUG_INFO_STRING_SIZE) + 1) {
1808            let mut string = format!("{index:08}");
1809            string.push_str(&"x".repeat(MAX_DEBUG_INFO_STRING_SIZE - string.len()));
1810            builder.add_string(string);
1811        }
1812        let info = builder.build();
1813        assert_matches!(
1814            info.to_bytes_with_standard_limits(),
1815            Err(super::super::DebugInfoEncodingError::LimitExceeded {
1816                resource: "package debug info payload size",
1817                ..
1818            })
1819        );
1820        assert!(PackageDebugInfo::read_from_bytes(&info.to_bytes()).is_err());
1821    }
1822
1823    #[test]
1824    fn test_debug_info_rejects_truncated_string_table() {
1825        let mut payload = Vec::new();
1826        payload.write_usize(2);
1827
1828        let mut bytes = Vec::new();
1829        bytes.write_u8(DEBUG_INFO_VERSION);
1830        bytes.write_usize(payload.len());
1831        bytes.write_bytes(&payload);
1832
1833        let mut reader = miden_core::serde::SliceReader::new(&bytes);
1834        let error = PackageDebugInfo::read_from(&mut reader).unwrap_err();
1835        let DeserializationError::InvalidValue(message) = error else {
1836            panic!("expected InvalidValue error");
1837        };
1838        assert!(message.contains("debug_info strings count 2"));
1839        assert!(message.contains("exceeds budget"));
1840    }
1841
1842    #[test]
1843    fn test_function_params_bounds() {
1844        let too_many = function_type_bytes(2);
1845        let mut reader = FixedBudgetReader::new(&too_many, 4);
1846        let error = DebugTypeInfo::read_from(&mut reader).unwrap_err();
1847        assert!(matches!(error, DeserializationError::InvalidValue(_)));
1848
1849        let ok = function_type_bytes(1);
1850        let mut reader = FixedBudgetReader::new(&ok, 4);
1851        let ty = DebugTypeInfo::read_from(&mut reader).unwrap();
1852        match ty {
1853            DebugTypeInfo::Function { param_type_indices, .. } => {
1854                assert_eq!(param_type_indices.len(), 1);
1855            },
1856            _ => panic!("expected function type"),
1857        }
1858    }
1859}