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.
11 use std::cell::RefCell;
15 diagnostics::{Diagnostic as _, DiagnosticCode, DiagnosticSinkBuilder},
18 use ide_assists::AssistResolveStrategy;
19 use ide_db::{base_db::SourceDatabase, RootDatabase};
20 use itertools::Itertools;
21 use rustc_hash::FxHashSet;
24 SyntaxNode, SyntaxNodePtr, TextRange, TextSize,
26 use text_edit::TextEdit;
27 use unlinked_file::UnlinkedFile;
29 use crate::{Assist, AssistId, AssistKind, FileId, Label, SourceChange};
31 use self::fixes::DiagnosticWithFixes;
34 pub struct Diagnostic {
35 // pub name: Option<String>,
38 pub severity: Severity,
39 pub fixes: Option<Vec<Assist>>,
41 pub code: Option<DiagnosticCode>,
45 fn error(range: TextRange, message: String) -> Self {
46 Self { message, range, severity: Severity::Error, fixes: None, unused: false, code: None }
49 fn hint(range: TextRange, message: String) -> Self {
53 severity: Severity::WeakWarning,
60 fn with_fixes(self, fixes: Option<Vec<Assist>>) -> Self {
61 Self { fixes, ..self }
64 fn with_unused(self, unused: bool) -> Self {
65 Self { unused, ..self }
68 fn with_code(self, code: Option<DiagnosticCode>) -> Self {
73 #[derive(Debug, Copy, Clone)]
79 #[derive(Default, Debug, Clone)]
80 pub struct DiagnosticsConfig {
81 pub disable_experimental: bool,
82 pub disabled: FxHashSet<String>,
85 pub(crate) fn diagnostics(
87 config: &DiagnosticsConfig,
88 resolve: &AssistResolveStrategy,
90 ) -> Vec<Diagnostic> {
91 let _p = profile::span("diagnostics");
92 let sema = Semantics::new(db);
93 let parse = db.parse(file_id);
94 let mut res = Vec::new();
96 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
102 .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
105 for node in parse.tree().syntax().descendants() {
106 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
107 field_shorthand::check(&mut res, file_id, &node);
109 let res = RefCell::new(res);
110 let sink_builder = DiagnosticSinkBuilder::new()
111 .on::<hir::diagnostics::UnresolvedModule, _>(|d| {
112 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
114 .on::<hir::diagnostics::MissingFields, _>(|d| {
115 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
117 .on::<hir::diagnostics::MissingOkOrSomeInTailExpr, _>(|d| {
118 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
120 .on::<hir::diagnostics::NoSuchField, _>(|d| {
121 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
123 .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| {
124 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
126 .on::<hir::diagnostics::IncorrectCase, _>(|d| {
127 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
129 .on::<hir::diagnostics::ReplaceFilterMapNextWithFindMap, _>(|d| {
130 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
132 .on::<hir::diagnostics::InactiveCode, _>(|d| {
133 // If there's inactive code somewhere in a macro, don't propagate to the call-site.
134 if d.display_source().file_id.expansion_info(db).is_some() {
138 // Override severity and mark as unused.
139 res.borrow_mut().push(
141 sema.diagnostics_display_range(d.display_source()).range,
145 .with_code(Some(d.code())),
148 .on::<UnlinkedFile, _>(|d| {
149 // Limit diagnostic to the first few characters in the file. This matches how VS Code
150 // renders it with the full span, but on other editors, and is less invasive.
151 let range = sema.diagnostics_display_range(d.display_source()).range;
152 let range = range.intersect(TextRange::up_to(TextSize::of("..."))).unwrap_or(range);
154 // Override severity and mark as unused.
155 res.borrow_mut().push(
156 Diagnostic::hint(range, d.message())
157 .with_fixes(d.fixes(&sema, resolve))
158 .with_code(Some(d.code())),
161 .on::<hir::diagnostics::UnresolvedProcMacro, _>(|d| {
162 // Use more accurate position if available.
163 let display_range = d
165 .unwrap_or_else(|| sema.diagnostics_display_range(d.display_source()).range);
167 // FIXME: it would be nice to tell the user whether proc macros are currently disabled
169 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
171 .on::<hir::diagnostics::UnresolvedMacroCall, _>(|d| {
172 let last_path_segment = sema.db.parse_or_expand(d.file).and_then(|root| {
176 .and_then(|it| it.segment())
177 .and_then(|it| it.name_ref())
178 .map(|it| InFile::new(d.file, SyntaxNodePtr::new(it.syntax())))
180 let diagnostics = last_path_segment.unwrap_or_else(|| d.display_source());
181 let display_range = sema.diagnostics_display_range(diagnostics).range;
183 .push(Diagnostic::error(display_range, d.message()).with_code(Some(d.code())));
185 .on::<hir::diagnostics::UnimplementedBuiltinMacro, _>(|d| {
186 let display_range = sema.diagnostics_display_range(d.display_source()).range;
188 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
190 // Only collect experimental diagnostics when they're enabled.
191 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
192 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
194 // Finalize the `DiagnosticSink` building process.
195 let mut sink = sink_builder
196 // Diagnostics not handled above get no fix and default treatment.
198 res.borrow_mut().push(
200 sema.diagnostics_display_range(d.display_source()).range,
203 .with_code(Some(d.code())),
207 let internal_diagnostics = cfg!(test);
208 match sema.to_module_def(file_id) {
209 Some(m) => m.diagnostics(db, &mut sink, internal_diagnostics),
211 sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(&parse.tree().syntax()) });
219 fn diagnostic_with_fix<D: DiagnosticWithFixes>(
221 sema: &Semantics<RootDatabase>,
222 resolve: &AssistResolveStrategy,
224 Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message())
225 .with_fixes(d.fixes(&sema, resolve))
226 .with_code(Some(d.code()))
229 fn warning_with_fix<D: DiagnosticWithFixes>(
231 sema: &Semantics<RootDatabase>,
232 resolve: &AssistResolveStrategy,
234 Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message())
235 .with_fixes(d.fixes(&sema, resolve))
236 .with_code(Some(d.code()))
239 fn check_unnecessary_braces_in_use_statement(
240 acc: &mut Vec<Diagnostic>,
244 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
245 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
246 // If there is a comment inside the bracketed `use`,
247 // assume it is a commented out module path and don't show diagnostic.
248 if use_tree_list.has_inner_comment() {
252 let use_range = use_tree_list.syntax().text_range();
254 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
256 let to_replace = single_use_tree.syntax().text().to_string();
257 let mut edit_builder = TextEdit::builder();
258 edit_builder.delete(use_range);
259 edit_builder.insert(use_range.start(), to_replace);
260 edit_builder.finish()
264 Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
265 .with_fixes(Some(vec![fix(
267 "Remove unnecessary braces",
268 SourceChange::from_text_edit(file_id, edit),
277 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
278 single_use_tree: &ast::UseTree,
279 ) -> Option<TextEdit> {
280 let use_tree_list_node = single_use_tree.syntax().parent()?;
281 if single_use_tree.path()?.segment()?.self_token().is_some() {
282 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
283 let end = use_tree_list_node.text_range().end();
284 return Some(TextEdit::delete(TextRange::new(start, end)));
289 fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
290 let mut res = unresolved_fix(id, label, target);
291 res.source_change = Some(source_change);
295 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
296 assert!(!id.contains(' '));
298 id: AssistId(id, AssistKind::QuickFix),
299 label: Label::new(label),
308 use expect_test::Expect;
309 use hir::diagnostics::DiagnosticCode;
310 use ide_assists::AssistResolveStrategy;
311 use stdx::trim_indent;
312 use test_utils::{assert_eq_text, extract_annotations};
314 use crate::{fixture, DiagnosticsConfig};
316 /// Takes a multi-file input fixture with annotated cursor positions,
318 /// * a diagnostic is produced
319 /// * the first diagnostic fix trigger range touches the input cursor position
320 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
322 pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
323 check_nth_fix(0, ra_fixture_before, ra_fixture_after);
325 /// Takes a multi-file input fixture with annotated cursor positions,
327 /// * a diagnostic is produced
328 /// * every diagnostic fixes trigger range touches the input cursor position
329 /// * that the contents of the file containing the cursor match `after` after each diagnostic fix is applied
330 pub(crate) fn check_fixes(ra_fixture_before: &str, ra_fixtures_after: Vec<&str>) {
331 for (i, ra_fixture_after) in ra_fixtures_after.iter().enumerate() {
332 check_nth_fix(i, ra_fixture_before, ra_fixture_after)
337 fn check_nth_fix(nth: usize, ra_fixture_before: &str, ra_fixture_after: &str) {
338 let after = trim_indent(ra_fixture_after);
340 let (analysis, file_position) = fixture::position(ra_fixture_before);
341 let diagnostic = analysis
343 &DiagnosticsConfig::default(),
344 AssistResolveStrategy::All,
345 file_position.file_id,
350 let fix = &diagnostic.fixes.unwrap()[nth];
352 let source_change = fix.source_change.as_ref().unwrap();
353 let file_id = *source_change.source_file_edits.keys().next().unwrap();
354 let mut actual = analysis.file_text(file_id).unwrap().to_string();
356 for edit in source_change.source_file_edits.values() {
357 edit.apply(&mut actual);
362 assert_eq_text!(&after, &actual);
364 fix.target.contains_inclusive(file_position.offset),
365 "diagnostic fix range {:?} does not touch cursor position {:?}",
370 /// Checks that there's a diagnostic *without* fix at `$0`.
371 fn check_no_fix(ra_fixture: &str) {
372 let (analysis, file_position) = fixture::position(ra_fixture);
373 let diagnostic = analysis
375 &DiagnosticsConfig::default(),
376 AssistResolveStrategy::All,
377 file_position.file_id,
382 assert!(diagnostic.fixes.is_none(), "got a fix when none was expected: {:?}", diagnostic);
385 /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
386 /// apply to the file containing the cursor.
387 pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
388 let (analysis, files) = fixture::files(ra_fixture);
389 let diagnostics = files
391 .flat_map(|file_id| {
393 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
396 .collect::<Vec<_>>();
397 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
400 pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) {
401 let (analysis, file_id) = fixture::file(ra_fixture);
402 let diagnostics = analysis
403 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
405 expect.assert_debug_eq(&diagnostics)
408 pub(crate) fn check_diagnostics(ra_fixture: &str) {
409 let (analysis, file_id) = fixture::file(ra_fixture);
410 let diagnostics = analysis
411 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
414 let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
415 let mut actual = diagnostics
417 .filter(|d| d.code != Some(DiagnosticCode("inactive-code")))
418 .map(|d| (d.range, d.message))
419 .collect::<Vec<_>>();
420 actual.sort_by_key(|(range, _)| range.start());
421 assert_eq!(expected, actual);
425 fn test_unresolved_macro_range() {
429 //^^^ unresolved macro `foo::bar!`
435 fn unresolved_import_in_use_tree() {
436 // Only the relevant part of a nested `use` item should be highlighted.
439 use does_exist::{Exists, DoesntExist};
440 //^^^^^^^^^^^ unresolved import
442 use {does_not_exist::*, does_exist};
443 //^^^^^^^^^^^^^^^^^ unresolved import
445 use does_not_exist::{
447 //^ unresolved import
449 //^ unresolved import
451 //^ unresolved import
462 fn range_mapping_out_of_macros() {
463 // FIXME: this is very wrong, but somewhat tricky to fix.
470 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
473 let _x = id![Foo { a: $042 }];
476 pub struct Foo { pub a: i32, pub b: i32 }
483 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
486 let _x = id![Foo { a: 42 }];
489 pub struct Foo { pub a: i32, pub b: i32 }
495 fn test_check_unnecessary_braces_in_use_statement() {
496 check_no_diagnostics(
509 check_no_diagnostics(
567 mod a { mod c {} mod d { mod e {} } }
568 use a::{c, d::{e$0}};
571 mod a { mod c {} mod d { mod e {} } }
578 fn test_disabled_diagnostics() {
579 let mut config = DiagnosticsConfig::default();
580 config.disabled.insert("unresolved-module".into());
582 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
585 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
586 assert!(diagnostics.is_empty());
588 let diagnostics = analysis
589 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
591 assert!(!diagnostics.is_empty());
595 fn unlinked_file_prepend_first_item() {
596 cov_mark::check!(unlinked_file_prepend_before_first_item);
597 // Only tests the first one for `pub mod` since the rest are the same
621 fn unlinked_file_append_mod() {
622 cov_mark::check!(unlinked_file_append_to_existing_mods);
634 mod preexisting_bottom;)
648 mod preexisting_bottom;)
654 fn unlinked_file_insert_in_empty_file() {
655 cov_mark::check!(unlinked_file_empty_file);
669 fn unlinked_file_old_style_modrs() {
687 fn unlinked_file_new_style_mod() {
703 fn unlinked_file_with_cfg_off() {
704 cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
718 fn unlinked_file_with_cfg_on() {
719 check_no_diagnostics(
731 fn break_outside_of_loop() {
735 //^^^^^ break outside of loop
741 fn no_such_field_diagnostics() {
744 struct S { foo: i32, bar: () }
748 //^ Missing structure fields:
752 //^^^^^^^ no such field
760 fn no_such_field_with_feature_flag_diagnostics() {
763 //- /lib.rs crate:foo cfg:feature=foo
766 #[cfg(feature = "foo")]
771 #[cfg(feature = "foo")]
772 pub(crate) fn new(my_val: usize, bar: bool) -> Self {
775 #[cfg(not(feature = "foo"))]
776 pub(crate) fn new(my_val: usize, _bar: bool) -> Self {
785 fn no_such_field_enum_with_feature_flag_diagnostics() {
788 //- /lib.rs crate:foo cfg:feature=foo
790 #[cfg(not(feature = "foo"))]
792 #[cfg(feature = "foo")]
808 fn no_such_field_with_feature_flag_diagnostics_on_struct_lit() {
811 //- /lib.rs crate:foo cfg:feature=foo
813 #[cfg(feature = "foo")]
815 #[cfg(not(feature = "foo"))]
820 #[cfg(feature = "foo")]
821 fn new(foo: u32) -> Self {
824 #[cfg(not(feature = "foo"))]
825 fn new(bar: u32) -> Self {
828 fn new2(bar: u32) -> Self {
829 #[cfg(feature = "foo")]
830 { Self { foo: bar } }
831 #[cfg(not(feature = "foo"))]
834 fn new2(val: u32) -> Self {
836 #[cfg(feature = "foo")]
838 #[cfg(not(feature = "foo"))]
848 fn no_such_field_with_type_macro() {
851 macro_rules! Type { () => { u32 }; }
852 struct Foo { bar: Type![] }
864 fn missing_unsafe_diagnostic_with_raw_ptr() {
868 let x = &5 as *const usize;
869 unsafe { let y = *x; }
871 } //^^ This operation is unsafe and requires an unsafe function or block
877 fn missing_unsafe_diagnostic_with_unsafe_call() {
883 unsafe fn unsafe_fn(&self) {
884 let x = &5 as *const usize;
889 unsafe fn unsafe_fn() {
890 let x = &5 as *const usize;
896 //^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
897 HasUnsafe.unsafe_fn();
898 //^^^^^^^^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
901 HasUnsafe.unsafe_fn();
909 fn missing_unsafe_diagnostic_with_static_mut() {
916 static mut STATIC_MUT: Ty = Ty { a: 0 };
919 let x = STATIC_MUT.a;
920 //^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
922 let x = STATIC_MUT.a;
930 fn no_missing_unsafe_diagnostic_with_safe_intrinsic() {
933 extern "rust-intrinsic" {
934 pub fn bitreverse(x: u32) -> u32; // Safe intrinsic
935 pub fn floorf32(x: f32) -> f32; // Unsafe intrinsic
939 let _ = bitreverse(12);
940 let _ = floorf32(12.0);
941 //^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
947 // Register the required standard library types to make the tests work
948 fn add_filter_map_with_find_next_boilerplate(body: &str) -> String {
950 //- /main.rs crate:main deps:core
951 use core::iter::Iterator;
952 use core::option::Option::{self, Some, None};
955 //- /core/lib.rs crate:core
957 pub enum Option<T> { Some(T), None }
962 fn filter_map<B, F>(self, f: F) -> FilterMap where F: FnMut(Self::Item) -> Option<B> { FilterMap }
963 fn next(&mut self) -> Option<Self::Item>;
965 pub struct FilterMap {}
966 impl Iterator for FilterMap {
968 fn next(&mut self) -> i32 { 7 }
972 format!("{}{}{}", prefix, body, suffix)
976 fn replace_filter_map_next_with_find_map2() {
977 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
980 let m = [1, 2, 3].iter().filter_map(|x| if *x == 2 { Some (4) } else { None }).next();
981 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ replace filter_map(..).next() with find_map(..)
988 fn replace_filter_map_next_with_find_map_no_diagnostic_without_next() {
989 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
994 .filter_map(|x| if *x == 2 { Some (4) } else { None })
1002 fn replace_filter_map_next_with_find_map_no_diagnostic_with_intervening_methods() {
1003 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1008 .filter_map(|x| if *x == 2 { Some (4) } else { None })
1017 fn replace_filter_map_next_with_find_map_no_diagnostic_if_not_in_chain() {
1018 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1023 .filter_map(|x| if *x == 2 { Some (4) } else { None });
1031 fn missing_record_pat_field_diagnostic() {
1034 struct S { foo: i32, bar: () }
1036 let S { foo: _ } = s;
1037 //^ Missing structure fields:
1045 fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
1048 struct S { foo: i32, bar: () }
1049 fn baz(s: S) -> i32 {
1051 S { foo, .. } => foo,
1059 fn missing_record_pat_field_box() {
1062 struct S { s: Box<u32> }
1064 let S { box s } = a;
1071 fn missing_record_pat_field_ref() {
1076 let S { ref s } = a;
1083 fn simple_free_fn_zero() {
1088 //^^^^^^^ Expected 0 arguments, found 1
1101 fn simple_free_fn_one() {
1106 //^^^^^ Expected 1 argument, found 0
1123 impl S { fn method(&self) {} }
1127 } //^^^^^^^^^^^ Expected 1 argument, found 0
1134 impl S { fn method(&self) {} }
1145 fn method_with_arg() {
1149 impl S { fn method(&self, arg: u8) {} }
1153 } //^^^^^^^^^^ Expected 1 argument, found 0
1160 impl S { fn method(&self, arg: u8) {} }
1171 fn method_unknown_receiver() {
1172 // note: this is incorrect code, so there might be errors on this in the
1173 // future, but we shouldn't emit an argument count diagnostic here
1176 trait Foo { fn method(&self, arg: usize) {} }
1190 struct Tup(u8, u16);
1193 } //^^^^^^ Expected 2 arguments, found 1
1202 enum En { Variant(u8, u16), }
1205 } //^^^^^^^^^^^^^^ Expected 2 arguments, found 1
1211 fn enum_variant_type_macro() {
1224 //^^^^^^^^^^^^^^ Expected 1 argument, found 2
1226 //^^^^^^^^^^ Expected 1 argument, found 0
1238 fn fixed(fixed: u8);
1239 fn varargs(fixed: u8, ...);
1247 //^^^^^^^^^^^ Expected 1 argument, found 2
1260 fn arg_count_lambda() {
1266 //^^^ Expected 1 argument, found 0
1269 //^^^^^^^^^ Expected 1 argument, found 2
1276 fn cfgd_out_call_arguments() {
1279 struct C(#[cfg(FALSE)] ());
1292 C::new().method(#[cfg(FALSE)] 0);
1299 fn cfgd_out_fn_params() {
1302 fn foo(#[cfg(NEVER)] x: ()) {}
1307 fn method(#[cfg(NEVER)] self) {}
1308 fn method2(#[cfg(NEVER)] self, arg: u8) {}
1309 fn method3(self, #[cfg(NEVER)] arg: u8) {}
1313 fn fixed(fixed: u8, #[cfg(NEVER)] ...);
1314 fn varargs(#[cfg(not(NEVER))] ...);
1333 fn missing_semicolon() {
1336 fn test() -> i32 { 123; }
1337 //^^^ Remove this semicolon
1343 fn import_extern_crate_clash_with_inner_item() {
1344 // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
1348 //- /lib.rs crate:lib deps:jwt
1351 use permissions::jwt;
1355 jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
1360 pub struct Claims {}
1363 //- /jwt/lib.rs crate:jwt
1373 pub(super) mod match_check_tests {
1374 use crate::diagnostics::tests::check_diagnostics;
1382 //^^ Missing match arm
1384 //^^^^ Missing match arm
1386 match () { _ => (), }
1387 match () { () => (), }
1388 match (()) { (()) => (), }
1395 fn tuple_of_two_empty_tuple() {
1400 //^^^^^^^^ Missing match arm
1402 match ((), ()) { ((), ()) => (), }
1414 //^^^^^ Missing match arm
1415 match false { true => (), }
1416 //^^^^^ Missing match arm
1417 match (false, true) {}
1418 //^^^^^^^^^^^^^ Missing match arm
1419 match (false, true) { (true, true) => (), }
1420 //^^^^^^^^^^^^^ Missing match arm
1421 match (false, true) {
1422 //^^^^^^^^^^^^^ Missing match arm
1423 (false, true) => (),
1424 (false, false) => (),
1425 (true, false) => (),
1427 match (false, true) { (true, _x) => (), }
1428 //^^^^^^^^^^^^^ Missing match arm
1430 match false { true => (), false => (), }
1431 match (false, true) {
1433 (true, false) => (),
1436 match (false, true) {
1438 (true, false) => (),
1439 (false, true) => (),
1440 (false, false) => (),
1442 match (false, true) {
1444 (false, true) => (),
1445 (false, false) => (),
1447 match (false, true, false) {
1451 match (false, true, false) {
1455 match (false, true, false) { (..) => (), }
1462 fn tuple_of_tuple_and_bools() {
1466 match (false, ((), false)) {}
1467 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1468 match (false, ((), false)) { (true, ((), true)) => (), }
1469 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1470 match (false, ((), false)) { (true, _) => (), }
1471 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1473 match (false, ((), false)) {
1474 (true, ((), true)) => (),
1475 (true, ((), false)) => (),
1476 (false, ((), true)) => (),
1477 (false, ((), false)) => (),
1479 match (false, ((), false)) {
1480 (true, ((), true)) => (),
1481 (true, ((), false)) => (),
1493 enum Either { A, B, }
1497 //^^^^^^^^^ Missing match arm
1498 match Either::B { Either::A => (), }
1499 //^^^^^^^^^ Missing match arm
1502 //^^^^^^^^^^ Missing match arm
1507 Either::A => (), Either::B => (),
1510 Either::A => (), Either::B => (),
1518 fn enum_containing_bool() {
1521 enum Either { A(bool), B }
1525 //^^^^^^^^^ Missing match arm
1527 //^^^^^^^^^ Missing match arm
1528 Either::A(true) => (), Either::B => ()
1532 Either::A(true) => (),
1533 Either::A(false) => (),
1551 fn enum_different_sizes() {
1554 enum Either { A(bool), B(bool, bool) }
1557 match Either::A(false) {
1558 //^^^^^^^^^^^^^^^^ Missing match arm
1560 Either::B(false, _) => (),
1563 match Either::A(false) {
1565 Either::B(true, _) => (),
1566 Either::B(false, _) => (),
1568 match Either::A(false) {
1569 Either::A(true) | Either::A(false) => (),
1570 Either::B(true, _) => (),
1571 Either::B(false, _) => (),
1579 fn tuple_of_enum_no_diagnostic() {
1582 enum Either { A(bool), B(bool, bool) }
1583 enum Either2 { C, D }
1586 match (Either::A(false), Either2::C) {
1587 (Either::A(true), _) | (Either::A(false), _) => (),
1588 (Either::B(true, _), Either2::C) => (),
1589 (Either::B(false, _), Either2::C) => (),
1590 (Either::B(_, _), Either2::D) => (),
1598 fn or_pattern_no_diagnostic() {
1604 match (Either::A, Either::B) {
1605 (Either::A | Either::B, _) => (),
1612 fn mismatched_types() {
1613 // Match statements with arms that don't match the
1614 // expression pattern do not fire this diagnostic.
1617 enum Either { A, B }
1618 enum Either2 { C, D }
1623 // ^^^^^^^^^^ Internal: match check bailed out
1626 match (true, false) {
1627 (true, false, true) => (),
1628 // ^^^^^^^^^^^^^^^^^^^ Internal: match check bailed out
1631 match (true, false) { (true,) => {} }
1632 // ^^^^^^^ Internal: match check bailed out
1633 match (0) { () => () }
1634 // ^^ Internal: match check bailed out
1635 match Unresolved::Bar { Unresolved::Baz => () }
1642 fn mismatched_types_in_or_patterns() {
1646 match false { true | () => {} }
1647 // ^^^^^^^^^ Internal: match check bailed out
1648 match (false,) { (true | (),) => {} }
1649 // ^^^^^^^^^^^^ Internal: match check bailed out
1656 fn malformed_match_arm_tuple_enum_missing_pattern() {
1657 // We are testing to be sure we don't panic here when the match
1658 // arm `Either::B` is missing its pattern.
1661 enum Either { A, B(u32) }
1674 fn malformed_match_arm_extra_fields() {
1677 enum A { B(isize, isize), C }
1680 A::B(_, _, _) => (),
1681 // ^^^^^^^^^^^^^ Internal: match check bailed out
1685 // ^^^^^^^ Internal: match check bailed out
1693 fn expr_diverges() {
1696 enum Either { A, B }
1701 // ^^^^^^^^^ Internal: match check bailed out
1706 // ^^^^^^^^^ Internal: match check bailed out
1708 match loop { break Foo::A } {
1709 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1712 match loop { break Foo::A } {
1722 fn expr_partially_diverges() {
1725 enum Either<T> { A(T), B }
1727 fn foo() -> Either<!> { Either::B }
1730 Either::A(val) => val,
1742 enum Either { A { foo: bool }, B }
1745 let a = Either::A { foo: true };
1747 //^ Missing match arm
1748 match a { Either::A { foo: true } => () }
1749 //^ Missing match arm
1751 Either::A { } => (),
1752 //^^^^^^^^^ Missing structure fields:
1757 //^ Missing match arm
1758 Either::A { } => (),
1759 } //^^^^^^^^^ Missing structure fields:
1763 Either::A { foo: true } => (),
1764 Either::A { foo: false } => (),
1768 Either::A { foo: _ } => (),
1777 fn enum_record_fields_out_of_order() {
1781 A { foo: bool, bar: () },
1786 let a = Either::A { foo: true, bar: () };
1788 //^ Missing match arm
1789 Either::A { bar: (), foo: false } => (),
1790 Either::A { foo: true, bar: () } => (),
1794 Either::A { bar: (), foo: false } => (),
1795 Either::A { foo: true, bar: () } => (),
1804 fn enum_record_ellipsis() {
1808 A { foo: bool, bar: bool },
1815 //^ Missing match arm
1816 Either::A { foo: true, .. } => (),
1820 //^ Missing match arm
1821 Either::A { .. } => (),
1825 Either::A { foo: true, .. } => (),
1826 Either::A { foo: false, .. } => (),
1831 Either::A { .. } => (),
1840 fn enum_tuple_partial_ellipsis() {
1844 A(bool, bool, bool, bool),
1850 //^^^^^^^^^ Missing match arm
1851 Either::A(true, .., true) => (),
1852 Either::A(true, .., false) => (),
1853 Either::A(false, .., false) => (),
1857 //^^^^^^^^^ Missing match arm
1858 Either::A(true, .., true) => (),
1859 Either::A(true, .., false) => (),
1860 Either::A(.., true) => (),
1865 Either::A(true, .., true) => (),
1866 Either::A(true, .., false) => (),
1867 Either::A(false, .., true) => (),
1868 Either::A(false, .., false) => (),
1872 Either::A(true, .., true) => (),
1873 Either::A(true, .., false) => (),
1874 Either::A(.., true) => (),
1875 Either::A(.., false) => (),
1889 fn enum_(never: Never) {
1892 fn enum_ref(never: &Never) {
1894 //^^^^^ Missing match arm
1907 enum Option<T> { Some(T), None }
1910 // `Never` is deliberately not defined so that it's an uninferred type.
1911 match Option::<Never>::None {
1913 Some(never) => match never {},
1914 // ^^^^^^^^^^^ Internal: match check bailed out
1916 match Option::<Never>::None {
1917 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1918 Option::Some(_never) => {},
1926 fn tuple_of_bools_with_ellipsis_at_end_missing_arm() {
1930 match (false, true, false) {
1931 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1939 fn tuple_of_bools_with_ellipsis_at_beginning_missing_arm() {
1943 match (false, true, false) {
1944 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1952 fn tuple_of_bools_with_ellipsis_in_middle_missing_arm() {
1956 match (false, true, false) {
1957 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1958 (true, .., false) => (),
1965 fn record_struct() {
1967 r#"struct Foo { a: bool }
1970 //^ Missing match arm
1971 match f { Foo { a: true } => () }
1972 //^ Missing match arm
1973 match &f { Foo { a: true } => () }
1974 //^^ Missing match arm
1975 match f { Foo { a: _ } => () }
1977 Foo { a: true } => (),
1978 Foo { a: false } => (),
1981 Foo { a: true } => (),
1982 Foo { a: false } => (),
1992 r#"struct Foo(bool);
1995 //^ Missing match arm
1996 match f { Foo(true) => () }
1997 //^ Missing match arm
2013 //^ Missing match arm
2014 match f { Foo => () }
2021 fn record_struct_ellipsis() {
2023 r#"struct Foo { foo: bool, bar: bool }
2025 match f { Foo { foo: true, .. } => () }
2026 //^ Missing match arm
2028 //^ Missing match arm
2029 Foo { foo: true, .. } => (),
2030 Foo { bar: false, .. } => ()
2032 match f { Foo { .. } => () }
2034 Foo { foo: true, .. } => (),
2035 Foo { foo: false, .. } => ()
2047 enum Either { A(bool), B }
2049 //^^^^^^^^^ Missing match arm
2050 Either::A(true | false) => (),
2058 fn no_panic_at_unimplemented_subpattern_type() {
2063 match v { S{ a } => {} }
2064 match v { S{ a: _x } => {} }
2065 match v { S{ a: 'a' } => {} }
2066 //^^^^^^^^^^^ Internal: match check bailed out
2067 match v { S{..} => {} }
2070 //^ Missing match arm
2085 match true { _x @ true => {} }
2086 //^^^^ Missing match arm
2093 fn binding_ref_has_correct_type() {
2094 // Asserts `PatKind::Binding(ref _x): bool`, not &bool.
2095 // If that's not true match checking will panic with "incompatible constructors"
2096 // FIXME: make facilities to test this directly like `tests::check_infer(..)`
2101 // FIXME: this should not bail out but current behavior is such as the old algorithm.
2102 // ExprValidator::validate_match(..) checks types of top level patterns incorrecly.
2105 // ^^^^^^ Internal: match check bailed out
2118 fn enum_non_exhaustive() {
2121 //- /lib.rs crate:lib
2125 match E::A { _ => {} }
2135 //- /main.rs crate:main deps:lib
2138 match E::A { _ => {} }
2140 //^^^^ Missing match arm
2145 //^^^^ Missing match arm
2164 //^^^^ Missing match arm
2174 fn pattern_type_is_of_substitution() {
2189 fn record_struct_no_such_field() {
2194 match f { Foo { bar } => () }
2195 // ^^^^^^^^^^^ Internal: match check bailed out
2202 fn match_ergonomics_issue_9095() {
2205 enum Foo<T> { A(T) }
2207 match &Foo::A(true) {
2216 mod false_negatives {
2217 //! The implementation of match checking here is a work in progress. As we roll this out, we
2218 //! prefer false negatives to false positives (ideally there would be no false positives). This
2219 //! test module should document known false negatives. Eventually we will have a complete
2220 //! implementation of match checking and this module will be empty.
2222 //! The reasons for documenting known false negatives:
2224 //! 1. It acts as a backlog of work that can be done to improve the behavior of the system.
2225 //! 2. It ensures the code doesn't panic when handling these cases.
2230 // We don't currently check integer exhaustiveness.
2236 // ^^ Internal: match check bailed out
2245 fn reference_patterns_at_top_level() {
2251 // ^^^^^ Internal: match check bailed out
2259 fn reference_patterns_in_fields() {
2265 // ^^^^^^^ Internal: match check bailed out
2269 // ^^^^^^^^ Internal: match check bailed out
2279 mod decl_check_tests {
2280 use crate::diagnostics::tests::check_diagnostics;
2283 fn incorrect_function_name() {
2286 fn NonSnakeCaseName() {}
2287 // ^^^^^^^^^^^^^^^^ Function `NonSnakeCaseName` should have snake_case name, e.g. `non_snake_case_name`
2293 fn incorrect_function_params() {
2296 fn foo(SomeParam: u8) {}
2297 // ^^^^^^^^^ Parameter `SomeParam` should have snake_case name, e.g. `some_param`
2299 fn foo2(ok_param: &str, CAPS_PARAM: u8) {}
2300 // ^^^^^^^^^^ Parameter `CAPS_PARAM` should have snake_case name, e.g. `caps_param`
2306 fn incorrect_variable_names() {
2310 let SOME_VALUE = 10;
2311 // ^^^^^^^^^^ Variable `SOME_VALUE` should have snake_case name, e.g. `some_value`
2312 let AnotherValue = 20;
2313 // ^^^^^^^^^^^^ Variable `AnotherValue` should have snake_case name, e.g. `another_value`
2320 fn incorrect_struct_names() {
2323 struct non_camel_case_name {}
2324 // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName`
2326 struct SCREAMING_CASE {}
2327 // ^^^^^^^^^^^^^^ Structure `SCREAMING_CASE` should have CamelCase name, e.g. `ScreamingCase`
2333 fn no_diagnostic_for_camel_cased_acronyms_in_struct_name() {
2342 fn incorrect_struct_field() {
2345 struct SomeStruct { SomeField: u8 }
2346 // ^^^^^^^^^ Field `SomeField` should have snake_case name, e.g. `some_field`
2352 fn incorrect_enum_names() {
2355 enum some_enum { Val(u8) }
2356 // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum`
2359 // ^^^^^^^^^ Enum `SOME_ENUM` should have CamelCase name, e.g. `SomeEnum`
2365 fn no_diagnostic_for_camel_cased_acronyms_in_enum_name() {
2374 fn incorrect_enum_variant_name() {
2377 enum SomeEnum { SOME_VARIANT(u8) }
2378 // ^^^^^^^^^^^^ Variant `SOME_VARIANT` should have CamelCase name, e.g. `SomeVariant`
2384 fn incorrect_const_name() {
2387 const some_weird_const: u8 = 10;
2388 // ^^^^^^^^^^^^^^^^ Constant `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2394 fn incorrect_static_name() {
2397 static some_weird_const: u8 = 10;
2398 // ^^^^^^^^^^^^^^^^ Static variable `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2404 fn fn_inside_impl_struct() {
2408 // ^^^^^^^^^^ Structure `someStruct` should have CamelCase name, e.g. `SomeStruct`
2411 fn SomeFunc(&self) {
2412 // ^^^^^^^^ Function `SomeFunc` should have snake_case name, e.g. `some_func`
2413 let WHY_VAR_IS_CAPS = 10;
2414 // ^^^^^^^^^^^^^^^ Variable `WHY_VAR_IS_CAPS` should have snake_case name, e.g. `why_var_is_caps`
2422 fn no_diagnostic_for_enum_varinats() {
2425 enum Option { Some, None }
2428 match Option::None {
2441 enum Option { Some, None }
2444 match Option::None {
2445 SOME_VAR @ None => (),
2446 // ^^^^^^^^ Variable `SOME_VAR` should have snake_case name, e.g. `some_var`
2455 fn allow_attributes() {
2458 #[allow(non_snake_case)]
2459 fn NonSnakeCaseName(SOME_VAR: u8) -> u8{
2460 // cov_flags generated output from elsewhere in this file
2463 static lower_case: u8;
2466 let OtherVar = SOME_VAR + 1;
2470 #[allow(nonstandard_style)]
2471 mod CheckNonstandardStyle {
2472 fn HiImABadFnName() {}
2477 fn HiImABadFnName() {}
2481 #![allow(non_snake_case)]
2482 fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {}
2485 #[allow(non_snake_case, non_camel_case_types)]
2486 pub struct some_type {
2491 #[allow(non_upper_case_globals)]
2492 pub const some_const: u8 = 10;
2494 #[allow(non_upper_case_globals)]
2495 pub static SomeStatic: u8 = 10;
2501 fn allow_attributes_crate_attr() {
2504 #![allow(non_snake_case)]
2507 fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {}
2515 fn bug_trait_inside_fn() {
2517 // This is broken, and in fact, should not even be looked at by this
2518 // lint in the first place. There's weird stuff going on in the
2519 // collection phase.
2520 // It's currently being brought in by:
2521 // * validate_func on `a` recursing into modules
2522 // * then it finds the trait and then the function while iterating
2524 // * then validate_func is called on Dirty
2525 // * ... which then proceeds to look at some unknown module taking no
2526 // attrs from either the impl or the fn a, and then finally to the root
2529 // It should find the attribute on the trait, but it *doesn't even see
2530 // the trait* as far as I can tell.
2538 // this comes out of bitflags, mostly
2539 #[allow(non_snake_case)]
2541 const HiImAlsoBad: u8 = 2;
2543 fn Dirty(&self) -> bool {
2556 fn bug_traits_arent_checked() {
2557 // FIXME: Traits and functions in traits aren't currently checked by
2558 // r-a, even though rustc will complain about them.
2562 // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait`
2564 // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function`
2566 // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function`
2573 fn ignores_extern_items() {
2574 cov_mark::check!(extern_func_incorrect_case_ignored);
2575 cov_mark::check!(extern_static_incorrect_case_ignored);
2579 fn NonSnakeCaseName(SOME_VAR: u8) -> u8;
2580 pub static SomeStatic: u8 = 10;
2587 fn infinite_loop_inner_items() {
2599 #[test] // Issue #8809.
2600 fn parenthesized_parameter() {
2601 check_diagnostics(r#"fn f((O): _) {}"#)