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 /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
420 /// apply to the file containing the cursor.
421 pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
422 let (analysis, files) = fixture::files(ra_fixture);
423 let diagnostics = files
425 .flat_map(|file_id| {
427 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
430 .collect::<Vec<_>>();
431 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
434 pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) {
435 let (analysis, file_id) = fixture::file(ra_fixture);
436 let diagnostics = analysis
437 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
439 expect.assert_debug_eq(&diagnostics)
443 pub(crate) fn check_diagnostics(ra_fixture: &str) {
444 let mut config = DiagnosticsConfig::default();
445 config.disabled.insert("inactive-code".to_string());
446 check_diagnostics_with_config(config, ra_fixture)
450 pub(crate) fn check_diagnostics_with_config(config: DiagnosticsConfig, ra_fixture: &str) {
451 let (analysis, files) = fixture::files(ra_fixture);
452 for file_id in files {
454 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
456 let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
458 diagnostics.into_iter().map(|d| (d.range, d.message)).collect::<Vec<_>>();
459 actual.sort_by_key(|(range, _)| range.start());
460 assert_eq!(expected, actual);
465 fn range_mapping_out_of_macros() {
466 // FIXME: this is very wrong, but somewhat tricky to fix.
473 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
476 let _x = id![Foo { a: $042 }];
479 pub struct Foo { pub a: i32, pub b: i32 }
486 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
489 let _x = id![Foo { a: 42 }];
492 pub struct Foo { pub a: i32, pub b: i32 }
498 fn test_check_unnecessary_braces_in_use_statement() {
499 check_no_diagnostics(
512 check_no_diagnostics(
570 mod a { mod c {} mod d { mod e {} } }
571 use a::{c, d::{e$0}};
574 mod a { mod c {} mod d { mod e {} } }
581 fn test_disabled_diagnostics() {
582 let mut config = DiagnosticsConfig::default();
583 config.disabled.insert("unresolved-module".into());
585 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
588 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
589 assert!(diagnostics.is_empty());
591 let diagnostics = analysis
592 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
594 assert!(!diagnostics.is_empty());
598 fn unlinked_file_prepend_first_item() {
599 cov_mark::check!(unlinked_file_prepend_before_first_item);
600 // Only tests the first one for `pub mod` since the rest are the same
624 fn unlinked_file_append_mod() {
625 cov_mark::check!(unlinked_file_append_to_existing_mods);
637 mod preexisting_bottom;)
651 mod preexisting_bottom;)
657 fn unlinked_file_insert_in_empty_file() {
658 cov_mark::check!(unlinked_file_empty_file);
672 fn unlinked_file_old_style_modrs() {
690 fn unlinked_file_new_style_mod() {
706 fn unlinked_file_with_cfg_off() {
707 cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
721 fn unlinked_file_with_cfg_on() {
722 check_no_diagnostics(
734 fn break_outside_of_loop() {
738 //^^^^^ break outside of loop
744 fn no_such_field_diagnostics() {
747 struct S { foo: i32, bar: () }
751 //^ Missing structure fields:
755 //^^^^^^^ no such field
763 fn no_such_field_with_feature_flag_diagnostics() {
766 //- /lib.rs crate:foo cfg:feature=foo
769 #[cfg(feature = "foo")]
774 #[cfg(feature = "foo")]
775 pub(crate) fn new(my_val: usize, bar: bool) -> Self {
778 #[cfg(not(feature = "foo"))]
779 pub(crate) fn new(my_val: usize, _bar: bool) -> Self {
788 fn no_such_field_enum_with_feature_flag_diagnostics() {
791 //- /lib.rs crate:foo cfg:feature=foo
793 #[cfg(not(feature = "foo"))]
795 #[cfg(feature = "foo")]
811 fn no_such_field_with_feature_flag_diagnostics_on_struct_lit() {
814 //- /lib.rs crate:foo cfg:feature=foo
816 #[cfg(feature = "foo")]
818 #[cfg(not(feature = "foo"))]
823 #[cfg(feature = "foo")]
824 fn new(foo: u32) -> Self {
827 #[cfg(not(feature = "foo"))]
828 fn new(bar: u32) -> Self {
831 fn new2(bar: u32) -> Self {
832 #[cfg(feature = "foo")]
833 { Self { foo: bar } }
834 #[cfg(not(feature = "foo"))]
837 fn new2(val: u32) -> Self {
839 #[cfg(feature = "foo")]
841 #[cfg(not(feature = "foo"))]
851 fn no_such_field_with_type_macro() {
854 macro_rules! Type { () => { u32 }; }
855 struct Foo { bar: Type![] }
867 fn missing_unsafe_diagnostic_with_raw_ptr() {
871 let x = &5 as *const usize;
872 unsafe { let y = *x; }
874 } //^^ This operation is unsafe and requires an unsafe function or block
880 fn missing_unsafe_diagnostic_with_unsafe_call() {
886 unsafe fn unsafe_fn(&self) {
887 let x = &5 as *const usize;
892 unsafe fn unsafe_fn() {
893 let x = &5 as *const usize;
899 //^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
900 HasUnsafe.unsafe_fn();
901 //^^^^^^^^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
904 HasUnsafe.unsafe_fn();
912 fn missing_unsafe_diagnostic_with_static_mut() {
919 static mut STATIC_MUT: Ty = Ty { a: 0 };
922 let x = STATIC_MUT.a;
923 //^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
925 let x = STATIC_MUT.a;
933 fn no_missing_unsafe_diagnostic_with_safe_intrinsic() {
936 extern "rust-intrinsic" {
937 pub fn bitreverse(x: u32) -> u32; // Safe intrinsic
938 pub fn floorf32(x: f32) -> f32; // Unsafe intrinsic
942 let _ = bitreverse(12);
943 let _ = floorf32(12.0);
944 //^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
950 // Register the required standard library types to make the tests work
951 fn add_filter_map_with_find_next_boilerplate(body: &str) -> String {
953 //- /main.rs crate:main deps:core
954 use core::iter::Iterator;
955 use core::option::Option::{self, Some, None};
958 //- /core/lib.rs crate:core
960 pub enum Option<T> { Some(T), None }
965 fn filter_map<B, F>(self, f: F) -> FilterMap where F: FnMut(Self::Item) -> Option<B> { FilterMap }
966 fn next(&mut self) -> Option<Self::Item>;
968 pub struct FilterMap {}
969 impl Iterator for FilterMap {
971 fn next(&mut self) -> i32 { 7 }
975 format!("{}{}{}", prefix, body, suffix)
979 fn replace_filter_map_next_with_find_map2() {
980 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
983 let m = [1, 2, 3].iter().filter_map(|x| if *x == 2 { Some (4) } else { None }).next();
984 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ replace filter_map(..).next() with find_map(..)
991 fn replace_filter_map_next_with_find_map_no_diagnostic_without_next() {
992 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
997 .filter_map(|x| if *x == 2 { Some (4) } else { None })
1005 fn replace_filter_map_next_with_find_map_no_diagnostic_with_intervening_methods() {
1006 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1011 .filter_map(|x| if *x == 2 { Some (4) } else { None })
1020 fn replace_filter_map_next_with_find_map_no_diagnostic_if_not_in_chain() {
1021 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1026 .filter_map(|x| if *x == 2 { Some (4) } else { None });
1034 fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
1037 struct S { foo: i32, bar: () }
1038 fn baz(s: S) -> i32 {
1040 S { foo, .. } => foo,
1048 fn missing_record_pat_field_box() {
1051 struct S { s: Box<u32> }
1053 let S { box s } = a;
1060 fn missing_record_pat_field_ref() {
1065 let S { ref s } = a;
1072 fn simple_free_fn_zero() {
1077 //^^^^^^^ Expected 0 arguments, found 1
1090 fn simple_free_fn_one() {
1095 //^^^^^ Expected 1 argument, found 0
1112 impl S { fn method(&self) {} }
1116 } //^^^^^^^^^^^ Expected 1 argument, found 0
1123 impl S { fn method(&self) {} }
1134 fn method_with_arg() {
1138 impl S { fn method(&self, arg: u8) {} }
1142 } //^^^^^^^^^^ Expected 1 argument, found 0
1149 impl S { fn method(&self, arg: u8) {} }
1160 fn method_unknown_receiver() {
1161 // note: this is incorrect code, so there might be errors on this in the
1162 // future, but we shouldn't emit an argument count diagnostic here
1165 trait Foo { fn method(&self, arg: usize) {} }
1179 struct Tup(u8, u16);
1182 } //^^^^^^ Expected 2 arguments, found 1
1191 enum En { Variant(u8, u16), }
1194 } //^^^^^^^^^^^^^^ Expected 2 arguments, found 1
1200 fn enum_variant_type_macro() {
1213 //^^^^^^^^^^^^^^ Expected 1 argument, found 2
1215 //^^^^^^^^^^ Expected 1 argument, found 0
1227 fn fixed(fixed: u8);
1228 fn varargs(fixed: u8, ...);
1236 //^^^^^^^^^^^ Expected 1 argument, found 2
1249 fn arg_count_lambda() {
1255 //^^^ Expected 1 argument, found 0
1258 //^^^^^^^^^ Expected 1 argument, found 2
1265 fn cfgd_out_call_arguments() {
1268 struct C(#[cfg(FALSE)] ());
1281 C::new().method(#[cfg(FALSE)] 0);
1288 fn cfgd_out_fn_params() {
1291 fn foo(#[cfg(NEVER)] x: ()) {}
1296 fn method(#[cfg(NEVER)] self) {}
1297 fn method2(#[cfg(NEVER)] self, arg: u8) {}
1298 fn method3(self, #[cfg(NEVER)] arg: u8) {}
1302 fn fixed(fixed: u8, #[cfg(NEVER)] ...);
1303 fn varargs(#[cfg(not(NEVER))] ...);
1322 fn missing_semicolon() {
1325 fn test() -> i32 { 123; }
1326 //^^^ Remove this semicolon
1332 fn import_extern_crate_clash_with_inner_item() {
1333 // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
1337 //- /lib.rs crate:lib deps:jwt
1340 use permissions::jwt;
1344 jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
1349 pub struct Claims {}
1352 //- /jwt/lib.rs crate:jwt
1362 pub(super) mod match_check_tests {
1363 use crate::diagnostics::tests::check_diagnostics;
1371 //^^ Missing match arm
1373 //^^^^ Missing match arm
1375 match () { _ => (), }
1376 match () { () => (), }
1377 match (()) { (()) => (), }
1384 fn tuple_of_two_empty_tuple() {
1389 //^^^^^^^^ Missing match arm
1391 match ((), ()) { ((), ()) => (), }
1403 //^^^^^ Missing match arm
1404 match false { true => (), }
1405 //^^^^^ Missing match arm
1406 match (false, true) {}
1407 //^^^^^^^^^^^^^ Missing match arm
1408 match (false, true) { (true, true) => (), }
1409 //^^^^^^^^^^^^^ Missing match arm
1410 match (false, true) {
1411 //^^^^^^^^^^^^^ Missing match arm
1412 (false, true) => (),
1413 (false, false) => (),
1414 (true, false) => (),
1416 match (false, true) { (true, _x) => (), }
1417 //^^^^^^^^^^^^^ Missing match arm
1419 match false { true => (), false => (), }
1420 match (false, true) {
1422 (true, false) => (),
1425 match (false, true) {
1427 (true, false) => (),
1428 (false, true) => (),
1429 (false, false) => (),
1431 match (false, true) {
1433 (false, true) => (),
1434 (false, false) => (),
1436 match (false, true, false) {
1440 match (false, true, false) {
1444 match (false, true, false) { (..) => (), }
1451 fn tuple_of_tuple_and_bools() {
1455 match (false, ((), false)) {}
1456 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1457 match (false, ((), false)) { (true, ((), true)) => (), }
1458 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1459 match (false, ((), false)) { (true, _) => (), }
1460 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1462 match (false, ((), false)) {
1463 (true, ((), true)) => (),
1464 (true, ((), false)) => (),
1465 (false, ((), true)) => (),
1466 (false, ((), false)) => (),
1468 match (false, ((), false)) {
1469 (true, ((), true)) => (),
1470 (true, ((), false)) => (),
1482 enum Either { A, B, }
1486 //^^^^^^^^^ Missing match arm
1487 match Either::B { Either::A => (), }
1488 //^^^^^^^^^ Missing match arm
1491 //^^^^^^^^^^ Missing match arm
1496 Either::A => (), Either::B => (),
1499 Either::A => (), Either::B => (),
1507 fn enum_containing_bool() {
1510 enum Either { A(bool), B }
1514 //^^^^^^^^^ Missing match arm
1516 //^^^^^^^^^ Missing match arm
1517 Either::A(true) => (), Either::B => ()
1521 Either::A(true) => (),
1522 Either::A(false) => (),
1540 fn enum_different_sizes() {
1543 enum Either { A(bool), B(bool, bool) }
1546 match Either::A(false) {
1547 //^^^^^^^^^^^^^^^^ Missing match arm
1549 Either::B(false, _) => (),
1552 match Either::A(false) {
1554 Either::B(true, _) => (),
1555 Either::B(false, _) => (),
1557 match Either::A(false) {
1558 Either::A(true) | Either::A(false) => (),
1559 Either::B(true, _) => (),
1560 Either::B(false, _) => (),
1568 fn tuple_of_enum_no_diagnostic() {
1571 enum Either { A(bool), B(bool, bool) }
1572 enum Either2 { C, D }
1575 match (Either::A(false), Either2::C) {
1576 (Either::A(true), _) | (Either::A(false), _) => (),
1577 (Either::B(true, _), Either2::C) => (),
1578 (Either::B(false, _), Either2::C) => (),
1579 (Either::B(_, _), Either2::D) => (),
1587 fn or_pattern_no_diagnostic() {
1593 match (Either::A, Either::B) {
1594 (Either::A | Either::B, _) => (),
1601 fn mismatched_types() {
1602 // Match statements with arms that don't match the
1603 // expression pattern do not fire this diagnostic.
1606 enum Either { A, B }
1607 enum Either2 { C, D }
1612 // ^^^^^^^^^^ Internal: match check bailed out
1615 match (true, false) {
1616 (true, false, true) => (),
1617 // ^^^^^^^^^^^^^^^^^^^ Internal: match check bailed out
1620 match (true, false) { (true,) => {} }
1621 // ^^^^^^^ Internal: match check bailed out
1622 match (0) { () => () }
1623 // ^^ Internal: match check bailed out
1624 match Unresolved::Bar { Unresolved::Baz => () }
1631 fn mismatched_types_in_or_patterns() {
1635 match false { true | () => {} }
1636 // ^^^^^^^^^ Internal: match check bailed out
1637 match (false,) { (true | (),) => {} }
1638 // ^^^^^^^^^^^^ Internal: match check bailed out
1645 fn malformed_match_arm_tuple_enum_missing_pattern() {
1646 // We are testing to be sure we don't panic here when the match
1647 // arm `Either::B` is missing its pattern.
1650 enum Either { A, B(u32) }
1663 fn malformed_match_arm_extra_fields() {
1666 enum A { B(isize, isize), C }
1669 A::B(_, _, _) => (),
1670 // ^^^^^^^^^^^^^ Internal: match check bailed out
1674 // ^^^^^^^ Internal: match check bailed out
1682 fn expr_diverges() {
1685 enum Either { A, B }
1690 // ^^^^^^^^^ Internal: match check bailed out
1695 // ^^^^^^^^^ Internal: match check bailed out
1697 match loop { break Foo::A } {
1698 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1701 match loop { break Foo::A } {
1711 fn expr_partially_diverges() {
1714 enum Either<T> { A(T), B }
1716 fn foo() -> Either<!> { Either::B }
1719 Either::A(val) => val,
1731 enum Either { A { foo: bool }, B }
1734 let a = Either::A { foo: true };
1736 //^ Missing match arm
1737 match a { Either::A { foo: true } => () }
1738 //^ Missing match arm
1740 Either::A { } => (),
1741 //^^^^^^^^^ Missing structure fields:
1746 //^ Missing match arm
1747 Either::A { } => (),
1748 } //^^^^^^^^^ Missing structure fields:
1752 Either::A { foo: true } => (),
1753 Either::A { foo: false } => (),
1757 Either::A { foo: _ } => (),
1766 fn enum_record_fields_out_of_order() {
1770 A { foo: bool, bar: () },
1775 let a = Either::A { foo: true, bar: () };
1777 //^ Missing match arm
1778 Either::A { bar: (), foo: false } => (),
1779 Either::A { foo: true, bar: () } => (),
1783 Either::A { bar: (), foo: false } => (),
1784 Either::A { foo: true, bar: () } => (),
1793 fn enum_record_ellipsis() {
1797 A { foo: bool, bar: bool },
1804 //^ Missing match arm
1805 Either::A { foo: true, .. } => (),
1809 //^ Missing match arm
1810 Either::A { .. } => (),
1814 Either::A { foo: true, .. } => (),
1815 Either::A { foo: false, .. } => (),
1820 Either::A { .. } => (),
1829 fn enum_tuple_partial_ellipsis() {
1833 A(bool, bool, bool, bool),
1839 //^^^^^^^^^ Missing match arm
1840 Either::A(true, .., true) => (),
1841 Either::A(true, .., false) => (),
1842 Either::A(false, .., false) => (),
1846 //^^^^^^^^^ Missing match arm
1847 Either::A(true, .., true) => (),
1848 Either::A(true, .., false) => (),
1849 Either::A(.., true) => (),
1854 Either::A(true, .., true) => (),
1855 Either::A(true, .., false) => (),
1856 Either::A(false, .., true) => (),
1857 Either::A(false, .., false) => (),
1861 Either::A(true, .., true) => (),
1862 Either::A(true, .., false) => (),
1863 Either::A(.., true) => (),
1864 Either::A(.., false) => (),
1878 fn enum_(never: Never) {
1881 fn enum_ref(never: &Never) {
1883 //^^^^^ Missing match arm
1896 enum Option<T> { Some(T), None }
1899 // `Never` is deliberately not defined so that it's an uninferred type.
1900 match Option::<Never>::None {
1902 Some(never) => match never {},
1903 // ^^^^^^^^^^^ Internal: match check bailed out
1905 match Option::<Never>::None {
1906 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1907 Option::Some(_never) => {},
1915 fn tuple_of_bools_with_ellipsis_at_end_missing_arm() {
1919 match (false, true, false) {
1920 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1928 fn tuple_of_bools_with_ellipsis_at_beginning_missing_arm() {
1932 match (false, true, false) {
1933 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1941 fn tuple_of_bools_with_ellipsis_in_middle_missing_arm() {
1945 match (false, true, false) {
1946 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1947 (true, .., false) => (),
1954 fn record_struct() {
1956 r#"struct Foo { a: bool }
1959 //^ Missing match arm
1960 match f { Foo { a: true } => () }
1961 //^ Missing match arm
1962 match &f { Foo { a: true } => () }
1963 //^^ Missing match arm
1964 match f { Foo { a: _ } => () }
1966 Foo { a: true } => (),
1967 Foo { a: false } => (),
1970 Foo { a: true } => (),
1971 Foo { a: false } => (),
1981 r#"struct Foo(bool);
1984 //^ Missing match arm
1985 match f { Foo(true) => () }
1986 //^ Missing match arm
2002 //^ Missing match arm
2003 match f { Foo => () }
2010 fn record_struct_ellipsis() {
2012 r#"struct Foo { foo: bool, bar: bool }
2014 match f { Foo { foo: true, .. } => () }
2015 //^ Missing match arm
2017 //^ Missing match arm
2018 Foo { foo: true, .. } => (),
2019 Foo { bar: false, .. } => ()
2021 match f { Foo { .. } => () }
2023 Foo { foo: true, .. } => (),
2024 Foo { foo: false, .. } => ()
2036 enum Either { A(bool), B }
2038 //^^^^^^^^^ Missing match arm
2039 Either::A(true | false) => (),
2047 fn no_panic_at_unimplemented_subpattern_type() {
2052 match v { S{ a } => {} }
2053 match v { S{ a: _x } => {} }
2054 match v { S{ a: 'a' } => {} }
2055 //^^^^^^^^^^^ Internal: match check bailed out
2056 match v { S{..} => {} }
2059 //^ Missing match arm
2074 match true { _x @ true => {} }
2075 //^^^^ Missing match arm
2082 fn binding_ref_has_correct_type() {
2083 // Asserts `PatKind::Binding(ref _x): bool`, not &bool.
2084 // If that's not true match checking will panic with "incompatible constructors"
2085 // FIXME: make facilities to test this directly like `tests::check_infer(..)`
2090 // FIXME: this should not bail out but current behavior is such as the old algorithm.
2091 // ExprValidator::validate_match(..) checks types of top level patterns incorrecly.
2094 // ^^^^^^ Internal: match check bailed out
2107 fn enum_non_exhaustive() {
2110 //- /lib.rs crate:lib
2114 match E::A { _ => {} }
2124 //- /main.rs crate:main deps:lib
2127 match E::A { _ => {} }
2129 //^^^^ Missing match arm
2134 //^^^^ Missing match arm
2153 //^^^^ Missing match arm
2163 fn pattern_type_is_of_substitution() {
2164 cov_mark::check!(match_check_wildcard_expanded_to_substitutions);
2179 fn record_struct_no_such_field() {
2184 match f { Foo { bar } => () }
2185 // ^^^^^^^^^^^ Internal: match check bailed out
2192 fn match_ergonomics_issue_9095() {
2195 enum Foo<T> { A(T) }
2197 match &Foo::A(true) {
2206 mod false_negatives {
2207 //! The implementation of match checking here is a work in progress. As we roll this out, we
2208 //! prefer false negatives to false positives (ideally there would be no false positives). This
2209 //! test module should document known false negatives. Eventually we will have a complete
2210 //! implementation of match checking and this module will be empty.
2212 //! The reasons for documenting known false negatives:
2214 //! 1. It acts as a backlog of work that can be done to improve the behavior of the system.
2215 //! 2. It ensures the code doesn't panic when handling these cases.
2220 // We don't currently check integer exhaustiveness.
2226 // ^^ Internal: match check bailed out
2235 fn reference_patterns_at_top_level() {
2241 // ^^^^^ Internal: match check bailed out
2249 fn reference_patterns_in_fields() {
2255 // ^^^^^^^ Internal: match check bailed out
2259 // ^^^^^^^^ Internal: match check bailed out
2269 mod decl_check_tests {
2270 use crate::diagnostics::tests::check_diagnostics;
2273 fn incorrect_function_name() {
2276 fn NonSnakeCaseName() {}
2277 // ^^^^^^^^^^^^^^^^ Function `NonSnakeCaseName` should have snake_case name, e.g. `non_snake_case_name`
2283 fn incorrect_function_params() {
2286 fn foo(SomeParam: u8) {}
2287 // ^^^^^^^^^ Parameter `SomeParam` should have snake_case name, e.g. `some_param`
2289 fn foo2(ok_param: &str, CAPS_PARAM: u8) {}
2290 // ^^^^^^^^^^ Parameter `CAPS_PARAM` should have snake_case name, e.g. `caps_param`
2296 fn incorrect_variable_names() {
2300 let SOME_VALUE = 10;
2301 // ^^^^^^^^^^ Variable `SOME_VALUE` should have snake_case name, e.g. `some_value`
2302 let AnotherValue = 20;
2303 // ^^^^^^^^^^^^ Variable `AnotherValue` should have snake_case name, e.g. `another_value`
2310 fn incorrect_struct_names() {
2313 struct non_camel_case_name {}
2314 // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName`
2316 struct SCREAMING_CASE {}
2317 // ^^^^^^^^^^^^^^ Structure `SCREAMING_CASE` should have CamelCase name, e.g. `ScreamingCase`
2323 fn no_diagnostic_for_camel_cased_acronyms_in_struct_name() {
2332 fn incorrect_struct_field() {
2335 struct SomeStruct { SomeField: u8 }
2336 // ^^^^^^^^^ Field `SomeField` should have snake_case name, e.g. `some_field`
2342 fn incorrect_enum_names() {
2345 enum some_enum { Val(u8) }
2346 // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum`
2349 // ^^^^^^^^^ Enum `SOME_ENUM` should have CamelCase name, e.g. `SomeEnum`
2355 fn no_diagnostic_for_camel_cased_acronyms_in_enum_name() {
2364 fn incorrect_enum_variant_name() {
2367 enum SomeEnum { SOME_VARIANT(u8) }
2368 // ^^^^^^^^^^^^ Variant `SOME_VARIANT` should have CamelCase name, e.g. `SomeVariant`
2374 fn incorrect_const_name() {
2377 const some_weird_const: u8 = 10;
2378 // ^^^^^^^^^^^^^^^^ Constant `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2384 fn incorrect_static_name() {
2387 static some_weird_const: u8 = 10;
2388 // ^^^^^^^^^^^^^^^^ Static variable `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2394 fn fn_inside_impl_struct() {
2398 // ^^^^^^^^^^ Structure `someStruct` should have CamelCase name, e.g. `SomeStruct`
2401 fn SomeFunc(&self) {
2402 // ^^^^^^^^ Function `SomeFunc` should have snake_case name, e.g. `some_func`
2403 let WHY_VAR_IS_CAPS = 10;
2404 // ^^^^^^^^^^^^^^^ Variable `WHY_VAR_IS_CAPS` should have snake_case name, e.g. `why_var_is_caps`
2412 fn no_diagnostic_for_enum_varinats() {
2415 enum Option { Some, None }
2418 match Option::None {
2431 enum Option { Some, None }
2434 match Option::None {
2435 SOME_VAR @ None => (),
2436 // ^^^^^^^^ Variable `SOME_VAR` should have snake_case name, e.g. `some_var`
2445 fn allow_attributes() {
2448 #[allow(non_snake_case)]
2449 fn NonSnakeCaseName(SOME_VAR: u8) -> u8{
2450 // cov_flags generated output from elsewhere in this file
2453 static lower_case: u8;
2456 let OtherVar = SOME_VAR + 1;
2460 #[allow(nonstandard_style)]
2461 mod CheckNonstandardStyle {
2462 fn HiImABadFnName() {}
2467 fn HiImABadFnName() {}
2471 #![allow(non_snake_case)]
2472 fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {}
2475 #[allow(non_snake_case, non_camel_case_types)]
2476 pub struct some_type {
2481 #[allow(non_upper_case_globals)]
2482 pub const some_const: u8 = 10;
2484 #[allow(non_upper_case_globals)]
2485 pub static SomeStatic: u8 = 10;
2491 fn allow_attributes_crate_attr() {
2494 #![allow(non_snake_case)]
2497 fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {}
2505 fn bug_trait_inside_fn() {
2507 // This is broken, and in fact, should not even be looked at by this
2508 // lint in the first place. There's weird stuff going on in the
2509 // collection phase.
2510 // It's currently being brought in by:
2511 // * validate_func on `a` recursing into modules
2512 // * then it finds the trait and then the function while iterating
2514 // * then validate_func is called on Dirty
2515 // * ... which then proceeds to look at some unknown module taking no
2516 // attrs from either the impl or the fn a, and then finally to the root
2519 // It should find the attribute on the trait, but it *doesn't even see
2520 // the trait* as far as I can tell.
2528 // this comes out of bitflags, mostly
2529 #[allow(non_snake_case)]
2531 const HiImAlsoBad: u8 = 2;
2533 fn Dirty(&self) -> bool {
2546 fn bug_traits_arent_checked() {
2547 // FIXME: Traits and functions in traits aren't currently checked by
2548 // r-a, even though rustc will complain about them.
2552 // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait`
2554 // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function`
2556 // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function`
2563 fn ignores_extern_items() {
2564 cov_mark::check!(extern_func_incorrect_case_ignored);
2565 cov_mark::check!(extern_static_incorrect_case_ignored);
2569 fn NonSnakeCaseName(SOME_VAR: u8) -> u8;
2570 pub static SomeStatic: u8 = 10;
2577 fn infinite_loop_inner_items() {
2589 #[test] // Issue #8809.
2590 fn parenthesized_parameter() {
2591 check_diagnostics(r#"fn f((O): _) {}"#)