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