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