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