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