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;
14 mod unimplemented_builtin_macro;
15 mod unresolved_extern_crate;
16 mod unresolved_import;
17 mod unresolved_macro_call;
18 mod unresolved_module;
19 mod unresolved_proc_macro;
25 use std::cell::RefCell;
28 diagnostics::{AnyDiagnostic, Diagnostic as _, DiagnosticCode, DiagnosticSinkBuilder},
31 use ide_assists::AssistResolveStrategy;
32 use ide_db::{base_db::SourceDatabase, RootDatabase};
33 use itertools::Itertools;
34 use rustc_hash::FxHashSet;
37 SyntaxNode, SyntaxNodePtr, TextRange, TextSize,
39 use text_edit::TextEdit;
40 use unlinked_file::UnlinkedFile;
42 use crate::{Assist, AssistId, AssistKind, FileId, Label, SourceChange};
44 use self::fixes::DiagnosticWithFixes;
47 pub struct Diagnostic {
48 // pub name: Option<String>,
51 pub severity: Severity,
52 pub fixes: Option<Vec<Assist>>,
54 pub code: Option<DiagnosticCode>,
55 pub experimental: bool,
59 fn new(code: &'static str, message: impl Into<String>, range: TextRange) -> Diagnostic {
60 let message = message.into();
61 let code = Some(DiagnosticCode(code));
65 severity: Severity::Error,
73 fn experimental(mut self) -> Diagnostic {
74 self.experimental = true;
78 fn severity(mut self, severity: Severity) -> Diagnostic {
79 self.severity = severity;
83 fn error(range: TextRange, message: String) -> Self {
87 severity: Severity::Error,
95 fn hint(range: TextRange, message: String) -> Self {
99 severity: Severity::WeakWarning,
107 fn with_fixes(self, fixes: Option<Vec<Assist>>) -> Self {
108 Self { fixes, ..self }
111 fn with_unused(self, unused: bool) -> Self {
112 Self { unused, ..self }
115 fn with_code(self, code: Option<DiagnosticCode>) -> Self {
116 Self { code, ..self }
120 #[derive(Debug, Copy, Clone)]
126 #[derive(Default, Debug, Clone)]
127 pub struct DiagnosticsConfig {
128 pub disable_experimental: bool,
129 pub disabled: FxHashSet<String>,
132 struct DiagnosticsContext<'a> {
133 config: &'a DiagnosticsConfig,
134 sema: Semantics<'a, RootDatabase>,
136 resolve: &'a AssistResolveStrategy,
139 pub(crate) fn diagnostics(
141 config: &DiagnosticsConfig,
142 resolve: &AssistResolveStrategy,
144 ) -> Vec<Diagnostic> {
145 let _p = profile::span("diagnostics");
146 let sema = Semantics::new(db);
147 let parse = db.parse(file_id);
148 let mut res = Vec::new();
150 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
156 .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
159 for node in parse.tree().syntax().descendants() {
160 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
161 field_shorthand::check(&mut res, file_id, &node);
163 let res = RefCell::new(res);
164 let sink_builder = DiagnosticSinkBuilder::new()
165 .on::<hir::diagnostics::MissingOkOrSomeInTailExpr, _>(|d| {
166 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
168 .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| {
169 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
171 .on::<hir::diagnostics::IncorrectCase, _>(|d| {
172 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
174 .on::<hir::diagnostics::ReplaceFilterMapNextWithFindMap, _>(|d| {
175 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
177 .on::<UnlinkedFile, _>(|d| {
178 // Limit diagnostic to the first few characters in the file. This matches how VS Code
179 // renders it with the full span, but on other editors, and is less invasive.
180 let range = sema.diagnostics_display_range(d.display_source()).range;
181 let range = range.intersect(TextRange::up_to(TextSize::of("..."))).unwrap_or(range);
183 // Override severity and mark as unused.
184 res.borrow_mut().push(
185 Diagnostic::hint(range, d.message())
186 .with_fixes(d.fixes(&sema, resolve))
187 .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 mut diags = Vec::new();
208 let internal_diagnostics = cfg!(test);
209 match sema.to_module_def(file_id) {
210 Some(m) => diags = m.diagnostics(db, &mut sink, internal_diagnostics),
212 sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(parse.tree().syntax()) });
218 let mut res = res.into_inner();
220 let ctx = DiagnosticsContext { config, sema, resolve };
224 AnyDiagnostic::BreakOutsideOfLoop(d) => break_outside_of_loop::break_outside_of_loop(&ctx, &d),
225 AnyDiagnostic::MacroError(d) => macro_error::macro_error(&ctx, &d),
226 AnyDiagnostic::MissingFields(d) => missing_fields::missing_fields(&ctx, &d),
227 AnyDiagnostic::MissingUnsafe(d) => missing_unsafe::missing_unsafe(&ctx, &d),
228 AnyDiagnostic::MismatchedArgCount(d) => mismatched_arg_count::mismatched_arg_count(&ctx, &d),
229 AnyDiagnostic::NoSuchField(d) => no_such_field::no_such_field(&ctx, &d),
230 AnyDiagnostic::UnimplementedBuiltinMacro(d) => unimplemented_builtin_macro::unimplemented_builtin_macro(&ctx, &d),
231 AnyDiagnostic::UnresolvedExternCrate(d) => unresolved_extern_crate::unresolved_extern_crate(&ctx, &d),
232 AnyDiagnostic::UnresolvedImport(d) => unresolved_import::unresolved_import(&ctx, &d),
233 AnyDiagnostic::UnresolvedMacroCall(d) => unresolved_macro_call::unresolved_macro_call(&ctx, &d),
234 AnyDiagnostic::UnresolvedModule(d) => unresolved_module::unresolved_module(&ctx, &d),
235 AnyDiagnostic::UnresolvedProcMacro(d) => unresolved_proc_macro::unresolved_proc_macro(&ctx, &d),
237 AnyDiagnostic::InactiveCode(d) => match inactive_code::inactive_code(&ctx, &d) {
242 if let Some(code) = d.code {
243 if ctx.config.disabled.contains(code.as_str()) {
247 if ctx.config.disable_experimental && d.experimental {
256 fn diagnostic_with_fix<D: DiagnosticWithFixes>(
258 sema: &Semantics<RootDatabase>,
259 resolve: &AssistResolveStrategy,
261 Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message())
262 .with_fixes(d.fixes(sema, resolve))
263 .with_code(Some(d.code()))
266 fn warning_with_fix<D: DiagnosticWithFixes>(
268 sema: &Semantics<RootDatabase>,
269 resolve: &AssistResolveStrategy,
271 Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message())
272 .with_fixes(d.fixes(sema, resolve))
273 .with_code(Some(d.code()))
276 fn check_unnecessary_braces_in_use_statement(
277 acc: &mut Vec<Diagnostic>,
281 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
282 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
283 // If there is a comment inside the bracketed `use`,
284 // assume it is a commented out module path and don't show diagnostic.
285 if use_tree_list.has_inner_comment() {
289 let use_range = use_tree_list.syntax().text_range();
291 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
293 let to_replace = single_use_tree.syntax().text().to_string();
294 let mut edit_builder = TextEdit::builder();
295 edit_builder.delete(use_range);
296 edit_builder.insert(use_range.start(), to_replace);
297 edit_builder.finish()
301 Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
302 .with_fixes(Some(vec![fix(
304 "Remove unnecessary braces",
305 SourceChange::from_text_edit(file_id, edit),
314 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
315 single_use_tree: &ast::UseTree,
316 ) -> Option<TextEdit> {
317 let use_tree_list_node = single_use_tree.syntax().parent()?;
318 if single_use_tree.path()?.segment()?.self_token().is_some() {
319 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
320 let end = use_tree_list_node.text_range().end();
321 return Some(TextEdit::delete(TextRange::new(start, end)));
326 fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
327 let mut res = unresolved_fix(id, label, target);
328 res.source_change = Some(source_change);
332 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
333 assert!(!id.contains(' '));
335 id: AssistId(id, AssistKind::QuickFix),
336 label: Label::new(label),
345 use expect_test::Expect;
346 use ide_assists::AssistResolveStrategy;
347 use stdx::trim_indent;
348 use test_utils::{assert_eq_text, extract_annotations};
350 use crate::{fixture, DiagnosticsConfig};
352 /// Takes a multi-file input fixture with annotated cursor positions,
354 /// * a diagnostic is produced
355 /// * the first diagnostic fix trigger range touches the input cursor position
356 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
358 pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
359 check_nth_fix(0, ra_fixture_before, ra_fixture_after);
361 /// Takes a multi-file input fixture with annotated cursor positions,
363 /// * a diagnostic is produced
364 /// * every diagnostic fixes trigger range touches the input cursor position
365 /// * that the contents of the file containing the cursor match `after` after each diagnostic fix is applied
366 pub(crate) fn check_fixes(ra_fixture_before: &str, ra_fixtures_after: Vec<&str>) {
367 for (i, ra_fixture_after) in ra_fixtures_after.iter().enumerate() {
368 check_nth_fix(i, ra_fixture_before, ra_fixture_after)
373 fn check_nth_fix(nth: usize, ra_fixture_before: &str, ra_fixture_after: &str) {
374 let after = trim_indent(ra_fixture_after);
376 let (analysis, file_position) = fixture::position(ra_fixture_before);
377 let diagnostic = analysis
379 &DiagnosticsConfig::default(),
380 AssistResolveStrategy::All,
381 file_position.file_id,
386 let fix = &diagnostic.fixes.unwrap()[nth];
388 let source_change = fix.source_change.as_ref().unwrap();
389 let file_id = *source_change.source_file_edits.keys().next().unwrap();
390 let mut actual = analysis.file_text(file_id).unwrap().to_string();
392 for edit in source_change.source_file_edits.values() {
393 edit.apply(&mut actual);
398 assert_eq_text!(&after, &actual);
400 fix.target.contains_inclusive(file_position.offset),
401 "diagnostic fix range {:?} does not touch cursor position {:?}",
406 /// Checks that there's a diagnostic *without* fix at `$0`.
407 fn check_no_fix(ra_fixture: &str) {
408 let (analysis, file_position) = fixture::position(ra_fixture);
409 let diagnostic = analysis
411 &DiagnosticsConfig::default(),
412 AssistResolveStrategy::All,
413 file_position.file_id,
418 assert!(diagnostic.fixes.is_none(), "got a fix when none was expected: {:?}", diagnostic);
421 pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) {
422 let (analysis, file_id) = fixture::file(ra_fixture);
423 let diagnostics = analysis
424 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
426 expect.assert_debug_eq(&diagnostics)
430 pub(crate) fn check_diagnostics(ra_fixture: &str) {
431 let mut config = DiagnosticsConfig::default();
432 config.disabled.insert("inactive-code".to_string());
433 check_diagnostics_with_config(config, ra_fixture)
437 pub(crate) fn check_diagnostics_with_config(config: DiagnosticsConfig, ra_fixture: &str) {
438 let (analysis, files) = fixture::files(ra_fixture);
439 for file_id in files {
441 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
443 let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
445 diagnostics.into_iter().map(|d| (d.range, d.message)).collect::<Vec<_>>();
446 actual.sort_by_key(|(range, _)| range.start());
447 assert_eq!(expected, actual);
452 fn range_mapping_out_of_macros() {
453 // FIXME: this is very wrong, but somewhat tricky to fix.
460 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
463 let _x = id![Foo { a: $042 }];
466 pub struct Foo { pub a: i32, pub b: i32 }
473 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
476 let _x = id![Foo { a: 42 }];
479 pub struct Foo { pub a: i32, pub b: i32 }
485 fn test_check_unnecessary_braces_in_use_statement() {
557 mod a { mod c {} mod d { mod e {} } }
558 use a::{c, d::{e$0}};
561 mod a { mod c {} mod d { mod e {} } }
568 fn test_disabled_diagnostics() {
569 let mut config = DiagnosticsConfig::default();
570 config.disabled.insert("unresolved-module".into());
572 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
575 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
576 assert!(diagnostics.is_empty());
578 let diagnostics = analysis
579 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
581 assert!(!diagnostics.is_empty());
585 fn unlinked_file_prepend_first_item() {
586 cov_mark::check!(unlinked_file_prepend_before_first_item);
587 // Only tests the first one for `pub mod` since the rest are the same
611 fn unlinked_file_append_mod() {
612 cov_mark::check!(unlinked_file_append_to_existing_mods);
624 mod preexisting_bottom;)
638 mod preexisting_bottom;)
644 fn unlinked_file_insert_in_empty_file() {
645 cov_mark::check!(unlinked_file_empty_file);
659 fn unlinked_file_old_style_modrs() {
677 fn unlinked_file_new_style_mod() {
693 fn unlinked_file_with_cfg_off() {
694 cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
708 fn unlinked_file_with_cfg_on() {
720 // Register the required standard library types to make the tests work
721 fn add_filter_map_with_find_next_boilerplate(body: &str) -> String {
723 //- /main.rs crate:main deps:core
724 use core::iter::Iterator;
725 use core::option::Option::{self, Some, None};
728 //- /core/lib.rs crate:core
730 pub enum Option<T> { Some(T), None }
735 fn filter_map<B, F>(self, f: F) -> FilterMap where F: FnMut(Self::Item) -> Option<B> { FilterMap }
736 fn next(&mut self) -> Option<Self::Item>;
738 pub struct FilterMap {}
739 impl Iterator for FilterMap {
741 fn next(&mut self) -> i32 { 7 }
745 format!("{}{}{}", prefix, body, suffix)
749 fn replace_filter_map_next_with_find_map2() {
750 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
753 let m = [1, 2, 3].iter().filter_map(|x| if *x == 2 { Some (4) } else { None }).next();
754 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ replace filter_map(..).next() with find_map(..)
761 fn replace_filter_map_next_with_find_map_no_diagnostic_without_next() {
762 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
767 .filter_map(|x| if *x == 2 { Some (4) } else { None })
775 fn replace_filter_map_next_with_find_map_no_diagnostic_with_intervening_methods() {
776 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
781 .filter_map(|x| if *x == 2 { Some (4) } else { None })
790 fn replace_filter_map_next_with_find_map_no_diagnostic_if_not_in_chain() {
791 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
796 .filter_map(|x| if *x == 2 { Some (4) } else { None });
804 fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
807 struct S { foo: i32, bar: () }
808 fn baz(s: S) -> i32 {
810 S { foo, .. } => foo,
818 fn missing_record_pat_field_box() {
821 struct S { s: Box<u32> }
830 fn missing_record_pat_field_ref() {
842 fn missing_semicolon() {
845 fn test() -> i32 { 123; }
846 //^^^ Remove this semicolon
852 fn import_extern_crate_clash_with_inner_item() {
853 // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
857 //- /lib.rs crate:lib deps:jwt
860 use permissions::jwt;
864 jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
872 //- /jwt/lib.rs crate:jwt
882 pub(super) mod match_check_tests {
883 use crate::diagnostics::tests::check_diagnostics;
891 //^^ Missing match arm
893 //^^^^ Missing match arm
895 match () { _ => (), }
896 match () { () => (), }
897 match (()) { (()) => (), }
904 fn tuple_of_two_empty_tuple() {
909 //^^^^^^^^ Missing match arm
911 match ((), ()) { ((), ()) => (), }
923 //^^^^^ Missing match arm
924 match false { true => (), }
925 //^^^^^ Missing match arm
926 match (false, true) {}
927 //^^^^^^^^^^^^^ Missing match arm
928 match (false, true) { (true, true) => (), }
929 //^^^^^^^^^^^^^ Missing match arm
930 match (false, true) {
931 //^^^^^^^^^^^^^ Missing match arm
933 (false, false) => (),
936 match (false, true) { (true, _x) => (), }
937 //^^^^^^^^^^^^^ Missing match arm
939 match false { true => (), false => (), }
940 match (false, true) {
945 match (false, true) {
949 (false, false) => (),
951 match (false, true) {
954 (false, false) => (),
956 match (false, true, false) {
960 match (false, true, false) {
964 match (false, true, false) { (..) => (), }
971 fn tuple_of_tuple_and_bools() {
975 match (false, ((), false)) {}
976 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
977 match (false, ((), false)) { (true, ((), true)) => (), }
978 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
979 match (false, ((), false)) { (true, _) => (), }
980 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
982 match (false, ((), false)) {
983 (true, ((), true)) => (),
984 (true, ((), false)) => (),
985 (false, ((), true)) => (),
986 (false, ((), false)) => (),
988 match (false, ((), false)) {
989 (true, ((), true)) => (),
990 (true, ((), false)) => (),
1002 enum Either { A, B, }
1006 //^^^^^^^^^ Missing match arm
1007 match Either::B { Either::A => (), }
1008 //^^^^^^^^^ Missing match arm
1011 //^^^^^^^^^^ Missing match arm
1016 Either::A => (), Either::B => (),
1019 Either::A => (), Either::B => (),
1027 fn enum_containing_bool() {
1030 enum Either { A(bool), B }
1034 //^^^^^^^^^ Missing match arm
1036 //^^^^^^^^^ Missing match arm
1037 Either::A(true) => (), Either::B => ()
1041 Either::A(true) => (),
1042 Either::A(false) => (),
1060 fn enum_different_sizes() {
1063 enum Either { A(bool), B(bool, bool) }
1066 match Either::A(false) {
1067 //^^^^^^^^^^^^^^^^ Missing match arm
1069 Either::B(false, _) => (),
1072 match Either::A(false) {
1074 Either::B(true, _) => (),
1075 Either::B(false, _) => (),
1077 match Either::A(false) {
1078 Either::A(true) | Either::A(false) => (),
1079 Either::B(true, _) => (),
1080 Either::B(false, _) => (),
1088 fn tuple_of_enum_no_diagnostic() {
1091 enum Either { A(bool), B(bool, bool) }
1092 enum Either2 { C, D }
1095 match (Either::A(false), Either2::C) {
1096 (Either::A(true), _) | (Either::A(false), _) => (),
1097 (Either::B(true, _), Either2::C) => (),
1098 (Either::B(false, _), Either2::C) => (),
1099 (Either::B(_, _), Either2::D) => (),
1107 fn or_pattern_no_diagnostic() {
1113 match (Either::A, Either::B) {
1114 (Either::A | Either::B, _) => (),
1121 fn mismatched_types() {
1122 // Match statements with arms that don't match the
1123 // expression pattern do not fire this diagnostic.
1126 enum Either { A, B }
1127 enum Either2 { C, D }
1132 // ^^^^^^^^^^ Internal: match check bailed out
1135 match (true, false) {
1136 (true, false, true) => (),
1137 // ^^^^^^^^^^^^^^^^^^^ Internal: match check bailed out
1140 match (true, false) { (true,) => {} }
1141 // ^^^^^^^ Internal: match check bailed out
1142 match (0) { () => () }
1143 // ^^ Internal: match check bailed out
1144 match Unresolved::Bar { Unresolved::Baz => () }
1151 fn mismatched_types_in_or_patterns() {
1155 match false { true | () => {} }
1156 // ^^^^^^^^^ Internal: match check bailed out
1157 match (false,) { (true | (),) => {} }
1158 // ^^^^^^^^^^^^ Internal: match check bailed out
1165 fn malformed_match_arm_tuple_enum_missing_pattern() {
1166 // We are testing to be sure we don't panic here when the match
1167 // arm `Either::B` is missing its pattern.
1170 enum Either { A, B(u32) }
1183 fn malformed_match_arm_extra_fields() {
1186 enum A { B(isize, isize), C }
1189 A::B(_, _, _) => (),
1190 // ^^^^^^^^^^^^^ Internal: match check bailed out
1194 // ^^^^^^^ Internal: match check bailed out
1202 fn expr_diverges() {
1205 enum Either { A, B }
1210 // ^^^^^^^^^ Internal: match check bailed out
1215 // ^^^^^^^^^ Internal: match check bailed out
1217 match loop { break Foo::A } {
1218 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1221 match loop { break Foo::A } {
1231 fn expr_partially_diverges() {
1234 enum Either<T> { A(T), B }
1236 fn foo() -> Either<!> { Either::B }
1239 Either::A(val) => val,
1251 enum Either { A { foo: bool }, B }
1254 let a = Either::A { foo: true };
1256 //^ Missing match arm
1257 match a { Either::A { foo: true } => () }
1258 //^ Missing match arm
1260 Either::A { } => (),
1261 //^^^^^^^^^ Missing structure fields:
1266 //^ Missing match arm
1267 Either::A { } => (),
1268 } //^^^^^^^^^ Missing structure fields:
1272 Either::A { foo: true } => (),
1273 Either::A { foo: false } => (),
1277 Either::A { foo: _ } => (),
1286 fn enum_record_fields_out_of_order() {
1290 A { foo: bool, bar: () },
1295 let a = Either::A { foo: true, bar: () };
1297 //^ Missing match arm
1298 Either::A { bar: (), foo: false } => (),
1299 Either::A { foo: true, bar: () } => (),
1303 Either::A { bar: (), foo: false } => (),
1304 Either::A { foo: true, bar: () } => (),
1313 fn enum_record_ellipsis() {
1317 A { foo: bool, bar: bool },
1324 //^ Missing match arm
1325 Either::A { foo: true, .. } => (),
1329 //^ Missing match arm
1330 Either::A { .. } => (),
1334 Either::A { foo: true, .. } => (),
1335 Either::A { foo: false, .. } => (),
1340 Either::A { .. } => (),
1349 fn enum_tuple_partial_ellipsis() {
1353 A(bool, bool, bool, bool),
1359 //^^^^^^^^^ Missing match arm
1360 Either::A(true, .., true) => (),
1361 Either::A(true, .., false) => (),
1362 Either::A(false, .., false) => (),
1366 //^^^^^^^^^ Missing match arm
1367 Either::A(true, .., true) => (),
1368 Either::A(true, .., false) => (),
1369 Either::A(.., true) => (),
1374 Either::A(true, .., true) => (),
1375 Either::A(true, .., false) => (),
1376 Either::A(false, .., true) => (),
1377 Either::A(false, .., false) => (),
1381 Either::A(true, .., true) => (),
1382 Either::A(true, .., false) => (),
1383 Either::A(.., true) => (),
1384 Either::A(.., false) => (),
1398 fn enum_(never: Never) {
1401 fn enum_ref(never: &Never) {
1403 //^^^^^ Missing match arm
1416 enum Option<T> { Some(T), None }
1419 // `Never` is deliberately not defined so that it's an uninferred type.
1420 match Option::<Never>::None {
1422 Some(never) => match never {},
1423 // ^^^^^^^^^^^ Internal: match check bailed out
1425 match Option::<Never>::None {
1426 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1427 Option::Some(_never) => {},
1435 fn tuple_of_bools_with_ellipsis_at_end_missing_arm() {
1439 match (false, true, false) {
1440 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1448 fn tuple_of_bools_with_ellipsis_at_beginning_missing_arm() {
1452 match (false, true, false) {
1453 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1461 fn tuple_of_bools_with_ellipsis_in_middle_missing_arm() {
1465 match (false, true, false) {
1466 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1467 (true, .., false) => (),
1474 fn record_struct() {
1476 r#"struct Foo { a: bool }
1479 //^ Missing match arm
1480 match f { Foo { a: true } => () }
1481 //^ Missing match arm
1482 match &f { Foo { a: true } => () }
1483 //^^ Missing match arm
1484 match f { Foo { a: _ } => () }
1486 Foo { a: true } => (),
1487 Foo { a: false } => (),
1490 Foo { a: true } => (),
1491 Foo { a: false } => (),
1501 r#"struct Foo(bool);
1504 //^ Missing match arm
1505 match f { Foo(true) => () }
1506 //^ Missing match arm
1522 //^ Missing match arm
1523 match f { Foo => () }
1530 fn record_struct_ellipsis() {
1532 r#"struct Foo { foo: bool, bar: bool }
1534 match f { Foo { foo: true, .. } => () }
1535 //^ Missing match arm
1537 //^ Missing match arm
1538 Foo { foo: true, .. } => (),
1539 Foo { bar: false, .. } => ()
1541 match f { Foo { .. } => () }
1543 Foo { foo: true, .. } => (),
1544 Foo { foo: false, .. } => ()
1556 enum Either { A(bool), B }
1558 //^^^^^^^^^ Missing match arm
1559 Either::A(true | false) => (),
1567 fn no_panic_at_unimplemented_subpattern_type() {
1572 match v { S{ a } => {} }
1573 match v { S{ a: _x } => {} }
1574 match v { S{ a: 'a' } => {} }
1575 //^^^^^^^^^^^ Internal: match check bailed out
1576 match v { S{..} => {} }
1579 //^ Missing match arm
1594 match true { _x @ true => {} }
1595 //^^^^ Missing match arm
1602 fn binding_ref_has_correct_type() {
1603 // Asserts `PatKind::Binding(ref _x): bool`, not &bool.
1604 // If that's not true match checking will panic with "incompatible constructors"
1605 // FIXME: make facilities to test this directly like `tests::check_infer(..)`
1610 // FIXME: this should not bail out but current behavior is such as the old algorithm.
1611 // ExprValidator::validate_match(..) checks types of top level patterns incorrecly.
1614 // ^^^^^^ Internal: match check bailed out
1627 fn enum_non_exhaustive() {
1630 //- /lib.rs crate:lib
1634 match E::A { _ => {} }
1644 //- /main.rs crate:main deps:lib
1647 match E::A { _ => {} }
1649 //^^^^ Missing match arm
1654 //^^^^ Missing match arm
1673 //^^^^ Missing match arm
1683 fn pattern_type_is_of_substitution() {
1684 cov_mark::check!(match_check_wildcard_expanded_to_substitutions);
1699 fn record_struct_no_such_field() {
1704 match f { Foo { bar } => () }
1705 // ^^^^^^^^^^^ Internal: match check bailed out
1712 fn match_ergonomics_issue_9095() {
1715 enum Foo<T> { A(T) }
1717 match &Foo::A(true) {
1726 mod false_negatives {
1727 //! The implementation of match checking here is a work in progress. As we roll this out, we
1728 //! prefer false negatives to false positives (ideally there would be no false positives). This
1729 //! test module should document known false negatives. Eventually we will have a complete
1730 //! implementation of match checking and this module will be empty.
1732 //! The reasons for documenting known false negatives:
1734 //! 1. It acts as a backlog of work that can be done to improve the behavior of the system.
1735 //! 2. It ensures the code doesn't panic when handling these cases.
1740 // We don't currently check integer exhaustiveness.
1746 // ^^ Internal: match check bailed out
1755 fn reference_patterns_at_top_level() {
1761 // ^^^^^ Internal: match check bailed out
1769 fn reference_patterns_in_fields() {
1775 // ^^^^^^^ Internal: match check bailed out
1779 // ^^^^^^^^ Internal: match check bailed out
1789 mod decl_check_tests {
1790 use crate::diagnostics::tests::check_diagnostics;
1793 fn incorrect_function_name() {
1796 fn NonSnakeCaseName() {}
1797 // ^^^^^^^^^^^^^^^^ Function `NonSnakeCaseName` should have snake_case name, e.g. `non_snake_case_name`
1803 fn incorrect_function_params() {
1806 fn foo(SomeParam: u8) {}
1807 // ^^^^^^^^^ Parameter `SomeParam` should have snake_case name, e.g. `some_param`
1809 fn foo2(ok_param: &str, CAPS_PARAM: u8) {}
1810 // ^^^^^^^^^^ Parameter `CAPS_PARAM` should have snake_case name, e.g. `caps_param`
1816 fn incorrect_variable_names() {
1820 let SOME_VALUE = 10;
1821 // ^^^^^^^^^^ Variable `SOME_VALUE` should have snake_case name, e.g. `some_value`
1822 let AnotherValue = 20;
1823 // ^^^^^^^^^^^^ Variable `AnotherValue` should have snake_case name, e.g. `another_value`
1830 fn incorrect_struct_names() {
1833 struct non_camel_case_name {}
1834 // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName`
1836 struct SCREAMING_CASE {}
1837 // ^^^^^^^^^^^^^^ Structure `SCREAMING_CASE` should have CamelCase name, e.g. `ScreamingCase`
1843 fn no_diagnostic_for_camel_cased_acronyms_in_struct_name() {
1852 fn incorrect_struct_field() {
1855 struct SomeStruct { SomeField: u8 }
1856 // ^^^^^^^^^ Field `SomeField` should have snake_case name, e.g. `some_field`
1862 fn incorrect_enum_names() {
1865 enum some_enum { Val(u8) }
1866 // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum`
1869 // ^^^^^^^^^ Enum `SOME_ENUM` should have CamelCase name, e.g. `SomeEnum`
1875 fn no_diagnostic_for_camel_cased_acronyms_in_enum_name() {
1884 fn incorrect_enum_variant_name() {
1887 enum SomeEnum { SOME_VARIANT(u8) }
1888 // ^^^^^^^^^^^^ Variant `SOME_VARIANT` should have CamelCase name, e.g. `SomeVariant`
1894 fn incorrect_const_name() {
1897 const some_weird_const: u8 = 10;
1898 // ^^^^^^^^^^^^^^^^ Constant `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
1904 fn incorrect_static_name() {
1907 static some_weird_const: u8 = 10;
1908 // ^^^^^^^^^^^^^^^^ Static variable `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
1914 fn fn_inside_impl_struct() {
1918 // ^^^^^^^^^^ Structure `someStruct` should have CamelCase name, e.g. `SomeStruct`
1921 fn SomeFunc(&self) {
1922 // ^^^^^^^^ Function `SomeFunc` should have snake_case name, e.g. `some_func`
1923 let WHY_VAR_IS_CAPS = 10;
1924 // ^^^^^^^^^^^^^^^ Variable `WHY_VAR_IS_CAPS` should have snake_case name, e.g. `why_var_is_caps`
1932 fn no_diagnostic_for_enum_varinats() {
1935 enum Option { Some, None }
1938 match Option::None {
1951 enum Option { Some, None }
1954 match Option::None {
1955 SOME_VAR @ None => (),
1956 // ^^^^^^^^ Variable `SOME_VAR` should have snake_case name, e.g. `some_var`
1965 fn allow_attributes() {
1968 #[allow(non_snake_case)]
1969 fn NonSnakeCaseName(SOME_VAR: u8) -> u8{
1970 // cov_flags generated output from elsewhere in this file
1973 static lower_case: u8;
1976 let OtherVar = SOME_VAR + 1;
1980 #[allow(nonstandard_style)]
1981 mod CheckNonstandardStyle {
1982 fn HiImABadFnName() {}
1987 fn HiImABadFnName() {}
1991 #![allow(non_snake_case)]
1992 fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {}
1995 #[allow(non_snake_case, non_camel_case_types)]
1996 pub struct some_type {
2001 #[allow(non_upper_case_globals)]
2002 pub const some_const: u8 = 10;
2004 #[allow(non_upper_case_globals)]
2005 pub static SomeStatic: u8 = 10;
2011 fn allow_attributes_crate_attr() {
2014 #![allow(non_snake_case)]
2017 fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {}
2025 fn bug_trait_inside_fn() {
2027 // This is broken, and in fact, should not even be looked at by this
2028 // lint in the first place. There's weird stuff going on in the
2029 // collection phase.
2030 // It's currently being brought in by:
2031 // * validate_func on `a` recursing into modules
2032 // * then it finds the trait and then the function while iterating
2034 // * then validate_func is called on Dirty
2035 // * ... which then proceeds to look at some unknown module taking no
2036 // attrs from either the impl or the fn a, and then finally to the root
2039 // It should find the attribute on the trait, but it *doesn't even see
2040 // the trait* as far as I can tell.
2048 // this comes out of bitflags, mostly
2049 #[allow(non_snake_case)]
2051 const HiImAlsoBad: u8 = 2;
2053 fn Dirty(&self) -> bool {
2066 fn bug_traits_arent_checked() {
2067 // FIXME: Traits and functions in traits aren't currently checked by
2068 // r-a, even though rustc will complain about them.
2072 // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait`
2074 // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function`
2076 // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function`
2083 fn ignores_extern_items() {
2084 cov_mark::check!(extern_func_incorrect_case_ignored);
2085 cov_mark::check!(extern_static_incorrect_case_ignored);
2089 fn NonSnakeCaseName(SOME_VAR: u8) -> u8;
2090 pub static SomeStatic: u8 = 10;
2097 fn infinite_loop_inner_items() {
2109 #[test] // Issue #8809.
2110 fn parenthesized_parameter() {
2111 check_diagnostics(r#"fn f((O): _) {}"#)