naga_oil/compose/
error.rs

1use std::{borrow::Cow, collections::HashMap, ops::Range};
2
3use codespan_reporting::{
4    diagnostic::{Diagnostic, Label},
5    files::SimpleFile,
6    term,
7    term::termcolor::WriteColor,
8};
9use thiserror::Error;
10use tracing::trace;
11
12use super::{preprocess::PreprocessOutput, Composer, ShaderDefValue};
13use crate::{compose::SPAN_SHIFT, redirect::RedirectError};
14
15#[derive(Debug)]
16pub enum ErrSource {
17    Module {
18        name: String,
19        offset: usize,
20        defs: HashMap<String, ShaderDefValue>,
21    },
22    Constructing {
23        path: String,
24        source: String,
25        offset: usize,
26    },
27}
28
29impl ErrSource {
30    pub fn path<'a>(&'a self, composer: &'a Composer) -> &'a String {
31        match self {
32            ErrSource::Module { name, .. } => &composer.module_sets.get(name).unwrap().file_path,
33            ErrSource::Constructing { path, .. } => path,
34        }
35    }
36
37    pub fn source<'a>(&'a self, composer: &'a Composer) -> Cow<'a, String> {
38        match self {
39            ErrSource::Module { name, defs, .. } => {
40                let raw_source = &composer.module_sets.get(name).unwrap().sanitized_source;
41                let Ok(PreprocessOutput {
42                    preprocessed_source: source,
43                    ..
44                }) = composer.preprocessor.preprocess(raw_source, defs)
45                else {
46                    return Default::default();
47                };
48
49                Cow::Owned(source)
50            }
51            ErrSource::Constructing { source, .. } => Cow::Borrowed(source),
52        }
53    }
54
55    pub fn offset(&self) -> usize {
56        match self {
57            ErrSource::Module { offset, .. } | ErrSource::Constructing { offset, .. } => *offset,
58        }
59    }
60}
61
62#[derive(Debug, Error)]
63#[error("Composer error: {inner}")]
64pub struct ComposerError {
65    #[source]
66    pub inner: ComposerErrorInner,
67    pub source: ErrSource,
68}
69
70#[derive(Debug, Error)]
71pub enum ComposerErrorInner {
72    #[error("{0}")]
73    ImportParseError(String, usize),
74    #[error("required import '{0}' not found")]
75    ImportNotFound(String, usize),
76    #[error("{0}")]
77    WgslParseError(naga::front::wgsl::ParseError),
78    #[cfg(feature = "glsl")]
79    #[error("{0:?}")]
80    GlslParseError(naga::front::glsl::ParseErrors),
81    #[error("naga_oil bug, please file a report: failed to convert imported module IR back into WGSL for use with WGSL shaders: {0}")]
82    WgslBackError(naga::back::wgsl::Error),
83    #[cfg(feature = "glsl")]
84    #[error("naga_oil bug, please file a report: failed to convert imported module IR back into GLSL for use with GLSL shaders: {0}")]
85    GlslBackError(naga::back::glsl::Error),
86    #[error("naga_oil bug, please file a report: composer failed to build a valid header: {0}")]
87    HeaderValidationError(naga::WithSpan<naga::valid::ValidationError>),
88    #[error("failed to build a valid final module: {0}")]
89    ShaderValidationError(naga::WithSpan<naga::valid::ValidationError>),
90    #[error(
91        "Not enough '# endif' lines. Each if statement should be followed by an endif statement."
92    )]
93    NotEnoughEndIfs(usize),
94    #[error("Too many '# endif' lines. Each endif should be preceded by an if statement.")]
95    TooManyEndIfs(usize),
96    #[error("'#else' without preceding condition.")]
97    ElseWithoutCondition(usize),
98    #[error("Unknown shader def operator: '{operator}'")]
99    UnknownShaderDefOperator { pos: usize, operator: String },
100    #[error("Unknown shader def: '{shader_def_name}'")]
101    UnknownShaderDef { pos: usize, shader_def_name: String },
102    #[error(
103        "Invalid shader def comparison for '{shader_def_name}': expected {expected}, got {value}"
104    )]
105    InvalidShaderDefComparisonValue {
106        pos: usize,
107        shader_def_name: String,
108        expected: String,
109        value: String,
110    },
111    #[error("multiple inconsistent shader def values: '{def}'")]
112    InconsistentShaderDefValue { def: String },
113    #[error("Attempted to add a module with no #define_import_path")]
114    NoModuleName,
115    #[error("source contains internal decoration string, results probably won't be what you expect. if you have a legitimate reason to do this please file a report")]
116    DecorationInSource(Range<usize>),
117    #[error("naga oil only supports glsl 440 and 450")]
118    GlslInvalidVersion(usize),
119    #[error("invalid override :{0}")]
120    RedirectError(#[from] RedirectError),
121    #[error(
122        "override is invalid as `{name}` is not virtual (this error can be disabled with feature 'override_any')"
123    )]
124    OverrideNotVirtual { name: String, pos: usize },
125    #[error(
126        "Composable module identifiers must not require substitution according to naga writeback rules: `{original}`"
127    )]
128    InvalidIdentifier { original: String, at: naga::Span },
129    #[error("Invalid value for `#define`d shader def {name}: {value}")]
130    InvalidShaderDefDefinitionValue {
131        name: String,
132        value: String,
133        pos: usize,
134    },
135    #[error("#define statements are only allowed at the start of the top-level shaders")]
136    DefineInModule(usize),
137}
138
139struct ErrorSources<'a> {
140    current: Option<&'a (dyn std::error::Error + 'static)>,
141}
142
143impl<'a> ErrorSources<'a> {
144    fn of(error: &'a dyn std::error::Error) -> Self {
145        Self {
146            current: error.source(),
147        }
148    }
149}
150
151impl<'a> Iterator for ErrorSources<'a> {
152    type Item = &'a (dyn std::error::Error + 'static);
153
154    fn next(&mut self) -> Option<Self::Item> {
155        let current = self.current;
156        self.current = self.current.and_then(std::error::Error::source);
157        current
158    }
159}
160
161// impl<'a> FusedIterator for ErrorSources<'a> {}
162
163impl ComposerError {
164    /// format a Composer error
165    pub fn emit_to_string(&self, composer: &Composer) -> String {
166        composer.undecorate(&self.emit_to_string_internal(composer))
167    }
168
169    fn emit_to_string_internal(&self, composer: &Composer) -> String {
170        let path = self.source.path(composer);
171        let source = self.source.source(composer);
172        let source_offset = self.source.offset();
173
174        trace!("source:\n~{}~", source);
175        trace!("source offset: {}", source_offset);
176
177        let map_span = |rng: Range<usize>| -> Range<usize> {
178            ((rng.start & ((1 << SPAN_SHIFT) - 1)).saturating_sub(source_offset))
179                ..((rng.end & ((1 << SPAN_SHIFT) - 1)).saturating_sub(source_offset))
180        };
181
182        let files = SimpleFile::new(path, source.as_str());
183        let config = term::Config::default();
184        let (labels, notes) = match &self.inner {
185            ComposerErrorInner::DecorationInSource(range) => {
186                (vec![Label::primary((), range.clone())], vec![])
187            }
188            ComposerErrorInner::HeaderValidationError(v)
189            | ComposerErrorInner::ShaderValidationError(v) => (
190                v.spans()
191                    .map(|(span, desc)| {
192                        trace!(
193                            "mapping span {:?} -> {:?}",
194                            span.to_range().unwrap_or(0..0),
195                            map_span(span.to_range().unwrap_or(0..0))
196                        );
197                        Label::primary((), map_span(span.to_range().unwrap_or(0..0)))
198                            .with_message(desc.to_owned())
199                    })
200                    .collect(),
201                ErrorSources::of(&v)
202                    .map(|source| source.to_string())
203                    .collect(),
204            ),
205            ComposerErrorInner::ImportNotFound(msg, pos) => (
206                vec![Label::primary((), *pos..*pos)],
207                vec![format!("missing import '{msg}'")],
208            ),
209            ComposerErrorInner::ImportParseError(msg, pos) => (
210                vec![Label::primary((), *pos..*pos)],
211                vec![format!("invalid import spec: '{msg}'")],
212            ),
213            ComposerErrorInner::WgslParseError(e) => (
214                e.labels()
215                    .map(|(range, msg)| {
216                        Label::primary((), map_span(range.to_range().unwrap_or(0..0)))
217                            .with_message(msg)
218                    })
219                    .collect(),
220                vec![e.message().to_owned()],
221            ),
222            #[cfg(feature = "glsl")]
223            ComposerErrorInner::GlslParseError(e) => (
224                e.errors
225                    .iter()
226                    .map(|naga::front::glsl::Error { kind, meta }| {
227                        Label::primary((), map_span(meta.to_range().unwrap_or(0..0)))
228                            .with_message(kind.to_string())
229                    })
230                    .collect(),
231                vec![],
232            ),
233            ComposerErrorInner::NotEnoughEndIfs(pos)
234            | ComposerErrorInner::TooManyEndIfs(pos)
235            | ComposerErrorInner::ElseWithoutCondition(pos)
236            | ComposerErrorInner::UnknownShaderDef { pos, .. }
237            | ComposerErrorInner::UnknownShaderDefOperator { pos, .. }
238            | ComposerErrorInner::InvalidShaderDefComparisonValue { pos, .. }
239            | ComposerErrorInner::OverrideNotVirtual { pos, .. }
240            | ComposerErrorInner::GlslInvalidVersion(pos)
241            | ComposerErrorInner::DefineInModule(pos)
242            | ComposerErrorInner::InvalidShaderDefDefinitionValue { pos, .. } => {
243                (vec![Label::primary((), *pos..*pos)], vec![])
244            }
245            ComposerErrorInner::WgslBackError(e) => {
246                return format!("{path}: wgsl back error: {e}");
247            }
248            #[cfg(feature = "glsl")]
249            ComposerErrorInner::GlslBackError(e) => {
250                return format!("{path}: glsl back error: {e}");
251            }
252            ComposerErrorInner::InconsistentShaderDefValue { def } => {
253                return format!("{path}: multiple inconsistent shader def values: '{def}'");
254            }
255            ComposerErrorInner::RedirectError(..) => (
256                vec![Label::primary((), 0..0)],
257                vec![format!("override error")],
258            ),
259            ComposerErrorInner::NoModuleName => {
260                return format!(
261                    "{path}: no #define_import_path declaration found in composable module"
262                );
263            }
264            ComposerErrorInner::InvalidIdentifier { at, .. } => (
265                vec![Label::primary((), map_span(at.to_range().unwrap_or(0..0)))
266                    .with_message(self.inner.to_string())],
267                vec![],
268            ),
269        };
270
271        let diagnostic = Diagnostic::error()
272            .with_message(self.inner.to_string())
273            .with_labels(labels)
274            .with_notes(notes);
275
276        let mut msg = Vec::with_capacity(256);
277
278        let mut color_writer;
279        let mut no_color_writer;
280        let writer: &mut dyn WriteColor = if supports_color() {
281            color_writer = term::termcolor::Ansi::new(&mut msg);
282            &mut color_writer
283        } else {
284            no_color_writer = term::termcolor::NoColor::new(&mut msg);
285            &mut no_color_writer
286        };
287
288        term::emit(writer, &config, &files, &diagnostic).expect("cannot write error");
289
290        String::from_utf8_lossy(&msg).into_owned()
291    }
292}
293
294#[cfg(any(test, target_arch = "wasm32"))]
295fn supports_color() -> bool {
296    false
297}
298
299// termcolor doesn't expose this logic when using custom buffers
300#[cfg(not(any(test, target_arch = "wasm32")))]
301fn supports_color() -> bool {
302    match std::env::var_os("TERM") {
303        None if cfg!(unix) => false,
304        Some(term) if term == "dumb" => false,
305        _ => std::env::var_os("NO_COLOR").is_none(),
306    }
307}