1use std::path::{Path, PathBuf};
2use std::str::FromStr;
3
4use clap::{Args, Subcommand};
5use qualia_core_db::wgsl_forge::execute::WgpuComputeContext;
6use qualia_core_db::wgsl_forge::{
7 candidate_evaluation, generate_builtin, resolve_execution_backend, tune_with, validate_native,
8 validate_wgsl, AdapterConstraints, BuiltinKernel, CertificationManifest, ForgeError,
9 ManifestCache, Schedule, ScheduleSpace, TargetBackend, TuningConfig, TuningManifest,
10};
11
12#[derive(Debug, Clone, Args)]
13pub struct ScheduleArgs {
14 #[arg(long, default_value_t = 64)]
16 pub workgroup: u32,
17 #[arg(long, default_value_t = 1)]
19 pub items: u32,
20 #[arg(long, default_value_t = 1)]
22 pub vector_width: u32,
23}
24
25impl ScheduleArgs {
26 fn schedule(&self) -> Schedule {
27 Schedule {
28 workgroup_size: self.workgroup,
29 items_per_invocation: self.items,
30 vector_width: self.vector_width,
31 ..Default::default()
32 }
33 }
34}
35
36#[derive(Debug, Subcommand)]
37pub enum ShaderAction {
38 ListKernels,
40 Doctor,
43 Roofline {
45 #[arg(default_value = "affine-f32")]
46 kernel: String,
47 #[arg(long, default_value_t = 65_536)]
49 n: u64,
50 #[arg(long)]
51 json: bool,
52 },
53 ProfileHardware {
55 #[arg(long)]
57 export: Option<PathBuf>,
58 #[arg(long)]
59 json: bool,
60 },
61 Generate {
63 #[arg(default_value = "affine-f32")]
64 kernel: String,
65 #[arg(long, default_value = "wgsl")]
67 target: String,
68 #[command(flatten)]
69 schedule: ScheduleArgs,
70 #[arg(long)]
72 out: Option<PathBuf>,
73 #[arg(long)]
75 json: bool,
76 },
77 Validate {
79 #[arg(long)]
81 input: Option<PathBuf>,
82 #[arg(default_value = "affine-f32")]
83 kernel: String,
84 #[arg(long, default_value = "wgsl")]
86 target: String,
87 #[command(flatten)]
88 schedule: ScheduleArgs,
89 #[arg(long)]
91 manifest: Option<PathBuf>,
92 #[arg(long)]
93 json: bool,
94 },
95 Certify {
97 #[arg(default_value = "affine-f32")]
98 kernel: String,
99 #[command(flatten)]
100 schedule: ScheduleArgs,
101 #[arg(long, default_value_t = 4_099)]
102 length: usize,
103 #[arg(long, default_value_t = 3)]
104 warmups: usize,
105 #[arg(long, default_value_t = 9)]
106 samples: usize,
107 #[arg(long)]
108 manifest: Option<PathBuf>,
109 #[arg(long)]
111 cache_dir: Option<PathBuf>,
112 #[arg(long)]
114 dry_run: bool,
115 },
116 Tune {
118 #[arg(default_value = "affine-f32")]
119 kernel: String,
120 #[arg(long, default_value_t = 65_537)]
121 length: usize,
122 #[arg(long, default_value_t = 2)]
123 warmups: usize,
124 #[arg(long, default_value_t = 3)]
125 initial_samples: usize,
126 #[arg(long, default_value_t = 11)]
127 finalist_samples: usize,
128 #[arg(long, default_value_t = 6)]
129 finalists: usize,
130 #[arg(long, default_value_t = 48)]
131 max_candidates: usize,
132 #[arg(long)]
133 manifest: Option<PathBuf>,
134 #[arg(long)]
136 cache_dir: Option<PathBuf>,
137 #[arg(long)]
139 dry_run: bool,
140 },
141 AutoTuneAll {
143 #[arg(long, default_value_t = 65_537)]
144 length: usize,
145 #[arg(long, default_value_t = 2)]
146 warmups: usize,
147 #[arg(long, default_value_t = 24)]
148 max_candidates: usize,
149 #[arg(long)]
152 cache_dir: Option<PathBuf>,
153 #[arg(long)]
155 update_local_manifest: bool,
156 #[arg(long)]
158 dry_run: bool,
159 #[arg(long)]
164 budget_ms: Option<u64>,
165 #[arg(long)]
170 thermal_limit: Option<f32>,
171 },
172}
173
174pub fn run(action: &ShaderAction) -> Result<(), Box<dyn std::error::Error>> {
176 match action {
177 ShaderAction::ListKernels => {
178 println!("Qualia WGSL Forge kernels:");
179 for builtin in BuiltinKernel::ALL {
180 let spec = builtin.spec();
181 println!(
182 " {:<16} v{} {}",
183 builtin.name(),
184 spec.semantic_version,
185 spec.description
186 );
187 }
188 }
189 ShaderAction::Roofline { kernel, n, json } => {
190 let builtin = parse_kernel(kernel)?;
191 let estimate = qualia_core_db::wgsl_forge::roofline_for(builtin, *n);
192 if *json {
193 println!("{}", serde_json::to_string_pretty(&estimate)?);
194 } else {
195 println!(
196 "{} @ n={}: {} FLOP / {} bytes -> {:.3} FLOP/byte ({:?}-bound)",
197 builtin.name(),
198 n,
199 estimate.flops,
200 estimate.bytes,
201 estimate.arithmetic_intensity,
202 estimate.bound
203 );
204 }
205 }
206 ShaderAction::Doctor => {
207 use std::process::Command;
208 println!("Qualia WGSL Forge — environment doctor\n");
209
210 match WgpuComputeContext::new(1024 * 1024) {
211 Ok(runner) => println!(
212 "[ok] wgpu adapter: {} ({})",
213 runner.adapter.name, runner.adapter.backend
214 ),
215 Err(error) => println!(
216 "[warn] wgpu adapter: none ({error}); generation/validation still work headless"
217 ),
218 }
219
220 let dxc = std::env::var("QUALIA_DXC_PATH").unwrap_or_else(|_| "dxc".to_string());
221 match Command::new(&dxc).arg("--version").output() {
222 Ok(out) if out.status.success() => {
223 println!("[ok] DXC (HLSL->SPIR-V/DXIL): {dxc}");
224 }
225 _ => println!(
226 "[warn] DXC not found — set QUALIA_DXC_PATH or add dxc to PATH.\n HLSL native path disabled; get DXC: https://github.com/microsoft/DirectXShaderCompiler/releases"
227 ),
228 }
229
230 let nvcc = std::env::var("CUDA_PATH")
231 .map(|p| format!("{p}/bin/nvcc"))
232 .unwrap_or_else(|_| "nvcc".to_string());
233 match Command::new(&nvcc).arg("--version").output() {
234 Ok(out) if out.status.success() => {
235 let text = String::from_utf8_lossy(&out.stdout);
236 let release = text.lines().find(|l| l.contains("release")).unwrap_or("present");
237 println!("[ok] CUDA toolkit (nvcc): {}", release.trim());
238 }
239 _ => println!(
240 "[warn] CUDA toolkit not found — set CUDA_PATH.\n PTX/CUDA backend disabled; get CUDA: https://developer.nvidia.com/cuda-downloads"
241 ),
242 }
243
244 println!(
245 "\nMissing native toolchains degrade gracefully to the wgpu/WGSL path (plan §12)."
246 );
247 }
248 ShaderAction::ProfileHardware { export, json } => {
249 let runner = WgpuComputeContext::new(1024 * 1024)?;
250 let profile = &runner.profile;
251 let topology_hash = profile.topology_hash()?;
252 if let Some(path) = export {
253 std::fs::write(path, profile.to_pretty_json()?.as_bytes())?;
254 eprintln!("wrote {} (topology {})", path.display(), topology_hash);
255 }
256 if *json {
257 println!("{}", profile.to_pretty_json()?);
258 } else {
259 println!(
260 "Adapter: {} ({})",
261 profile.adapter.name, profile.adapter.backend
262 );
263 println!("Device type: {}", profile.adapter.device_type);
264 println!(
265 "Driver: {} {}",
266 profile.adapter.driver, profile.adapter.driver_info
267 );
268 println!("Memory class: {}", profile.memory_class);
269 println!("Subgroups: {}", profile.constraints.supports_subgroups);
270 println!("Tensor (coopmat): {}", profile.constraints.supports_coopmat);
271 println!("RT cores: {}", profile.constraints.supports_rt_cores);
272 println!("Timestamp query: {}", profile.supports_timestamp_query);
273 println!(
274 "Max workgroup: {} invocations, {} bytes shared",
275 profile.constraints.max_invocations_per_workgroup,
276 profile.max_compute_workgroup_storage_size
277 );
278 println!(
279 "Bind alignment: storage {} / uniform {}",
280 profile.min_storage_buffer_offset_alignment,
281 profile.min_uniform_buffer_offset_alignment
282 );
283 println!("Topology hash: {topology_hash}");
284 }
285 }
286 ShaderAction::Generate {
287 kernel,
288 target,
289 schedule,
290 out,
291 json,
292 } => {
293 let builtin = parse_kernel(kernel)?;
294 let target_backend = target
295 .parse()
296 .map_err(|e: String| ForgeError::Emission(e))?;
297 let generated = generate_builtin(builtin, schedule.schedule(), target_backend)?;
298 if let Some(path) = out {
299 std::fs::write(path, generated.source.as_bytes())?;
300 eprintln!(
301 "generated {} -> {} ({})",
302 generated.kernel_id,
303 path.display(),
304 generated.source_hash
305 );
306 } else if *json {
307 println!("{}", serde_json::to_string_pretty(&generated)?);
308 } else {
309 print!("{}", generated.source);
310 }
311 }
312 ShaderAction::Validate {
313 input,
314 kernel,
315 target,
316 schedule,
317 manifest,
318 json,
319 } => {
320 let requested_backend: TargetBackend = target
321 .parse()
322 .map_err(|e: String| ForgeError::Emission(e))?;
323 let (target_backend, fallback_note) =
331 resolve_execution_backend(requested_backend, |t| check_native_toolchain(t).is_ok());
332 if let Some(note) = fallback_note {
333 println!("note: {note}");
334 }
335 let (source, generated, spec) = if let Some(path) = input {
336 (std::fs::read_to_string(path)?, None, None)
337 } else {
338 let builtin = parse_kernel(kernel)?;
339 let generated = generate_builtin(builtin, schedule.schedule(), target_backend)?;
340 (
341 generated.source.clone(),
342 Some(generated),
343 Some(builtin.spec()),
344 )
345 };
346 let report = if target_backend == TargetBackend::Wgsl {
347 Some(validate_wgsl(&source)?)
348 } else if target_backend == TargetBackend::Spirv {
349 if let Some(builtin) = parse_kernel(kernel).ok() {
355 let wgsl = generate_builtin(builtin, schedule.schedule(), TargetBackend::Wgsl)?;
356 Some(validate_wgsl(&wgsl.source)?)
357 } else {
358 eprintln!("SPIR-V validation of an opaque --input blob is not supported; provide a kernel.");
359 None
360 }
361 } else {
362 match validate_native(&source, target_backend, spec.as_ref()) {
363 Ok(r) => Some(r),
364 Err(ForgeError::WgslValidation(msg)) => {
365 eprintln!("Native validation skipped or failed: {}", msg);
366 None
367 }
368 Err(e) => return Err(Box::new(e)),
369 }
370 };
371 if let Some(path) = manifest {
372 let generated = generated.ok_or_else(|| {
373 std::io::Error::new(
374 std::io::ErrorKind::InvalidInput,
375 "--manifest requires a generated kernel (omit --input)",
376 )
377 })?;
378 if let Some(report) = report.clone() {
379 let record = CertificationManifest::naga_only(&generated, report);
380 write_json(path, &record)?;
381 } else {
382 eprintln!("Warning: Validation manifest generation is currently only supported for WGSL targets.");
383 }
384 }
385 if let Some(report) = report {
386 if *json {
387 println!("{}", serde_json::to_string_pretty(&report)?);
388 } else {
389 println!(
390 "Validated {} binding(s), entry point(s): {}",
391 report.binding_count,
392 report.entry_points.join(", ")
393 );
394 if let Some(tool) = report.native_tool_validated {
395 println!(
396 "Validation success (via {}): entry points = {:?}",
397 tool, report.entry_points
398 );
399 } else {
400 println!(
401 "Validation success (via Naga): entry points = {:?}",
402 report.entry_points
403 );
404 }
405 }
406 } else {
407 println!("Validation skipped for non-WGSL target.");
408 }
409 }
410 ShaderAction::Certify {
411 kernel,
412 schedule,
413 length,
414 warmups,
415 samples,
416 manifest,
417 cache_dir,
418 dry_run,
419 } => {
420 let builtin = parse_kernel(kernel)?;
421 if *dry_run {
422 let sched = schedule.schedule();
423 let spec = builtin.spec();
424 let generated = generate_builtin(builtin, sched, TargetBackend::Wgsl)?;
425 let report = validate_wgsl(&generated.source)?;
426 let constraints = AdapterConstraints::portable();
427 let schedule_ok = sched.validate(&spec, &constraints).is_ok();
428 let adapter_ok = constraints.supports_kernel(&spec).is_ok();
429 println!(
430 "DRY-RUN certify {}: naga={} ({} bindings), schedule_valid={}, adapter_supported(portable)={}, gpu_oracle={}",
431 builtin.name(), report.naga_validated, report.binding_count, schedule_ok, adapter_ok, builtin.has_gpu_oracle()
432 );
433 return Ok(());
434 }
435 let mut runner = WgpuComputeContext::new(4 * 1024 * 1024)?;
436 runner.constraints.supports_kernel(&builtin.spec())?;
437 let record = qualia_core_db::wgsl_forge::certify_builtin(
438 &mut runner,
439 builtin,
440 schedule.schedule(),
441 *length,
442 *warmups,
443 *samples,
444 )?;
445 if let Some(path) = manifest {
446 write_json(path, &record)?;
447 }
448 if let Some(root) = cache_dir {
449 let path = ManifestCache::new(root).store_certification(&record)?;
450 eprintln!("cached {}", path.display());
451 }
452 println!(
453 "CERTIFIED {} on {}: median {} ns, p95 {} ns",
454 record.kernel_id,
455 record
456 .adapter
457 .as_ref()
458 .map(|value| value.name.as_str())
459 .unwrap_or("unknown"),
460 record
461 .timing
462 .as_ref()
463 .map(|value| value.median_ns)
464 .unwrap_or(0),
465 record
466 .timing
467 .as_ref()
468 .map(|value| value.p95_ns)
469 .unwrap_or(0)
470 );
471 println!(
472 "cache key: {}",
473 record.cache_key.as_deref().unwrap_or("none")
474 );
475 }
476 ShaderAction::Tune {
477 kernel,
478 length,
479 warmups,
480 initial_samples,
481 finalist_samples,
482 finalists,
483 max_candidates,
484 manifest,
485 cache_dir,
486 dry_run,
487 } => {
488 let builtin = parse_kernel(kernel)?;
489 let spec = builtin.spec();
490 if *dry_run {
491 let constraints = match WgpuComputeContext::new(4 * 1024 * 1024) {
492 Ok(runner) => runner.constraints,
493 Err(_) => AdapterConstraints::portable(),
494 };
495 let space = ScheduleSpace::default();
496 let total = space.workgroup_sizes.len()
497 * space.items_per_invocation.len()
498 * space.vector_widths.len();
499 let candidates = space.candidates(&spec, &constraints);
500 let adapter_ok = constraints.supports_kernel(&spec);
501 let roofline = qualia_core_db::wgsl_forge::roofline_for(builtin, *length as u64);
502 println!(
503 "DRY-RUN tune {}: {}/{} schedule(s) survive pruning; adapter_supported={}; gpu_oracle={}",
504 builtin.name(),
505 candidates.len(),
506 total,
507 adapter_ok.is_ok(),
508 builtin.has_gpu_oracle()
509 );
510 println!(
511 " roofline @ n={}: {:.3} FLOP/byte ({:?}-bound)",
512 length, roofline.arithmetic_intensity, roofline.bound
513 );
514 println!(
515 " warp size: {} (non-multiples pruned)",
516 constraints.warp_size
517 );
518 for &wg in &space.workgroup_sizes {
519 let kept = candidates.iter().filter(|c| c.workgroup_size == wg).count();
520 let note = if wg % constraints.warp_size == 0 {
521 ""
522 } else {
523 " [warp-pruned]"
524 };
525 println!(" workgroup {wg:>4}: {kept} kept{note}");
526 }
527 if let Err(error) = adapter_ok {
528 println!(" pruned: {error}");
529 }
530 return Ok(());
531 }
532 let mut runner = WgpuComputeContext::new(4 * 1024 * 1024)?;
533 let constraints = runner.constraints;
534 let result = tune_with(
535 &spec,
536 &constraints,
537 &ScheduleSpace::default(),
538 TuningConfig {
539 initial_samples: *initial_samples,
540 finalist_samples: *finalist_samples,
541 finalist_count: *finalists,
542 max_candidates: *max_candidates,
543 },
544 |schedule, sample_count| {
545 candidate_evaluation(
546 &mut runner,
547 builtin,
548 schedule,
549 *length,
550 *warmups,
551 sample_count,
552 )
553 },
554 )?;
555 println!("\nBest configuration:");
556 let generated = generate_builtin(builtin, result.winner.schedule, TargetBackend::Wgsl)?;
557 println!("{}", generated.source);
558 let record = TuningManifest::new(&generated, runner.adapter.clone(), result)?;
559 if let Some(path) = manifest {
560 write_json(path, &record)?;
561 }
562 if let Some(root) = cache_dir {
563 let path = ManifestCache::new(root).store_tuning(&record)?;
564 eprintln!("cached {}", path.display());
565 }
566 let winner = &record.result.winner;
567 println!(
568 "TUNED {} on {}: wg={}, items={}, vector={} -> median {} ns, p95 {} ns",
569 record.kernel_id,
570 record.adapter.name,
571 winner.schedule.workgroup_size,
572 winner.schedule.items_per_invocation,
573 winner.schedule.vector_width,
574 winner.timing.median_ns,
575 winner.timing.p95_ns
576 );
577 println!(
578 "evaluated {}, rejected {}, cache key {}",
579 record.result.evaluated_candidates,
580 record.result.rejected_candidates,
581 record.cache_key
582 );
583 }
584 ShaderAction::AutoTuneAll {
585 length,
586 warmups,
587 max_candidates,
588 cache_dir,
589 update_local_manifest,
590 dry_run,
591 budget_ms,
592 thermal_limit,
593 } => {
594 if let Err(why) = check_native_toolchain(TargetBackend::Wgsl) {
599 return Err(why.into());
600 }
601
602 let mut runner = WgpuComputeContext::new(4 * 1024 * 1024)?;
603 let topology_hash = runner.profile.topology_hash()?;
604 let constraints = runner.constraints;
605 let adapter_name = runner.adapter.name.clone();
606 let cache = cache_dir.as_ref().map(|p| ManifestCache::new(p.clone()));
607 println!("auto-tune-all on {adapter_name} (topology {topology_hash})");
608
609 let start = std::time::Instant::now();
613
614 let thermal_active = match (thermal_limit, read_gpu_temperature_celsius()) {
617 (Some(limit), Some(_)) => Some(*limit),
618 (Some(limit), None) => {
619 eprintln!(
620 "warning: --thermal-limit {limit} requested but no GPU temperature sensor is available on this host (nvidia-smi missing or non-NVIDIA GPU); proceeding WITHOUT thermal limiting."
621 );
622 None
623 }
624 (None, _) => None,
625 };
626
627 let mut tuned = 0usize;
628 let mut skipped_budget = 0usize;
629 for builtin in BuiltinKernel::ALL {
630 let spec = builtin.spec();
631 let name = builtin.name();
632 if constraints.supports_kernel(&spec).is_err() {
633 println!(" {name:<12} SKIP (adapter lacks required intrinsics)");
634 continue;
635 }
636 if !builtin.has_gpu_oracle() {
637 println!(" {name:<12} SKIP (no GPU oracle wired yet)");
638 continue;
639 }
640 if let Some(cache) = &cache {
641 if let Some(existing) = cache.load_tuning_for_topology(&topology_hash, name)? {
642 let winner = &existing.result.winner;
643 println!(
644 " {name:<12} CACHED wg={} items={} -> median {} ns",
645 winner.schedule.workgroup_size,
646 winner.schedule.items_per_invocation,
647 winner.timing.median_ns
648 );
649 continue;
650 }
651 }
652 if *dry_run {
653 println!(" {name:<12} WOULD TUNE");
654 continue;
655 }
656 if let Some(budget) = budget_ms {
659 let elapsed = start.elapsed().as_millis() as u64;
660 if elapsed >= *budget {
661 println!(" {name:<12} SKIP (budget: {elapsed} ms elapsed >= {budget} ms)");
662 skipped_budget += 1;
663 continue;
664 }
665 }
666 if let Some(limit) = thermal_active {
669 const MAX_WAITS: u32 = 5;
670 for attempt in 0..MAX_WAITS {
671 match read_gpu_temperature_celsius() {
672 Some(temp) if temp >= limit => {
673 println!(
674 " {name:<12} THERMAL HOLD ({temp:.0} C >= {limit:.0} C), waiting ~2s [{}/{}]",
675 attempt + 1,
676 MAX_WAITS
677 );
678 std::thread::sleep(std::time::Duration::from_secs(2));
679 }
680 _ => break,
681 }
682 }
683 }
684 let result = tune_with(
685 &spec,
686 &constraints,
687 &ScheduleSpace::default(),
688 TuningConfig {
689 initial_samples: 3,
690 finalist_samples: 11,
691 finalist_count: 6,
692 max_candidates: *max_candidates,
693 },
694 |schedule, sample_count| {
695 candidate_evaluation(
696 &mut runner,
697 builtin,
698 schedule,
699 *length,
700 *warmups,
701 sample_count,
702 )
703 },
704 );
705 match result {
706 Ok(result) => {
707 tuned += 1;
708 let generated =
709 generate_builtin(builtin, result.winner.schedule, TargetBackend::Wgsl)?;
710 let record =
711 TuningManifest::new(&generated, runner.adapter.clone(), result)?;
712 let winner = &record.result.winner;
713 println!(
714 " {name:<12} TUNED wg={} items={} vec={} -> median {} ns, p95 {} ns",
715 winner.schedule.workgroup_size,
716 winner.schedule.items_per_invocation,
717 winner.schedule.vector_width,
718 winner.timing.median_ns,
719 winner.timing.p95_ns
720 );
721 if *update_local_manifest {
722 if let Some(cache) = &cache {
723 let path = cache.store_tuning_for_topology(
724 &topology_hash,
725 name,
726 &record,
727 )?;
728 eprintln!(" cached {}", path.display());
729 }
730 }
731 }
732 Err(error) => println!(" {name:<12} FAILED: {error}"),
733 }
734 }
735 if budget_ms.is_some() {
736 println!(
737 "auto-tune-all done in {} ms: {tuned} kernel(s) tuned, {skipped_budget} skipped due to budget",
738 start.elapsed().as_millis()
739 );
740 }
741 }
742 }
743 Ok(())
744}
745
746fn parse_kernel(value: &str) -> Result<BuiltinKernel, Box<dyn std::error::Error>> {
747 Ok(BuiltinKernel::from_str(value)?)
748}
749
750fn read_gpu_temperature_celsius() -> Option<f32> {
756 use std::process::Command;
757 let output = Command::new("nvidia-smi")
758 .arg("--query-gpu=temperature.gpu")
759 .arg("--format=csv,noheader,nounits")
760 .output()
761 .ok()?;
762 if !output.status.success() {
763 return None;
764 }
765 let text = String::from_utf8_lossy(&output.stdout);
766 text.lines()
768 .next()?
769 .trim()
770 .split(|c: char| !c.is_ascii_digit())
771 .find(|s| !s.is_empty())
772 .and_then(|s| s.parse::<f32>().ok())
773}
774
775fn check_native_toolchain(target: TargetBackend) -> Result<(), String> {
780 use std::process::Command;
781 match target {
782 TargetBackend::Wgsl | TargetBackend::Spirv => Ok(()),
784 TargetBackend::Hlsl => {
785 let dxc = std::env::var("QUALIA_DXC_PATH").unwrap_or_else(|_| "dxc".to_string());
786 match Command::new(&dxc).arg("--version").output() {
787 Ok(out) if out.status.success() => Ok(()),
788 _ => Err(format!(
789 "DXC (HLSL compiler) not found as `{dxc}`; set QUALIA_DXC_PATH or add dxc to PATH. Run `shader doctor` for details."
790 )),
791 }
792 }
793 TargetBackend::Ptx | TargetBackend::CudaC => {
794 let nvcc = std::env::var("CUDA_PATH")
795 .map(|p| format!("{p}/bin/nvcc"))
796 .unwrap_or_else(|_| "nvcc".to_string());
797 match Command::new(&nvcc).arg("--version").output() {
798 Ok(out) if out.status.success() => Ok(()),
799 _ => Err(
800 "CUDA toolkit (nvcc) not found at CUDA_PATH; set CUDA_PATH or add nvcc to PATH. Run `shader doctor` for details.".to_string(),
801 ),
802 }
803 }
804 TargetBackend::Msl => {
805 match Command::new("xcrun").arg("--version").output() {
806 Ok(out) if out.status.success() => Ok(()),
807 _ => Err(
808 "Metal toolchain (xcrun) not found; install Xcode command-line tools. Run `shader doctor` for details.".to_string(),
809 ),
810 }
811 }
812 }
813}
814
815fn write_json<T: serde::Serialize>(
816 path: &Path,
817 value: &T,
818) -> Result<(), Box<dyn std::error::Error>> {
819 let json = serde_json::to_string_pretty(value)?;
820 std::fs::write(path, json.as_bytes())?;
821 eprintln!("wrote {}", path.display());
822 Ok(())
823}