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;
11 mod unresolved_proc_macro;
20 use std::cell::RefCell;
23 diagnostics::{AnyDiagnostic, Diagnostic as _, DiagnosticCode, DiagnosticSinkBuilder},
26 use ide_assists::AssistResolveStrategy;
27 use ide_db::{base_db::SourceDatabase, RootDatabase};
28 use itertools::Itertools;
29 use rustc_hash::FxHashSet;
32 SyntaxNode, SyntaxNodePtr, TextRange, TextSize,
34 use text_edit::TextEdit;
35 use unlinked_file::UnlinkedFile;
37 use crate::{Assist, AssistId, AssistKind, FileId, Label, SourceChange};
39 use self::fixes::DiagnosticWithFixes;
42 pub struct Diagnostic {
43 // pub name: Option<String>,
46 pub severity: Severity,
47 pub fixes: Option<Vec<Assist>>,
49 pub code: Option<DiagnosticCode>,
50 pub experimental: bool,
54 fn new(code: &'static str, message: impl Into<String>, range: TextRange) -> Diagnostic {
55 let message = message.into();
56 let code = Some(DiagnosticCode(code));
60 severity: Severity::Error,
68 fn experimental(mut self) -> Diagnostic {
69 self.experimental = true;
73 fn severity(mut self, severity: Severity) -> Diagnostic {
74 self.severity = severity;
78 fn error(range: TextRange, message: String) -> Self {
82 severity: Severity::Error,
90 fn hint(range: TextRange, message: String) -> Self {
94 severity: Severity::WeakWarning,
102 fn with_fixes(self, fixes: Option<Vec<Assist>>) -> Self {
103 Self { fixes, ..self }
106 fn with_unused(self, unused: bool) -> Self {
107 Self { unused, ..self }
110 fn with_code(self, code: Option<DiagnosticCode>) -> Self {
111 Self { code, ..self }
115 #[derive(Debug, Copy, Clone)]
121 #[derive(Default, Debug, Clone)]
122 pub struct DiagnosticsConfig {
123 pub disable_experimental: bool,
124 pub disabled: FxHashSet<String>,
127 struct DiagnosticsContext<'a> {
128 config: &'a DiagnosticsConfig,
129 sema: Semantics<'a, RootDatabase>,
131 resolve: &'a AssistResolveStrategy,
134 pub(crate) fn diagnostics(
136 config: &DiagnosticsConfig,
137 resolve: &AssistResolveStrategy,
139 ) -> Vec<Diagnostic> {
140 let _p = profile::span("diagnostics");
141 let sema = Semantics::new(db);
142 let parse = db.parse(file_id);
143 let mut res = Vec::new();
145 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
151 .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
154 for node in parse.tree().syntax().descendants() {
155 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
156 field_shorthand::check(&mut res, file_id, &node);
158 let res = RefCell::new(res);
159 let sink_builder = DiagnosticSinkBuilder::new()
160 .on::<hir::diagnostics::MissingOkOrSomeInTailExpr, _>(|d| {
161 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
163 .on::<hir::diagnostics::NoSuchField, _>(|d| {
164 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
166 .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| {
167 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
169 .on::<hir::diagnostics::IncorrectCase, _>(|d| {
170 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
172 .on::<hir::diagnostics::ReplaceFilterMapNextWithFindMap, _>(|d| {
173 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
175 .on::<UnlinkedFile, _>(|d| {
176 // Limit diagnostic to the first few characters in the file. This matches how VS Code
177 // renders it with the full span, but on other editors, and is less invasive.
178 let range = sema.diagnostics_display_range(d.display_source()).range;
179 let range = range.intersect(TextRange::up_to(TextSize::of("..."))).unwrap_or(range);
181 // Override severity and mark as unused.
182 res.borrow_mut().push(
183 Diagnostic::hint(range, d.message())
184 .with_fixes(d.fixes(&sema, resolve))
185 .with_code(Some(d.code())),
188 .on::<hir::diagnostics::UnimplementedBuiltinMacro, _>(|d| {
189 let display_range = sema.diagnostics_display_range(d.display_source()).range;
191 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
193 // Only collect experimental diagnostics when they're enabled.
194 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
195 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
197 // Finalize the `DiagnosticSink` building process.
198 let mut sink = sink_builder
199 // Diagnostics not handled above get no fix and default treatment.
201 res.borrow_mut().push(
203 sema.diagnostics_display_range(d.display_source()).range,
206 .with_code(Some(d.code())),
210 let mut diags = Vec::new();
211 let internal_diagnostics = cfg!(test);
212 match sema.to_module_def(file_id) {
213 Some(m) => diags = m.diagnostics(db, &mut sink, internal_diagnostics),
215 sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(parse.tree().syntax()) });
221 let mut res = res.into_inner();
223 let ctx = DiagnosticsContext { config, sema, resolve };
227 AnyDiagnostic::UnresolvedModule(d) => unresolved_module::unresolved_module(&ctx, &d),
228 AnyDiagnostic::UnresolvedExternCrate(d) => unresolved_extern_crate::unresolved_extern_crate(&ctx, &d),
229 AnyDiagnostic::UnresolvedImport(d) => unresolved_import::unresolved_import(&ctx, &d),
230 AnyDiagnostic::UnresolvedMacroCall(d) => unresolved_macro_call::unresolved_macro_call(&ctx, &d),
231 AnyDiagnostic::UnresolvedProcMacro(d) => unresolved_proc_macro::unresolved_proc_macro(&ctx, &d),
232 AnyDiagnostic::MissingFields(d) => missing_fields::missing_fields(&ctx, &d),
233 AnyDiagnostic::MacroError(d) => macro_error::macro_error(&ctx, &d),
235 AnyDiagnostic::InactiveCode(d) => match inactive_code::inactive_code(&ctx, &d) {
240 if let Some(code) = d.code {
241 if ctx.config.disabled.contains(code.as_str()) {
245 if ctx.config.disable_experimental && d.experimental {
254 fn diagnostic_with_fix<D: DiagnosticWithFixes>(
256 sema: &Semantics<RootDatabase>,
257 resolve: &AssistResolveStrategy,
259 Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message())
260 .with_fixes(d.fixes(sema, resolve))
261 .with_code(Some(d.code()))
264 fn warning_with_fix<D: DiagnosticWithFixes>(
266 sema: &Semantics<RootDatabase>,
267 resolve: &AssistResolveStrategy,
269 Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message())
270 .with_fixes(d.fixes(sema, resolve))
271 .with_code(Some(d.code()))
274 fn check_unnecessary_braces_in_use_statement(
275 acc: &mut Vec<Diagnostic>,
279 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
280 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
281 // If there is a comment inside the bracketed `use`,
282 // assume it is a commented out module path and don't show diagnostic.
283 if use_tree_list.has_inner_comment() {
287 let use_range = use_tree_list.syntax().text_range();
289 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
291 let to_replace = single_use_tree.syntax().text().to_string();
292 let mut edit_builder = TextEdit::builder();
293 edit_builder.delete(use_range);
294 edit_builder.insert(use_range.start(), to_replace);
295 edit_builder.finish()
299 Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
300 .with_fixes(Some(vec![fix(
302 "Remove unnecessary braces",
303 SourceChange::from_text_edit(file_id, edit),
312 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
313 single_use_tree: &ast::UseTree,
314 ) -> Option<TextEdit> {
315 let use_tree_list_node = single_use_tree.syntax().parent()?;
316 if single_use_tree.path()?.segment()?.self_token().is_some() {
317 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
318 let end = use_tree_list_node.text_range().end();
319 return Some(TextEdit::delete(TextRange::new(start, end)));
324 fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
325 let mut res = unresolved_fix(id, label, target);
326 res.source_change = Some(source_change);
330 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
331 assert!(!id.contains(' '));
333 id: AssistId(id, AssistKind::QuickFix),
334 label: Label::new(label),
343 use expect_test::Expect;
344 use ide_assists::AssistResolveStrategy;
345 use stdx::trim_indent;
346 use test_utils::{assert_eq_text, extract_annotations};
348 use crate::{fixture, DiagnosticsConfig};
350 /// Takes a multi-file input fixture with annotated cursor positions,
352 /// * a diagnostic is produced
353 /// * the first diagnostic fix trigger range touches the input cursor position
354 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
356 pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
357 check_nth_fix(0, ra_fixture_before, ra_fixture_after);
359 /// Takes a multi-file input fixture with annotated cursor positions,
361 /// * a diagnostic is produced
362 /// * every diagnostic fixes trigger range touches the input cursor position
363 /// * that the contents of the file containing the cursor match `after` after each diagnostic fix is applied
364 pub(crate) fn check_fixes(ra_fixture_before: &str, ra_fixtures_after: Vec<&str>) {
365 for (i, ra_fixture_after) in ra_fixtures_after.iter().enumerate() {
366 check_nth_fix(i, ra_fixture_before, ra_fixture_after)
371 fn check_nth_fix(nth: usize, ra_fixture_before: &str, ra_fixture_after: &str) {
372 let after = trim_indent(ra_fixture_after);
374 let (analysis, file_position) = fixture::position(ra_fixture_before);
375 let diagnostic = analysis
377 &DiagnosticsConfig::default(),
378 AssistResolveStrategy::All,
379 file_position.file_id,
384 let fix = &diagnostic.fixes.unwrap()[nth];
386 let source_change = fix.source_change.as_ref().unwrap();
387 let file_id = *source_change.source_file_edits.keys().next().unwrap();
388 let mut actual = analysis.file_text(file_id).unwrap().to_string();
390 for edit in source_change.source_file_edits.values() {
391 edit.apply(&mut actual);
396 assert_eq_text!(&after, &actual);
398 fix.target.contains_inclusive(file_position.offset),
399 "diagnostic fix range {:?} does not touch cursor position {:?}",
404 /// Checks that there's a diagnostic *without* fix at `$0`.
405 fn check_no_fix(ra_fixture: &str) {
406 let (analysis, file_position) = fixture::position(ra_fixture);
407 let diagnostic = analysis
409 &DiagnosticsConfig::default(),
410 AssistResolveStrategy::All,
411 file_position.file_id,
416 assert!(diagnostic.fixes.is_none(), "got a fix when none was expected: {:?}", diagnostic);
419 pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) {
420 let (analysis, file_id) = fixture::file(ra_fixture);
421 let diagnostics = analysis
422 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
424 expect.assert_debug_eq(&diagnostics)
428 pub(crate) fn check_diagnostics(ra_fixture: &str) {
429 let mut config = DiagnosticsConfig::default();
430 config.disabled.insert("inactive-code".to_string());
431 check_diagnostics_with_config(config, ra_fixture)
435 pub(crate) fn check_diagnostics_with_config(config: DiagnosticsConfig, ra_fixture: &str) {
436 let (analysis, files) = fixture::files(ra_fixture);
437 for file_id in files {
439 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
441 let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
443 diagnostics.into_iter().map(|d| (d.range, d.message)).collect::<Vec<_>>();
444 actual.sort_by_key(|(range, _)| range.start());
445 assert_eq!(expected, actual);
450 fn range_mapping_out_of_macros() {
451 // FIXME: this is very wrong, but somewhat tricky to fix.
458 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
461 let _x = id![Foo { a: $042 }];
464 pub struct Foo { pub a: i32, pub b: i32 }
471 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
474 let _x = id![Foo { a: 42 }];
477 pub struct Foo { pub a: i32, pub b: i32 }
483 fn test_check_unnecessary_braces_in_use_statement() {
555 mod a { mod c {} mod d { mod e {} } }
556 use a::{c, d::{e$0}};
559 mod a { mod c {} mod d { mod e {} } }
566 fn test_disabled_diagnostics() {
567 let mut config = DiagnosticsConfig::default();
568 config.disabled.insert("unresolved-module".into());
570 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
573 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
574 assert!(diagnostics.is_empty());
576 let diagnostics = analysis
577 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
579 assert!(!diagnostics.is_empty());
583 fn unlinked_file_prepend_first_item() {
584 cov_mark::check!(unlinked_file_prepend_before_first_item);
585 // Only tests the first one for `pub mod` since the rest are the same
609 fn unlinked_file_append_mod() {
610 cov_mark::check!(unlinked_file_append_to_existing_mods);
622 mod preexisting_bottom;)
636 mod preexisting_bottom;)
642 fn unlinked_file_insert_in_empty_file() {
643 cov_mark::check!(unlinked_file_empty_file);
657 fn unlinked_file_old_style_modrs() {
675 fn unlinked_file_new_style_mod() {
691 fn unlinked_file_with_cfg_off() {
692 cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
706 fn unlinked_file_with_cfg_on() {
719 fn break_outside_of_loop() {
723 //^^^^^ break outside of loop
729 fn no_such_field_diagnostics() {
732 struct S { foo: i32, bar: () }
736 //^ Missing structure fields:
740 //^^^^^^^ no such field
748 fn no_such_field_with_feature_flag_diagnostics() {
751 //- /lib.rs crate:foo cfg:feature=foo
754 #[cfg(feature = "foo")]
759 #[cfg(feature = "foo")]
760 pub(crate) fn new(my_val: usize, bar: bool) -> Self {
763 #[cfg(not(feature = "foo"))]
764 pub(crate) fn new(my_val: usize, _bar: bool) -> Self {
773 fn no_such_field_enum_with_feature_flag_diagnostics() {
776 //- /lib.rs crate:foo cfg:feature=foo
778 #[cfg(not(feature = "foo"))]
780 #[cfg(feature = "foo")]
796 fn no_such_field_with_feature_flag_diagnostics_on_struct_lit() {
799 //- /lib.rs crate:foo cfg:feature=foo
801 #[cfg(feature = "foo")]
803 #[cfg(not(feature = "foo"))]
808 #[cfg(feature = "foo")]
809 fn new(foo: u32) -> Self {
812 #[cfg(not(feature = "foo"))]
813 fn new(bar: u32) -> Self {
816 fn new2(bar: u32) -> Self {
817 #[cfg(feature = "foo")]
818 { Self { foo: bar } }
819 #[cfg(not(feature = "foo"))]
822 fn new2(val: u32) -> Self {
824 #[cfg(feature = "foo")]
826 #[cfg(not(feature = "foo"))]
836 fn no_such_field_with_type_macro() {
839 macro_rules! Type { () => { u32 }; }
840 struct Foo { bar: Type![] }
852 fn missing_unsafe_diagnostic_with_raw_ptr() {
856 let x = &5 as *const usize;
857 unsafe { let y = *x; }
859 } //^^ This operation is unsafe and requires an unsafe function or block
865 fn missing_unsafe_diagnostic_with_unsafe_call() {
871 unsafe fn unsafe_fn(&self) {
872 let x = &5 as *const usize;
877 unsafe fn unsafe_fn() {
878 let x = &5 as *const usize;
884 //^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
885 HasUnsafe.unsafe_fn();
886 //^^^^^^^^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
889 HasUnsafe.unsafe_fn();
897 fn missing_unsafe_diagnostic_with_static_mut() {
904 static mut STATIC_MUT: Ty = Ty { a: 0 };
907 let x = STATIC_MUT.a;
908 //^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
910 let x = STATIC_MUT.a;
918 fn no_missing_unsafe_diagnostic_with_safe_intrinsic() {
921 extern "rust-intrinsic" {
922 pub fn bitreverse(x: u32) -> u32; // Safe intrinsic
923 pub fn floorf32(x: f32) -> f32; // Unsafe intrinsic
927 let _ = bitreverse(12);
928 let _ = floorf32(12.0);
929 //^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
935 // Register the required standard library types to make the tests work
936 fn add_filter_map_with_find_next_boilerplate(body: &str) -> String {
938 //- /main.rs crate:main deps:core
939 use core::iter::Iterator;
940 use core::option::Option::{self, Some, None};
943 //- /core/lib.rs crate:core
945 pub enum Option<T> { Some(T), None }
950 fn filter_map<B, F>(self, f: F) -> FilterMap where F: FnMut(Self::Item) -> Option<B> { FilterMap }
951 fn next(&mut self) -> Option<Self::Item>;
953 pub struct FilterMap {}
954 impl Iterator for FilterMap {
956 fn next(&mut self) -> i32 { 7 }
960 format!("{}{}{}", prefix, body, suffix)
964 fn replace_filter_map_next_with_find_map2() {
965 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
968 let m = [1, 2, 3].iter().filter_map(|x| if *x == 2 { Some (4) } else { None }).next();
969 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ replace filter_map(..).next() with find_map(..)
976 fn replace_filter_map_next_with_find_map_no_diagnostic_without_next() {
977 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
982 .filter_map(|x| if *x == 2 { Some (4) } else { None })
990 fn replace_filter_map_next_with_find_map_no_diagnostic_with_intervening_methods() {
991 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
996 .filter_map(|x| if *x == 2 { Some (4) } else { None })
1005 fn replace_filter_map_next_with_find_map_no_diagnostic_if_not_in_chain() {
1006 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1011 .filter_map(|x| if *x == 2 { Some (4) } else { None });
1019 fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
1022 struct S { foo: i32, bar: () }
1023 fn baz(s: S) -> i32 {
1025 S { foo, .. } => foo,
1033 fn missing_record_pat_field_box() {
1036 struct S { s: Box<u32> }
1038 let S { box s } = a;
1045 fn missing_record_pat_field_ref() {
1050 let S { ref s } = a;
1057 fn simple_free_fn_zero() {
1062 //^^^^^^^ Expected 0 arguments, found 1
1075 fn simple_free_fn_one() {
1080 //^^^^^ Expected 1 argument, found 0
1097 impl S { fn method(&self) {} }
1101 } //^^^^^^^^^^^ Expected 1 argument, found 0
1108 impl S { fn method(&self) {} }
1119 fn method_with_arg() {
1123 impl S { fn method(&self, arg: u8) {} }
1127 } //^^^^^^^^^^ Expected 1 argument, found 0
1134 impl S { fn method(&self, arg: u8) {} }
1145 fn method_unknown_receiver() {
1146 // note: this is incorrect code, so there might be errors on this in the
1147 // future, but we shouldn't emit an argument count diagnostic here
1150 trait Foo { fn method(&self, arg: usize) {} }
1164 struct Tup(u8, u16);
1167 } //^^^^^^ Expected 2 arguments, found 1
1176 enum En { Variant(u8, u16), }
1179 } //^^^^^^^^^^^^^^ Expected 2 arguments, found 1
1185 fn enum_variant_type_macro() {
1198 //^^^^^^^^^^^^^^ Expected 1 argument, found 2
1200 //^^^^^^^^^^ Expected 1 argument, found 0
1212 fn fixed(fixed: u8);
1213 fn varargs(fixed: u8, ...);
1221 //^^^^^^^^^^^ Expected 1 argument, found 2
1234 fn arg_count_lambda() {
1240 //^^^ Expected 1 argument, found 0
1243 //^^^^^^^^^ Expected 1 argument, found 2
1250 fn cfgd_out_call_arguments() {
1253 struct C(#[cfg(FALSE)] ());
1266 C::new().method(#[cfg(FALSE)] 0);
1273 fn cfgd_out_fn_params() {
1276 fn foo(#[cfg(NEVER)] x: ()) {}
1281 fn method(#[cfg(NEVER)] self) {}
1282 fn method2(#[cfg(NEVER)] self, arg: u8) {}
1283 fn method3(self, #[cfg(NEVER)] arg: u8) {}
1287 fn fixed(fixed: u8, #[cfg(NEVER)] ...);
1288 fn varargs(#[cfg(not(NEVER))] ...);
1307 fn missing_semicolon() {
1310 fn test() -> i32 { 123; }
1311 //^^^ Remove this semicolon
1317 fn import_extern_crate_clash_with_inner_item() {
1318 // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
1322 //- /lib.rs crate:lib deps:jwt
1325 use permissions::jwt;
1329 jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
1334 pub struct Claims {}
1337 //- /jwt/lib.rs crate:jwt
1347 pub(super) mod match_check_tests {
1348 use crate::diagnostics::tests::check_diagnostics;
1356 //^^ Missing match arm
1358 //^^^^ Missing match arm
1360 match () { _ => (), }
1361 match () { () => (), }
1362 match (()) { (()) => (), }
1369 fn tuple_of_two_empty_tuple() {
1374 //^^^^^^^^ Missing match arm
1376 match ((), ()) { ((), ()) => (), }
1388 //^^^^^ Missing match arm
1389 match false { true => (), }
1390 //^^^^^ Missing match arm
1391 match (false, true) {}
1392 //^^^^^^^^^^^^^ Missing match arm
1393 match (false, true) { (true, true) => (), }
1394 //^^^^^^^^^^^^^ Missing match arm
1395 match (false, true) {
1396 //^^^^^^^^^^^^^ Missing match arm
1397 (false, true) => (),
1398 (false, false) => (),
1399 (true, false) => (),
1401 match (false, true) { (true, _x) => (), }
1402 //^^^^^^^^^^^^^ Missing match arm
1404 match false { true => (), false => (), }
1405 match (false, true) {
1407 (true, false) => (),
1410 match (false, true) {
1412 (true, false) => (),
1413 (false, true) => (),
1414 (false, false) => (),
1416 match (false, true) {
1418 (false, true) => (),
1419 (false, false) => (),
1421 match (false, true, false) {
1425 match (false, true, false) {
1429 match (false, true, false) { (..) => (), }
1436 fn tuple_of_tuple_and_bools() {
1440 match (false, ((), false)) {}
1441 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1442 match (false, ((), false)) { (true, ((), true)) => (), }
1443 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1444 match (false, ((), false)) { (true, _) => (), }
1445 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1447 match (false, ((), false)) {
1448 (true, ((), true)) => (),
1449 (true, ((), false)) => (),
1450 (false, ((), true)) => (),
1451 (false, ((), false)) => (),
1453 match (false, ((), false)) {
1454 (true, ((), true)) => (),
1455 (true, ((), false)) => (),
1467 enum Either { A, B, }
1471 //^^^^^^^^^ Missing match arm
1472 match Either::B { Either::A => (), }
1473 //^^^^^^^^^ Missing match arm
1476 //^^^^^^^^^^ Missing match arm
1481 Either::A => (), Either::B => (),
1484 Either::A => (), Either::B => (),
1492 fn enum_containing_bool() {
1495 enum Either { A(bool), B }
1499 //^^^^^^^^^ Missing match arm
1501 //^^^^^^^^^ Missing match arm
1502 Either::A(true) => (), Either::B => ()
1506 Either::A(true) => (),
1507 Either::A(false) => (),
1525 fn enum_different_sizes() {
1528 enum Either { A(bool), B(bool, bool) }
1531 match Either::A(false) {
1532 //^^^^^^^^^^^^^^^^ Missing match arm
1534 Either::B(false, _) => (),
1537 match Either::A(false) {
1539 Either::B(true, _) => (),
1540 Either::B(false, _) => (),
1542 match Either::A(false) {
1543 Either::A(true) | Either::A(false) => (),
1544 Either::B(true, _) => (),
1545 Either::B(false, _) => (),
1553 fn tuple_of_enum_no_diagnostic() {
1556 enum Either { A(bool), B(bool, bool) }
1557 enum Either2 { C, D }
1560 match (Either::A(false), Either2::C) {
1561 (Either::A(true), _) | (Either::A(false), _) => (),
1562 (Either::B(true, _), Either2::C) => (),
1563 (Either::B(false, _), Either2::C) => (),
1564 (Either::B(_, _), Either2::D) => (),
1572 fn or_pattern_no_diagnostic() {
1578 match (Either::A, Either::B) {
1579 (Either::A | Either::B, _) => (),
1586 fn mismatched_types() {
1587 // Match statements with arms that don't match the
1588 // expression pattern do not fire this diagnostic.
1591 enum Either { A, B }
1592 enum Either2 { C, D }
1597 // ^^^^^^^^^^ Internal: match check bailed out
1600 match (true, false) {
1601 (true, false, true) => (),
1602 // ^^^^^^^^^^^^^^^^^^^ Internal: match check bailed out
1605 match (true, false) { (true,) => {} }
1606 // ^^^^^^^ Internal: match check bailed out
1607 match (0) { () => () }
1608 // ^^ Internal: match check bailed out
1609 match Unresolved::Bar { Unresolved::Baz => () }
1616 fn mismatched_types_in_or_patterns() {
1620 match false { true | () => {} }
1621 // ^^^^^^^^^ Internal: match check bailed out
1622 match (false,) { (true | (),) => {} }
1623 // ^^^^^^^^^^^^ Internal: match check bailed out
1630 fn malformed_match_arm_tuple_enum_missing_pattern() {
1631 // We are testing to be sure we don't panic here when the match
1632 // arm `Either::B` is missing its pattern.
1635 enum Either { A, B(u32) }
1648 fn malformed_match_arm_extra_fields() {
1651 enum A { B(isize, isize), C }
1654 A::B(_, _, _) => (),
1655 // ^^^^^^^^^^^^^ Internal: match check bailed out
1659 // ^^^^^^^ Internal: match check bailed out
1667 fn expr_diverges() {
1670 enum Either { A, B }
1675 // ^^^^^^^^^ Internal: match check bailed out
1680 // ^^^^^^^^^ Internal: match check bailed out
1682 match loop { break Foo::A } {
1683 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1686 match loop { break Foo::A } {
1696 fn expr_partially_diverges() {
1699 enum Either<T> { A(T), B }
1701 fn foo() -> Either<!> { Either::B }
1704 Either::A(val) => val,
1716 enum Either { A { foo: bool }, B }
1719 let a = Either::A { foo: true };
1721 //^ Missing match arm
1722 match a { Either::A { foo: true } => () }
1723 //^ Missing match arm
1725 Either::A { } => (),
1726 //^^^^^^^^^ Missing structure fields:
1731 //^ Missing match arm
1732 Either::A { } => (),
1733 } //^^^^^^^^^ Missing structure fields:
1737 Either::A { foo: true } => (),
1738 Either::A { foo: false } => (),
1742 Either::A { foo: _ } => (),
1751 fn enum_record_fields_out_of_order() {
1755 A { foo: bool, bar: () },
1760 let a = Either::A { foo: true, bar: () };
1762 //^ Missing match arm
1763 Either::A { bar: (), foo: false } => (),
1764 Either::A { foo: true, bar: () } => (),
1768 Either::A { bar: (), foo: false } => (),
1769 Either::A { foo: true, bar: () } => (),
1778 fn enum_record_ellipsis() {
1782 A { foo: bool, bar: bool },
1789 //^ Missing match arm
1790 Either::A { foo: true, .. } => (),
1794 //^ Missing match arm
1795 Either::A { .. } => (),
1799 Either::A { foo: true, .. } => (),
1800 Either::A { foo: false, .. } => (),
1805 Either::A { .. } => (),
1814 fn enum_tuple_partial_ellipsis() {
1818 A(bool, bool, bool, bool),
1824 //^^^^^^^^^ Missing match arm
1825 Either::A(true, .., true) => (),
1826 Either::A(true, .., false) => (),
1827 Either::A(false, .., false) => (),
1831 //^^^^^^^^^ Missing match arm
1832 Either::A(true, .., true) => (),
1833 Either::A(true, .., false) => (),
1834 Either::A(.., true) => (),
1839 Either::A(true, .., true) => (),
1840 Either::A(true, .., false) => (),
1841 Either::A(false, .., true) => (),
1842 Either::A(false, .., false) => (),
1846 Either::A(true, .., true) => (),
1847 Either::A(true, .., false) => (),
1848 Either::A(.., true) => (),
1849 Either::A(.., false) => (),
1863 fn enum_(never: Never) {
1866 fn enum_ref(never: &Never) {
1868 //^^^^^ Missing match arm
1881 enum Option<T> { Some(T), None }
1884 // `Never` is deliberately not defined so that it's an uninferred type.
1885 match Option::<Never>::None {
1887 Some(never) => match never {},
1888 // ^^^^^^^^^^^ Internal: match check bailed out
1890 match Option::<Never>::None {
1891 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1892 Option::Some(_never) => {},
1900 fn tuple_of_bools_with_ellipsis_at_end_missing_arm() {
1904 match (false, true, false) {
1905 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1913 fn tuple_of_bools_with_ellipsis_at_beginning_missing_arm() {
1917 match (false, true, false) {
1918 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1926 fn tuple_of_bools_with_ellipsis_in_middle_missing_arm() {
1930 match (false, true, false) {
1931 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1932 (true, .., false) => (),
1939 fn record_struct() {
1941 r#"struct Foo { a: bool }
1944 //^ Missing match arm
1945 match f { Foo { a: true } => () }
1946 //^ Missing match arm
1947 match &f { Foo { a: true } => () }
1948 //^^ Missing match arm
1949 match f { Foo { a: _ } => () }
1951 Foo { a: true } => (),
1952 Foo { a: false } => (),
1955 Foo { a: true } => (),
1956 Foo { a: false } => (),
1966 r#"struct Foo(bool);
1969 //^ Missing match arm
1970 match f { Foo(true) => () }
1971 //^ Missing match arm
1987 //^ Missing match arm
1988 match f { Foo => () }
1995 fn record_struct_ellipsis() {
1997 r#"struct Foo { foo: bool, bar: bool }
1999 match f { Foo { foo: true, .. } => () }
2000 //^ Missing match arm
2002 //^ Missing match arm
2003 Foo { foo: true, .. } => (),
2004 Foo { bar: false, .. } => ()
2006 match f { Foo { .. } => () }
2008 Foo { foo: true, .. } => (),
2009 Foo { foo: false, .. } => ()
2021 enum Either { A(bool), B }
2023 //^^^^^^^^^ Missing match arm
2024 Either::A(true | false) => (),
2032 fn no_panic_at_unimplemented_subpattern_type() {
2037 match v { S{ a } => {} }
2038 match v { S{ a: _x } => {} }
2039 match v { S{ a: 'a' } => {} }
2040 //^^^^^^^^^^^ Internal: match check bailed out
2041 match v { S{..} => {} }
2044 //^ Missing match arm
2059 match true { _x @ true => {} }
2060 //^^^^ Missing match arm
2067 fn binding_ref_has_correct_type() {
2068 // Asserts `PatKind::Binding(ref _x): bool`, not &bool.
2069 // If that's not true match checking will panic with "incompatible constructors"
2070 // FIXME: make facilities to test this directly like `tests::check_infer(..)`
2075 // FIXME: this should not bail out but current behavior is such as the old algorithm.
2076 // ExprValidator::validate_match(..) checks types of top level patterns incorrecly.
2079 // ^^^^^^ Internal: match check bailed out
2092 fn enum_non_exhaustive() {
2095 //- /lib.rs crate:lib
2099 match E::A { _ => {} }
2109 //- /main.rs crate:main deps:lib
2112 match E::A { _ => {} }
2114 //^^^^ Missing match arm
2119 //^^^^ Missing match arm
2138 //^^^^ Missing match arm
2148 fn pattern_type_is_of_substitution() {
2149 cov_mark::check!(match_check_wildcard_expanded_to_substitutions);
2164 fn record_struct_no_such_field() {
2169 match f { Foo { bar } => () }
2170 // ^^^^^^^^^^^ Internal: match check bailed out
2177 fn match_ergonomics_issue_9095() {
2180 enum Foo<T> { A(T) }
2182 match &Foo::A(true) {
2191 mod false_negatives {
2192 //! The implementation of match checking here is a work in progress. As we roll this out, we
2193 //! prefer false negatives to false positives (ideally there would be no false positives). This
2194 //! test module should document known false negatives. Eventually we will have a complete
2195 //! implementation of match checking and this module will be empty.
2197 //! The reasons for documenting known false negatives:
2199 //! 1. It acts as a backlog of work that can be done to improve the behavior of the system.
2200 //! 2. It ensures the code doesn't panic when handling these cases.
2205 // We don't currently check integer exhaustiveness.
2211 // ^^ Internal: match check bailed out
2220 fn reference_patterns_at_top_level() {
2226 // ^^^^^ Internal: match check bailed out
2234 fn reference_patterns_in_fields() {
2240 // ^^^^^^^ Internal: match check bailed out
2244 // ^^^^^^^^ Internal: match check bailed out
2254 mod decl_check_tests {
2255 use crate::diagnostics::tests::check_diagnostics;
2258 fn incorrect_function_name() {
2261 fn NonSnakeCaseName() {}
2262 // ^^^^^^^^^^^^^^^^ Function `NonSnakeCaseName` should have snake_case name, e.g. `non_snake_case_name`
2268 fn incorrect_function_params() {
2271 fn foo(SomeParam: u8) {}
2272 // ^^^^^^^^^ Parameter `SomeParam` should have snake_case name, e.g. `some_param`
2274 fn foo2(ok_param: &str, CAPS_PARAM: u8) {}
2275 // ^^^^^^^^^^ Parameter `CAPS_PARAM` should have snake_case name, e.g. `caps_param`
2281 fn incorrect_variable_names() {
2285 let SOME_VALUE = 10;
2286 // ^^^^^^^^^^ Variable `SOME_VALUE` should have snake_case name, e.g. `some_value`
2287 let AnotherValue = 20;
2288 // ^^^^^^^^^^^^ Variable `AnotherValue` should have snake_case name, e.g. `another_value`
2295 fn incorrect_struct_names() {
2298 struct non_camel_case_name {}
2299 // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName`
2301 struct SCREAMING_CASE {}
2302 // ^^^^^^^^^^^^^^ Structure `SCREAMING_CASE` should have CamelCase name, e.g. `ScreamingCase`
2308 fn no_diagnostic_for_camel_cased_acronyms_in_struct_name() {
2317 fn incorrect_struct_field() {
2320 struct SomeStruct { SomeField: u8 }
2321 // ^^^^^^^^^ Field `SomeField` should have snake_case name, e.g. `some_field`
2327 fn incorrect_enum_names() {
2330 enum some_enum { Val(u8) }
2331 // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum`
2334 // ^^^^^^^^^ Enum `SOME_ENUM` should have CamelCase name, e.g. `SomeEnum`
2340 fn no_diagnostic_for_camel_cased_acronyms_in_enum_name() {
2349 fn incorrect_enum_variant_name() {
2352 enum SomeEnum { SOME_VARIANT(u8) }
2353 // ^^^^^^^^^^^^ Variant `SOME_VARIANT` should have CamelCase name, e.g. `SomeVariant`
2359 fn incorrect_const_name() {
2362 const some_weird_const: u8 = 10;
2363 // ^^^^^^^^^^^^^^^^ Constant `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2369 fn incorrect_static_name() {
2372 static some_weird_const: u8 = 10;
2373 // ^^^^^^^^^^^^^^^^ Static variable `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2379 fn fn_inside_impl_struct() {
2383 // ^^^^^^^^^^ Structure `someStruct` should have CamelCase name, e.g. `SomeStruct`
2386 fn SomeFunc(&self) {
2387 // ^^^^^^^^ Function `SomeFunc` should have snake_case name, e.g. `some_func`
2388 let WHY_VAR_IS_CAPS = 10;
2389 // ^^^^^^^^^^^^^^^ Variable `WHY_VAR_IS_CAPS` should have snake_case name, e.g. `why_var_is_caps`
2397 fn no_diagnostic_for_enum_varinats() {
2400 enum Option { Some, None }
2403 match Option::None {
2416 enum Option { Some, None }
2419 match Option::None {
2420 SOME_VAR @ None => (),
2421 // ^^^^^^^^ Variable `SOME_VAR` should have snake_case name, e.g. `some_var`
2430 fn allow_attributes() {
2433 #[allow(non_snake_case)]
2434 fn NonSnakeCaseName(SOME_VAR: u8) -> u8{
2435 // cov_flags generated output from elsewhere in this file
2438 static lower_case: u8;
2441 let OtherVar = SOME_VAR + 1;
2445 #[allow(nonstandard_style)]
2446 mod CheckNonstandardStyle {
2447 fn HiImABadFnName() {}
2452 fn HiImABadFnName() {}
2456 #![allow(non_snake_case)]
2457 fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {}
2460 #[allow(non_snake_case, non_camel_case_types)]
2461 pub struct some_type {
2466 #[allow(non_upper_case_globals)]
2467 pub const some_const: u8 = 10;
2469 #[allow(non_upper_case_globals)]
2470 pub static SomeStatic: u8 = 10;
2476 fn allow_attributes_crate_attr() {
2479 #![allow(non_snake_case)]
2482 fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {}
2490 fn bug_trait_inside_fn() {
2492 // This is broken, and in fact, should not even be looked at by this
2493 // lint in the first place. There's weird stuff going on in the
2494 // collection phase.
2495 // It's currently being brought in by:
2496 // * validate_func on `a` recursing into modules
2497 // * then it finds the trait and then the function while iterating
2499 // * then validate_func is called on Dirty
2500 // * ... which then proceeds to look at some unknown module taking no
2501 // attrs from either the impl or the fn a, and then finally to the root
2504 // It should find the attribute on the trait, but it *doesn't even see
2505 // the trait* as far as I can tell.
2513 // this comes out of bitflags, mostly
2514 #[allow(non_snake_case)]
2516 const HiImAlsoBad: u8 = 2;
2518 fn Dirty(&self) -> bool {
2531 fn bug_traits_arent_checked() {
2532 // FIXME: Traits and functions in traits aren't currently checked by
2533 // r-a, even though rustc will complain about them.
2537 // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait`
2539 // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function`
2541 // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function`
2548 fn ignores_extern_items() {
2549 cov_mark::check!(extern_func_incorrect_case_ignored);
2550 cov_mark::check!(extern_static_incorrect_case_ignored);
2554 fn NonSnakeCaseName(SOME_VAR: u8) -> u8;
2555 pub static SomeStatic: u8 = 10;
2562 fn infinite_loop_inner_items() {
2574 #[test] // Issue #8809.
2575 fn parenthesized_parameter() {
2576 check_diagnostics(r#"fn f((O): _) {}"#)