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;
19 use std::cell::RefCell;
22 diagnostics::{AnyDiagnostic, Diagnostic as _, DiagnosticCode, DiagnosticSinkBuilder},
25 use ide_assists::AssistResolveStrategy;
26 use ide_db::{base_db::SourceDatabase, RootDatabase};
27 use itertools::Itertools;
28 use rustc_hash::FxHashSet;
31 SyntaxNode, SyntaxNodePtr, TextRange, TextSize,
33 use text_edit::TextEdit;
34 use unlinked_file::UnlinkedFile;
36 use crate::{Assist, AssistId, AssistKind, FileId, Label, SourceChange};
38 use self::fixes::DiagnosticWithFixes;
41 pub struct Diagnostic {
42 // pub name: Option<String>,
45 pub severity: Severity,
46 pub fixes: Option<Vec<Assist>>,
48 pub code: Option<DiagnosticCode>,
49 pub experimental: bool,
53 fn new(code: &'static str, message: impl Into<String>, range: TextRange) -> Diagnostic {
54 let message = message.into();
55 let code = Some(DiagnosticCode(code));
59 severity: Severity::Error,
67 fn experimental(mut self) -> Diagnostic {
68 self.experimental = true;
72 fn severity(mut self, severity: Severity) -> Diagnostic {
73 self.severity = severity;
77 fn error(range: TextRange, message: String) -> Self {
81 severity: Severity::Error,
89 fn hint(range: TextRange, message: String) -> Self {
93 severity: Severity::WeakWarning,
101 fn with_fixes(self, fixes: Option<Vec<Assist>>) -> Self {
102 Self { fixes, ..self }
105 fn with_unused(self, unused: bool) -> Self {
106 Self { unused, ..self }
109 fn with_code(self, code: Option<DiagnosticCode>) -> Self {
110 Self { code, ..self }
114 #[derive(Debug, Copy, Clone)]
120 #[derive(Default, Debug, Clone)]
121 pub struct DiagnosticsConfig {
122 pub disable_experimental: bool,
123 pub disabled: FxHashSet<String>,
126 struct DiagnosticsContext<'a> {
127 config: &'a DiagnosticsConfig,
128 sema: Semantics<'a, RootDatabase>,
130 resolve: &'a AssistResolveStrategy,
133 pub(crate) fn diagnostics(
135 config: &DiagnosticsConfig,
136 resolve: &AssistResolveStrategy,
138 ) -> Vec<Diagnostic> {
139 let _p = profile::span("diagnostics");
140 let sema = Semantics::new(db);
141 let parse = db.parse(file_id);
142 let mut res = Vec::new();
144 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
150 .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
153 for node in parse.tree().syntax().descendants() {
154 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
155 field_shorthand::check(&mut res, file_id, &node);
157 let res = RefCell::new(res);
158 let sink_builder = DiagnosticSinkBuilder::new()
159 .on::<hir::diagnostics::MissingOkOrSomeInTailExpr, _>(|d| {
160 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
162 .on::<hir::diagnostics::NoSuchField, _>(|d| {
163 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
165 .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| {
166 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
168 .on::<hir::diagnostics::IncorrectCase, _>(|d| {
169 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
171 .on::<hir::diagnostics::ReplaceFilterMapNextWithFindMap, _>(|d| {
172 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
174 .on::<UnlinkedFile, _>(|d| {
175 // Limit diagnostic to the first few characters in the file. This matches how VS Code
176 // renders it with the full span, but on other editors, and is less invasive.
177 let range = sema.diagnostics_display_range(d.display_source()).range;
178 let range = range.intersect(TextRange::up_to(TextSize::of("..."))).unwrap_or(range);
180 // Override severity and mark as unused.
181 res.borrow_mut().push(
182 Diagnostic::hint(range, d.message())
183 .with_fixes(d.fixes(&sema, resolve))
184 .with_code(Some(d.code())),
187 .on::<hir::diagnostics::UnimplementedBuiltinMacro, _>(|d| {
188 let display_range = sema.diagnostics_display_range(d.display_source()).range;
190 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
192 // Only collect experimental diagnostics when they're enabled.
193 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
194 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
196 // Finalize the `DiagnosticSink` building process.
197 let mut sink = sink_builder
198 // Diagnostics not handled above get no fix and default treatment.
200 res.borrow_mut().push(
202 sema.diagnostics_display_range(d.display_source()).range,
205 .with_code(Some(d.code())),
209 let mut diags = Vec::new();
210 let internal_diagnostics = cfg!(test);
211 match sema.to_module_def(file_id) {
212 Some(m) => diags = m.diagnostics(db, &mut sink, internal_diagnostics),
214 sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(parse.tree().syntax()) });
220 let mut res = res.into_inner();
222 let ctx = DiagnosticsContext { config, sema, resolve };
226 AnyDiagnostic::UnresolvedModule(d) => unresolved_module::unresolved_module(&ctx, &d),
227 AnyDiagnostic::UnresolvedExternCrate(d) => unresolved_extern_crate::unresolved_extern_crate(&ctx, &d),
228 AnyDiagnostic::UnresolvedImport(d) => unresolved_import::unresolved_import(&ctx, &d),
229 AnyDiagnostic::UnresolvedMacroCall(d) => unresolved_macro_call::unresolved_macro_call(&ctx, &d),
230 AnyDiagnostic::UnresolvedProcMacro(d) => unresolved_proc_macro::unresolved_proc_macro(&ctx, &d),
231 AnyDiagnostic::MissingFields(d) => missing_fields::missing_fields(&ctx, &d),
233 AnyDiagnostic::InactiveCode(d) => match inactive_code::inactive_code(&ctx, &d) {
238 if let Some(code) = d.code {
239 if ctx.config.disabled.contains(code.as_str()) {
243 if ctx.config.disable_experimental && d.experimental {
252 fn diagnostic_with_fix<D: DiagnosticWithFixes>(
254 sema: &Semantics<RootDatabase>,
255 resolve: &AssistResolveStrategy,
257 Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message())
258 .with_fixes(d.fixes(sema, resolve))
259 .with_code(Some(d.code()))
262 fn warning_with_fix<D: DiagnosticWithFixes>(
264 sema: &Semantics<RootDatabase>,
265 resolve: &AssistResolveStrategy,
267 Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message())
268 .with_fixes(d.fixes(sema, resolve))
269 .with_code(Some(d.code()))
272 fn check_unnecessary_braces_in_use_statement(
273 acc: &mut Vec<Diagnostic>,
277 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
278 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
279 // If there is a comment inside the bracketed `use`,
280 // assume it is a commented out module path and don't show diagnostic.
281 if use_tree_list.has_inner_comment() {
285 let use_range = use_tree_list.syntax().text_range();
287 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
289 let to_replace = single_use_tree.syntax().text().to_string();
290 let mut edit_builder = TextEdit::builder();
291 edit_builder.delete(use_range);
292 edit_builder.insert(use_range.start(), to_replace);
293 edit_builder.finish()
297 Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
298 .with_fixes(Some(vec![fix(
300 "Remove unnecessary braces",
301 SourceChange::from_text_edit(file_id, edit),
310 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
311 single_use_tree: &ast::UseTree,
312 ) -> Option<TextEdit> {
313 let use_tree_list_node = single_use_tree.syntax().parent()?;
314 if single_use_tree.path()?.segment()?.self_token().is_some() {
315 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
316 let end = use_tree_list_node.text_range().end();
317 return Some(TextEdit::delete(TextRange::new(start, end)));
322 fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
323 let mut res = unresolved_fix(id, label, target);
324 res.source_change = Some(source_change);
328 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
329 assert!(!id.contains(' '));
331 id: AssistId(id, AssistKind::QuickFix),
332 label: Label::new(label),
341 use expect_test::Expect;
342 use hir::diagnostics::DiagnosticCode;
343 use ide_assists::AssistResolveStrategy;
344 use stdx::trim_indent;
345 use test_utils::{assert_eq_text, extract_annotations};
347 use crate::{fixture, DiagnosticsConfig};
349 /// Takes a multi-file input fixture with annotated cursor positions,
351 /// * a diagnostic is produced
352 /// * the first diagnostic fix trigger range touches the input cursor position
353 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
355 pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
356 check_nth_fix(0, ra_fixture_before, ra_fixture_after);
358 /// Takes a multi-file input fixture with annotated cursor positions,
360 /// * a diagnostic is produced
361 /// * every diagnostic fixes trigger range touches the input cursor position
362 /// * that the contents of the file containing the cursor match `after` after each diagnostic fix is applied
363 pub(crate) fn check_fixes(ra_fixture_before: &str, ra_fixtures_after: Vec<&str>) {
364 for (i, ra_fixture_after) in ra_fixtures_after.iter().enumerate() {
365 check_nth_fix(i, ra_fixture_before, ra_fixture_after)
370 fn check_nth_fix(nth: usize, ra_fixture_before: &str, ra_fixture_after: &str) {
371 let after = trim_indent(ra_fixture_after);
373 let (analysis, file_position) = fixture::position(ra_fixture_before);
374 let diagnostic = analysis
376 &DiagnosticsConfig::default(),
377 AssistResolveStrategy::All,
378 file_position.file_id,
383 let fix = &diagnostic.fixes.unwrap()[nth];
385 let source_change = fix.source_change.as_ref().unwrap();
386 let file_id = *source_change.source_file_edits.keys().next().unwrap();
387 let mut actual = analysis.file_text(file_id).unwrap().to_string();
389 for edit in source_change.source_file_edits.values() {
390 edit.apply(&mut actual);
395 assert_eq_text!(&after, &actual);
397 fix.target.contains_inclusive(file_position.offset),
398 "diagnostic fix range {:?} does not touch cursor position {:?}",
403 /// Checks that there's a diagnostic *without* fix at `$0`.
404 fn check_no_fix(ra_fixture: &str) {
405 let (analysis, file_position) = fixture::position(ra_fixture);
406 let diagnostic = analysis
408 &DiagnosticsConfig::default(),
409 AssistResolveStrategy::All,
410 file_position.file_id,
415 assert!(diagnostic.fixes.is_none(), "got a fix when none was expected: {:?}", diagnostic);
418 /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
419 /// apply to the file containing the cursor.
420 pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
421 let (analysis, files) = fixture::files(ra_fixture);
422 let diagnostics = files
424 .flat_map(|file_id| {
426 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
429 .collect::<Vec<_>>();
430 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
433 pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) {
434 let (analysis, file_id) = fixture::file(ra_fixture);
435 let diagnostics = analysis
436 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
438 expect.assert_debug_eq(&diagnostics)
442 pub(crate) fn check_diagnostics(ra_fixture: &str) {
443 check_diagnostics_with_inactive_code(ra_fixture, false)
447 pub(crate) fn check_diagnostics_with_inactive_code(ra_fixture: &str, with_inactive_code: bool) {
448 let (analysis, file_id) = fixture::file(ra_fixture);
449 let diagnostics = analysis
450 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
453 let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
454 let mut actual = diagnostics
456 .filter(|d| d.code != Some(DiagnosticCode("inactive-code")) || with_inactive_code)
457 .map(|d| (d.range, d.message))
458 .collect::<Vec<_>>();
459 actual.sort_by_key(|(range, _)| range.start());
460 assert_eq!(expected, actual);
464 fn range_mapping_out_of_macros() {
465 // FIXME: this is very wrong, but somewhat tricky to fix.
472 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
475 let _x = id![Foo { a: $042 }];
478 pub struct Foo { pub a: i32, pub b: i32 }
485 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
488 let _x = id![Foo { a: 42 }];
491 pub struct Foo { pub a: i32, pub b: i32 }
497 fn test_check_unnecessary_braces_in_use_statement() {
498 check_no_diagnostics(
511 check_no_diagnostics(
569 mod a { mod c {} mod d { mod e {} } }
570 use a::{c, d::{e$0}};
573 mod a { mod c {} mod d { mod e {} } }
580 fn test_disabled_diagnostics() {
581 let mut config = DiagnosticsConfig::default();
582 config.disabled.insert("unresolved-module".into());
584 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
587 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
588 assert!(diagnostics.is_empty());
590 let diagnostics = analysis
591 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
593 assert!(!diagnostics.is_empty());
597 fn unlinked_file_prepend_first_item() {
598 cov_mark::check!(unlinked_file_prepend_before_first_item);
599 // Only tests the first one for `pub mod` since the rest are the same
623 fn unlinked_file_append_mod() {
624 cov_mark::check!(unlinked_file_append_to_existing_mods);
636 mod preexisting_bottom;)
650 mod preexisting_bottom;)
656 fn unlinked_file_insert_in_empty_file() {
657 cov_mark::check!(unlinked_file_empty_file);
671 fn unlinked_file_old_style_modrs() {
689 fn unlinked_file_new_style_mod() {
705 fn unlinked_file_with_cfg_off() {
706 cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
720 fn unlinked_file_with_cfg_on() {
721 check_no_diagnostics(
733 fn break_outside_of_loop() {
737 //^^^^^ break outside of loop
743 fn no_such_field_diagnostics() {
746 struct S { foo: i32, bar: () }
750 //^ Missing structure fields:
754 //^^^^^^^ no such field
762 fn no_such_field_with_feature_flag_diagnostics() {
765 //- /lib.rs crate:foo cfg:feature=foo
768 #[cfg(feature = "foo")]
773 #[cfg(feature = "foo")]
774 pub(crate) fn new(my_val: usize, bar: bool) -> Self {
777 #[cfg(not(feature = "foo"))]
778 pub(crate) fn new(my_val: usize, _bar: bool) -> Self {
787 fn no_such_field_enum_with_feature_flag_diagnostics() {
790 //- /lib.rs crate:foo cfg:feature=foo
792 #[cfg(not(feature = "foo"))]
794 #[cfg(feature = "foo")]
810 fn no_such_field_with_feature_flag_diagnostics_on_struct_lit() {
813 //- /lib.rs crate:foo cfg:feature=foo
815 #[cfg(feature = "foo")]
817 #[cfg(not(feature = "foo"))]
822 #[cfg(feature = "foo")]
823 fn new(foo: u32) -> Self {
826 #[cfg(not(feature = "foo"))]
827 fn new(bar: u32) -> Self {
830 fn new2(bar: u32) -> Self {
831 #[cfg(feature = "foo")]
832 { Self { foo: bar } }
833 #[cfg(not(feature = "foo"))]
836 fn new2(val: u32) -> Self {
838 #[cfg(feature = "foo")]
840 #[cfg(not(feature = "foo"))]
850 fn no_such_field_with_type_macro() {
853 macro_rules! Type { () => { u32 }; }
854 struct Foo { bar: Type![] }
866 fn missing_unsafe_diagnostic_with_raw_ptr() {
870 let x = &5 as *const usize;
871 unsafe { let y = *x; }
873 } //^^ This operation is unsafe and requires an unsafe function or block
879 fn missing_unsafe_diagnostic_with_unsafe_call() {
885 unsafe fn unsafe_fn(&self) {
886 let x = &5 as *const usize;
891 unsafe fn unsafe_fn() {
892 let x = &5 as *const usize;
898 //^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
899 HasUnsafe.unsafe_fn();
900 //^^^^^^^^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
903 HasUnsafe.unsafe_fn();
911 fn missing_unsafe_diagnostic_with_static_mut() {
918 static mut STATIC_MUT: Ty = Ty { a: 0 };
921 let x = STATIC_MUT.a;
922 //^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
924 let x = STATIC_MUT.a;
932 fn no_missing_unsafe_diagnostic_with_safe_intrinsic() {
935 extern "rust-intrinsic" {
936 pub fn bitreverse(x: u32) -> u32; // Safe intrinsic
937 pub fn floorf32(x: f32) -> f32; // Unsafe intrinsic
941 let _ = bitreverse(12);
942 let _ = floorf32(12.0);
943 //^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
949 // Register the required standard library types to make the tests work
950 fn add_filter_map_with_find_next_boilerplate(body: &str) -> String {
952 //- /main.rs crate:main deps:core
953 use core::iter::Iterator;
954 use core::option::Option::{self, Some, None};
957 //- /core/lib.rs crate:core
959 pub enum Option<T> { Some(T), None }
964 fn filter_map<B, F>(self, f: F) -> FilterMap where F: FnMut(Self::Item) -> Option<B> { FilterMap }
965 fn next(&mut self) -> Option<Self::Item>;
967 pub struct FilterMap {}
968 impl Iterator for FilterMap {
970 fn next(&mut self) -> i32 { 7 }
974 format!("{}{}{}", prefix, body, suffix)
978 fn replace_filter_map_next_with_find_map2() {
979 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
982 let m = [1, 2, 3].iter().filter_map(|x| if *x == 2 { Some (4) } else { None }).next();
983 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ replace filter_map(..).next() with find_map(..)
990 fn replace_filter_map_next_with_find_map_no_diagnostic_without_next() {
991 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
996 .filter_map(|x| if *x == 2 { Some (4) } else { None })
1004 fn replace_filter_map_next_with_find_map_no_diagnostic_with_intervening_methods() {
1005 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1010 .filter_map(|x| if *x == 2 { Some (4) } else { None })
1019 fn replace_filter_map_next_with_find_map_no_diagnostic_if_not_in_chain() {
1020 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1025 .filter_map(|x| if *x == 2 { Some (4) } else { None });
1033 fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
1036 struct S { foo: i32, bar: () }
1037 fn baz(s: S) -> i32 {
1039 S { foo, .. } => foo,
1047 fn missing_record_pat_field_box() {
1050 struct S { s: Box<u32> }
1052 let S { box s } = a;
1059 fn missing_record_pat_field_ref() {
1064 let S { ref s } = a;
1071 fn simple_free_fn_zero() {
1076 //^^^^^^^ Expected 0 arguments, found 1
1089 fn simple_free_fn_one() {
1094 //^^^^^ Expected 1 argument, found 0
1111 impl S { fn method(&self) {} }
1115 } //^^^^^^^^^^^ Expected 1 argument, found 0
1122 impl S { fn method(&self) {} }
1133 fn method_with_arg() {
1137 impl S { fn method(&self, arg: u8) {} }
1141 } //^^^^^^^^^^ Expected 1 argument, found 0
1148 impl S { fn method(&self, arg: u8) {} }
1159 fn method_unknown_receiver() {
1160 // note: this is incorrect code, so there might be errors on this in the
1161 // future, but we shouldn't emit an argument count diagnostic here
1164 trait Foo { fn method(&self, arg: usize) {} }
1178 struct Tup(u8, u16);
1181 } //^^^^^^ Expected 2 arguments, found 1
1190 enum En { Variant(u8, u16), }
1193 } //^^^^^^^^^^^^^^ Expected 2 arguments, found 1
1199 fn enum_variant_type_macro() {
1212 //^^^^^^^^^^^^^^ Expected 1 argument, found 2
1214 //^^^^^^^^^^ Expected 1 argument, found 0
1226 fn fixed(fixed: u8);
1227 fn varargs(fixed: u8, ...);
1235 //^^^^^^^^^^^ Expected 1 argument, found 2
1248 fn arg_count_lambda() {
1254 //^^^ Expected 1 argument, found 0
1257 //^^^^^^^^^ Expected 1 argument, found 2
1264 fn cfgd_out_call_arguments() {
1267 struct C(#[cfg(FALSE)] ());
1280 C::new().method(#[cfg(FALSE)] 0);
1287 fn cfgd_out_fn_params() {
1290 fn foo(#[cfg(NEVER)] x: ()) {}
1295 fn method(#[cfg(NEVER)] self) {}
1296 fn method2(#[cfg(NEVER)] self, arg: u8) {}
1297 fn method3(self, #[cfg(NEVER)] arg: u8) {}
1301 fn fixed(fixed: u8, #[cfg(NEVER)] ...);
1302 fn varargs(#[cfg(not(NEVER))] ...);
1321 fn missing_semicolon() {
1324 fn test() -> i32 { 123; }
1325 //^^^ Remove this semicolon
1331 fn import_extern_crate_clash_with_inner_item() {
1332 // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
1336 //- /lib.rs crate:lib deps:jwt
1339 use permissions::jwt;
1343 jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
1348 pub struct Claims {}
1351 //- /jwt/lib.rs crate:jwt
1361 pub(super) mod match_check_tests {
1362 use crate::diagnostics::tests::check_diagnostics;
1370 //^^ Missing match arm
1372 //^^^^ Missing match arm
1374 match () { _ => (), }
1375 match () { () => (), }
1376 match (()) { (()) => (), }
1383 fn tuple_of_two_empty_tuple() {
1388 //^^^^^^^^ Missing match arm
1390 match ((), ()) { ((), ()) => (), }
1402 //^^^^^ Missing match arm
1403 match false { true => (), }
1404 //^^^^^ Missing match arm
1405 match (false, true) {}
1406 //^^^^^^^^^^^^^ Missing match arm
1407 match (false, true) { (true, true) => (), }
1408 //^^^^^^^^^^^^^ Missing match arm
1409 match (false, true) {
1410 //^^^^^^^^^^^^^ Missing match arm
1411 (false, true) => (),
1412 (false, false) => (),
1413 (true, false) => (),
1415 match (false, true) { (true, _x) => (), }
1416 //^^^^^^^^^^^^^ Missing match arm
1418 match false { true => (), false => (), }
1419 match (false, true) {
1421 (true, false) => (),
1424 match (false, true) {
1426 (true, false) => (),
1427 (false, true) => (),
1428 (false, false) => (),
1430 match (false, true) {
1432 (false, true) => (),
1433 (false, false) => (),
1435 match (false, true, false) {
1439 match (false, true, false) {
1443 match (false, true, false) { (..) => (), }
1450 fn tuple_of_tuple_and_bools() {
1454 match (false, ((), false)) {}
1455 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1456 match (false, ((), false)) { (true, ((), true)) => (), }
1457 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1458 match (false, ((), false)) { (true, _) => (), }
1459 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1461 match (false, ((), false)) {
1462 (true, ((), true)) => (),
1463 (true, ((), false)) => (),
1464 (false, ((), true)) => (),
1465 (false, ((), false)) => (),
1467 match (false, ((), false)) {
1468 (true, ((), true)) => (),
1469 (true, ((), false)) => (),
1481 enum Either { A, B, }
1485 //^^^^^^^^^ Missing match arm
1486 match Either::B { Either::A => (), }
1487 //^^^^^^^^^ Missing match arm
1490 //^^^^^^^^^^ Missing match arm
1495 Either::A => (), Either::B => (),
1498 Either::A => (), Either::B => (),
1506 fn enum_containing_bool() {
1509 enum Either { A(bool), B }
1513 //^^^^^^^^^ Missing match arm
1515 //^^^^^^^^^ Missing match arm
1516 Either::A(true) => (), Either::B => ()
1520 Either::A(true) => (),
1521 Either::A(false) => (),
1539 fn enum_different_sizes() {
1542 enum Either { A(bool), B(bool, bool) }
1545 match Either::A(false) {
1546 //^^^^^^^^^^^^^^^^ Missing match arm
1548 Either::B(false, _) => (),
1551 match Either::A(false) {
1553 Either::B(true, _) => (),
1554 Either::B(false, _) => (),
1556 match Either::A(false) {
1557 Either::A(true) | Either::A(false) => (),
1558 Either::B(true, _) => (),
1559 Either::B(false, _) => (),
1567 fn tuple_of_enum_no_diagnostic() {
1570 enum Either { A(bool), B(bool, bool) }
1571 enum Either2 { C, D }
1574 match (Either::A(false), Either2::C) {
1575 (Either::A(true), _) | (Either::A(false), _) => (),
1576 (Either::B(true, _), Either2::C) => (),
1577 (Either::B(false, _), Either2::C) => (),
1578 (Either::B(_, _), Either2::D) => (),
1586 fn or_pattern_no_diagnostic() {
1592 match (Either::A, Either::B) {
1593 (Either::A | Either::B, _) => (),
1600 fn mismatched_types() {
1601 // Match statements with arms that don't match the
1602 // expression pattern do not fire this diagnostic.
1605 enum Either { A, B }
1606 enum Either2 { C, D }
1611 // ^^^^^^^^^^ Internal: match check bailed out
1614 match (true, false) {
1615 (true, false, true) => (),
1616 // ^^^^^^^^^^^^^^^^^^^ Internal: match check bailed out
1619 match (true, false) { (true,) => {} }
1620 // ^^^^^^^ Internal: match check bailed out
1621 match (0) { () => () }
1622 // ^^ Internal: match check bailed out
1623 match Unresolved::Bar { Unresolved::Baz => () }
1630 fn mismatched_types_in_or_patterns() {
1634 match false { true | () => {} }
1635 // ^^^^^^^^^ Internal: match check bailed out
1636 match (false,) { (true | (),) => {} }
1637 // ^^^^^^^^^^^^ Internal: match check bailed out
1644 fn malformed_match_arm_tuple_enum_missing_pattern() {
1645 // We are testing to be sure we don't panic here when the match
1646 // arm `Either::B` is missing its pattern.
1649 enum Either { A, B(u32) }
1662 fn malformed_match_arm_extra_fields() {
1665 enum A { B(isize, isize), C }
1668 A::B(_, _, _) => (),
1669 // ^^^^^^^^^^^^^ Internal: match check bailed out
1673 // ^^^^^^^ Internal: match check bailed out
1681 fn expr_diverges() {
1684 enum Either { A, B }
1689 // ^^^^^^^^^ Internal: match check bailed out
1694 // ^^^^^^^^^ Internal: match check bailed out
1696 match loop { break Foo::A } {
1697 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1700 match loop { break Foo::A } {
1710 fn expr_partially_diverges() {
1713 enum Either<T> { A(T), B }
1715 fn foo() -> Either<!> { Either::B }
1718 Either::A(val) => val,
1730 enum Either { A { foo: bool }, B }
1733 let a = Either::A { foo: true };
1735 //^ Missing match arm
1736 match a { Either::A { foo: true } => () }
1737 //^ Missing match arm
1739 Either::A { } => (),
1740 //^^^^^^^^^ Missing structure fields:
1745 //^ Missing match arm
1746 Either::A { } => (),
1747 } //^^^^^^^^^ Missing structure fields:
1751 Either::A { foo: true } => (),
1752 Either::A { foo: false } => (),
1756 Either::A { foo: _ } => (),
1765 fn enum_record_fields_out_of_order() {
1769 A { foo: bool, bar: () },
1774 let a = Either::A { foo: true, bar: () };
1776 //^ Missing match arm
1777 Either::A { bar: (), foo: false } => (),
1778 Either::A { foo: true, bar: () } => (),
1782 Either::A { bar: (), foo: false } => (),
1783 Either::A { foo: true, bar: () } => (),
1792 fn enum_record_ellipsis() {
1796 A { foo: bool, bar: bool },
1803 //^ Missing match arm
1804 Either::A { foo: true, .. } => (),
1808 //^ Missing match arm
1809 Either::A { .. } => (),
1813 Either::A { foo: true, .. } => (),
1814 Either::A { foo: false, .. } => (),
1819 Either::A { .. } => (),
1828 fn enum_tuple_partial_ellipsis() {
1832 A(bool, bool, bool, bool),
1838 //^^^^^^^^^ Missing match arm
1839 Either::A(true, .., true) => (),
1840 Either::A(true, .., false) => (),
1841 Either::A(false, .., false) => (),
1845 //^^^^^^^^^ Missing match arm
1846 Either::A(true, .., true) => (),
1847 Either::A(true, .., false) => (),
1848 Either::A(.., true) => (),
1853 Either::A(true, .., true) => (),
1854 Either::A(true, .., false) => (),
1855 Either::A(false, .., true) => (),
1856 Either::A(false, .., false) => (),
1860 Either::A(true, .., true) => (),
1861 Either::A(true, .., false) => (),
1862 Either::A(.., true) => (),
1863 Either::A(.., false) => (),
1877 fn enum_(never: Never) {
1880 fn enum_ref(never: &Never) {
1882 //^^^^^ Missing match arm
1895 enum Option<T> { Some(T), None }
1898 // `Never` is deliberately not defined so that it's an uninferred type.
1899 match Option::<Never>::None {
1901 Some(never) => match never {},
1902 // ^^^^^^^^^^^ Internal: match check bailed out
1904 match Option::<Never>::None {
1905 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1906 Option::Some(_never) => {},
1914 fn tuple_of_bools_with_ellipsis_at_end_missing_arm() {
1918 match (false, true, false) {
1919 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1927 fn tuple_of_bools_with_ellipsis_at_beginning_missing_arm() {
1931 match (false, true, false) {
1932 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1940 fn tuple_of_bools_with_ellipsis_in_middle_missing_arm() {
1944 match (false, true, false) {
1945 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1946 (true, .., false) => (),
1953 fn record_struct() {
1955 r#"struct Foo { a: bool }
1958 //^ Missing match arm
1959 match f { Foo { a: true } => () }
1960 //^ Missing match arm
1961 match &f { Foo { a: true } => () }
1962 //^^ Missing match arm
1963 match f { Foo { a: _ } => () }
1965 Foo { a: true } => (),
1966 Foo { a: false } => (),
1969 Foo { a: true } => (),
1970 Foo { a: false } => (),
1980 r#"struct Foo(bool);
1983 //^ Missing match arm
1984 match f { Foo(true) => () }
1985 //^ Missing match arm
2001 //^ Missing match arm
2002 match f { Foo => () }
2009 fn record_struct_ellipsis() {
2011 r#"struct Foo { foo: bool, bar: bool }
2013 match f { Foo { foo: true, .. } => () }
2014 //^ Missing match arm
2016 //^ Missing match arm
2017 Foo { foo: true, .. } => (),
2018 Foo { bar: false, .. } => ()
2020 match f { Foo { .. } => () }
2022 Foo { foo: true, .. } => (),
2023 Foo { foo: false, .. } => ()
2035 enum Either { A(bool), B }
2037 //^^^^^^^^^ Missing match arm
2038 Either::A(true | false) => (),
2046 fn no_panic_at_unimplemented_subpattern_type() {
2051 match v { S{ a } => {} }
2052 match v { S{ a: _x } => {} }
2053 match v { S{ a: 'a' } => {} }
2054 //^^^^^^^^^^^ Internal: match check bailed out
2055 match v { S{..} => {} }
2058 //^ Missing match arm
2073 match true { _x @ true => {} }
2074 //^^^^ Missing match arm
2081 fn binding_ref_has_correct_type() {
2082 // Asserts `PatKind::Binding(ref _x): bool`, not &bool.
2083 // If that's not true match checking will panic with "incompatible constructors"
2084 // FIXME: make facilities to test this directly like `tests::check_infer(..)`
2089 // FIXME: this should not bail out but current behavior is such as the old algorithm.
2090 // ExprValidator::validate_match(..) checks types of top level patterns incorrecly.
2093 // ^^^^^^ Internal: match check bailed out
2106 fn enum_non_exhaustive() {
2109 //- /lib.rs crate:lib
2113 match E::A { _ => {} }
2123 //- /main.rs crate:main deps:lib
2126 match E::A { _ => {} }
2128 //^^^^ Missing match arm
2133 //^^^^ Missing match arm
2152 //^^^^ Missing match arm
2162 fn pattern_type_is_of_substitution() {
2163 cov_mark::check!(match_check_wildcard_expanded_to_substitutions);
2178 fn record_struct_no_such_field() {
2183 match f { Foo { bar } => () }
2184 // ^^^^^^^^^^^ Internal: match check bailed out
2191 fn match_ergonomics_issue_9095() {
2194 enum Foo<T> { A(T) }
2196 match &Foo::A(true) {
2205 mod false_negatives {
2206 //! The implementation of match checking here is a work in progress. As we roll this out, we
2207 //! prefer false negatives to false positives (ideally there would be no false positives). This
2208 //! test module should document known false negatives. Eventually we will have a complete
2209 //! implementation of match checking and this module will be empty.
2211 //! The reasons for documenting known false negatives:
2213 //! 1. It acts as a backlog of work that can be done to improve the behavior of the system.
2214 //! 2. It ensures the code doesn't panic when handling these cases.
2219 // We don't currently check integer exhaustiveness.
2225 // ^^ Internal: match check bailed out
2234 fn reference_patterns_at_top_level() {
2240 // ^^^^^ Internal: match check bailed out
2248 fn reference_patterns_in_fields() {
2254 // ^^^^^^^ Internal: match check bailed out
2258 // ^^^^^^^^ Internal: match check bailed out
2268 mod decl_check_tests {
2269 use crate::diagnostics::tests::check_diagnostics;
2272 fn incorrect_function_name() {
2275 fn NonSnakeCaseName() {}
2276 // ^^^^^^^^^^^^^^^^ Function `NonSnakeCaseName` should have snake_case name, e.g. `non_snake_case_name`
2282 fn incorrect_function_params() {
2285 fn foo(SomeParam: u8) {}
2286 // ^^^^^^^^^ Parameter `SomeParam` should have snake_case name, e.g. `some_param`
2288 fn foo2(ok_param: &str, CAPS_PARAM: u8) {}
2289 // ^^^^^^^^^^ Parameter `CAPS_PARAM` should have snake_case name, e.g. `caps_param`
2295 fn incorrect_variable_names() {
2299 let SOME_VALUE = 10;
2300 // ^^^^^^^^^^ Variable `SOME_VALUE` should have snake_case name, e.g. `some_value`
2301 let AnotherValue = 20;
2302 // ^^^^^^^^^^^^ Variable `AnotherValue` should have snake_case name, e.g. `another_value`
2309 fn incorrect_struct_names() {
2312 struct non_camel_case_name {}
2313 // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName`
2315 struct SCREAMING_CASE {}
2316 // ^^^^^^^^^^^^^^ Structure `SCREAMING_CASE` should have CamelCase name, e.g. `ScreamingCase`
2322 fn no_diagnostic_for_camel_cased_acronyms_in_struct_name() {
2331 fn incorrect_struct_field() {
2334 struct SomeStruct { SomeField: u8 }
2335 // ^^^^^^^^^ Field `SomeField` should have snake_case name, e.g. `some_field`
2341 fn incorrect_enum_names() {
2344 enum some_enum { Val(u8) }
2345 // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum`
2348 // ^^^^^^^^^ Enum `SOME_ENUM` should have CamelCase name, e.g. `SomeEnum`
2354 fn no_diagnostic_for_camel_cased_acronyms_in_enum_name() {
2363 fn incorrect_enum_variant_name() {
2366 enum SomeEnum { SOME_VARIANT(u8) }
2367 // ^^^^^^^^^^^^ Variant `SOME_VARIANT` should have CamelCase name, e.g. `SomeVariant`
2373 fn incorrect_const_name() {
2376 const some_weird_const: u8 = 10;
2377 // ^^^^^^^^^^^^^^^^ Constant `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2383 fn incorrect_static_name() {
2386 static some_weird_const: u8 = 10;
2387 // ^^^^^^^^^^^^^^^^ Static variable `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2393 fn fn_inside_impl_struct() {
2397 // ^^^^^^^^^^ Structure `someStruct` should have CamelCase name, e.g. `SomeStruct`
2400 fn SomeFunc(&self) {
2401 // ^^^^^^^^ Function `SomeFunc` should have snake_case name, e.g. `some_func`
2402 let WHY_VAR_IS_CAPS = 10;
2403 // ^^^^^^^^^^^^^^^ Variable `WHY_VAR_IS_CAPS` should have snake_case name, e.g. `why_var_is_caps`
2411 fn no_diagnostic_for_enum_varinats() {
2414 enum Option { Some, None }
2417 match Option::None {
2430 enum Option { Some, None }
2433 match Option::None {
2434 SOME_VAR @ None => (),
2435 // ^^^^^^^^ Variable `SOME_VAR` should have snake_case name, e.g. `some_var`
2444 fn allow_attributes() {
2447 #[allow(non_snake_case)]
2448 fn NonSnakeCaseName(SOME_VAR: u8) -> u8{
2449 // cov_flags generated output from elsewhere in this file
2452 static lower_case: u8;
2455 let OtherVar = SOME_VAR + 1;
2459 #[allow(nonstandard_style)]
2460 mod CheckNonstandardStyle {
2461 fn HiImABadFnName() {}
2466 fn HiImABadFnName() {}
2470 #![allow(non_snake_case)]
2471 fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {}
2474 #[allow(non_snake_case, non_camel_case_types)]
2475 pub struct some_type {
2480 #[allow(non_upper_case_globals)]
2481 pub const some_const: u8 = 10;
2483 #[allow(non_upper_case_globals)]
2484 pub static SomeStatic: u8 = 10;
2490 fn allow_attributes_crate_attr() {
2493 #![allow(non_snake_case)]
2496 fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {}
2504 fn bug_trait_inside_fn() {
2506 // This is broken, and in fact, should not even be looked at by this
2507 // lint in the first place. There's weird stuff going on in the
2508 // collection phase.
2509 // It's currently being brought in by:
2510 // * validate_func on `a` recursing into modules
2511 // * then it finds the trait and then the function while iterating
2513 // * then validate_func is called on Dirty
2514 // * ... which then proceeds to look at some unknown module taking no
2515 // attrs from either the impl or the fn a, and then finally to the root
2518 // It should find the attribute on the trait, but it *doesn't even see
2519 // the trait* as far as I can tell.
2527 // this comes out of bitflags, mostly
2528 #[allow(non_snake_case)]
2530 const HiImAlsoBad: u8 = 2;
2532 fn Dirty(&self) -> bool {
2545 fn bug_traits_arent_checked() {
2546 // FIXME: Traits and functions in traits aren't currently checked by
2547 // r-a, even though rustc will complain about them.
2551 // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait`
2553 // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function`
2555 // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function`
2562 fn ignores_extern_items() {
2563 cov_mark::check!(extern_func_incorrect_case_ignored);
2564 cov_mark::check!(extern_static_incorrect_case_ignored);
2568 fn NonSnakeCaseName(SOME_VAR: u8) -> u8;
2569 pub static SomeStatic: u8 = 10;
2576 fn infinite_loop_inner_items() {
2588 #[test] // Issue #8809.
2589 fn parenthesized_parameter() {
2590 check_diagnostics(r#"fn f((O): _) {}"#)