Skip to main content

ide_diagnostics/
lib.rs

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