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.
7 mod break_outside_of_loop;
10 mod mismatched_arg_count;
12 mod missing_ok_or_some_in_tail_expr;
15 mod remove_this_semicolon;
16 mod unimplemented_builtin_macro;
17 mod unresolved_extern_crate;
18 mod unresolved_import;
19 mod unresolved_macro_call;
20 mod unresolved_module;
21 mod unresolved_proc_macro;
27 use std::cell::RefCell;
30 diagnostics::{AnyDiagnostic, Diagnostic as _, DiagnosticCode, DiagnosticSinkBuilder},
33 use ide_assists::AssistResolveStrategy;
34 use ide_db::{base_db::SourceDatabase, RootDatabase};
35 use itertools::Itertools;
36 use rustc_hash::FxHashSet;
39 SyntaxNode, SyntaxNodePtr, TextRange, TextSize,
41 use text_edit::TextEdit;
42 use unlinked_file::UnlinkedFile;
44 use crate::{Assist, AssistId, AssistKind, FileId, Label, SourceChange};
46 use self::fixes::DiagnosticWithFixes;
49 pub struct Diagnostic {
50 // pub name: Option<String>,
53 pub severity: Severity,
54 pub fixes: Option<Vec<Assist>>,
56 pub code: Option<DiagnosticCode>,
57 pub experimental: bool,
61 fn new(code: &'static str, message: impl Into<String>, range: TextRange) -> Diagnostic {
62 let message = message.into();
63 let code = Some(DiagnosticCode(code));
67 severity: Severity::Error,
75 fn experimental(mut self) -> Diagnostic {
76 self.experimental = true;
80 fn severity(mut self, severity: Severity) -> Diagnostic {
81 self.severity = severity;
85 fn error(range: TextRange, message: String) -> Self {
89 severity: Severity::Error,
97 fn hint(range: TextRange, message: String) -> Self {
101 severity: Severity::WeakWarning,
109 fn with_fixes(self, fixes: Option<Vec<Assist>>) -> Self {
110 Self { fixes, ..self }
113 fn with_unused(self, unused: bool) -> Self {
114 Self { unused, ..self }
117 fn with_code(self, code: Option<DiagnosticCode>) -> Self {
118 Self { code, ..self }
122 #[derive(Debug, Copy, Clone)]
128 #[derive(Default, Debug, Clone)]
129 pub struct DiagnosticsConfig {
130 pub disable_experimental: bool,
131 pub disabled: FxHashSet<String>,
134 struct DiagnosticsContext<'a> {
135 config: &'a DiagnosticsConfig,
136 sema: Semantics<'a, RootDatabase>,
138 resolve: &'a AssistResolveStrategy,
141 pub(crate) fn diagnostics(
143 config: &DiagnosticsConfig,
144 resolve: &AssistResolveStrategy,
146 ) -> Vec<Diagnostic> {
147 let _p = profile::span("diagnostics");
148 let sema = Semantics::new(db);
149 let parse = db.parse(file_id);
150 let mut res = Vec::new();
152 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
158 .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
161 for node in parse.tree().syntax().descendants() {
162 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
163 field_shorthand::check(&mut res, file_id, &node);
165 let res = RefCell::new(res);
166 let sink_builder = DiagnosticSinkBuilder::new()
167 .on::<hir::diagnostics::IncorrectCase, _>(|d| {
168 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
170 .on::<hir::diagnostics::ReplaceFilterMapNextWithFindMap, _>(|d| {
171 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
173 .on::<UnlinkedFile, _>(|d| {
174 // Limit diagnostic to the first few characters in the file. This matches how VS Code
175 // renders it with the full span, but on other editors, and is less invasive.
176 let range = sema.diagnostics_display_range(d.display_source()).range;
177 let range = range.intersect(TextRange::up_to(TextSize::of("..."))).unwrap_or(range);
179 // Override severity and mark as unused.
180 res.borrow_mut().push(
181 Diagnostic::hint(range, d.message())
182 .with_fixes(d.fixes(&sema, resolve))
183 .with_code(Some(d.code())),
186 // Only collect experimental diagnostics when they're enabled.
187 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
188 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
190 // Finalize the `DiagnosticSink` building process.
191 let mut sink = sink_builder
192 // Diagnostics not handled above get no fix and default treatment.
194 res.borrow_mut().push(
196 sema.diagnostics_display_range(d.display_source()).range,
199 .with_code(Some(d.code())),
203 let mut diags = Vec::new();
204 let internal_diagnostics = cfg!(test);
205 match sema.to_module_def(file_id) {
206 Some(m) => diags = m.diagnostics(db, &mut sink, internal_diagnostics),
208 sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(parse.tree().syntax()) });
214 let mut res = res.into_inner();
216 let ctx = DiagnosticsContext { config, sema, resolve };
220 AnyDiagnostic::BreakOutsideOfLoop(d) => break_outside_of_loop::break_outside_of_loop(&ctx, &d),
221 AnyDiagnostic::MacroError(d) => macro_error::macro_error(&ctx, &d),
222 AnyDiagnostic::MismatchedArgCount(d) => mismatched_arg_count::mismatched_arg_count(&ctx, &d),
223 AnyDiagnostic::MissingFields(d) => missing_fields::missing_fields(&ctx, &d),
224 AnyDiagnostic::MissingOkOrSomeInTailExpr(d) => missing_ok_or_some_in_tail_expr::missing_ok_or_some_in_tail_expr(&ctx, &d),
225 AnyDiagnostic::MissingUnsafe(d) => missing_unsafe::missing_unsafe(&ctx, &d),
226 AnyDiagnostic::NoSuchField(d) => no_such_field::no_such_field(&ctx, &d),
227 AnyDiagnostic::RemoveThisSemicolon(d) => remove_this_semicolon::remove_this_semicolon(&ctx, &d),
228 AnyDiagnostic::UnimplementedBuiltinMacro(d) => unimplemented_builtin_macro::unimplemented_builtin_macro(&ctx, &d),
229 AnyDiagnostic::UnresolvedExternCrate(d) => unresolved_extern_crate::unresolved_extern_crate(&ctx, &d),
230 AnyDiagnostic::UnresolvedImport(d) => unresolved_import::unresolved_import(&ctx, &d),
231 AnyDiagnostic::UnresolvedMacroCall(d) => unresolved_macro_call::unresolved_macro_call(&ctx, &d),
232 AnyDiagnostic::UnresolvedModule(d) => unresolved_module::unresolved_module(&ctx, &d),
233 AnyDiagnostic::UnresolvedProcMacro(d) => unresolved_proc_macro::unresolved_proc_macro(&ctx, &d),
235 AnyDiagnostic::InactiveCode(d) => match inactive_code::inactive_code(&ctx, &d) {
240 if let Some(code) = d.code {
241 if ctx.config.disabled.contains(code.as_str()) {
245 if ctx.config.disable_experimental && d.experimental {
254 fn diagnostic_with_fix<D: DiagnosticWithFixes>(
256 sema: &Semantics<RootDatabase>,
257 resolve: &AssistResolveStrategy,
259 Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message())
260 .with_fixes(d.fixes(sema, resolve))
261 .with_code(Some(d.code()))
264 fn warning_with_fix<D: DiagnosticWithFixes>(
266 sema: &Semantics<RootDatabase>,
267 resolve: &AssistResolveStrategy,
269 Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message())
270 .with_fixes(d.fixes(sema, resolve))
271 .with_code(Some(d.code()))
274 fn check_unnecessary_braces_in_use_statement(
275 acc: &mut Vec<Diagnostic>,
279 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
280 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
281 // If there is a comment inside the bracketed `use`,
282 // assume it is a commented out module path and don't show diagnostic.
283 if use_tree_list.has_inner_comment() {
287 let use_range = use_tree_list.syntax().text_range();
289 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
291 let to_replace = single_use_tree.syntax().text().to_string();
292 let mut edit_builder = TextEdit::builder();
293 edit_builder.delete(use_range);
294 edit_builder.insert(use_range.start(), to_replace);
295 edit_builder.finish()
299 Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
300 .with_fixes(Some(vec![fix(
302 "Remove unnecessary braces",
303 SourceChange::from_text_edit(file_id, edit),
312 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
313 single_use_tree: &ast::UseTree,
314 ) -> Option<TextEdit> {
315 let use_tree_list_node = single_use_tree.syntax().parent()?;
316 if single_use_tree.path()?.segment()?.self_token().is_some() {
317 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
318 let end = use_tree_list_node.text_range().end();
319 return Some(TextEdit::delete(TextRange::new(start, end)));
324 fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
325 let mut res = unresolved_fix(id, label, target);
326 res.source_change = Some(source_change);
330 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
331 assert!(!id.contains(' '));
333 id: AssistId(id, AssistKind::QuickFix),
334 label: Label::new(label),
343 use expect_test::Expect;
344 use ide_assists::AssistResolveStrategy;
345 use stdx::trim_indent;
346 use test_utils::{assert_eq_text, extract_annotations};
348 use crate::{fixture, DiagnosticsConfig};
350 /// Takes a multi-file input fixture with annotated cursor positions,
352 /// * a diagnostic is produced
353 /// * the first diagnostic fix trigger range touches the input cursor position
354 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
356 pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
357 check_nth_fix(0, ra_fixture_before, ra_fixture_after);
359 /// Takes a multi-file input fixture with annotated cursor positions,
361 /// * a diagnostic is produced
362 /// * every diagnostic fixes trigger range touches the input cursor position
363 /// * that the contents of the file containing the cursor match `after` after each diagnostic fix is applied
364 pub(crate) fn check_fixes(ra_fixture_before: &str, ra_fixtures_after: Vec<&str>) {
365 for (i, ra_fixture_after) in ra_fixtures_after.iter().enumerate() {
366 check_nth_fix(i, ra_fixture_before, ra_fixture_after)
371 fn check_nth_fix(nth: usize, ra_fixture_before: &str, ra_fixture_after: &str) {
372 let after = trim_indent(ra_fixture_after);
374 let (analysis, file_position) = fixture::position(ra_fixture_before);
375 let diagnostic = analysis
377 &DiagnosticsConfig::default(),
378 AssistResolveStrategy::All,
379 file_position.file_id,
384 let fix = &diagnostic.fixes.unwrap()[nth];
386 let source_change = fix.source_change.as_ref().unwrap();
387 let file_id = *source_change.source_file_edits.keys().next().unwrap();
388 let mut actual = analysis.file_text(file_id).unwrap().to_string();
390 for edit in source_change.source_file_edits.values() {
391 edit.apply(&mut actual);
396 assert_eq_text!(&after, &actual);
398 fix.target.contains_inclusive(file_position.offset),
399 "diagnostic fix range {:?} does not touch cursor position {:?}",
404 /// Checks that there's a diagnostic *without* fix at `$0`.
405 fn check_no_fix(ra_fixture: &str) {
406 let (analysis, file_position) = fixture::position(ra_fixture);
407 let diagnostic = analysis
409 &DiagnosticsConfig::default(),
410 AssistResolveStrategy::All,
411 file_position.file_id,
416 assert!(diagnostic.fixes.is_none(), "got a fix when none was expected: {:?}", diagnostic);
419 pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) {
420 let (analysis, file_id) = fixture::file(ra_fixture);
421 let diagnostics = analysis
422 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
424 expect.assert_debug_eq(&diagnostics)
428 pub(crate) fn check_diagnostics(ra_fixture: &str) {
429 let mut config = DiagnosticsConfig::default();
430 config.disabled.insert("inactive-code".to_string());
431 check_diagnostics_with_config(config, ra_fixture)
435 pub(crate) fn check_diagnostics_with_config(config: DiagnosticsConfig, ra_fixture: &str) {
436 let (analysis, files) = fixture::files(ra_fixture);
437 for file_id in files {
439 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
441 let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
443 diagnostics.into_iter().map(|d| (d.range, d.message)).collect::<Vec<_>>();
444 actual.sort_by_key(|(range, _)| range.start());
445 assert_eq!(expected, actual);
450 fn range_mapping_out_of_macros() {
451 // FIXME: this is very wrong, but somewhat tricky to fix.
458 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
461 let _x = id![Foo { a: $042 }];
464 pub struct Foo { pub a: i32, pub b: i32 }
471 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
474 let _x = id![Foo { a: 42 }];
477 pub struct Foo { pub a: i32, pub b: i32 }
483 fn test_check_unnecessary_braces_in_use_statement() {
555 mod a { mod c {} mod d { mod e {} } }
556 use a::{c, d::{e$0}};
559 mod a { mod c {} mod d { mod e {} } }
566 fn test_disabled_diagnostics() {
567 let mut config = DiagnosticsConfig::default();
568 config.disabled.insert("unresolved-module".into());
570 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
573 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
574 assert!(diagnostics.is_empty());
576 let diagnostics = analysis
577 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
579 assert!(!diagnostics.is_empty());
583 fn unlinked_file_prepend_first_item() {
584 cov_mark::check!(unlinked_file_prepend_before_first_item);
585 // Only tests the first one for `pub mod` since the rest are the same
609 fn unlinked_file_append_mod() {
610 cov_mark::check!(unlinked_file_append_to_existing_mods);
622 mod preexisting_bottom;)
636 mod preexisting_bottom;)
642 fn unlinked_file_insert_in_empty_file() {
643 cov_mark::check!(unlinked_file_empty_file);
657 fn unlinked_file_old_style_modrs() {
675 fn unlinked_file_new_style_mod() {
691 fn unlinked_file_with_cfg_off() {
692 cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
706 fn unlinked_file_with_cfg_on() {
718 // Register the required standard library types to make the tests work
719 fn add_filter_map_with_find_next_boilerplate(body: &str) -> String {
721 //- /main.rs crate:main deps:core
722 use core::iter::Iterator;
723 use core::option::Option::{self, Some, None};
726 //- /core/lib.rs crate:core
728 pub enum Option<T> { Some(T), None }
733 fn filter_map<B, F>(self, f: F) -> FilterMap where F: FnMut(Self::Item) -> Option<B> { FilterMap }
734 fn next(&mut self) -> Option<Self::Item>;
736 pub struct FilterMap {}
737 impl Iterator for FilterMap {
739 fn next(&mut self) -> i32 { 7 }
743 format!("{}{}{}", prefix, body, suffix)
747 fn replace_filter_map_next_with_find_map2() {
748 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
751 let m = [1, 2, 3].iter().filter_map(|x| if *x == 2 { Some (4) } else { None }).next();
752 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ replace filter_map(..).next() with find_map(..)
759 fn replace_filter_map_next_with_find_map_no_diagnostic_without_next() {
760 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
765 .filter_map(|x| if *x == 2 { Some (4) } else { None })
773 fn replace_filter_map_next_with_find_map_no_diagnostic_with_intervening_methods() {
774 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
779 .filter_map(|x| if *x == 2 { Some (4) } else { None })
788 fn replace_filter_map_next_with_find_map_no_diagnostic_if_not_in_chain() {
789 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
794 .filter_map(|x| if *x == 2 { Some (4) } else { None });
802 fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
805 struct S { foo: i32, bar: () }
806 fn baz(s: S) -> i32 {
808 S { foo, .. } => foo,
816 fn missing_record_pat_field_box() {
819 struct S { s: Box<u32> }
828 fn missing_record_pat_field_ref() {
840 fn import_extern_crate_clash_with_inner_item() {
841 // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
845 //- /lib.rs crate:lib deps:jwt
848 use permissions::jwt;
852 jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
860 //- /jwt/lib.rs crate:jwt
870 pub(super) mod match_check_tests {
871 use crate::diagnostics::tests::check_diagnostics;
879 //^^ Missing match arm
881 //^^^^ Missing match arm
883 match () { _ => (), }
884 match () { () => (), }
885 match (()) { (()) => (), }
892 fn tuple_of_two_empty_tuple() {
897 //^^^^^^^^ Missing match arm
899 match ((), ()) { ((), ()) => (), }
911 //^^^^^ Missing match arm
912 match false { true => (), }
913 //^^^^^ Missing match arm
914 match (false, true) {}
915 //^^^^^^^^^^^^^ Missing match arm
916 match (false, true) { (true, true) => (), }
917 //^^^^^^^^^^^^^ Missing match arm
918 match (false, true) {
919 //^^^^^^^^^^^^^ Missing match arm
921 (false, false) => (),
924 match (false, true) { (true, _x) => (), }
925 //^^^^^^^^^^^^^ Missing match arm
927 match false { true => (), false => (), }
928 match (false, true) {
933 match (false, true) {
937 (false, false) => (),
939 match (false, true) {
942 (false, false) => (),
944 match (false, true, false) {
948 match (false, true, false) {
952 match (false, true, false) { (..) => (), }
959 fn tuple_of_tuple_and_bools() {
963 match (false, ((), false)) {}
964 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
965 match (false, ((), false)) { (true, ((), true)) => (), }
966 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
967 match (false, ((), false)) { (true, _) => (), }
968 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
970 match (false, ((), false)) {
971 (true, ((), true)) => (),
972 (true, ((), false)) => (),
973 (false, ((), true)) => (),
974 (false, ((), false)) => (),
976 match (false, ((), false)) {
977 (true, ((), true)) => (),
978 (true, ((), false)) => (),
990 enum Either { A, B, }
994 //^^^^^^^^^ Missing match arm
995 match Either::B { Either::A => (), }
996 //^^^^^^^^^ Missing match arm
999 //^^^^^^^^^^ Missing match arm
1004 Either::A => (), Either::B => (),
1007 Either::A => (), Either::B => (),
1015 fn enum_containing_bool() {
1018 enum Either { A(bool), B }
1022 //^^^^^^^^^ Missing match arm
1024 //^^^^^^^^^ Missing match arm
1025 Either::A(true) => (), Either::B => ()
1029 Either::A(true) => (),
1030 Either::A(false) => (),
1048 fn enum_different_sizes() {
1051 enum Either { A(bool), B(bool, bool) }
1054 match Either::A(false) {
1055 //^^^^^^^^^^^^^^^^ Missing match arm
1057 Either::B(false, _) => (),
1060 match Either::A(false) {
1062 Either::B(true, _) => (),
1063 Either::B(false, _) => (),
1065 match Either::A(false) {
1066 Either::A(true) | Either::A(false) => (),
1067 Either::B(true, _) => (),
1068 Either::B(false, _) => (),
1076 fn tuple_of_enum_no_diagnostic() {
1079 enum Either { A(bool), B(bool, bool) }
1080 enum Either2 { C, D }
1083 match (Either::A(false), Either2::C) {
1084 (Either::A(true), _) | (Either::A(false), _) => (),
1085 (Either::B(true, _), Either2::C) => (),
1086 (Either::B(false, _), Either2::C) => (),
1087 (Either::B(_, _), Either2::D) => (),
1095 fn or_pattern_no_diagnostic() {
1101 match (Either::A, Either::B) {
1102 (Either::A | Either::B, _) => (),
1109 fn mismatched_types() {
1110 // Match statements with arms that don't match the
1111 // expression pattern do not fire this diagnostic.
1114 enum Either { A, B }
1115 enum Either2 { C, D }
1120 // ^^^^^^^^^^ Internal: match check bailed out
1123 match (true, false) {
1124 (true, false, true) => (),
1125 // ^^^^^^^^^^^^^^^^^^^ Internal: match check bailed out
1128 match (true, false) { (true,) => {} }
1129 // ^^^^^^^ Internal: match check bailed out
1130 match (0) { () => () }
1131 // ^^ Internal: match check bailed out
1132 match Unresolved::Bar { Unresolved::Baz => () }
1139 fn mismatched_types_in_or_patterns() {
1143 match false { true | () => {} }
1144 // ^^^^^^^^^ Internal: match check bailed out
1145 match (false,) { (true | (),) => {} }
1146 // ^^^^^^^^^^^^ Internal: match check bailed out
1153 fn malformed_match_arm_tuple_enum_missing_pattern() {
1154 // We are testing to be sure we don't panic here when the match
1155 // arm `Either::B` is missing its pattern.
1158 enum Either { A, B(u32) }
1171 fn malformed_match_arm_extra_fields() {
1174 enum A { B(isize, isize), C }
1177 A::B(_, _, _) => (),
1178 // ^^^^^^^^^^^^^ Internal: match check bailed out
1182 // ^^^^^^^ Internal: match check bailed out
1190 fn expr_diverges() {
1193 enum Either { A, B }
1198 // ^^^^^^^^^ Internal: match check bailed out
1203 // ^^^^^^^^^ Internal: match check bailed out
1205 match loop { break Foo::A } {
1206 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1209 match loop { break Foo::A } {
1219 fn expr_partially_diverges() {
1222 enum Either<T> { A(T), B }
1224 fn foo() -> Either<!> { Either::B }
1227 Either::A(val) => val,
1239 enum Either { A { foo: bool }, B }
1242 let a = Either::A { foo: true };
1244 //^ Missing match arm
1245 match a { Either::A { foo: true } => () }
1246 //^ Missing match arm
1248 Either::A { } => (),
1249 //^^^^^^^^^ Missing structure fields:
1254 //^ Missing match arm
1255 Either::A { } => (),
1256 } //^^^^^^^^^ Missing structure fields:
1260 Either::A { foo: true } => (),
1261 Either::A { foo: false } => (),
1265 Either::A { foo: _ } => (),
1274 fn enum_record_fields_out_of_order() {
1278 A { foo: bool, bar: () },
1283 let a = Either::A { foo: true, bar: () };
1285 //^ Missing match arm
1286 Either::A { bar: (), foo: false } => (),
1287 Either::A { foo: true, bar: () } => (),
1291 Either::A { bar: (), foo: false } => (),
1292 Either::A { foo: true, bar: () } => (),
1301 fn enum_record_ellipsis() {
1305 A { foo: bool, bar: bool },
1312 //^ Missing match arm
1313 Either::A { foo: true, .. } => (),
1317 //^ Missing match arm
1318 Either::A { .. } => (),
1322 Either::A { foo: true, .. } => (),
1323 Either::A { foo: false, .. } => (),
1328 Either::A { .. } => (),
1337 fn enum_tuple_partial_ellipsis() {
1341 A(bool, bool, bool, bool),
1347 //^^^^^^^^^ Missing match arm
1348 Either::A(true, .., true) => (),
1349 Either::A(true, .., false) => (),
1350 Either::A(false, .., false) => (),
1354 //^^^^^^^^^ Missing match arm
1355 Either::A(true, .., true) => (),
1356 Either::A(true, .., false) => (),
1357 Either::A(.., true) => (),
1362 Either::A(true, .., true) => (),
1363 Either::A(true, .., false) => (),
1364 Either::A(false, .., true) => (),
1365 Either::A(false, .., false) => (),
1369 Either::A(true, .., true) => (),
1370 Either::A(true, .., false) => (),
1371 Either::A(.., true) => (),
1372 Either::A(.., false) => (),
1386 fn enum_(never: Never) {
1389 fn enum_ref(never: &Never) {
1391 //^^^^^ Missing match arm
1404 enum Option<T> { Some(T), None }
1407 // `Never` is deliberately not defined so that it's an uninferred type.
1408 match Option::<Never>::None {
1410 Some(never) => match never {},
1411 // ^^^^^^^^^^^ Internal: match check bailed out
1413 match Option::<Never>::None {
1414 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1415 Option::Some(_never) => {},
1423 fn tuple_of_bools_with_ellipsis_at_end_missing_arm() {
1427 match (false, true, false) {
1428 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1436 fn tuple_of_bools_with_ellipsis_at_beginning_missing_arm() {
1440 match (false, true, false) {
1441 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1449 fn tuple_of_bools_with_ellipsis_in_middle_missing_arm() {
1453 match (false, true, false) {
1454 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1455 (true, .., false) => (),
1462 fn record_struct() {
1464 r#"struct Foo { a: bool }
1467 //^ Missing match arm
1468 match f { Foo { a: true } => () }
1469 //^ Missing match arm
1470 match &f { Foo { a: true } => () }
1471 //^^ Missing match arm
1472 match f { Foo { a: _ } => () }
1474 Foo { a: true } => (),
1475 Foo { a: false } => (),
1478 Foo { a: true } => (),
1479 Foo { a: false } => (),
1489 r#"struct Foo(bool);
1492 //^ Missing match arm
1493 match f { Foo(true) => () }
1494 //^ Missing match arm
1510 //^ Missing match arm
1511 match f { Foo => () }
1518 fn record_struct_ellipsis() {
1520 r#"struct Foo { foo: bool, bar: bool }
1522 match f { Foo { foo: true, .. } => () }
1523 //^ Missing match arm
1525 //^ Missing match arm
1526 Foo { foo: true, .. } => (),
1527 Foo { bar: false, .. } => ()
1529 match f { Foo { .. } => () }
1531 Foo { foo: true, .. } => (),
1532 Foo { foo: false, .. } => ()
1544 enum Either { A(bool), B }
1546 //^^^^^^^^^ Missing match arm
1547 Either::A(true | false) => (),
1555 fn no_panic_at_unimplemented_subpattern_type() {
1560 match v { S{ a } => {} }
1561 match v { S{ a: _x } => {} }
1562 match v { S{ a: 'a' } => {} }
1563 //^^^^^^^^^^^ Internal: match check bailed out
1564 match v { S{..} => {} }
1567 //^ Missing match arm
1582 match true { _x @ true => {} }
1583 //^^^^ Missing match arm
1590 fn binding_ref_has_correct_type() {
1591 // Asserts `PatKind::Binding(ref _x): bool`, not &bool.
1592 // If that's not true match checking will panic with "incompatible constructors"
1593 // FIXME: make facilities to test this directly like `tests::check_infer(..)`
1598 // FIXME: this should not bail out but current behavior is such as the old algorithm.
1599 // ExprValidator::validate_match(..) checks types of top level patterns incorrecly.
1602 // ^^^^^^ Internal: match check bailed out
1615 fn enum_non_exhaustive() {
1618 //- /lib.rs crate:lib
1622 match E::A { _ => {} }
1632 //- /main.rs crate:main deps:lib
1635 match E::A { _ => {} }
1637 //^^^^ Missing match arm
1642 //^^^^ Missing match arm
1661 //^^^^ Missing match arm
1671 fn pattern_type_is_of_substitution() {
1672 cov_mark::check!(match_check_wildcard_expanded_to_substitutions);
1687 fn record_struct_no_such_field() {
1692 match f { Foo { bar } => () }
1693 // ^^^^^^^^^^^ Internal: match check bailed out
1700 fn match_ergonomics_issue_9095() {
1703 enum Foo<T> { A(T) }
1705 match &Foo::A(true) {
1714 mod false_negatives {
1715 //! The implementation of match checking here is a work in progress. As we roll this out, we
1716 //! prefer false negatives to false positives (ideally there would be no false positives). This
1717 //! test module should document known false negatives. Eventually we will have a complete
1718 //! implementation of match checking and this module will be empty.
1720 //! The reasons for documenting known false negatives:
1722 //! 1. It acts as a backlog of work that can be done to improve the behavior of the system.
1723 //! 2. It ensures the code doesn't panic when handling these cases.
1728 // We don't currently check integer exhaustiveness.
1734 // ^^ Internal: match check bailed out
1743 fn reference_patterns_at_top_level() {
1749 // ^^^^^ Internal: match check bailed out
1757 fn reference_patterns_in_fields() {
1763 // ^^^^^^^ Internal: match check bailed out
1767 // ^^^^^^^^ Internal: match check bailed out
1777 mod decl_check_tests {
1778 use crate::diagnostics::tests::check_diagnostics;
1781 fn incorrect_function_name() {
1784 fn NonSnakeCaseName() {}
1785 // ^^^^^^^^^^^^^^^^ Function `NonSnakeCaseName` should have snake_case name, e.g. `non_snake_case_name`
1791 fn incorrect_function_params() {
1794 fn foo(SomeParam: u8) {}
1795 // ^^^^^^^^^ Parameter `SomeParam` should have snake_case name, e.g. `some_param`
1797 fn foo2(ok_param: &str, CAPS_PARAM: u8) {}
1798 // ^^^^^^^^^^ Parameter `CAPS_PARAM` should have snake_case name, e.g. `caps_param`
1804 fn incorrect_variable_names() {
1808 let SOME_VALUE = 10;
1809 // ^^^^^^^^^^ Variable `SOME_VALUE` should have snake_case name, e.g. `some_value`
1810 let AnotherValue = 20;
1811 // ^^^^^^^^^^^^ Variable `AnotherValue` should have snake_case name, e.g. `another_value`
1818 fn incorrect_struct_names() {
1821 struct non_camel_case_name {}
1822 // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName`
1824 struct SCREAMING_CASE {}
1825 // ^^^^^^^^^^^^^^ Structure `SCREAMING_CASE` should have CamelCase name, e.g. `ScreamingCase`
1831 fn no_diagnostic_for_camel_cased_acronyms_in_struct_name() {
1840 fn incorrect_struct_field() {
1843 struct SomeStruct { SomeField: u8 }
1844 // ^^^^^^^^^ Field `SomeField` should have snake_case name, e.g. `some_field`
1850 fn incorrect_enum_names() {
1853 enum some_enum { Val(u8) }
1854 // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum`
1857 // ^^^^^^^^^ Enum `SOME_ENUM` should have CamelCase name, e.g. `SomeEnum`
1863 fn no_diagnostic_for_camel_cased_acronyms_in_enum_name() {
1872 fn incorrect_enum_variant_name() {
1875 enum SomeEnum { SOME_VARIANT(u8) }
1876 // ^^^^^^^^^^^^ Variant `SOME_VARIANT` should have CamelCase name, e.g. `SomeVariant`
1882 fn incorrect_const_name() {
1885 const some_weird_const: u8 = 10;
1886 // ^^^^^^^^^^^^^^^^ Constant `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
1892 fn incorrect_static_name() {
1895 static some_weird_const: u8 = 10;
1896 // ^^^^^^^^^^^^^^^^ Static variable `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
1902 fn fn_inside_impl_struct() {
1906 // ^^^^^^^^^^ Structure `someStruct` should have CamelCase name, e.g. `SomeStruct`
1909 fn SomeFunc(&self) {
1910 // ^^^^^^^^ Function `SomeFunc` should have snake_case name, e.g. `some_func`
1911 let WHY_VAR_IS_CAPS = 10;
1912 // ^^^^^^^^^^^^^^^ Variable `WHY_VAR_IS_CAPS` should have snake_case name, e.g. `why_var_is_caps`
1920 fn no_diagnostic_for_enum_varinats() {
1923 enum Option { Some, None }
1926 match Option::None {
1939 enum Option { Some, None }
1942 match Option::None {
1943 SOME_VAR @ None => (),
1944 // ^^^^^^^^ Variable `SOME_VAR` should have snake_case name, e.g. `some_var`
1953 fn allow_attributes() {
1956 #[allow(non_snake_case)]
1957 fn NonSnakeCaseName(SOME_VAR: u8) -> u8{
1958 // cov_flags generated output from elsewhere in this file
1961 static lower_case: u8;
1964 let OtherVar = SOME_VAR + 1;
1968 #[allow(nonstandard_style)]
1969 mod CheckNonstandardStyle {
1970 fn HiImABadFnName() {}
1975 fn HiImABadFnName() {}
1979 #![allow(non_snake_case)]
1980 fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {}
1983 #[allow(non_snake_case, non_camel_case_types)]
1984 pub struct some_type {
1989 #[allow(non_upper_case_globals)]
1990 pub const some_const: u8 = 10;
1992 #[allow(non_upper_case_globals)]
1993 pub static SomeStatic: u8 = 10;
1999 fn allow_attributes_crate_attr() {
2002 #![allow(non_snake_case)]
2005 fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {}
2013 fn bug_trait_inside_fn() {
2015 // This is broken, and in fact, should not even be looked at by this
2016 // lint in the first place. There's weird stuff going on in the
2017 // collection phase.
2018 // It's currently being brought in by:
2019 // * validate_func on `a` recursing into modules
2020 // * then it finds the trait and then the function while iterating
2022 // * then validate_func is called on Dirty
2023 // * ... which then proceeds to look at some unknown module taking no
2024 // attrs from either the impl or the fn a, and then finally to the root
2027 // It should find the attribute on the trait, but it *doesn't even see
2028 // the trait* as far as I can tell.
2036 // this comes out of bitflags, mostly
2037 #[allow(non_snake_case)]
2039 const HiImAlsoBad: u8 = 2;
2041 fn Dirty(&self) -> bool {
2054 fn bug_traits_arent_checked() {
2055 // FIXME: Traits and functions in traits aren't currently checked by
2056 // r-a, even though rustc will complain about them.
2060 // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait`
2062 // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function`
2064 // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function`
2071 fn ignores_extern_items() {
2072 cov_mark::check!(extern_func_incorrect_case_ignored);
2073 cov_mark::check!(extern_static_incorrect_case_ignored);
2077 fn NonSnakeCaseName(SOME_VAR: u8) -> u8;
2078 pub static SomeStatic: u8 = 10;
2085 fn infinite_loop_inner_items() {
2097 #[test] // Issue #8809.
2098 fn parenthesized_parameter() {
2099 check_diagnostics(r#"fn f((O): _) {}"#)