1use std::fmt::Display;
2use std::ops::{Deref, DerefMut};
3
4use cairo_lang_debug::DebugWithDb;
5use cairo_lang_defs::diagnostic_utils::StableLocation;
6use cairo_lang_defs::ids::{
7 EnumId, FunctionTitleId, GenericKind, ImplDefId, ImplFunctionId, ModuleId, ModuleItemId,
8 NamedLanguageElementId, StructId, TopLevelLanguageElementId, TraitFunctionId, TraitId,
9 TraitImplId, TraitItemId, UseId,
10};
11use cairo_lang_defs::plugin::PluginDiagnostic;
12use cairo_lang_diagnostics::{
13 DiagnosticAdded, DiagnosticEntry, DiagnosticNote, Diagnostics, DiagnosticsBuilder, ErrorCode,
14 Severity, error_code,
15};
16use cairo_lang_filesystem::db::Edition;
17use cairo_lang_filesystem::ids::{SmolStrId, SpanInFile};
18use cairo_lang_filesystem::span::TextWidth;
19use cairo_lang_parser::ParserDiagnostic;
20use cairo_lang_syntax as syntax;
21use cairo_lang_syntax::node::ast;
22use cairo_lang_syntax::node::helpers::GetIdentifier;
23use itertools::Itertools;
24use salsa::Database;
25use syntax::node::ids::SyntaxStablePtrId;
26
27use crate::corelib::LiteralError;
28use crate::expr::inference::InferenceError;
29use crate::items::feature_kind::FeatureMarkerDiagnostic;
30use crate::items::trt::ConcreteTraitTypeId;
31use crate::path::ContextualizePath;
32use crate::resolve::{ResolvedConcreteItem, ResolvedGenericItem};
33use crate::types::peel_snapshots;
34use crate::{ConcreteTraitId, semantic};
35
36#[cfg(test)]
37#[path = "diagnostic_test.rs"]
38mod test;
39
40pub struct SemanticDiagnostics<'db> {
42 builder: DiagnosticsBuilder<'db, SemanticDiagnostic<'db>>,
43 context_module: ModuleId<'db>,
44}
45
46impl<'db> SemanticDiagnostics<'db> {
47 pub fn new(context_module: ModuleId<'db>) -> Self {
49 Self { builder: DiagnosticsBuilder::default(), context_module }
50 }
51
52 pub fn from_diagnostics(
54 context_module: ModuleId<'db>,
55 diagnostics: Diagnostics<'db, SemanticDiagnostic<'db>>,
56 ) -> Self {
57 let mut builder = DiagnosticsBuilder::default();
58 builder.extend(diagnostics);
59 Self { builder, context_module }
60 }
61
62 pub fn build(self) -> Diagnostics<'db, SemanticDiagnostic<'db>> {
64 self.builder.build()
65 }
66}
67
68impl<'db> Deref for SemanticDiagnostics<'db> {
69 type Target = DiagnosticsBuilder<'db, SemanticDiagnostic<'db>>;
70
71 fn deref(&self) -> &Self::Target {
72 &self.builder
73 }
74}
75
76impl<'db> DerefMut for SemanticDiagnostics<'db> {
77 fn deref_mut(&mut self) -> &mut Self::Target {
78 &mut self.builder
79 }
80}
81
82pub trait SemanticDiagnosticsBuilder<'db> {
83 fn report(
85 &mut self,
86 stable_ptr: impl Into<SyntaxStablePtrId<'db>>,
87 kind: SemanticDiagnosticKind<'db>,
88 ) -> DiagnosticAdded;
89 fn report_after(
91 &mut self,
92 stable_ptr: impl Into<SyntaxStablePtrId<'db>>,
93 kind: SemanticDiagnosticKind<'db>,
94 ) -> DiagnosticAdded;
95 fn report_with_inner_span(
98 &mut self,
99 stable_ptr: impl Into<SyntaxStablePtrId<'db>>,
100 inner_span: (TextWidth, TextWidth),
101 kind: SemanticDiagnosticKind<'db>,
102 ) -> DiagnosticAdded;
103}
104impl<'db> SemanticDiagnosticsBuilder<'db> for SemanticDiagnostics<'db> {
105 fn report(
106 &mut self,
107 stable_ptr: impl Into<SyntaxStablePtrId<'db>>,
108 kind: SemanticDiagnosticKind<'db>,
109 ) -> DiagnosticAdded {
110 self.builder.add(SemanticDiagnostic::new(
111 StableLocation::new(stable_ptr.into()),
112 kind,
113 self.context_module,
114 ))
115 }
116 fn report_after(
117 &mut self,
118 stable_ptr: impl Into<SyntaxStablePtrId<'db>>,
119 kind: SemanticDiagnosticKind<'db>,
120 ) -> DiagnosticAdded {
121 self.builder.add(SemanticDiagnostic::new_after(
122 StableLocation::new(stable_ptr.into()),
123 kind,
124 self.context_module,
125 ))
126 }
127 fn report_with_inner_span(
128 &mut self,
129 stable_ptr: impl Into<SyntaxStablePtrId<'db>>,
130 inner_span: (TextWidth, TextWidth),
131 kind: SemanticDiagnosticKind<'db>,
132 ) -> DiagnosticAdded {
133 self.builder.add(SemanticDiagnostic::new(
134 StableLocation::with_inner_span(stable_ptr.into(), inner_span),
135 kind,
136 self.context_module,
137 ))
138 }
139}
140
141#[derive(Clone, Debug, Eq, Hash, PartialEq, salsa::Update)]
142pub struct SemanticDiagnostic<'db> {
143 pub stable_location: StableLocation<'db>,
144 pub kind: SemanticDiagnosticKind<'db>,
145 pub after: bool,
148 pub context_module: ModuleId<'db>,
150}
151impl<'db> SemanticDiagnostic<'db> {
152 pub fn new(
154 stable_location: StableLocation<'db>,
155 kind: SemanticDiagnosticKind<'db>,
156 context_module: ModuleId<'db>,
157 ) -> Self {
158 SemanticDiagnostic { stable_location, kind, after: false, context_module }
159 }
160 pub fn new_after(
162 stable_location: StableLocation<'db>,
163 kind: SemanticDiagnosticKind<'db>,
164 context_module: ModuleId<'db>,
165 ) -> Self {
166 SemanticDiagnostic { stable_location, kind, after: true, context_module }
167 }
168}
169impl<'db> DiagnosticEntry<'db> for SemanticDiagnostic<'db> {
170 fn format(&self, db: &dyn Database) -> String {
171 match &self.kind {
172 SemanticDiagnosticKind::ModuleFileNotFound(path) => {
173 format!("Module file not found. Expected path: {path}")
174 }
175 SemanticDiagnosticKind::Unsupported => "Unsupported feature.".into(),
176 SemanticDiagnosticKind::UnknownLiteral => "Unknown literal.".into(),
177 SemanticDiagnosticKind::UnknownBinaryOperator => "Unknown binary operator.".into(),
178 SemanticDiagnosticKind::UnknownTrait => "Unknown trait.".into(),
179 SemanticDiagnosticKind::UnknownImpl => "Unknown impl.".into(),
180 SemanticDiagnosticKind::UnexpectedElement { expected, actual } => {
181 let expected_str = expected.iter().map(|kind| kind.to_string()).join(" or ");
182 format!("Expected {expected_str}, found {actual}.")
183 }
184 SemanticDiagnosticKind::UnknownType => "Unknown type.".into(),
185 SemanticDiagnosticKind::UnknownEnum => "Unknown enum.".into(),
186 SemanticDiagnosticKind::LiteralError(literal_error) => literal_error.format(db),
187 SemanticDiagnosticKind::NotAVariant => {
188 "Not a variant. Use the full name Enum::Variant.".into()
189 }
190 SemanticDiagnosticKind::NotAStruct => "Not a struct.".into(),
191 SemanticDiagnosticKind::NotAType => "Not a type.".into(),
192 SemanticDiagnosticKind::NotATrait => "Not a trait.".into(),
193 SemanticDiagnosticKind::NotAnImpl => "Not an impl.".into(),
194 SemanticDiagnosticKind::ImplItemNotInTrait {
195 impl_def_id,
196 impl_item_name,
197 trait_id,
198 item_kind,
199 } => {
200 format!(
201 "Impl item {item_kind} `{}::{}` is not a member of trait `{}`.",
202 impl_def_id.name(db).long(db),
203 impl_item_name.long(db),
204 trait_id.name(db).long(db)
205 )
206 }
207 SemanticDiagnosticKind::ImplicitImplNotInferred {
208 trait_impl_id,
209 concrete_trait_id,
210 } => {
211 format!(
212 "Cannot infer implicit impl `{}.`\nCould not find implementation of trait \
213 `{:?}`",
214 trait_impl_id.name(db).long(db),
215 concrete_trait_id.debug(db)
216 )
217 }
218 SemanticDiagnosticKind::GenericsNotSupportedInItem { scope, item_kind } => {
219 format!("Generic parameters are not supported in {scope} item {item_kind}.")
220 }
221 SemanticDiagnosticKind::UnexpectedGenericArgs => "Unexpected generic arguments".into(),
222 SemanticDiagnosticKind::UnknownMember => "Unknown member.".into(),
223 SemanticDiagnosticKind::MemberSpecifiedMoreThanOnce => {
224 "Member specified more than once.".into()
225 }
226 SemanticDiagnosticKind::ConstCycle => {
227 "Cycle detected while resolving 'const' items.".into()
228 }
229 SemanticDiagnosticKind::UseCycle => {
230 "Cycle detected while resolving 'use' items.".into()
231 }
232 SemanticDiagnosticKind::TypeAliasCycle => {
233 "Cycle detected while resolving type-alias/impl-type items.".into()
234 }
235 SemanticDiagnosticKind::ImplAliasCycle => {
236 "Cycle detected while resolving 'impls alias' items.".into()
237 }
238 SemanticDiagnosticKind::ImplRequirementCycle => {
239 "Cycle detected while resolving generic param. Try specifying the generic impl \
240 parameter explicitly to break the cycle."
241 .into()
242 }
243 SemanticDiagnosticKind::MissingMember(member_name) => {
244 format!(r#"Missing member "{}"."#, member_name.long(db))
245 }
246 SemanticDiagnosticKind::WrongNumberOfParameters {
247 impl_def_id,
248 impl_function_id,
249 trait_id,
250 expected,
251 actual,
252 } => {
253 let function_name = impl_function_id.name(db).long(db);
254 format!(
255 "The number of parameters in the impl function `{}::{}` is incompatible with \
256 `{}::{}`. Expected: {}, actual: {}.",
257 impl_def_id.name(db).long(db),
258 function_name,
259 trait_id.name(db).long(db),
260 function_name,
261 expected,
262 actual,
263 )
264 }
265 SemanticDiagnosticKind::WrongNumberOfArguments { expected, actual } => {
266 format!("Wrong number of arguments. Expected {expected}, found: {actual}")
267 }
268 SemanticDiagnosticKind::WrongParameterType {
269 impl_def_id,
270 impl_function_id,
271 trait_id,
272 expected_ty,
273 actual_ty,
274 } => {
275 let function_name = impl_function_id.name(db).long(db);
276 format!(
277 "Parameter type of impl function `{}::{}` is incompatible with `{}::{}`. \
278 Expected: `{}`, actual: `{}`.",
279 impl_def_id.name(db).long(db),
280 function_name,
281 trait_id.name(db).long(db),
282 function_name,
283 expected_ty.format(db),
284 actual_ty.format(db)
285 )
286 }
287 SemanticDiagnosticKind::VariantCtorNotImmutable => {
288 "Variant constructor argument must be immutable.".to_string()
289 }
290 SemanticDiagnosticKind::TraitParamMutable { trait_id, function_id } => {
291 format!(
292 "Parameter of trait function `{}::{}` can't be defined as mutable.",
293 trait_id.name(db).long(db),
294 function_id.name(db).long(db),
295 )
296 }
297 SemanticDiagnosticKind::ParameterShouldBeReference {
298 impl_def_id,
299 impl_function_id,
300 trait_id,
301 } => {
302 let function_name = impl_function_id.name(db).long(db);
303 format!(
304 "Parameter of impl function {}::{} is incompatible with {}::{}. It should be \
305 a reference.",
306 impl_def_id.name(db).long(db),
307 function_name,
308 trait_id.name(db).long(db),
309 function_name,
310 )
311 }
312 SemanticDiagnosticKind::ParameterShouldNotBeReference {
313 impl_def_id,
314 impl_function_id,
315 trait_id,
316 } => {
317 let function_name = impl_function_id.name(db).long(db);
318 format!(
319 "Parameter of impl function {}::{} is incompatible with {}::{}. It should not \
320 be a reference.",
321 impl_def_id.name(db).long(db),
322 function_name,
323 trait_id.name(db).long(db),
324 function_name,
325 )
326 }
327 SemanticDiagnosticKind::WrongParameterName {
328 impl_def_id,
329 impl_function_id,
330 trait_id,
331 expected_name,
332 } => {
333 let function_name = impl_function_id.name(db).long(db);
334 format!(
335 "Parameter name of impl function {}::{function_name} is incompatible with \
336 {}::{function_name} parameter `{}`.",
337 impl_def_id.name(db).long(db),
338 trait_id.name(db).long(db),
339 expected_name.long(db)
340 )
341 }
342 SemanticDiagnosticKind::WrongType { expected_ty, actual_ty } => {
343 format!(
344 r#"Expected type "{}", found: "{}"."#,
345 expected_ty.format(db),
346 actual_ty.format(db)
347 )
348 }
349 SemanticDiagnosticKind::InconsistentBinding => "variable is bound inconsistently \
350 across alternatives separated by `|` \
351 bound in different ways"
352 .into(),
353 SemanticDiagnosticKind::WrongArgumentType { expected_ty, actual_ty } => {
354 let diagnostic_prefix = format!(
355 r#"Unexpected argument type. Expected: "{}", found: "{}"."#,
356 expected_ty.format(db),
357 actual_ty.format(db)
358 );
359 if (expected_ty.is_fully_concrete(db) && actual_ty.is_fully_concrete(db))
360 || peel_snapshots(db, *expected_ty).0 == peel_snapshots(db, *actual_ty).0
361 {
362 diagnostic_prefix
363 } else {
364 format!(
365 "{diagnostic_prefix}\nIt is possible that the type inference failed \
366 because the types differ in the number of snapshots.\nConsider adding or \
367 removing snapshots."
368 )
369 }
370 }
371 SemanticDiagnosticKind::WrongReturnType { expected_ty, actual_ty } => {
372 format!(
373 r#"Unexpected return type. Expected: "{}", found: "{}"."#,
374 expected_ty.format(db),
375 actual_ty.format(db)
376 )
377 }
378 SemanticDiagnosticKind::WrongExprType { expected_ty, actual_ty } => {
379 format!(
380 r#"Unexpected expression type. Expected: "{}", found: "{}"."#,
381 expected_ty.format(db),
382 actual_ty.format(db)
383 )
384 }
385 SemanticDiagnosticKind::WrongNumberOfGenericParamsForImplFunction {
386 expected,
387 actual,
388 } => {
389 format!(
390 "Wrong number of generic parameters for impl function. Expected: {expected}, \
391 found: {actual}."
392 )
393 }
394 SemanticDiagnosticKind::WrongReturnTypeForImpl {
395 impl_def_id,
396 impl_function_id,
397 trait_id,
398 expected_ty,
399 actual_ty,
400 } => {
401 let function_name = impl_function_id.name(db).long(db);
402 format!(
403 "Return type of impl function `{}::{}` is incompatible with `{}::{}`. \
404 Expected: `{}`, actual: `{}`.",
405 impl_def_id.name(db).long(db),
406 function_name,
407 trait_id.name(db).long(db),
408 function_name,
409 expected_ty.format(db),
410 actual_ty.format(db)
411 )
412 }
413 SemanticDiagnosticKind::WrongGenericParamTraitForImplFunction {
414 impl_def_id,
415 impl_function_id,
416 trait_id,
417 expected_trait,
418 actual_trait,
419 } => {
420 let function_name = impl_function_id.name(db).long(db);
421 format!(
422 "Generic parameter trait of impl function `{}::{}` is incompatible with \
423 `{}::{}`. Expected: `{:?}`, actual: `{:?}`.",
424 impl_def_id.name(db).long(db),
425 function_name,
426 trait_id.name(db).long(db),
427 function_name,
428 expected_trait.debug(db),
429 actual_trait.debug(db)
430 )
431 }
432 SemanticDiagnosticKind::WrongGenericParamKindForImplFunction {
433 impl_def_id,
434 impl_function_id,
435 trait_id,
436 expected_kind,
437 actual_kind,
438 } => {
439 let function_name = impl_function_id.name(db).long(db);
440 format!(
441 "Generic parameter kind of impl function `{}::{}` is incompatible with \
442 `{}::{}`. Expected: `{:?}`, actual: `{:?}`.",
443 impl_def_id.name(db).long(db),
444 function_name,
445 trait_id.name(db).long(db),
446 function_name,
447 expected_kind,
448 actual_kind
449 )
450 }
451 SemanticDiagnosticKind::AmbiguousTrait { trait_function_id0, trait_function_id1 } => {
452 format!(
453 "Ambiguous method call. More than one applicable trait function with a \
454 suitable self type was found: {} and {}. Consider adding type annotations or \
455 explicitly refer to the impl function.",
456 trait_function_id0
457 .contextualized_path(db, self.context_module)
458 .unwrap_or_else(|_| trait_function_id0.full_path(db)),
459 trait_function_id1
460 .contextualized_path(db, self.context_module)
461 .unwrap_or_else(|_| trait_function_id1.full_path(db))
462 )
463 }
464 SemanticDiagnosticKind::VariableNotFound(name) => {
465 format!(r#"Variable "{}" not found."#, name.long(db))
466 }
467 SemanticDiagnosticKind::MissingVariableInPattern => {
468 "Missing variable in pattern.".into()
469 }
470 SemanticDiagnosticKind::VariableDefinedMultipleTimesInPattern(name) => {
471 format!(r#"Redefinition of variable name "{}" in pattern."#, name.long(db))
472 }
473 SemanticDiagnosticKind::StructMemberRedefinition { struct_id, member_name } => {
474 format!(
475 r#"Redefinition of member "{}" on struct "{}"."#,
476 member_name.long(db),
477 struct_id
478 .contextualized_path(db, self.context_module)
479 .unwrap_or_else(|_| struct_id.full_path(db))
480 )
481 }
482 SemanticDiagnosticKind::EnumVariantRedefinition { enum_id, variant_name } => {
483 format!(
484 r#"Redefinition of variant "{}" on enum "{}"."#,
485 variant_name.long(db),
486 enum_id
487 .contextualized_path(db, self.context_module)
488 .unwrap_or_else(|_| enum_id.full_path(db))
489 )
490 }
491 SemanticDiagnosticKind::InfiniteSizeType(ty) => {
492 format!(r#"Recursive type "{}" has infinite size."#, ty.format(db))
493 }
494 SemanticDiagnosticKind::ArrayOfZeroSizedElements(ty) => {
495 format!(r#"Cannot have array of type "{}" that is zero sized."#, ty.format(db))
496 }
497 SemanticDiagnosticKind::ParamNameRedefinition { function_title_id, param_name } => {
498 format!(
499 r#"Redefinition of parameter name "{}"{}"#,
500 param_name.long(db),
501 function_title_id
502 .map(|function_title_id| format!(
503 r#" in function "{}"."#,
504 function_title_id
505 .contextualized_path(db, self.context_module)
506 .unwrap_or_else(|_| function_title_id.full_path(db))
507 ))
508 .unwrap_or(".".into()),
509 )
510 }
511 SemanticDiagnosticKind::ConditionNotBool(condition_ty) => {
512 format!(r#"Condition has type "{}", expected bool."#, condition_ty.format(db))
513 }
514 SemanticDiagnosticKind::IncompatibleArms {
515 multi_arm_expr_kind: incompatibility_kind,
516 pending_ty: first_ty,
517 different_ty,
518 } => {
519 let prefix = match incompatibility_kind {
520 MultiArmExprKind::Match => "Match arms have incompatible types",
521 MultiArmExprKind::If => "If blocks have incompatible types",
522 MultiArmExprKind::Loop => "Loop has incompatible return types",
523 };
524 format!(r#"{prefix}: "{}" and "{}""#, first_ty.format(db), different_ty.format(db))
525 }
526 SemanticDiagnosticKind::TypeHasNoMembers { ty, member_name: _ } => {
527 format!(r#"Type "{}" has no members."#, ty.format(db))
528 }
529 SemanticDiagnosticKind::NoSuchStructMember { struct_id, member_name } => {
530 format!(
531 r#"Struct "{}" has no member "{}""#,
532 struct_id
533 .contextualized_path(db, self.context_module)
534 .unwrap_or_else(|_| struct_id.full_path(db)),
535 member_name.long(db)
536 )
537 }
538 SemanticDiagnosticKind::NoSuchTypeMember { ty, member_name } => {
539 format!(r#"Type "{}" has no member "{}""#, ty.format(db), member_name.long(db))
540 }
541 SemanticDiagnosticKind::MemberNotVisible(member_name) => {
542 format!(r#"Member "{}" is not visible in this context."#, member_name.long(db))
543 }
544 SemanticDiagnosticKind::NoSuchVariant { enum_id, variant_name } => {
545 format!(
546 r#"Enum "{}" has no variant "{}""#,
547 enum_id
548 .contextualized_path(db, self.context_module)
549 .unwrap_or_else(|_| enum_id.full_path(db)),
550 variant_name.long(db)
551 )
552 }
553 SemanticDiagnosticKind::ReturnTypeNotErrorPropagateType => {
554 "`?` can only be used in a function with `Option` or `Result` return type.".into()
555 }
556 SemanticDiagnosticKind::IncompatibleErrorPropagateType { return_ty, err_ty } => {
557 format!(
558 r#"Return type "{}" does not wrap error "{}""#,
559 return_ty.format(db),
560 err_ty.format(db)
561 )
562 }
563 SemanticDiagnosticKind::ErrorPropagateOnNonErrorType(ty) => {
564 format!(r#"Type "{}" cannot error propagate"#, ty.format(db))
565 }
566 SemanticDiagnosticKind::UnhandledMustUseType(ty) => {
567 format!(r#"Unhandled `#[must_use]` type `{}`"#, ty.format(db))
568 }
569 SemanticDiagnosticKind::UnhandledMustUseFunction => {
570 "Unhandled `#[must_use]` function.".into()
571 }
572 SemanticDiagnosticKind::UnstableFeature { feature_name, note } => {
573 format!(
574 "Usage of unstable feature `{0}` with no `#[feature({0})]` attribute.{1}",
575 feature_name.long(db),
576 note.as_ref()
577 .map(|note| format!(" Note: {}", note.long(db)))
578 .unwrap_or_default()
579 )
580 }
581 SemanticDiagnosticKind::DeprecatedFeature { feature_name, note } => {
582 format!(
583 "Usage of deprecated feature `{0}` with no `#[feature({0})]` attribute.{1}",
584 feature_name.long(db),
585 note.as_ref()
586 .map(|note| format!(" Note: {}", note.long(db)))
587 .unwrap_or_default()
588 )
589 }
590 SemanticDiagnosticKind::InternalFeature { feature_name, note } => {
591 format!(
592 "Usage of internal feature `{0}` with no `#[feature({0})]` attribute.{1}",
593 feature_name.long(db),
594 note.as_ref()
595 .map(|note| format!(" Note: {}", note.long(db)))
596 .unwrap_or_default()
597 )
598 }
599 SemanticDiagnosticKind::FeatureMarkerDiagnostic(diagnostic) => match diagnostic {
600 FeatureMarkerDiagnostic::MultipleMarkers => {
601 "Multiple feature marker attributes.".into()
602 }
603 FeatureMarkerDiagnostic::MissingAllowFeature => {
604 "Missing `feature` arg for feature marker attribute.".into()
605 }
606 FeatureMarkerDiagnostic::UnsupportedArgument => {
607 "Unsupported argument for feature marker attribute.".into()
608 }
609 FeatureMarkerDiagnostic::DuplicatedArgument => {
610 "Duplicated argument for feature marker attribute.".into()
611 }
612 },
613 SemanticDiagnosticKind::UnusedVariable => {
614 "Unused variable. Consider ignoring by prefixing with `_`.".into()
615 }
616 SemanticDiagnosticKind::UnusedConstant => {
617 "Unused constant. Consider ignoring by prefixing with `_`.".into()
618 }
619 SemanticDiagnosticKind::MultipleConstantDefinition(constant_name) => {
620 format!(r#"Multiple definitions of constant "{}"."#, constant_name.long(db))
621 }
622 SemanticDiagnosticKind::UnusedUse => "Unused use.".into(),
623 SemanticDiagnosticKind::MultipleDefinitionforBinding(name) => {
624 format!(
625 r#"Multiple definitions of identifier '{}' as constant and variable."#,
626 name.long(db)
627 )
628 }
629 SemanticDiagnosticKind::MultipleGenericItemDefinition(type_name) => {
630 format!(r#"Multiple definitions of an item "{}"."#, type_name.long(db))
631 }
632 SemanticDiagnosticKind::UnsupportedUseItemInStatement => {
633 "Unsupported use item in statement.".into()
634 }
635 SemanticDiagnosticKind::InvalidMemberExpression => "Invalid member expression.".into(),
636 SemanticDiagnosticKind::InvalidPath => "Invalid path.".into(),
637 SemanticDiagnosticKind::RefArgNotAVariable => "ref argument must be a variable.".into(),
638 SemanticDiagnosticKind::RefArgNotMutable => {
639 "ref argument must be a mutable variable.".into()
640 }
641 SemanticDiagnosticKind::RefArgNotExplicit => {
642 "ref argument must be passed with a preceding 'ref'.".into()
643 }
644 SemanticDiagnosticKind::ImmutableArgWithModifiers => {
645 "Argument to immutable parameter cannot have modifiers.".into()
646 }
647 SemanticDiagnosticKind::AssignmentToImmutableVar => {
648 "Cannot assign to an immutable variable.".into()
649 }
650 SemanticDiagnosticKind::InvalidLhsForAssignment => {
651 "Invalid left-hand side of assignment.".into()
652 }
653 SemanticDiagnosticKind::PathNotFound(item_type) => match item_type {
654 NotFoundItemType::Identifier => "Identifier not found.".into(),
655 NotFoundItemType::Function => "Function not found.".into(),
656 NotFoundItemType::Type => "Type not found.".into(),
657 NotFoundItemType::Trait => "Trait not found.".into(),
658 NotFoundItemType::Impl => "Impl not found.".into(),
659 NotFoundItemType::Macro => "Macro not found.".into(),
660 },
661 SemanticDiagnosticKind::AmbiguousPath(module_items) => {
662 format!(
663 "Ambiguous path. Multiple matching items: {}",
664 module_items.iter().map(|item| format!("`{}`", item.full_path(db))).join(", ")
665 )
666 }
667 SemanticDiagnosticKind::UseSelfNonMulti => {
668 "`self` in `use` items is not allowed not in multi.".into()
669 }
670 SemanticDiagnosticKind::UseSelfEmptyPath => {
671 "`self` in `use` items is not allowed for empty path.".into()
672 }
673 SemanticDiagnosticKind::UseStarEmptyPath => {
674 "`*` in `use` items is not allowed for empty path.".into()
675 }
676 SemanticDiagnosticKind::GlobalUsesNotSupportedInEdition(edition) => {
677 format!("Global `use` item is not supported in `{edition:?}` edition.")
678 }
679 SemanticDiagnosticKind::TraitInTraitMustBeExplicit => {
680 "In a trait, paths of the same trait must be fully explicit. Either use `Self` if \
681 this is the intention, or explicitly specify all the generic arguments."
682 .to_string()
683 }
684 SemanticDiagnosticKind::ImplInImplMustBeExplicit => {
685 "In an impl, paths of the same impl must be fully explicit. Either use `Self` if \
686 this is the intention, or explicitly specify all the generic arguments."
687 .to_string()
688 }
689 SemanticDiagnosticKind::TraitItemForbiddenInTheTrait => {
690 "In a trait, paths of the same trait are not allowed. Did you mean to use `Self::`?"
691 .to_string()
692 }
693 SemanticDiagnosticKind::TraitItemForbiddenInItsImpl => "In an impl, paths of the \
694 impl's trait are not allowed. \
695 Did you mean to use `Self::`?"
696 .to_string(),
697 SemanticDiagnosticKind::ImplItemForbiddenInTheImpl => {
698 "In an impl, paths of the same impl are not allowed. Did you mean to use `Self::`?"
699 .to_string()
700 }
701 SemanticDiagnosticKind::SuperUsedInRootModule => {
702 "'super' cannot be used for the crate's root module.".into()
703 }
704 SemanticDiagnosticKind::SuperUsedInMacroCallTopLevel => {
705 "`super` used in macro call top level.".into()
706 }
707 SemanticDiagnosticKind::ItemNotVisible(item_id, containing_modules) => {
708 format!(
709 "Item `{}` is not visible in this context{}.",
710 item_id.full_path(db),
711 if containing_modules.is_empty() {
712 "".to_string()
713 } else if let [module_id] = &containing_modules[..] {
714 format!(" through module `{}`", module_id.full_path(db))
715 } else {
716 format!(
717 " through any of the modules: {}",
718 containing_modules
719 .iter()
720 .map(|module_id| format!("`{}`", module_id.full_path(db)))
721 .join(", ")
722 )
723 }
724 )
725 }
726 SemanticDiagnosticKind::UnusedImport(use_id) => {
727 format!("Unused import: `{}`", use_id.full_path(db))
728 }
729 SemanticDiagnosticKind::UnexpectedEnumPattern(ty) => {
730 format!(r#"Unexpected type for enum pattern. "{}" is not an enum."#, ty.format(db),)
731 }
732 SemanticDiagnosticKind::UnexpectedStructPattern(ty) => {
733 format!(
734 r#"Unexpected type for struct pattern. "{}" is not a struct."#,
735 ty.format(db),
736 )
737 }
738 SemanticDiagnosticKind::UnexpectedTuplePattern(ty) => {
739 format!(r#"Unexpected type for tuple pattern. "{}" is not a tuple."#, ty.format(db),)
740 }
741 SemanticDiagnosticKind::UnexpectedFixedSizeArrayPattern(ty) => {
742 format!(
743 "Unexpected type for fixed size array pattern. \"{}\" is not a fixed size \
744 array.",
745 ty.format(db),
746 )
747 }
748 SemanticDiagnosticKind::WrongNumberOfTupleElements { expected, actual } => format!(
749 r#"Wrong number of tuple elements in pattern. Expected: {expected}. Got: {actual}."#,
750 ),
751 SemanticDiagnosticKind::WrongNumberOfFixedSizeArrayElements { expected, actual } => {
752 format!(
753 "Wrong number of fixed size array elements in pattern. Expected: {expected}. \
754 Got: {actual}.",
755 )
756 }
757 SemanticDiagnosticKind::WrongEnum { expected_enum, actual_enum } => {
758 format!(
759 r#"Wrong enum in pattern. Expected: "{}". Got: "{}"."#,
760 expected_enum
761 .contextualized_path(db, self.context_module)
762 .unwrap_or_else(|_| expected_enum.full_path(db)),
763 actual_enum
764 .contextualized_path(db, self.context_module)
765 .unwrap_or_else(|_| actual_enum.full_path(db))
766 )
767 }
768 SemanticDiagnosticKind::RedundantModifier { current_modifier, previous_modifier } => {
769 format!(
770 "`{}` modifier was specified after another modifier (`{}`). Only a single \
771 modifier is allowed.",
772 current_modifier.long(db),
773 previous_modifier.long(db)
774 )
775 }
776 SemanticDiagnosticKind::ReferenceLocalVariable => {
777 "`ref` is only allowed for function parameters, not for local variables."
778 .to_string()
779 }
780 SemanticDiagnosticKind::InvalidCopyTraitImpl(inference_error) => {
781 format!("Invalid copy trait implementation, {}", inference_error.format(db))
782 }
783 SemanticDiagnosticKind::InvalidDropTraitImpl(inference_error) => {
784 format!("Invalid drop trait implementation, {}", inference_error.format(db))
785 }
786 SemanticDiagnosticKind::InvalidImplItem(item_kw) => {
787 format!("`{}` is not allowed inside impl.", item_kw.long(db))
788 }
789 SemanticDiagnosticKind::MissingItemsInImpl(item_names) => {
790 format!(
791 "Not all trait items are implemented. Missing: {}.",
792 item_names.iter().map(|name| format!("'{}'", name.long(db))).join(", ")
793 )
794 }
795 SemanticDiagnosticKind::PassPanicAsNopanic { impl_function_id, trait_id } => {
796 let name = impl_function_id.name(db).long(db);
797 let trait_name = trait_id.name(db).long(db);
798 format!(
799 "The signature of function `{name}` is incompatible with trait \
800 `{trait_name}`. The trait function is declared as nopanic."
801 )
802 }
803 SemanticDiagnosticKind::PassConstAsNonConst { impl_function_id, trait_id } => {
804 let name = impl_function_id.name(db).long(db);
805 let trait_name = trait_id.name(db).long(db);
806 format!(
807 "The signature of function `{name}` is incompatible with trait \
808 `{trait_name}`. The trait function is declared as const."
809 )
810 }
811 SemanticDiagnosticKind::PanicableFromNonPanicable => {
812 "Function is declared as nopanic but calls a function that may panic.".into()
813 }
814 SemanticDiagnosticKind::PanicableExternFunction => {
815 "An extern function must be marked as nopanic.".into()
816 }
817 SemanticDiagnosticKind::PluginDiagnostic(diagnostic) => {
818 format!("Plugin diagnostic: {}", diagnostic.message)
819 }
820 SemanticDiagnosticKind::MacroGeneratedCodeParserDiagnostic(parser_diagnostic) => {
821 format!("Parser error in macro-expanded code: {}", parser_diagnostic.format(db))
822 }
823 SemanticDiagnosticKind::NameDefinedMultipleTimes(name) => {
824 format!("The name `{}` is defined multiple times.", name.long(db))
825 }
826 SemanticDiagnosticKind::NonPrivateUseStar => {
827 "`pub` not supported for global `use`.".into()
828 }
829 SemanticDiagnosticKind::SelfGlobalUse => {
830 "cannot glob-import a module into itself".into()
831 }
832 SemanticDiagnosticKind::NamedArgumentsAreNotSupported => {
833 "Named arguments are not supported in this context.".into()
834 }
835 SemanticDiagnosticKind::UnnamedArgumentFollowsNamed => {
836 "Unnamed arguments cannot follow named arguments.".into()
837 }
838 SemanticDiagnosticKind::NamedArgumentMismatch { expected, found } => {
839 format!(
840 "Unexpected argument name. Expected: '{}', found '{}'.",
841 expected.long(db),
842 found.long(db)
843 )
844 }
845 SemanticDiagnosticKind::UnsupportedOutsideOfFunction(feature_name) => {
846 let feature_name_str = match feature_name {
847 UnsupportedOutsideOfFunctionFeatureName::ReturnStatement => "Return statement",
848 UnsupportedOutsideOfFunctionFeatureName::ErrorPropagate => "The '?' operator",
849 };
850 format!("{feature_name_str} is not supported outside of functions.")
851 }
852 SemanticDiagnosticKind::ConstTypeNotVarFree => {
853 "Constant type must not depend on its value.".into()
854 }
855 SemanticDiagnosticKind::UnsupportedConstant => {
856 "This expression is not supported as constant.".into()
857 }
858 SemanticDiagnosticKind::FailedConstantCalculation => {
859 "Failed to calculate constant.".into()
860 }
861 SemanticDiagnosticKind::ConstantCalculationDepthExceeded => {
862 "Constant calculation depth exceeded.".into()
863 }
864 SemanticDiagnosticKind::InnerFailedConstantCalculation(inner, _) => inner.format(db),
865 SemanticDiagnosticKind::DivisionByZero => "Division by zero.".into(),
866 SemanticDiagnosticKind::ExternTypeWithImplGenericsNotSupported => {
867 "Extern types with impl generics are not supported.".into()
868 }
869 SemanticDiagnosticKind::MissingSemicolon => "Missing semicolon".into(),
870 SemanticDiagnosticKind::TraitMismatch { expected_trt, actual_trt } => {
871 format!(
872 "Expected an impl of `{:?}`. Got an impl of `{:?}`.",
873 expected_trt.debug(db),
874 actual_trt.debug(db),
875 )
876 }
877 SemanticDiagnosticKind::InternalInferenceError(err) => err.format(db),
878 SemanticDiagnosticKind::DerefNonRef { ty } => {
879 format!("Type `{}` cannot be dereferenced", ty.format(db))
880 }
881 SemanticDiagnosticKind::NoImplementationOfIndexOperator { ty, inference_errors } => {
882 if inference_errors.is_empty() {
883 format!(
884 "Type `{}` does not implement the `Index` trait nor the `IndexView` trait.",
885 ty.format(db)
886 )
887 } else {
888 format!(
889 "Type `{}` could not be indexed.\n{}",
890 ty.format(db),
891 inference_errors.format(db)
892 )
893 }
894 }
895 SemanticDiagnosticKind::MultipleImplementationOfIndexOperator(ty) => {
896 format!(
897 r#"Type "{}" implements both the "Index" trait and the "IndexView" trait."#,
898 ty.format(db)
899 )
900 }
901 SemanticDiagnosticKind::UnsupportedInlineArguments => {
902 "Unsupported `inline` arguments.".into()
903 }
904 SemanticDiagnosticKind::RedundantInlineAttribute => {
905 "Redundant `inline` attribute.".into()
906 }
907 SemanticDiagnosticKind::InlineAttrForExternFunctionNotAllowed => {
908 "`inline` attribute is not allowed for extern functions.".into()
909 }
910 SemanticDiagnosticKind::InlineAlwaysWithImplGenericArgNotAllowed => {
911 "`#[inline(always)]` is not allowed for functions with impl generic parameters."
912 .into()
913 }
914 SemanticDiagnosticKind::CannotCallMethod {
915 ty,
916 method_name,
917 inference_errors,
918 relevant_traits,
919 } => {
920 if !inference_errors.is_empty() {
921 return format!(
922 "Method `{}` could not be called on type `{}`.\n{}",
923 method_name.long(db),
924 ty.format(db),
925 inference_errors.format(db)
926 );
927 }
928 if !relevant_traits.is_empty() {
929 let suggestions = relevant_traits
930 .iter()
931 .map(|trait_path| format!("`{trait_path}`"))
932 .collect::<Vec<_>>()
933 .join(", ");
934
935 format!(
936 "Method `{}` not found on type `{}`. Consider importing one of the \
937 following traits: {}.",
938 method_name.long(db),
939 ty.format(db),
940 suggestions
941 )
942 } else {
943 format!(
944 "Method `{}` not found on type `{}`. Did you import the correct trait and \
945 impl?",
946 method_name.long(db),
947 ty.format(db)
948 )
949 }
950 }
951 SemanticDiagnosticKind::TailExpressionNotAllowedInLoop => {
952 "Tail expression not allowed in a `loop` block.".into()
953 }
954 SemanticDiagnosticKind::ContinueOnlyAllowedInsideALoop => {
955 "`continue` only allowed inside a `loop`.".into()
956 }
957 SemanticDiagnosticKind::BreakOnlyAllowedInsideALoop => {
958 "`break` only allowed inside a `loop`.".into()
959 }
960 SemanticDiagnosticKind::BreakWithValueOnlyAllowedInsideALoop => {
961 "Can only break with a value inside a `loop`.".into()
962 }
963 SemanticDiagnosticKind::ErrorPropagateNotAllowedInsideALoop => {
964 "`?` not allowed inside a `loop`.".into()
965 }
966 SemanticDiagnosticKind::ConstGenericParamNotSupported => {
967 "Const generic args are not allowed in this context.".into()
968 }
969 SemanticDiagnosticKind::NegativeImplsNotEnabled => {
970 "Negative impls are not enabled in the current crate.".into()
971 }
972 SemanticDiagnosticKind::NegativeImplsOnlyOnImpls => {
973 "Negative impls supported only in impl definitions.".into()
974 }
975 SemanticDiagnosticKind::ImplicitPrecedenceAttrForExternFunctionNotAllowed => {
976 "`implicit_precedence` attribute is not allowed for extern functions.".into()
977 }
978 SemanticDiagnosticKind::RedundantImplicitPrecedenceAttribute => {
979 "Redundant `implicit_precedence` attribute.".into()
980 }
981 SemanticDiagnosticKind::UnsupportedImplicitPrecedenceArguments => {
982 "Unsupported `implicit_precedence` arguments.".into()
983 }
984 SemanticDiagnosticKind::UnsupportedFeatureAttrArguments => {
985 "`feature` attribute argument should be a single string.".into()
986 }
987 SemanticDiagnosticKind::UnsupportedAllowAttrArguments => {
988 "`allow` attribute argument not supported.".into()
990 }
991 SemanticDiagnosticKind::UnsupportedPubArgument => "Unsupported `pub` argument.".into(),
992 SemanticDiagnosticKind::UnknownStatementAttribute => {
993 "Unknown statement attribute.".into()
994 }
995 SemanticDiagnosticKind::InlineMacroNotFound(macro_name) => {
996 format!("Inline macro `{}` not found.", macro_name.long(db))
997 }
998 SemanticDiagnosticKind::InlineMacroFailed(macro_name) => {
999 format!("Inline macro `{}` failed.", macro_name.long(db))
1000 }
1001 SemanticDiagnosticKind::InlineMacroNoMatchingRule(macro_name) => {
1002 format!("No matching rule found in inline macro `{}`.", macro_name.long(db))
1003 }
1004 SemanticDiagnosticKind::MacroCallToNotAMacro(name) => {
1005 format!("Call to `{}` which is not a macro.", name.long(db))
1006 }
1007 SemanticDiagnosticKind::UnknownGenericParam(name) => {
1008 format!("Unknown generic parameter `{}`.", name.long(db))
1009 }
1010 SemanticDiagnosticKind::PositionalGenericAfterNamed => {
1011 "Positional generic parameters must come before named generic parameters.".into()
1012 }
1013 SemanticDiagnosticKind::GenericArgDuplicate(name) => {
1014 format!("Generic argument `{}` is specified more than once.", name.long(db))
1015 }
1016 SemanticDiagnosticKind::TooManyGenericArguments { expected, actual } => {
1017 format!("Expected {expected} generic arguments, found {actual}.")
1018 }
1019 SemanticDiagnosticKind::GenericArgOutOfOrder(name) => {
1020 format!("Generic argument `{}` is out of order.", name.long(db))
1021 }
1022 SemanticDiagnosticKind::ArgPassedToNegativeImpl => {
1023 "Only `_` is valid as a negative impl argument.".into()
1024 }
1025 SemanticDiagnosticKind::CouponForExternFunctionNotAllowed => {
1026 "Coupon cannot be used with extern functions.".into()
1027 }
1028 SemanticDiagnosticKind::CouponArgumentNoModifiers => {
1029 "The __coupon__ argument cannot have modifiers.".into()
1030 }
1031 SemanticDiagnosticKind::CouponsDisabled => {
1032 "Coupons are disabled in the current crate.\nYou can enable them by enabling the \
1033 coupons experimental feature in the crate config."
1034 .into()
1035 }
1036 SemanticDiagnosticKind::ReprPtrsDisabled => {
1037 "Representation pointers are disabled in the current crate.\nYou can enable them \
1038 by enabling the `repr_ptrs` experimental feature in the crate config."
1039 .into()
1040 }
1041 SemanticDiagnosticKind::AssignmentToReprPtrVariable { .. } => {
1042 "Cannot assign to a variable with a taken pointer".into()
1043 }
1044 SemanticDiagnosticKind::StructBaseStructExpressionNotLast => {
1045 "The base struct must always be the last argument.".into()
1046 }
1047 SemanticDiagnosticKind::StructBaseStructExpressionNoEffect => {
1048 "Base struct has no effect, all the fields in the struct have already been \
1049 specified."
1050 .into()
1051 }
1052 SemanticDiagnosticKind::FixedSizeArrayTypeNonSingleType => {
1053 "Fixed size array type must have exactly one type.".into()
1054 }
1055 SemanticDiagnosticKind::FixedSizeArrayTypeEmptySize => {
1056 "Fixed size array type must have a size clause.".into()
1057 }
1058 SemanticDiagnosticKind::FixedSizeArrayNonNumericSize => {
1059 "Fixed size array type must have a positive integer size.".into()
1060 }
1061 SemanticDiagnosticKind::FixedSizeArrayNonSingleValue => {
1062 "Fixed size array with defined size must have exactly one value.".into()
1063 }
1064 SemanticDiagnosticKind::FixedSizeArraySizeTooBig => {
1065 "Fixed size array size must be smaller than 2^15.".into()
1066 }
1067 SemanticDiagnosticKind::SelfNotSupportedInContext => {
1068 "`Self` is not supported in this context.".into()
1069 }
1070 SemanticDiagnosticKind::SelfMustBeFirst => {
1071 "`Self` can only be the first segment of a path.".into()
1072 }
1073 SemanticDiagnosticKind::DollarNotSupportedInContext => {
1074 "`$` is not supported in this context.".into()
1075 }
1076 SemanticDiagnosticKind::UnknownResolverModifier { modifier } => {
1077 format!("`${}` is not supported.", modifier.long(db))
1078 }
1079 SemanticDiagnosticKind::EmptyPathAfterResolverModifier => {
1080 "Expected path after modifier.".into()
1081 }
1082 SemanticDiagnosticKind::CannotCreateInstancesOfPhantomTypes => {
1083 "Can not create instances of phantom types.".into()
1084 }
1085 SemanticDiagnosticKind::NonPhantomTypeContainingPhantomType => {
1086 "Non-phantom type containing phantom type.".into()
1087 }
1088 SemanticDiagnosticKind::DerefCycle { deref_chain } => {
1089 format!("Deref impls cycle detected:\n{deref_chain}")
1090 }
1091 SemanticDiagnosticKind::NoImplementationOfTrait {
1092 ty,
1093 trait_name,
1094 inference_errors,
1095 } => {
1096 if inference_errors.is_empty() {
1097 format!(
1098 "Implementation of trait `{}` not found on type `{}`. Did you import the \
1099 correct trait and impl?",
1100 trait_name.long(db),
1101 ty.format(db)
1102 )
1103 } else {
1104 format!(
1105 "Could not find implementation of trait `{}` on type `{}`.\n{}",
1106 trait_name.long(db),
1107 ty.format(db),
1108 inference_errors.format(db)
1109 )
1110 }
1111 }
1112 SemanticDiagnosticKind::CallExpressionRequiresFunction { ty, inference_errors } => {
1113 if inference_errors.is_empty() {
1114 format!("Call expression requires a function, found `{}`.", ty.format(db))
1115 } else {
1116 format!(
1117 "Call expression requires a function, found `{}`.\n{}",
1118 ty.format(db),
1119 inference_errors.format(db)
1120 )
1121 }
1122 }
1123 SemanticDiagnosticKind::CompilerTraitReImplementation { trait_id } => {
1124 format!(
1125 "Trait `{}` should not be implemented outside of the corelib.",
1126 trait_id.full_path(db)
1127 )
1128 }
1129 SemanticDiagnosticKind::ClosureInGlobalScope => {
1130 "Closures are not allowed in this context.".into()
1131 }
1132 SemanticDiagnosticKind::MaybeMissingColonColon => "Are you missing a `::`?.".into(),
1133 SemanticDiagnosticKind::CallingShadowedFunction { shadowed_function_name } => {
1134 format!(
1135 "Function `{}` is shadowed by a local variable.",
1136 shadowed_function_name.long(db)
1137 )
1138 }
1139 SemanticDiagnosticKind::RefClosureArgument => {
1140 "Arguments to closure functions cannot be references".into()
1141 }
1142 SemanticDiagnosticKind::RefClosureParam => {
1143 "Closure parameters cannot be references".into()
1144 }
1145 SemanticDiagnosticKind::MustBeNextToTypeOrTrait { trait_id } => {
1146 format!(
1147 "'{}' implementation must be defined in the same module as either the type \
1148 being dereferenced or the trait itself",
1149 trait_id.name(db).long(db)
1150 )
1151 }
1152 SemanticDiagnosticKind::MutableCapturedVariable => {
1153 "Capture of mutable variables in a closure is not supported".into()
1154 }
1155 SemanticDiagnosticKind::NonTraitTypeConstrained { identifier, concrete_trait_id } => {
1156 format!(
1157 "associated type `{}` not found for `{}`",
1158 identifier.long(db),
1159 concrete_trait_id
1160 .contextualized_path(db, self.context_module)
1161 .unwrap_or_else(|_| concrete_trait_id.full_path(db))
1162 )
1163 }
1164 SemanticDiagnosticKind::DuplicateTypeConstraint {
1165 concrete_trait_type_id: trait_type_id,
1166 } => {
1167 let concrete_trait = trait_type_id.concrete_trait(db);
1168 format!(
1169 "the value of the associated type `{}` in trait `{}` is already specified",
1170 trait_type_id.trait_type(db).name(db).long(db),
1171 concrete_trait
1172 .contextualized_path(db, self.context_module)
1173 .unwrap_or_else(|_| concrete_trait.full_path(db))
1174 )
1175 }
1176 SemanticDiagnosticKind::TypeConstraintsSyntaxNotEnabled => {
1177 "Type constraints syntax is not enabled in the current crate.".into()
1178 }
1179 SemanticDiagnosticKind::PatternMissingArgs(path) => {
1180 format!(
1181 "Pattern missing subpattern for the payload of variant. Consider using `{}(_)`",
1182 path.segments(db)
1183 .elements(db)
1184 .map(|seg| seg.identifier(db).long(db))
1185 .join("::")
1186 )
1187 }
1188 SemanticDiagnosticKind::UndefinedMacroPlaceholder(name) => {
1189 format!("Undefined macro placeholder: '{}'.", name.long(db))
1190 }
1191 SemanticDiagnosticKind::UserDefinedInlineMacrosDisabled => {
1192 "User defined inline macros are disabled in the current crate.".into()
1193 }
1194 SemanticDiagnosticKind::NonNeverLetElseType => concat!(
1195 "`else` clause of `let...else` must exit the scope. ",
1196 "Consider using `return`, `continue`, ..."
1197 )
1198 .into(),
1199 SemanticDiagnosticKind::OnlyTypeOrConstParamsInNegImpl => {
1200 "Negative impls may only use type or const generic parameters.".into()
1201 }
1202 }
1203 }
1204 fn location(&self, db: &'db dyn Database) -> SpanInFile<'db> {
1205 if let SemanticDiagnosticKind::MacroGeneratedCodeParserDiagnostic(parser_diagnostic) =
1206 &self.kind
1207 {
1208 return SpanInFile { file_id: parser_diagnostic.file_id, span: parser_diagnostic.span };
1209 };
1210
1211 let mut location = self.stable_location.span_in_file(db);
1212 if self.after {
1213 location = location.after();
1214 }
1215 location
1216 }
1217
1218 fn severity(&self) -> Severity {
1219 match &self.kind {
1220 SemanticDiagnosticKind::UnusedVariable
1221 | SemanticDiagnosticKind::UnhandledMustUseType { .. }
1222 | SemanticDiagnosticKind::UnhandledMustUseFunction
1223 | SemanticDiagnosticKind::TraitInTraitMustBeExplicit
1224 | SemanticDiagnosticKind::ImplInImplMustBeExplicit
1225 | SemanticDiagnosticKind::TraitItemForbiddenInTheTrait
1226 | SemanticDiagnosticKind::TraitItemForbiddenInItsImpl
1227 | SemanticDiagnosticKind::ImplItemForbiddenInTheImpl
1228 | SemanticDiagnosticKind::UnstableFeature { .. }
1229 | SemanticDiagnosticKind::DeprecatedFeature { .. }
1230 | SemanticDiagnosticKind::UnusedImport { .. }
1231 | SemanticDiagnosticKind::CallingShadowedFunction { .. }
1232 | SemanticDiagnosticKind::UnusedConstant
1233 | SemanticDiagnosticKind::UnusedUse
1234 | SemanticDiagnosticKind::PatternMissingArgs(_)
1235 | SemanticDiagnosticKind::UnsupportedAllowAttrArguments => Severity::Warning,
1236 SemanticDiagnosticKind::PluginDiagnostic(diag) => diag.severity,
1237 _ => Severity::Error,
1238 }
1239 }
1240
1241 fn notes(&self, _db: &dyn Database) -> &[DiagnosticNote<'_>] {
1242 match &self.kind {
1243 SemanticDiagnosticKind::InnerFailedConstantCalculation(_, notes) => notes,
1244 SemanticDiagnosticKind::AssignmentToReprPtrVariable(notes) => notes,
1245 _ => &[],
1246 }
1247 }
1248
1249 fn error_code(&self) -> Option<ErrorCode> {
1250 Some(match &self.kind {
1251 SemanticDiagnosticKind::UnusedVariable => error_code!(E0001),
1252 SemanticDiagnosticKind::CannotCallMethod { .. } => error_code!(E0002),
1253 SemanticDiagnosticKind::MissingMember(_) => error_code!(E0003),
1254 SemanticDiagnosticKind::MissingItemsInImpl(_) => error_code!(E0004),
1255 SemanticDiagnosticKind::ModuleFileNotFound(_) => error_code!(E0005),
1256 SemanticDiagnosticKind::PathNotFound(_) => error_code!(E0006),
1257 SemanticDiagnosticKind::NoSuchTypeMember { .. } => error_code!(E0007),
1258 SemanticDiagnosticKind::Unsupported => error_code!(E2000),
1259 SemanticDiagnosticKind::UnknownLiteral => error_code!(E2001),
1260 SemanticDiagnosticKind::UnknownBinaryOperator => error_code!(E2002),
1261 SemanticDiagnosticKind::UnknownTrait => error_code!(E2003),
1262 SemanticDiagnosticKind::UnknownImpl => error_code!(E2004),
1263 SemanticDiagnosticKind::UnexpectedElement { .. } => error_code!(E2005),
1264 SemanticDiagnosticKind::UnknownType => error_code!(E2006),
1265 SemanticDiagnosticKind::UnknownEnum => error_code!(E2007),
1266 SemanticDiagnosticKind::LiteralError(..) => error_code!(E2008),
1267 SemanticDiagnosticKind::NotAVariant => error_code!(E2009),
1268 SemanticDiagnosticKind::NotAStruct => error_code!(E2010),
1269 SemanticDiagnosticKind::NotAType => error_code!(E2011),
1270 SemanticDiagnosticKind::NotATrait => error_code!(E2012),
1271 SemanticDiagnosticKind::NotAnImpl => error_code!(E2013),
1272 SemanticDiagnosticKind::ImplItemNotInTrait { .. } => error_code!(E2014),
1273 SemanticDiagnosticKind::ImplicitImplNotInferred { .. } => error_code!(E2015),
1274 SemanticDiagnosticKind::GenericsNotSupportedInItem { .. } => error_code!(E2016),
1275 SemanticDiagnosticKind::UnexpectedGenericArgs => error_code!(E2017),
1276 SemanticDiagnosticKind::UnknownMember => error_code!(E2018),
1277 SemanticDiagnosticKind::CannotCreateInstancesOfPhantomTypes => error_code!(E2019),
1278 SemanticDiagnosticKind::NonPhantomTypeContainingPhantomType => error_code!(E2020),
1279 SemanticDiagnosticKind::MemberSpecifiedMoreThanOnce => error_code!(E2021),
1280 SemanticDiagnosticKind::StructBaseStructExpressionNotLast => error_code!(E2022),
1281 SemanticDiagnosticKind::StructBaseStructExpressionNoEffect => error_code!(E2023),
1282 SemanticDiagnosticKind::ConstCycle => error_code!(E2024),
1283 SemanticDiagnosticKind::UseCycle => error_code!(E2025),
1284 SemanticDiagnosticKind::TypeAliasCycle => error_code!(E2026),
1285 SemanticDiagnosticKind::ImplAliasCycle => error_code!(E2027),
1286 SemanticDiagnosticKind::ImplRequirementCycle => error_code!(E2028),
1287 SemanticDiagnosticKind::WrongNumberOfParameters { .. } => error_code!(E2029),
1288 SemanticDiagnosticKind::WrongNumberOfArguments { .. } => error_code!(E2030),
1289 SemanticDiagnosticKind::WrongParameterType { .. } => error_code!(E2031),
1290 SemanticDiagnosticKind::VariantCtorNotImmutable => error_code!(E2032),
1291 SemanticDiagnosticKind::TraitParamMutable { .. } => error_code!(E2033),
1292 SemanticDiagnosticKind::ParameterShouldBeReference { .. } => error_code!(E2034),
1293 SemanticDiagnosticKind::ParameterShouldNotBeReference { .. } => error_code!(E2035),
1294 SemanticDiagnosticKind::WrongParameterName { .. } => error_code!(E2036),
1295 SemanticDiagnosticKind::WrongGenericParamTraitForImplFunction { .. } => {
1296 error_code!(E2037)
1297 }
1298 SemanticDiagnosticKind::WrongGenericParamKindForImplFunction { .. } => {
1299 error_code!(E2038)
1300 }
1301 SemanticDiagnosticKind::WrongType { .. } => error_code!(E2039),
1302 SemanticDiagnosticKind::InconsistentBinding => error_code!(E2040),
1303 SemanticDiagnosticKind::WrongArgumentType { .. } => error_code!(E2041),
1304 SemanticDiagnosticKind::WrongReturnType { .. } => error_code!(E2042),
1305 SemanticDiagnosticKind::WrongExprType { .. } => error_code!(E2043),
1306 SemanticDiagnosticKind::WrongNumberOfGenericParamsForImplFunction { .. } => {
1307 error_code!(E2044)
1308 }
1309 SemanticDiagnosticKind::WrongReturnTypeForImpl { .. } => error_code!(E2045),
1310 SemanticDiagnosticKind::AmbiguousTrait { .. } => error_code!(E2046),
1311 SemanticDiagnosticKind::VariableNotFound(..) => error_code!(E2047),
1312 SemanticDiagnosticKind::MissingVariableInPattern => error_code!(E2048),
1313 SemanticDiagnosticKind::VariableDefinedMultipleTimesInPattern(..) => error_code!(E2049),
1314 SemanticDiagnosticKind::StructMemberRedefinition { .. } => error_code!(E2050),
1315 SemanticDiagnosticKind::EnumVariantRedefinition { .. } => error_code!(E2051),
1316 SemanticDiagnosticKind::InfiniteSizeType(..) => error_code!(E2052),
1317 SemanticDiagnosticKind::ArrayOfZeroSizedElements(..) => error_code!(E2053),
1318 SemanticDiagnosticKind::ParamNameRedefinition { .. } => error_code!(E2054),
1319 SemanticDiagnosticKind::ConditionNotBool(..) => error_code!(E2055),
1320 SemanticDiagnosticKind::IncompatibleArms { .. } => error_code!(E2056),
1321 SemanticDiagnosticKind::TypeHasNoMembers { .. } => error_code!(E2057),
1322 SemanticDiagnosticKind::NoSuchStructMember { .. } => error_code!(E2058),
1323 SemanticDiagnosticKind::MemberNotVisible(..) => error_code!(E2059),
1324 SemanticDiagnosticKind::NoSuchVariant { .. } => error_code!(E2060),
1325 SemanticDiagnosticKind::ReturnTypeNotErrorPropagateType => error_code!(E2061),
1326 SemanticDiagnosticKind::IncompatibleErrorPropagateType { .. } => error_code!(E2062),
1327 SemanticDiagnosticKind::ErrorPropagateOnNonErrorType(_) => error_code!(E2063),
1328 SemanticDiagnosticKind::UnhandledMustUseType(_) => error_code!(E2064),
1329 SemanticDiagnosticKind::UnstableFeature { .. } => error_code!(E2065),
1330 SemanticDiagnosticKind::DeprecatedFeature { .. } => error_code!(E2066),
1331 SemanticDiagnosticKind::InternalFeature { .. } => error_code!(E2067),
1332 SemanticDiagnosticKind::FeatureMarkerDiagnostic(_) => error_code!(E2068),
1333 SemanticDiagnosticKind::UnhandledMustUseFunction => error_code!(E2069),
1334 SemanticDiagnosticKind::UnusedConstant => error_code!(E2070),
1335 SemanticDiagnosticKind::UnusedUse => error_code!(E2071),
1336 SemanticDiagnosticKind::MultipleConstantDefinition(_) => error_code!(E2072),
1337 SemanticDiagnosticKind::MultipleDefinitionforBinding(_) => error_code!(E2073),
1338 SemanticDiagnosticKind::MultipleGenericItemDefinition(_) => error_code!(E2074),
1339 SemanticDiagnosticKind::UnsupportedUseItemInStatement => error_code!(E2075),
1340 SemanticDiagnosticKind::ConstGenericParamNotSupported => error_code!(E2076),
1341 SemanticDiagnosticKind::NegativeImplsNotEnabled => error_code!(E2077),
1342 SemanticDiagnosticKind::NegativeImplsOnlyOnImpls => error_code!(E2078),
1343 SemanticDiagnosticKind::RefArgNotAVariable => error_code!(E2079),
1344 SemanticDiagnosticKind::RefArgNotMutable => error_code!(E2080),
1345 SemanticDiagnosticKind::RefArgNotExplicit => error_code!(E2081),
1346 SemanticDiagnosticKind::ImmutableArgWithModifiers => error_code!(E2082),
1347 SemanticDiagnosticKind::AssignmentToImmutableVar => error_code!(E2083),
1348 SemanticDiagnosticKind::InvalidLhsForAssignment => error_code!(E2084),
1349 SemanticDiagnosticKind::InvalidMemberExpression => error_code!(E2085),
1350 SemanticDiagnosticKind::InvalidPath => error_code!(E2086),
1351 SemanticDiagnosticKind::AmbiguousPath(_) => error_code!(E2087),
1352 SemanticDiagnosticKind::UseSelfNonMulti => error_code!(E2088),
1353 SemanticDiagnosticKind::UseSelfEmptyPath => error_code!(E2089),
1354 SemanticDiagnosticKind::UseStarEmptyPath => error_code!(E2090),
1355 SemanticDiagnosticKind::GlobalUsesNotSupportedInEdition(_) => error_code!(E2091),
1356 SemanticDiagnosticKind::TraitInTraitMustBeExplicit => error_code!(E2092),
1357 SemanticDiagnosticKind::ImplInImplMustBeExplicit => error_code!(E2093),
1358 SemanticDiagnosticKind::TraitItemForbiddenInTheTrait => error_code!(E2094),
1359 SemanticDiagnosticKind::TraitItemForbiddenInItsImpl => error_code!(E2095),
1360 SemanticDiagnosticKind::ImplItemForbiddenInTheImpl => error_code!(E2096),
1361 SemanticDiagnosticKind::SuperUsedInRootModule => error_code!(E2097),
1362 SemanticDiagnosticKind::SuperUsedInMacroCallTopLevel => error_code!(E2098),
1363 SemanticDiagnosticKind::ItemNotVisible(..) => error_code!(E2099),
1364 SemanticDiagnosticKind::UnusedImport(_) => error_code!(E2100),
1365 SemanticDiagnosticKind::RedundantModifier { .. } => error_code!(E2101),
1366 SemanticDiagnosticKind::ReferenceLocalVariable => error_code!(E2102),
1367 SemanticDiagnosticKind::UnexpectedEnumPattern(_) => error_code!(E2103),
1368 SemanticDiagnosticKind::UnexpectedStructPattern(_) => error_code!(E2104),
1369 SemanticDiagnosticKind::UnexpectedTuplePattern(_) => error_code!(E2105),
1370 SemanticDiagnosticKind::UnexpectedFixedSizeArrayPattern(_) => error_code!(E2106),
1371 SemanticDiagnosticKind::WrongNumberOfTupleElements { .. } => error_code!(E2107),
1372 SemanticDiagnosticKind::WrongNumberOfFixedSizeArrayElements { .. } => {
1373 error_code!(E2108)
1374 }
1375 SemanticDiagnosticKind::WrongEnum { .. } => error_code!(E2109),
1376 SemanticDiagnosticKind::InvalidCopyTraitImpl(_) => error_code!(E2110),
1377 SemanticDiagnosticKind::InvalidDropTraitImpl(_) => error_code!(E2111),
1378 SemanticDiagnosticKind::InvalidImplItem(_) => error_code!(E2112),
1379 SemanticDiagnosticKind::PassPanicAsNopanic { .. } => error_code!(E2113),
1380 SemanticDiagnosticKind::PassConstAsNonConst { .. } => error_code!(E2114),
1381 SemanticDiagnosticKind::PanicableFromNonPanicable => error_code!(E2115),
1382 SemanticDiagnosticKind::PanicableExternFunction => error_code!(E2116),
1383 SemanticDiagnosticKind::MacroGeneratedCodeParserDiagnostic(_) => error_code!(E2117),
1384 SemanticDiagnosticKind::NameDefinedMultipleTimes(_) => error_code!(E2118),
1385 SemanticDiagnosticKind::NonPrivateUseStar => error_code!(E2119),
1386 SemanticDiagnosticKind::SelfGlobalUse => error_code!(E2120),
1387 SemanticDiagnosticKind::NamedArgumentsAreNotSupported => error_code!(E2121),
1388 SemanticDiagnosticKind::ArgPassedToNegativeImpl => error_code!(E2122),
1389 SemanticDiagnosticKind::UnnamedArgumentFollowsNamed => error_code!(E2123),
1390 SemanticDiagnosticKind::NamedArgumentMismatch { .. } => error_code!(E2124),
1391 SemanticDiagnosticKind::UnsupportedOutsideOfFunction(_) => error_code!(E2125),
1392 SemanticDiagnosticKind::ConstTypeNotVarFree => error_code!(E2126),
1393 SemanticDiagnosticKind::UnsupportedConstant => error_code!(E2127),
1394 SemanticDiagnosticKind::FailedConstantCalculation => error_code!(E2128),
1395 SemanticDiagnosticKind::ConstantCalculationDepthExceeded => error_code!(E2129),
1396 SemanticDiagnosticKind::InnerFailedConstantCalculation(..) => error_code!(E2130),
1397 SemanticDiagnosticKind::DivisionByZero => error_code!(E2131),
1398 SemanticDiagnosticKind::ExternTypeWithImplGenericsNotSupported => error_code!(E2132),
1399 SemanticDiagnosticKind::MissingSemicolon => error_code!(E2133),
1400 SemanticDiagnosticKind::TraitMismatch { .. } => error_code!(E2134),
1401 SemanticDiagnosticKind::DerefNonRef { .. } => error_code!(E2135),
1402 SemanticDiagnosticKind::NoImplementationOfIndexOperator { .. } => error_code!(E2136),
1403 SemanticDiagnosticKind::NoImplementationOfTrait { .. } => error_code!(E2137),
1404 SemanticDiagnosticKind::CallExpressionRequiresFunction { .. } => error_code!(E2138),
1405 SemanticDiagnosticKind::MultipleImplementationOfIndexOperator(_) => error_code!(E2139),
1406 SemanticDiagnosticKind::UnsupportedInlineArguments => error_code!(E2140),
1407 SemanticDiagnosticKind::RedundantInlineAttribute => error_code!(E2141),
1408 SemanticDiagnosticKind::InlineAttrForExternFunctionNotAllowed => error_code!(E2142),
1409 SemanticDiagnosticKind::InlineAlwaysWithImplGenericArgNotAllowed => error_code!(E2143),
1410 SemanticDiagnosticKind::TailExpressionNotAllowedInLoop => error_code!(E2144),
1411 SemanticDiagnosticKind::ContinueOnlyAllowedInsideALoop => error_code!(E2145),
1412 SemanticDiagnosticKind::BreakOnlyAllowedInsideALoop => error_code!(E2146),
1413 SemanticDiagnosticKind::BreakWithValueOnlyAllowedInsideALoop => error_code!(E2147),
1414 SemanticDiagnosticKind::ErrorPropagateNotAllowedInsideALoop => error_code!(E2148),
1415 SemanticDiagnosticKind::ImplicitPrecedenceAttrForExternFunctionNotAllowed => {
1416 error_code!(E2149)
1417 }
1418 SemanticDiagnosticKind::RedundantImplicitPrecedenceAttribute => error_code!(E2150),
1419 SemanticDiagnosticKind::UnsupportedImplicitPrecedenceArguments => error_code!(E2151),
1420 SemanticDiagnosticKind::UnsupportedFeatureAttrArguments => error_code!(E2152),
1421 SemanticDiagnosticKind::UnsupportedAllowAttrArguments => error_code!(E2153),
1422 SemanticDiagnosticKind::UnsupportedPubArgument => error_code!(E2154),
1423 SemanticDiagnosticKind::UnknownStatementAttribute => error_code!(E2155),
1424 SemanticDiagnosticKind::InlineMacroNotFound(_) => error_code!(E2156),
1425 SemanticDiagnosticKind::InlineMacroFailed(_) => error_code!(E2157),
1426 SemanticDiagnosticKind::InlineMacroNoMatchingRule(_) => error_code!(E2158),
1427 SemanticDiagnosticKind::MacroCallToNotAMacro(_) => error_code!(E2159),
1428 SemanticDiagnosticKind::UnknownGenericParam(_) => error_code!(E2160),
1429 SemanticDiagnosticKind::PositionalGenericAfterNamed => error_code!(E2161),
1430 SemanticDiagnosticKind::GenericArgDuplicate(_) => error_code!(E2162),
1431 SemanticDiagnosticKind::TooManyGenericArguments { .. } => error_code!(E2163),
1432 SemanticDiagnosticKind::GenericArgOutOfOrder(_) => error_code!(E2164),
1433 SemanticDiagnosticKind::CouponForExternFunctionNotAllowed => error_code!(E2165),
1434 SemanticDiagnosticKind::CouponArgumentNoModifiers => error_code!(E2166),
1435 SemanticDiagnosticKind::CouponsDisabled => error_code!(E2167),
1436 SemanticDiagnosticKind::ReprPtrsDisabled => error_code!(E2168),
1437 SemanticDiagnosticKind::AssignmentToReprPtrVariable(_) => error_code!(E2169),
1438 SemanticDiagnosticKind::FixedSizeArrayTypeNonSingleType => error_code!(E2170),
1439 SemanticDiagnosticKind::FixedSizeArrayTypeEmptySize => error_code!(E2171),
1440 SemanticDiagnosticKind::FixedSizeArrayNonNumericSize => error_code!(E2172),
1441 SemanticDiagnosticKind::FixedSizeArrayNonSingleValue => error_code!(E2173),
1442 SemanticDiagnosticKind::FixedSizeArraySizeTooBig => error_code!(E2174),
1443 SemanticDiagnosticKind::SelfNotSupportedInContext => error_code!(E2175),
1444 SemanticDiagnosticKind::SelfMustBeFirst => error_code!(E2176),
1445 SemanticDiagnosticKind::DollarNotSupportedInContext => error_code!(E2177),
1446 SemanticDiagnosticKind::UnknownResolverModifier { .. } => error_code!(E2178),
1447 SemanticDiagnosticKind::EmptyPathAfterResolverModifier => error_code!(E2179),
1448 SemanticDiagnosticKind::DerefCycle { .. } => error_code!(E2180),
1449 SemanticDiagnosticKind::CompilerTraitReImplementation { .. } => error_code!(E2181),
1450 SemanticDiagnosticKind::ClosureInGlobalScope => error_code!(E2182),
1451 SemanticDiagnosticKind::MaybeMissingColonColon => error_code!(E2183),
1452 SemanticDiagnosticKind::CallingShadowedFunction { .. } => error_code!(E2184),
1453 SemanticDiagnosticKind::RefClosureArgument => error_code!(E2185),
1454 SemanticDiagnosticKind::RefClosureParam => error_code!(E2186),
1455 SemanticDiagnosticKind::MustBeNextToTypeOrTrait { .. } => error_code!(E2187),
1456 SemanticDiagnosticKind::MutableCapturedVariable => error_code!(E2188),
1457 SemanticDiagnosticKind::NonTraitTypeConstrained { .. } => error_code!(E2189),
1458 SemanticDiagnosticKind::DuplicateTypeConstraint { .. } => error_code!(E2190),
1459 SemanticDiagnosticKind::TypeConstraintsSyntaxNotEnabled => error_code!(E2191),
1460 SemanticDiagnosticKind::PatternMissingArgs(_) => error_code!(E2192),
1461 SemanticDiagnosticKind::UndefinedMacroPlaceholder(_) => error_code!(E2193),
1462 SemanticDiagnosticKind::UserDefinedInlineMacrosDisabled => error_code!(E2194),
1463 SemanticDiagnosticKind::NonNeverLetElseType => error_code!(E2195),
1464 SemanticDiagnosticKind::OnlyTypeOrConstParamsInNegImpl => error_code!(E2196),
1465 SemanticDiagnosticKind::PluginDiagnostic(diag) => {
1466 diag.error_code.unwrap_or(error_code!(E2200))
1467 }
1468 SemanticDiagnosticKind::InternalInferenceError(inference_error) => {
1469 match inference_error {
1470 InferenceError::Reported(_) => error_code!(E2300),
1471 InferenceError::Cycle(_) => error_code!(E2301),
1472 InferenceError::TypeKindMismatch { .. } => error_code!(E2302),
1473 InferenceError::ConstKindMismatch { .. } => error_code!(E2303),
1474 InferenceError::ImplKindMismatch { .. } => error_code!(E2304),
1475 InferenceError::NegativeImplKindMismatch { .. } => error_code!(E2305),
1476 InferenceError::GenericArgMismatch { .. } => error_code!(E2306),
1477 InferenceError::TraitMismatch { .. } => error_code!(E2307),
1478 InferenceError::ImplTypeMismatch { .. } => error_code!(E2308),
1479 InferenceError::GenericFunctionMismatch { .. } => error_code!(E2309),
1480 InferenceError::ConstNotInferred => error_code!(E2310),
1481 InferenceError::NoImplsFound(_) => error_code!(E2311),
1482 InferenceError::NoNegativeImplsFound(_) => error_code!(E2312),
1483 InferenceError::Ambiguity(_) => error_code!(E2313),
1484 InferenceError::TypeNotInferred(_) => error_code!(E2314),
1485 }
1486 }
1487 })
1488 }
1489
1490 fn is_same_kind(&self, other: &Self) -> bool {
1491 other.kind == self.kind
1492 }
1493}
1494
1495#[derive(Clone, Debug, Eq, Hash, PartialEq, salsa::Update)]
1496pub enum SemanticDiagnosticKind<'db> {
1497 ModuleFileNotFound(String),
1498 Unsupported,
1499 UnknownLiteral,
1500 UnknownBinaryOperator,
1501 UnknownTrait,
1502 UnknownImpl,
1503 UnexpectedElement {
1504 expected: Vec<ElementKind>,
1505 actual: ElementKind,
1506 },
1507 UnknownType,
1508 UnknownEnum,
1509 LiteralError(LiteralError<'db>),
1510 NotAVariant,
1511 NotAStruct,
1512 NotAType,
1513 NotATrait,
1514 NotAnImpl,
1515 ImplItemNotInTrait {
1516 impl_def_id: ImplDefId<'db>,
1517 impl_item_name: SmolStrId<'db>,
1518 trait_id: TraitId<'db>,
1519 item_kind: String,
1520 },
1521 ImplicitImplNotInferred {
1522 trait_impl_id: TraitImplId<'db>,
1523 concrete_trait_id: ConcreteTraitId<'db>,
1524 },
1525 GenericsNotSupportedInItem {
1526 scope: String,
1527 item_kind: String,
1528 },
1529 UnexpectedGenericArgs,
1530 UnknownMember,
1531 CannotCreateInstancesOfPhantomTypes,
1532 NonPhantomTypeContainingPhantomType,
1533 MemberSpecifiedMoreThanOnce,
1534 StructBaseStructExpressionNotLast,
1535 StructBaseStructExpressionNoEffect,
1536 ConstCycle,
1537 UseCycle,
1538 TypeAliasCycle,
1539 ImplAliasCycle,
1540 ImplRequirementCycle,
1541 MissingMember(SmolStrId<'db>),
1542 WrongNumberOfParameters {
1543 impl_def_id: ImplDefId<'db>,
1544 impl_function_id: ImplFunctionId<'db>,
1545 trait_id: TraitId<'db>,
1546 expected: usize,
1547 actual: usize,
1548 },
1549 WrongNumberOfArguments {
1550 expected: usize,
1551 actual: usize,
1552 },
1553 WrongParameterType {
1554 impl_def_id: ImplDefId<'db>,
1555 impl_function_id: ImplFunctionId<'db>,
1556 trait_id: TraitId<'db>,
1557 expected_ty: semantic::TypeId<'db>,
1558 actual_ty: semantic::TypeId<'db>,
1559 },
1560 VariantCtorNotImmutable,
1561 TraitParamMutable {
1562 trait_id: TraitId<'db>,
1563 function_id: TraitFunctionId<'db>,
1564 },
1565 ParameterShouldBeReference {
1566 impl_def_id: ImplDefId<'db>,
1567 impl_function_id: ImplFunctionId<'db>,
1568 trait_id: TraitId<'db>,
1569 },
1570 ParameterShouldNotBeReference {
1571 impl_def_id: ImplDefId<'db>,
1572 impl_function_id: ImplFunctionId<'db>,
1573 trait_id: TraitId<'db>,
1574 },
1575 WrongParameterName {
1576 impl_def_id: ImplDefId<'db>,
1577 impl_function_id: ImplFunctionId<'db>,
1578 trait_id: TraitId<'db>,
1579 expected_name: SmolStrId<'db>,
1580 },
1581 WrongGenericParamTraitForImplFunction {
1582 impl_def_id: ImplDefId<'db>,
1583 impl_function_id: ImplFunctionId<'db>,
1584 trait_id: TraitId<'db>,
1585 expected_trait: ConcreteTraitId<'db>,
1586 actual_trait: ConcreteTraitId<'db>,
1587 },
1588 WrongGenericParamKindForImplFunction {
1589 impl_def_id: ImplDefId<'db>,
1590 impl_function_id: ImplFunctionId<'db>,
1591 trait_id: TraitId<'db>,
1592 expected_kind: GenericKind,
1593 actual_kind: GenericKind,
1594 },
1595 WrongType {
1596 expected_ty: semantic::TypeId<'db>,
1597 actual_ty: semantic::TypeId<'db>,
1598 },
1599 InconsistentBinding,
1600 WrongArgumentType {
1601 expected_ty: semantic::TypeId<'db>,
1602 actual_ty: semantic::TypeId<'db>,
1603 },
1604 WrongReturnType {
1605 expected_ty: semantic::TypeId<'db>,
1606 actual_ty: semantic::TypeId<'db>,
1607 },
1608 WrongExprType {
1609 expected_ty: semantic::TypeId<'db>,
1610 actual_ty: semantic::TypeId<'db>,
1611 },
1612 WrongNumberOfGenericParamsForImplFunction {
1613 expected: usize,
1614 actual: usize,
1615 },
1616 WrongReturnTypeForImpl {
1617 impl_def_id: ImplDefId<'db>,
1618 impl_function_id: ImplFunctionId<'db>,
1619 trait_id: TraitId<'db>,
1620 expected_ty: semantic::TypeId<'db>,
1621 actual_ty: semantic::TypeId<'db>,
1622 },
1623 AmbiguousTrait {
1624 trait_function_id0: TraitFunctionId<'db>,
1625 trait_function_id1: TraitFunctionId<'db>,
1626 },
1627 VariableNotFound(SmolStrId<'db>),
1628 MissingVariableInPattern,
1629 VariableDefinedMultipleTimesInPattern(SmolStrId<'db>),
1630 StructMemberRedefinition {
1631 struct_id: StructId<'db>,
1632 member_name: SmolStrId<'db>,
1633 },
1634 EnumVariantRedefinition {
1635 enum_id: EnumId<'db>,
1636 variant_name: SmolStrId<'db>,
1637 },
1638 InfiniteSizeType(semantic::TypeId<'db>),
1639 ArrayOfZeroSizedElements(semantic::TypeId<'db>),
1640 ParamNameRedefinition {
1641 function_title_id: Option<FunctionTitleId<'db>>,
1642 param_name: SmolStrId<'db>,
1643 },
1644 ConditionNotBool(semantic::TypeId<'db>),
1645 IncompatibleArms {
1646 multi_arm_expr_kind: MultiArmExprKind,
1647 pending_ty: semantic::TypeId<'db>,
1648 different_ty: semantic::TypeId<'db>,
1649 },
1650 TypeHasNoMembers {
1651 ty: semantic::TypeId<'db>,
1652 member_name: SmolStrId<'db>,
1653 },
1654 CannotCallMethod {
1655 ty: semantic::TypeId<'db>,
1656 method_name: SmolStrId<'db>,
1657 inference_errors: TraitInferenceErrors<'db>,
1658 relevant_traits: Vec<String>,
1659 },
1660 NoSuchStructMember {
1661 struct_id: StructId<'db>,
1662 member_name: SmolStrId<'db>,
1663 },
1664 NoSuchTypeMember {
1665 ty: semantic::TypeId<'db>,
1666 member_name: SmolStrId<'db>,
1667 },
1668 MemberNotVisible(SmolStrId<'db>),
1669 NoSuchVariant {
1670 enum_id: EnumId<'db>,
1671 variant_name: SmolStrId<'db>,
1672 },
1673 ReturnTypeNotErrorPropagateType,
1674 IncompatibleErrorPropagateType {
1675 return_ty: semantic::TypeId<'db>,
1676 err_ty: semantic::TypeId<'db>,
1677 },
1678 ErrorPropagateOnNonErrorType(semantic::TypeId<'db>),
1679 UnhandledMustUseType(semantic::TypeId<'db>),
1680 UnstableFeature {
1681 feature_name: SmolStrId<'db>,
1682 note: Option<SmolStrId<'db>>,
1683 },
1684 DeprecatedFeature {
1685 feature_name: SmolStrId<'db>,
1686 note: Option<SmolStrId<'db>>,
1687 },
1688 InternalFeature {
1689 feature_name: SmolStrId<'db>,
1690 note: Option<SmolStrId<'db>>,
1691 },
1692 FeatureMarkerDiagnostic(FeatureMarkerDiagnostic),
1693 UnhandledMustUseFunction,
1694 UnusedVariable,
1695 UnusedConstant,
1696 UnusedUse,
1697 MultipleConstantDefinition(SmolStrId<'db>),
1698 MultipleDefinitionforBinding(SmolStrId<'db>),
1699 MultipleGenericItemDefinition(SmolStrId<'db>),
1700 UnsupportedUseItemInStatement,
1701 ConstGenericParamNotSupported,
1702 NegativeImplsNotEnabled,
1703 NegativeImplsOnlyOnImpls,
1704 RefArgNotAVariable,
1705 RefArgNotMutable,
1706 RefArgNotExplicit,
1707 ImmutableArgWithModifiers,
1708 AssignmentToImmutableVar,
1709 InvalidLhsForAssignment,
1710 InvalidMemberExpression,
1711 InvalidPath,
1712 PathNotFound(NotFoundItemType),
1713 AmbiguousPath(Vec<ModuleItemId<'db>>),
1714 UseSelfNonMulti,
1715 UseSelfEmptyPath,
1716 UseStarEmptyPath,
1717 GlobalUsesNotSupportedInEdition(Edition),
1718 TraitInTraitMustBeExplicit,
1719 ImplInImplMustBeExplicit,
1720 TraitItemForbiddenInTheTrait,
1721 TraitItemForbiddenInItsImpl,
1722 ImplItemForbiddenInTheImpl,
1723 SuperUsedInRootModule,
1724 SuperUsedInMacroCallTopLevel,
1725 ItemNotVisible(ModuleItemId<'db>, Vec<ModuleId<'db>>),
1726 UnusedImport(UseId<'db>),
1727 RedundantModifier {
1728 current_modifier: SmolStrId<'db>,
1729 previous_modifier: SmolStrId<'db>,
1730 },
1731 ReferenceLocalVariable,
1732 UnexpectedEnumPattern(semantic::TypeId<'db>),
1733 UnexpectedStructPattern(semantic::TypeId<'db>),
1734 UnexpectedTuplePattern(semantic::TypeId<'db>),
1735 UnexpectedFixedSizeArrayPattern(semantic::TypeId<'db>),
1736 WrongNumberOfTupleElements {
1737 expected: usize,
1738 actual: usize,
1739 },
1740 WrongNumberOfFixedSizeArrayElements {
1741 expected: usize,
1742 actual: usize,
1743 },
1744 WrongEnum {
1745 expected_enum: EnumId<'db>,
1746 actual_enum: EnumId<'db>,
1747 },
1748 InvalidCopyTraitImpl(InferenceError<'db>),
1749 InvalidDropTraitImpl(InferenceError<'db>),
1750 InvalidImplItem(SmolStrId<'db>),
1751 MissingItemsInImpl(Vec<SmolStrId<'db>>),
1752 PassPanicAsNopanic {
1753 impl_function_id: ImplFunctionId<'db>,
1754 trait_id: TraitId<'db>,
1755 },
1756 PassConstAsNonConst {
1757 impl_function_id: ImplFunctionId<'db>,
1758 trait_id: TraitId<'db>,
1759 },
1760 PanicableFromNonPanicable,
1761 PanicableExternFunction,
1762 MacroGeneratedCodeParserDiagnostic(ParserDiagnostic<'db>),
1763 PluginDiagnostic(PluginDiagnostic<'db>),
1764 NameDefinedMultipleTimes(SmolStrId<'db>),
1765 NonPrivateUseStar,
1766 SelfGlobalUse,
1767 NamedArgumentsAreNotSupported,
1768 ArgPassedToNegativeImpl,
1769 UnnamedArgumentFollowsNamed,
1770 NamedArgumentMismatch {
1771 expected: SmolStrId<'db>,
1772 found: SmolStrId<'db>,
1773 },
1774 UnsupportedOutsideOfFunction(UnsupportedOutsideOfFunctionFeatureName),
1775 ConstTypeNotVarFree,
1776 UnsupportedConstant,
1777 FailedConstantCalculation,
1778 ConstantCalculationDepthExceeded,
1779 InnerFailedConstantCalculation(Box<SemanticDiagnostic<'db>>, Vec<DiagnosticNote<'db>>),
1780 DivisionByZero,
1781 ExternTypeWithImplGenericsNotSupported,
1782 MissingSemicolon,
1783 TraitMismatch {
1784 expected_trt: semantic::ConcreteTraitId<'db>,
1785 actual_trt: semantic::ConcreteTraitId<'db>,
1786 },
1787 DerefNonRef {
1788 ty: semantic::TypeId<'db>,
1789 },
1790 InternalInferenceError(InferenceError<'db>),
1791 NoImplementationOfIndexOperator {
1792 ty: semantic::TypeId<'db>,
1793 inference_errors: TraitInferenceErrors<'db>,
1794 },
1795 NoImplementationOfTrait {
1796 ty: semantic::TypeId<'db>,
1797 trait_name: SmolStrId<'db>,
1798 inference_errors: TraitInferenceErrors<'db>,
1799 },
1800 CallExpressionRequiresFunction {
1801 ty: semantic::TypeId<'db>,
1802 inference_errors: TraitInferenceErrors<'db>,
1803 },
1804 MultipleImplementationOfIndexOperator(semantic::TypeId<'db>),
1805
1806 UnsupportedInlineArguments,
1807 RedundantInlineAttribute,
1808 InlineAttrForExternFunctionNotAllowed,
1809 InlineAlwaysWithImplGenericArgNotAllowed,
1810 TailExpressionNotAllowedInLoop,
1811 ContinueOnlyAllowedInsideALoop,
1812 BreakOnlyAllowedInsideALoop,
1813 BreakWithValueOnlyAllowedInsideALoop,
1814 ErrorPropagateNotAllowedInsideALoop,
1815 ImplicitPrecedenceAttrForExternFunctionNotAllowed,
1816 RedundantImplicitPrecedenceAttribute,
1817 UnsupportedImplicitPrecedenceArguments,
1818 UnsupportedFeatureAttrArguments,
1819 UnsupportedAllowAttrArguments,
1820 UnsupportedPubArgument,
1821 UnknownStatementAttribute,
1822 InlineMacroNotFound(SmolStrId<'db>),
1823 InlineMacroFailed(SmolStrId<'db>),
1824 InlineMacroNoMatchingRule(SmolStrId<'db>),
1825 MacroCallToNotAMacro(SmolStrId<'db>),
1826 UnknownGenericParam(SmolStrId<'db>),
1827 PositionalGenericAfterNamed,
1828 GenericArgDuplicate(SmolStrId<'db>),
1829 TooManyGenericArguments {
1830 expected: usize,
1831 actual: usize,
1832 },
1833 GenericArgOutOfOrder(SmolStrId<'db>),
1834 CouponForExternFunctionNotAllowed,
1835 CouponArgumentNoModifiers,
1836 CouponsDisabled,
1838 ReprPtrsDisabled,
1840 AssignmentToReprPtrVariable(Vec<DiagnosticNote<'db>>),
1842 FixedSizeArrayTypeNonSingleType,
1843 FixedSizeArrayTypeEmptySize,
1844 FixedSizeArrayNonNumericSize,
1845 FixedSizeArrayNonSingleValue,
1846 FixedSizeArraySizeTooBig,
1847 SelfNotSupportedInContext,
1848 SelfMustBeFirst,
1849 DollarNotSupportedInContext,
1850 UnknownResolverModifier {
1851 modifier: SmolStrId<'db>,
1852 },
1853 EmptyPathAfterResolverModifier,
1854 DerefCycle {
1855 deref_chain: String,
1856 },
1857 CompilerTraitReImplementation {
1858 trait_id: TraitId<'db>,
1859 },
1860 ClosureInGlobalScope,
1861 MaybeMissingColonColon,
1862 CallingShadowedFunction {
1863 shadowed_function_name: SmolStrId<'db>,
1864 },
1865 RefClosureArgument,
1866 RefClosureParam,
1867 MustBeNextToTypeOrTrait {
1868 trait_id: TraitId<'db>,
1869 },
1870 MutableCapturedVariable,
1871 NonTraitTypeConstrained {
1872 identifier: SmolStrId<'db>,
1873 concrete_trait_id: ConcreteTraitId<'db>,
1874 },
1875 DuplicateTypeConstraint {
1876 concrete_trait_type_id: ConcreteTraitTypeId<'db>,
1877 },
1878 TypeConstraintsSyntaxNotEnabled,
1879 PatternMissingArgs(ast::ExprPath<'db>),
1880 UndefinedMacroPlaceholder(SmolStrId<'db>),
1881 UserDefinedInlineMacrosDisabled,
1882 NonNeverLetElseType,
1883 OnlyTypeOrConstParamsInNegImpl,
1884}
1885
1886#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, salsa::Update)]
1888pub enum MultiArmExprKind {
1889 If,
1890 Match,
1891 Loop,
1892}
1893
1894#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, salsa::Update)]
1896pub enum NotFoundItemType {
1897 Identifier,
1898 Function,
1899 Type,
1900 Trait,
1901 Impl,
1902 Macro,
1903}
1904
1905#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, salsa::Update)]
1906pub enum UnsupportedOutsideOfFunctionFeatureName {
1907 ReturnStatement,
1908 ErrorPropagate,
1909}
1910
1911#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, salsa::Update)]
1912pub enum ElementKind {
1913 Constant,
1914 Variable,
1915 Module,
1916 Function,
1917 Type,
1918 Variant,
1919 Trait,
1920 Impl,
1921 Macro,
1922}
1923impl<'db> From<&ResolvedConcreteItem<'db>> for ElementKind {
1924 fn from(val: &ResolvedConcreteItem<'db>) -> Self {
1925 match val {
1926 ResolvedConcreteItem::Constant(_) => ElementKind::Constant,
1927 ResolvedConcreteItem::Module(_) => ElementKind::Module,
1928 ResolvedConcreteItem::Function(_) => ElementKind::Function,
1929 ResolvedConcreteItem::Type(_) => ElementKind::Type,
1930 ResolvedConcreteItem::Variant(_) => ElementKind::Variant,
1931 ResolvedConcreteItem::Trait(_) | ResolvedConcreteItem::SelfTrait(_) => {
1932 ElementKind::Trait
1933 }
1934 ResolvedConcreteItem::Impl(_) => ElementKind::Impl,
1935 ResolvedConcreteItem::Macro(_) => ElementKind::Macro,
1936 }
1937 }
1938}
1939impl<'db> From<&ResolvedGenericItem<'db>> for ElementKind {
1940 fn from(val: &ResolvedGenericItem<'db>) -> Self {
1941 match val {
1942 ResolvedGenericItem::GenericConstant(_)
1943 | ResolvedGenericItem::TraitItem(TraitItemId::Constant(_)) => ElementKind::Constant,
1944 ResolvedGenericItem::Module(_) => ElementKind::Module,
1945 ResolvedGenericItem::GenericFunction(_)
1946 | ResolvedGenericItem::TraitItem(TraitItemId::Function(_)) => ElementKind::Function,
1947 ResolvedGenericItem::GenericType(_)
1948 | ResolvedGenericItem::GenericTypeAlias(_)
1949 | ResolvedGenericItem::TraitItem(TraitItemId::Type(_)) => ElementKind::Type,
1950 ResolvedGenericItem::Variant(_) => ElementKind::Variant,
1951 ResolvedGenericItem::Trait(_) => ElementKind::Trait,
1952 ResolvedGenericItem::Impl(_)
1953 | ResolvedGenericItem::GenericImplAlias(_)
1954 | ResolvedGenericItem::TraitItem(TraitItemId::Impl(_)) => ElementKind::Impl,
1955 ResolvedGenericItem::Variable(_) => ElementKind::Variable,
1956 ResolvedGenericItem::Macro(_) => ElementKind::Macro,
1957 }
1958 }
1959}
1960impl Display for ElementKind {
1961 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1962 let res = match self {
1963 ElementKind::Constant => "constant",
1964 ElementKind::Variable => "variable",
1965 ElementKind::Module => "module",
1966 ElementKind::Function => "function",
1967 ElementKind::Type => "type",
1968 ElementKind::Variant => "variant",
1969 ElementKind::Trait => "trait",
1970 ElementKind::Impl => "impl",
1971 ElementKind::Macro => "macro",
1972 };
1973 write!(f, "{res}")
1974 }
1975}
1976
1977#[derive(Clone, Debug, Eq, Hash, PartialEq, salsa::Update)]
1979pub struct TraitInferenceErrors<'db> {
1980 pub traits_and_errors: Vec<(TraitFunctionId<'db>, InferenceError<'db>)>,
1981}
1982impl<'db> TraitInferenceErrors<'db> {
1983 pub fn is_empty(&self) -> bool {
1985 self.traits_and_errors.is_empty()
1986 }
1987 fn format(&self, db: &dyn Database) -> String {
1989 self.traits_and_errors
1990 .iter()
1991 .map(|(trait_function_id, inference_error)| {
1992 format!(
1993 "Candidate `{}` inference failed with: {}",
1994 trait_function_id.full_path(db),
1995 inference_error.format(db)
1996 )
1997 })
1998 .join("\n")
1999 }
2000}