1 //! Collects diagnostics & fixits for a single file.
3 //! The tricky bit here is that diagnostics are produced by hir in terms of
4 //! macro-expanded files, but we need to present them to the users in terms of
5 //! original files. So we need to map the ranges.
8 mod unresolved_extern_crate;
10 mod unresolved_macro_call;
18 use std::cell::RefCell;
21 diagnostics::{AnyDiagnostic, Diagnostic as _, DiagnosticCode, DiagnosticSinkBuilder},
24 use ide_assists::AssistResolveStrategy;
25 use ide_db::{base_db::SourceDatabase, RootDatabase};
26 use itertools::Itertools;
27 use rustc_hash::FxHashSet;
30 SyntaxNode, SyntaxNodePtr, TextRange, TextSize,
32 use text_edit::TextEdit;
33 use unlinked_file::UnlinkedFile;
35 use crate::{Assist, AssistId, AssistKind, FileId, Label, SourceChange};
37 use self::fixes::DiagnosticWithFixes;
40 pub struct Diagnostic {
41 // pub name: Option<String>,
44 pub severity: Severity,
45 pub fixes: Option<Vec<Assist>>,
47 pub code: Option<DiagnosticCode>,
48 pub experimental: bool,
52 fn new(code: &'static str, message: impl Into<String>, range: TextRange) -> Diagnostic {
53 let message = message.into();
54 let code = Some(DiagnosticCode(code));
58 severity: Severity::Error,
66 fn experimental(mut self) -> Diagnostic {
67 self.experimental = true;
71 fn error(range: TextRange, message: String) -> Self {
75 severity: Severity::Error,
83 fn hint(range: TextRange, message: String) -> Self {
87 severity: Severity::WeakWarning,
95 fn with_fixes(self, fixes: Option<Vec<Assist>>) -> Self {
96 Self { fixes, ..self }
99 fn with_unused(self, unused: bool) -> Self {
100 Self { unused, ..self }
103 fn with_code(self, code: Option<DiagnosticCode>) -> Self {
104 Self { code, ..self }
108 #[derive(Debug, Copy, Clone)]
114 #[derive(Default, Debug, Clone)]
115 pub struct DiagnosticsConfig {
116 pub disable_experimental: bool,
117 pub disabled: FxHashSet<String>,
120 struct DiagnosticsContext<'a> {
121 config: &'a DiagnosticsConfig,
122 sema: Semantics<'a, RootDatabase>,
124 resolve: &'a AssistResolveStrategy,
127 pub(crate) fn diagnostics(
129 config: &DiagnosticsConfig,
130 resolve: &AssistResolveStrategy,
132 ) -> Vec<Diagnostic> {
133 let _p = profile::span("diagnostics");
134 let sema = Semantics::new(db);
135 let parse = db.parse(file_id);
136 let mut res = Vec::new();
138 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
144 .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
147 for node in parse.tree().syntax().descendants() {
148 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
149 field_shorthand::check(&mut res, file_id, &node);
151 let res = RefCell::new(res);
152 let sink_builder = DiagnosticSinkBuilder::new()
153 .on::<hir::diagnostics::MissingOkOrSomeInTailExpr, _>(|d| {
154 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
156 .on::<hir::diagnostics::NoSuchField, _>(|d| {
157 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
159 .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| {
160 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
162 .on::<hir::diagnostics::IncorrectCase, _>(|d| {
163 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
165 .on::<hir::diagnostics::ReplaceFilterMapNextWithFindMap, _>(|d| {
166 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
168 .on::<UnlinkedFile, _>(|d| {
169 // Limit diagnostic to the first few characters in the file. This matches how VS Code
170 // renders it with the full span, but on other editors, and is less invasive.
171 let range = sema.diagnostics_display_range(d.display_source()).range;
172 let range = range.intersect(TextRange::up_to(TextSize::of("..."))).unwrap_or(range);
174 // Override severity and mark as unused.
175 res.borrow_mut().push(
176 Diagnostic::hint(range, d.message())
177 .with_fixes(d.fixes(&sema, resolve))
178 .with_code(Some(d.code())),
181 .on::<hir::diagnostics::UnresolvedProcMacro, _>(|d| {
182 // Use more accurate position if available.
183 let display_range = d
185 .unwrap_or_else(|| sema.diagnostics_display_range(d.display_source()).range);
187 // FIXME: it would be nice to tell the user whether proc macros are currently disabled
189 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
191 .on::<hir::diagnostics::UnimplementedBuiltinMacro, _>(|d| {
192 let display_range = sema.diagnostics_display_range(d.display_source()).range;
194 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
196 // Only collect experimental diagnostics when they're enabled.
197 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
198 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
200 // Finalize the `DiagnosticSink` building process.
201 let mut sink = sink_builder
202 // Diagnostics not handled above get no fix and default treatment.
204 res.borrow_mut().push(
206 sema.diagnostics_display_range(d.display_source()).range,
209 .with_code(Some(d.code())),
213 let mut diags = Vec::new();
214 let internal_diagnostics = cfg!(test);
215 match sema.to_module_def(file_id) {
216 Some(m) => diags = m.diagnostics(db, &mut sink, internal_diagnostics),
218 sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(parse.tree().syntax()) });
224 let mut res = res.into_inner();
226 let ctx = DiagnosticsContext { config, sema, resolve };
230 AnyDiagnostic::UnresolvedModule(d) => unresolved_module::unresolved_module(&ctx, &d),
231 AnyDiagnostic::UnresolvedExternCrate(d) => unresolved_extern_crate::unresolved_extern_crate(&ctx, &d),
232 AnyDiagnostic::UnresolvedImport(d) => unresolved_import::unresolved_import(&ctx, &d),
233 AnyDiagnostic::UnresolvedMacroCall(d) => unresolved_macro_call::unresolved_macro_call(&ctx, &d),
234 AnyDiagnostic::MissingFields(d) => missing_fields::missing_fields(&ctx, &d),
236 AnyDiagnostic::InactiveCode(d) => match inactive_code::inactive_code(&ctx, &d) {
241 if let Some(code) = d.code {
242 if ctx.config.disabled.contains(code.as_str()) {
246 if ctx.config.disable_experimental && d.experimental {
255 fn diagnostic_with_fix<D: DiagnosticWithFixes>(
257 sema: &Semantics<RootDatabase>,
258 resolve: &AssistResolveStrategy,
260 Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message())
261 .with_fixes(d.fixes(sema, resolve))
262 .with_code(Some(d.code()))
265 fn warning_with_fix<D: DiagnosticWithFixes>(
267 sema: &Semantics<RootDatabase>,
268 resolve: &AssistResolveStrategy,
270 Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message())
271 .with_fixes(d.fixes(sema, resolve))
272 .with_code(Some(d.code()))
275 fn check_unnecessary_braces_in_use_statement(
276 acc: &mut Vec<Diagnostic>,
280 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
281 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
282 // If there is a comment inside the bracketed `use`,
283 // assume it is a commented out module path and don't show diagnostic.
284 if use_tree_list.has_inner_comment() {
288 let use_range = use_tree_list.syntax().text_range();
290 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
292 let to_replace = single_use_tree.syntax().text().to_string();
293 let mut edit_builder = TextEdit::builder();
294 edit_builder.delete(use_range);
295 edit_builder.insert(use_range.start(), to_replace);
296 edit_builder.finish()
300 Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
301 .with_fixes(Some(vec![fix(
303 "Remove unnecessary braces",
304 SourceChange::from_text_edit(file_id, edit),
313 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
314 single_use_tree: &ast::UseTree,
315 ) -> Option<TextEdit> {
316 let use_tree_list_node = single_use_tree.syntax().parent()?;
317 if single_use_tree.path()?.segment()?.self_token().is_some() {
318 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
319 let end = use_tree_list_node.text_range().end();
320 return Some(TextEdit::delete(TextRange::new(start, end)));
325 fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
326 let mut res = unresolved_fix(id, label, target);
327 res.source_change = Some(source_change);
331 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
332 assert!(!id.contains(' '));
334 id: AssistId(id, AssistKind::QuickFix),
335 label: Label::new(label),
344 use expect_test::Expect;
345 use hir::diagnostics::DiagnosticCode;
346 use ide_assists::AssistResolveStrategy;
347 use stdx::trim_indent;
348 use test_utils::{assert_eq_text, extract_annotations};
350 use crate::{fixture, DiagnosticsConfig};
352 /// Takes a multi-file input fixture with annotated cursor positions,
354 /// * a diagnostic is produced
355 /// * the first diagnostic fix trigger range touches the input cursor position
356 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
358 pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
359 check_nth_fix(0, ra_fixture_before, ra_fixture_after);
361 /// Takes a multi-file input fixture with annotated cursor positions,
363 /// * a diagnostic is produced
364 /// * every diagnostic fixes trigger range touches the input cursor position
365 /// * that the contents of the file containing the cursor match `after` after each diagnostic fix is applied
366 pub(crate) fn check_fixes(ra_fixture_before: &str, ra_fixtures_after: Vec<&str>) {
367 for (i, ra_fixture_after) in ra_fixtures_after.iter().enumerate() {
368 check_nth_fix(i, ra_fixture_before, ra_fixture_after)
373 fn check_nth_fix(nth: usize, ra_fixture_before: &str, ra_fixture_after: &str) {
374 let after = trim_indent(ra_fixture_after);
376 let (analysis, file_position) = fixture::position(ra_fixture_before);
377 let diagnostic = analysis
379 &DiagnosticsConfig::default(),
380 AssistResolveStrategy::All,
381 file_position.file_id,
386 let fix = &diagnostic.fixes.unwrap()[nth];
388 let source_change = fix.source_change.as_ref().unwrap();
389 let file_id = *source_change.source_file_edits.keys().next().unwrap();
390 let mut actual = analysis.file_text(file_id).unwrap().to_string();
392 for edit in source_change.source_file_edits.values() {
393 edit.apply(&mut actual);
398 assert_eq_text!(&after, &actual);
400 fix.target.contains_inclusive(file_position.offset),
401 "diagnostic fix range {:?} does not touch cursor position {:?}",
406 /// Checks that there's a diagnostic *without* fix at `$0`.
407 fn check_no_fix(ra_fixture: &str) {
408 let (analysis, file_position) = fixture::position(ra_fixture);
409 let diagnostic = analysis
411 &DiagnosticsConfig::default(),
412 AssistResolveStrategy::All,
413 file_position.file_id,
418 assert!(diagnostic.fixes.is_none(), "got a fix when none was expected: {:?}", diagnostic);
421 /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
422 /// apply to the file containing the cursor.
423 pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
424 let (analysis, files) = fixture::files(ra_fixture);
425 let diagnostics = files
427 .flat_map(|file_id| {
429 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
432 .collect::<Vec<_>>();
433 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
436 pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) {
437 let (analysis, file_id) = fixture::file(ra_fixture);
438 let diagnostics = analysis
439 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
441 expect.assert_debug_eq(&diagnostics)
445 pub(crate) fn check_diagnostics(ra_fixture: &str) {
446 check_diagnostics_with_inactive_code(ra_fixture, false)
450 pub(crate) fn check_diagnostics_with_inactive_code(ra_fixture: &str, with_inactive_code: bool) {
451 let (analysis, file_id) = fixture::file(ra_fixture);
452 let diagnostics = analysis
453 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
456 let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
457 let mut actual = diagnostics
459 .filter(|d| d.code != Some(DiagnosticCode("inactive-code")) || with_inactive_code)
460 .map(|d| (d.range, d.message))
461 .collect::<Vec<_>>();
462 actual.sort_by_key(|(range, _)| range.start());
463 assert_eq!(expected, actual);
467 fn range_mapping_out_of_macros() {
468 // FIXME: this is very wrong, but somewhat tricky to fix.
475 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
478 let _x = id![Foo { a: $042 }];
481 pub struct Foo { pub a: i32, pub b: i32 }
488 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
491 let _x = id![Foo { a: 42 }];
494 pub struct Foo { pub a: i32, pub b: i32 }
500 fn test_check_unnecessary_braces_in_use_statement() {
501 check_no_diagnostics(
514 check_no_diagnostics(
572 mod a { mod c {} mod d { mod e {} } }
573 use a::{c, d::{e$0}};
576 mod a { mod c {} mod d { mod e {} } }
583 fn test_disabled_diagnostics() {
584 let mut config = DiagnosticsConfig::default();
585 config.disabled.insert("unresolved-module".into());
587 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
590 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
591 assert!(diagnostics.is_empty());
593 let diagnostics = analysis
594 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
596 assert!(!diagnostics.is_empty());
600 fn unlinked_file_prepend_first_item() {
601 cov_mark::check!(unlinked_file_prepend_before_first_item);
602 // Only tests the first one for `pub mod` since the rest are the same
626 fn unlinked_file_append_mod() {
627 cov_mark::check!(unlinked_file_append_to_existing_mods);
639 mod preexisting_bottom;)
653 mod preexisting_bottom;)
659 fn unlinked_file_insert_in_empty_file() {
660 cov_mark::check!(unlinked_file_empty_file);
674 fn unlinked_file_old_style_modrs() {
692 fn unlinked_file_new_style_mod() {
708 fn unlinked_file_with_cfg_off() {
709 cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
723 fn unlinked_file_with_cfg_on() {
724 check_no_diagnostics(
736 fn break_outside_of_loop() {
740 //^^^^^ break outside of loop
746 fn no_such_field_diagnostics() {
749 struct S { foo: i32, bar: () }
753 //^ Missing structure fields:
757 //^^^^^^^ no such field
765 fn no_such_field_with_feature_flag_diagnostics() {
768 //- /lib.rs crate:foo cfg:feature=foo
771 #[cfg(feature = "foo")]
776 #[cfg(feature = "foo")]
777 pub(crate) fn new(my_val: usize, bar: bool) -> Self {
780 #[cfg(not(feature = "foo"))]
781 pub(crate) fn new(my_val: usize, _bar: bool) -> Self {
790 fn no_such_field_enum_with_feature_flag_diagnostics() {
793 //- /lib.rs crate:foo cfg:feature=foo
795 #[cfg(not(feature = "foo"))]
797 #[cfg(feature = "foo")]
813 fn no_such_field_with_feature_flag_diagnostics_on_struct_lit() {
816 //- /lib.rs crate:foo cfg:feature=foo
818 #[cfg(feature = "foo")]
820 #[cfg(not(feature = "foo"))]
825 #[cfg(feature = "foo")]
826 fn new(foo: u32) -> Self {
829 #[cfg(not(feature = "foo"))]
830 fn new(bar: u32) -> Self {
833 fn new2(bar: u32) -> Self {
834 #[cfg(feature = "foo")]
835 { Self { foo: bar } }
836 #[cfg(not(feature = "foo"))]
839 fn new2(val: u32) -> Self {
841 #[cfg(feature = "foo")]
843 #[cfg(not(feature = "foo"))]
853 fn no_such_field_with_type_macro() {
856 macro_rules! Type { () => { u32 }; }
857 struct Foo { bar: Type![] }
869 fn missing_unsafe_diagnostic_with_raw_ptr() {
873 let x = &5 as *const usize;
874 unsafe { let y = *x; }
876 } //^^ This operation is unsafe and requires an unsafe function or block
882 fn missing_unsafe_diagnostic_with_unsafe_call() {
888 unsafe fn unsafe_fn(&self) {
889 let x = &5 as *const usize;
894 unsafe fn unsafe_fn() {
895 let x = &5 as *const usize;
901 //^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
902 HasUnsafe.unsafe_fn();
903 //^^^^^^^^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
906 HasUnsafe.unsafe_fn();
914 fn missing_unsafe_diagnostic_with_static_mut() {
921 static mut STATIC_MUT: Ty = Ty { a: 0 };
924 let x = STATIC_MUT.a;
925 //^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
927 let x = STATIC_MUT.a;
935 fn no_missing_unsafe_diagnostic_with_safe_intrinsic() {
938 extern "rust-intrinsic" {
939 pub fn bitreverse(x: u32) -> u32; // Safe intrinsic
940 pub fn floorf32(x: f32) -> f32; // Unsafe intrinsic
944 let _ = bitreverse(12);
945 let _ = floorf32(12.0);
946 //^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
952 // Register the required standard library types to make the tests work
953 fn add_filter_map_with_find_next_boilerplate(body: &str) -> String {
955 //- /main.rs crate:main deps:core
956 use core::iter::Iterator;
957 use core::option::Option::{self, Some, None};
960 //- /core/lib.rs crate:core
962 pub enum Option<T> { Some(T), None }
967 fn filter_map<B, F>(self, f: F) -> FilterMap where F: FnMut(Self::Item) -> Option<B> { FilterMap }
968 fn next(&mut self) -> Option<Self::Item>;
970 pub struct FilterMap {}
971 impl Iterator for FilterMap {
973 fn next(&mut self) -> i32 { 7 }
977 format!("{}{}{}", prefix, body, suffix)
981 fn replace_filter_map_next_with_find_map2() {
982 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
985 let m = [1, 2, 3].iter().filter_map(|x| if *x == 2 { Some (4) } else { None }).next();
986 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ replace filter_map(..).next() with find_map(..)
993 fn replace_filter_map_next_with_find_map_no_diagnostic_without_next() {
994 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
999 .filter_map(|x| if *x == 2 { Some (4) } else { None })
1007 fn replace_filter_map_next_with_find_map_no_diagnostic_with_intervening_methods() {
1008 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1013 .filter_map(|x| if *x == 2 { Some (4) } else { None })
1022 fn replace_filter_map_next_with_find_map_no_diagnostic_if_not_in_chain() {
1023 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1028 .filter_map(|x| if *x == 2 { Some (4) } else { None });
1036 fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
1039 struct S { foo: i32, bar: () }
1040 fn baz(s: S) -> i32 {
1042 S { foo, .. } => foo,
1050 fn missing_record_pat_field_box() {
1053 struct S { s: Box<u32> }
1055 let S { box s } = a;
1062 fn missing_record_pat_field_ref() {
1067 let S { ref s } = a;
1074 fn simple_free_fn_zero() {
1079 //^^^^^^^ Expected 0 arguments, found 1
1092 fn simple_free_fn_one() {
1097 //^^^^^ Expected 1 argument, found 0
1114 impl S { fn method(&self) {} }
1118 } //^^^^^^^^^^^ Expected 1 argument, found 0
1125 impl S { fn method(&self) {} }
1136 fn method_with_arg() {
1140 impl S { fn method(&self, arg: u8) {} }
1144 } //^^^^^^^^^^ Expected 1 argument, found 0
1151 impl S { fn method(&self, arg: u8) {} }
1162 fn method_unknown_receiver() {
1163 // note: this is incorrect code, so there might be errors on this in the
1164 // future, but we shouldn't emit an argument count diagnostic here
1167 trait Foo { fn method(&self, arg: usize) {} }
1181 struct Tup(u8, u16);
1184 } //^^^^^^ Expected 2 arguments, found 1
1193 enum En { Variant(u8, u16), }
1196 } //^^^^^^^^^^^^^^ Expected 2 arguments, found 1
1202 fn enum_variant_type_macro() {
1215 //^^^^^^^^^^^^^^ Expected 1 argument, found 2
1217 //^^^^^^^^^^ Expected 1 argument, found 0
1229 fn fixed(fixed: u8);
1230 fn varargs(fixed: u8, ...);
1238 //^^^^^^^^^^^ Expected 1 argument, found 2
1251 fn arg_count_lambda() {
1257 //^^^ Expected 1 argument, found 0
1260 //^^^^^^^^^ Expected 1 argument, found 2
1267 fn cfgd_out_call_arguments() {
1270 struct C(#[cfg(FALSE)] ());
1283 C::new().method(#[cfg(FALSE)] 0);
1290 fn cfgd_out_fn_params() {
1293 fn foo(#[cfg(NEVER)] x: ()) {}
1298 fn method(#[cfg(NEVER)] self) {}
1299 fn method2(#[cfg(NEVER)] self, arg: u8) {}
1300 fn method3(self, #[cfg(NEVER)] arg: u8) {}
1304 fn fixed(fixed: u8, #[cfg(NEVER)] ...);
1305 fn varargs(#[cfg(not(NEVER))] ...);
1324 fn missing_semicolon() {
1327 fn test() -> i32 { 123; }
1328 //^^^ Remove this semicolon
1334 fn import_extern_crate_clash_with_inner_item() {
1335 // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
1339 //- /lib.rs crate:lib deps:jwt
1342 use permissions::jwt;
1346 jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
1351 pub struct Claims {}
1354 //- /jwt/lib.rs crate:jwt
1364 pub(super) mod match_check_tests {
1365 use crate::diagnostics::tests::check_diagnostics;
1373 //^^ Missing match arm
1375 //^^^^ Missing match arm
1377 match () { _ => (), }
1378 match () { () => (), }
1379 match (()) { (()) => (), }
1386 fn tuple_of_two_empty_tuple() {
1391 //^^^^^^^^ Missing match arm
1393 match ((), ()) { ((), ()) => (), }
1405 //^^^^^ Missing match arm
1406 match false { true => (), }
1407 //^^^^^ Missing match arm
1408 match (false, true) {}
1409 //^^^^^^^^^^^^^ Missing match arm
1410 match (false, true) { (true, true) => (), }
1411 //^^^^^^^^^^^^^ Missing match arm
1412 match (false, true) {
1413 //^^^^^^^^^^^^^ Missing match arm
1414 (false, true) => (),
1415 (false, false) => (),
1416 (true, false) => (),
1418 match (false, true) { (true, _x) => (), }
1419 //^^^^^^^^^^^^^ Missing match arm
1421 match false { true => (), false => (), }
1422 match (false, true) {
1424 (true, false) => (),
1427 match (false, true) {
1429 (true, false) => (),
1430 (false, true) => (),
1431 (false, false) => (),
1433 match (false, true) {
1435 (false, true) => (),
1436 (false, false) => (),
1438 match (false, true, false) {
1442 match (false, true, false) {
1446 match (false, true, false) { (..) => (), }
1453 fn tuple_of_tuple_and_bools() {
1457 match (false, ((), false)) {}
1458 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1459 match (false, ((), false)) { (true, ((), true)) => (), }
1460 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1461 match (false, ((), false)) { (true, _) => (), }
1462 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1464 match (false, ((), false)) {
1465 (true, ((), true)) => (),
1466 (true, ((), false)) => (),
1467 (false, ((), true)) => (),
1468 (false, ((), false)) => (),
1470 match (false, ((), false)) {
1471 (true, ((), true)) => (),
1472 (true, ((), false)) => (),
1484 enum Either { A, B, }
1488 //^^^^^^^^^ Missing match arm
1489 match Either::B { Either::A => (), }
1490 //^^^^^^^^^ Missing match arm
1493 //^^^^^^^^^^ Missing match arm
1498 Either::A => (), Either::B => (),
1501 Either::A => (), Either::B => (),
1509 fn enum_containing_bool() {
1512 enum Either { A(bool), B }
1516 //^^^^^^^^^ Missing match arm
1518 //^^^^^^^^^ Missing match arm
1519 Either::A(true) => (), Either::B => ()
1523 Either::A(true) => (),
1524 Either::A(false) => (),
1542 fn enum_different_sizes() {
1545 enum Either { A(bool), B(bool, bool) }
1548 match Either::A(false) {
1549 //^^^^^^^^^^^^^^^^ Missing match arm
1551 Either::B(false, _) => (),
1554 match Either::A(false) {
1556 Either::B(true, _) => (),
1557 Either::B(false, _) => (),
1559 match Either::A(false) {
1560 Either::A(true) | Either::A(false) => (),
1561 Either::B(true, _) => (),
1562 Either::B(false, _) => (),
1570 fn tuple_of_enum_no_diagnostic() {
1573 enum Either { A(bool), B(bool, bool) }
1574 enum Either2 { C, D }
1577 match (Either::A(false), Either2::C) {
1578 (Either::A(true), _) | (Either::A(false), _) => (),
1579 (Either::B(true, _), Either2::C) => (),
1580 (Either::B(false, _), Either2::C) => (),
1581 (Either::B(_, _), Either2::D) => (),
1589 fn or_pattern_no_diagnostic() {
1595 match (Either::A, Either::B) {
1596 (Either::A | Either::B, _) => (),
1603 fn mismatched_types() {
1604 // Match statements with arms that don't match the
1605 // expression pattern do not fire this diagnostic.
1608 enum Either { A, B }
1609 enum Either2 { C, D }
1614 // ^^^^^^^^^^ Internal: match check bailed out
1617 match (true, false) {
1618 (true, false, true) => (),
1619 // ^^^^^^^^^^^^^^^^^^^ Internal: match check bailed out
1622 match (true, false) { (true,) => {} }
1623 // ^^^^^^^ Internal: match check bailed out
1624 match (0) { () => () }
1625 // ^^ Internal: match check bailed out
1626 match Unresolved::Bar { Unresolved::Baz => () }
1633 fn mismatched_types_in_or_patterns() {
1637 match false { true | () => {} }
1638 // ^^^^^^^^^ Internal: match check bailed out
1639 match (false,) { (true | (),) => {} }
1640 // ^^^^^^^^^^^^ Internal: match check bailed out
1647 fn malformed_match_arm_tuple_enum_missing_pattern() {
1648 // We are testing to be sure we don't panic here when the match
1649 // arm `Either::B` is missing its pattern.
1652 enum Either { A, B(u32) }
1665 fn malformed_match_arm_extra_fields() {
1668 enum A { B(isize, isize), C }
1671 A::B(_, _, _) => (),
1672 // ^^^^^^^^^^^^^ Internal: match check bailed out
1676 // ^^^^^^^ Internal: match check bailed out
1684 fn expr_diverges() {
1687 enum Either { A, B }
1692 // ^^^^^^^^^ Internal: match check bailed out
1697 // ^^^^^^^^^ Internal: match check bailed out
1699 match loop { break Foo::A } {
1700 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1703 match loop { break Foo::A } {
1713 fn expr_partially_diverges() {
1716 enum Either<T> { A(T), B }
1718 fn foo() -> Either<!> { Either::B }
1721 Either::A(val) => val,
1733 enum Either { A { foo: bool }, B }
1736 let a = Either::A { foo: true };
1738 //^ Missing match arm
1739 match a { Either::A { foo: true } => () }
1740 //^ Missing match arm
1742 Either::A { } => (),
1743 //^^^^^^^^^ Missing structure fields:
1748 //^ Missing match arm
1749 Either::A { } => (),
1750 } //^^^^^^^^^ Missing structure fields:
1754 Either::A { foo: true } => (),
1755 Either::A { foo: false } => (),
1759 Either::A { foo: _ } => (),
1768 fn enum_record_fields_out_of_order() {
1772 A { foo: bool, bar: () },
1777 let a = Either::A { foo: true, bar: () };
1779 //^ Missing match arm
1780 Either::A { bar: (), foo: false } => (),
1781 Either::A { foo: true, bar: () } => (),
1785 Either::A { bar: (), foo: false } => (),
1786 Either::A { foo: true, bar: () } => (),
1795 fn enum_record_ellipsis() {
1799 A { foo: bool, bar: bool },
1806 //^ Missing match arm
1807 Either::A { foo: true, .. } => (),
1811 //^ Missing match arm
1812 Either::A { .. } => (),
1816 Either::A { foo: true, .. } => (),
1817 Either::A { foo: false, .. } => (),
1822 Either::A { .. } => (),
1831 fn enum_tuple_partial_ellipsis() {
1835 A(bool, bool, bool, bool),
1841 //^^^^^^^^^ Missing match arm
1842 Either::A(true, .., true) => (),
1843 Either::A(true, .., false) => (),
1844 Either::A(false, .., false) => (),
1848 //^^^^^^^^^ Missing match arm
1849 Either::A(true, .., true) => (),
1850 Either::A(true, .., false) => (),
1851 Either::A(.., true) => (),
1856 Either::A(true, .., true) => (),
1857 Either::A(true, .., false) => (),
1858 Either::A(false, .., true) => (),
1859 Either::A(false, .., false) => (),
1863 Either::A(true, .., true) => (),
1864 Either::A(true, .., false) => (),
1865 Either::A(.., true) => (),
1866 Either::A(.., false) => (),
1880 fn enum_(never: Never) {
1883 fn enum_ref(never: &Never) {
1885 //^^^^^ Missing match arm
1898 enum Option<T> { Some(T), None }
1901 // `Never` is deliberately not defined so that it's an uninferred type.
1902 match Option::<Never>::None {
1904 Some(never) => match never {},
1905 // ^^^^^^^^^^^ Internal: match check bailed out
1907 match Option::<Never>::None {
1908 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1909 Option::Some(_never) => {},
1917 fn tuple_of_bools_with_ellipsis_at_end_missing_arm() {
1921 match (false, true, false) {
1922 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1930 fn tuple_of_bools_with_ellipsis_at_beginning_missing_arm() {
1934 match (false, true, false) {
1935 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1943 fn tuple_of_bools_with_ellipsis_in_middle_missing_arm() {
1947 match (false, true, false) {
1948 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1949 (true, .., false) => (),
1956 fn record_struct() {
1958 r#"struct Foo { a: bool }
1961 //^ Missing match arm
1962 match f { Foo { a: true } => () }
1963 //^ Missing match arm
1964 match &f { Foo { a: true } => () }
1965 //^^ Missing match arm
1966 match f { Foo { a: _ } => () }
1968 Foo { a: true } => (),
1969 Foo { a: false } => (),
1972 Foo { a: true } => (),
1973 Foo { a: false } => (),
1983 r#"struct Foo(bool);
1986 //^ Missing match arm
1987 match f { Foo(true) => () }
1988 //^ Missing match arm
2004 //^ Missing match arm
2005 match f { Foo => () }
2012 fn record_struct_ellipsis() {
2014 r#"struct Foo { foo: bool, bar: bool }
2016 match f { Foo { foo: true, .. } => () }
2017 //^ Missing match arm
2019 //^ Missing match arm
2020 Foo { foo: true, .. } => (),
2021 Foo { bar: false, .. } => ()
2023 match f { Foo { .. } => () }
2025 Foo { foo: true, .. } => (),
2026 Foo { foo: false, .. } => ()
2038 enum Either { A(bool), B }
2040 //^^^^^^^^^ Missing match arm
2041 Either::A(true | false) => (),
2049 fn no_panic_at_unimplemented_subpattern_type() {
2054 match v { S{ a } => {} }
2055 match v { S{ a: _x } => {} }
2056 match v { S{ a: 'a' } => {} }
2057 //^^^^^^^^^^^ Internal: match check bailed out
2058 match v { S{..} => {} }
2061 //^ Missing match arm
2076 match true { _x @ true => {} }
2077 //^^^^ Missing match arm
2084 fn binding_ref_has_correct_type() {
2085 // Asserts `PatKind::Binding(ref _x): bool`, not &bool.
2086 // If that's not true match checking will panic with "incompatible constructors"
2087 // FIXME: make facilities to test this directly like `tests::check_infer(..)`
2092 // FIXME: this should not bail out but current behavior is such as the old algorithm.
2093 // ExprValidator::validate_match(..) checks types of top level patterns incorrecly.
2096 // ^^^^^^ Internal: match check bailed out
2109 fn enum_non_exhaustive() {
2112 //- /lib.rs crate:lib
2116 match E::A { _ => {} }
2126 //- /main.rs crate:main deps:lib
2129 match E::A { _ => {} }
2131 //^^^^ Missing match arm
2136 //^^^^ Missing match arm
2155 //^^^^ Missing match arm
2165 fn pattern_type_is_of_substitution() {
2166 cov_mark::check!(match_check_wildcard_expanded_to_substitutions);
2181 fn record_struct_no_such_field() {
2186 match f { Foo { bar } => () }
2187 // ^^^^^^^^^^^ Internal: match check bailed out
2194 fn match_ergonomics_issue_9095() {
2197 enum Foo<T> { A(T) }
2199 match &Foo::A(true) {
2208 mod false_negatives {
2209 //! The implementation of match checking here is a work in progress. As we roll this out, we
2210 //! prefer false negatives to false positives (ideally there would be no false positives). This
2211 //! test module should document known false negatives. Eventually we will have a complete
2212 //! implementation of match checking and this module will be empty.
2214 //! The reasons for documenting known false negatives:
2216 //! 1. It acts as a backlog of work that can be done to improve the behavior of the system.
2217 //! 2. It ensures the code doesn't panic when handling these cases.
2222 // We don't currently check integer exhaustiveness.
2228 // ^^ Internal: match check bailed out
2237 fn reference_patterns_at_top_level() {
2243 // ^^^^^ Internal: match check bailed out
2251 fn reference_patterns_in_fields() {
2257 // ^^^^^^^ Internal: match check bailed out
2261 // ^^^^^^^^ Internal: match check bailed out
2271 mod decl_check_tests {
2272 use crate::diagnostics::tests::check_diagnostics;
2275 fn incorrect_function_name() {
2278 fn NonSnakeCaseName() {}
2279 // ^^^^^^^^^^^^^^^^ Function `NonSnakeCaseName` should have snake_case name, e.g. `non_snake_case_name`
2285 fn incorrect_function_params() {
2288 fn foo(SomeParam: u8) {}
2289 // ^^^^^^^^^ Parameter `SomeParam` should have snake_case name, e.g. `some_param`
2291 fn foo2(ok_param: &str, CAPS_PARAM: u8) {}
2292 // ^^^^^^^^^^ Parameter `CAPS_PARAM` should have snake_case name, e.g. `caps_param`
2298 fn incorrect_variable_names() {
2302 let SOME_VALUE = 10;
2303 // ^^^^^^^^^^ Variable `SOME_VALUE` should have snake_case name, e.g. `some_value`
2304 let AnotherValue = 20;
2305 // ^^^^^^^^^^^^ Variable `AnotherValue` should have snake_case name, e.g. `another_value`
2312 fn incorrect_struct_names() {
2315 struct non_camel_case_name {}
2316 // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName`
2318 struct SCREAMING_CASE {}
2319 // ^^^^^^^^^^^^^^ Structure `SCREAMING_CASE` should have CamelCase name, e.g. `ScreamingCase`
2325 fn no_diagnostic_for_camel_cased_acronyms_in_struct_name() {
2334 fn incorrect_struct_field() {
2337 struct SomeStruct { SomeField: u8 }
2338 // ^^^^^^^^^ Field `SomeField` should have snake_case name, e.g. `some_field`
2344 fn incorrect_enum_names() {
2347 enum some_enum { Val(u8) }
2348 // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum`
2351 // ^^^^^^^^^ Enum `SOME_ENUM` should have CamelCase name, e.g. `SomeEnum`
2357 fn no_diagnostic_for_camel_cased_acronyms_in_enum_name() {
2366 fn incorrect_enum_variant_name() {
2369 enum SomeEnum { SOME_VARIANT(u8) }
2370 // ^^^^^^^^^^^^ Variant `SOME_VARIANT` should have CamelCase name, e.g. `SomeVariant`
2376 fn incorrect_const_name() {
2379 const some_weird_const: u8 = 10;
2380 // ^^^^^^^^^^^^^^^^ Constant `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2386 fn incorrect_static_name() {
2389 static some_weird_const: u8 = 10;
2390 // ^^^^^^^^^^^^^^^^ Static variable `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2396 fn fn_inside_impl_struct() {
2400 // ^^^^^^^^^^ Structure `someStruct` should have CamelCase name, e.g. `SomeStruct`
2403 fn SomeFunc(&self) {
2404 // ^^^^^^^^ Function `SomeFunc` should have snake_case name, e.g. `some_func`
2405 let WHY_VAR_IS_CAPS = 10;
2406 // ^^^^^^^^^^^^^^^ Variable `WHY_VAR_IS_CAPS` should have snake_case name, e.g. `why_var_is_caps`
2414 fn no_diagnostic_for_enum_varinats() {
2417 enum Option { Some, None }
2420 match Option::None {
2433 enum Option { Some, None }
2436 match Option::None {
2437 SOME_VAR @ None => (),
2438 // ^^^^^^^^ Variable `SOME_VAR` should have snake_case name, e.g. `some_var`
2447 fn allow_attributes() {
2450 #[allow(non_snake_case)]
2451 fn NonSnakeCaseName(SOME_VAR: u8) -> u8{
2452 // cov_flags generated output from elsewhere in this file
2455 static lower_case: u8;
2458 let OtherVar = SOME_VAR + 1;
2462 #[allow(nonstandard_style)]
2463 mod CheckNonstandardStyle {
2464 fn HiImABadFnName() {}
2469 fn HiImABadFnName() {}
2473 #![allow(non_snake_case)]
2474 fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {}
2477 #[allow(non_snake_case, non_camel_case_types)]
2478 pub struct some_type {
2483 #[allow(non_upper_case_globals)]
2484 pub const some_const: u8 = 10;
2486 #[allow(non_upper_case_globals)]
2487 pub static SomeStatic: u8 = 10;
2493 fn allow_attributes_crate_attr() {
2496 #![allow(non_snake_case)]
2499 fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {}
2507 fn bug_trait_inside_fn() {
2509 // This is broken, and in fact, should not even be looked at by this
2510 // lint in the first place. There's weird stuff going on in the
2511 // collection phase.
2512 // It's currently being brought in by:
2513 // * validate_func on `a` recursing into modules
2514 // * then it finds the trait and then the function while iterating
2516 // * then validate_func is called on Dirty
2517 // * ... which then proceeds to look at some unknown module taking no
2518 // attrs from either the impl or the fn a, and then finally to the root
2521 // It should find the attribute on the trait, but it *doesn't even see
2522 // the trait* as far as I can tell.
2530 // this comes out of bitflags, mostly
2531 #[allow(non_snake_case)]
2533 const HiImAlsoBad: u8 = 2;
2535 fn Dirty(&self) -> bool {
2548 fn bug_traits_arent_checked() {
2549 // FIXME: Traits and functions in traits aren't currently checked by
2550 // r-a, even though rustc will complain about them.
2554 // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait`
2556 // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function`
2558 // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function`
2565 fn ignores_extern_items() {
2566 cov_mark::check!(extern_func_incorrect_case_ignored);
2567 cov_mark::check!(extern_static_incorrect_case_ignored);
2571 fn NonSnakeCaseName(SOME_VAR: u8) -> u8;
2572 pub static SomeStatic: u8 = 10;
2579 fn infinite_loop_inner_items() {
2591 #[test] // Issue #8809.
2592 fn parenthesized_parameter() {
2593 check_diagnostics(r#"fn f((O): _) {}"#)