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    source_change::SourceChange,
104};
105use syntax::{
106    AstPtr, Edition, SmolStr, SyntaxNode, SyntaxNodePtr, TextRange,
107    ast::{self, AstNode},
108};
109
110// FIXME: Make this an enum
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}
242
243impl DiagnosticsConfig {
244    pub fn test_sample() -> Self {
245        use hir::PrefixKind;
246        use ide_db::imports::insert_use::ImportGranularity;
247
248        Self {
249            enabled: true,
250            proc_macros_enabled: Default::default(),
251            proc_attr_macros_enabled: Default::default(),
252            disable_experimental: Default::default(),
253            disabled: Default::default(),
254            expr_fill_default: Default::default(),
255            style_lints: true,
256            snippet_cap: SnippetCap::new(true),
257            insert_use: InsertUseConfig {
258                granularity: ImportGranularity::Item,
259                enforce_granularity: false,
260                prefix_kind: PrefixKind::Plain,
261                group: false,
262                skip_glob_imports: false,
263            },
264            prefer_no_std: false,
265            prefer_prelude: true,
266            prefer_absolute: false,
267            term_search_fuel: 400,
268            term_search_borrowck: true,
269        }
270    }
271}
272
273struct DiagnosticsContext<'a> {
274    config: &'a DiagnosticsConfig,
275    sema: Semantics<'a, RootDatabase>,
276    resolve: &'a AssistResolveStrategy,
277    edition: Edition,
278    display_target: DisplayTarget,
279    is_nightly: bool,
280}
281
282/// Request parser level diagnostics for the given [`FileId`].
283pub fn syntax_diagnostics(
284    db: &RootDatabase,
285    config: &DiagnosticsConfig,
286    file_id: FileId,
287) -> Vec<Diagnostic> {
288    let _p = tracing::info_span!("syntax_diagnostics").entered();
289
290    if config.disabled.contains("syntax-error") {
291        return Vec::new();
292    }
293
294    let sema = Semantics::new(db);
295    let editioned_file_id = sema.attach_first_edition(file_id);
296
297    let (file_id, _) = editioned_file_id.unpack(db);
298
299    // [#3434] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
300    db.parse_errors(editioned_file_id)
301        .into_iter()
302        .flatten()
303        .take(128)
304        .map(|err| {
305            Diagnostic::new(
306                DiagnosticCode::SyntaxError,
307                format!("Syntax Error: {err}"),
308                FileRange { file_id, range: err.range() },
309            )
310        })
311        .collect()
312}
313
314/// Request semantic diagnostics for the given [`FileId`]. The produced diagnostics may point to other files
315/// due to macros.
316pub fn semantic_diagnostics(
317    db: &RootDatabase,
318    config: &DiagnosticsConfig,
319    resolve: &AssistResolveStrategy,
320    file_id: FileId,
321) -> Vec<Diagnostic> {
322    let _p = tracing::info_span!("semantic_diagnostics").entered();
323    let sema = Semantics::new(db);
324    let editioned_file_id = sema.attach_first_edition(file_id);
325
326    let (file_id, edition) = editioned_file_id.unpack(db);
327    let mut res = Vec::new();
328
329    let parse = sema.parse(editioned_file_id);
330
331    // FIXME: This iterates the entire file which is a rather expensive operation.
332    // We should implement these differently in some form?
333    // Salsa caching + incremental re-parse would be better here
334    for node in parse.syntax().descendants() {
335        handlers::useless_braces::useless_braces(db, &mut res, editioned_file_id, &node);
336        handlers::field_shorthand::field_shorthand(db, &mut res, editioned_file_id, &node);
337        handlers::json_is_not_rust::json_in_items(
338            &sema,
339            &mut res,
340            editioned_file_id,
341            &node,
342            config,
343            edition,
344        );
345    }
346
347    let module = sema.file_to_module_def(file_id);
348
349    let is_nightly = matches!(
350        module.and_then(|m| db.toolchain_channel(m.krate(db).into())),
351        Some(ReleaseChannel::Nightly) | None
352    );
353
354    let krate = match module {
355        Some(module) => module.krate(db),
356        None => {
357            match db.all_crates().last() {
358                Some(last) => (*last).into(),
359                // short-circuit, return an empty vec of diagnostics
360                None => return vec![],
361            }
362        }
363    };
364    let display_target = krate.to_display_target(db);
365    let ctx = DiagnosticsContext { config, sema, resolve, edition, is_nightly, display_target };
366
367    let mut diags = Vec::new();
368    match module {
369        // A bunch of parse errors in a file indicate some bigger structural parse changes in the
370        // file, so we skip semantic diagnostics so we can show these faster.
371        Some(m) => {
372            if db.parse_errors(editioned_file_id).is_none_or(|es| es.len() < 16) {
373                m.diagnostics(db, &mut diags, config.style_lints);
374            }
375        }
376        None => {
377            handlers::unlinked_file::unlinked_file(&ctx, &mut res, editioned_file_id.file_id(db))
378        }
379    }
380
381    for diag in diags {
382        let d = match diag {
383            AnyDiagnostic::AwaitOutsideOfAsync(d) => handlers::await_outside_of_async::await_outside_of_async(&ctx, &d),
384            AnyDiagnostic::CastToUnsized(d) => handlers::invalid_cast::cast_to_unsized(&ctx, &d),
385            AnyDiagnostic::ExpectedFunction(d) => handlers::expected_function::expected_function(&ctx, &d),
386            AnyDiagnostic::InactiveCode(d) => match handlers::inactive_code::inactive_code(&ctx, &d) {
387                Some(it) => it,
388                None => continue,
389            }
390            AnyDiagnostic::IncoherentImpl(d) => handlers::incoherent_impl::incoherent_impl(&ctx, &d),
391            AnyDiagnostic::IncorrectCase(d) => handlers::incorrect_case::incorrect_case(&ctx, &d),
392            AnyDiagnostic::InvalidCast(d) => handlers::invalid_cast::invalid_cast(&ctx, &d),
393            AnyDiagnostic::InvalidDeriveTarget(d) => handlers::invalid_derive_target::invalid_derive_target(&ctx, &d),
394            AnyDiagnostic::MacroDefError(d) => handlers::macro_error::macro_def_error(&ctx, &d),
395            AnyDiagnostic::MacroError(d) => handlers::macro_error::macro_error(&ctx, &d),
396            AnyDiagnostic::MacroExpansionParseError(d) => {
397                // FIXME: Point to the correct error span here, not just the macro-call name
398                res.extend(d.errors.iter().take(16).map(|err| {
399                        Diagnostic::new(
400                            DiagnosticCode::SyntaxError,
401                            format!("Syntax Error in Expansion: {err}"),
402                            ctx.sema.diagnostics_display_range_for_range(d.range),
403                        )
404                }));
405                continue;
406            },
407            AnyDiagnostic::MalformedDerive(d) => handlers::malformed_derive::malformed_derive(&ctx, &d),
408            AnyDiagnostic::MismatchedArgCount(d) => handlers::mismatched_arg_count::mismatched_arg_count(&ctx, &d),
409            AnyDiagnostic::MissingFields(d) => handlers::missing_fields::missing_fields(&ctx, &d),
410            AnyDiagnostic::MissingMatchArms(d) => handlers::missing_match_arms::missing_match_arms(&ctx, &d),
411            AnyDiagnostic::MissingUnsafe(d) => handlers::missing_unsafe::missing_unsafe(&ctx, &d),
412            AnyDiagnostic::MovedOutOfRef(d) => handlers::moved_out_of_ref::moved_out_of_ref(&ctx, &d),
413            AnyDiagnostic::NeedMut(d) => match handlers::mutability_errors::need_mut(&ctx, &d) {
414                Some(it) => it,
415                None => continue,
416            },
417            AnyDiagnostic::NonExhaustiveLet(d) => handlers::non_exhaustive_let::non_exhaustive_let(&ctx, &d),
418            AnyDiagnostic::NoSuchField(d) => handlers::no_such_field::no_such_field(&ctx, &d),
419            AnyDiagnostic::PrivateAssocItem(d) => handlers::private_assoc_item::private_assoc_item(&ctx, &d),
420            AnyDiagnostic::PrivateField(d) => handlers::private_field::private_field(&ctx, &d),
421            AnyDiagnostic::ReplaceFilterMapNextWithFindMap(d) => handlers::replace_filter_map_next_with_find_map::replace_filter_map_next_with_find_map(&ctx, &d),
422            AnyDiagnostic::TraitImplIncorrectSafety(d) => handlers::trait_impl_incorrect_safety::trait_impl_incorrect_safety(&ctx, &d),
423            AnyDiagnostic::TraitImplMissingAssocItems(d) => handlers::trait_impl_missing_assoc_item::trait_impl_missing_assoc_item(&ctx, &d),
424            AnyDiagnostic::TraitImplRedundantAssocItems(d) => handlers::trait_impl_redundant_assoc_item::trait_impl_redundant_assoc_item(&ctx, &d),
425            AnyDiagnostic::TraitImplOrphan(d) => handlers::trait_impl_orphan::trait_impl_orphan(&ctx, &d),
426            AnyDiagnostic::TypedHole(d) => handlers::typed_hole::typed_hole(&ctx, &d),
427            AnyDiagnostic::TypeMismatch(d) => handlers::type_mismatch::type_mismatch(&ctx, &d),
428            AnyDiagnostic::UndeclaredLabel(d) => handlers::undeclared_label::undeclared_label(&ctx, &d),
429            AnyDiagnostic::UnimplementedBuiltinMacro(d) => handlers::unimplemented_builtin_macro::unimplemented_builtin_macro(&ctx, &d),
430            AnyDiagnostic::UnreachableLabel(d) => handlers::unreachable_label::unreachable_label(&ctx, &d),
431            AnyDiagnostic::UnresolvedAssocItem(d) => handlers::unresolved_assoc_item::unresolved_assoc_item(&ctx, &d),
432            AnyDiagnostic::UnresolvedExternCrate(d) => handlers::unresolved_extern_crate::unresolved_extern_crate(&ctx, &d),
433            AnyDiagnostic::UnresolvedField(d) => handlers::unresolved_field::unresolved_field(&ctx, &d),
434            AnyDiagnostic::UnresolvedIdent(d) => handlers::unresolved_ident::unresolved_ident(&ctx, &d),
435            AnyDiagnostic::UnresolvedImport(d) => handlers::unresolved_import::unresolved_import(&ctx, &d),
436            AnyDiagnostic::UnresolvedMacroCall(d) => handlers::unresolved_macro_call::unresolved_macro_call(&ctx, &d),
437            AnyDiagnostic::UnresolvedMethodCall(d) => handlers::unresolved_method::unresolved_method(&ctx, &d),
438            AnyDiagnostic::UnresolvedModule(d) => handlers::unresolved_module::unresolved_module(&ctx, &d),
439            AnyDiagnostic::UnusedMut(d) => match handlers::mutability_errors::unused_mut(&ctx, &d) {
440                Some(it) => it,
441                None => continue,
442            },
443            AnyDiagnostic::UnusedVariable(d) => match handlers::unused_variables::unused_variables(&ctx, &d) {
444                Some(it) => it,
445                None => continue,
446            },
447            AnyDiagnostic::BreakOutsideOfLoop(d) => handlers::break_outside_of_loop::break_outside_of_loop(&ctx, &d),
448            AnyDiagnostic::MismatchedTupleStructPatArgCount(d) => handlers::mismatched_arg_count::mismatched_tuple_struct_pat_arg_count(&ctx, &d),
449            AnyDiagnostic::RemoveTrailingReturn(d) => match handlers::remove_trailing_return::remove_trailing_return(&ctx, &d) {
450                Some(it) => it,
451                None => continue,
452            },
453            AnyDiagnostic::RemoveUnnecessaryElse(d) => match handlers::remove_unnecessary_else::remove_unnecessary_else(&ctx, &d) {
454                Some(it) => it,
455                None => continue,
456            },
457            AnyDiagnostic::GenericArgsProhibited(d) => handlers::generic_args_prohibited::generic_args_prohibited(&ctx, &d),
458            AnyDiagnostic::ParenthesizedGenericArgsWithoutFnTrait(d) => handlers::parenthesized_generic_args_without_fn_trait::parenthesized_generic_args_without_fn_trait(&ctx, &d),
459            AnyDiagnostic::BadRtn(d) => handlers::bad_rtn::bad_rtn(&ctx, &d),
460            AnyDiagnostic::IncorrectGenericsLen(d) => handlers::incorrect_generics_len::incorrect_generics_len(&ctx, &d),
461            AnyDiagnostic::IncorrectGenericsOrder(d) => handlers::incorrect_generics_order::incorrect_generics_order(&ctx, &d),
462            AnyDiagnostic::MissingLifetime(d) => handlers::missing_lifetime::missing_lifetime(&ctx, &d),
463            AnyDiagnostic::ElidedLifetimesInPath(d) => handlers::elided_lifetimes_in_path::elided_lifetimes_in_path(&ctx, &d),
464        };
465        res.push(d)
466    }
467
468    res.retain(|d| {
469        !(ctx.config.disabled.contains(d.code.as_str())
470            || ctx.config.disable_experimental && d.experimental)
471    });
472
473    let mut lints = res
474        .iter_mut()
475        .filter(|it| matches!(it.code, DiagnosticCode::Clippy(_) | DiagnosticCode::RustcLint(_)))
476        .filter_map(|it| {
477            Some((
478                it.main_node.map(|ptr| {
479                    ptr.map(|node| node.to_node(&ctx.sema.parse_or_expand(ptr.file_id)))
480                })?,
481                it,
482            ))
483        })
484        .collect::<Vec<_>>();
485
486    // The edition isn't accurate (each diagnostics may have its own edition due to macros),
487    // but it's okay as it's only being used for error recovery.
488    handle_lints(&ctx.sema, krate, &mut lints, editioned_file_id.edition(db));
489
490    res.retain(|d| d.severity != Severity::Allow);
491
492    res.retain_mut(|diag| {
493        if let Some(node) = diag
494            .main_node
495            .map(|ptr| ptr.map(|node| node.to_node(&ctx.sema.parse_or_expand(ptr.file_id))))
496        {
497            handle_diag_from_macros(&ctx.sema, diag, &node)
498        } else {
499            true
500        }
501    });
502
503    res
504}
505
506/// Request both syntax and semantic diagnostics for the given [`FileId`].
507pub fn full_diagnostics(
508    db: &RootDatabase,
509    config: &DiagnosticsConfig,
510    resolve: &AssistResolveStrategy,
511    file_id: FileId,
512) -> Vec<Diagnostic> {
513    let mut res = syntax_diagnostics(db, config, file_id);
514    let sema = semantic_diagnostics(db, config, resolve, file_id);
515    res.extend(sema);
516    res
517}
518
519/// Returns whether to keep this diagnostic (or remove it).
520fn handle_diag_from_macros(
521    sema: &Semantics<'_, RootDatabase>,
522    diag: &mut Diagnostic,
523    node: &InFile<SyntaxNode>,
524) -> bool {
525    let Some(macro_file) = node.file_id.macro_file() else { return true };
526    let span_map = sema.db.expansion_span_map(macro_file);
527    let mut spans = span_map.spans_for_range(node.text_range());
528    if spans.any(|span| {
529        span.ctx.outer_expn(sema.db).is_some_and(|expansion| {
530            let macro_call = sema.db.lookup_intern_macro_call(expansion.into());
531            // We don't want to show diagnostics for non-local macros at all, but proc macros authors
532            // seem to rely on being able to emit non-warning-free code, so we don't want to show warnings
533            // for them even when the proc macro comes from the same workspace (in rustc that's not a
534            // problem because it doesn't have the concept of workspaces, and proc macros always reside
535            // in a different crate).
536            !Crate::from(macro_call.def.krate).origin(sema.db).is_local()
537                || !macro_call.def.kind.is_declarative()
538        })
539    }) {
540        // Disable suggestions for external macros, they'll change library code and it's just bad.
541        diag.fixes = None;
542
543        // All Clippy lints report in macros, see https://github.com/rust-lang/rust-clippy/blob/903293b199364/declare_clippy_lint/src/lib.rs#L172.
544        if let DiagnosticCode::RustcLint(lint) = diag.code
545            && !LINTS_TO_REPORT_IN_EXTERNAL_MACROS.contains(lint)
546        {
547            return false;
548        };
549    }
550    true
551}
552
553struct BuiltLint {
554    lint: &'static Lint,
555    groups: Vec<&'static str>,
556}
557
558static RUSTC_LINTS: LazyLock<FxHashMap<&str, BuiltLint>> =
559    LazyLock::new(|| build_lints_map(DEFAULT_LINTS, DEFAULT_LINT_GROUPS, ""));
560
561static CLIPPY_LINTS: LazyLock<FxHashMap<&str, BuiltLint>> = LazyLock::new(|| {
562    build_lints_map(ide_db::generated::lints::CLIPPY_LINTS, CLIPPY_LINT_GROUPS, "clippy::")
563});
564
565// FIXME: Autogenerate this instead of enumerating by hand.
566static LINTS_TO_REPORT_IN_EXTERNAL_MACROS: LazyLock<FxHashSet<&str>> =
567    LazyLock::new(|| FxHashSet::from_iter([]));
568
569fn build_lints_map(
570    lints: &'static [Lint],
571    lint_group: &'static [LintGroup],
572    prefix: &'static str,
573) -> FxHashMap<&'static str, BuiltLint> {
574    let mut map_with_prefixes: FxHashMap<_, _> = lints
575        .iter()
576        .map(|lint| (lint.label, BuiltLint { lint, groups: vec![lint.label, "__RA_EVERY_LINT"] }))
577        .collect();
578    for g in lint_group {
579        let mut add_children = |label: &'static str| {
580            for child in g.children {
581                map_with_prefixes.get_mut(child).unwrap().groups.push(label);
582            }
583        };
584        add_children(g.lint.label);
585
586        if g.lint.label == "nonstandard_style" {
587            // Also add `bad_style`, which for some reason isn't listed in the groups.
588            add_children("bad_style");
589        }
590    }
591    map_with_prefixes.into_iter().map(|(k, v)| (k.strip_prefix(prefix).unwrap(), v)).collect()
592}
593
594fn handle_lints(
595    sema: &Semantics<'_, RootDatabase>,
596    krate: hir::Crate,
597    diagnostics: &mut [(InFile<SyntaxNode>, &mut Diagnostic)],
598    edition: Edition,
599) {
600    for (node, diag) in diagnostics {
601        let lint = match diag.code {
602            DiagnosticCode::RustcLint(lint) => RUSTC_LINTS[lint].lint,
603            DiagnosticCode::Clippy(lint) => CLIPPY_LINTS[lint].lint,
604            _ => panic!("non-lint passed to `handle_lints()`"),
605        };
606        let default_severity = default_lint_severity(lint, edition);
607        if !(default_severity == Severity::Allow && diag.severity == Severity::WeakWarning) {
608            diag.severity = default_severity;
609        }
610
611        let mut diag_severity =
612            lint_severity_at(sema, krate, node, &lint_groups(&diag.code, edition));
613
614        if let outline_diag_severity @ Some(_) =
615            find_outline_mod_lint_severity(sema, krate, node, diag, edition)
616        {
617            diag_severity = outline_diag_severity;
618        }
619
620        if let Some(diag_severity) = diag_severity {
621            diag.severity = diag_severity;
622        }
623    }
624}
625
626fn default_lint_severity(lint: &Lint, edition: Edition) -> Severity {
627    if lint.deny_since.is_some_and(|e| edition >= e) {
628        Severity::Error
629    } else if lint.warn_since.is_some_and(|e| edition >= e) {
630        Severity::Warning
631    } else {
632        lint.default_severity
633    }
634}
635
636fn find_outline_mod_lint_severity(
637    sema: &Semantics<'_, RootDatabase>,
638    krate: hir::Crate,
639    node: &InFile<SyntaxNode>,
640    diag: &Diagnostic,
641    edition: Edition,
642) -> Option<Severity> {
643    let mod_node = node.value.ancestors().find_map(ast::Module::cast)?;
644    if mod_node.item_list().is_some() {
645        // Inline modules will be handled by `fill_lint_attrs()`.
646        return None;
647    }
648
649    let mod_def = sema.to_module_def(&mod_node)?;
650    let module_source_file = sema.module_definition_node(mod_def);
651    let lint_groups = lint_groups(&diag.code, edition);
652    lint_attrs(
653        sema,
654        krate,
655        ast::AnyHasAttrs::cast(module_source_file.value).expect("SourceFile always has attrs"),
656    )
657    .find_map(|(lint, severity)| lint_groups.contains(&lint).then_some(severity))
658}
659
660fn lint_severity_at(
661    sema: &Semantics<'_, RootDatabase>,
662    krate: hir::Crate,
663    node: &InFile<SyntaxNode>,
664    lint_groups: &LintGroups,
665) -> Option<Severity> {
666    node.value
667        .ancestors()
668        .filter_map(ast::AnyHasAttrs::cast)
669        .find_map(|ancestor| {
670            lint_attrs(sema, krate, ancestor)
671                .find_map(|(lint, severity)| lint_groups.contains(&lint).then_some(severity))
672        })
673        .or_else(|| {
674            lint_severity_at(sema, krate, &sema.find_parent_file(node.file_id)?, lint_groups)
675        })
676}
677
678// FIXME: Switch this to analysis' `expand_cfg_attr`.
679fn lint_attrs(
680    sema: &Semantics<'_, RootDatabase>,
681    krate: hir::Crate,
682    ancestor: ast::AnyHasAttrs,
683) -> impl Iterator<Item = (SmolStr, Severity)> {
684    sema.lint_attrs(krate, ancestor).rev().map(|(lint_attr, lint)| {
685        let severity = match lint_attr {
686            hir::LintAttr::Allow | hir::LintAttr::Expect => Severity::Allow,
687            hir::LintAttr::Warn => Severity::Warning,
688            hir::LintAttr::Deny | hir::LintAttr::Forbid => Severity::Error,
689        };
690        (lint, severity)
691    })
692}
693
694#[derive(Debug)]
695struct LintGroups {
696    groups: &'static [&'static str],
697    inside_warnings: bool,
698}
699
700impl LintGroups {
701    fn contains(&self, group: &str) -> bool {
702        self.groups.contains(&group) || (self.inside_warnings && group == "warnings")
703    }
704}
705
706fn lint_groups(lint: &DiagnosticCode, edition: Edition) -> LintGroups {
707    let (groups, inside_warnings) = match lint {
708        DiagnosticCode::RustcLint(name) => {
709            let lint = &RUSTC_LINTS[name];
710            let inside_warnings = default_lint_severity(lint.lint, edition) == Severity::Warning;
711            (&lint.groups, inside_warnings)
712        }
713        DiagnosticCode::Clippy(name) => {
714            let lint = &CLIPPY_LINTS[name];
715            let inside_warnings = default_lint_severity(lint.lint, edition) == Severity::Warning;
716            (&lint.groups, inside_warnings)
717        }
718        _ => panic!("non-lint passed to `handle_lints()`"),
719    };
720    LintGroups { groups, inside_warnings }
721}
722
723fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
724    let mut res = unresolved_fix(id, label, target);
725    res.source_change = Some(source_change);
726    res
727}
728
729fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
730    assert!(!id.contains(' '));
731    Assist {
732        id: AssistId::quick_fix(id),
733        label: Label::new(label.to_owned()),
734        group: None,
735        target,
736        source_change: None,
737        command: None,
738    }
739}
740
741fn adjusted_display_range<N: AstNode>(
742    ctx: &DiagnosticsContext<'_>,
743    diag_ptr: InFile<AstPtr<N>>,
744    adj: &dyn Fn(N) -> Option<TextRange>,
745) -> FileRange {
746    let source_file = ctx.sema.parse_or_expand(diag_ptr.file_id);
747    let node = diag_ptr.value.to_node(&source_file);
748    let hir::FileRange { file_id, range } = diag_ptr
749        .with_value(adj(node).unwrap_or_else(|| diag_ptr.value.text_range()))
750        .original_node_file_range_rooted(ctx.sema.db);
751    ide_db::FileRange { file_id: file_id.file_id(ctx.sema.db), range }
752}