Skip to main content

ide_diagnostics/
lib.rs

1//! Diagnostics rendering and fixits.
2//!
3//! Most of the diagnostics originate from the dark depth of the compiler, and
4//! are originally expressed in term of IR. When we emit the diagnostic, we are
5//! usually not in the position to decide how to best "render" it in terms of
6//! user-authored source code. We are especially not in the position to offer
7//! fixits, as the compiler completely lacks the infrastructure to edit the
8//! source code.
9//!
10//! Instead, we "bubble up" raw, structured diagnostics until the `hir` crate,
11//! where we "cook" them so that each diagnostic is formulated in terms of `hir`
12//! types. Well, at least that's the aspiration, the "cooking" is somewhat
13//! ad-hoc at the moment. Anyways, we get a bunch of ide-friendly diagnostic
14//! structs from hir, and we want to render them to unified serializable
15//! representation (span, level, message) here. If we can, we also provide
16//! fixits. By the way, that's why we want to keep diagnostics structured
17//! internally -- so that we have all the info to make fixes.
18//!
19//! We have one "handler" module per diagnostic code. Such a module contains
20//! rendering, optional fixes and tests. It's OK if some low-level compiler
21//! functionality ends up being tested via a diagnostic.
22//!
23//! There are also a couple of ad-hoc diagnostics implemented directly here, we
24//! don't yet have a great pattern for how to do them properly.
25
26#![cfg_attr(feature = "in-rust-tree", feature(rustc_private))]
27
28#[cfg(feature = "in-rust-tree")]
29extern crate rustc_driver as _;
30
31mod handlers {
32    pub(crate) mod array_pattern_without_fixed_length;
33    pub(crate) mod await_outside_of_async;
34    pub(crate) mod bad_rtn;
35    pub(crate) mod break_outside_of_loop;
36    pub(crate) mod cannot_be_dereferenced;
37    pub(crate) mod cannot_implicitly_deref_trait_object;
38    pub(crate) mod cannot_index_into;
39    pub(crate) mod duplicate_field;
40    pub(crate) mod elided_lifetimes_in_path;
41    pub(crate) mod expected_array_or_slice_pat;
42    pub(crate) mod expected_function;
43    pub(crate) mod explicit_drop_method_use;
44    pub(crate) mod fru_in_destructuring_assignment;
45    pub(crate) mod functional_record_update_on_non_struct;
46    pub(crate) mod generic_args_prohibited;
47    pub(crate) mod generic_default_refers_to_self;
48    pub(crate) mod inactive_code;
49    pub(crate) mod incoherent_impl;
50    pub(crate) mod incorrect_case;
51    pub(crate) mod incorrect_generics_len;
52    pub(crate) mod incorrect_generics_order;
53    pub(crate) mod infer_vars_not_allowed;
54    pub(crate) mod invalid_cast;
55    pub(crate) mod invalid_derive_target;
56    pub(crate) mod invalid_lhs_of_assignment;
57    pub(crate) mod invalid_range_pat_type;
58    pub(crate) mod macro_error;
59    pub(crate) mod malformed_derive;
60    pub(crate) mod method_call_illegal_sized_bound;
61    pub(crate) mod mismatched_arg_count;
62    pub(crate) mod mismatched_array_pat_len;
63    pub(crate) mod missing_fields;
64    pub(crate) mod missing_lifetime;
65    pub(crate) mod missing_match_arms;
66    pub(crate) mod missing_unsafe;
67    pub(crate) mod moved_out_of_ref;
68    pub(crate) mod mut_ref_in_imm_ref_pat;
69    pub(crate) mod mutability_errors;
70    pub(crate) mod mutable_ref;
71    pub(crate) mod no_such_field;
72    pub(crate) mod non_exhaustive_let;
73    pub(crate) mod non_exhaustive_record_expr;
74    pub(crate) mod non_exhaustive_record_pat;
75    pub(crate) mod parenthesized_generic_args_without_fn_trait;
76    pub(crate) mod pattern_arg_in_extern_fn;
77    pub(crate) mod private_assoc_item;
78    pub(crate) mod private_field;
79    pub(crate) mod remove_trailing_return;
80    pub(crate) mod remove_unnecessary_else;
81    pub(crate) mod replace_filter_map_next_with_find_map;
82    pub(crate) mod return_outside_function;
83    pub(crate) mod trait_impl_incorrect_safety;
84    pub(crate) mod trait_impl_missing_assoc_item;
85    pub(crate) mod trait_impl_orphan;
86    pub(crate) mod trait_impl_redundant_assoc_item;
87    pub(crate) mod type_mismatch;
88    pub(crate) mod type_must_be_known;
89    pub(crate) mod typed_hole;
90    pub(crate) mod undeclared_label;
91    pub(crate) mod unimplemented_builtin_macro;
92    pub(crate) mod unimplemented_trait;
93    pub(crate) mod union_expr_must_have_exactly_one_field;
94    pub(crate) mod union_pat_has_rest;
95    pub(crate) mod union_pat_must_have_exactly_one_field;
96    pub(crate) mod unreachable_label;
97    pub(crate) mod unresolved_assoc_item;
98    pub(crate) mod unresolved_extern_crate;
99    pub(crate) mod unresolved_field;
100    pub(crate) mod unresolved_ident;
101    pub(crate) mod unresolved_import;
102    pub(crate) mod unresolved_macro_call;
103    pub(crate) mod unresolved_method;
104    pub(crate) mod unresolved_module;
105    pub(crate) mod unused_must_use;
106    pub(crate) mod unused_variables;
107    pub(crate) mod yield_outside_coroutine;
108
109    // The handlers below are unusual, the implement the diagnostics as well.
110    pub(crate) mod field_shorthand;
111    pub(crate) mod json_is_not_rust;
112    pub(crate) mod unlinked_file;
113    pub(crate) mod useless_braces;
114}
115
116#[cfg(test)]
117mod tests;
118
119use std::sync::LazyLock;
120
121use hir::{Crate, DisplayTarget, InFile, MacroCallIdExt, Semantics, diagnostics::AnyDiagnostic};
122use ide_db::{
123    FileId, FileRange, FxHashMap, FxHashSet, RootDatabase, Severity, SnippetCap,
124    assists::{Assist, AssistId, AssistResolveStrategy, ExprFillDefaultMode},
125    base_db::{ReleaseChannel, all_crates, toolchain_channel},
126    generated::lints::{CLIPPY_LINT_GROUPS, DEFAULT_LINT_GROUPS, DEFAULT_LINTS, Lint, LintGroup},
127    imports::insert_use::InsertUseConfig,
128    label::Label,
129    rename::RenameConfig,
130    source_change::SourceChange,
131};
132use syntax::{
133    AstPtr, Edition, SmolStr, SyntaxNode, SyntaxNodePtr, TextRange,
134    ast::{self, AstNode},
135};
136
137#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
138pub enum DiagnosticCode {
139    RustcHardError(&'static str),
140    SyntaxError,
141    RustcLint(&'static str),
142    Clippy(&'static str),
143    Ra(&'static str, Severity),
144}
145
146impl DiagnosticCode {
147    pub fn url(&self) -> String {
148        match self {
149            DiagnosticCode::RustcHardError(e) => {
150                format!("https://doc.rust-lang.org/stable/error_codes/{e}.html")
151            }
152            DiagnosticCode::SyntaxError => {
153                String::from("https://doc.rust-lang.org/stable/reference/")
154            }
155            DiagnosticCode::RustcLint(e) => {
156                format!("https://doc.rust-lang.org/rustc/?search={e}")
157            }
158            DiagnosticCode::Clippy(e) => {
159                format!("https://rust-lang.github.io/rust-clippy/master/#/{e}")
160            }
161            DiagnosticCode::Ra(e, _) => {
162                format!("https://rust-analyzer.github.io/book/diagnostics.html#{e}")
163            }
164        }
165    }
166
167    pub fn as_str(&self) -> &'static str {
168        match self {
169            DiagnosticCode::RustcHardError(r)
170            | DiagnosticCode::RustcLint(r)
171            | DiagnosticCode::Clippy(r)
172            | DiagnosticCode::Ra(r, _) => r,
173            DiagnosticCode::SyntaxError => "syntax-error",
174        }
175    }
176}
177
178#[derive(Debug)]
179pub struct Diagnostic {
180    pub code: DiagnosticCode,
181    pub message: String,
182    pub range: FileRange,
183    pub severity: Severity,
184    pub unused: bool,
185    pub experimental: bool,
186    pub fixes: Option<Vec<Assist>>,
187    // The node that will be affected by `#[allow]` and similar attributes.
188    pub main_node: Option<InFile<SyntaxNodePtr>>,
189}
190
191impl Diagnostic {
192    fn new(
193        code: DiagnosticCode,
194        message: impl Into<String>,
195        range: impl Into<FileRange>,
196    ) -> Diagnostic {
197        let message = message.into();
198        Diagnostic {
199            code,
200            message,
201            range: range.into(),
202            severity: match code {
203                DiagnosticCode::RustcHardError(_) | DiagnosticCode::SyntaxError => Severity::Error,
204                // FIXME: Rustc lints are not always warning, but the ones that are currently implemented are all warnings.
205                DiagnosticCode::RustcLint(_) => Severity::Warning,
206                // FIXME: We can make this configurable, and if the user uses `cargo clippy` on flycheck, we can
207                // make it normal warning.
208                DiagnosticCode::Clippy(_) => Severity::WeakWarning,
209                DiagnosticCode::Ra(_, s) => s,
210            },
211            unused: false,
212            experimental: true,
213            fixes: None,
214            main_node: None,
215        }
216    }
217
218    fn new_with_syntax_node_ptr(
219        ctx: &DiagnosticsContext<'_, '_>,
220        code: DiagnosticCode,
221        message: impl Into<String>,
222        node: InFile<SyntaxNodePtr>,
223    ) -> Diagnostic {
224        Diagnostic::new(code, message, ctx.sema.diagnostics_display_range(node))
225            .with_main_node(node)
226    }
227
228    fn stable(mut self) -> Diagnostic {
229        self.experimental = false;
230        self
231    }
232
233    fn with_main_node(mut self, main_node: InFile<SyntaxNodePtr>) -> Diagnostic {
234        self.main_node = Some(main_node);
235        self
236    }
237
238    fn with_fixes(mut self, fixes: Option<Vec<Assist>>) -> Diagnostic {
239        self.fixes = fixes;
240        self
241    }
242
243    fn with_unused(mut self, unused: bool) -> Diagnostic {
244        self.unused = unused;
245        self
246    }
247
248    fn main_node(&self, sema: &Semantics<'_, RootDatabase>) -> Option<InFile<SyntaxNode>> {
249        self.main_node.map(|ptr| ptr.with_value(sema.to_node_syntax(ptr))).or_else(|| {
250            let token = sema
251                .parse_guess_edition(self.range.file_id)
252                .syntax()
253                .token_at_offset(self.range.range.start())
254                .right_biased()?;
255            sema.descend_into_macros(token).into_iter().find_map(|token| {
256                let node = sema.ancestors_with_macros(token.parent().unwrap()).find(|node| {
257                    let original_range = sema.original_range(node);
258                    original_range.file_id.file_id(sema.db) == self.range.file_id
259                        && original_range.range.contains_range(self.range.range)
260                })?;
261                let file = sema.hir_file_for(&node);
262                Some(InFile::new(file, node))
263            })
264        })
265    }
266}
267
268#[derive(Debug, Clone)]
269pub struct DiagnosticsConfig {
270    /// Whether native diagnostics are enabled.
271    pub enabled: bool,
272    pub proc_macros_enabled: bool,
273    pub proc_attr_macros_enabled: bool,
274    pub disable_experimental: bool,
275    pub disabled: FxHashSet<String>,
276    pub expr_fill_default: ExprFillDefaultMode,
277    pub style_lints: bool,
278    // FIXME: We may want to include a whole `AssistConfig` here
279    pub snippet_cap: Option<SnippetCap>,
280    pub insert_use: InsertUseConfig,
281    pub prefer_no_std: bool,
282    pub prefer_prelude: bool,
283    pub prefer_absolute: bool,
284    pub term_search_fuel: u64,
285    pub term_search_borrowck: bool,
286    pub show_rename_conflicts: bool,
287}
288
289impl DiagnosticsConfig {
290    pub fn test_sample() -> Self {
291        use hir::PrefixKind;
292        use ide_db::imports::insert_use::ImportGranularity;
293
294        Self {
295            enabled: true,
296            proc_macros_enabled: Default::default(),
297            proc_attr_macros_enabled: Default::default(),
298            disable_experimental: Default::default(),
299            disabled: Default::default(),
300            expr_fill_default: Default::default(),
301            style_lints: true,
302            snippet_cap: SnippetCap::new(true),
303            insert_use: InsertUseConfig {
304                granularity: ImportGranularity::Item,
305                enforce_granularity: false,
306                prefix_kind: PrefixKind::Plain,
307                group: false,
308                skip_glob_imports: false,
309            },
310            prefer_no_std: false,
311            prefer_prelude: true,
312            prefer_absolute: false,
313            term_search_fuel: 400,
314            term_search_borrowck: true,
315            show_rename_conflicts: true,
316        }
317    }
318
319    pub fn rename_config(&self) -> RenameConfig {
320        RenameConfig { show_conflicts: self.show_rename_conflicts }
321    }
322}
323
324struct DiagnosticsContext<'a, 'db> {
325    config: &'a DiagnosticsConfig,
326    sema: Semantics<'db, RootDatabase>,
327    resolve: &'a AssistResolveStrategy,
328    edition: Edition,
329    display_target: DisplayTarget,
330    is_nightly: bool,
331}
332
333impl<'db> DiagnosticsContext<'_, 'db> {
334    fn db(&self) -> &'db RootDatabase {
335        self.sema.db
336    }
337}
338
339/// Request parser level diagnostics for the given [`FileId`].
340pub fn syntax_diagnostics(
341    db: &RootDatabase,
342    config: &DiagnosticsConfig,
343    file_id: FileId,
344) -> Vec<Diagnostic> {
345    let _p = tracing::info_span!("syntax_diagnostics").entered();
346
347    if config.disabled.contains("syntax-error") {
348        return Vec::new();
349    }
350
351    let sema = Semantics::new(db);
352    let editioned_file_id = sema.attach_first_edition(file_id);
353
354    let (file_id, _) = editioned_file_id.unpack(db);
355
356    // [#3434] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
357    editioned_file_id
358        .parse_errors(db)
359        .into_iter()
360        .flatten()
361        .take(128)
362        .map(|err| {
363            Diagnostic::new(
364                DiagnosticCode::SyntaxError,
365                format!("Syntax Error: {err}"),
366                FileRange { file_id, range: err.range() },
367            )
368        })
369        .collect()
370}
371
372/// Request semantic diagnostics for the given [`FileId`]. The produced diagnostics may point to other files
373/// due to macros.
374pub fn semantic_diagnostics(
375    db: &RootDatabase,
376    config: &DiagnosticsConfig,
377    resolve: &AssistResolveStrategy,
378    file_id: FileId,
379) -> Vec<Diagnostic> {
380    let _p = tracing::info_span!("semantic_diagnostics").entered();
381    let sema = Semantics::new(db);
382    let editioned_file_id = sema.attach_first_edition(file_id);
383
384    let (file_id, edition) = editioned_file_id.unpack(db);
385    let mut res = Vec::new();
386
387    let parse = sema.parse(editioned_file_id);
388
389    // FIXME: This iterates the entire file which is a rather expensive operation.
390    // We should implement these differently in some form?
391    // Salsa caching + incremental re-parse would be better here
392    for node in parse.syntax().descendants() {
393        handlers::useless_braces::useless_braces(db, &mut res, editioned_file_id, &node);
394        handlers::field_shorthand::field_shorthand(db, &mut res, editioned_file_id, &node);
395        handlers::json_is_not_rust::json_in_items(
396            &sema,
397            &mut res,
398            editioned_file_id,
399            &node,
400            config,
401            edition,
402        );
403    }
404
405    let module = sema.file_to_module_def(file_id);
406
407    let is_nightly = matches!(
408        module.and_then(|m| toolchain_channel(db, m.krate(db).into())),
409        Some(ReleaseChannel::Nightly) | None
410    );
411
412    let krate = match module {
413        Some(module) => module.krate(db),
414        None => {
415            match all_crates(db).last() {
416                Some(last) => (*last).into(),
417                // short-circuit, return an empty vec of diagnostics
418                None => return vec![],
419            }
420        }
421    };
422    let display_target = krate.to_display_target(db);
423    let ctx = DiagnosticsContext { config, sema, resolve, edition, is_nightly, display_target };
424
425    let mut diags = Vec::new();
426    match module {
427        // A bunch of parse errors in a file indicate some bigger structural parse changes in the
428        // file, so we skip semantic diagnostics so we can show these faster.
429        Some(m) => {
430            if editioned_file_id.parse_errors(db).is_none_or(|es| es.len() < 16) {
431                m.diagnostics(db, &mut diags, config.style_lints);
432            }
433        }
434        None => {
435            handlers::unlinked_file::unlinked_file(&ctx, &mut res, editioned_file_id.file_id(db))
436        }
437    }
438
439    for diag in diags {
440        let d = match diag {
441            AnyDiagnostic::AwaitOutsideOfAsync(d) => handlers::await_outside_of_async::await_outside_of_async(&ctx, &d),
442            AnyDiagnostic::CannotBeDereferenced(d) => handlers::cannot_be_dereferenced::cannot_be_dereferenced(&ctx, &d),
443            AnyDiagnostic::CannotImplicitlyDerefTraitObject(d) => handlers::cannot_implicitly_deref_trait_object::cannot_implicitly_deref_trait_object(&ctx, &d),
444            AnyDiagnostic::CannotIndexInto(d) => handlers::cannot_index_into::cannot_index_into(&ctx, &d),
445            AnyDiagnostic::CastToUnsized(d) => handlers::invalid_cast::cast_to_unsized(&ctx, &d),
446            AnyDiagnostic::InferVarsNotAllowed(d) => handlers::infer_vars_not_allowed::infer_vars_not_allowed(&ctx, &d),
447            AnyDiagnostic::ArrayPatternWithoutFixedLength(d) => {
448                handlers::array_pattern_without_fixed_length::array_pattern_without_fixed_length(
449                    &ctx, &d,
450                )
451            }
452            AnyDiagnostic::ExpectedArrayOrSlicePat(d) => handlers::expected_array_or_slice_pat::expected_array_or_slice_pat(&ctx, &d),
453            AnyDiagnostic::ExpectedFunction(d) => handlers::expected_function::expected_function(&ctx, &d),
454            AnyDiagnostic::FunctionalRecordUpdateOnNonStruct(d) => handlers::functional_record_update_on_non_struct::functional_record_update_on_non_struct(&ctx, &d),
455            AnyDiagnostic::InactiveCode(d) => match handlers::inactive_code::inactive_code(&ctx, &d) {
456                Some(it) => it,
457                None => continue,
458            }
459            AnyDiagnostic::IncoherentImpl(d) => handlers::incoherent_impl::incoherent_impl(&ctx, &d),
460            AnyDiagnostic::IncorrectCase(d) => handlers::incorrect_case::incorrect_case(&ctx, &d),
461            AnyDiagnostic::InvalidCast(d) => handlers::invalid_cast::invalid_cast(&ctx, &d),
462            AnyDiagnostic::InvalidDeriveTarget(d) => handlers::invalid_derive_target::invalid_derive_target(&ctx, &d),
463            AnyDiagnostic::MacroDefError(d) => handlers::macro_error::macro_def_error(&ctx, &d),
464            AnyDiagnostic::MacroError(d) => handlers::macro_error::macro_error(&ctx, &d),
465            AnyDiagnostic::MacroExpansionParseError(d) => {
466                // FIXME: Point to the correct error span here, not just the macro-call name
467                res.extend(d.errors.iter().take(16).map(|err| {
468                        Diagnostic::new(
469                            DiagnosticCode::SyntaxError,
470                            format!("Syntax Error in Expansion: {err}"),
471                            ctx.sema.diagnostics_display_range_for_range(d.range),
472                        )
473                }));
474                continue;
475            },
476            AnyDiagnostic::MalformedDerive(d) => handlers::malformed_derive::malformed_derive(&ctx, &d),
477            AnyDiagnostic::MethodCallIllegalSizedBound(d) => handlers::method_call_illegal_sized_bound::method_call_illegal_sized_bound(&ctx, &d),
478            AnyDiagnostic::MismatchedArgCount(d) => handlers::mismatched_arg_count::mismatched_arg_count(&ctx, &d),
479            AnyDiagnostic::MismatchedArrayPatLen(d) => handlers::mismatched_array_pat_len::mismatched_array_pat_len(&ctx, &d),
480            AnyDiagnostic::MissingFields(d) => handlers::missing_fields::missing_fields(&ctx, &d),
481            AnyDiagnostic::MissingMatchArms(d) => handlers::missing_match_arms::missing_match_arms(&ctx, &d),
482            AnyDiagnostic::MissingUnsafe(d) => handlers::missing_unsafe::missing_unsafe(&ctx, &d),
483            AnyDiagnostic::MovedOutOfRef(d) => handlers::moved_out_of_ref::moved_out_of_ref(&ctx, &d),
484            AnyDiagnostic::MutRefInImmRefPat(d) => handlers::mut_ref_in_imm_ref_pat::mut_ref_in_imm_ref_pat(&ctx, &d),
485            AnyDiagnostic::MutableRefBinding(d) => handlers::mutable_ref::mutable_ref_binding(&ctx, &d),
486            AnyDiagnostic::NeedMut(d) => match handlers::mutability_errors::need_mut(&ctx, &d) {
487                Some(it) => it,
488                None => continue,
489            },
490            AnyDiagnostic::NonExhaustiveLet(d) => handlers::non_exhaustive_let::non_exhaustive_let(&ctx, &d),
491            AnyDiagnostic::NonExhaustiveRecordExpr(d) => {
492                handlers::non_exhaustive_record_expr::non_exhaustive_record_expr(&ctx, &d)
493            }
494            AnyDiagnostic::NonExhaustiveRecordPat(d) => {
495                handlers::non_exhaustive_record_pat::non_exhaustive_record_pat(&ctx, &d)
496            }
497            AnyDiagnostic::NoSuchField(d) => handlers::no_such_field::no_such_field(&ctx, &d),
498            AnyDiagnostic::DuplicateField(d) => handlers::duplicate_field::duplicate_field(&ctx, &d),
499            AnyDiagnostic::PrivateAssocItem(d) => handlers::private_assoc_item::private_assoc_item(&ctx, &d),
500            AnyDiagnostic::PrivateField(d) => handlers::private_field::private_field(&ctx, &d),
501            AnyDiagnostic::ReplaceFilterMapNextWithFindMap(d) => handlers::replace_filter_map_next_with_find_map::replace_filter_map_next_with_find_map(&ctx, &d),
502            AnyDiagnostic::TraitImplIncorrectSafety(d) => handlers::trait_impl_incorrect_safety::trait_impl_incorrect_safety(&ctx, &d),
503            AnyDiagnostic::TraitImplMissingAssocItems(d) => handlers::trait_impl_missing_assoc_item::trait_impl_missing_assoc_item(&ctx, &d),
504            AnyDiagnostic::TraitImplRedundantAssocItems(d) => handlers::trait_impl_redundant_assoc_item::trait_impl_redundant_assoc_item(&ctx, &d),
505            AnyDiagnostic::TraitImplOrphan(d) => handlers::trait_impl_orphan::trait_impl_orphan(&ctx, &d),
506            AnyDiagnostic::TypedHole(d) => handlers::typed_hole::typed_hole(&ctx, &d),
507            AnyDiagnostic::TypeMismatch(d) => match handlers::type_mismatch::type_mismatch(&ctx, &d) {
508                Some(diag) => diag,
509                None => continue,
510            },
511            AnyDiagnostic::UndeclaredLabel(d) => handlers::undeclared_label::undeclared_label(&ctx, &d),
512            AnyDiagnostic::UnimplementedBuiltinMacro(d) => handlers::unimplemented_builtin_macro::unimplemented_builtin_macro(&ctx, &d),
513            AnyDiagnostic::UnreachableLabel(d) => handlers::unreachable_label::unreachable_label(&ctx, &d),
514            AnyDiagnostic::UnresolvedAssocItem(d) => handlers::unresolved_assoc_item::unresolved_assoc_item(&ctx, &d),
515            AnyDiagnostic::UnresolvedExternCrate(d) => handlers::unresolved_extern_crate::unresolved_extern_crate(&ctx, &d),
516            AnyDiagnostic::UnresolvedField(d) => handlers::unresolved_field::unresolved_field(&ctx, &d),
517            AnyDiagnostic::UnresolvedIdent(d) => handlers::unresolved_ident::unresolved_ident(&ctx, &d),
518            AnyDiagnostic::UnresolvedImport(d) => handlers::unresolved_import::unresolved_import(&ctx, &d),
519            AnyDiagnostic::UnresolvedMacroCall(d) => handlers::unresolved_macro_call::unresolved_macro_call(&ctx, &d),
520            AnyDiagnostic::UnresolvedMethodCall(d) => handlers::unresolved_method::unresolved_method(&ctx, &d),
521            AnyDiagnostic::UnresolvedModule(d) => handlers::unresolved_module::unresolved_module(&ctx, &d),
522            AnyDiagnostic::UnusedMustUse(d) => handlers::unused_must_use::unused_must_use(&ctx, &d),
523            AnyDiagnostic::UnusedMut(d) => match handlers::mutability_errors::unused_mut(&ctx, &d) {
524                Some(it) => it,
525                None => continue,
526            },
527            AnyDiagnostic::UnusedVariable(d) => match handlers::unused_variables::unused_variables(&ctx, &d) {
528                Some(it) => it,
529                None => continue,
530            },
531            AnyDiagnostic::BreakOutsideOfLoop(d) => handlers::break_outside_of_loop::break_outside_of_loop(&ctx, &d),
532            AnyDiagnostic::MismatchedTupleStructPatArgCount(d) => handlers::mismatched_arg_count::mismatched_tuple_struct_pat_arg_count(&ctx, &d),
533            AnyDiagnostic::RemoveTrailingReturn(d) => match handlers::remove_trailing_return::remove_trailing_return(&ctx, &d) {
534                Some(it) => it,
535                None => continue,
536            },
537            AnyDiagnostic::RemoveUnnecessaryElse(d) => match handlers::remove_unnecessary_else::remove_unnecessary_else(&ctx, &d) {
538                Some(it) => it,
539                None => continue,
540            },
541            AnyDiagnostic::GenericArgsProhibited(d) => handlers::generic_args_prohibited::generic_args_prohibited(&ctx, &d),
542            AnyDiagnostic::ParenthesizedGenericArgsWithoutFnTrait(d) => handlers::parenthesized_generic_args_without_fn_trait::parenthesized_generic_args_without_fn_trait(&ctx, &d),
543            AnyDiagnostic::BadRtn(d) => handlers::bad_rtn::bad_rtn(&ctx, &d),
544            AnyDiagnostic::IncorrectGenericsLen(d) => handlers::incorrect_generics_len::incorrect_generics_len(&ctx, &d),
545            AnyDiagnostic::IncorrectGenericsOrder(d) => handlers::incorrect_generics_order::incorrect_generics_order(&ctx, &d),
546            AnyDiagnostic::MissingLifetime(d) => handlers::missing_lifetime::missing_lifetime(&ctx, &d),
547            AnyDiagnostic::ElidedLifetimesInPath(d) => handlers::elided_lifetimes_in_path::elided_lifetimes_in_path(&ctx, &d),
548            AnyDiagnostic::GenericDefaultRefersToSelf(d) => handlers::generic_default_refers_to_self::generic_default_refers_to_self(&ctx, &d),
549            AnyDiagnostic::InvalidLhsOfAssignment(d) => handlers::invalid_lhs_of_assignment::invalid_lhs_of_assignment(&ctx, &d),
550            AnyDiagnostic::InvalidRangePatType(d) => handlers::invalid_range_pat_type::invalid_range_pat_type(&ctx, &d),
551            AnyDiagnostic::TypeMustBeKnown(d) => handlers::type_must_be_known::type_must_be_known(&ctx, &d),
552            AnyDiagnostic::PatternArgInExternFn(d) => handlers::pattern_arg_in_extern_fn::pattern_arg_in_extern_fn(&ctx, &d),
553            AnyDiagnostic::UnionExprMustHaveExactlyOneField(d) => handlers::union_expr_must_have_exactly_one_field::union_expr_must_have_exactly_one_field(&ctx, &d),
554            AnyDiagnostic::UnionPatMustHaveExactlyOneField(d) => {
555                handlers::union_pat_must_have_exactly_one_field::union_pat_must_have_exactly_one_field(&ctx, &d)
556            }
557            AnyDiagnostic::UnionPatHasRest(d) => {
558                handlers::union_pat_has_rest::union_pat_has_rest(&ctx, &d)
559            }
560            AnyDiagnostic::UnimplementedTrait(d) => handlers::unimplemented_trait::unimplemented_trait(&ctx, &d),
561            AnyDiagnostic::FruInDestructuringAssignment(d) => handlers::fru_in_destructuring_assignment::fru_in_destructuring_assignment(&ctx, &d),
562            AnyDiagnostic::ExplicitDropMethodUse(d) => handlers::explicit_drop_method_use::explicit_drop_method_use(&ctx, &d),
563            AnyDiagnostic::YieldOutsideCoroutine(d) => handlers::yield_outside_coroutine::yield_outside_coroutine(&ctx, &d),
564            AnyDiagnostic::ReturnOutsideFunction(d) => handlers::return_outside_function::return_outside_function(&ctx, &d),
565        };
566        res.push(d)
567    }
568
569    res.retain(|d| {
570        !(ctx.config.disabled.contains(d.code.as_str())
571            || ctx.config.disable_experimental && d.experimental)
572    });
573
574    let mut lints = res
575        .iter_mut()
576        .filter(|it| matches!(it.code, DiagnosticCode::Clippy(_) | DiagnosticCode::RustcLint(_)))
577        .filter_map(|it| Some((it.main_node(&ctx.sema)?, it)))
578        .collect::<Vec<_>>();
579
580    // The edition isn't accurate (each diagnostics may have its own edition due to macros),
581    // but it's okay as it's only being used for error recovery.
582    handle_lints(&ctx.sema, file_id, krate, &mut lints, editioned_file_id.edition(db));
583
584    res.retain(|d| d.severity != Severity::Allow);
585
586    res.retain_mut(|diag| {
587        if let Some(node) = diag
588            .main_node
589            .map(|ptr| ptr.map(|node| node.to_node(&ctx.sema.parse_or_expand(ptr.file_id))))
590        {
591            handle_diag_from_macros(&ctx.sema, diag, &node)
592        } else {
593            true
594        }
595    });
596
597    res
598}
599
600/// Request both syntax and semantic diagnostics for the given [`FileId`].
601pub fn full_diagnostics(
602    db: &RootDatabase,
603    config: &DiagnosticsConfig,
604    resolve: &AssistResolveStrategy,
605    file_id: FileId,
606) -> Vec<Diagnostic> {
607    let mut res = syntax_diagnostics(db, config, file_id);
608    let sema = semantic_diagnostics(db, config, resolve, file_id);
609    res.extend(sema);
610    res
611}
612
613/// Returns whether to keep this diagnostic (or remove it).
614fn handle_diag_from_macros(
615    sema: &Semantics<'_, RootDatabase>,
616    diag: &mut Diagnostic,
617    node: &InFile<SyntaxNode>,
618) -> bool {
619    let Some(macro_file) = node.file_id.macro_file() else { return true };
620    let span_map = macro_file.expansion_span_map(sema.db);
621    let mut spans = span_map.spans_for_range(node.text_range());
622    if spans.any(|span| {
623        span.ctx.outer_expn(sema.db).is_some_and(|expansion| {
624            let macro_call = expansion.loc(sema.db);
625            // We don't want to show diagnostics for non-local macros at all, but proc macros authors
626            // seem to rely on being able to emit non-warning-free code, so we don't want to show warnings
627            // for them even when the proc macro comes from the same workspace (in rustc that's not a
628            // problem because it doesn't have the concept of workspaces, and proc macros always reside
629            // in a different crate).
630            !Crate::from(macro_call.def.krate).origin(sema.db).is_local()
631                || !macro_call.def.kind.is_declarative()
632        })
633    }) {
634        // Disable suggestions for external macros, they'll change library code and it's just bad.
635        diag.fixes = None;
636
637        // All Clippy lints report in macros, see https://github.com/rust-lang/rust-clippy/blob/903293b199364/declare_clippy_lint/src/lib.rs#L172.
638        if let DiagnosticCode::RustcLint(lint) = diag.code
639            && !LINTS_TO_REPORT_IN_EXTERNAL_MACROS.contains(lint)
640        {
641            return false;
642        };
643    }
644    true
645}
646
647struct BuiltLint {
648    lint: &'static Lint,
649    groups: Vec<&'static str>,
650}
651
652static RUSTC_LINTS: LazyLock<FxHashMap<&str, BuiltLint>> =
653    LazyLock::new(|| build_lints_map(DEFAULT_LINTS, DEFAULT_LINT_GROUPS, ""));
654
655static CLIPPY_LINTS: LazyLock<FxHashMap<&str, BuiltLint>> = LazyLock::new(|| {
656    build_lints_map(ide_db::generated::lints::CLIPPY_LINTS, CLIPPY_LINT_GROUPS, "clippy::")
657});
658
659// FIXME: Autogenerate this instead of enumerating by hand.
660static LINTS_TO_REPORT_IN_EXTERNAL_MACROS: LazyLock<FxHashSet<&str>> =
661    LazyLock::new(|| FxHashSet::from_iter([]));
662
663fn build_lints_map(
664    lints: &'static [Lint],
665    lint_group: &'static [LintGroup],
666    prefix: &'static str,
667) -> FxHashMap<&'static str, BuiltLint> {
668    let mut map_with_prefixes: FxHashMap<_, _> = lints
669        .iter()
670        .map(|lint| (lint.label, BuiltLint { lint, groups: vec![lint.label, "__RA_EVERY_LINT"] }))
671        .collect();
672    for g in lint_group {
673        let mut add_children = |label: &'static str| {
674            for child in g.children {
675                map_with_prefixes.get_mut(child).unwrap().groups.push(label);
676            }
677        };
678        add_children(g.lint.label);
679
680        if g.lint.label == "nonstandard_style" {
681            // Also add `bad_style`, which for some reason isn't listed in the groups.
682            add_children("bad_style");
683        }
684    }
685    map_with_prefixes.into_iter().map(|(k, v)| (k.strip_prefix(prefix).unwrap(), v)).collect()
686}
687
688fn handle_lints(
689    sema: &Semantics<'_, RootDatabase>,
690    file_id: FileId,
691    krate: hir::Crate,
692    diagnostics: &mut [(InFile<SyntaxNode>, &mut Diagnostic)],
693    edition: Edition,
694) {
695    for (node, diag) in diagnostics {
696        let lint = match diag.code {
697            DiagnosticCode::RustcLint(lint) => RUSTC_LINTS[lint].lint,
698            DiagnosticCode::Clippy(lint) => CLIPPY_LINTS[lint].lint,
699            _ => panic!("non-lint passed to `handle_lints()`"),
700        };
701        let default_severity = default_lint_severity(lint, edition);
702        if !(default_severity == Severity::Allow && diag.severity == Severity::WeakWarning) {
703            diag.severity = default_severity;
704        }
705
706        let mut diag_severity =
707            lint_severity_at(sema, file_id, krate, node, &lint_groups(&diag.code, edition));
708
709        if let outline_diag_severity @ Some(_) =
710            find_outline_mod_lint_severity(sema, file_id, krate, node, diag, edition)
711        {
712            diag_severity = outline_diag_severity;
713        }
714
715        if let Some(diag_severity) = diag_severity {
716            diag.severity = diag_severity;
717        }
718    }
719}
720
721fn default_lint_severity(lint: &Lint, edition: Edition) -> Severity {
722    if lint.deny_since.is_some_and(|e| edition >= e) {
723        Severity::Error
724    } else if lint.warn_since.is_some_and(|e| edition >= e) {
725        Severity::Warning
726    } else {
727        lint.default_severity
728    }
729}
730
731fn find_outline_mod_lint_severity(
732    sema: &Semantics<'_, RootDatabase>,
733    file_id: FileId,
734    krate: hir::Crate,
735    node: &InFile<SyntaxNode>,
736    diag: &Diagnostic,
737    edition: Edition,
738) -> Option<Severity> {
739    let mod_node = node.value.ancestors().find_map(ast::Module::cast)?;
740    if mod_node.item_list().is_some() {
741        // Inline modules will be handled by `fill_lint_attrs()`.
742        return None;
743    }
744
745    let mod_def = sema.to_module_def(&mod_node)?;
746    let module_source_file = sema.module_definition_node(mod_def);
747    let lint_groups = lint_groups(&diag.code, edition);
748    lint_attrs(
749        sema,
750        file_id,
751        krate,
752        ast::AnyHasAttrs::cast(module_source_file.value).expect("SourceFile always has attrs"),
753    )
754    .find_map(|(lint, severity)| lint_groups.contains(&lint).then_some(severity))
755}
756
757fn lint_severity_at(
758    sema: &Semantics<'_, RootDatabase>,
759    file_id: FileId,
760    krate: hir::Crate,
761    node: &InFile<SyntaxNode>,
762    lint_groups: &LintGroups,
763) -> Option<Severity> {
764    node.value
765        .ancestors()
766        .filter_map(ast::AnyHasAttrs::cast)
767        .find_map(|ancestor| {
768            lint_attrs(sema, file_id, krate, ancestor)
769                .find_map(|(lint, severity)| lint_groups.contains(&lint).then_some(severity))
770        })
771        .or_else(|| {
772            lint_severity_at(
773                sema,
774                file_id,
775                krate,
776                &sema.find_parent_file(node.file_id)?,
777                lint_groups,
778            )
779        })
780}
781
782// FIXME: Switch this to analysis' `expand_cfg_attr`.
783fn lint_attrs(
784    sema: &Semantics<'_, RootDatabase>,
785    file_id: FileId,
786    krate: hir::Crate,
787    ancestor: ast::AnyHasAttrs,
788) -> impl Iterator<Item = (SmolStr, Severity)> {
789    sema.lint_attrs(file_id, krate, ancestor).rev().map(|(lint_attr, lint)| {
790        let severity = match lint_attr {
791            hir::LintAttr::Allow | hir::LintAttr::Expect => Severity::Allow,
792            hir::LintAttr::Warn => Severity::Warning,
793            hir::LintAttr::Deny | hir::LintAttr::Forbid => Severity::Error,
794        };
795        (lint, severity)
796    })
797}
798
799#[derive(Debug)]
800struct LintGroups {
801    groups: &'static [&'static str],
802    inside_warnings: bool,
803}
804
805impl LintGroups {
806    fn contains(&self, group: &str) -> bool {
807        self.groups.contains(&group) || (self.inside_warnings && group == "warnings")
808    }
809}
810
811fn lint_groups(lint: &DiagnosticCode, edition: Edition) -> LintGroups {
812    let (groups, inside_warnings) = match lint {
813        DiagnosticCode::RustcLint(name) => {
814            let lint = &RUSTC_LINTS[name];
815            let inside_warnings = default_lint_severity(lint.lint, edition) == Severity::Warning;
816            (&lint.groups, inside_warnings)
817        }
818        DiagnosticCode::Clippy(name) => {
819            let lint = &CLIPPY_LINTS[name];
820            let inside_warnings = default_lint_severity(lint.lint, edition) == Severity::Warning;
821            (&lint.groups, inside_warnings)
822        }
823        _ => panic!("non-lint passed to `handle_lints()`"),
824    };
825    LintGroups { groups, inside_warnings }
826}
827
828fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
829    let mut res = unresolved_fix(id, label, target);
830    res.source_change = Some(source_change);
831    res
832}
833
834fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
835    assert!(!id.contains(' '));
836    Assist {
837        id: AssistId::quick_fix(id),
838        label: Label::new(label.to_owned()),
839        group: None,
840        target,
841        source_change: None,
842        command: None,
843    }
844}
845
846fn adjusted_display_range<N: AstNode>(
847    ctx: &DiagnosticsContext<'_, '_>,
848    diag_ptr: InFile<AstPtr<N>>,
849    adj: &dyn Fn(N) -> Option<TextRange>,
850) -> FileRange {
851    let source_file = ctx.sema.parse_or_expand(diag_ptr.file_id);
852    let node = diag_ptr.value.to_node(&source_file);
853    let hir::FileRange { file_id, range } = diag_ptr
854        .with_value(adj(node).unwrap_or_else(|| diag_ptr.value.text_range()))
855        .original_node_file_range_rooted(ctx.sema.db);
856    ide_db::FileRange { file_id: file_id.file_id(ctx.sema.db), range }
857}