1use std::collections::{HashMap, HashSet};
2use std::fmt::Write;
3use std::sync::{Arc, PoisonError, RwLockReadGuard, RwLockWriteGuard};
4
5use alpha2_gpu::CapabilityTier;
6
7use crate::effect::EffectKey;
8use crate::gpu_errors::{Answer, CreationErrorScopes, ScopeErrors, create_checked};
9use crate::loop_bound::{BUDGET, MAX_LOOP_ITERATIONS, blank_comments, bound_for_loops};
10use crate::uniform::{PARAM_SLOT_BYTES, RUNTIME_UNIFORM_WORDS, param_uniform_bytes};
11
12use crate::{
13 DiagnosticSeverity, EffectDef, EffectId, EffectKind, EffectResourceKind, InputSpec, ParamSpec,
14 ParamType, ParamUnit, ParamValue, Renderer, ResourceSpec, ShaderDiagnostic, ShaderDiagnostics,
15 UniformField, UniformLayout,
16};
17
18const MAX_REGISTERED_EFFECTS: usize = 256;
20const MAX_WGSL_BODY_BYTES: usize = 32 * 1024;
21const MAX_WGSL_NESTING: usize = 64;
22const MAX_ARRAY_SLOTS: u64 = 128;
26const MAX_ARRAY_TYPES: usize = 32;
28const MAX_WGSL_STATEMENT_OPERATORS: usize = 256;
34const RESERVED_PREFIX: &str = "alpha2_";
36const MAX_EFFECT_RESOURCES: usize = 8;
37pub const MAX_EFFECT_INPUTS: usize = 8;
40#[allow(clippy::cast_possible_truncation)]
43const INPUT_BINDING_BASE: u32 = 5 + 2 * MAX_EFFECT_RESOURCES as u32;
44const RESOURCE_METADATA_BYTES: usize = 32;
46
47#[cfg(not(target_arch = "wasm32"))]
51const COMPILE_STACK: usize = 8 << 20;
52
53#[cfg(not(target_arch = "wasm32"))]
56fn on_compile_stack<T: Send>(make: impl FnOnce() -> T + Send) -> T {
57 std::thread::scope(|scope| {
58 let compile = std::thread::Builder::new()
59 .name("alpha2 shader compile".to_owned())
60 .stack_size(COMPILE_STACK)
61 .spawn_scoped(scope, make)
62 .expect("the shader compile thread starts");
63 compile
64 .join()
65 .unwrap_or_else(|panic| std::panic::resume_unwind(panic))
66 })
67}
68
69#[cfg(target_arch = "wasm32")]
70fn on_compile_stack<T>(make: impl FnOnce() -> T) -> T {
71 make()
72}
73
74pub struct PendingEffect {
80 compiled: CompiledEffect,
81 compilation: Answer<wgpu::CompilationInfo>,
82 shader_errors: ScopeErrors,
83 pipeline_errors: ScopeErrors,
84}
85
86impl std::fmt::Debug for PendingEffect {
87 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88 formatter
89 .debug_struct("PendingEffect")
90 .field("id", &self.compiled.id)
91 .finish_non_exhaustive()
92 }
93}
94
95impl PendingEffect {
96 pub async fn compiled(self) -> Result<CompiledEffect, ShaderDiagnostics> {
101 let mut diagnostics = compilation_diagnostics(self.compilation.await);
102 for error in self.shader_errors.await {
103 diagnostics.messages.push(ShaderDiagnostic {
104 severity: DiagnosticSeverity::Error,
105 message: error.to_string(),
106 line: None,
107 column: None,
108 });
109 }
110 if diagnostics
112 .messages
113 .iter()
114 .any(|message| message.severity == DiagnosticSeverity::Error)
115 {
116 return Err(diagnostics);
117 }
118 let errors = self.pipeline_errors.await;
119 if !errors.is_empty() {
120 return Err(ShaderDiagnostics {
121 messages: errors
122 .into_iter()
123 .map(|error| ShaderDiagnostic {
124 severity: DiagnosticSeverity::Error,
125 message: error.to_string(),
126 line: None,
127 column: None,
128 })
129 .collect(),
130 });
131 }
132 Ok(self.compiled)
133 }
134}
135
136pub struct CompiledEffect {
138 device: wgpu::Device,
139 id: EffectId,
140 effect: RegisteredEffect,
141}
142
143impl std::fmt::Debug for CompiledEffect {
144 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
145 formatter
146 .debug_struct("CompiledEffect")
147 .field("id", &self.id)
148 .finish_non_exhaustive()
149 }
150}
151
152impl CompiledEffect {
153 #[must_use]
155 pub const fn id(&self) -> &EffectId {
156 &self.id
157 }
158}
159
160#[derive(Debug, Default)]
162pub(crate) struct EffectRegistry {
163 entries: HashMap<EffectId, crate::Shared<RegisteredEffect>>,
164 builtins: HashSet<EffectId>,
165 internal: HashSet<EffectId>,
166}
167
168impl EffectRegistry {
169 fn check_room(&self, id: &EffectId) -> Result<(), ShaderDiagnostics> {
171 if self.entries.contains_key(id) {
172 return Err(ShaderDiagnostics::error(format!(
173 "effect {} version {} is already registered",
174 id.as_str(),
175 id.version()
176 )));
177 }
178 if self.entries.len() - self.builtins.len() >= MAX_REGISTERED_EFFECTS {
179 return Err(ShaderDiagnostics::error(format!(
180 "effect registry is full (maximum {MAX_REGISTERED_EFFECTS})"
181 )));
182 }
183 Ok(())
184 }
185}
186
187#[derive(Debug)]
188pub(crate) struct RegisteredEffect {
189 pub(crate) definition: Arc<EffectDef>,
190 pub(crate) uniform_layout: UniformLayout,
191 reads_time: bool,
192 pub(crate) cost: crate::effect_cost::EffectCost,
194 pub(crate) pass_id: u64,
195 pipeline: std::sync::OnceLock<EffectPipeline>,
197}
198
199#[derive(Debug)]
200pub(crate) struct EffectPipeline {
201 _shader: wgpu::ShaderModule,
202 pub(crate) bind_group_layout: wgpu::BindGroupLayout,
203 pub(crate) pipeline: wgpu::RenderPipeline,
204 pub(crate) sampler: wgpu::Sampler,
205}
206
207impl Renderer {
208 pub async fn register_effect(
217 &self,
218 definition: EffectDef,
219 ) -> Result<EffectId, ShaderDiagnostics> {
220 let compiled = self.compile_effect(definition)?.compiled().await?;
221 self.register_compiled(compiled)
222 }
223
224 pub fn compile_effect(
233 &self,
234 definition: EffectDef,
235 ) -> Result<PendingEffect, ShaderDiagnostics> {
236 let id = self.check_registration(&definition)?;
237 let device = self.gpu.device();
238 let format = self.intermediate_format();
239 let (compilation, shader_errors, pipeline, pipeline_errors) = on_compile_stack(|| {
240 let shader_scope = CreationErrorScopes::push(device);
241 let shader = effect_shader(device, &definition);
242 let compilation: Answer<wgpu::CompilationInfo> =
243 Box::pin(shader.get_compilation_info());
244 let shader_errors = shader_scope.pop();
245 let pipeline_scope = CreationErrorScopes::push(device);
246 let pipeline = effect_pipeline(device, &definition, shader, format);
247 (compilation, shader_errors, pipeline, pipeline_scope.pop())
248 });
249 Ok(PendingEffect {
250 compiled: CompiledEffect {
251 device: device.clone(),
252 id,
253 effect: RegisteredEffect {
254 pipeline: std::sync::OnceLock::from(pipeline),
255 ..registered_effect(definition)
256 },
257 },
258 compilation,
259 shader_errors,
260 pipeline_errors,
261 })
262 }
263
264 pub(crate) fn register_lazily(
271 &self,
272 definition: EffectDef,
273 ) -> Result<EffectId, ShaderDiagnostics> {
274 let id = self.check_registration(&definition)?;
275 let mut effects = self.effects_mut();
276 effects.check_room(&id)?;
277 effects.entries.insert(
278 id.clone(),
279 crate::Shared::new(registered_effect(definition)),
280 );
281 Ok(id)
282 }
283
284 pub(crate) fn effects(&self) -> RwLockReadGuard<'_, EffectRegistry> {
286 self.effects.read().unwrap_or_else(PoisonError::into_inner)
287 }
288
289 pub(crate) fn effects_mut(&self) -> RwLockWriteGuard<'_, EffectRegistry> {
290 self.effects.write().unwrap_or_else(PoisonError::into_inner)
291 }
292
293 fn check_registration(&self, definition: &EffectDef) -> Result<EffectId, ShaderDiagnostics> {
295 validate_definition(definition)?;
296 self.validate_parameter_uniform(definition)?;
297 self.validate_texture_bindings(definition)?;
298 if definition.tier_min == CapabilityTier::TierA
299 && self.gpu.capabilities().tier == CapabilityTier::TierB
300 {
301 return Err(ShaderDiagnostics::error(
302 "effect requires capability tier A on a tier B adapter",
303 ));
304 }
305 let id = EffectId::new(definition.id.clone(), definition.version);
306 self.effects().check_room(&id)?;
307 Ok(id)
308 }
309
310 pub(crate) fn effect_pipeline<'a>(
315 &self,
316 effect: &'a RegisteredEffect,
317 ) -> Result<&'a EffectPipeline, crate::RenderError> {
318 if let Some(pipeline) = effect.pipeline.get() {
319 return Ok(pipeline);
320 }
321 let created = crate::diagnostics::timed_pipeline_creation(
322 &self.diagnostics,
323 || effect.definition.id.as_str().to_owned(),
324 || {
325 let device = self.gpu.device();
326 let format = self.intermediate_format();
327 on_compile_stack(|| {
329 let shader = create_checked(device, || self.lazy_effect_shader(effect))?;
330 create_checked(device, || {
331 effect_pipeline(device, &effect.definition, shader, format)
332 })
333 })
334 },
335 )
336 .map_err(|kind| crate::RenderError::Gpu { kind })?;
337 Ok(effect.pipeline.get_or_init(|| created))
338 }
339
340 fn lazy_effect_shader(&self, effect: &RegisteredEffect) -> wgpu::ShaderModule {
341 let device = self.gpu.device();
342 #[cfg(test)]
343 if self
344 .fail_next_pipeline
345 .swap(false, std::sync::atomic::Ordering::Relaxed)
346 {
347 return device.create_shader_module(wgpu::ShaderModuleDescriptor {
349 label: Some("alpha2 test module without entry points"),
350 source: wgpu::ShaderSource::Wgsl("fn unused() {}".into()),
351 });
352 }
353 effect_shader(device, &effect.definition)
354 }
355
356 pub fn register_compiled(
361 &self,
362 compiled: CompiledEffect,
363 ) -> Result<EffectId, ShaderDiagnostics> {
364 if compiled.device != *self.gpu.device() {
365 return Err(ShaderDiagnostics::error(format!(
366 "effect {} version {} was compiled on another GPU device",
367 compiled.id.as_str(),
368 compiled.id.version()
369 )));
370 }
371 let mut effects = self.effects_mut();
372 effects.check_room(&compiled.id)?;
373 effects
374 .entries
375 .insert(compiled.id.clone(), crate::Shared::new(compiled.effect));
376 Ok(compiled.id)
377 }
378
379 fn validate_parameter_uniform(&self, definition: &EffectDef) -> Result<(), ShaderDiagnostics> {
385 let limit = self
386 .limits
387 .max_uniform_buffer_binding_size
388 .min(wgpu::Limits::downlevel_webgl2_defaults().max_uniform_buffer_binding_size);
389 let bytes = u64::try_from(param_uniform_bytes(definition.params.len())).unwrap_or(u64::MAX);
390 if bytes > limit {
391 let most = limit / u64::try_from(PARAM_SLOT_BYTES).unwrap_or(u64::MAX);
392 return Err(ShaderDiagnostics::error(format!(
393 "effect declares {} parameters, a {bytes}-byte uniform past the {limit}-byte \
394 limit every alpha2 runtime binds (at most {most} parameters)",
395 definition.params.len()
396 )));
397 }
398 Ok(())
399 }
400
401 fn validate_texture_bindings(&self, definition: &EffectDef) -> Result<(), ShaderDiagnostics> {
404 let textures = 2 + definition.resources.len() + definition.inputs.len();
405 let limit =
406 usize::try_from(self.limits.max_sampled_textures_per_shader_stage.min(
407 wgpu::Limits::downlevel_webgl2_defaults().max_sampled_textures_per_shader_stage,
408 ))
409 .unwrap_or(usize::MAX);
410 if textures > limit {
411 return Err(ShaderDiagnostics::error(format!(
412 "effect samples {textures} textures (its source pair, {} resources, and {} \
413 named inputs), past this device's {limit} per shader stage",
414 definition.resources.len(),
415 definition.inputs.len()
416 )));
417 }
418 Ok(())
419 }
420
421 #[must_use]
423 pub fn effect_uniform_layout(&self, id: &EffectId) -> Option<UniformLayout> {
424 self.effects()
425 .entries
426 .get(id)
427 .map(|entry| entry.uniform_layout.clone())
428 }
429
430 #[must_use]
432 pub fn effect_definition(&self, id: &EffectId) -> Option<Arc<EffectDef>> {
433 self.effects()
434 .entries
435 .get(id)
436 .map(|entry| Arc::clone(&entry.definition))
437 }
438
439 #[must_use]
445 pub fn effect_reads_time(&self, id: &EffectId) -> bool {
446 if let Some(passes) = crate::gaussian_blur::expanded_passes(id.as_str()) {
447 return passes
448 .iter()
449 .any(|pass| self.effect_reads_time(&EffectId::from_static(pass, 1)));
450 }
451 self.effects()
452 .entries
453 .get(id)
454 .is_none_or(|entry| entry.reads_time)
455 }
456
457 #[must_use]
459 pub fn is_effect_registered(&self, id: &EffectId) -> bool {
460 self.effects().entries.contains_key(id)
461 }
462
463 #[must_use]
465 pub fn is_effect_project_visible(&self, id: &EffectId) -> bool {
466 let effects = self.effects();
467 effects.entries.contains_key(id) && !effects.internal.contains(id)
468 }
469
470 #[must_use]
473 pub fn project_effect_id(&self, id: &str, version: u32) -> Option<EffectId> {
474 let key: &dyn EffectKey = &(id, version);
475 let effects = self.effects();
476 effects
477 .entries
478 .get_key_value(key)
479 .map(|(id, _)| id)
480 .filter(|id| !effects.internal.contains(*id))
481 .cloned()
482 }
483
484 #[must_use]
486 pub fn is_builtin_effect(&self, id: &EffectId) -> bool {
487 self.effects().builtins.contains(id)
488 }
489
490 pub fn unregister_effect(&self, id: &EffectId) -> bool {
492 let removed = {
493 let mut effects = self.effects_mut();
494 !effects.builtins.contains(id) && effects.entries.remove(id).is_some()
495 };
496 if removed {
497 self.clear_result_cache_for(crate::CacheInvalidation::Effects);
498 }
499 removed
500 }
501
502 pub fn clear_effects(&self) {
504 {
505 let mut effects = self.effects_mut();
506 let EffectRegistry {
507 entries, builtins, ..
508 } = &mut *effects;
509 entries.retain(|id, _| builtins.contains(id));
510 }
511 self.clear_result_cache_for(crate::CacheInvalidation::Effects);
512 }
513
514 pub fn warmup(&self, effects: &[EffectId]) -> Result<(), ShaderDiagnostics> {
520 let create = |effect: &EffectId, registered: &RegisteredEffect| {
521 self.effect_pipeline(registered)
522 .map(|_| ())
523 .map_err(|error| {
524 ShaderDiagnostics::error(format!(
525 "effect {} version {}: {error}",
526 effect.as_str(),
527 effect.version()
528 ))
529 })
530 };
531 for effect in effects {
532 let Some(registered) = self.effects().get(effect) else {
533 return Err(ShaderDiagnostics::error(format!(
534 "effect {} version {} is not registered",
535 effect.as_str(),
536 effect.version()
537 )));
538 };
539 create(effect, ®istered)?;
540 for pass in crate::gaussian_blur::expanded_passes(effect.as_str()).unwrap_or_default() {
541 let pass = EffectId::from_static(pass, 1);
542 if let Some(registered) = self.effects().get(&pass) {
543 create(&pass, ®istered)?;
544 }
545 }
546 }
547 Ok(())
548 }
549}
550
551impl EffectRegistry {
552 pub(crate) fn get(&self, id: &EffectId) -> Option<crate::Shared<RegisteredEffect>> {
553 self.entries.get(id).cloned()
554 }
555
556 pub(crate) fn len(&self) -> usize {
557 self.entries.len()
558 }
559
560 pub(crate) fn mark_builtin(&mut self, id: EffectId) {
561 debug_assert!(self.entries.contains_key(&id));
562 self.builtins.insert(id);
563 }
564
565 pub(crate) fn mark_internal(&mut self, id: EffectId) {
566 debug_assert!(self.entries.contains_key(&id));
567 self.internal.insert(id);
568 }
569}
570
571pub(crate) fn registered_effect(definition: EffectDef) -> RegisteredEffect {
573 RegisteredEffect {
574 uniform_layout: uniform_layout(&definition.params),
575 reads_time: body_reads_time(&definition.wgsl_body),
576 cost: crate::effect_cost::invocation_cost(&blank_comments(&definition.wgsl_body)),
577 pass_id: pass_id(&definition),
578 definition: Arc::new(definition),
579 pipeline: std::sync::OnceLock::new(),
580 }
581}
582
583fn pass_id(definition: &EffectDef) -> u64 {
584 use std::hash::{Hash, Hasher};
585 let mut hasher = std::hash::DefaultHasher::new();
586 definition.id.hash(&mut hasher);
587 definition.version.hash(&mut hasher);
588 definition.wgsl_body.hash(&mut hasher);
589 hasher.finish()
590}
591
592fn effect_shader(device: &wgpu::Device, definition: &EffectDef) -> wgpu::ShaderModule {
593 device.create_shader_module(wgpu::ShaderModuleDescriptor {
594 label: Some(&definition.id),
595 source: wgpu::ShaderSource::Wgsl(build_shader(definition).into()),
596 })
597}
598
599fn effect_pipeline(
600 device: &wgpu::Device,
601 definition: &EffectDef,
602 shader: wgpu::ShaderModule,
603 format: wgpu::TextureFormat,
604) -> EffectPipeline {
605 let bind_group_layout = runtime_bind_group_layout(
606 device,
607 &definition.params,
608 &definition.resources,
609 &definition.inputs,
610 );
611 let pipeline = runtime_pipeline(device, &bind_group_layout, &shader, format);
612 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
613 label: Some("alpha2 runtime effect sampler"),
614 address_mode_u: wgpu::AddressMode::ClampToEdge,
615 address_mode_v: wgpu::AddressMode::ClampToEdge,
616 mag_filter: wgpu::FilterMode::Linear,
617 min_filter: wgpu::FilterMode::Linear,
618 ..Default::default()
619 });
620 EffectPipeline {
621 _shader: shader,
622 bind_group_layout,
623 pipeline,
624 sampler,
625 }
626}
627
628fn runtime_bind_group_layout(
629 device: &wgpu::Device,
630 params: &[ParamSpec],
631 resources: &[ResourceSpec],
632 inputs: &[InputSpec],
633) -> wgpu::BindGroupLayout {
634 let mut entries = vec![
635 runtime_texture_entry(0, wgpu::TextureViewDimension::D2),
636 runtime_texture_entry(1, wgpu::TextureViewDimension::D2),
637 wgpu::BindGroupLayoutEntry {
638 binding: 2,
639 visibility: wgpu::ShaderStages::FRAGMENT,
640 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
641 count: None,
642 },
643 runtime_uniform_entry(3, param_uniform_bytes(params.len())),
646 runtime_uniform_entry(4, RUNTIME_UNIFORM_WORDS * size_of::<f32>()),
647 ];
648 for (index, resource) in resources.iter().enumerate() {
649 let binding = u32::try_from(index).unwrap_or(0) * 2 + 5;
650 let dimension = match resource.kind {
651 EffectResourceKind::Lut3d => wgpu::TextureViewDimension::D3,
652 };
653 entries.push(runtime_texture_entry(binding, dimension));
654 entries.push(runtime_uniform_entry(binding + 1, RESOURCE_METADATA_BYTES));
655 }
656 for index in 0..inputs.len() {
657 entries.push(runtime_texture_entry(
658 input_binding(index),
659 wgpu::TextureViewDimension::D2,
660 ));
661 }
662 device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
663 label: Some("alpha2 runtime effect layout"),
664 entries: &entries,
665 })
666}
667
668pub(crate) fn input_binding(index: usize) -> u32 {
669 INPUT_BINDING_BASE + u32::try_from(index).unwrap_or(0)
670}
671
672fn runtime_texture_entry(
673 binding: u32,
674 view_dimension: wgpu::TextureViewDimension,
675) -> wgpu::BindGroupLayoutEntry {
676 wgpu::BindGroupLayoutEntry {
677 binding,
678 visibility: wgpu::ShaderStages::FRAGMENT,
679 ty: wgpu::BindingType::Texture {
680 sample_type: wgpu::TextureSampleType::Float { filterable: true },
681 view_dimension,
682 multisampled: false,
683 },
684 count: None,
685 }
686}
687
688fn runtime_uniform_entry(binding: u32, bytes: usize) -> wgpu::BindGroupLayoutEntry {
689 wgpu::BindGroupLayoutEntry {
690 binding,
691 visibility: wgpu::ShaderStages::FRAGMENT,
692 ty: wgpu::BindingType::Buffer {
693 ty: wgpu::BufferBindingType::Uniform,
694 has_dynamic_offset: false,
695 min_binding_size: u64::try_from(bytes)
696 .ok()
697 .and_then(std::num::NonZeroU64::new),
698 },
699 count: None,
700 }
701}
702
703fn runtime_pipeline(
704 device: &wgpu::Device,
705 bind_group_layout: &wgpu::BindGroupLayout,
706 shader: &wgpu::ShaderModule,
707 format: wgpu::TextureFormat,
708) -> wgpu::RenderPipeline {
709 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
710 label: Some("alpha2 runtime effect pipeline layout"),
711 bind_group_layouts: &[Some(bind_group_layout)],
712 immediate_size: 0,
713 });
714 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
715 label: Some("alpha2 runtime effect pipeline"),
716 layout: Some(&layout),
717 vertex: wgpu::VertexState {
718 module: shader,
719 entry_point: Some("alpha2_vs"),
720 buffers: &[],
721 compilation_options: wgpu::PipelineCompilationOptions::default(),
722 },
723 fragment: Some(wgpu::FragmentState {
724 module: shader,
725 entry_point: Some("alpha2_fs"),
726 targets: &[Some(format.into())],
727 compilation_options: wgpu::PipelineCompilationOptions::default(),
728 }),
729 primitive: wgpu::PrimitiveState::default(),
730 depth_stencil: None,
731 multisample: wgpu::MultisampleState::default(),
732 multiview_mask: None,
733 cache: None,
734 })
735}
736
737pub(crate) fn uniform_layout(params: &[ParamSpec]) -> UniformLayout {
738 let fields = params
739 .iter()
740 .enumerate()
741 .map(|(index, param)| UniformField {
742 name: param.name.clone(),
743 offset: u32::try_from(index).expect("parameter count fits u32") * 16,
744 size: 16,
745 })
746 .collect::<Vec<_>>();
747 UniformLayout {
748 size: u32::try_from(param_uniform_bytes(params.len())).expect("parameter uniform fits u32"),
749 fields,
750 }
751}
752
753pub(crate) fn body_reads_time(body: &str) -> bool {
760 body.split(|character: char| !(character.is_alphanumeric() || character == '_'))
761 .any(|word| matches!(word, "time" | "time_ticks" | "runtime"))
762}
763
764pub(crate) fn build_shader(definition: &EffectDef) -> String {
765 let param_fields = if definition.params.is_empty() {
766 " _padding: vec4f,\n".to_owned()
767 } else {
768 definition
769 .params
770 .iter()
771 .fold(String::new(), |mut output, param| {
772 writeln!(
773 output,
774 " {}: {},",
775 param.name,
776 wgsl_type(param.param_type)
777 )
778 .expect("writing to a String cannot fail");
779 output
780 })
781 };
782 let uniform_fields =
783 (0..definition.params.len().max(1)).fold(String::new(), |mut output, index| {
784 writeln!(output, " slot_{index}: vec4u,").expect("writing to a String cannot fail");
785 output
786 });
787 let param_values = if definition.params.is_empty() {
788 "vec4f(0.0)".to_owned()
789 } else {
790 definition
791 .params
792 .iter()
793 .enumerate()
794 .map(|(index, param)| uniform_value(index, param.param_type))
795 .collect::<Vec<_>>()
796 .join(", ")
797 };
798 let call = match definition.kind {
799 EffectKind::Effect => "effect(input.uv, sample_src(input.uv))",
800 EffectKind::Transition => "alpha2_transition(input.uv)",
801 EffectKind::Generator => "generate(input.uv)",
802 };
803 let transition_wrapper = match definition.kind {
804 EffectKind::Effect | EffectKind::Generator => "",
805 EffectKind::Transition => {
806 r"fn alpha2_transition(uv: vec2f) -> vec4f {
807 if (progress() <= 0.0) { return from_color(uv); }
808 if (progress() >= 1.0) { return to_color(uv); }
809 return transition(uv);
810}"
811 }
812 };
813 let resource_declarations = resource_declarations(&definition.resources);
814 let input_declarations = input_declarations(&definition.inputs);
815 format!(
816 r"@group(0) @binding(0) var source_a: texture_2d<f32>;
817@group(0) @binding(1) var source_b: texture_2d<f32>;
818@group(0) @binding(2) var source_sampler: sampler;
819struct EffectParams {{
820{param_fields}}};
821struct EffectParamUniforms {{
822{uniform_fields}}};
823@group(0) @binding(3) var<uniform> param_uniforms: EffectParamUniforms;
824var<private> params: EffectParams;
825var<private> {BUDGET}: u32;
826struct RuntimeValues {{ resolution_time: vec4f, transition: vec4f, ticks: vec4u, }};
827@group(0) @binding(4) var<uniform> runtime: RuntimeValues;
828{resource_declarations}{input_declarations}
829
830fn sample_src(uv: vec2f) -> vec4f {{ return textureSampleLevel(source_a, source_sampler, uv, 0.0); }}
831fn from_color(uv: vec2f) -> vec4f {{ return textureSampleLevel(source_a, source_sampler, uv, 0.0); }}
832fn to_color(uv: vec2f) -> vec4f {{ return textureSampleLevel(source_b, source_sampler, uv, 0.0); }}
833fn resolution() -> vec2f {{ return runtime.resolution_time.xy; }}
834fn time() -> f32 {{ return runtime.resolution_time.z; }}
835fn time_ticks() -> vec2u {{ return runtime.ticks.xy; }}
836fn progress() -> f32 {{ return runtime.transition.x; }}
837fn ratio() -> f32 {{ return runtime.transition.y; }}
838fn render_scale() -> f32 {{ return runtime.resolution_time.w; }}
839fn render_scale_fixed() -> u32 {{ return runtime.ticks.z; }}
840fn max_filter_samples() -> f32 {{ return runtime.transition.z; }}
841fn load_params() -> EffectParams {{ return EffectParams({param_values}); }}
842
843{body}
844
845{transition_wrapper}
846
847struct VertexOutput {{ @builtin(position) position: vec4f, @location(0) uv: vec2f, }};
848@vertex fn alpha2_vs(@builtin(vertex_index) index: u32) -> VertexOutput {{
849 var p = array<vec2f, 3>(vec2f(-1.0, -1.0), vec2f(3.0, -1.0), vec2f(-1.0, 3.0));
850 var u = array<vec2f, 3>(vec2f(0.0, 1.0), vec2f(2.0, 1.0), vec2f(0.0, -1.0));
851 return VertexOutput(vec4f(p[index], 0.0, 1.0), u[index]);
852}}
853@fragment fn alpha2_fs(input: VertexOutput) -> @location(0) vec4f {{
854 params = load_params();
855 {BUDGET} = {MAX_LOOP_ITERATIONS}u;
856 return {call};
857}}
858",
859 body =
861 bound_for_loops(&definition.wgsl_body).unwrap_or_else(|_| definition.wgsl_body.clone()),
862 resource_declarations = resource_declarations,
863 input_declarations = input_declarations,
864 transition_wrapper = transition_wrapper,
865 )
866}
867
868fn resource_declarations(resources: &[ResourceSpec]) -> String {
869 resources
870 .iter()
871 .enumerate()
872 .map(|(index, resource)| match resource.kind {
873 EffectResourceKind::Lut3d => format!(
874 "struct ResourceMetadata_{} {{ domain_min: vec4f, domain_max: vec4f, }};\n\
875 @group(0) @binding({}) var resource_{}: texture_3d<f32>;\n\
876 @group(0) @binding({}) var<uniform> resource_{}_metadata: ResourceMetadata_{};\n\
877 fn sample_{}(rgb: vec3f) -> vec3f {{\n\
878 let edge = f32(textureDimensions(resource_{}).x);\n\
879 let normalized = clamp((rgb - resource_{}_metadata.domain_min.xyz) /\n\
880 (resource_{}_metadata.domain_max.xyz - resource_{}_metadata.domain_min.xyz),\n\
881 vec3f(0.0), vec3f(1.0));\n\
882 let coord = (normalized * (edge - 1.0) + 0.5) / edge;\n\
883 return textureSampleLevel(resource_{}, source_sampler, coord, 0.0).rgb;\n\
884 }}",
885 resource.name,
886 index * 2 + 5,
887 resource.name,
888 index * 2 + 6,
889 resource.name,
890 resource.name,
891 resource.name,
892 resource.name,
893 resource.name,
894 resource.name,
895 resource.name,
896 resource.name,
897 ),
898 })
899 .collect::<Vec<_>>()
900 .join("\n")
901}
902
903fn input_declarations(inputs: &[InputSpec]) -> String {
905 inputs
906 .iter()
907 .enumerate()
908 .fold(String::new(), |mut output, (index, input)| {
909 let name = &input.name;
910 write!(
911 output,
912 "\n@group(0) @binding({binding}) var input_{name}: texture_2d<f32>;\n\
913 fn sample_{name}(uv: vec2f) -> vec4f {{ return textureSampleLevel(input_{name}, source_sampler, uv, 0.0); }}\n\
914 fn size_{name}() -> vec2f {{ return vec2f(textureDimensions(input_{name})); }}",
915 binding = input_binding(index),
916 )
917 .expect("writing to a String cannot fail");
918 output
919 })
920}
921
922fn uniform_value(index: usize, param_type: ParamType) -> String {
923 match param_type {
924 ParamType::Float => format!("bitcast<f32>(param_uniforms.slot_{index}.x)"),
925 ParamType::Vec2 => format!("bitcast<vec2f>(param_uniforms.slot_{index}.xy)"),
926 ParamType::Vec4 | ParamType::Color => {
927 format!("bitcast<vec4f>(param_uniforms.slot_{index})")
928 }
929 ParamType::Enum | ParamType::Bool => format!("param_uniforms.slot_{index}.x"),
930 }
931}
932
933fn wgsl_type(param_type: ParamType) -> &'static str {
934 match param_type {
935 ParamType::Float => "f32",
936 ParamType::Vec2 => "vec2f",
937 ParamType::Vec4 | ParamType::Color => "vec4f",
938 ParamType::Enum | ParamType::Bool => "u32",
939 }
940}
941
942#[derive(Clone, Debug, PartialEq, Eq)]
944pub struct CheckedEffect {
945 pub module: String,
947 pub functions: usize,
949 pub calls: u64,
951 pub cost_units: u64,
953}
954
955pub fn check_effect(definition: &EffectDef) -> Result<CheckedEffect, ShaderDiagnostics> {
962 validate_definition(definition)?;
963 let code = blank_comments(&definition.wgsl_body);
964 let (calls, _) = crate::call_budget::invocation_calls(&code)?;
965 Ok(CheckedEffect {
966 module: build_shader(definition),
967 functions: crate::call_budget::declarations(&code).len(),
968 calls,
969 cost_units: crate::effect_cost::invocation_cost(&code).units(),
970 })
971}
972
973fn validate_definition(definition: &EffectDef) -> Result<(), ShaderDiagnostics> {
974 if !valid_identifier(&definition.id) {
975 return Err(ShaderDiagnostics::error(
976 "effect id must contain only ASCII letters, digits, '-', '_', or '.'",
977 ));
978 }
979 if definition.version == 0 {
980 return Err(ShaderDiagnostics::error("effect version must be non-zero"));
981 }
982 validate_wgsl_body(&definition.wgsl_body)?;
983 if !definition.inputs.is_empty() && definition.kind != EffectKind::Effect {
984 return Err(ShaderDiagnostics::error(
985 "only effects declare named inputs; a transition samples from and to",
986 ));
987 }
988 if definition.inputs.len() > MAX_EFFECT_INPUTS {
989 return Err(ShaderDiagnostics::error(format!(
990 "effect declares more than {MAX_EFFECT_INPUTS} named inputs"
991 )));
992 }
993 let mut names = std::collections::HashSet::new();
994 for param in &definition.params {
995 validate_param(param)?;
996 if !names.insert(param.name.as_str()) {
997 return Err(ShaderDiagnostics::error(format!(
998 "duplicate parameter name {}",
999 param.name
1000 )));
1001 }
1002 }
1003 if definition.resources.len() > MAX_EFFECT_RESOURCES {
1004 return Err(ShaderDiagnostics::error(format!(
1005 "effect declares more than {MAX_EFFECT_RESOURCES} resources"
1006 )));
1007 }
1008 let mut resource_names = std::collections::HashSet::new();
1009 let mut declared = std::collections::HashSet::new();
1011 for resource in &definition.resources {
1012 let generated = resource_declarations_of(&resource.name);
1013 if !valid_wgsl_identifier(&resource.name)
1014 || names.contains(resource.name.as_str())
1015 || !resource_names.insert(resource.name.as_str())
1016 || !generated
1017 .iter()
1018 .all(|name| valid_wgsl_identifier(name) && declared.insert(name.clone()))
1019 {
1020 return Err(ShaderDiagnostics::error(format!(
1021 "invalid or duplicate effect resource name {}",
1022 resource.name
1023 )));
1024 }
1025 }
1026 let mut input_names = std::collections::HashSet::new();
1028 for input in &definition.inputs {
1029 let generated = input_declarations_of(&input.name);
1030 if !valid_wgsl_identifier(&input.name)
1031 || names.contains(input.name.as_str())
1032 || resource_names.contains(input.name.as_str())
1033 || !input_names.insert(input.name.as_str())
1034 || !generated
1035 .iter()
1036 .all(|name| valid_wgsl_identifier(name) && declared.insert(name.clone()))
1037 {
1038 return Err(ShaderDiagnostics::error(format!(
1039 "invalid or duplicate effect input name {}",
1040 input.name
1041 )));
1042 }
1043 }
1044 Ok(())
1045}
1046
1047fn input_declarations_of(name: &str) -> [String; 3] {
1050 [
1051 format!("input_{name}"),
1052 format!("sample_{name}"),
1053 format!("size_{name}"),
1054 ]
1055}
1056
1057fn resource_declarations_of(name: &str) -> [String; 4] {
1059 [
1060 format!("resource_{name}"),
1061 format!("resource_{name}_metadata"),
1062 format!("sample_{name}"),
1063 format!("ResourceMetadata_{name}"),
1064 ]
1065}
1066
1067fn validate_wgsl_body(body: &str) -> Result<(), ShaderDiagnostics> {
1068 if body.len() > MAX_WGSL_BODY_BYTES {
1069 return Err(ShaderDiagnostics::error(format!(
1070 "WGSL body exceeds {MAX_WGSL_BODY_BYTES} bytes"
1071 )));
1072 }
1073 if body
1074 .chars()
1075 .any(|character| character.is_control() && !matches!(character, '\n' | '\r' | '\t'))
1076 {
1077 return Err(ShaderDiagnostics::error(
1078 "WGSL body contains unsupported control characters",
1079 ));
1080 }
1081 let code = blank_comments(body);
1083 if !code.is_ascii() {
1085 return Err(ShaderDiagnostics::error(
1086 "a runtime effect's code is ASCII; comments may hold any text",
1087 ));
1088 }
1089 if let Some(identifier) = identifiers(&code).find(|word| word.starts_with(RESERVED_PREFIX)) {
1090 return Err(ShaderDiagnostics::error(format!(
1091 "WGSL identifier {identifier} is reserved: names starting with {RESERVED_PREFIX} belong to the generated wrapper"
1092 )));
1093 }
1094 if code.split([';', '{', '}']).any(|statement| {
1095 statement.bytes().filter(|byte| is_operator(*byte)).count() > MAX_WGSL_STATEMENT_OPERATORS
1096 }) {
1097 return Err(ShaderDiagnostics::error(format!(
1098 "a WGSL statement has more than {MAX_WGSL_STATEMENT_OPERATORS} operators; split it with `let`"
1099 )));
1100 }
1101 check_nesting(&code)?;
1102 check_arrays(&code)?;
1103
1104 let forbidden = [
1105 "@binding",
1106 "@compute",
1107 "@group",
1108 "atomic",
1109 "enable",
1110 "loop",
1111 "override",
1112 "var<storage",
1113 "var<uniform",
1114 "var<workgroup",
1115 "while",
1116 ];
1117 for token in code.split(|character: char| {
1118 !(character.is_ascii_alphanumeric() || matches!(character, '_' | '@' | '<'))
1119 }) {
1120 if forbidden.contains(&token) {
1121 return Err(ShaderDiagnostics::error(format!(
1122 "WGSL token {token} is not allowed in a runtime effect"
1123 )));
1124 }
1125 }
1126 bound_for_loops(body)?;
1127 crate::call_budget::check_invocation_calls(&code)?;
1128 crate::effect_cost::check_invocation_cost(&code).map(drop)
1129}
1130
1131fn check_arrays(code: &str) -> Result<(), ShaderDiagnostics> {
1134 let arrays = crate::effect_cost::array_types(code);
1135 if arrays.len() > MAX_ARRAY_TYPES {
1136 return Err(ShaderDiagnostics::error(format!(
1137 "a runtime effect writes at most {MAX_ARRAY_TYPES} array types"
1138 )));
1139 }
1140 for array in arrays {
1141 let text = &code[array.span.clone()];
1142 if !array.templated {
1143 return Err(ShaderDiagnostics::error(
1144 "write a runtime effect's arrays with their element type and count, as \
1145 `array<T, N>(...)`",
1146 ));
1147 }
1148 let Some(slots) = array.slots else {
1149 return Err(ShaderDiagnostics::error(format!(
1150 "`{text}` needs an integer literal count and elements that are scalars, \
1151 vectors, matrices or arrays"
1152 )));
1153 };
1154 if slots > MAX_ARRAY_SLOTS {
1155 return Err(ShaderDiagnostics::error(format!(
1156 "`{text}` holds more than {MAX_ARRAY_SLOTS} vectors; put a large table in a \
1157 resource texture"
1158 )));
1159 }
1160 }
1161 Ok(())
1162}
1163
1164fn check_nesting(code: &str) -> Result<(), ShaderDiagnostics> {
1167 let unbalanced = || ShaderDiagnostics::error("WGSL body has unbalanced delimiters");
1168 let too_deep = |chained: bool| {
1169 ShaderDiagnostics::error(if chained {
1170 format!(
1171 "an `else if` chain nests past {MAX_WGSL_NESTING} levels; use `switch` or \
1172 early returns"
1173 )
1174 } else {
1175 format!("WGSL nesting exceeds {MAX_WGSL_NESTING} levels")
1176 })
1177 };
1178 let mut open: Vec<(u8, usize, Option<usize>)> = Vec::new();
1180 let mut pending_if: Option<(usize, usize)> = None;
1182 let mut closed_chain: Option<usize> = None;
1184 let mut after_else = false;
1185 let bytes = code.as_bytes();
1186 let mut index = 0;
1187 while index < bytes.len() {
1188 let byte = bytes[index];
1189 if byte.is_ascii_whitespace() {
1190 index += 1;
1191 continue;
1192 }
1193 if crate::loop_bound::is_identifier_byte(byte) {
1194 let end = index
1195 + bytes[index..]
1196 .iter()
1197 .take_while(|byte| crate::loop_bound::is_identifier_byte(**byte))
1198 .count();
1199 let word = &code[index..end];
1200 index = end;
1201 if word == "else" && closed_chain.is_some() && !after_else {
1202 after_else = true;
1203 continue;
1204 }
1205 if word == "if" {
1206 let chain = if after_else {
1207 closed_chain.map_or(1, |chain| chain + 1)
1208 } else {
1209 1
1210 };
1211 pending_if = Some((open.len(), chain));
1212 }
1213 closed_chain = None;
1214 after_else = false;
1215 continue;
1216 }
1217 closed_chain = None;
1218 after_else = false;
1219 index += 1;
1220 match byte {
1221 b'{' | b'(' | b'[' => {
1222 let chain = pending_if
1223 .filter(|(at, _)| byte == b'{' && *at == open.len())
1224 .map(|(_, chain)| chain);
1225 if chain.is_some() {
1226 pending_if = None;
1227 }
1228 let depth = open.last().map_or(0, |(_, depth, _)| *depth) + chain.unwrap_or(1);
1229 if depth > MAX_WGSL_NESTING {
1230 return Err(too_deep(chain.is_some_and(|chain| chain > 1)));
1231 }
1232 open.push((byte, depth, chain));
1233 }
1234 b'}' | b')' | b']' => {
1235 let Some((opened, _, chain)) = open.pop() else {
1236 return Err(unbalanced());
1237 };
1238 if !matches!((opened, byte), (b'{', b'}') | (b'(', b')') | (b'[', b']')) {
1239 return Err(unbalanced());
1240 }
1241 closed_chain = chain;
1242 }
1243 _ => {}
1244 }
1245 }
1246 if open.is_empty() {
1247 Ok(())
1248 } else {
1249 Err(unbalanced())
1250 }
1251}
1252
1253fn identifiers(code: &str) -> impl Iterator<Item = &str> {
1255 code.split(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))
1256 .filter(|word| word.starts_with(|first: char| first.is_ascii_alphabetic() || first == '_'))
1257}
1258
1259const fn is_operator(byte: u8) -> bool {
1262 matches!(
1263 byte,
1264 b'+' | b'-'
1265 | b'*'
1266 | b'/'
1267 | b'%'
1268 | b'&'
1269 | b'|'
1270 | b'^'
1271 | b'!'
1272 | b'~'
1273 | b'<'
1274 | b'>'
1275 | b'='
1276 | b'.'
1277 | b'['
1278 )
1279}
1280
1281fn validate_param(param: &ParamSpec) -> Result<(), ShaderDiagnostics> {
1282 if !valid_wgsl_identifier(¶m.name) {
1283 return Err(ShaderDiagnostics::error(format!(
1284 "invalid WGSL parameter name {}",
1285 param.name
1286 )));
1287 }
1288 let compatible = matches!(
1289 (¶m.param_type, ¶m.default, ¶m.unit),
1290 (
1291 ParamType::Float,
1292 ParamValue::Float(_),
1293 ParamUnit::Normalized | ParamUnit::Degrees
1294 ) | (ParamType::Vec2, ParamValue::Vec2(_), ParamUnit::Normalized)
1295 | (ParamType::Vec4, ParamValue::Vec4(_), ParamUnit::Normalized)
1296 | (ParamType::Color, ParamValue::Color(_), ParamUnit::Color)
1297 | (ParamType::Enum, ParamValue::Enum(_), ParamUnit::Enum)
1298 | (ParamType::Bool, ParamValue::Bool(_), ParamUnit::Bool)
1299 );
1300 if !compatible {
1301 return Err(ShaderDiagnostics::error(format!(
1302 "parameter {} has incompatible type, default, and unit",
1303 param.name
1304 )));
1305 }
1306 if !finite_value(¶m.default)
1307 || param.min.is_some_and(|value| !value.is_finite())
1308 || param.max.is_some_and(|value| !value.is_finite())
1309 || param
1310 .step
1311 .is_some_and(|value| !value.is_finite() || value <= 0.0)
1312 || matches!((param.min, param.max), (Some(min), Some(max)) if min > max)
1313 {
1314 return Err(ShaderDiagnostics::error(format!(
1315 "parameter {} has an invalid numeric range",
1316 param.name
1317 )));
1318 }
1319 if !matches!(
1320 param.param_type,
1321 ParamType::Float | ParamType::Vec2 | ParamType::Vec4
1322 ) && (param.min.is_some() || param.max.is_some() || param.step.is_some())
1323 {
1324 return Err(ShaderDiagnostics::error(format!(
1325 "only float, vec2, or vec4 parameter {} may declare a numeric range",
1326 param.name
1327 )));
1328 }
1329 if matches!(
1330 param.param_type,
1331 ParamType::Float | ParamType::Vec2 | ParamType::Vec4
1332 ) && !value_in_range(¶m.default, param.min, param.max)
1333 {
1334 return Err(ShaderDiagnostics::error(format!(
1335 "parameter {} default is outside its numeric range",
1336 param.name
1337 )));
1338 }
1339 if let ParamValue::Color(values) = ¶m.default
1340 && !values.iter().all(|value| (0.0..=1.0).contains(value))
1341 {
1342 return Err(ShaderDiagnostics::error(format!(
1343 "color parameter {} default must be inside 0..=1",
1344 param.name
1345 )));
1346 }
1347 if param.param_type == ParamType::Enum && param.enum_values.is_empty() {
1348 return Err(ShaderDiagnostics::error(format!(
1349 "enum parameter {} requires named values",
1350 param.name
1351 )));
1352 }
1353 if let ParamValue::Enum(value) = ¶m.default
1354 && usize::try_from(*value).map_or(true, |index| index >= param.enum_values.len())
1355 {
1356 return Err(ShaderDiagnostics::error(format!(
1357 "enum parameter {} default is out of range",
1358 param.name
1359 )));
1360 }
1361 Ok(())
1362}
1363
1364fn value_in_range(value: &ParamValue, min: Option<f32>, max: Option<f32>) -> bool {
1365 let in_range = |value: &f32| {
1366 min.is_none_or(|minimum| *value >= minimum) && max.is_none_or(|maximum| *value <= maximum)
1367 };
1368 match value {
1369 ParamValue::Float(value) => in_range(value),
1370 ParamValue::Vec2(values) => values.iter().all(in_range),
1371 ParamValue::Vec4(values) => values.iter().all(in_range),
1372 _ => true,
1373 }
1374}
1375
1376fn finite_value(value: &ParamValue) -> bool {
1377 match value {
1378 ParamValue::Float(value) => value.is_finite(),
1379 ParamValue::Vec2(values) => values.iter().all(|value| value.is_finite()),
1380 ParamValue::Vec4(values) | ParamValue::Color(values) => {
1381 values.iter().all(|value| value.is_finite())
1382 }
1383 ParamValue::Enum(_) | ParamValue::Bool(_) => true,
1384 }
1385}
1386
1387fn valid_identifier(value: &str) -> bool {
1388 !value.is_empty()
1389 && value
1390 .bytes()
1391 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
1392}
1393
1394fn valid_wgsl_identifier(value: &str) -> bool {
1395 let mut bytes = value.bytes();
1396 bytes
1397 .next()
1398 .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
1399 && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
1400 && !value.starts_with(RESERVED_PREFIX)
1401 && !matches!(
1402 value,
1403 "params"
1404 | "resolution"
1405 | "time"
1406 | "time_ticks"
1407 | "progress"
1408 | "ratio"
1409 | "render_scale"
1410 | "render_scale_fixed"
1411 | "sample_src"
1412 | "from_color"
1413 | "to_color"
1414 | "load_params"
1415 | "max_filter_samples"
1416 | "source_a"
1417 | "source_b"
1418 | "source_sampler"
1419 | "param_uniforms"
1420 | "runtime"
1421 | "EffectParams"
1422 )
1423}
1424
1425fn compilation_diagnostics(info: wgpu::CompilationInfo) -> ShaderDiagnostics {
1426 ShaderDiagnostics {
1427 messages: info
1428 .messages
1429 .into_iter()
1430 .map(|message| {
1431 let severity = match message.message_type {
1432 wgpu::CompilationMessageType::Error => DiagnosticSeverity::Error,
1433 wgpu::CompilationMessageType::Warning => DiagnosticSeverity::Warning,
1434 wgpu::CompilationMessageType::Info => DiagnosticSeverity::Info,
1435 };
1436 ShaderDiagnostic {
1437 severity,
1438 message: message.message,
1439 line: message.location.map(|location| location.line_number),
1440 column: message.location.map(|location| location.line_position),
1441 }
1442 })
1443 .collect(),
1444 }
1445}
1446
1447#[cfg(test)]
1448#[path = "registry_tests.rs"]
1449mod tests;