Skip to main content

vyre_emit_metal/
lib.rs

1#![allow(
2    clippy::doc_lazy_continuation,
3    clippy::double_must_use,
4    clippy::manual_div_ceil,
5    clippy::needless_range_loop,
6    clippy::collapsible_if,
7    clippy::match_like_matches_macro,
8    clippy::redundant_closure,
9    clippy::too_many_arguments,
10    clippy::nonminimal_bool,
11    clippy::derivable_impls
12)]
13//! Metal Shading Language emitter for vyre `KernelDescriptor`.
14//!
15//! This crate is the first native-Metal artifact seam. It deliberately reuses
16//! the canonical LEGO path:
17//!
18//! ```text
19//! Program -> vyre-lower::pre_emit -> KernelDescriptor
20//! KernelDescriptor -> vyre-emit-naga -> naga::Module
21//! naga::Module -> naga::back::msl -> MSL native_module artifact
22//! ```
23//!
24//! It does not own runtime dispatch, device probing, buffer residency, or
25//! semantic lowering. Those stay in the driver and lowerer layers.
26
27use std::collections::BTreeMap;
28
29use naga::back::msl::{BindTarget, EntryPointResources, Options, PipelineOptions};
30use naga::valid::{Capabilities, ValidationFlags, Validator};
31use naga::{AddressSpace, StorageAccess};
32use thiserror::Error;
33use vyre_lower::{BindingSlot, KernelDescriptor, MemoryClass};
34
35/// `native_module` artifact schema version.
36pub const METAL_ARTIFACT_SCHEMA: u32 = 3;
37
38/// Default MSL target version used for source emission.
39pub const DEFAULT_MSL_VERSION: (u8, u8) = (2, 4);
40
41/// Metal emission options.
42#[derive(Clone, Debug, Eq, PartialEq)]
43pub struct MetalEmitOptions {
44    /// Target MSL version.
45    pub lang_version: (u8, u8),
46    /// Entry point to emit.
47    pub entry_point: String,
48    /// Include deterministic MSL source in the JSON artifact.
49    pub include_source: bool,
50}
51
52impl Default for MetalEmitOptions {
53    fn default() -> Self {
54        Self {
55            lang_version: DEFAULT_MSL_VERSION,
56            entry_point: "main".to_string(),
57            include_source: true,
58        }
59    }
60}
61
62/// Metal emission failure.
63#[derive(Debug, Error)]
64pub enum EmitError {
65    /// The shared Naga emitter rejected the descriptor.
66    #[error("Naga emission failed before Metal MSL writing: {0}. Fix: extend vyre-emit-naga descriptor emission instead of forking Metal-local lowering.")]
67    NagaEmit(String),
68    /// Naga validation rejected the module.
69    #[error("Naga validation failed before Metal MSL writing: {0}. Fix: repair the shared descriptor/Naga emission path before emitting native_module artifacts.")]
70    NagaValidation(String),
71    /// The requested entry point is missing or not compute.
72    #[error("Metal entry point `{entry_point}` is unavailable for compute emission: {reason}. Fix: emit a compute KernelDescriptor with entry point `main` or pass the correct entry point name.")]
73    EntryPoint {
74        /// Requested entry-point name.
75        entry_point: String,
76        /// Validation reason that made the entry point unusable.
77        reason: String,
78    },
79    /// The MSL writer rejected the validated module.
80    #[error("MSL writer failed: {0}. Fix: extend the shared Naga-to-MSL emission seam or lower unsupported constructs before Metal artifact emission.")]
81    MslWriter(String),
82    /// A binding could not be represented in Metal's flat buffer namespace.
83    #[error("Metal binding map failed for resource group {group} binding {binding}: {reason}. Fix: keep Metal buffer indices within u8::MAX or add argument-buffer metadata before native_module emission.")]
84    BindingMap {
85        /// Descriptor resource group.
86        group: u32,
87        /// Descriptor binding within the resource group.
88        binding: u32,
89        /// Mapping failure reason.
90        reason: String,
91    },
92    /// Descriptor hashing failed.
93    #[error("KernelDescriptor artifact hash failed: {0}. Fix: keep KernelDescriptor serde stable before using it as native_module artifact identity.")]
94    DescriptorHash(String),
95    /// Artifact serialization failed.
96    #[error("Metal native_module JSON serialization failed: {0}. Fix: keep artifact metadata serde-compatible and deterministic.")]
97    ArtifactSerialization(String),
98    /// Program pre-emission lowering failed.
99    #[error("Program pre-emission lowering failed before Metal artifact emission: {0}. Fix: route through vyre-lower::pre_emit and repair the neutral descriptor mapping.")]
100    PreEmit(String),
101}
102
103/// ABI binding metadata stored in a Metal artifact.
104#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
105pub struct MetalBindingMetadata {
106    /// Vyre binding name.
107    pub name: String,
108    /// Descriptor slot.
109    pub slot: u32,
110    /// MSL buffer index.
111    pub metal_buffer_index: u8,
112    /// Element type as stable debug text until the shared artifact schema owns
113    /// a typed cross-emitter field.
114    pub element_type: String,
115    /// Static element count when known.
116    pub element_count: Option<u32>,
117    /// Lowered memory class.
118    pub memory_class: String,
119    /// Read/write visibility.
120    pub visibility: String,
121}
122
123/// Threadgroup-memory metadata stored in a Metal artifact.
124#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
125pub struct MetalThreadgroupMemoryMetadata {
126    /// Vyre binding name.
127    pub name: String,
128    /// Descriptor slot.
129    pub slot: u32,
130    /// Metal threadgroup-memory argument index.
131    pub threadgroup_index: u8,
132    /// Unaligned byte length required by the lowered workgroup binding.
133    pub byte_length: u64,
134    /// Metal-compatible 16-byte aligned allocation length.
135    pub aligned_byte_length: u64,
136}
137
138/// Structured `native_module` artifact emitted by this crate.
139#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
140pub struct MetalArtifact {
141    /// Artifact schema version.
142    pub schema: u32,
143    /// Artifact target name used by `xtask compile --to native_module`.
144    pub target: String,
145    /// Emitter crate/version identity.
146    pub emitter: String,
147    /// MSL version.
148    pub msl_version: String,
149    /// Kernel entry point.
150    pub entry_point: String,
151    /// Canonical descriptor digest.
152    pub descriptor_blake3: String,
153    /// MSL source digest.
154    pub msl_blake3: String,
155    /// Dispatch workgroup shape.
156    pub workgroup_size: [u32; 3],
157    /// Binding ABI metadata.
158    pub bindings: Vec<MetalBindingMetadata>,
159    /// Metal buffer index used for Naga's `_buffer_sizes` sidecar when MSL
160    /// bounds checks require runtime buffer lengths.
161    pub sizes_buffer_index: Option<u8>,
162    /// Threadgroup-memory arguments emitted by Naga for `var<workgroup>`
163    /// globals. Runtime dispatch must allocate each index before launch.
164    pub threadgroup_memories: Vec<MetalThreadgroupMemoryMetadata>,
165    /// Generated MSL source.
166    pub msl: String,
167}
168
169/// Emit MSL source from a descriptor using default Metal options.
170///
171/// # Errors
172///
173/// Returns [`EmitError`] when Naga emission, validation, binding-map creation,
174/// or MSL writing fails.
175pub fn emit(desc: &KernelDescriptor) -> Result<String, EmitError> {
176    emit_with_options(desc, &MetalEmitOptions::default())
177}
178
179/// Emit MSL source from a descriptor using explicit options.
180///
181/// # Errors
182///
183/// Returns [`EmitError`] when Naga emission, validation, binding-map creation,
184/// or MSL writing fails.
185pub fn emit_with_options(
186    desc: &KernelDescriptor,
187    options: &MetalEmitOptions,
188) -> Result<String, EmitError> {
189    emit_artifact_with_options(desc, options).map(|artifact| artifact.msl)
190}
191
192/// Emit a structured `native_module` artifact.
193///
194/// # Errors
195///
196/// Returns [`EmitError`] when MSL emission or artifact serialization metadata
197/// construction fails.
198pub fn emit_artifact(desc: &KernelDescriptor) -> Result<MetalArtifact, EmitError> {
199    emit_artifact_with_options(desc, &MetalEmitOptions::default())
200}
201
202/// Emit a structured `native_module` artifact with explicit options.
203///
204/// # Errors
205///
206/// Returns [`EmitError`] when MSL emission or artifact serialization metadata
207/// construction fails.
208pub fn emit_artifact_with_options(
209    desc: &KernelDescriptor,
210    options: &MetalEmitOptions,
211) -> Result<MetalArtifact, EmitError> {
212    let index_map = metal_binding_indices(desc)?;
213    let bindings = metal_bindings(desc, &index_map.by_slot)?;
214    let threadgroup_memories = metal_threadgroup_memories(desc)?;
215    let module =
216        vyre_emit_naga::emit(desc).map_err(|error| EmitError::NagaEmit(error.to_string()))?;
217    let (msl, entry_point, sizes_buffer_index) =
218        emit_from_naga_module_with_resource_indices(&module, options, &index_map.by_resource)?;
219    let descriptor_blake3 = descriptor_blake3(desc)?;
220    let msl_blake3 = hex_encode(blake3::hash(msl.as_bytes()).as_bytes());
221    Ok(MetalArtifact {
222        schema: METAL_ARTIFACT_SCHEMA,
223        target: "native_module".to_string(),
224        emitter: format!("vyre-emit-metal/{}", env!("CARGO_PKG_VERSION")),
225        msl_version: format!("{}.{}", options.lang_version.0, options.lang_version.1),
226        entry_point,
227        descriptor_blake3,
228        msl_blake3,
229        workgroup_size: desc.dispatch.workgroup_size,
230        bindings,
231        sizes_buffer_index,
232        threadgroup_memories,
233        msl: if options.include_source {
234            msl
235        } else {
236            String::new()
237        },
238    })
239}
240
241/// Emit a deterministic JSON `native_module` artifact.
242///
243/// # Errors
244///
245/// Returns [`EmitError`] when emission or JSON serialization fails.
246pub fn emit_artifact_json(desc: &KernelDescriptor) -> Result<String, EmitError> {
247    artifact_to_json(&emit_artifact(desc)?)
248}
249
250/// Emit deterministic JSON bytes for `xtask compile --to native_module`.
251///
252/// # Errors
253///
254/// Same as [`emit_artifact_json`].
255pub fn emit_artifact_bytes(desc: &KernelDescriptor) -> Result<Vec<u8>, EmitError> {
256    let mut bytes = emit_artifact_json(desc)?.into_bytes();
257    bytes.push(b'\n');
258    Ok(bytes)
259}
260
261/// Emit MSL from an already-constructed Naga module.
262///
263/// This is the narrow seam used by tests and future direct driver code that
264/// wants to inspect or transform Naga before Metal source generation.
265///
266/// # Errors
267///
268/// Returns [`EmitError`] when validation, resource mapping, or MSL writing
269/// fails.
270pub fn emit_from_naga_module(
271    module: &naga::Module,
272    options: &MetalEmitOptions,
273) -> Result<String, EmitError> {
274    emit_from_naga_module_with_entry_name(module, options).map(|(source, _, _)| source)
275}
276
277fn emit_from_naga_module_with_entry_name(
278    module: &naga::Module,
279    options: &MetalEmitOptions,
280) -> Result<(String, String, Option<u8>), EmitError> {
281    let resource_indices = metal_resource_indices_from_module(module)?;
282    emit_from_naga_module_with_resource_indices(module, options, &resource_indices)
283}
284
285fn emit_from_naga_module_with_resource_indices(
286    module: &naga::Module,
287    options: &MetalEmitOptions,
288    resource_indices: &BTreeMap<(u32, u32), u8>,
289) -> Result<(String, String, Option<u8>), EmitError> {
290    let entry_index = ensure_compute_entry_point(module, &options.entry_point)?;
291
292    let mut validator = Validator::new(ValidationFlags::all(), Capabilities::all());
293    let info = validator
294        .validate(module)
295        .map_err(|error| EmitError::NagaValidation(format!("{error:?}")))?;
296
297    let mut msl_options = Options::default();
298    msl_options.lang_version = options.lang_version;
299    msl_options.fake_missing_bindings = false;
300    let resource_map =
301        metal_entry_point_resource_map(module, &options.entry_point, resource_indices)?;
302    msl_options.per_entry_point_map = resource_map.per_entry_point;
303
304    let pipeline_options = PipelineOptions::default();
305    let (source, translation) =
306        naga::back::msl::write_string(module, &info, &msl_options, &pipeline_options)
307            .map_err(|error| EmitError::MslWriter(format!("{error:?}")))?;
308    let entry_point = translation
309        .entry_point_names
310        .get(entry_index)
311        .ok_or_else(|| EmitError::EntryPoint {
312            entry_point: options.entry_point.clone(),
313            reason: "MSL translation omitted the entry point name mapping".to_string(),
314        })?
315        .as_ref()
316        .map_err(|error| EmitError::EntryPoint {
317            entry_point: options.entry_point.clone(),
318            reason: format!("MSL writer rejected the entry point name: {error:?}"),
319        })?
320        .clone();
321    Ok((source, entry_point, resource_map.sizes_buffer_index))
322}
323
324fn ensure_compute_entry_point(
325    module: &naga::Module,
326    entry_point: &str,
327) -> Result<usize, EmitError> {
328    let Some((index, ep)) = module
329        .entry_points
330        .iter()
331        .enumerate()
332        .find(|(_index, ep)| ep.name == entry_point)
333    else {
334        return Err(EmitError::EntryPoint {
335            entry_point: entry_point.to_string(),
336            reason: "entry point name was not present in the Naga module".to_string(),
337        });
338    };
339    if ep.stage != naga::ShaderStage::Compute {
340        return Err(EmitError::EntryPoint {
341            entry_point: entry_point.to_string(),
342            reason: format!("stage was {:?}, not Compute", ep.stage),
343        });
344    }
345    Ok(index)
346}
347
348fn metal_entry_point_resource_map(
349    module: &naga::Module,
350    entry_point: &str,
351    resource_indices: &BTreeMap<(u32, u32), u8>,
352) -> Result<MetalResourceMap, EmitError> {
353    let mut resources = EntryPointResources::default();
354    let mut max_buffer = None::<u8>;
355    for (_handle, global) in module.global_variables.iter() {
356        let Some(binding) = global.binding else {
357            continue;
358        };
359        let buffer = resource_indices
360            .get(&(binding.group, binding.binding))
361            .copied()
362            .ok_or_else(|| EmitError::BindingMap {
363                group: binding.group,
364                binding: binding.binding,
365                reason: "resource binding was not present in the dense Metal buffer index map"
366                    .to_string(),
367            })?;
368        // Naga MSL backend uses `mutable` to choose between `const device T*`
369        // (read-only) and `device T*` (read-write). We derive the flag from
370        // the address space recorded on the global variable by vyre-emit-naga:
371        // `AddressSpace::Storage { access: LOAD }` is read-only; any access
372        // that includes STORE is mutable. Hardcoding `true` prevents Metal's
373        // compiler from alias-analysing read-only inputs and can produce
374        // undefined behaviour under strict Metal validation.
375        let is_read_only = matches!(global.space, AddressSpace::Storage { access } if access == StorageAccess::LOAD);
376        resources.resources.insert(
377            binding,
378            BindTarget {
379                buffer: Some(buffer),
380                texture: None,
381                sampler: None,
382                mutable: !is_read_only,
383            },
384        );
385        max_buffer = Some(max_buffer.map_or(buffer, |max| max.max(buffer)));
386    }
387    let sizes_buffer_index = max_buffer
388        .map(|max| {
389            max.checked_add(1).ok_or_else(|| EmitError::BindingMap {
390                group: 0,
391                binding: u32::from(max),
392                reason: "no free Metal buffer slot remains for Naga's _buffer_sizes sidecar"
393                    .to_string(),
394            })
395        })
396        .transpose()?;
397    resources.sizes_buffer = sizes_buffer_index;
398    let mut map = BTreeMap::new();
399    map.insert(entry_point.to_string(), resources);
400    Ok(MetalResourceMap {
401        per_entry_point: map,
402        sizes_buffer_index,
403    })
404}
405
406struct MetalResourceMap {
407    per_entry_point: BTreeMap<String, EntryPointResources>,
408    sizes_buffer_index: Option<u8>,
409}
410
411struct MetalBindingIndexMap {
412    by_slot: BTreeMap<u32, u8>,
413    by_resource: BTreeMap<(u32, u32), u8>,
414}
415
416fn metal_binding_indices(desc: &KernelDescriptor) -> Result<MetalBindingIndexMap, EmitError> {
417    let mut by_slot = BTreeMap::new();
418    let mut by_resource = BTreeMap::new();
419    for slot in &desc.bindings.slots {
420        let Some(group) = metal_resource_group(slot) else {
421            continue;
422        };
423        let metal_buffer_index =
424            u8::try_from(by_slot.len()).map_err(|error| EmitError::BindingMap {
425                group,
426                binding: slot.slot,
427                reason: format!(
428                    "too many resource-bound buffers for Metal's flat buffer namespace: {error}"
429                ),
430            })?;
431        if by_slot.insert(slot.slot, metal_buffer_index).is_some() {
432            return Err(EmitError::BindingMap {
433                group,
434                binding: slot.slot,
435                reason: "duplicate descriptor slot in Metal resource binding map".to_string(),
436            });
437        }
438        if by_resource
439            .insert((group, slot.slot), metal_buffer_index)
440            .is_some()
441        {
442            return Err(EmitError::BindingMap {
443                group,
444                binding: slot.slot,
445                reason: "duplicate resource binding in Metal resource binding map".to_string(),
446            });
447        }
448    }
449    Ok(MetalBindingIndexMap {
450        by_slot,
451        by_resource,
452    })
453}
454
455fn metal_resource_indices_from_module(
456    module: &naga::Module,
457) -> Result<BTreeMap<(u32, u32), u8>, EmitError> {
458    let mut keys = BTreeMap::new();
459    for (_handle, global) in module.global_variables.iter() {
460        let Some(binding) = global.binding else {
461            continue;
462        };
463        if keys.insert((binding.group, binding.binding), ()).is_some() {
464            return Err(EmitError::BindingMap {
465                group: binding.group,
466                binding: binding.binding,
467                reason: "duplicate Naga resource binding in Metal resource map".to_string(),
468            });
469        }
470    }
471    let mut indices = BTreeMap::new();
472    for (index, key) in keys.keys().copied().enumerate() {
473        let metal_buffer_index = u8::try_from(index).map_err(|error| EmitError::BindingMap {
474            group: key.0,
475            binding: key.1,
476            reason: format!(
477                "too many Naga resource bindings for Metal's flat buffer namespace: {error}"
478            ),
479        })?;
480        indices.insert(key, metal_buffer_index);
481    }
482    Ok(indices)
483}
484
485fn metal_resource_group(slot: &BindingSlot) -> Option<u32> {
486    match slot.memory_class {
487        MemoryClass::Uniform => Some(1),
488        MemoryClass::Global | MemoryClass::Constant => Some(0),
489        MemoryClass::Shared | MemoryClass::Scratch => None,
490    }
491}
492
493fn metal_bindings(
494    desc: &KernelDescriptor,
495    slot_indices: &BTreeMap<u32, u8>,
496) -> Result<Vec<MetalBindingMetadata>, EmitError> {
497    let mut out = Vec::with_capacity(desc.bindings.slots.len());
498    for slot in &desc.bindings.slots {
499        let Some(group) = metal_resource_group(slot) else {
500            continue;
501        };
502        let metal_buffer_index =
503            slot_indices
504                .get(&slot.slot)
505                .copied()
506                .ok_or_else(|| EmitError::BindingMap {
507                    group,
508                    binding: slot.slot,
509                    reason: "descriptor slot was missing from the dense Metal buffer index map"
510                        .to_string(),
511                })?;
512        out.push(MetalBindingMetadata {
513            name: slot.name.clone(),
514            slot: slot.slot,
515            metal_buffer_index,
516            element_type: format!("{:?}", slot.element_type),
517            element_count: slot.element_count,
518            memory_class: format!("{:?}", slot.memory_class),
519            visibility: format!("{:?}", slot.visibility),
520        });
521    }
522    Ok(out)
523}
524
525fn metal_threadgroup_memories(
526    desc: &KernelDescriptor,
527) -> Result<Vec<MetalThreadgroupMemoryMetadata>, EmitError> {
528    let mut out = Vec::new();
529    for slot in &desc.bindings.slots {
530        if slot.memory_class != MemoryClass::Shared {
531            continue;
532        }
533        let threadgroup_index =
534            u8::try_from(out.len()).map_err(|error| EmitError::BindingMap {
535                group: 0,
536                binding: slot.slot,
537                reason: format!(
538                    "too many threadgroup-memory bindings for Metal's flat threadgroup namespace: {error}"
539                ),
540            })?;
541        let element_count = slot.element_count.ok_or_else(|| EmitError::BindingMap {
542            group: 0,
543            binding: slot.slot,
544            reason: "threadgroup memory requires static element_count metadata".to_string(),
545        })?;
546        let element_size =
547            u64::try_from(slot.element_type.min_bytes().max(4)).map_err(|error| {
548                EmitError::BindingMap {
549                    group: 0,
550                    binding: slot.slot,
551                    reason: format!("threadgroup element byte size does not fit u64: {error}"),
552                }
553            })?;
554        let byte_length = u64::from(element_count)
555            .checked_mul(element_size)
556            .ok_or_else(|| EmitError::BindingMap {
557                group: 0,
558                binding: slot.slot,
559                reason: "threadgroup byte length overflows u64".to_string(),
560            })?;
561        out.push(MetalThreadgroupMemoryMetadata {
562            name: slot.name.clone(),
563            slot: slot.slot,
564            threadgroup_index,
565            byte_length,
566            aligned_byte_length: align_u64(byte_length, 16)?,
567        });
568    }
569    Ok(out)
570}
571
572fn align_u64(value: u64, alignment: u64) -> Result<u64, EmitError> {
573    value
574        .checked_add(alignment - 1)
575        .map(|rounded| rounded / alignment * alignment)
576        .ok_or_else(|| EmitError::BindingMap {
577            group: 0,
578            binding: 0,
579            reason: format!("Metal alignment to {alignment} bytes overflows u64"),
580        })
581}
582
583fn descriptor_blake3(desc: &KernelDescriptor) -> Result<String, EmitError> {
584    let bytes = bincode::serde::encode_to_vec(desc, bincode::config::standard())
585        .map_err(|error| EmitError::DescriptorHash(error.to_string()))?;
586    Ok(hex_encode(blake3::hash(&bytes).as_bytes()))
587}
588
589fn artifact_to_json(artifact: &MetalArtifact) -> Result<String, EmitError> {
590    serde_json::to_string_pretty(artifact)
591        .map_err(|error| EmitError::ArtifactSerialization(error.to_string()))
592}
593
594fn hex_encode(bytes: &[u8]) -> String {
595    const HEX: &[u8; 16] = b"0123456789abcdef";
596    let mut out = String::with_capacity(bytes.len() * 2);
597    for &byte in bytes {
598        out.push(HEX[(byte >> 4) as usize] as char);
599        out.push(HEX[(byte & 0x0f) as usize] as char);
600    }
601    out
602}
603
604#[cfg(test)]
605mod tests {
606    use super::*;
607    use vyre_foundation::ir::{DataType, Expr, Node, Program};
608    use vyre_lower::descriptor_builder::{
609        SlotCount,
610        body,
611        descriptor,
612        effect,
613        global_ro,
614        global_rw,
615        lit,
616        op,
617        shared_rw,
618    };
619    use vyre_lower::{KernelDescriptor, KernelOpKind, LiteralValue};
620
621    fn empty_kernel() -> KernelDescriptor {
622        descriptor("empty").dispatch(64, 1, 1).build()
623    }
624
625    fn one_store_kernel() -> KernelDescriptor {
626        descriptor("store_one")
627            .slot(global_rw(0, DataType::U32, "out").with_count(1))
628            .dispatch(64, 1, 1)
629            .body(
630                body()
631                    .ops([lit(0, 0), lit(1, 1), effect(KernelOpKind::StoreGlobal, [0, 0, 1])])
632                    .literals([LiteralValue::U32(0), LiteralValue::U32(7)]),
633            )
634            .build()
635    }
636
637    #[test]
638    fn empty_kernel_emits_compute_msl() {
639        let msl = emit(&empty_kernel()).unwrap();
640        assert!(
641            msl.contains("kernel"),
642            "MSL source must include a Metal kernel entry point"
643        );
644        assert!(
645            msl.contains("main"),
646            "MSL source must include the canonical main entry point"
647        );
648    }
649
650    #[test]
651    fn one_store_kernel_emits_buffer_binding_metadata() {
652        let artifact = emit_artifact(&one_store_kernel()).unwrap();
653        assert_eq!(artifact.target, "native_module");
654        assert!(
655            artifact.msl.contains(&artifact.entry_point),
656            "artifact entry point must name the actual emitted MSL function"
657        );
658        assert_eq!(artifact.workgroup_size, [64, 1, 1]);
659        assert_eq!(artifact.bindings.len(), 1);
660        assert_eq!(artifact.bindings[0].name, "out");
661        assert_eq!(artifact.bindings[0].metal_buffer_index, 0);
662        assert_eq!(artifact.sizes_buffer_index, Some(1));
663        assert!(artifact.threadgroup_memories.is_empty());
664        assert!(!artifact.msl.is_empty());
665    }
666
667    #[test]
668    fn artifact_json_is_deterministic_for_same_descriptor() {
669        let desc = one_store_kernel();
670        let left = emit_artifact_json(&desc).unwrap();
671        let right = emit_artifact_json(&desc).unwrap();
672        assert_eq!(left, right);
673    }
674
675    #[test]
676    fn missing_entry_point_returns_actionable_error() {
677        let module = vyre_emit_naga::emit(&empty_kernel()).unwrap();
678        let options = MetalEmitOptions {
679            entry_point: "not_main".to_string(),
680            ..MetalEmitOptions::default()
681        };
682        let error = emit_from_naga_module(&module, &options).unwrap_err();
683        let text = error.to_string();
684        assert!(text.contains("Fix:"));
685        assert!(text.contains("not_main"));
686    }
687
688    #[test]
689    fn descriptor_slot_above_metal_flat_limit_is_remapped() {
690        let mut desc = one_store_kernel();
691        desc.bindings.slots[0].slot = 300;
692        desc.body.ops[2].operands[0] = 300;
693        let artifact = emit_artifact(&desc).unwrap();
694        assert_eq!(artifact.bindings[0].slot, 300);
695        assert_eq!(artifact.bindings[0].metal_buffer_index, 0);
696        assert_eq!(artifact.sizes_buffer_index, Some(1));
697    }
698
699    #[test]
700    fn workgroup_slot_is_not_a_metal_buffer_binding() {
701        let mut desc = one_store_kernel();
702        desc.bindings.slots.push(shared_rw(1 << 24, DataType::U32, 4, "tile"));
703        desc.bindings.slots.sort_by_key(|slot| slot.slot);
704        let artifact = emit_artifact(&desc).unwrap();
705        assert_eq!(artifact.bindings.len(), 1);
706        assert_eq!(artifact.bindings[0].name, "out");
707        assert_eq!(artifact.bindings[0].metal_buffer_index, 0);
708        assert_eq!(artifact.sizes_buffer_index, Some(1));
709        assert_eq!(artifact.threadgroup_memories.len(), 1);
710        assert_eq!(artifact.threadgroup_memories[0].name, "tile");
711        assert_eq!(artifact.threadgroup_memories[0].slot, 1 << 24);
712        assert_eq!(artifact.threadgroup_memories[0].threadgroup_index, 0);
713        assert_eq!(artifact.threadgroup_memories[0].byte_length, 16);
714        assert_eq!(artifact.threadgroup_memories[0].aligned_byte_length, 16);
715    }
716
717    #[test]
718    fn metal_resource_count_without_sidecar_room_is_rejected() {
719        let mut desc = empty_kernel();
720        desc.bindings.slots = (0..=255)
721            .map(|slot| global_ro(slot, DataType::U32, &format!("buf{slot}")).with_count(1))
722            .collect();
723        let error = emit_artifact(&desc).unwrap_err();
724        let text = error.to_string();
725        assert!(text.contains("Fix:"));
726        assert!(text.contains("_buffer_sizes"));
727    }
728
729    #[test]
730    fn trap_sidecar_compare_exchange_emits_msl_helper() {
731        let program = Program::wrapped(vec![], [64, 1, 1], vec![Node::trap(Expr::u32(7), "fault")]);
732        let desc = vyre_lower::lower_verified(&program)
733            .map(|lowered| lowered.descriptor)
734            .expect("Fix: trap programs must descriptor-lower");
735        let artifact = emit_artifact(&desc).expect("Fix: trap descriptors must emit Metal MSL");
736
737        assert!(
738            artifact
739                .msl
740                .contains("naga_atomic_compare_exchange_weak_explicit"),
741            "Fix: trap/CAS Metal MSL must include Naga's compare-exchange helper."
742        );
743        let sidecar = artifact
744            .bindings
745            .iter()
746            .find(|binding| binding.name == vyre_lower::TRAP_SIDECAR_NAME)
747            .expect("Fix: trap sidecar must stay host-bound in Metal metadata.");
748        assert_eq!(
749            sidecar.element_count,
750            Some(vyre_lower::TRAP_SIDECAR_WORDS),
751            "Fix: trap sidecar metadata must preserve the four-word runtime ABI."
752        );
753    }
754
755    /// A read-only binding must produce `const device` in MSL, not a mutable
756    /// `device` pointer. Before this fix `mutable: true` was hardcoded for
757    /// every binding regardless of `BindingVisibility`, which prevented Naga's
758    /// MSL backend from emitting `const device T*` and could cause silent
759    /// miscompilation under Metal's strict aliasing rules.
760    #[test]
761    fn readonly_binding_emits_const_device_pointer() {
762        let desc = descriptor("readonly_smoke")
763            .slots([
764                global_ro(0, DataType::U32, "input").with_count(16),
765                global_rw(1, DataType::U32, "output").with_count(16),
766            ])
767            .dispatch(16, 1, 1)
768            .body(
769                body()
770                    .ops([
771                        lit(0, 0),
772                        op(KernelOpKind::LoadGlobal, [0, 0], 1),
773                        effect(KernelOpKind::StoreGlobal, [1, 0, 1]),
774                    ])
775                    .literal(LiteralValue::U32(0)),
776            )
777            .build();
778        let msl =
779            emit(&desc).expect("Fix: read-only + read-write kernel must emit MSL without error.");
780        // Naga's MSL backend emits a read-only storage buffer as a CONST
781        // reference (`device <type> const& name`) and a read-write buffer as a
782        // mutable reference (`device <type>& name`). The read-only "input"
783        // binding (BindingVisibility::ReadOnly -> AddressSpace access LOAD ->
784        // BindTarget.mutable = false) MUST be const-qualified; the read-write
785        // "output" binding MUST NOT be. Before the fix `mutable: true` was
786        // hardcoded for every binding, regressing "input" to a mutable
787        // `device input_elements&` and losing Metal's read-only aliasing
788        // guarantees. (Naga spells it `device T const&`, not `const device T*`.)
789        assert!(
790            msl.contains("input_elements const&"),
791            "read-only `input` binding must emit a `device <type> const&` reference, not a mutable one. MSL excerpt:\n{}",
792            &msl[..msl.len().min(800)]
793        );
794        assert!(
795            !msl.contains("output_elements const&"),
796            "read-write `output` binding must NOT be const-qualified. MSL excerpt:\n{}",
797            &msl[..msl.len().min(800)]
798        );
799    }
800}