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