Skip to main content

naga/front/wgsl/
error.rs

1//! Formatting WGSL front end error messages.
2
3#![expect(
4    clippy::pattern_type_mismatch,
5    reason = "There are matches on references, since it produces less LLVM IR than dereferencing"
6)]
7
8use crate::common::wgsl::TryToWgsl;
9use crate::diagnostic_filter::ConflictingDiagnosticRuleError;
10use crate::error::replace_control_chars;
11use crate::proc::{Alignment, ConstantEvaluatorError, ResolveError};
12use crate::{Scalar, SourceLocation, Span, UnaryOperator};
13
14use super::parse::directive::enable_extension::{EnableExtension, UnimplementedEnableExtension};
15use super::parse::directive::language_extension::{
16    LanguageExtension, UnimplementedLanguageExtension,
17};
18use super::parse::lexer::Token;
19
20use codespan_reporting::diagnostic::{Diagnostic, Label};
21use codespan_reporting::files::SimpleFile;
22use codespan_reporting::term;
23use thiserror::Error;
24
25use alloc::{
26    borrow::Cow,
27    boxed::Box,
28    format,
29    string::{String, ToString},
30    vec,
31    vec::Vec,
32};
33use core::fmt::Write as _;
34use core::ops::Range;
35
36#[derive(Clone, Debug)]
37pub struct ParseError {
38    message: Cow<'static, str>,
39    // The first span should be the primary span, and the other ones should be complementary.
40    labels: Vec<(Span, Cow<'static, str>)>,
41    notes: Vec<Cow<'static, str>>,
42}
43
44impl ParseError {
45    pub fn labels(&self) -> impl ExactSizeIterator<Item = (Span, &str)> + '_ {
46        self.labels
47            .iter()
48            .map(|&(span, ref msg)| (span, msg.as_ref()))
49    }
50
51    pub fn message(&self) -> &str {
52        &self.message
53    }
54
55    pub fn notes(&self) -> impl ExactSizeIterator<Item = &str> + '_ {
56        self.notes.iter().map(Cow::as_ref)
57    }
58
59    fn diagnostic(&self) -> Diagnostic<()> {
60        let diagnostic = Diagnostic::error()
61            .with_message(self.message.to_string())
62            .with_labels(
63                self.labels
64                    .iter()
65                    .filter_map(|label| label.0.to_range().map(|range| (label, range)))
66                    .map(|(label, range)| {
67                        Label::primary((), range).with_message(label.1.to_string())
68                    })
69                    .collect(),
70            )
71            .with_notes(
72                self.notes
73                    .iter()
74                    .map(|note| format!("note: {note}"))
75                    .collect(),
76            );
77        diagnostic
78    }
79
80    /// Emits a summary of the error to standard error stream.
81    #[cfg(feature = "stderr")]
82    pub fn emit_to_stderr(&self, source: &str) {
83        self.emit_to_stderr_with_path(source, "wgsl")
84    }
85
86    /// Emits a summary of the error to standard error stream.
87    #[cfg(feature = "stderr")]
88    pub fn emit_to_stderr_with_path<P>(&self, source: &str, path: P)
89    where
90        P: AsRef<std::path::Path>,
91    {
92        let path = path.as_ref().display().to_string();
93        let files = SimpleFile::new(path, replace_control_chars(source));
94        let config = term::Config::default();
95
96        cfg_if::cfg_if! {
97            if #[cfg(feature = "termcolor")] {
98                let writer = term::termcolor::StandardStream::stderr(term::termcolor::ColorChoice::Auto);
99                term::emit_to_write_style(&mut writer.lock(), &config, &files, &self.diagnostic())
100                    .expect("cannot write error");
101            } else {
102                let writer = std::io::stderr();
103                term::emit_to_io_write(&mut writer.lock(), &config, &files, &self.diagnostic())
104                    .expect("cannot write error");
105            }
106        }
107    }
108
109    /// Emits a summary of the error to a string.
110    pub fn emit_to_string(&self, source: &str) -> String {
111        self.emit_to_string_with_path(source, "wgsl")
112    }
113
114    /// Emits a summary of the error to a string.
115    ///
116    /// `path` gives the filename to attribute the error to in the
117    /// output; this function does not try to access the file.
118    pub fn emit_to_string_with_path(&self, source: &str, path: &str) -> String {
119        let files = SimpleFile::new(path, replace_control_chars(source));
120        let config = term::Config::default();
121
122        let mut writer = crate::error::DiagnosticBuffer::new();
123        writer
124            .emit_to_self(&config, &files, &self.diagnostic())
125            .expect("cannot write error");
126        writer.into_string()
127    }
128
129    /// Returns a [`SourceLocation`] for the first label in the error message.
130    pub fn location(&self, source: &str) -> Option<SourceLocation> {
131        self.labels.first().map(|label| label.0.location(source))
132    }
133}
134
135impl core::fmt::Display for ParseError {
136    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
137        write!(f, "{}", self.message)
138    }
139}
140
141impl core::error::Error for ParseError {}
142
143#[cfg(test)]
144mod parse_error_tests {
145
146    #[test]
147    fn test_notes() {
148        use crate::front::wgsl::parse_str;
149        // wgsl code and notes taken from: `cross_vec2()` in naga/tests/naga/wgsl_errors.rs
150        assert_eq!(
151            parse_str(
152                r#"
153            fn x() -> f32 {
154                return cross(vec2(0., 1.), vec2(0., 1.));
155            }
156        "#,
157            )
158            .unwrap_err()
159            .notes()
160            .collect::<super::Vec<_>>(),
161            [
162                "`cross` accepts the following types for argument #1:",
163                "allowed type: vec3<{AbstractFloat}>",
164                "allowed type: vec3<f32>",
165                "allowed type: vec3<f16>",
166                "allowed type: vec3<f64>"
167            ]
168            .to_vec()
169        );
170    }
171}
172
173#[derive(Copy, Clone, Debug, PartialEq)]
174pub enum ExpectedToken<'a> {
175    Token(Token<'a>),
176    Identifier,
177    AfterIdentListComma,
178    AfterIdentListArg,
179    /// LHS expression (identifier component_or_swizzle_specifier?, (`lhs_expression`) component_or_swizzle_specifier?, &`lhs_expression`, *`lhs_expression`)
180    LhsExpression,
181    /// Expected: constant, parenthesized expression, identifier
182    PrimaryExpression,
183    /// Expected: assignment, increment/decrement expression
184    Assignment,
185    /// Expected: 'case', 'default', '}'
186    SwitchItem,
187    /// Expected: ',', ')'
188    WorkgroupSizeSeparator,
189    /// Expected: 'struct', 'let', 'var', 'type', ';', 'fn', eof
190    GlobalItem,
191    /// Access of `var`, `let`, `const`.
192    Variable,
193    /// Access of a function
194    Function,
195    /// The `diagnostic` identifier of the `@diagnostic(…)` attribute.
196    DiagnosticAttribute,
197    /// statement
198    Statement,
199    /// for loop init statement (variable_or_value_statement, variable_updating_statement, func_call_statement)
200    ForInit,
201    /// for loop update statement (variable_updating_statement, func_call_statement)
202    ForUpdate,
203}
204
205impl core::fmt::Display for ExpectedToken<'_> {
206    #[expect(
207        unused,
208        reason = "This ignores write errors, since this should only be called to write into a \
209                  String, which is infallible. Ignoring errors lowers binary bloat from this \
210                  function."
211    )]
212    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
213        // This function uses a temporary enum here to lower binary bloat by merging calls to
214        // write_str.
215        //
216        // Tokens where the output is already a single string (such as Token::Number) use Kind::Str.
217        // Tokens where the output is made up of two static strings split by a char (such as
218        // Token::Operation) use Kind::FormatChar
219        // Tokens where the output is 3 strings concatenated (such as Token::DocComment) use
220        // Kind::FormatStr
221        //
222        // Any exceptions (such as Token::ShiftOperation) handle their cases explicitly and return
223        enum Kind<'a> {
224            Str(&'a str),
225            FormatChar(&'static str, char, &'static str),
226            FormatStr([&'a str; 3]),
227        }
228
229        let kind = match *self {
230            ExpectedToken::Token(token) => match token {
231                Token::Separator(c) | Token::Paren(c) => Kind::FormatChar("`", c, "`"),
232                Token::Attribute => Kind::Str("@"),
233                Token::Number(_) => Kind::Str("number"),
234                Token::Word(s) => Kind::Str(s),
235                Token::String(_) => Kind::Str("string literal"),
236                Token::Operation(c) => Kind::FormatChar("operation (`", c, "`)"),
237                Token::LogicalOperation(c) => Kind::FormatChar("logical operation (`", c, "`)"),
238                Token::ShiftOperation(c) => {
239                    f.write_str("bitshift (`");
240                    f.write_char(c);
241                    f.write_char(c);
242                    f.write_str("`)");
243                    return Ok(())
244                },
245                Token::AssignmentOperation(c) if c == '<' || c == '>' => {
246                    f.write_str("bitshift (`");
247                    f.write_char(c);
248                    f.write_char(c);
249                    f.write_str("=`)");
250                    return Ok(())
251                }
252                Token::AssignmentOperation(c) => Kind::FormatChar("operation (`", c, "=`)"),
253                Token::IncrementOperation => Kind::Str("increment operation"),
254                Token::DecrementOperation => Kind::Str("decrement operation"),
255                Token::Arrow => Kind::Str("->"),
256                Token::TemplateArgsStart => Kind::Str("template args start"),
257                Token::TemplateArgsEnd => Kind::Str("template args end"),
258                Token::Unknown(c) => Kind::FormatChar("unknown (`", c, "`)"),
259                Token::Trivia => Kind::Str("trivia"),
260                Token::DocComment(s) => Kind::FormatStr(["doc comment ('", s, "')"]),
261                Token::ModuleDocComment(s) => Kind::FormatStr(["module doc comment ('", s, "')"]),
262                Token::End => Kind::Str("end"),
263                Token::UnterminatedBlockComment(s) => {
264                    Kind::FormatStr(["unterminated doc comment ('", s, "')"])
265                }
266            },
267            ExpectedToken::Identifier => Kind::Str("identifier"),
268            ExpectedToken::LhsExpression => Kind::Str("LHS expression (identifier component_or_swizzle_specifier?, (`lhs_expression`) component_or_swizzle_specifier?, &`lhs_expression`, *`lhs_expression`)"),
269            ExpectedToken::PrimaryExpression => Kind::Str("expression"),
270            ExpectedToken::Assignment => Kind::Str("assignment or increment/decrement"),
271            ExpectedToken::SwitchItem => Kind::Str(concat!(
272                "switch item (`case` or `default`) or a closing curly bracket ",
273                "to signify the end of the switch statement (`}`)"
274            )),
275            ExpectedToken::WorkgroupSizeSeparator => {
276                Kind::Str("workgroup size separator (`,`) or a closing parenthesis")
277            }
278            ExpectedToken::GlobalItem => Kind::Str(concat!(
279                "global item (`struct`, `const`, `var`, `alias`, ",
280                "`fn`, `diagnostic`, `enable`, `requires`, `;`) ",
281                "or the end of the file"
282            )),
283            ExpectedToken::Variable => Kind::Str("variable access"),
284            ExpectedToken::Function => Kind::Str("function name"),
285            ExpectedToken::AfterIdentListArg => {
286                Kind::Str("next argument, trailing comma, or end of list (`,` or `;`)")
287            }
288            ExpectedToken::AfterIdentListComma => {
289                Kind::Str("next argument or end of list (`;`)")
290            }
291            ExpectedToken::DiagnosticAttribute => {
292                Kind::Str("the `diagnostic` attribute identifier")
293            }
294            ExpectedToken::Statement => Kind::Str("statement"),
295            ExpectedToken::ForInit => Kind::Str("for loop initializer statement (`var`/`let`/`const` declaration, assignment, `i++`/`i--` statement, function call)"),
296            ExpectedToken::ForUpdate => Kind::Str("for loop update statement (assignment, `i++`/`i--` statement, function call)"),
297        };
298
299        match kind {
300            Kind::Str(s) => {
301                f.write_str(s);
302            }
303            Kind::FormatChar(a, b, c) => {
304                f.write_str(a);
305                f.write_char(b);
306                f.write_str(c);
307            }
308            Kind::FormatStr(strings) => {
309                for s in strings {
310                    f.write_str(s);
311                }
312            }
313        }
314
315        Ok(())
316    }
317}
318
319#[derive(Clone, Copy, Debug, Error, PartialEq)]
320pub enum NumberError {
321    #[error("invalid numeric literal format")]
322    Invalid,
323    #[error("numeric literal not representable by target type")]
324    NotRepresentable,
325}
326
327#[derive(Copy, Clone, Debug, PartialEq)]
328pub enum InvalidAssignmentType {
329    Other,
330    Swizzle,
331    ImmutableBinding(Span),
332}
333
334#[derive(Clone, Debug)]
335pub(crate) enum Error<'a> {
336    Unexpected(Span, ExpectedToken<'a>),
337    UnexpectedComponents(Span),
338    UnexpectedOperationInConstContext(Span),
339    BadNumber(Span, NumberError),
340    BadMatrixScalarKind(Span, Scalar),
341    BadAccessor(Span),
342    BadTexture(Span),
343    BadTypeCast {
344        span: Span,
345        from_type: String,
346        to_type: String,
347    },
348    NotStorageTexture(Span),
349    BadTextureSampleType {
350        span: Span,
351        scalar: Scalar,
352    },
353    BadIncrDecrReferenceType(Span),
354    InvalidResolve(ResolveError),
355    /// A break if appeared outside of a continuing block
356    InvalidBreakIf(Span),
357    InvalidGatherComponent(Span),
358    InvalidConstructorComponentType(Span, i32),
359    InvalidIdentifierUnderscore(Span),
360    ReservedIdentifierPrefix(Span),
361    UnknownAddressSpace(Span),
362    InvalidLocalVariableAddressSpace(Span),
363    UnknownRayFlag(Span),
364    RepeatedAttribute(Span),
365    UnknownAttribute(Span),
366    UnknownBuiltin(Span),
367    UnknownAccess(Span),
368    UnknownIdent(Span, &'a str),
369    UnknownScalarType(Span),
370    UnknownStorageFormat(Span),
371    UnknownConservativeDepth(Span),
372    UnknownEnableExtension(Span, &'a str),
373    UnknownLanguageExtension(Span, &'a str),
374    UnknownDiagnosticRuleName(Span),
375    SizeAttributeTooLow(Span, u32),
376    SizeAttributeRequiresFixedFootprint(Span),
377    AlignAttributeTooLow(Span, Alignment),
378    NonPowerOfTwoAlignAttribute(Span),
379    InconsistentBinding(Span),
380    TypeNotConstructible(Span),
381    TypeNotInferable(Span),
382    InitializationTypeMismatch {
383        name: Span,
384        expected: String,
385        got: String,
386    },
387    DeclMissingTypeAndInit(Span),
388    MissingAttribute(&'static str, Span),
389    InvalidUnaryOperandType {
390        span: Span,
391        op: UnaryOperator,
392        operand_type: String,
393    },
394
395    InvalidAddrOfOperand(Span),
396    InvalidAtomicPointer(Span),
397    InvalidAtomicOperandType(Span),
398    InvalidAtomicAccess(Span),
399    InvalidRayQueryPointer(Span),
400    InvalidHitObjectPointer(Span),
401    NotPointer(Span),
402    NotReference(&'static str, Span),
403    InvalidAssignment {
404        span: Span,
405        ty: InvalidAssignmentType,
406    },
407    ReservedKeyword(Span),
408    /// Redefinition of an identifier (used for both module-scope and local redefinitions).
409    Redefinition {
410        /// Span of the identifier in the previous definition.
411        previous: Span,
412
413        /// Span of the identifier in the new definition.
414        current: Span,
415    },
416    /// A declaration refers to itself directly.
417    RecursiveDeclaration {
418        /// The location of the name of the declaration.
419        ident: Span,
420
421        /// The point at which it is used.
422        usage: Span,
423    },
424    /// A declaration refers to itself indirectly, through one or more other
425    /// definitions.
426    CyclicDeclaration {
427        /// The location of the name of some declaration in the cycle.
428        ident: Span,
429
430        /// The edges of the cycle of references.
431        ///
432        /// Each `(decl, reference)` pair indicates that the declaration whose
433        /// name is `decl` has an identifier at `reference` whose definition is
434        /// the next declaration in the cycle. The last pair's `reference` is
435        /// the same identifier as `ident`, above.
436        path: Box<[(Span, Span)]>,
437    },
438    InvalidSwitchSelector {
439        span: Span,
440    },
441    InvalidSwitchCase {
442        span: Span,
443    },
444    SwitchCaseTypeMismatch {
445        span: Span,
446    },
447    CalledEntryPoint(Span),
448    CalledLocalDecl(Span),
449    WrongArgumentCount {
450        span: Span,
451        expected: Range<u32>,
452        found: u32,
453    },
454    /// No overload of this function accepts this many arguments.
455    TooManyArguments {
456        /// The name of the function being called.
457        function: String,
458
459        /// The function name in the call expression.
460        call_span: Span,
461
462        /// The first argument that is unacceptable.
463        arg_span: Span,
464
465        /// Maximum number of arguments accepted by any overload of
466        /// this function.
467        max_arguments: u32,
468    },
469    /// A value passed to a builtin function has a type that is not
470    /// accepted by any overload of the function.
471    WrongArgumentType {
472        /// The name of the function being called.
473        function: String,
474
475        /// The function name in the call expression.
476        call_span: Span,
477
478        /// The first argument whose type is unacceptable.
479        arg_span: Span,
480
481        /// The index of the first argument whose type is unacceptable.
482        arg_index: u32,
483
484        /// That argument's actual type.
485        arg_ty: String,
486
487        /// The set of argument types that would have been accepted for
488        /// this argument, given the prior arguments.
489        allowed: Vec<String>,
490    },
491    /// A value passed to a builtin function has a type that is not
492    /// accepted, given the earlier arguments' types.
493    InconsistentArgumentType {
494        /// The name of the function being called.
495        function: String,
496
497        /// The function name in the call expression.
498        call_span: Span,
499
500        /// The first unacceptable argument.
501        arg_span: Span,
502
503        /// The index of the first unacceptable argument.
504        arg_index: u32,
505
506        /// The actual type of the first unacceptable argument.
507        arg_ty: String,
508
509        /// The prior argument whose type made the `arg_span` argument
510        /// unacceptable.
511        inconsistent_span: Span,
512
513        /// The index of the `inconsistent_span` argument.
514        inconsistent_index: u32,
515
516        /// The type of the `inconsistent_span` argument.
517        inconsistent_ty: String,
518
519        /// The types that would have been accepted instead of the
520        /// first unacceptable argument.
521        allowed: Vec<String>,
522    },
523    FunctionReturnsVoid(Span),
524    FunctionMustUseUnused(Span),
525    FunctionMustUseReturnsVoid(Span, Span),
526    FunctionMustUseOnNonFunction(Span),
527    InvalidWorkGroupUniformLoad(Span),
528    InvalidStringLiteral {
529        span: Span,
530        description: &'static str,
531    },
532    ExpectedStringLiteral {
533        span: Span,
534        description: &'static str,
535    },
536    Internal(&'static str),
537    ExpectedConstExprConcreteIntegerScalar(Span),
538    ExpectedNonNegative(Span),
539    ExpectedPositiveArrayLength(Span),
540    MissingWorkgroupSize(Span),
541    ConstantEvaluatorError(Box<ConstantEvaluatorError>, Span),
542    TypeMismatch(Box<TypeMismatchError>),
543    AutoConversion(Box<AutoConversionError>),
544    AutoConversionLeafScalar(Box<AutoConversionLeafScalarError>),
545    ConcretizationFailed(Box<ConcretizationFailedError>),
546    ExceededLimitForNestedBraces {
547        span: Span,
548        limit: u8,
549    },
550    PipelineConstantIDValue(Span),
551    NotBool(Span),
552    ConstAssertFailed(Span),
553    DirectiveAfterFirstGlobalDecl {
554        directive_span: Span,
555    },
556    EnableExtensionNotYetImplemented {
557        kind: UnimplementedEnableExtension,
558        span: Span,
559    },
560    EnableExtensionNotEnabled {
561        kind: EnableExtension,
562        span: Span,
563    },
564    EnableExtensionNotSupported {
565        kind: EnableExtension,
566        span: Span,
567    },
568    LanguageExtensionNotYetImplemented {
569        kind: UnimplementedLanguageExtension,
570        span: Span,
571    },
572    DiagnosticInvalidSeverity {
573        severity_control_name_span: Span,
574    },
575    DiagnosticDuplicateTriggeringRule(ConflictingDiagnosticRuleError),
576    DiagnosticAttributeNotYetImplementedAtParseSite {
577        site_name_plural: &'static str,
578        spans: Vec<Span>,
579    },
580    DiagnosticAttributeNotSupported {
581        on_what: DiagnosticAttributeNotSupportedPosition,
582        spans: Vec<Span>,
583    },
584    SelectUnexpectedArgumentType {
585        arg_span: Span,
586        arg_type: String,
587    },
588    SelectRejectAndAcceptHaveNoCommonType {
589        reject_span: Span,
590        reject_type: String,
591        accept_span: Span,
592        accept_type: String,
593    },
594    ExpectedGlobalVariable {
595        name_span: Span,
596    },
597    StructMemberTooLarge {
598        member_name_span: Span,
599    },
600    TypeTooLarge {
601        span: Span,
602    },
603    UnderspecifiedCooperativeMatrix,
604    InvalidCooperativeLoadType(Span),
605    UnsupportedCooperativeScalar(Span),
606    UnexpectedIdentForEnumerant(Span),
607    UnexpectedExprForEnumerant(Span),
608    UnusedArgsForTemplate(Vec<Span>),
609    UnexpectedTemplate(Span),
610    MissingTemplateArg {
611        span: Span,
612        description: &'static str,
613    },
614    UnexpectedExprForTypeExpression(Span),
615    MissingIncomingPayload(Span),
616    UnterminatedBlockComment(Span),
617    RayQueryWithInitializer(Span),
618    HitObjectWithInitializer(Span),
619}
620
621impl From<ConflictingDiagnosticRuleError> for Error<'_> {
622    fn from(value: ConflictingDiagnosticRuleError) -> Self {
623        Self::DiagnosticDuplicateTriggeringRule(value)
624    }
625}
626
627/// Used for diagnostic refinement in [`Error::DiagnosticAttributeNotSupported`].
628#[derive(Clone, Copy, Debug)]
629pub(crate) enum DiagnosticAttributeNotSupportedPosition {
630    SemicolonInModulePosition,
631    Other { display_plural: &'static str },
632}
633
634impl From<&'static str> for DiagnosticAttributeNotSupportedPosition {
635    fn from(display_plural: &'static str) -> Self {
636        Self::Other { display_plural }
637    }
638}
639
640/// A value's concrete type differs from the type required by its context.
641#[derive(Clone, Debug)]
642pub(crate) struct TypeMismatchError {
643    /// Where the required type comes from.
644    pub dest_span: Span,
645    pub dest_type: String,
646    /// The value whose type is wrong.
647    pub source_span: Span,
648    pub source_type: String,
649}
650
651#[derive(Clone, Debug)]
652pub(crate) struct AutoConversionError {
653    pub dest_span: Span,
654    pub dest_type: String,
655    pub source_span: Span,
656    pub source_type: String,
657}
658
659#[derive(Clone, Debug)]
660pub(crate) struct AutoConversionLeafScalarError {
661    pub dest_span: Span,
662    pub dest_scalar: String,
663    pub source_span: Span,
664    pub source_type: String,
665}
666
667#[derive(Clone, Debug)]
668pub(crate) struct ConcretizationFailedError {
669    pub expr_span: Span,
670    pub expr_type: String,
671    pub concretization_preferences: Vec<(String, ConstantEvaluatorError)>,
672}
673
674impl<'a> Error<'a> {
675    #[cold]
676    #[inline(never)]
677    // This function is not recursive, so it can exceed our conservatively-set
678    // `stack-frame-limit` without causing problems.
679    #[allow(clippy::large_stack_frames)]
680    pub(crate) fn as_parse_error(&self, source: &'a str) -> ParseError {
681        // This function normally produces a lot of binary bloat, so has been structured in a
682        // non-idiomatic way to minimize its size.
683        //
684        // Errors where the output has a static message and a single, static label are handled in
685        // the block starting with UnexpectedComponents.
686        //
687        // Errors where the output has a single static label, and a message in the form
688        // "..{&source[span]}.." are handled in the block starting with BadAccessor.
689        //
690        // Other errors with a single static label, and a non-static message are handled in the
691        // block starting with BadMatrixScalarKind.
692        //
693        // Other errors are handled on their own.
694        //
695        // If you're adding a new error type, and you're not sure where to put it, you can put it
696        // on its own; there'll only be a small difference in size from one variant :)
697
698        match self {
699            Error::Unexpected(unexpected_span, expected) => {
700                ParseError {
701                    message: format!(
702                        "expected {expected}, found {:?}",
703                        &source[*unexpected_span]
704                    ).into(),
705                    labels: vec![(*unexpected_span, format!("expected {expected}").into())],
706                    notes: vec![],
707                }
708            }
709            // Variants where message and label are static strings
710            Error::UnexpectedComponents(span)
711                | Error::UnexpectedOperationInConstContext(span)
712                | Error::NotStorageTexture(span)
713                | Error::BadIncrDecrReferenceType(span)
714                | Error::InvalidBreakIf(span)
715                | Error::NonPowerOfTwoAlignAttribute(span)
716                | Error::InconsistentBinding(span)
717                | Error::TypeNotInferable(span)
718                | Error::InvalidAddrOfOperand(span)
719                | Error::InvalidAtomicPointer(span)
720                | Error::InvalidAtomicOperandType(span)
721                | Error::InvalidAtomicAccess(span)
722                | Error::InvalidRayQueryPointer(span)
723                | Error::InvalidHitObjectPointer(span)
724                | Error::NotPointer(span)
725                | Error::InvalidSwitchSelector { span }
726                | Error::InvalidSwitchCase { span }
727                | Error::SwitchCaseTypeMismatch { span }
728                | Error::CalledEntryPoint(span)
729                | Error::CalledLocalDecl(span)
730                | Error::ExpectedConstExprConcreteIntegerScalar(span)
731                | Error::ExpectedNonNegative(span)
732                | Error::ExpectedPositiveArrayLength(span)
733                | Error::MissingWorkgroupSize(span)
734                | Error::PipelineConstantIDValue(span)
735                | Error::NotBool(span)
736                | Error::ConstAssertFailed(span)
737                | Error::ExpectedGlobalVariable { name_span: span }
738                | Error::UnexpectedExprForEnumerant(span)
739                | Error::UnexpectedTemplate(span)
740                | Error::UnexpectedExprForTypeExpression(span)
741                | Error::MissingIncomingPayload(span) => {
742                let (message, label) = match self {
743                    Error::UnexpectedComponents(_) => (
744                        "unexpected components",
745                        "unexpected components"
746                    ),
747                    Error::UnexpectedOperationInConstContext(_) => (
748                        "this operation is not supported in a const context",
749                        "operation not supported here"
750                    ),
751                    Error::NotStorageTexture(_) => (
752                        "textureStore can only be applied to storage textures",
753                        "not a storage texture"
754                    ),
755                    Error::BadIncrDecrReferenceType(_) => (
756                        concat!(
757                            "increment/decrement operation requires ",
758                            "reference type to be one of i32 or u32"
759                        ),
760                        "must be a reference type of i32 or u32"
761                    ),
762                    Error::InvalidBreakIf(_) => (
763                        "A break if is only allowed in a continuing block",
764                        "not in a continuing block"
765                    ),
766                    Error::NonPowerOfTwoAlignAttribute(_) => (
767                        "struct member alignment must be a power of 2",
768                        "must be a power of 2"
769                    ),
770                    Error::InconsistentBinding(_) => (
771                        "input/output binding is not consistent",
772                        "input/output binding is not consistent"
773                    ),
774                    Error::TypeNotInferable(_) => (
775                        "type can't be inferred",
776                        "type can't be inferred"
777                    ),
778                    Error::InvalidAddrOfOperand(_) => (
779                        "cannot take the address of a vector component",
780                        "invalid operand for address-of"
781                    ),
782                    Error::InvalidAtomicPointer(_) => (
783                        "atomic operation is done on a pointer to a non-atomic",
784                        "atomic pointer is invalid"
785                    ),
786                    Error::InvalidAtomicOperandType(_) => (
787                        "atomic operand type is inconsistent with the operation",
788                        "atomic operand type is invalid"
789                    ),
790                    Error::InvalidAtomicAccess(_) => (
791                        "direct access to atomic variable is not allowed",
792                        "atomic variables cannot be accessed directly; use atomic built-in functions",
793                    ),
794                    Error::InvalidRayQueryPointer(_) => (
795                        "ray query operation is done on a pointer to a non-ray-query",
796                        "ray query pointer is invalid"
797                    ),
798                    Error::InvalidHitObjectPointer(_) => (
799                        "hit object operation is done on a pointer to a non-hit-object",
800                        "hit object pointer is invalid"
801                    ),
802                    Error::NotPointer(_) => (
803                        "the operand of the `*` operator must be a pointer",
804                        "expression is not a pointer"
805                    ),
806                    Error::InvalidSwitchSelector { .. } => (
807                        "invalid `switch` selector",
808                        "`switch` selector must be a scalar integer"
809                    ),
810                    Error::InvalidSwitchCase { .. } => (
811                        "invalid `switch` case selector value",
812                        "`switch` case selector must be a scalar integer const expression"
813                    ),
814                    Error::SwitchCaseTypeMismatch { .. } => (
815                        "invalid `switch` case selector value",
816                        "`switch` case selector must have the same type as the `switch` selector expression"
817                    ),
818                    Error::CalledEntryPoint(_) => (
819                        "entry point cannot be called",
820                        "entry point cannot be called"
821                    ),
822                    Error::CalledLocalDecl(_) => (
823                        "local declaration cannot be called",
824                        "local declaration cannot be called"
825                    ),
826                    Error::ExpectedConstExprConcreteIntegerScalar(_) => (
827                        concat!(
828                            "must be a const-expression that ",
829                            "resolves to a concrete integer scalar (`u32` or `i32`)"
830                        ),
831                        "must resolve to `u32` or `i32`"
832                    ),
833                    Error::ExpectedNonNegative(_) => (
834                        "must be non-negative (>= 0)",
835                        "must be non-negative"
836                    ),
837                    Error::ExpectedPositiveArrayLength(_) => (
838                        "array element count must be positive (> 0)",
839                        "must be positive"
840                    ),
841                    Error::MissingWorkgroupSize(_) => (
842                        "workgroup size is missing on compute shader entry point",
843                        "must be paired with a `@workgroup_size` attribute"
844                    ),
845                    Error::PipelineConstantIDValue(_) => (
846                        "pipeline constant ID must be between 0 and 65535 inclusive",
847                        "must be between 0 and 65535 inclusive"
848                    ),
849                    Error::NotBool(_) => (
850                        "must be a const-expression that resolves to a `bool`",
851                        "must resolve to `bool`"
852                    ),
853                    Error::ConstAssertFailed(_) => (
854                        "`const_assert` failure",
855                        "evaluates to `false`"
856                    ),
857                    Error::ExpectedGlobalVariable { .. } => (
858                        "expected global variable",
859                        "variable used here"
860                    ),
861                    Error::UnexpectedExprForEnumerant(_) => (
862                        "unexpected expression",
863                        "needs to be an identifier resolving to a predeclared enumerant"
864                    ),
865                    Error::UnexpectedTemplate(_) => (
866                        "unexpected template",
867                        "expected identifier"
868                    ),
869                    Error::UnexpectedExprForTypeExpression(_) => (
870                        "unexpected expression",
871                        "needs to be an identifier resolving to a type declaration (alias or struct) or predeclared type(-generator)"
872                    ),
873                    Error::MissingIncomingPayload(_) => (
874                        "incoming payload is missing on a `closest_hit`, `any_hit` or `miss` shader entry point",
875                        "must be paired with a `@incoming_payload` attribute"
876                    ),
877                    _ => unreachable!()
878                };
879
880                ParseError {
881                    labels: vec![(*span, label.into())],
882                    message: message.into(),
883                    notes: vec![],
884                }
885            },
886            // Variants with a static label, and a message in the form "..{&source[span]}.."
887            Error::BadAccessor(span)
888                | Error::BadTexture(span)
889                | Error::InvalidGatherComponent(span)
890                | Error::ReservedIdentifierPrefix(span)
891                | Error::UnknownAddressSpace(span)
892                | Error::InvalidLocalVariableAddressSpace(span)
893                | Error::UnknownRayFlag(span)
894                | Error::RepeatedAttribute(span)
895                | Error::UnknownAttribute(span)
896                | Error::UnknownBuiltin(span)
897                | Error::UnknownAccess(span)
898                | Error::UnknownStorageFormat(span)
899                | Error::UnknownConservativeDepth(span)
900                | Error::TypeNotConstructible(span)
901                | Error::DeclMissingTypeAndInit(span)
902                | Error::UnexpectedIdentForEnumerant(span) => {
903                let (message_a, message_b, label) = match self {
904                    Error::BadAccessor(_) => (
905                        "invalid field accessor `",
906                        "`",
907                        "invalid accessor"
908                    ),
909                    Error::BadTexture(_) => (
910                        "expected an image, but found `",
911                        "` which is not an image",
912                        "not an image"
913                    ),
914                    Error::InvalidGatherComponent(_) => (
915                        "textureGather component `",
916                        "` doesn't exist, must be 0, 1, 2, or 3",
917                        "invalid component"
918                    ),
919                    Error::ReservedIdentifierPrefix(_) => (
920                        "Identifier starts with a reserved prefix: `",
921                        "`",
922                        "invalid identifier"
923                    ),
924                    Error::UnknownAddressSpace(_) => (
925                        "unknown address space: `",
926                        "`",
927                        "unknown address space"
928                    ),
929                    Error::InvalidLocalVariableAddressSpace(_) => (
930                        "invalid address space for local variable: `",
931                        "`",
932                        "local variables can only use 'function' address space"
933                    ),
934                    Error::UnknownRayFlag(_) => (
935                        "unknown ray flag: `",
936                        "`",
937                        "unknown ray flag"
938                    ),
939                    Error::RepeatedAttribute(_) => (
940                        "repeated attribute: `",
941                        "`",
942                        "repeated attribute"
943                    ),
944                    Error::UnknownAttribute(_) => (
945                        "unknown attribute: `",
946                        "`",
947                        "unknown attribute"
948                    ),
949                    Error::UnknownBuiltin(_) => (
950                        "unknown builtin: `",
951                        "`",
952                        "unknown builtin"
953                    ),
954                    Error::UnknownAccess(_) => (
955                        "unknown access: `",
956                        "`",
957                        "unknown access"
958                    ),
959                    Error::UnknownStorageFormat(_) => (
960                        "unknown storage format: `",
961                        "`",
962                        "unknown storage format"
963                    ),
964                    Error::UnknownConservativeDepth(_) => (
965                        "unknown conservative depth: `",
966                        "`",
967                        "unknown conservative depth"
968                    ),
969                    Error::TypeNotConstructible(_) => (
970                        "type `",
971                        "` is not constructible",
972                        "type is not constructible"
973                    ),
974                    Error::DeclMissingTypeAndInit(_) => (
975                        "declaration of `",
976                        "` needs a type specifier or initializer",
977                        "needs a type specifier or initializer"
978                    ),
979                    Error::UnexpectedIdentForEnumerant(_) => (
980                        "identifier `",
981                        "` resolves to a declaration",
982                        "needs to resolve to a predeclared enumerant"
983                    ),
984                    _ => unreachable!()
985                };
986
987                ParseError {
988                    message: [message_a, &source[*span], message_b].concat().into(),
989                    labels: vec![(*span, label.into())],
990                    notes: vec![]
991                }
992            },
993            // Other variants with a single static label and no notes
994            Error::BadMatrixScalarKind(span, _)
995                | Error::UnknownIdent(span, _)
996                | Error::BadTextureSampleType { span, .. }
997                | Error::InvalidConstructorComponentType(span, _)
998                | Error::NotReference(_, span)
999                | Error::WrongArgumentCount { span, .. }
1000                | Error::ConstantEvaluatorError(_, span)
1001                | Error::EnableExtensionNotSupported { span, .. }
1002                | Error::InvalidUnaryOperandType { span, .. }
1003                | Error::MissingTemplateArg { span, .. } => {
1004                let (message, label) = match self {
1005                    Error::BadMatrixScalarKind(_, scalar) => (
1006                        format!(
1007                            "matrix scalar type must be floating-point, but found `{}`",
1008                            scalar.to_wgsl_for_diagnostics()
1009                        ),
1010                        "must be floating-point (e.g. `f32`)"
1011                    ),
1012                    Error::UnknownIdent(_, ident) => (
1013                        format!("no definition in scope for identifier: `{ident}`"),
1014                        "unknown identifier"
1015                    ),
1016                    Error::BadTextureSampleType { scalar, .. } => (
1017                        format!(
1018                            "texture sample type must be one of f32, i32 or u32, but found {}",
1019                            scalar.to_wgsl_for_diagnostics()
1020                        ),
1021                        "must be one of f32, i32 or u32"
1022                    ),
1023                    Error::InvalidConstructorComponentType(_, component) => (
1024                        format!("invalid type for constructor component at index [{component}]"),
1025                        "invalid component type"
1026                    ),
1027                    Error::NotReference(what, _) => (
1028                        format!("{what} must be a reference"),
1029                        "expression is not a reference"
1030                    ),
1031                    Error::WrongArgumentCount {
1032                        ref expected,
1033                        found,
1034                        ..
1035                    } => (
1036                        format!(
1037                            "wrong number of arguments: expected {}, found {}",
1038                            if expected.len() < 2 {
1039                                format!("{}", expected.start)
1040                            } else {
1041                                format!("{}..{}", expected.start, expected.end)
1042                            },
1043                            found
1044                        ),
1045                        "wrong number of arguments"
1046                    ),
1047                    Error::ConstantEvaluatorError(ref e, _) => (e.to_string(), "see msg"),
1048                    Error::EnableExtensionNotSupported { kind, .. } => (
1049                        format!(
1050                            "the `{}` extension is not supported in the current environment",
1051                            kind.to_ident()
1052                        ),
1053                        "unsupported enable-extension"
1054                    ),
1055                    Error::MissingTemplateArg { description, .. } => (
1056                        format!(
1057                            "`{}` needs a template argument specified: {description}",
1058                            &source[*span]
1059                        ),
1060                        "is missing a template argument"
1061                    ),
1062                    Error::InvalidUnaryOperandType { op, operand_type, .. } => {
1063                        let operator = match op {
1064                            UnaryOperator::Negate => "-",
1065                            UnaryOperator::LogicalNot => "!",
1066                            UnaryOperator::BitwiseNot => "~",
1067                        };
1068                        (
1069                            format!(
1070                                "unary operator `{operator}` is not defined for operand type `{}`",
1071                                operand_type
1072                            ),
1073                            "invalid operand type for this operator"
1074                        )
1075                    },
1076                    _ => unreachable!()
1077                };
1078
1079                ParseError {
1080                    message: message.into(),
1081                    labels: vec![(*span, label.into())],
1082                    notes: vec![]
1083                }
1084            },
1085            Error::BadNumber(bad_span, ref err) => ParseError {
1086                message: format!("{}: `{}`", err, &source[*bad_span]).into(),
1087                labels: vec![(*bad_span, err.to_string().into())],
1088                notes: vec![],
1089            },
1090            Error::UnknownScalarType(bad_span) => ParseError {
1091                message: format!("unknown scalar type: `{}`", &source[*bad_span]).into(),
1092                labels: vec![(*bad_span, "unknown scalar type".into())],
1093                notes: vec!["Valid scalar types are f32, f64, i32, u32, bool".into()],
1094            },
1095            Error::BadTypeCast {
1096                span,
1097                ref from_type,
1098                ref to_type,
1099            } => {
1100                let msg = format!("cannot cast a {from_type} to a {to_type}");
1101                ParseError {
1102                    message: msg.clone().into(),
1103                    labels: vec![(*span, msg.into())],
1104                    notes: vec![],
1105                }
1106            }
1107            Error::InvalidResolve(ref resolve_error) => ParseError {
1108                message: resolve_error.to_string().into(),
1109                labels: vec![],
1110                notes: vec![],
1111            },
1112            Error::InvalidIdentifierUnderscore(bad_span) => ParseError {
1113                labels: vec![(*bad_span, "invalid identifier".into())],
1114                notes: vec![
1115                    "Use phony assignment instead (`_ =` notice the absence of `let` or `var`)"
1116                        .into(),
1117                ],
1118                message: "Identifier can't be `_`".into(),
1119            },
1120            Error::UnknownEnableExtension(span, word) => ParseError {
1121                message: format!("unknown enable-extension `{word}`").into(),
1122                labels: vec![(*span, "".into())],
1123                notes: vec![
1124                    "See available extensions at <https://www.w3.org/TR/WGSL/#enable-extension>."
1125                        .into(),
1126                ],
1127            },
1128            Error::UnknownLanguageExtension(span, name) => ParseError {
1129                message: format!("unknown language extension `{name}`").into(),
1130                labels: vec![(*span, "".into())],
1131                notes: vec![concat!(
1132                    "See available extensions at ",
1133                    "<https://www.w3.org/TR/WGSL/#language-extensions-sec>."
1134                )
1135                .into()],
1136            },
1137            Error::UnknownDiagnosticRuleName(span) => ParseError {
1138                message: format!("unknown `diagnostic(…)` rule name `{}`", &source[*span]).into(),
1139                labels: vec![(*span, "not a valid diagnostic rule name".into())],
1140                notes: vec![concat!(
1141                    "See available trigger rules at ",
1142                    "<https://www.w3.org/TR/WGSL/#filterable-triggering-rules>."
1143                )
1144                .into()],
1145            },
1146            Error::SizeAttributeTooLow(bad_span, min_size) => ParseError {
1147                message: format!("struct member size must be at least {min_size}").into(),
1148                labels: vec![(*bad_span, format!("must be at least {min_size}").into())],
1149                notes: vec![],
1150            },
1151            Error::SizeAttributeRequiresFixedFootprint(bad_span) => ParseError {
1152                labels: vec![(*bad_span, "type does not have creation-fixed footprint".into())],
1153                message: "@size attribute requires a type with creation-fixed footprint".into(),
1154                notes: vec![],
1155            },
1156            Error::AlignAttributeTooLow(bad_span, min_align) => ParseError {
1157                message: format!("struct member alignment must be at least {min_align}").into(),
1158                labels: vec![(*bad_span, format!("must be at least {min_align}").into())],
1159                notes: vec![],
1160            },
1161            Error::InitializationTypeMismatch {
1162                name,
1163                ref expected,
1164                ref got,
1165            } => {
1166                let name_str = &source[*name];
1167                ParseError {
1168                    message: format!(
1169                        "the type of `{name_str}` is expected to be `{expected}`, but got `{got}`"
1170                    )
1171                        .into(),
1172                    labels: vec![(*name, format!("definition of `{name_str}`").into())],
1173                    notes: vec![],
1174                }
1175            },
1176            Error::MissingAttribute(name, name_span) => {
1177                let variable = &source[*name_span];
1178                ParseError {
1179                    message: format!(
1180                        "variable `{variable}` needs a '{name}' attribute",
1181                    )
1182                        .into(),
1183                    labels: vec![(
1184                        *name_span,
1185                        format!("definition of `{variable}`").into(),
1186                    )],
1187                    notes: vec![],
1188                }
1189            },
1190            Error::InvalidAssignment { span, ty } => {
1191                let (notes, extra_label) = match ty {
1192                    InvalidAssignmentType::Swizzle => (
1193                        vec![
1194                            "WGSL does not support assignments to swizzles".into(),
1195                            "consider assigning each component individually".into(),
1196                        ],
1197                        None,
1198                    ),
1199                    InvalidAssignmentType::ImmutableBinding(binding_span) => (
1200                        vec![format!(
1201                            "consider declaring `{}` with `var` instead of `let`",
1202                            &source[*binding_span]
1203                        ).into()],
1204                        Some((*binding_span, "this is an immutable binding".into())),
1205                    ),
1206                    InvalidAssignmentType::Other => (vec![], None),
1207                };
1208
1209                let label = (*span, "cannot assign to this expression".into());
1210
1211                ParseError {
1212                    labels: if let Some(extra_label) = extra_label {
1213                        vec![label, extra_label]
1214                    } else {
1215                        vec![label]
1216                    },
1217                    message: "invalid left-hand side of assignment".into(),
1218                    notes,
1219                }
1220            }
1221            Error::ReservedKeyword(name_span) => {
1222                let name = &source[*name_span];
1223                ParseError {
1224                    message: format!("name `{name}` is a reserved keyword").into(),
1225                    labels: vec![(
1226                        *name_span,
1227                        format!("definition of `{name}`").into(),
1228                    )],
1229                    notes: vec![],
1230                }
1231            },
1232            Error::Redefinition { previous, current } => {
1233                let message = format!("redefinition of `{}`", &source[*current]);
1234                ParseError {
1235                    message: message.clone().into(),
1236                    labels: vec![
1237                        (*current, message.into()),
1238                        (
1239                            *previous,
1240                            format!("previous definition of `{}`", &source[*previous]).into(),
1241                        ),
1242                    ],
1243                    notes: vec![],
1244                }
1245            },
1246            Error::RecursiveDeclaration { ident, usage } => ParseError {
1247                message: format!("declaration of `{}` is recursive", &source[*ident]).into(),
1248                labels: vec![(*ident, "".into()), (*usage, "uses itself here".into())],
1249                notes: vec![],
1250            },
1251            Error::CyclicDeclaration { ident, ref path } => ParseError {
1252                message: format!("declaration of `{}` is cyclic", &source[*ident]).into(),
1253                labels: path
1254                    .iter()
1255                    .enumerate()
1256                    .flat_map(|(i, &(ident, usage))| {
1257                        [
1258                            (ident, "".into()),
1259                            (
1260                                usage,
1261                                if i == path.len() - 1 {
1262                                    "ending the cycle".into()
1263                                } else {
1264                                    format!("uses `{}`", &source[ident]).into()
1265                                },
1266                            ),
1267                        ]
1268                    })
1269                    .collect(),
1270                notes: vec![],
1271            },
1272            Error::TooManyArguments {
1273                ref function,
1274                call_span,
1275                arg_span,
1276                max_arguments,
1277            } => ParseError {
1278                message: format!("too many arguments passed to `{function}`").into(),
1279                labels: vec![
1280                    (*call_span, "".into()),
1281                    (*arg_span, format!("unexpected argument #{}", max_arguments + 1).into())
1282                ],
1283                notes: vec![
1284                    format!("The `{function}` function accepts at most {max_arguments} argument(s)").into()
1285                ],
1286            },
1287            Error::WrongArgumentType {
1288                ref function,
1289                call_span,
1290                arg_span,
1291                arg_index,
1292                ref arg_ty,
1293                ref allowed,
1294            } => {
1295                let message = format!(
1296                    "wrong type passed as argument #{} to `{function}`",
1297                    arg_index + 1,
1298                ).into();
1299                let labels = vec![
1300                    (*call_span, "".into()),
1301                    (*arg_span, format!("argument #{} has type `{arg_ty}`", arg_index + 1).into())
1302                ];
1303
1304                let mut notes = vec![];
1305                notes.push(format!("`{function}` accepts the following types for argument #{}:", arg_index + 1).into());
1306                notes.extend(allowed.iter().map(|ty| format!("allowed type: {ty}").into()));
1307
1308                ParseError { message, labels, notes }
1309            },
1310            Error::InconsistentArgumentType {
1311                ref function,
1312                call_span,
1313                arg_span,
1314                arg_index,
1315                ref arg_ty,
1316                inconsistent_span,
1317                inconsistent_index,
1318                ref inconsistent_ty,
1319                ref allowed
1320            } => {
1321                let message = format!(
1322                    "inconsistent type passed as argument #{} to `{function}`",
1323                    arg_index + 1,
1324                ).into();
1325                let labels = vec![
1326                    (*call_span, "".into()),
1327                    (*arg_span, format!("argument #{} has type {arg_ty}", arg_index + 1).into()),
1328                    (*inconsistent_span, format!(
1329                        "this argument has type {inconsistent_ty}, which constrains subsequent arguments"
1330                    ).into()),
1331                ];
1332                let mut notes = vec![
1333                    format!("Because argument #{} has type {inconsistent_ty}, only the following types", inconsistent_index + 1).into(),
1334                    format!("(or types that automatically convert to them) are accepted for argument #{}:", arg_index + 1).into(),
1335                ];
1336                notes.extend(allowed.iter().map(|ty| format!("allowed type: {ty}").into()));
1337
1338                ParseError { message, labels, notes }
1339            }
1340            Error::FunctionReturnsVoid(span) => ParseError {
1341                labels: vec![(*span, "".into())],
1342                notes: vec![
1343                    "perhaps you meant to call the function in a separate statement?".into(),
1344                ],
1345                message: "function does not return any value".into(),
1346            },
1347            Error::FunctionMustUseUnused(call) => ParseError {
1348                labels: vec![(*call, "".into())],
1349                notes: vec![
1350                    format!(
1351                        "function '{}' is declared with `@must_use` attribute",
1352                        &source[*call],
1353                    ).into(),
1354                    "use a phony assignment or declare a value using the function call as the initializer".into(),
1355                ],
1356                message: "unused return value from function annotated with @must_use".into(),
1357            },
1358            Error::FunctionMustUseReturnsVoid(attr, signature) => ParseError {
1359                labels: vec![
1360                    (*attr, "".into()),
1361                    (*signature, "".into()),
1362                ],
1363                notes: vec![
1364                    "declare a return type or remove the attribute".into(),
1365                ],
1366                message: "function annotated with @must_use but does not return any value".into(),
1367            },
1368            Error::FunctionMustUseOnNonFunction(attr) => ParseError {
1369                labels: vec![(*attr, "".into())],
1370                notes: vec![
1371                    "place `@must_use` on a function declaration with a return type".into(),
1372                ],
1373                message: "attribute `@must_use` is only valid on function declarations".into(),
1374            },
1375            Error::InvalidWorkGroupUniformLoad(span) => ParseError {
1376                labels: vec![(*span, "".into())],
1377                notes: vec!["passed type must be a workgroup pointer".into()],
1378                message: "incorrect type passed to workgroupUniformLoad".into(),
1379            },
1380            Error::InvalidStringLiteral { span, description } => ParseError {
1381                message: description.to_string().into(),
1382                labels: vec![(*span, "invalid string literal".into())],
1383                notes: vec![],
1384            },
1385            Error::ExpectedStringLiteral { span, description } => ParseError {
1386                message: description.to_string().into(),
1387                labels: vec![(*span, "expected a string literal".into())],
1388                notes: vec![],
1389            },
1390            Error::Internal(message) => ParseError {
1391                notes: vec![(*message).into()],
1392                message: "internal WGSL front end error".into(),
1393                labels: vec![],
1394            },
1395            Error::TypeMismatch(ref error) => {
1396                let TypeMismatchError {
1397                    dest_span,
1398                    ref dest_type,
1399                    source_span,
1400                    ref source_type,
1401                } = **error;
1402                let mut labels = vec![(
1403                    source_span,
1404                    format!("this expression has type `{source_type}`").into(),
1405                )];
1406                if dest_span != source_span {
1407                    labels.push((
1408                        dest_span,
1409                        format!("a value of type `{dest_type}` is required here").into(),
1410                    ));
1411                }
1412                ParseError {
1413                    message: format!("expected `{dest_type}`, found `{source_type}`").into(),
1414                    labels,
1415                    notes: vec![],
1416                }
1417            }
1418            Error::AutoConversion(ref error) => {
1419                // destructuring ensures all fields are handled
1420                let AutoConversionError {
1421                    dest_span,
1422                    ref dest_type,
1423                    source_span,
1424                    ref source_type,
1425                } = **error;
1426                ParseError {
1427                    message: format!(
1428                        "automatic conversions cannot convert `{source_type}` to `{dest_type}`"
1429                    ).into(),
1430                    labels: vec![
1431                        (
1432                            dest_span,
1433                            format!("a value of type {dest_type} is required here").into(),
1434                        ),
1435                        (
1436                            source_span,
1437                            format!("this expression has type {source_type}").into(),
1438                        ),
1439                    ],
1440                    notes: vec![],
1441                }
1442            }
1443            Error::AutoConversionLeafScalar(ref error) => {
1444                let AutoConversionLeafScalarError {
1445                    dest_span,
1446                    ref dest_scalar,
1447                    source_span,
1448                    ref source_type,
1449                } = **error;
1450                ParseError {
1451                    message: format!(
1452                        "automatic conversions cannot convert elements of `{source_type}` to `{dest_scalar}`"
1453                    ).into(),
1454                    labels: vec![
1455                        (
1456                            dest_span,
1457                            format!(
1458                                "a value with elements of type {dest_scalar} is required here"
1459                            )
1460                            .into(),
1461                        ),
1462                        (
1463                            source_span,
1464                            format!("this expression has type {source_type}").into(),
1465                        ),
1466                    ],
1467                    notes: vec![],
1468                }
1469            }
1470            Error::ConcretizationFailed(ref error) => {
1471                let ConcretizationFailedError {
1472                    expr_span,
1473                    ref expr_type,
1474                    ref concretization_preferences,
1475                } = **error;
1476                ParseError {
1477                    labels: vec![(
1478                        expr_span,
1479                        format!("this expression has type {expr_type}").into(),
1480                    )],
1481                    notes: concretization_preferences
1482                        .iter()
1483                        .map(|&(ref scalar, ref err)|
1484                            format!("the expression couldn't be converted to have {scalar} scalar type: {err}").into()
1485                        )
1486                        .collect(),
1487                    message: "failed to convert expression to a concrete type".into(),
1488                }
1489            }
1490            Error::ExceededLimitForNestedBraces { span, limit } => ParseError {
1491                labels: vec![(*span, "limit reached at this brace".into())],
1492                notes: vec![format!("nesting limit is currently set to {limit}").into()],
1493                message: "brace nesting limit reached".into(),
1494            },
1495            Error::DirectiveAfterFirstGlobalDecl { directive_span } => ParseError {
1496                labels: vec![(
1497                    *directive_span,
1498                    "written after first global declaration".into(),
1499                )],
1500                notes: vec![concat!(
1501                    "global directives are only allowed before global declarations; ",
1502                    "maybe hoist this closer to the top of the shader module?"
1503                )
1504                .into()],
1505                message: "expected global declaration, but found a global directive".into(),
1506            },
1507            Error::EnableExtensionNotYetImplemented { kind, span } => ParseError {
1508                message: format!(
1509                    "the `{}` enable-extension is not yet supported",
1510                    EnableExtension::Unimplemented(*kind).to_ident()
1511                ).into(),
1512                labels: vec![(
1513                    *span,
1514                    concat!(
1515                        "this enable-extension specifies standard functionality ",
1516                        "which is not yet implemented in Naga"
1517                    )
1518                    .into(),
1519                )],
1520                notes: vec![format!(
1521                    concat!(
1522                        "Let Naga maintainers know that you ran into this at ",
1523                        "<https://github.com/gfx-rs/wgpu/issues/{}>, ",
1524                        "so they can prioritize it!"
1525                    ),
1526                    kind.tracking_issue_num()
1527                ).into()],
1528            },
1529            Error::EnableExtensionNotEnabled { kind, span } => ParseError {
1530                message: format!("the `{}` enable extension is not enabled", kind.to_ident()).into(),
1531                labels: vec![(
1532                    *span,
1533                    format!(
1534                        concat!(
1535                            "the `{}` \"Enable Extension\" is needed for this functionality, ",
1536                            "but it is not currently enabled."
1537                        ),
1538                        kind.to_ident()
1539                    )
1540                    .into(),
1541                )],
1542                notes: if let EnableExtension::Unimplemented(kind) = kind {
1543                    vec![format!(
1544                        concat!(
1545                            "This \"Enable Extension\" is not yet implemented. ",
1546                            "Let Naga maintainers know that you ran into this at ",
1547                            "<https://github.com/gfx-rs/wgpu/issues/{}>, ",
1548                            "so they can prioritize it!"
1549                        ),
1550                        kind.tracking_issue_num()
1551                    ).into()]
1552                } else {
1553                    vec![
1554                        format!(
1555                            "You can enable this extension by adding `enable {};` at the top of the shader, before any other items.",
1556                            kind.to_ident()
1557                        ).into(),
1558                    ]
1559                },
1560            },
1561            Error::LanguageExtensionNotYetImplemented { kind, span } => ParseError {
1562                message: format!(
1563                    "the `{}` language extension is not yet supported",
1564                    LanguageExtension::Unimplemented(*kind).to_ident()
1565                ).into(),
1566                labels: vec![(*span, "".into())],
1567                notes: vec![format!(
1568                    concat!(
1569                        "Let Naga maintainers know that you ran into this at ",
1570                        "<https://github.com/gfx-rs/wgpu/issues/{}>, ",
1571                        "so they can prioritize it!"
1572                    ),
1573                    kind.tracking_issue_num()
1574                ).into()],
1575            },
1576            Error::DiagnosticInvalidSeverity {
1577                severity_control_name_span,
1578            } => ParseError {
1579                labels: vec![(
1580                    *severity_control_name_span,
1581                    "not a valid severity level".into(),
1582                )],
1583                notes: vec![concat!(
1584                    "See available severities at ",
1585                    "<https://www.w3.org/TR/WGSL/#diagnostic-severity>."
1586                )
1587                .into()],
1588                message: "invalid `diagnostic(…)` severity".into(),
1589            },
1590            Error::DiagnosticDuplicateTriggeringRule(ConflictingDiagnosticRuleError {
1591                triggering_rule_spans,
1592            }) => {
1593                let [first_span, second_span] = triggering_rule_spans;
1594                ParseError {
1595                    labels: vec![
1596                        (*first_span, "first rule".into()),
1597                        (*second_span, "second rule".into()),
1598                    ],
1599                    notes: vec![
1600                        concat!(
1601                            "Multiple `diagnostic(…)` rules with the same rule name ",
1602                            "conflict unless they are directives and the severity is the same.",
1603                        )
1604                        .into(),
1605                        "You should delete the rule you don't want.".into(),
1606                    ],
1607                    message: "found conflicting `diagnostic(…)` rule(s)".into(),
1608                }
1609            }
1610            Error::DiagnosticAttributeNotYetImplementedAtParseSite {
1611                site_name_plural,
1612                ref spans,
1613            } => ParseError {
1614                labels: {
1615                    let mut spans = spans.iter().cloned();
1616                    let first = spans
1617                        .next()
1618                        .map(|span| {
1619                            (
1620                                span,
1621                                format!("can't use this on {site_name_plural} (yet)").into(),
1622                            )
1623                        })
1624                        .expect("internal error: diag. attr. rejection on empty map");
1625                    core::iter::once(first)
1626                        .chain(spans.map(|span| (span, "".into())))
1627                        .collect()
1628                },
1629                notes: vec![concat!(
1630                    "Let Naga maintainers know that you ran into this at ",
1631                    "<https://github.com/gfx-rs/wgpu/issues/5320>, ",
1632                    "so they can prioritize it!"
1633                ).into()],
1634                message: "`@diagnostic(…)` attribute(s) not yet implemented".into(),
1635            },
1636            Error::DiagnosticAttributeNotSupported { on_what, ref spans } => {
1637                // In this case the user may have intended to create a global diagnostic filter directive,
1638                // so display a note to them suggesting the correct syntax.
1639                let intended_diagnostic_directive = match on_what {
1640                    DiagnosticAttributeNotSupportedPosition::SemicolonInModulePosition => true,
1641                    DiagnosticAttributeNotSupportedPosition::Other { .. } => false,
1642                };
1643                let on_what_plural = match on_what {
1644                    DiagnosticAttributeNotSupportedPosition::SemicolonInModulePosition => {
1645                        "semicolons"
1646                    }
1647                    DiagnosticAttributeNotSupportedPosition::Other { display_plural } => {
1648                        display_plural
1649                    }
1650                };
1651                ParseError {
1652                    message: format!(
1653                        "`@diagnostic(…)` attribute(s) on {on_what_plural} are not supported",
1654                    ).into(),
1655                    labels: spans
1656                        .iter()
1657                        .cloned()
1658                        .map(|span| (span, "".into()))
1659                        .collect(),
1660                    notes: vec![
1661                        concat!(
1662                            "`@diagnostic(…)` attributes are only permitted on `fn`s, ",
1663                            "some statements, and `switch`/`loop` bodies."
1664                        )
1665                        .into(),
1666                        {
1667                            if intended_diagnostic_directive {
1668                                concat!(
1669                                    "If you meant to declare a diagnostic filter that ",
1670                                    "applies to the entire module, move this line to ",
1671                                    "the top of the file and remove the `@` symbol."
1672                                )
1673                                .into()
1674                            } else {
1675                                concat!(
1676                                    "These attributes are well-formed, ",
1677                                    "you likely just need to move them."
1678                                )
1679                                .into()
1680                            }
1681                        },
1682                    ],
1683                }
1684            }
1685            Error::SelectUnexpectedArgumentType { arg_span, ref arg_type } => ParseError {
1686                labels: vec![(*arg_span, format!("this value of type {arg_type}").into())],
1687                notes: vec!["expected a scalar or a `vecN` of scalars".into()],
1688                message: "unexpected argument type for `select` call".into(),
1689            },
1690            Error::SelectRejectAndAcceptHaveNoCommonType {
1691                reject_span,
1692                ref reject_type,
1693                accept_span,
1694                ref accept_type,
1695            } => ParseError {
1696                labels: vec![
1697                    (*reject_span, format!("reject value of type {reject_type}").into()),
1698                    (*accept_span, format!("accept value of type {accept_type}").into()),
1699                ],
1700                message: "type mismatch for reject and accept values in `select` call".into(),
1701                notes: vec![],
1702            },
1703            Error::StructMemberTooLarge { member_name_span } => ParseError {
1704                labels: vec![(*member_name_span, "this member exceeds the maximum size".into())],
1705                notes: vec![format!(
1706                    "the maximum size is {} bytes",
1707                    crate::valid::MAX_TYPE_SIZE
1708                ).into()],
1709                message: "struct member is too large".into(),
1710            },
1711            Error::TypeTooLarge { span } => ParseError {
1712                labels: vec![(*span, "this type exceeds the maximum size".into())],
1713                notes: vec![format!(
1714                    "the maximum size is {} bytes",
1715                    crate::valid::MAX_TYPE_SIZE
1716                ).into()],
1717                message: "type is too large".into(),
1718            },
1719            Error::UnderspecifiedCooperativeMatrix => ParseError {
1720                labels: vec![],
1721                notes: vec!["must be F32".into()],
1722                message: "cooperative matrix constructor is underspecified".into(),
1723            },
1724            Error::InvalidCooperativeLoadType(span) => ParseError {
1725                labels: vec![(*span, "type needs the coop_mat<...>".into())],
1726                notes: vec!["must be a valid cooperative type".into()],
1727                message: "cooperative load should have a generic type for coop_mat".into(),
1728            },
1729            Error::UnsupportedCooperativeScalar(span) => ParseError {
1730                labels: vec![(*span, "type needs the scalar type specified".into())],
1731                notes: vec!["must be F32".into()],
1732                message: "cooperative scalar type is not supported".into(),
1733            },
1734            Error::UnusedArgsForTemplate(ref expr_spans) => ParseError {
1735                labels: expr_spans.iter().cloned().map(|span| -> (_, _){ (span, "unused".into()) }).collect(),
1736                message: "unused expressions for template".into(),
1737                notes: vec![],
1738            },
1739            Error::UnterminatedBlockComment(span) => ParseError {
1740                labels: vec![(
1741                    *span,
1742                    "must be closed with `*/`".into(),
1743                )],
1744                message: "unterminated block comment".into(),
1745                notes: vec![],
1746            },
1747            Error::RayQueryWithInitializer(span) => ParseError {
1748                message: "Ray query with initialize".into(),
1749                labels: vec![(
1750                    *span,
1751                    "variables with type `ray_query` are special and so cannot have initializers".into(),
1752                )],
1753                notes: vec![],
1754            },
1755            Error::HitObjectWithInitializer(span) => ParseError {
1756                message: "Hit object with initialize".into(),
1757                labels: vec![(
1758                    *span,
1759                    "variables with type `hit_object` are special and so cannot have initializers".into(),
1760                )],
1761                notes: vec![],
1762            },
1763        }
1764    }
1765}