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