Debian Codegraph @

third_party/rust/naga/src/front/wgsl/error.rs

raw
1 //! Formatting WGSL front end error messages.
2
3 use crate::common::wgsl::TryToWgsl;
4 use crate::diagnostic_filter::ConflictingDiagnosticRuleError;
5 use crate::proc::{Alignment, ConstantEvaluatorError, ResolveError};
6 use crate::{Scalar, SourceLocation, Span};
7
8 use super::parse::directive::enable_extension::{EnableExtension, UnimplementedEnableExtension};
9 use super::parse::directive::language_extension::{
10 LanguageExtension, UnimplementedLanguageExtension,
11 };
12 use super::parse::lexer::Token;
13
14 use codespan_reporting::diagnostic::{Diagnostic, Label};
15 use codespan_reporting::files::SimpleFile;
16 use codespan_reporting::term;
17 use thiserror::Error;
18
19 use alloc::{
20 borrow::Cow,
21 boxed::Box,
22 format,
23 string::{String, ToString},
24 vec,
25 vec::Vec,
26 };
27 use core::ops::Range;
28
29 #[derive(Clone, Debug)]
30 pub struct ParseError {
31 message: String,
32 // The first span should be the primary span, and the other ones should be complementary.
33 labels: Vec<(Span, Cow<'static, str>)>,
34 notes: Vec<String>,
35 }
36
37 impl ParseError {
38 pub fn labels(&self) -> impl ExactSizeIterator<Item = (Span, &str)> + '_ {
39 self.labels
40 .iter()
41 .map(|&(span, ref msg)| (span, msg.as_ref()))
42 }
43
44 pub fn message(&self) -> &str {
45 &self.message
46 }
47
48 fn diagnostic(&self) -> Diagnostic<()> {
49 let diagnostic = Diagnostic::error()
50 .with_message(self.message.to_string())
51 .with_labels(
52 self.labels
53 .iter()
54 .filter_map(|label| label.0.to_range().map(|range| (label, range)))
55 .map(|(label, range)| {
56 Label::primary((), range).with_message(label.1.to_string())
57 })
58 .collect(),
59 )
60 .with_notes(
61 self.notes
62 .iter()
63 .map(|note| format!("note: {note}"))
64 .collect(),
65 );
66 diagnostic
67 }
68
69 /// Emits a summary of the error to standard error stream.
70 #[cfg(feature = "stderr")]
71 pub fn emit_to_stderr(&self, source: &str) {
72 self.emit_to_stderr_with_path(source, "wgsl")
73 }
74
75 /// Emits a summary of the error to standard error stream.
76 #[cfg(feature = "stderr")]
77 pub fn emit_to_stderr_with_path<P>(&self, source: &str, path: P)
78 where
79 P: AsRef<std::path::Path>,
80 {
81 let path = path.as_ref().display().to_string();
82 let files = SimpleFile::new(path, source);
83 let config = term::Config::default();
84
85 cfg_if::cfg_if! {
86 if #[cfg(feature = "termcolor")] {
87 let writer = term::termcolor::StandardStream::stderr(term::termcolor::ColorChoice::Auto);
88 } else {
89 let writer = std::io::stderr();
90 }
91 }
92
93 term::emit(&mut writer.lock(), &config, &files, &self.diagnostic())
94 .expect("cannot write error");
95 }
96
97 /// Emits a summary of the error to a string.
98 pub fn emit_to_string(&self, source: &str) -> String {
99 self.emit_to_string_with_path(source, "wgsl")
100 }
101
102 /// Emits a summary of the error to a string.
103 pub fn emit_to_string_with_path<P>(&self, source: &str, path: P) -> String
104 where
105 P: AsRef<std::path::Path>,
106 {
107 let path = path.as_ref().display().to_string();
108 let files = SimpleFile::new(path, source);
109 let config = term::Config::default();
110
111 let mut writer = crate::error::DiagnosticBuffer::new();
112 term::emit(writer.inner_mut(), &config, &files, &self.diagnostic())
113 .expect("cannot write error");
114 writer.into_string()
115 }
116
117 /// Returns a [`SourceLocation`] for the first label in the error message.
118 pub fn location(&self, source: &str) -> Option<SourceLocation> {
119 self.labels.first().map(|label| label.0.location(source))
120 }
121 }
122
123 impl core::fmt::Display for ParseError {
124 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
125 write!(f, "{}", self.message)
126 }
127 }
128
129 impl core::error::Error for ParseError {
130 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
131 None
132 }
133 }
134
135 #[derive(Copy, Clone, Debug, PartialEq)]
136 pub enum ExpectedToken<'a> {
137 Token(Token<'a>),
138 Identifier,
139 AfterIdentListComma,
140 AfterIdentListArg,
141 /// Expected: constant, parenthesized expression, identifier
142 PrimaryExpression,
143 /// Expected: assignment, increment/decrement expression
144 Assignment,
145 /// Expected: 'case', 'default', '}'
146 SwitchItem,
147 /// Expected: ',', ')'
148 WorkgroupSizeSeparator,
149 /// Expected: 'struct', 'let', 'var', 'type', ';', 'fn', eof
150 GlobalItem,
151 /// Expected a type.
152 Type,
153 /// Access of `var`, `let`, `const`.
154 Variable,
155 /// Access of a function
156 Function,
157 /// The `diagnostic` identifier of the `@diagnostic(…)` attribute.
158 DiagnosticAttribute,
159 }
160
161 #[derive(Clone, Copy, Debug, Error, PartialEq)]
162 pub enum NumberError {
163 #[error("invalid numeric literal format")]
164 Invalid,
165 #[error("numeric literal not representable by target type")]
166 NotRepresentable,
167 }
168
169 #[derive(Copy, Clone, Debug, PartialEq)]
170 pub enum InvalidAssignmentType {
171 Other,
172 Swizzle,
173 ImmutableBinding(Span),
174 }
175
176 #[derive(Clone, Debug)]
177 pub(crate) enum Error<'a> {
178 Unexpected(Span, ExpectedToken<'a>),
179 UnexpectedComponents(Span),
180 UnexpectedOperationInConstContext(Span),
181 BadNumber(Span, NumberError),
182 BadMatrixScalarKind(Span, Scalar),
183 BadAccessor(Span),
184 BadTexture(Span),
185 BadTypeCast {
186 span: Span,
187 from_type: String,
188 to_type: String,
189 },
190 NotStorageTexture(Span),
191 BadTextureSampleType {
192 span: Span,
193 scalar: Scalar,
194 },
195 BadIncrDecrReferenceType(Span),
196 InvalidResolve(ResolveError),
197 InvalidForInitializer(Span),
198 /// A break if appeared outside of a continuing block
199 InvalidBreakIf(Span),
200 InvalidGatherComponent(Span),
201 InvalidConstructorComponentType(Span, i32),
202 InvalidIdentifierUnderscore(Span),
203 ReservedIdentifierPrefix(Span),
204 UnknownAddressSpace(Span),
205 RepeatedAttribute(Span),
206 UnknownAttribute(Span),
207 UnknownBuiltin(Span),
208 UnknownAccess(Span),
209 UnknownIdent(Span, &'a str),
210 UnknownScalarType(Span),
211 UnknownType(Span),
212 UnknownStorageFormat(Span),
213 UnknownConservativeDepth(Span),
214 UnknownEnableExtension(Span, &'a str),
215 UnknownLanguageExtension(Span, &'a str),
216 UnknownDiagnosticRuleName(Span),
217 SizeAttributeTooLow(Span, u32),
218 AlignAttributeTooLow(Span, Alignment),
219 NonPowerOfTwoAlignAttribute(Span),
220 InconsistentBinding(Span),
221 TypeNotConstructible(Span),
222 TypeNotInferable(Span),
223 InitializationTypeMismatch {
224 name: Span,
225 expected: String,
226 got: String,
227 },
228 DeclMissingTypeAndInit(Span),
229 MissingAttribute(&'static str, Span),
230 InvalidAddrOfOperand(Span),
231 InvalidAtomicPointer(Span),
232 InvalidAtomicOperandType(Span),
233 InvalidRayQueryPointer(Span),
234 NotPointer(Span),
235 NotReference(&'static str, Span),
236 InvalidAssignment {
237 span: Span,
238 ty: InvalidAssignmentType,
239 },
240 ReservedKeyword(Span),
241 /// Redefinition of an identifier (used for both module-scope and local redefinitions).
242 Redefinition {
243 /// Span of the identifier in the previous definition.
244 previous: Span,
245
246 /// Span of the identifier in the new definition.
247 current: Span,
248 },
249 /// A declaration refers to itself directly.
250 RecursiveDeclaration {
251 /// The location of the name of the declaration.
252 ident: Span,
253
254 /// The point at which it is used.
255 usage: Span,
256 },
257 /// A declaration refers to itself indirectly, through one or more other
258 /// definitions.
259 CyclicDeclaration {
260 /// The location of the name of some declaration in the cycle.
261 ident: Span,
262
263 /// The edges of the cycle of references.
264 ///
265 /// Each `(decl, reference)` pair indicates that the declaration whose
266 /// name is `decl` has an identifier at `reference` whose definition is
267 /// the next declaration in the cycle. The last pair's `reference` is
268 /// the same identifier as `ident`, above.
269 path: Box<[(Span, Span)]>,
270 },
271 InvalidSwitchSelector {
272 span: Span,
273 },
274 InvalidSwitchCase {
275 span: Span,
276 },
277 SwitchCaseTypeMismatch {
278 span: Span,
279 },
280 CalledEntryPoint(Span),
281 WrongArgumentCount {
282 span: Span,
283 expected: Range<u32>,
284 found: u32,
285 },
286 /// No overload of this function accepts this many arguments.
287 TooManyArguments {
288 /// The name of the function being called.
289 function: String,
290
291 /// The function name in the call expression.
292 call_span: Span,
293
294 /// The first argument that is unacceptable.
295 arg_span: Span,
296
297 /// Maximum number of arguments accepted by any overload of
298 /// this function.
299 max_arguments: u32,
300 },
301 /// A value passed to a builtin function has a type that is not
302 /// accepted by any overload of the function.
303 WrongArgumentType {
304 /// The name of the function being called.
305 function: String,
306
307 /// The function name in the call expression.
308 call_span: Span,
309
310 /// The first argument whose type is unacceptable.
311 arg_span: Span,
312
313 /// The index of the first argument whose type is unacceptable.
314 arg_index: u32,
315
316 /// That argument's actual type.
317 arg_ty: String,
318
319 /// The set of argument types that would have been accepted for
320 /// this argument, given the prior arguments.
321 allowed: Vec<String>,
322 },
323 /// A value passed to a builtin function has a type that is not
324 /// accepted, given the earlier arguments' types.
325 InconsistentArgumentType {
326 /// The name of the function being called.
327 function: String,
328
329 /// The function name in the call expression.
330 call_span: Span,
331
332 /// The first unacceptable argument.
333 arg_span: Span,
334
335 /// The index of the first unacceptable argument.
336 arg_index: u32,
337
338 /// The actual type of the first unacceptable argument.
339 arg_ty: String,
340
341 /// The prior argument whose type made the `arg_span` argument
342 /// unacceptable.
343 inconsistent_span: Span,
344
345 /// The index of the `inconsistent_span` argument.
346 inconsistent_index: u32,
347
348 /// The type of the `inconsistent_span` argument.
349 inconsistent_ty: String,
350
351 /// The types that would have been accepted instead of the
352 /// first unacceptable argument.
353 allowed: Vec<String>,
354 },
355 FunctionReturnsVoid(Span),
356 FunctionMustUseUnused(Span),
357 FunctionMustUseReturnsVoid(Span, Span),
358 InvalidWorkGroupUniformLoad(Span),
359 Internal(&'static str),
360 ExpectedConstExprConcreteIntegerScalar(Span),
361 ExpectedNonNegative(Span),
362 ExpectedPositiveArrayLength(Span),
363 MissingWorkgroupSize(Span),
364 ConstantEvaluatorError(Box<ConstantEvaluatorError>, Span),
365 AutoConversion(Box<AutoConversionError>),
366 AutoConversionLeafScalar(Box<AutoConversionLeafScalarError>),
367 ConcretizationFailed(Box<ConcretizationFailedError>),
368 ExceededLimitForNestedBraces {
369 span: Span,
370 limit: u8,
371 },
372 PipelineConstantIDValue(Span),
373 NotBool(Span),
374 ConstAssertFailed(Span),
375 DirectiveAfterFirstGlobalDecl {
376 directive_span: Span,
377 },
378 EnableExtensionNotYetImplemented {
379 kind: UnimplementedEnableExtension,
380 span: Span,
381 },
382 EnableExtensionNotEnabled {
383 kind: EnableExtension,
384 span: Span,
385 },
386 LanguageExtensionNotYetImplemented {
387 kind: UnimplementedLanguageExtension,
388 span: Span,
389 },
390 DiagnosticInvalidSeverity {
391 severity_control_name_span: Span,
392 },
393 DiagnosticDuplicateTriggeringRule(ConflictingDiagnosticRuleError),
394 DiagnosticAttributeNotYetImplementedAtParseSite {
395 site_name_plural: &'static str,
396 spans: Vec<Span>,
397 },
398 DiagnosticAttributeNotSupported {
399 on_what: DiagnosticAttributeNotSupportedPosition,
400 spans: Vec<Span>,
401 },
402 }
403
404 impl From<ConflictingDiagnosticRuleError> for Error<'_> {
405 fn from(value: ConflictingDiagnosticRuleError) -> Self {
406 Self::DiagnosticDuplicateTriggeringRule(value)
407 }
408 }
409
410 /// Used for diagnostic refinement in [`Error::DiagnosticAttributeNotSupported`].
411 #[derive(Clone, Copy, Debug)]
412 pub(crate) enum DiagnosticAttributeNotSupportedPosition {
413 SemicolonInModulePosition,
414 Other { display_plural: &'static str },
415 }
416
417 impl From<&'static str> for DiagnosticAttributeNotSupportedPosition {
418 fn from(display_plural: &'static str) -> Self {
419 Self::Other { display_plural }
420 }
421 }
422
423 #[derive(Clone, Debug)]
424 pub(crate) struct AutoConversionError {
425 pub dest_span: Span,
426 pub dest_type: String,
427 pub source_span: Span,
428 pub source_type: String,
429 }
430
431 #[derive(Clone, Debug)]
432 pub(crate) struct AutoConversionLeafScalarError {
433 pub dest_span: Span,
434 pub dest_scalar: String,
435 pub source_span: Span,
436 pub source_type: String,
437 }
438
439 #[derive(Clone, Debug)]
440 pub(crate) struct ConcretizationFailedError {
441 pub expr_span: Span,
442 pub expr_type: String,
443 pub scalar: String,
444 pub inner: ConstantEvaluatorError,
445 }
446
447 impl<'a> Error<'a> {
448 #[cold]
449 #[inline(never)]
450 pub(crate) fn as_parse_error(&self, source: &'a str) -> ParseError {
451 match *self {
452 Error::Unexpected(unexpected_span, expected) => {
453 let expected_str = match expected {
454 ExpectedToken::Token(token) => match token {
455 Token::Separator(c) => format!("`{c}`"),
456 Token::Paren(c) => format!("`{c}`"),
457 Token::Attribute => "@".to_string(),
458 Token::Number(_) => "number".to_string(),
459 Token::Word(s) => s.to_string(),
460 Token::Operation(c) => format!("operation (`{c}`)"),
461 Token::LogicalOperation(c) => format!("logical operation (`{c}`)"),
462 Token::ShiftOperation(c) => format!("bitshift (`{c}{c}`)"),
463 Token::AssignmentOperation(c) if c == '<' || c == '>' => {
464 format!("bitshift (`{c}{c}=`)")
465 }
466 Token::AssignmentOperation(c) => format!("operation (`{c}=`)"),
467 Token::IncrementOperation => "increment operation".to_string(),
468 Token::DecrementOperation => "decrement operation".to_string(),
469 Token::Arrow => "->".to_string(),
470 Token::Unknown(c) => format!("unknown (`{c}`)"),
471 Token::Trivia => "trivia".to_string(),
472 Token::End => "end".to_string(),
473 },
474 ExpectedToken::Identifier => "identifier".to_string(),
475 ExpectedToken::PrimaryExpression => "expression".to_string(),
476 ExpectedToken::Assignment => "assignment or increment/decrement".to_string(),
477 ExpectedToken::SwitchItem => concat!(
478 "switch item (`case` or `default`) or a closing curly bracket ",
479 "to signify the end of the switch statement (`}`)"
480 )
481 .to_string(),
482 ExpectedToken::WorkgroupSizeSeparator => {
483 "workgroup size separator (`,`) or a closing parenthesis".to_string()
484 }
485 ExpectedToken::GlobalItem => concat!(
486 "global item (`struct`, `const`, `var`, `alias`, ",
487 "`fn`, `diagnostic`, `enable`, `requires`, `;`) ",
488 "or the end of the file"
489 )
490 .to_string(),
491 ExpectedToken::Type => "type".to_string(),
492 ExpectedToken::Variable => "variable access".to_string(),
493 ExpectedToken::Function => "function name".to_string(),
494 ExpectedToken::AfterIdentListArg => {
495 "next argument, trailing comma, or end of list (`,` or `;`)".to_string()
496 }
497 ExpectedToken::AfterIdentListComma => {
498 "next argument or end of list (`;`)".to_string()
499 }
500 ExpectedToken::DiagnosticAttribute => {
501 "the `diagnostic` attribute identifier".to_string()
502 }
503 };
504 ParseError {
505 message: format!(
506 "expected {}, found {:?}",
507 expected_str, &source[unexpected_span],
508 ),
509 labels: vec![(unexpected_span, format!("expected {expected_str}").into())],
510 notes: vec![],
511 }
512 }
513 Error::UnexpectedComponents(bad_span) => ParseError {
514 message: "unexpected components".to_string(),
515 labels: vec![(bad_span, "unexpected components".into())],
516 notes: vec![],
517 },
518 Error::UnexpectedOperationInConstContext(span) => ParseError {
519 message: "this operation is not supported in a const context".to_string(),
520 labels: vec![(span, "operation not supported here".into())],
521 notes: vec![],
522 },
523 Error::BadNumber(bad_span, ref err) => ParseError {
524 message: format!("{}: `{}`", err, &source[bad_span],),
525 labels: vec![(bad_span, err.to_string().into())],
526 notes: vec![],
527 },
528 Error::BadMatrixScalarKind(span, scalar) => ParseError {
529 message: format!(
530 "matrix scalar type must be floating-point, but found `{}`",
531 scalar.to_wgsl_for_diagnostics()
532 ),
533 labels: vec![(span, "must be floating-point (e.g. `f32`)".into())],
534 notes: vec![],
535 },
536 Error::BadAccessor(accessor_span) => ParseError {
537 message: format!("invalid field accessor `{}`", &source[accessor_span],),
538 labels: vec![(accessor_span, "invalid accessor".into())],
539 notes: vec![],
540 },
541 Error::UnknownIdent(ident_span, ident) => ParseError {
542 message: format!("no definition in scope for identifier: `{ident}`"),
543 labels: vec![(ident_span, "unknown identifier".into())],
544 notes: vec![],
545 },
546 Error::UnknownScalarType(bad_span) => ParseError {
547 message: format!("unknown scalar type: `{}`", &source[bad_span]),
548 labels: vec![(bad_span, "unknown scalar type".into())],
549 notes: vec!["Valid scalar types are f32, f64, i32, u32, bool".into()],
550 },
551 Error::NotStorageTexture(bad_span) => ParseError {
552 message: "textureStore can only be applied to storage textures".to_string(),
553 labels: vec![(bad_span, "not a storage texture".into())],
554 notes: vec![],
555 },
556 Error::BadTextureSampleType { span, scalar } => ParseError {
557 message: format!(
558 "texture sample type must be one of f32, i32 or u32, but found {}",
559 scalar.to_wgsl_for_diagnostics()
560 ),
561 labels: vec![(span, "must be one of f32, i32 or u32".into())],
562 notes: vec![],
563 },
564 Error::BadIncrDecrReferenceType(span) => ParseError {
565 message: concat!(
566 "increment/decrement operation requires ",
567 "reference type to be one of i32 or u32"
568 )
569 .to_string(),
570 labels: vec![(span, "must be a reference type of i32 or u32".into())],
571 notes: vec![],
572 },
573 Error::BadTexture(bad_span) => ParseError {
574 message: format!(
575 "expected an image, but found `{}` which is not an image",
576 &source[bad_span]
577 ),
578 labels: vec![(bad_span, "not an image".into())],
579 notes: vec![],
580 },
581 Error::BadTypeCast {
582 span,
583 ref from_type,
584 ref to_type,
585 } => {
586 let msg = format!("cannot cast a {from_type} to a {to_type}");
587 ParseError {
588 message: msg.clone(),
589 labels: vec![(span, msg.into())],
590 notes: vec![],
591 }
592 }
593 Error::InvalidResolve(ref resolve_error) => ParseError {
594 message: resolve_error.to_string(),
595 labels: vec![],
596 notes: vec![],
597 },
598 Error::InvalidForInitializer(bad_span) => ParseError {
599 message: format!(
600 "for(;;) initializer is not an assignment or a function call: `{}`",
601 &source[bad_span]
602 ),
603 labels: vec![(bad_span, "not an assignment or function call".into())],
604 notes: vec![],
605 },
606 Error::InvalidBreakIf(bad_span) => ParseError {
607 message: "A break if is only allowed in a continuing block".to_string(),
608 labels: vec![(bad_span, "not in a continuing block".into())],
609 notes: vec![],
610 },
611 Error::InvalidGatherComponent(bad_span) => ParseError {
612 message: format!(
613 "textureGather component `{}` doesn't exist, must be 0, 1, 2, or 3",
614 &source[bad_span]
615 ),
616 labels: vec![(bad_span, "invalid component".into())],
617 notes: vec![],
618 },
619 Error::InvalidConstructorComponentType(bad_span, component) => ParseError {
620 message: format!("invalid type for constructor component at index [{component}]"),
621 labels: vec![(bad_span, "invalid component type".into())],
622 notes: vec![],
623 },
624 Error::InvalidIdentifierUnderscore(bad_span) => ParseError {
625 message: "Identifier can't be `_`".to_string(),
626 labels: vec![(bad_span, "invalid identifier".into())],
627 notes: vec![
628 "Use phony assignment instead (`_ =` notice the absence of `let` or `var`)"
629 .to_string(),
630 ],
631 },
632 Error::ReservedIdentifierPrefix(bad_span) => ParseError {
633 message: format!(
634 "Identifier starts with a reserved prefix: `{}`",
635 &source[bad_span]
636 ),
637 labels: vec![(bad_span, "invalid identifier".into())],
638 notes: vec![],
639 },
640 Error::UnknownAddressSpace(bad_span) => ParseError {
641 message: format!("unknown address space: `{}`", &source[bad_span]),
642 labels: vec![(bad_span, "unknown address space".into())],
643 notes: vec![],
644 },
645 Error::RepeatedAttribute(bad_span) => ParseError {
646 message: format!("repeated attribute: `{}`", &source[bad_span]),
647 labels: vec![(bad_span, "repeated attribute".into())],
648 notes: vec![],
649 },
650 Error::UnknownAttribute(bad_span) => ParseError {
651 message: format!("unknown attribute: `{}`", &source[bad_span]),
652 labels: vec![(bad_span, "unknown attribute".into())],
653 notes: vec![],
654 },
655 Error::UnknownBuiltin(bad_span) => ParseError {
656 message: format!("unknown builtin: `{}`", &source[bad_span]),
657 labels: vec![(bad_span, "unknown builtin".into())],
658 notes: vec![],
659 },
660 Error::UnknownAccess(bad_span) => ParseError {
661 message: format!("unknown access: `{}`", &source[bad_span]),
662 labels: vec![(bad_span, "unknown access".into())],
663 notes: vec![],
664 },
665 Error::UnknownStorageFormat(bad_span) => ParseError {
666 message: format!("unknown storage format: `{}`", &source[bad_span]),
667 labels: vec![(bad_span, "unknown storage format".into())],
668 notes: vec![],
669 },
670 Error::UnknownConservativeDepth(bad_span) => ParseError {
671 message: format!("unknown conservative depth: `{}`", &source[bad_span]),
672 labels: vec![(bad_span, "unknown conservative depth".into())],
673 notes: vec![],
674 },
675 Error::UnknownType(bad_span) => ParseError {
676 message: format!("unknown type: `{}`", &source[bad_span]),
677 labels: vec![(bad_span, "unknown type".into())],
678 notes: vec![],
679 },
680 Error::UnknownEnableExtension(span, word) => ParseError {
681 message: format!("unknown enable-extension `{}`", word),
682 labels: vec![(span, "".into())],
683 notes: vec![
684 "See available extensions at <https://www.w3.org/TR/WGSL/#enable-extension>."
685 .into(),
686 ],
687 },
688 Error::UnknownLanguageExtension(span, name) => ParseError {
689 message: format!("unknown language extension `{name}`"),
690 labels: vec![(span, "".into())],
691 notes: vec![concat!(
692 "See available extensions at ",
693 "<https://www.w3.org/TR/WGSL/#language-extensions-sec>."
694 )
695 .into()],
696 },
697 Error::UnknownDiagnosticRuleName(span) => ParseError {
698 message: format!("unknown `diagnostic(…)` rule name `{}`", &source[span]),
699 labels: vec![(span, "not a valid diagnostic rule name".into())],
700 notes: vec![concat!(
701 "See available trigger rules at ",
702 "<https://www.w3.org/TR/WGSL/#filterable-triggering-rules>."
703 )
704 .into()],
705 },
706 Error::SizeAttributeTooLow(bad_span, min_size) => ParseError {
707 message: format!("struct member size must be at least {min_size}"),
708 labels: vec![(bad_span, format!("must be at least {min_size}").into())],
709 notes: vec![],
710 },
711 Error::AlignAttributeTooLow(bad_span, min_align) => ParseError {
712 message: format!("struct member alignment must be at least {min_align}"),
713 labels: vec![(bad_span, format!("must be at least {min_align}").into())],
714 notes: vec![],
715 },
716 Error::NonPowerOfTwoAlignAttribute(bad_span) => ParseError {
717 message: "struct member alignment must be a power of 2".to_string(),
718 labels: vec![(bad_span, "must be a power of 2".into())],
719 notes: vec![],
720 },
721 Error::InconsistentBinding(span) => ParseError {
722 message: "input/output binding is not consistent".to_string(),
723 labels: vec![(span, "input/output binding is not consistent".into())],
724 notes: vec![],
725 },
726 Error::TypeNotConstructible(span) => ParseError {
727 message: format!("type `{}` is not constructible", &source[span]),
728 labels: vec![(span, "type is not constructible".into())],
729 notes: vec![],
730 },
731 Error::TypeNotInferable(span) => ParseError {
732 message: "type can't be inferred".to_string(),
733 labels: vec![(span, "type can't be inferred".into())],
734 notes: vec![],
735 },
736 Error::InitializationTypeMismatch {
737 name,
738 ref expected,
739 ref got,
740 } => ParseError {
741 message: format!(
742 "the type of `{}` is expected to be `{}`, but got `{}`",
743 &source[name], expected, got,
744 ),
745 labels: vec![(name, format!("definition of `{}`", &source[name]).into())],
746 notes: vec![],
747 },
748 Error::DeclMissingTypeAndInit(name_span) => ParseError {
749 message: format!(
750 "declaration of `{}` needs a type specifier or initializer",
751 &source[name_span]
752 ),
753 labels: vec![(name_span, "needs a type specifier or initializer".into())],
754 notes: vec![],
755 },
756 Error::MissingAttribute(name, name_span) => ParseError {
757 message: format!(
758 "variable `{}` needs a '{}' attribute",
759 &source[name_span], name
760 ),
761 labels: vec![(
762 name_span,
763 format!("definition of `{}`", &source[name_span]).into(),
764 )],
765 notes: vec![],
766 },
767 Error::InvalidAddrOfOperand(span) => ParseError {
768 message: "cannot take the address of a vector component".to_string(),
769 labels: vec![(span, "invalid operand for address-of".into())],
770 notes: vec![],
771 },
772 Error::InvalidAtomicPointer(span) => ParseError {
773 message: "atomic operation is done on a pointer to a non-atomic".to_string(),
774 labels: vec![(span, "atomic pointer is invalid".into())],
775 notes: vec![],
776 },
777 Error::InvalidAtomicOperandType(span) => ParseError {
778 message: "atomic operand type is inconsistent with the operation".to_string(),
779 labels: vec![(span, "atomic operand type is invalid".into())],
780 notes: vec![],
781 },
782 Error::InvalidRayQueryPointer(span) => ParseError {
783 message: "ray query operation is done on a pointer to a non-ray-query".to_string(),
784 labels: vec![(span, "ray query pointer is invalid".into())],
785 notes: vec![],
786 },
787 Error::NotPointer(span) => ParseError {
788 message: "the operand of the `*` operator must be a pointer".to_string(),
789 labels: vec![(span, "expression is not a pointer".into())],
790 notes: vec![],
791 },
792 Error::NotReference(what, span) => ParseError {
793 message: format!("{what} must be a reference"),
794 labels: vec![(span, "expression is not a reference".into())],
795 notes: vec![],
796 },
797 Error::InvalidAssignment { span, ty } => {
798 let (extra_label, notes) = match ty {
799 InvalidAssignmentType::Swizzle => (
800 None,
801 vec![
802 "WGSL does not support assignments to swizzles".into(),
803 "consider assigning each component individually".into(),
804 ],
805 ),
806 InvalidAssignmentType::ImmutableBinding(binding_span) => (
807 Some((binding_span, "this is an immutable binding".into())),
808 vec![format!(
809 "consider declaring `{}` with `var` instead of `let`",
810 &source[binding_span]
811 )],
812 ),
813 InvalidAssignmentType::Other => (None, vec![]),
814 };
815
816 ParseError {
817 message: "invalid left-hand side of assignment".into(),
818 labels: core::iter::once((span, "cannot assign to this expression".into()))
819 .chain(extra_label)
820 .collect(),
821 notes,
822 }
823 }
824 Error::ReservedKeyword(name_span) => ParseError {
825 message: format!("name `{}` is a reserved keyword", &source[name_span]),
826 labels: vec![(
827 name_span,
828 format!("definition of `{}`", &source[name_span]).into(),
829 )],
830 notes: vec![],
831 },
832 Error::Redefinition { previous, current } => ParseError {
833 message: format!("redefinition of `{}`", &source[current]),
834 labels: vec![
835 (
836 current,
837 format!("redefinition of `{}`", &source[current]).into(),
838 ),
839 (
840 previous,
841 format!("previous definition of `{}`", &source[previous]).into(),
842 ),
843 ],
844 notes: vec![],
845 },
846 Error::RecursiveDeclaration { ident, usage } => ParseError {
847 message: format!("declaration of `{}` is recursive", &source[ident]),
848 labels: vec![(ident, "".into()), (usage, "uses itself here".into())],
849 notes: vec![],
850 },
851 Error::CyclicDeclaration { ident, ref path } => ParseError {
852 message: format!("declaration of `{}` is cyclic", &source[ident]),
853 labels: path
854 .iter()
855 .enumerate()
856 .flat_map(|(i, &(ident, usage))| {
857 [
858 (ident, "".into()),
859 (
860 usage,
861 if i == path.len() - 1 {
862 "ending the cycle".into()
863 } else {
864 format!("uses `{}`", &source[ident]).into()
865 },
866 ),
867 ]
868 })
869 .collect(),
870 notes: vec![],
871 },
872 Error::InvalidSwitchSelector { span } => ParseError {
873 message: "invalid `switch` selector".to_string(),
874 labels: vec![(
875 span,
876 "`switch` selector must be a scalar integer"
877 .into(),
878 )],
879 notes: vec![],
880 },
881 Error::InvalidSwitchCase { span } => ParseError {
882 message: "invalid `switch` case selector value".to_string(),
883 labels: vec![(
884 span,
885 "`switch` case selector must be a scalar integer const expression"
886 .into(),
887 )],
888 notes: vec![],
889 },
890 Error::SwitchCaseTypeMismatch { span } => ParseError {
891 message: "invalid `switch` case selector value".to_string(),
892 labels: vec![(
893 span,
894 "`switch` case selector must have the same type as the `switch` selector expression"
895 .into(),
896 )],
897 notes: vec![],
898 },
899 Error::CalledEntryPoint(span) => ParseError {
900 message: "entry point cannot be called".to_string(),
901 labels: vec![(span, "entry point cannot be called".into())],
902 notes: vec![],
903 },
904 Error::WrongArgumentCount {
905 span,
906 ref expected,
907 found,
908 } => ParseError {
909 message: format!(
910 "wrong number of arguments: expected {}, found {}",
911 if expected.len() < 2 {
912 format!("{}", expected.start)
913 } else {
914 format!("{}..{}", expected.start, expected.end)
915 },
916 found
917 ),
918 labels: vec![(span, "wrong number of arguments".into())],
919 notes: vec![],
920 },
921 Error::TooManyArguments {
922 ref function,
923 call_span,
924 arg_span,
925 max_arguments,
926 } => ParseError {
927 message: format!("too many arguments passed to `{function}`"),
928 labels: vec![
929 (call_span, "".into()),
930 (arg_span, format!("unexpected argument #{}", max_arguments + 1).into())
931 ],
932 notes: vec![
933 format!("The `{function}` function accepts at most {max_arguments} argument(s)")
934 ],
935 },
936 Error::WrongArgumentType {
937 ref function,
938 call_span,
939 arg_span,
940 arg_index,
941 ref arg_ty,
942 ref allowed,
943 } => {
944 let message = format!(
945 "wrong type passed as argument #{} to `{function}`",
946 arg_index + 1,
947 );
948 let labels = vec![
949 (call_span, "".into()),
950 (arg_span, format!("argument #{} has type `{arg_ty}`", arg_index + 1).into())
951 ];
952
953 let mut notes = vec![];
954 notes.push(format!("`{function}` accepts the following types for argument #{}:", arg_index + 1));
955 notes.extend(allowed.iter().map(|ty| format!("allowed type: {ty}")));
956
957 ParseError { message, labels, notes }
958 },
959 Error::InconsistentArgumentType {
960 ref function,
961 call_span,
962 arg_span,
963 arg_index,
964 ref arg_ty,
965 inconsistent_span,
966 inconsistent_index,
967 ref inconsistent_ty,
968 ref allowed
969 } => {
970 let message = format!(
971 "inconsistent type passed as argument #{} to `{function}`",
972 arg_index + 1,
973 );
974 let labels = vec![
975 (call_span, "".into()),
976 (arg_span, format!("argument #{} has type {arg_ty}", arg_index + 1).into()),
977 (inconsistent_span, format!(
978 "this argument has type {inconsistent_ty}, which constrains subsequent arguments"
979 ).into()),
980 ];
981 let mut notes = vec![
982 format!("Because argument #{} has type {inconsistent_ty}, only the following types", inconsistent_index + 1),
983 format!("(or types that automatically convert to them) are accepted for argument #{}:", arg_index + 1),
984 ];
985 notes.extend(allowed.iter().map(|ty| format!("allowed type: {ty}")));
986
987 ParseError { message, labels, notes }
988 }
989 Error::FunctionReturnsVoid(span) => ParseError {
990 message: "function does not return any value".to_string(),
991 labels: vec![(span, "".into())],
992 notes: vec![
993 "perhaps you meant to call the function in a separate statement?".into(),
994 ],
995 },
996 Error::FunctionMustUseUnused(call) => ParseError {
997 message: "unused return value from function annotated with @must_use".into(),
998 labels: vec![(call, "".into())],
999 notes: vec![
1000 format!(
1001 "function '{}' is declared with `@must_use` attribute",
1002 &source[call],
1003 ),
1004 "use a phony assignment or declare a value using the function call as the initializer".into(),
1005 ],
1006 },
1007 Error::FunctionMustUseReturnsVoid(attr, signature) => ParseError {
1008 message: "function annotated with @must_use but does not return any value".into(),
1009 labels: vec![
1010 (attr, "".into()),
1011 (signature, "".into()),
1012 ],
1013 notes: vec![
1014 "declare a return type or remove the attribute".into(),
1015 ],
1016 },
1017 Error::InvalidWorkGroupUniformLoad(span) => ParseError {
1018 message: "incorrect type passed to workgroupUniformLoad".into(),
1019 labels: vec![(span, "".into())],
1020 notes: vec!["passed type must be a workgroup pointer".into()],
1021 },
1022 Error::Internal(message) => ParseError {
1023 message: "internal WGSL front end error".to_string(),
1024 labels: vec![],
1025 notes: vec![message.into()],
1026 },
1027 Error::ExpectedConstExprConcreteIntegerScalar(span) => ParseError {
1028 message: concat!(
1029 "must be a const-expression that ",
1030 "resolves to a concrete integer scalar (`u32` or `i32`)"
1031 )
1032 .to_string(),
1033 labels: vec![(span, "must resolve to `u32` or `i32`".into())],
1034 notes: vec![],
1035 },
1036 Error::ExpectedNonNegative(span) => ParseError {
1037 message: "must be non-negative (>= 0)".to_string(),
1038 labels: vec![(span, "must be non-negative".into())],
1039 notes: vec![],
1040 },
1041 Error::ExpectedPositiveArrayLength(span) => ParseError {
1042 message: "array element count must be positive (> 0)".to_string(),
1043 labels: vec![(span, "must be positive".into())],
1044 notes: vec![],
1045 },
1046 Error::ConstantEvaluatorError(ref e, span) => ParseError {
1047 message: e.to_string(),
1048 labels: vec![(span, "see msg".into())],
1049 notes: vec![],
1050 },
1051 Error::MissingWorkgroupSize(span) => ParseError {
1052 message: "workgroup size is missing on compute shader entry point".to_string(),
1053 labels: vec![(
1054 span,
1055 "must be paired with a `@workgroup_size` attribute".into(),
1056 )],
1057 notes: vec![],
1058 },
1059 Error::AutoConversion(ref error) => {
1060 // destructuring ensures all fields are handled
1061 let AutoConversionError {
1062 dest_span,
1063 ref dest_type,
1064 source_span,
1065 ref source_type,
1066 } = **error;
1067 ParseError {
1068 message: format!(
1069 "automatic conversions cannot convert `{}` to `{}`",
1070 source_type, dest_type
1071 ),
1072 labels: vec![
1073 (
1074 dest_span,
1075 format!("a value of type {dest_type} is required here").into(),
1076 ),
1077 (
1078 source_span,
1079 format!("this expression has type {source_type}").into(),
1080 ),
1081 ],
1082 notes: vec![],
1083 }
1084 }
1085 Error::AutoConversionLeafScalar(ref error) => {
1086 let AutoConversionLeafScalarError {
1087 dest_span,
1088 ref dest_scalar,
1089 source_span,
1090 ref source_type,
1091 } = **error;
1092 ParseError {
1093 message: format!(
1094 "automatic conversions cannot convert elements of `{}` to `{}`",
1095 source_type, dest_scalar
1096 ),
1097 labels: vec![
1098 (
1099 dest_span,
1100 format!(
1101 "a value with elements of type {} is required here",
1102 dest_scalar
1103 )
1104 .into(),
1105 ),
1106 (
1107 source_span,
1108 format!("this expression has type {source_type}").into(),
1109 ),
1110 ],
1111 notes: vec![],
1112 }
1113 }
1114 Error::ConcretizationFailed(ref error) => {
1115 let ConcretizationFailedError {
1116 expr_span,
1117 ref expr_type,
1118 ref scalar,
1119 ref inner,
1120 } = **error;
1121 ParseError {
1122 message: format!("failed to convert expression to a concrete type: {inner}"),
1123 labels: vec![(
1124 expr_span,
1125 format!("this expression has type {expr_type}").into(),
1126 )],
1127 notes: vec![format!(
1128 "the expression should have been converted to have {} scalar type",
1129 scalar
1130 )],
1131 }
1132 }
1133 Error::ExceededLimitForNestedBraces { span, limit } => ParseError {
1134 message: "brace nesting limit reached".into(),
1135 labels: vec![(span, "limit reached at this brace".into())],
1136 notes: vec![format!("nesting limit is currently set to {limit}")],
1137 },
1138 Error::PipelineConstantIDValue(span) => ParseError {
1139 message: "pipeline constant ID must be between 0 and 65535 inclusive".to_string(),
1140 labels: vec![(span, "must be between 0 and 65535 inclusive".into())],
1141 notes: vec![],
1142 },
1143 Error::NotBool(span) => ParseError {
1144 message: "must be a const-expression that resolves to a `bool`".to_string(),
1145 labels: vec![(span, "must resolve to `bool`".into())],
1146 notes: vec![],
1147 },
1148 Error::ConstAssertFailed(span) => ParseError {
1149 message: "`const_assert` failure".to_string(),
1150 labels: vec![(span, "evaluates to `false`".into())],
1151 notes: vec![],
1152 },
1153 Error::DirectiveAfterFirstGlobalDecl { directive_span } => ParseError {
1154 message: "expected global declaration, but found a global directive".into(),
1155 labels: vec![(
1156 directive_span,
1157 "written after first global declaration".into(),
1158 )],
1159 notes: vec![concat!(
1160 "global directives are only allowed before global declarations; ",
1161 "maybe hoist this closer to the top of the shader module?"
1162 )
1163 .into()],
1164 },
1165 Error::EnableExtensionNotYetImplemented { kind, span } => ParseError {
1166 message: format!(
1167 "the `{}` enable-extension is not yet supported",
1168 EnableExtension::Unimplemented(kind).to_ident()
1169 ),
1170 labels: vec![(
1171 span,
1172 concat!(
1173 "this enable-extension specifies standard functionality ",
1174 "which is not yet implemented in Naga"
1175 )
1176 .into(),
1177 )],
1178 notes: vec![format!(
1179 concat!(
1180 "Let Naga maintainers know that you ran into this at ",
1181 "<https://github.com/gfx-rs/wgpu/issues/{}>, ",
1182 "so they can prioritize it!"
1183 ),
1184 kind.tracking_issue_num()
1185 )],
1186 },
1187 Error::EnableExtensionNotEnabled { kind, span } => ParseError {
1188 message: format!("the `{}` enable extension is not enabled", kind.to_ident()),
1189 labels: vec![(
1190 span,
1191 format!(
1192 concat!(
1193 "the `{}` \"Enable Extension\" is needed for this functionality, ",
1194 "but it is not currently enabled."
1195 ),
1196 kind.to_ident()
1197 )
1198 .into(),
1199 )],
1200 notes: if let EnableExtension::Unimplemented(kind) = kind {
1201 vec![format!(
1202 concat!(
1203 "This \"Enable Extension\" is not yet implemented. ",
1204 "Let Naga maintainers know that you ran into this at ",
1205 "<https://github.com/gfx-rs/wgpu/issues/{}>, ",
1206 "so they can prioritize it!"
1207 ),
1208 kind.tracking_issue_num()
1209 )]
1210 } else {
1211 vec![
1212 format!(
1213 "You can enable this extension by adding `enable {};` at the top of the shader, before any other items.",
1214 kind.to_ident()
1215 ),
1216 ]
1217 },
1218 },
1219 Error::LanguageExtensionNotYetImplemented { kind, span } => ParseError {
1220 message: format!(
1221 "the `{}` language extension is not yet supported",
1222 LanguageExtension::Unimplemented(kind).to_ident()
1223 ),
1224 labels: vec![(span, "".into())],
1225 notes: vec![format!(
1226 concat!(
1227 "Let Naga maintainers know that you ran into this at ",
1228 "<https://github.com/gfx-rs/wgpu/issues/{}>, ",
1229 "so they can prioritize it!"
1230 ),
1231 kind.tracking_issue_num()
1232 )],
1233 },
1234 Error::DiagnosticInvalidSeverity {
1235 severity_control_name_span,
1236 } => ParseError {
1237 message: "invalid `diagnostic(…)` severity".into(),
1238 labels: vec![(
1239 severity_control_name_span,
1240 "not a valid severity level".into(),
1241 )],
1242 notes: vec![concat!(
1243 "See available severities at ",
1244 "<https://www.w3.org/TR/WGSL/#diagnostic-severity>."
1245 )
1246 .into()],
1247 },
1248 Error::DiagnosticDuplicateTriggeringRule(ConflictingDiagnosticRuleError {
1249 triggering_rule_spans,
1250 }) => {
1251 let [first_span, second_span] = triggering_rule_spans;
1252 ParseError {
1253 message: "found conflicting `diagnostic(…)` rule(s)".into(),
1254 labels: vec![
1255 (first_span, "first rule".into()),
1256 (second_span, "second rule".into()),
1257 ],
1258 notes: vec![
1259 concat!(
1260 "Multiple `diagnostic(…)` rules with the same rule name ",
1261 "conflict unless they are directives and the severity is the same.",
1262 )
1263 .into(),
1264 "You should delete the rule you don't want.".into(),
1265 ],
1266 }
1267 }
1268 Error::DiagnosticAttributeNotYetImplementedAtParseSite {
1269 site_name_plural,
1270 ref spans,
1271 } => ParseError {
1272 message: "`@diagnostic(…)` attribute(s) not yet implemented".into(),
1273 labels: {
1274 let mut spans = spans.iter().cloned();
1275 let first = spans
1276 .next()
1277 .map(|span| {
1278 (
1279 span,
1280 format!("can't use this on {site_name_plural} (yet)").into(),
1281 )
1282 })
1283 .expect("internal error: diag. attr. rejection on empty map");
1284 core::iter::once(first)
1285 .chain(spans.map(|span| (span, "".into())))
1286 .collect()
1287 },
1288 notes: vec![format!(concat!(
1289 "Let Naga maintainers know that you ran into this at ",
1290 "<https://github.com/gfx-rs/wgpu/issues/5320>, ",
1291 "so they can prioritize it!"
1292 ))],
1293 },
1294 Error::DiagnosticAttributeNotSupported { on_what, ref spans } => {
1295 // In this case the user may have intended to create a global diagnostic filter directive,
1296 // so display a note to them suggesting the correct syntax.
1297 let intended_diagnostic_directive = match on_what {
1298 DiagnosticAttributeNotSupportedPosition::SemicolonInModulePosition => true,
1299 DiagnosticAttributeNotSupportedPosition::Other { .. } => false,
1300 };
1301 let on_what_plural = match on_what {
1302 DiagnosticAttributeNotSupportedPosition::SemicolonInModulePosition => {
1303 "semicolons"
1304 }
1305 DiagnosticAttributeNotSupportedPosition::Other { display_plural } => {
1306 display_plural
1307 }
1308 };
1309 ParseError {
1310 message: format!(
1311 "`@diagnostic(…)` attribute(s) on {on_what_plural} are not supported",
1312 ),
1313 labels: spans
1314 .iter()
1315 .cloned()
1316 .map(|span| (span, "".into()))
1317 .collect(),
1318 notes: vec![
1319 concat!(
1320 "`@diagnostic(…)` attributes are only permitted on `fn`s, ",
1321 "some statements, and `switch`/`loop` bodies."
1322 )
1323 .into(),
1324 {
1325 if intended_diagnostic_directive {
1326 concat!(
1327 "If you meant to declare a diagnostic filter that ",
1328 "applies to the entire module, move this line to ",
1329 "the top of the file and remove the `@` symbol."
1330 )
1331 .into()
1332 } else {
1333 concat!(
1334 "These attributes are well-formed, ",
1335 "you likely just need to move them."
1336 )
1337 .into()
1338 }
1339 },
1340 ],
1341 }
1342 }
1343 }
1344 }
1345 }