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)]
13use 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
35pub const METAL_ARTIFACT_SCHEMA: u32 = 3;
37
38pub const DEFAULT_MSL_VERSION: (u8, u8) = (2, 4);
40
41#[derive(Clone, Debug, Eq, PartialEq)]
43pub struct MetalEmitOptions {
44 pub lang_version: (u8, u8),
46 pub entry_point: String,
48 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#[derive(Debug, Error)]
64pub enum EmitError {
65 #[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 #[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 #[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 entry_point: String,
76 reason: String,
78 },
79 #[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 #[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 group: u32,
87 binding: u32,
89 reason: String,
91 },
92 #[error("KernelDescriptor artifact hash failed: {0}. Fix: keep KernelDescriptor serde stable before using it as native_module artifact identity.")]
94 DescriptorHash(String),
95 #[error("Metal native_module JSON serialization failed: {0}. Fix: keep artifact metadata serde-compatible and deterministic.")]
97 ArtifactSerialization(String),
98 #[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#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
105pub struct MetalBindingMetadata {
106 pub name: String,
108 pub slot: u32,
110 pub metal_buffer_index: u8,
112 pub element_type: String,
115 pub element_count: Option<u32>,
117 pub memory_class: String,
119 pub visibility: String,
121}
122
123#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
125pub struct MetalThreadgroupMemoryMetadata {
126 pub name: String,
128 pub slot: u32,
130 pub threadgroup_index: u8,
132 pub byte_length: u64,
134 pub aligned_byte_length: u64,
136}
137
138#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
140pub struct MetalArtifact {
141 pub schema: u32,
143 pub target: String,
145 pub emitter: String,
147 pub msl_version: String,
149 pub entry_point: String,
151 pub descriptor_blake3: String,
153 pub msl_blake3: String,
155 pub workgroup_size: [u32; 3],
157 pub bindings: Vec<MetalBindingMetadata>,
159 pub sizes_buffer_index: Option<u8>,
162 pub threadgroup_memories: Vec<MetalThreadgroupMemoryMetadata>,
165 pub msl: String,
167}
168
169pub fn emit(desc: &KernelDescriptor) -> Result<String, EmitError> {
176 emit_with_options(desc, &MetalEmitOptions::default())
177}
178
179pub 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
192pub fn emit_artifact(desc: &KernelDescriptor) -> Result<MetalArtifact, EmitError> {
199 emit_artifact_with_options(desc, &MetalEmitOptions::default())
200}
201
202pub 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
241pub fn emit_artifact_json(desc: &KernelDescriptor) -> Result<String, EmitError> {
247 artifact_to_json(&emit_artifact(desc)?)
248}
249
250pub 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
261pub 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 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 #[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 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}