1 //! Collects diagnostics & fixits for a single file.
3 //! The tricky bit here is that diagnostics are produced by hir in terms of
4 //! macro-expanded files, but we need to present them to the users in terms of
5 //! original files. So we need to map the ranges.
8 mod unresolved_extern_crate;
10 mod unresolved_macro_call;
11 mod unresolved_proc_macro;
20 use std::cell::RefCell;
23 diagnostics::{AnyDiagnostic, Diagnostic as _, DiagnosticCode, DiagnosticSinkBuilder},
26 use ide_assists::AssistResolveStrategy;
27 use ide_db::{base_db::SourceDatabase, RootDatabase};
28 use itertools::Itertools;
29 use rustc_hash::FxHashSet;
32 SyntaxNode, SyntaxNodePtr, TextRange, TextSize,
34 use text_edit::TextEdit;
35 use unlinked_file::UnlinkedFile;
37 use crate::{Assist, AssistId, AssistKind, FileId, Label, SourceChange};
39 use self::fixes::DiagnosticWithFixes;
42 pub struct Diagnostic {
43 // pub name: Option<String>,
46 pub severity: Severity,
47 pub fixes: Option<Vec<Assist>>,
49 pub code: Option<DiagnosticCode>,
50 pub experimental: bool,
54 fn new(code: &'static str, message: impl Into<String>, range: TextRange) -> Diagnostic {
55 let message = message.into();
56 let code = Some(DiagnosticCode(code));
60 severity: Severity::Error,
68 fn experimental(mut self) -> Diagnostic {
69 self.experimental = true;
73 fn severity(mut self, severity: Severity) -> Diagnostic {
74 self.severity = severity;
78 fn error(range: TextRange, message: String) -> Self {
82 severity: Severity::Error,
90 fn hint(range: TextRange, message: String) -> Self {
94 severity: Severity::WeakWarning,
102 fn with_fixes(self, fixes: Option<Vec<Assist>>) -> Self {
103 Self { fixes, ..self }
106 fn with_unused(self, unused: bool) -> Self {
107 Self { unused, ..self }
110 fn with_code(self, code: Option<DiagnosticCode>) -> Self {
111 Self { code, ..self }
115 #[derive(Debug, Copy, Clone)]
121 #[derive(Default, Debug, Clone)]
122 pub struct DiagnosticsConfig {
123 pub disable_experimental: bool,
124 pub disabled: FxHashSet<String>,
127 struct DiagnosticsContext<'a> {
128 config: &'a DiagnosticsConfig,
129 sema: Semantics<'a, RootDatabase>,
131 resolve: &'a AssistResolveStrategy,
134 pub(crate) fn diagnostics(
136 config: &DiagnosticsConfig,
137 resolve: &AssistResolveStrategy,
139 ) -> Vec<Diagnostic> {
140 let _p = profile::span("diagnostics");
141 let sema = Semantics::new(db);
142 let parse = db.parse(file_id);
143 let mut res = Vec::new();
145 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
151 .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
154 for node in parse.tree().syntax().descendants() {
155 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
156 field_shorthand::check(&mut res, file_id, &node);
158 let res = RefCell::new(res);
159 let sink_builder = DiagnosticSinkBuilder::new()
160 .on::<hir::diagnostics::MissingOkOrSomeInTailExpr, _>(|d| {
161 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
163 .on::<hir::diagnostics::NoSuchField, _>(|d| {
164 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
166 .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| {
167 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
169 .on::<hir::diagnostics::IncorrectCase, _>(|d| {
170 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
172 .on::<hir::diagnostics::ReplaceFilterMapNextWithFindMap, _>(|d| {
173 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
175 .on::<UnlinkedFile, _>(|d| {
176 // Limit diagnostic to the first few characters in the file. This matches how VS Code
177 // renders it with the full span, but on other editors, and is less invasive.
178 let range = sema.diagnostics_display_range(d.display_source()).range;
179 let range = range.intersect(TextRange::up_to(TextSize::of("..."))).unwrap_or(range);
181 // Override severity and mark as unused.
182 res.borrow_mut().push(
183 Diagnostic::hint(range, d.message())
184 .with_fixes(d.fixes(&sema, resolve))
185 .with_code(Some(d.code())),
188 .on::<hir::diagnostics::UnimplementedBuiltinMacro, _>(|d| {
189 let display_range = sema.diagnostics_display_range(d.display_source()).range;
191 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
193 // Only collect experimental diagnostics when they're enabled.
194 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
195 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
197 // Finalize the `DiagnosticSink` building process.
198 let mut sink = sink_builder
199 // Diagnostics not handled above get no fix and default treatment.
201 res.borrow_mut().push(
203 sema.diagnostics_display_range(d.display_source()).range,
206 .with_code(Some(d.code())),
210 let mut diags = Vec::new();
211 let internal_diagnostics = cfg!(test);
212 match sema.to_module_def(file_id) {
213 Some(m) => diags = m.diagnostics(db, &mut sink, internal_diagnostics),
215 sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(parse.tree().syntax()) });
221 let mut res = res.into_inner();
223 let ctx = DiagnosticsContext { config, sema, resolve };
227 AnyDiagnostic::UnresolvedModule(d) => unresolved_module::unresolved_module(&ctx, &d),
228 AnyDiagnostic::UnresolvedExternCrate(d) => unresolved_extern_crate::unresolved_extern_crate(&ctx, &d),
229 AnyDiagnostic::UnresolvedImport(d) => unresolved_import::unresolved_import(&ctx, &d),
230 AnyDiagnostic::UnresolvedMacroCall(d) => unresolved_macro_call::unresolved_macro_call(&ctx, &d),
231 AnyDiagnostic::UnresolvedProcMacro(d) => unresolved_proc_macro::unresolved_proc_macro(&ctx, &d),
232 AnyDiagnostic::MissingFields(d) => missing_fields::missing_fields(&ctx, &d),
233 AnyDiagnostic::MacroError(d) => macro_error::macro_error(&ctx, &d),
235 AnyDiagnostic::InactiveCode(d) => match inactive_code::inactive_code(&ctx, &d) {
240 if let Some(code) = d.code {
241 if ctx.config.disabled.contains(code.as_str()) {
245 if ctx.config.disable_experimental && d.experimental {
254 fn diagnostic_with_fix<D: DiagnosticWithFixes>(
256 sema: &Semantics<RootDatabase>,
257 resolve: &AssistResolveStrategy,
259 Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message())
260 .with_fixes(d.fixes(sema, resolve))
261 .with_code(Some(d.code()))
264 fn warning_with_fix<D: DiagnosticWithFixes>(
266 sema: &Semantics<RootDatabase>,
267 resolve: &AssistResolveStrategy,
269 Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message())
270 .with_fixes(d.fixes(sema, resolve))
271 .with_code(Some(d.code()))
274 fn check_unnecessary_braces_in_use_statement(
275 acc: &mut Vec<Diagnostic>,
279 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
280 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
281 // If there is a comment inside the bracketed `use`,
282 // assume it is a commented out module path and don't show diagnostic.
283 if use_tree_list.has_inner_comment() {
287 let use_range = use_tree_list.syntax().text_range();
289 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
291 let to_replace = single_use_tree.syntax().text().to_string();
292 let mut edit_builder = TextEdit::builder();
293 edit_builder.delete(use_range);
294 edit_builder.insert(use_range.start(), to_replace);
295 edit_builder.finish()
299 Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
300 .with_fixes(Some(vec![fix(
302 "Remove unnecessary braces",
303 SourceChange::from_text_edit(file_id, edit),
312 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
313 single_use_tree: &ast::UseTree,
314 ) -> Option<TextEdit> {
315 let use_tree_list_node = single_use_tree.syntax().parent()?;
316 if single_use_tree.path()?.segment()?.self_token().is_some() {
317 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
318 let end = use_tree_list_node.text_range().end();
319 return Some(TextEdit::delete(TextRange::new(start, end)));
324 fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
325 let mut res = unresolved_fix(id, label, target);
326 res.source_change = Some(source_change);
330 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
331 assert!(!id.contains(' '));
333 id: AssistId(id, AssistKind::QuickFix),
334 label: Label::new(label),
343 use expect_test::Expect;
344 use hir::diagnostics::DiagnosticCode;
345 use ide_assists::AssistResolveStrategy;
346 use stdx::trim_indent;
347 use test_utils::{assert_eq_text, extract_annotations};
349 use crate::{fixture, DiagnosticsConfig};
351 /// Takes a multi-file input fixture with annotated cursor positions,
353 /// * a diagnostic is produced
354 /// * the first diagnostic fix trigger range touches the input cursor position
355 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
357 pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
358 check_nth_fix(0, ra_fixture_before, ra_fixture_after);
360 /// Takes a multi-file input fixture with annotated cursor positions,
362 /// * a diagnostic is produced
363 /// * every diagnostic fixes trigger range touches the input cursor position
364 /// * that the contents of the file containing the cursor match `after` after each diagnostic fix is applied
365 pub(crate) fn check_fixes(ra_fixture_before: &str, ra_fixtures_after: Vec<&str>) {
366 for (i, ra_fixture_after) in ra_fixtures_after.iter().enumerate() {
367 check_nth_fix(i, ra_fixture_before, ra_fixture_after)
372 fn check_nth_fix(nth: usize, ra_fixture_before: &str, ra_fixture_after: &str) {
373 let after = trim_indent(ra_fixture_after);
375 let (analysis, file_position) = fixture::position(ra_fixture_before);
376 let diagnostic = analysis
378 &DiagnosticsConfig::default(),
379 AssistResolveStrategy::All,
380 file_position.file_id,
385 let fix = &diagnostic.fixes.unwrap()[nth];
387 let source_change = fix.source_change.as_ref().unwrap();
388 let file_id = *source_change.source_file_edits.keys().next().unwrap();
389 let mut actual = analysis.file_text(file_id).unwrap().to_string();
391 for edit in source_change.source_file_edits.values() {
392 edit.apply(&mut actual);
397 assert_eq_text!(&after, &actual);
399 fix.target.contains_inclusive(file_position.offset),
400 "diagnostic fix range {:?} does not touch cursor position {:?}",
405 /// Checks that there's a diagnostic *without* fix at `$0`.
406 fn check_no_fix(ra_fixture: &str) {
407 let (analysis, file_position) = fixture::position(ra_fixture);
408 let diagnostic = analysis
410 &DiagnosticsConfig::default(),
411 AssistResolveStrategy::All,
412 file_position.file_id,
417 assert!(diagnostic.fixes.is_none(), "got a fix when none was expected: {:?}", diagnostic);
420 /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
421 /// apply to the file containing the cursor.
422 pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
423 let (analysis, files) = fixture::files(ra_fixture);
424 let diagnostics = files
426 .flat_map(|file_id| {
428 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
431 .collect::<Vec<_>>();
432 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
435 pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) {
436 let (analysis, file_id) = fixture::file(ra_fixture);
437 let diagnostics = analysis
438 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
440 expect.assert_debug_eq(&diagnostics)
444 pub(crate) fn check_diagnostics(ra_fixture: &str) {
445 check_diagnostics_with_inactive_code(ra_fixture, false)
449 pub(crate) fn check_diagnostics_with_inactive_code(ra_fixture: &str, with_inactive_code: bool) {
450 let (analysis, file_id) = fixture::file(ra_fixture);
451 let diagnostics = analysis
452 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
455 let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
456 let mut actual = diagnostics
458 .filter(|d| d.code != Some(DiagnosticCode("inactive-code")) || with_inactive_code)
459 .map(|d| (d.range, d.message))
460 .collect::<Vec<_>>();
461 actual.sort_by_key(|(range, _)| range.start());
462 assert_eq!(expected, actual);
466 fn range_mapping_out_of_macros() {
467 // FIXME: this is very wrong, but somewhat tricky to fix.
474 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
477 let _x = id![Foo { a: $042 }];
480 pub struct Foo { pub a: i32, pub b: i32 }
487 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
490 let _x = id![Foo { a: 42 }];
493 pub struct Foo { pub a: i32, pub b: i32 }
499 fn test_check_unnecessary_braces_in_use_statement() {
500 check_no_diagnostics(
513 check_no_diagnostics(
571 mod a { mod c {} mod d { mod e {} } }
572 use a::{c, d::{e$0}};
575 mod a { mod c {} mod d { mod e {} } }
582 fn test_disabled_diagnostics() {
583 let mut config = DiagnosticsConfig::default();
584 config.disabled.insert("unresolved-module".into());
586 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
589 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
590 assert!(diagnostics.is_empty());
592 let diagnostics = analysis
593 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
595 assert!(!diagnostics.is_empty());
599 fn unlinked_file_prepend_first_item() {
600 cov_mark::check!(unlinked_file_prepend_before_first_item);
601 // Only tests the first one for `pub mod` since the rest are the same
625 fn unlinked_file_append_mod() {
626 cov_mark::check!(unlinked_file_append_to_existing_mods);
638 mod preexisting_bottom;)
652 mod preexisting_bottom;)
658 fn unlinked_file_insert_in_empty_file() {
659 cov_mark::check!(unlinked_file_empty_file);
673 fn unlinked_file_old_style_modrs() {
691 fn unlinked_file_new_style_mod() {
707 fn unlinked_file_with_cfg_off() {
708 cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
722 fn unlinked_file_with_cfg_on() {
723 check_no_diagnostics(
735 fn break_outside_of_loop() {
739 //^^^^^ break outside of loop
745 fn no_such_field_diagnostics() {
748 struct S { foo: i32, bar: () }
752 //^ Missing structure fields:
756 //^^^^^^^ no such field
764 fn no_such_field_with_feature_flag_diagnostics() {
767 //- /lib.rs crate:foo cfg:feature=foo
770 #[cfg(feature = "foo")]
775 #[cfg(feature = "foo")]
776 pub(crate) fn new(my_val: usize, bar: bool) -> Self {
779 #[cfg(not(feature = "foo"))]
780 pub(crate) fn new(my_val: usize, _bar: bool) -> Self {
789 fn no_such_field_enum_with_feature_flag_diagnostics() {
792 //- /lib.rs crate:foo cfg:feature=foo
794 #[cfg(not(feature = "foo"))]
796 #[cfg(feature = "foo")]
812 fn no_such_field_with_feature_flag_diagnostics_on_struct_lit() {
815 //- /lib.rs crate:foo cfg:feature=foo
817 #[cfg(feature = "foo")]
819 #[cfg(not(feature = "foo"))]
824 #[cfg(feature = "foo")]
825 fn new(foo: u32) -> Self {
828 #[cfg(not(feature = "foo"))]
829 fn new(bar: u32) -> Self {
832 fn new2(bar: u32) -> Self {
833 #[cfg(feature = "foo")]
834 { Self { foo: bar } }
835 #[cfg(not(feature = "foo"))]
838 fn new2(val: u32) -> Self {
840 #[cfg(feature = "foo")]
842 #[cfg(not(feature = "foo"))]
852 fn no_such_field_with_type_macro() {
855 macro_rules! Type { () => { u32 }; }
856 struct Foo { bar: Type![] }
868 fn missing_unsafe_diagnostic_with_raw_ptr() {
872 let x = &5 as *const usize;
873 unsafe { let y = *x; }
875 } //^^ This operation is unsafe and requires an unsafe function or block
881 fn missing_unsafe_diagnostic_with_unsafe_call() {
887 unsafe fn unsafe_fn(&self) {
888 let x = &5 as *const usize;
893 unsafe fn unsafe_fn() {
894 let x = &5 as *const usize;
900 //^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
901 HasUnsafe.unsafe_fn();
902 //^^^^^^^^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
905 HasUnsafe.unsafe_fn();
913 fn missing_unsafe_diagnostic_with_static_mut() {
920 static mut STATIC_MUT: Ty = Ty { a: 0 };
923 let x = STATIC_MUT.a;
924 //^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
926 let x = STATIC_MUT.a;
934 fn no_missing_unsafe_diagnostic_with_safe_intrinsic() {
937 extern "rust-intrinsic" {
938 pub fn bitreverse(x: u32) -> u32; // Safe intrinsic
939 pub fn floorf32(x: f32) -> f32; // Unsafe intrinsic
943 let _ = bitreverse(12);
944 let _ = floorf32(12.0);
945 //^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
951 // Register the required standard library types to make the tests work
952 fn add_filter_map_with_find_next_boilerplate(body: &str) -> String {
954 //- /main.rs crate:main deps:core
955 use core::iter::Iterator;
956 use core::option::Option::{self, Some, None};
959 //- /core/lib.rs crate:core
961 pub enum Option<T> { Some(T), None }
966 fn filter_map<B, F>(self, f: F) -> FilterMap where F: FnMut(Self::Item) -> Option<B> { FilterMap }
967 fn next(&mut self) -> Option<Self::Item>;
969 pub struct FilterMap {}
970 impl Iterator for FilterMap {
972 fn next(&mut self) -> i32 { 7 }
976 format!("{}{}{}", prefix, body, suffix)
980 fn replace_filter_map_next_with_find_map2() {
981 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
984 let m = [1, 2, 3].iter().filter_map(|x| if *x == 2 { Some (4) } else { None }).next();
985 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ replace filter_map(..).next() with find_map(..)
992 fn replace_filter_map_next_with_find_map_no_diagnostic_without_next() {
993 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
998 .filter_map(|x| if *x == 2 { Some (4) } else { None })
1006 fn replace_filter_map_next_with_find_map_no_diagnostic_with_intervening_methods() {
1007 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1012 .filter_map(|x| if *x == 2 { Some (4) } else { None })
1021 fn replace_filter_map_next_with_find_map_no_diagnostic_if_not_in_chain() {
1022 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1027 .filter_map(|x| if *x == 2 { Some (4) } else { None });
1035 fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
1038 struct S { foo: i32, bar: () }
1039 fn baz(s: S) -> i32 {
1041 S { foo, .. } => foo,
1049 fn missing_record_pat_field_box() {
1052 struct S { s: Box<u32> }
1054 let S { box s } = a;
1061 fn missing_record_pat_field_ref() {
1066 let S { ref s } = a;
1073 fn simple_free_fn_zero() {
1078 //^^^^^^^ Expected 0 arguments, found 1
1091 fn simple_free_fn_one() {
1096 //^^^^^ Expected 1 argument, found 0
1113 impl S { fn method(&self) {} }
1117 } //^^^^^^^^^^^ Expected 1 argument, found 0
1124 impl S { fn method(&self) {} }
1135 fn method_with_arg() {
1139 impl S { fn method(&self, arg: u8) {} }
1143 } //^^^^^^^^^^ Expected 1 argument, found 0
1150 impl S { fn method(&self, arg: u8) {} }
1161 fn method_unknown_receiver() {
1162 // note: this is incorrect code, so there might be errors on this in the
1163 // future, but we shouldn't emit an argument count diagnostic here
1166 trait Foo { fn method(&self, arg: usize) {} }
1180 struct Tup(u8, u16);
1183 } //^^^^^^ Expected 2 arguments, found 1
1192 enum En { Variant(u8, u16), }
1195 } //^^^^^^^^^^^^^^ Expected 2 arguments, found 1
1201 fn enum_variant_type_macro() {
1214 //^^^^^^^^^^^^^^ Expected 1 argument, found 2
1216 //^^^^^^^^^^ Expected 1 argument, found 0
1228 fn fixed(fixed: u8);
1229 fn varargs(fixed: u8, ...);
1237 //^^^^^^^^^^^ Expected 1 argument, found 2
1250 fn arg_count_lambda() {
1256 //^^^ Expected 1 argument, found 0
1259 //^^^^^^^^^ Expected 1 argument, found 2
1266 fn cfgd_out_call_arguments() {
1269 struct C(#[cfg(FALSE)] ());
1282 C::new().method(#[cfg(FALSE)] 0);
1289 fn cfgd_out_fn_params() {
1292 fn foo(#[cfg(NEVER)] x: ()) {}
1297 fn method(#[cfg(NEVER)] self) {}
1298 fn method2(#[cfg(NEVER)] self, arg: u8) {}
1299 fn method3(self, #[cfg(NEVER)] arg: u8) {}
1303 fn fixed(fixed: u8, #[cfg(NEVER)] ...);
1304 fn varargs(#[cfg(not(NEVER))] ...);
1323 fn missing_semicolon() {
1326 fn test() -> i32 { 123; }
1327 //^^^ Remove this semicolon
1333 fn import_extern_crate_clash_with_inner_item() {
1334 // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
1338 //- /lib.rs crate:lib deps:jwt
1341 use permissions::jwt;
1345 jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
1350 pub struct Claims {}
1353 //- /jwt/lib.rs crate:jwt
1363 pub(super) mod match_check_tests {
1364 use crate::diagnostics::tests::check_diagnostics;
1372 //^^ Missing match arm
1374 //^^^^ Missing match arm
1376 match () { _ => (), }
1377 match () { () => (), }
1378 match (()) { (()) => (), }
1385 fn tuple_of_two_empty_tuple() {
1390 //^^^^^^^^ Missing match arm
1392 match ((), ()) { ((), ()) => (), }
1404 //^^^^^ Missing match arm
1405 match false { true => (), }
1406 //^^^^^ Missing match arm
1407 match (false, true) {}
1408 //^^^^^^^^^^^^^ Missing match arm
1409 match (false, true) { (true, true) => (), }
1410 //^^^^^^^^^^^^^ Missing match arm
1411 match (false, true) {
1412 //^^^^^^^^^^^^^ Missing match arm
1413 (false, true) => (),
1414 (false, false) => (),
1415 (true, false) => (),
1417 match (false, true) { (true, _x) => (), }
1418 //^^^^^^^^^^^^^ Missing match arm
1420 match false { true => (), false => (), }
1421 match (false, true) {
1423 (true, false) => (),
1426 match (false, true) {
1428 (true, false) => (),
1429 (false, true) => (),
1430 (false, false) => (),
1432 match (false, true) {
1434 (false, true) => (),
1435 (false, false) => (),
1437 match (false, true, false) {
1441 match (false, true, false) {
1445 match (false, true, false) { (..) => (), }
1452 fn tuple_of_tuple_and_bools() {
1456 match (false, ((), false)) {}
1457 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1458 match (false, ((), false)) { (true, ((), true)) => (), }
1459 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1460 match (false, ((), false)) { (true, _) => (), }
1461 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1463 match (false, ((), false)) {
1464 (true, ((), true)) => (),
1465 (true, ((), false)) => (),
1466 (false, ((), true)) => (),
1467 (false, ((), false)) => (),
1469 match (false, ((), false)) {
1470 (true, ((), true)) => (),
1471 (true, ((), false)) => (),
1483 enum Either { A, B, }
1487 //^^^^^^^^^ Missing match arm
1488 match Either::B { Either::A => (), }
1489 //^^^^^^^^^ Missing match arm
1492 //^^^^^^^^^^ Missing match arm
1497 Either::A => (), Either::B => (),
1500 Either::A => (), Either::B => (),
1508 fn enum_containing_bool() {
1511 enum Either { A(bool), B }
1515 //^^^^^^^^^ Missing match arm
1517 //^^^^^^^^^ Missing match arm
1518 Either::A(true) => (), Either::B => ()
1522 Either::A(true) => (),
1523 Either::A(false) => (),
1541 fn enum_different_sizes() {
1544 enum Either { A(bool), B(bool, bool) }
1547 match Either::A(false) {
1548 //^^^^^^^^^^^^^^^^ Missing match arm
1550 Either::B(false, _) => (),
1553 match Either::A(false) {
1555 Either::B(true, _) => (),
1556 Either::B(false, _) => (),
1558 match Either::A(false) {
1559 Either::A(true) | Either::A(false) => (),
1560 Either::B(true, _) => (),
1561 Either::B(false, _) => (),
1569 fn tuple_of_enum_no_diagnostic() {
1572 enum Either { A(bool), B(bool, bool) }
1573 enum Either2 { C, D }
1576 match (Either::A(false), Either2::C) {
1577 (Either::A(true), _) | (Either::A(false), _) => (),
1578 (Either::B(true, _), Either2::C) => (),
1579 (Either::B(false, _), Either2::C) => (),
1580 (Either::B(_, _), Either2::D) => (),
1588 fn or_pattern_no_diagnostic() {
1594 match (Either::A, Either::B) {
1595 (Either::A | Either::B, _) => (),
1602 fn mismatched_types() {
1603 // Match statements with arms that don't match the
1604 // expression pattern do not fire this diagnostic.
1607 enum Either { A, B }
1608 enum Either2 { C, D }
1613 // ^^^^^^^^^^ Internal: match check bailed out
1616 match (true, false) {
1617 (true, false, true) => (),
1618 // ^^^^^^^^^^^^^^^^^^^ Internal: match check bailed out
1621 match (true, false) { (true,) => {} }
1622 // ^^^^^^^ Internal: match check bailed out
1623 match (0) { () => () }
1624 // ^^ Internal: match check bailed out
1625 match Unresolved::Bar { Unresolved::Baz => () }
1632 fn mismatched_types_in_or_patterns() {
1636 match false { true | () => {} }
1637 // ^^^^^^^^^ Internal: match check bailed out
1638 match (false,) { (true | (),) => {} }
1639 // ^^^^^^^^^^^^ Internal: match check bailed out
1646 fn malformed_match_arm_tuple_enum_missing_pattern() {
1647 // We are testing to be sure we don't panic here when the match
1648 // arm `Either::B` is missing its pattern.
1651 enum Either { A, B(u32) }
1664 fn malformed_match_arm_extra_fields() {
1667 enum A { B(isize, isize), C }
1670 A::B(_, _, _) => (),
1671 // ^^^^^^^^^^^^^ Internal: match check bailed out
1675 // ^^^^^^^ Internal: match check bailed out
1683 fn expr_diverges() {
1686 enum Either { A, B }
1691 // ^^^^^^^^^ Internal: match check bailed out
1696 // ^^^^^^^^^ Internal: match check bailed out
1698 match loop { break Foo::A } {
1699 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1702 match loop { break Foo::A } {
1712 fn expr_partially_diverges() {
1715 enum Either<T> { A(T), B }
1717 fn foo() -> Either<!> { Either::B }
1720 Either::A(val) => val,
1732 enum Either { A { foo: bool }, B }
1735 let a = Either::A { foo: true };
1737 //^ Missing match arm
1738 match a { Either::A { foo: true } => () }
1739 //^ Missing match arm
1741 Either::A { } => (),
1742 //^^^^^^^^^ Missing structure fields:
1747 //^ Missing match arm
1748 Either::A { } => (),
1749 } //^^^^^^^^^ Missing structure fields:
1753 Either::A { foo: true } => (),
1754 Either::A { foo: false } => (),
1758 Either::A { foo: _ } => (),
1767 fn enum_record_fields_out_of_order() {
1771 A { foo: bool, bar: () },
1776 let a = Either::A { foo: true, bar: () };
1778 //^ Missing match arm
1779 Either::A { bar: (), foo: false } => (),
1780 Either::A { foo: true, bar: () } => (),
1784 Either::A { bar: (), foo: false } => (),
1785 Either::A { foo: true, bar: () } => (),
1794 fn enum_record_ellipsis() {
1798 A { foo: bool, bar: bool },
1805 //^ Missing match arm
1806 Either::A { foo: true, .. } => (),
1810 //^ Missing match arm
1811 Either::A { .. } => (),
1815 Either::A { foo: true, .. } => (),
1816 Either::A { foo: false, .. } => (),
1821 Either::A { .. } => (),
1830 fn enum_tuple_partial_ellipsis() {
1834 A(bool, bool, bool, bool),
1840 //^^^^^^^^^ Missing match arm
1841 Either::A(true, .., true) => (),
1842 Either::A(true, .., false) => (),
1843 Either::A(false, .., false) => (),
1847 //^^^^^^^^^ Missing match arm
1848 Either::A(true, .., true) => (),
1849 Either::A(true, .., false) => (),
1850 Either::A(.., true) => (),
1855 Either::A(true, .., true) => (),
1856 Either::A(true, .., false) => (),
1857 Either::A(false, .., true) => (),
1858 Either::A(false, .., false) => (),
1862 Either::A(true, .., true) => (),
1863 Either::A(true, .., false) => (),
1864 Either::A(.., true) => (),
1865 Either::A(.., false) => (),
1879 fn enum_(never: Never) {
1882 fn enum_ref(never: &Never) {
1884 //^^^^^ Missing match arm
1897 enum Option<T> { Some(T), None }
1900 // `Never` is deliberately not defined so that it's an uninferred type.
1901 match Option::<Never>::None {
1903 Some(never) => match never {},
1904 // ^^^^^^^^^^^ Internal: match check bailed out
1906 match Option::<Never>::None {
1907 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1908 Option::Some(_never) => {},
1916 fn tuple_of_bools_with_ellipsis_at_end_missing_arm() {
1920 match (false, true, false) {
1921 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1929 fn tuple_of_bools_with_ellipsis_at_beginning_missing_arm() {
1933 match (false, true, false) {
1934 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1942 fn tuple_of_bools_with_ellipsis_in_middle_missing_arm() {
1946 match (false, true, false) {
1947 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1948 (true, .., false) => (),
1955 fn record_struct() {
1957 r#"struct Foo { a: bool }
1960 //^ Missing match arm
1961 match f { Foo { a: true } => () }
1962 //^ Missing match arm
1963 match &f { Foo { a: true } => () }
1964 //^^ Missing match arm
1965 match f { Foo { a: _ } => () }
1967 Foo { a: true } => (),
1968 Foo { a: false } => (),
1971 Foo { a: true } => (),
1972 Foo { a: false } => (),
1982 r#"struct Foo(bool);
1985 //^ Missing match arm
1986 match f { Foo(true) => () }
1987 //^ Missing match arm
2003 //^ Missing match arm
2004 match f { Foo => () }
2011 fn record_struct_ellipsis() {
2013 r#"struct Foo { foo: bool, bar: bool }
2015 match f { Foo { foo: true, .. } => () }
2016 //^ Missing match arm
2018 //^ Missing match arm
2019 Foo { foo: true, .. } => (),
2020 Foo { bar: false, .. } => ()
2022 match f { Foo { .. } => () }
2024 Foo { foo: true, .. } => (),
2025 Foo { foo: false, .. } => ()
2037 enum Either { A(bool), B }
2039 //^^^^^^^^^ Missing match arm
2040 Either::A(true | false) => (),
2048 fn no_panic_at_unimplemented_subpattern_type() {
2053 match v { S{ a } => {} }
2054 match v { S{ a: _x } => {} }
2055 match v { S{ a: 'a' } => {} }
2056 //^^^^^^^^^^^ Internal: match check bailed out
2057 match v { S{..} => {} }
2060 //^ Missing match arm
2075 match true { _x @ true => {} }
2076 //^^^^ Missing match arm
2083 fn binding_ref_has_correct_type() {
2084 // Asserts `PatKind::Binding(ref _x): bool`, not &bool.
2085 // If that's not true match checking will panic with "incompatible constructors"
2086 // FIXME: make facilities to test this directly like `tests::check_infer(..)`
2091 // FIXME: this should not bail out but current behavior is such as the old algorithm.
2092 // ExprValidator::validate_match(..) checks types of top level patterns incorrecly.
2095 // ^^^^^^ Internal: match check bailed out
2108 fn enum_non_exhaustive() {
2111 //- /lib.rs crate:lib
2115 match E::A { _ => {} }
2125 //- /main.rs crate:main deps:lib
2128 match E::A { _ => {} }
2130 //^^^^ Missing match arm
2135 //^^^^ Missing match arm
2154 //^^^^ Missing match arm
2164 fn pattern_type_is_of_substitution() {
2165 cov_mark::check!(match_check_wildcard_expanded_to_substitutions);
2180 fn record_struct_no_such_field() {
2185 match f { Foo { bar } => () }
2186 // ^^^^^^^^^^^ Internal: match check bailed out
2193 fn match_ergonomics_issue_9095() {
2196 enum Foo<T> { A(T) }
2198 match &Foo::A(true) {
2207 mod false_negatives {
2208 //! The implementation of match checking here is a work in progress. As we roll this out, we
2209 //! prefer false negatives to false positives (ideally there would be no false positives). This
2210 //! test module should document known false negatives. Eventually we will have a complete
2211 //! implementation of match checking and this module will be empty.
2213 //! The reasons for documenting known false negatives:
2215 //! 1. It acts as a backlog of work that can be done to improve the behavior of the system.
2216 //! 2. It ensures the code doesn't panic when handling these cases.
2221 // We don't currently check integer exhaustiveness.
2227 // ^^ Internal: match check bailed out
2236 fn reference_patterns_at_top_level() {
2242 // ^^^^^ Internal: match check bailed out
2250 fn reference_patterns_in_fields() {
2256 // ^^^^^^^ Internal: match check bailed out
2260 // ^^^^^^^^ Internal: match check bailed out
2270 mod decl_check_tests {
2271 use crate::diagnostics::tests::check_diagnostics;
2274 fn incorrect_function_name() {
2277 fn NonSnakeCaseName() {}
2278 // ^^^^^^^^^^^^^^^^ Function `NonSnakeCaseName` should have snake_case name, e.g. `non_snake_case_name`
2284 fn incorrect_function_params() {
2287 fn foo(SomeParam: u8) {}
2288 // ^^^^^^^^^ Parameter `SomeParam` should have snake_case name, e.g. `some_param`
2290 fn foo2(ok_param: &str, CAPS_PARAM: u8) {}
2291 // ^^^^^^^^^^ Parameter `CAPS_PARAM` should have snake_case name, e.g. `caps_param`
2297 fn incorrect_variable_names() {
2301 let SOME_VALUE = 10;
2302 // ^^^^^^^^^^ Variable `SOME_VALUE` should have snake_case name, e.g. `some_value`
2303 let AnotherValue = 20;
2304 // ^^^^^^^^^^^^ Variable `AnotherValue` should have snake_case name, e.g. `another_value`
2311 fn incorrect_struct_names() {
2314 struct non_camel_case_name {}
2315 // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName`
2317 struct SCREAMING_CASE {}
2318 // ^^^^^^^^^^^^^^ Structure `SCREAMING_CASE` should have CamelCase name, e.g. `ScreamingCase`
2324 fn no_diagnostic_for_camel_cased_acronyms_in_struct_name() {
2333 fn incorrect_struct_field() {
2336 struct SomeStruct { SomeField: u8 }
2337 // ^^^^^^^^^ Field `SomeField` should have snake_case name, e.g. `some_field`
2343 fn incorrect_enum_names() {
2346 enum some_enum { Val(u8) }
2347 // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum`
2350 // ^^^^^^^^^ Enum `SOME_ENUM` should have CamelCase name, e.g. `SomeEnum`
2356 fn no_diagnostic_for_camel_cased_acronyms_in_enum_name() {
2365 fn incorrect_enum_variant_name() {
2368 enum SomeEnum { SOME_VARIANT(u8) }
2369 // ^^^^^^^^^^^^ Variant `SOME_VARIANT` should have CamelCase name, e.g. `SomeVariant`
2375 fn incorrect_const_name() {
2378 const some_weird_const: u8 = 10;
2379 // ^^^^^^^^^^^^^^^^ Constant `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2385 fn incorrect_static_name() {
2388 static some_weird_const: u8 = 10;
2389 // ^^^^^^^^^^^^^^^^ Static variable `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2395 fn fn_inside_impl_struct() {
2399 // ^^^^^^^^^^ Structure `someStruct` should have CamelCase name, e.g. `SomeStruct`
2402 fn SomeFunc(&self) {
2403 // ^^^^^^^^ Function `SomeFunc` should have snake_case name, e.g. `some_func`
2404 let WHY_VAR_IS_CAPS = 10;
2405 // ^^^^^^^^^^^^^^^ Variable `WHY_VAR_IS_CAPS` should have snake_case name, e.g. `why_var_is_caps`
2413 fn no_diagnostic_for_enum_varinats() {
2416 enum Option { Some, None }
2419 match Option::None {
2432 enum Option { Some, None }
2435 match Option::None {
2436 SOME_VAR @ None => (),
2437 // ^^^^^^^^ Variable `SOME_VAR` should have snake_case name, e.g. `some_var`
2446 fn allow_attributes() {
2449 #[allow(non_snake_case)]
2450 fn NonSnakeCaseName(SOME_VAR: u8) -> u8{
2451 // cov_flags generated output from elsewhere in this file
2454 static lower_case: u8;
2457 let OtherVar = SOME_VAR + 1;
2461 #[allow(nonstandard_style)]
2462 mod CheckNonstandardStyle {
2463 fn HiImABadFnName() {}
2468 fn HiImABadFnName() {}
2472 #![allow(non_snake_case)]
2473 fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {}
2476 #[allow(non_snake_case, non_camel_case_types)]
2477 pub struct some_type {
2482 #[allow(non_upper_case_globals)]
2483 pub const some_const: u8 = 10;
2485 #[allow(non_upper_case_globals)]
2486 pub static SomeStatic: u8 = 10;
2492 fn allow_attributes_crate_attr() {
2495 #![allow(non_snake_case)]
2498 fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {}
2506 fn bug_trait_inside_fn() {
2508 // This is broken, and in fact, should not even be looked at by this
2509 // lint in the first place. There's weird stuff going on in the
2510 // collection phase.
2511 // It's currently being brought in by:
2512 // * validate_func on `a` recursing into modules
2513 // * then it finds the trait and then the function while iterating
2515 // * then validate_func is called on Dirty
2516 // * ... which then proceeds to look at some unknown module taking no
2517 // attrs from either the impl or the fn a, and then finally to the root
2520 // It should find the attribute on the trait, but it *doesn't even see
2521 // the trait* as far as I can tell.
2529 // this comes out of bitflags, mostly
2530 #[allow(non_snake_case)]
2532 const HiImAlsoBad: u8 = 2;
2534 fn Dirty(&self) -> bool {
2547 fn bug_traits_arent_checked() {
2548 // FIXME: Traits and functions in traits aren't currently checked by
2549 // r-a, even though rustc will complain about them.
2553 // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait`
2555 // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function`
2557 // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function`
2564 fn ignores_extern_items() {
2565 cov_mark::check!(extern_func_incorrect_case_ignored);
2566 cov_mark::check!(extern_static_incorrect_case_ignored);
2570 fn NonSnakeCaseName(SOME_VAR: u8) -> u8;
2571 pub static SomeStatic: u8 = 10;
2578 fn infinite_loop_inner_items() {
2590 #[test] // Issue #8809.
2591 fn parenthesized_parameter() {
2592 check_diagnostics(r#"fn f((O): _) {}"#)