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 #![warn(rust_2018_idioms, unused_lifetimes, semicolon_in_expressions_from_macros)]
27
28 mod handlers {
29 pub(crate) mod break_outside_of_loop;
30 pub(crate) mod expected_function;
31 pub(crate) mod inactive_code;
32 pub(crate) mod incoherent_impl;
33 pub(crate) mod incorrect_case;
34 pub(crate) mod invalid_derive_target;
35 pub(crate) mod macro_error;
36 pub(crate) mod malformed_derive;
37 pub(crate) mod mismatched_arg_count;
38 pub(crate) mod missing_fields;
39 pub(crate) mod missing_match_arms;
40 pub(crate) mod missing_unsafe;
41 pub(crate) mod moved_out_of_ref;
42 pub(crate) mod mutability_errors;
43 pub(crate) mod no_such_field;
44 pub(crate) mod private_assoc_item;
45 pub(crate) mod private_field;
46 pub(crate) mod replace_filter_map_next_with_find_map;
47 pub(crate) mod typed_hole;
48 pub(crate) mod type_mismatch;
49 pub(crate) mod unimplemented_builtin_macro;
50 pub(crate) mod unresolved_extern_crate;
51 pub(crate) mod unresolved_field;
52 pub(crate) mod unresolved_method;
53 pub(crate) mod unresolved_import;
54 pub(crate) mod unresolved_macro_call;
55 pub(crate) mod unresolved_module;
56 pub(crate) mod unresolved_proc_macro;
57 pub(crate) mod undeclared_label;
58 pub(crate) mod unreachable_label;
59
60 // The handlers below are unusual, the implement the diagnostics as well.
61 pub(crate) mod field_shorthand;
62 pub(crate) mod useless_braces;
63 pub(crate) mod unlinked_file;
64 pub(crate) mod json_is_not_rust;
65 }
66
67 #[cfg(test)]
68 mod tests;
69
70 use hir::{diagnostics::AnyDiagnostic, InFile, Semantics};
71 use ide_db::{
72 assists::{Assist, AssistId, AssistKind, AssistResolveStrategy},
73 base_db::{FileId, FileRange, SourceDatabase},
74 imports::insert_use::InsertUseConfig,
75 label::Label,
76 source_change::SourceChange,
77 FxHashSet, RootDatabase,
78 };
79 use syntax::{algo::find_node_at_range, ast::AstNode, SyntaxNodePtr, TextRange};
80
81 // FIXME: Make this an enum
82 #[derive(Copy, Clone, Debug, PartialEq)]
83 pub struct DiagnosticCode(pub &'static str);
84
85 impl DiagnosticCode {
as_str(&self) -> &str86 pub fn as_str(&self) -> &str {
87 self.0
88 }
89 }
90
91 #[derive(Debug)]
92 pub struct Diagnostic {
93 pub code: DiagnosticCode,
94 pub message: String,
95 pub range: TextRange,
96 pub severity: Severity,
97 pub unused: bool,
98 pub experimental: bool,
99 pub fixes: Option<Vec<Assist>>,
100 }
101
102 impl Diagnostic {
new(code: &'static str, message: impl Into<String>, range: TextRange) -> Diagnostic103 fn new(code: &'static str, message: impl Into<String>, range: TextRange) -> Diagnostic {
104 let message = message.into();
105 Diagnostic {
106 code: DiagnosticCode(code),
107 message,
108 range,
109 severity: Severity::Error,
110 unused: false,
111 experimental: false,
112 fixes: None,
113 }
114 }
115
experimental(mut self) -> Diagnostic116 fn experimental(mut self) -> Diagnostic {
117 self.experimental = true;
118 self
119 }
120
severity(mut self, severity: Severity) -> Diagnostic121 fn severity(mut self, severity: Severity) -> Diagnostic {
122 self.severity = severity;
123 self
124 }
125
with_fixes(mut self, fixes: Option<Vec<Assist>>) -> Diagnostic126 fn with_fixes(mut self, fixes: Option<Vec<Assist>>) -> Diagnostic {
127 self.fixes = fixes;
128 self
129 }
130
with_unused(mut self, unused: bool) -> Diagnostic131 fn with_unused(mut self, unused: bool) -> Diagnostic {
132 self.unused = unused;
133 self
134 }
135 }
136
137 #[derive(Debug, Copy, Clone)]
138 pub enum Severity {
139 Error,
140 // We don't actually emit this one yet, but we should at some point.
141 // Warning,
142 WeakWarning,
143 }
144
145 #[derive(Clone, Debug, PartialEq, Eq)]
146 pub enum ExprFillDefaultMode {
147 Todo,
148 Default,
149 }
150 impl Default for ExprFillDefaultMode {
default() -> Self151 fn default() -> Self {
152 Self::Todo
153 }
154 }
155
156 #[derive(Debug, Clone)]
157 pub struct DiagnosticsConfig {
158 pub proc_macros_enabled: bool,
159 pub proc_attr_macros_enabled: bool,
160 pub disable_experimental: bool,
161 pub disabled: FxHashSet<String>,
162 pub expr_fill_default: ExprFillDefaultMode,
163 // FIXME: We may want to include a whole `AssistConfig` here
164 pub insert_use: InsertUseConfig,
165 pub prefer_no_std: bool,
166 }
167
168 impl DiagnosticsConfig {
test_sample() -> Self169 pub fn test_sample() -> Self {
170 use hir::PrefixKind;
171 use ide_db::imports::insert_use::ImportGranularity;
172
173 Self {
174 proc_macros_enabled: Default::default(),
175 proc_attr_macros_enabled: Default::default(),
176 disable_experimental: Default::default(),
177 disabled: Default::default(),
178 expr_fill_default: Default::default(),
179 insert_use: InsertUseConfig {
180 granularity: ImportGranularity::Preserve,
181 enforce_granularity: false,
182 prefix_kind: PrefixKind::Plain,
183 group: false,
184 skip_glob_imports: false,
185 },
186 prefer_no_std: false,
187 }
188 }
189 }
190
191 struct DiagnosticsContext<'a> {
192 config: &'a DiagnosticsConfig,
193 sema: Semantics<'a, RootDatabase>,
194 resolve: &'a AssistResolveStrategy,
195 }
196
197 impl<'a> DiagnosticsContext<'a> {
resolve_precise_location( &self, node: &InFile<SyntaxNodePtr>, precise_location: Option<TextRange>, ) -> TextRange198 fn resolve_precise_location(
199 &self,
200 node: &InFile<SyntaxNodePtr>,
201 precise_location: Option<TextRange>,
202 ) -> TextRange {
203 let sema = &self.sema;
204 (|| {
205 let precise_location = precise_location?;
206 let root = sema.parse_or_expand(node.file_id);
207 match root.covering_element(precise_location) {
208 syntax::NodeOrToken::Node(it) => Some(sema.original_range(&it)),
209 syntax::NodeOrToken::Token(it) => {
210 node.with_value(it).original_file_range_opt(sema.db)
211 }
212 }
213 })()
214 .unwrap_or_else(|| sema.diagnostics_display_range(node.clone()))
215 .range
216 }
217 }
218
diagnostics( db: &RootDatabase, config: &DiagnosticsConfig, resolve: &AssistResolveStrategy, file_id: FileId, ) -> Vec<Diagnostic>219 pub fn diagnostics(
220 db: &RootDatabase,
221 config: &DiagnosticsConfig,
222 resolve: &AssistResolveStrategy,
223 file_id: FileId,
224 ) -> Vec<Diagnostic> {
225 let _p = profile::span("diagnostics");
226 let sema = Semantics::new(db);
227 let parse = db.parse(file_id);
228 let mut res = Vec::new();
229
230 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
231 res.extend(
232 parse.errors().iter().take(128).map(|err| {
233 Diagnostic::new("syntax-error", format!("Syntax Error: {err}"), err.range())
234 }),
235 );
236
237 let parse = sema.parse(file_id);
238
239 for node in parse.syntax().descendants() {
240 handlers::useless_braces::useless_braces(&mut res, file_id, &node);
241 handlers::field_shorthand::field_shorthand(&mut res, file_id, &node);
242 handlers::json_is_not_rust::json_in_items(&sema, &mut res, file_id, &node, config);
243 }
244
245 let module = sema.to_module_def(file_id);
246
247 let ctx = DiagnosticsContext { config, sema, resolve };
248 if module.is_none() {
249 handlers::unlinked_file::unlinked_file(&ctx, &mut res, file_id);
250 }
251
252 let mut diags = Vec::new();
253 if let Some(m) = module {
254 m.diagnostics(db, &mut diags);
255 }
256
257 for diag in diags {
258 #[rustfmt::skip]
259 let d = match diag {
260 AnyDiagnostic::ExpectedFunction(d) => handlers::expected_function::expected_function(&ctx, &d),
261 AnyDiagnostic::InactiveCode(d) => match handlers::inactive_code::inactive_code(&ctx, &d) {
262 Some(it) => it,
263 None => continue,
264 }
265 AnyDiagnostic::IncoherentImpl(d) => handlers::incoherent_impl::incoherent_impl(&ctx, &d),
266 AnyDiagnostic::IncorrectCase(d) => handlers::incorrect_case::incorrect_case(&ctx, &d),
267 AnyDiagnostic::InvalidDeriveTarget(d) => handlers::invalid_derive_target::invalid_derive_target(&ctx, &d),
268 AnyDiagnostic::MacroDefError(d) => handlers::macro_error::macro_def_error(&ctx, &d),
269 AnyDiagnostic::MacroError(d) => handlers::macro_error::macro_error(&ctx, &d),
270 AnyDiagnostic::MacroExpansionParseError(d) => {
271 res.extend(d.errors.iter().take(32).map(|err| {
272 {
273 Diagnostic::new(
274 "syntax-error",
275 format!("Syntax Error in Expansion: {err}"),
276 ctx.resolve_precise_location(&d.node.clone(), d.precise_location),
277 )
278 }
279 .experimental()
280 }));
281 continue;
282 },
283 AnyDiagnostic::MalformedDerive(d) => handlers::malformed_derive::malformed_derive(&ctx, &d),
284 AnyDiagnostic::MismatchedArgCount(d) => handlers::mismatched_arg_count::mismatched_arg_count(&ctx, &d),
285 AnyDiagnostic::MissingFields(d) => handlers::missing_fields::missing_fields(&ctx, &d),
286 AnyDiagnostic::MissingMatchArms(d) => handlers::missing_match_arms::missing_match_arms(&ctx, &d),
287 AnyDiagnostic::MissingUnsafe(d) => handlers::missing_unsafe::missing_unsafe(&ctx, &d),
288 AnyDiagnostic::MovedOutOfRef(d) => handlers::moved_out_of_ref::moved_out_of_ref(&ctx, &d),
289 AnyDiagnostic::NeedMut(d) => handlers::mutability_errors::need_mut(&ctx, &d),
290 AnyDiagnostic::NoSuchField(d) => handlers::no_such_field::no_such_field(&ctx, &d),
291 AnyDiagnostic::PrivateAssocItem(d) => handlers::private_assoc_item::private_assoc_item(&ctx, &d),
292 AnyDiagnostic::PrivateField(d) => handlers::private_field::private_field(&ctx, &d),
293 AnyDiagnostic::ReplaceFilterMapNextWithFindMap(d) => handlers::replace_filter_map_next_with_find_map::replace_filter_map_next_with_find_map(&ctx, &d),
294 AnyDiagnostic::TypedHole(d) => handlers::typed_hole::typed_hole(&ctx, &d),
295 AnyDiagnostic::TypeMismatch(d) => handlers::type_mismatch::type_mismatch(&ctx, &d),
296 AnyDiagnostic::UndeclaredLabel(d) => handlers::undeclared_label::undeclared_label(&ctx, &d),
297 AnyDiagnostic::UnimplementedBuiltinMacro(d) => handlers::unimplemented_builtin_macro::unimplemented_builtin_macro(&ctx, &d),
298 AnyDiagnostic::UnreachableLabel(d) => handlers::unreachable_label:: unreachable_label(&ctx, &d),
299 AnyDiagnostic::UnresolvedExternCrate(d) => handlers::unresolved_extern_crate::unresolved_extern_crate(&ctx, &d),
300 AnyDiagnostic::UnresolvedField(d) => handlers::unresolved_field::unresolved_field(&ctx, &d),
301 AnyDiagnostic::UnresolvedImport(d) => handlers::unresolved_import::unresolved_import(&ctx, &d),
302 AnyDiagnostic::UnresolvedMacroCall(d) => handlers::unresolved_macro_call::unresolved_macro_call(&ctx, &d),
303 AnyDiagnostic::UnresolvedMethodCall(d) => handlers::unresolved_method::unresolved_method(&ctx, &d),
304 AnyDiagnostic::UnresolvedModule(d) => handlers::unresolved_module::unresolved_module(&ctx, &d),
305 AnyDiagnostic::UnresolvedProcMacro(d) => handlers::unresolved_proc_macro::unresolved_proc_macro(&ctx, &d, config.proc_macros_enabled, config.proc_attr_macros_enabled),
306 AnyDiagnostic::UnusedMut(d) => handlers::mutability_errors::unused_mut(&ctx, &d),
307 AnyDiagnostic::BreakOutsideOfLoop(d) => handlers::break_outside_of_loop::break_outside_of_loop(&ctx, &d),
308 };
309 res.push(d)
310 }
311
312 res.retain(|d| {
313 !ctx.config.disabled.contains(d.code.as_str())
314 && !(ctx.config.disable_experimental && d.experimental)
315 });
316
317 res
318 }
319
fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist320 fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
321 let mut res = unresolved_fix(id, label, target);
322 res.source_change = Some(source_change);
323 res
324 }
325
unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist326 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
327 assert!(!id.contains(' '));
328 Assist {
329 id: AssistId(id, AssistKind::QuickFix),
330 label: Label::new(label.to_string()),
331 group: None,
332 target,
333 source_change: None,
334 trigger_signature_help: false,
335 }
336 }
337
adjusted_display_range<N: AstNode>( ctx: &DiagnosticsContext<'_>, diag_ptr: InFile<SyntaxNodePtr>, adj: &dyn Fn(N) -> Option<TextRange>, ) -> TextRange338 fn adjusted_display_range<N: AstNode>(
339 ctx: &DiagnosticsContext<'_>,
340 diag_ptr: InFile<SyntaxNodePtr>,
341 adj: &dyn Fn(N) -> Option<TextRange>,
342 ) -> TextRange {
343 let FileRange { file_id, range } = ctx.sema.diagnostics_display_range(diag_ptr);
344
345 let source_file = ctx.sema.db.parse(file_id);
346 find_node_at_range::<N>(&source_file.syntax_node(), range)
347 .filter(|it| it.syntax().text_range() == range)
348 .and_then(adj)
349 .unwrap_or(range)
350 }
351