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.
13 use std::cell::RefCell;
17 diagnostics::{AnyDiagnostic, Diagnostic as _, DiagnosticCode, DiagnosticSinkBuilder},
20 use ide_assists::AssistResolveStrategy;
21 use ide_db::{base_db::SourceDatabase, RootDatabase};
22 use itertools::Itertools;
23 use rustc_hash::FxHashSet;
26 SyntaxNode, SyntaxNodePtr, TextRange, TextSize,
28 use text_edit::TextEdit;
29 use unlinked_file::UnlinkedFile;
31 use crate::{Assist, AssistId, AssistKind, FileId, Label, SourceChange};
33 use self::fixes::DiagnosticWithFixes;
36 pub struct Diagnostic {
37 // pub name: Option<String>,
40 pub severity: Severity,
41 pub fixes: Option<Vec<Assist>>,
43 pub code: Option<DiagnosticCode>,
47 fn new(code: &'static str, message: impl Into<String>, range: TextRange) -> Diagnostic {
48 let message = message.into();
49 let code = Some(DiagnosticCode(code));
50 Self { message, range, severity: Severity::Error, fixes: None, unused: false, code }
53 fn error(range: TextRange, message: String) -> Self {
54 Self { message, range, severity: Severity::Error, fixes: None, unused: false, code: None }
57 fn hint(range: TextRange, message: String) -> Self {
61 severity: Severity::WeakWarning,
68 fn with_fixes(self, fixes: Option<Vec<Assist>>) -> Self {
69 Self { fixes, ..self }
72 fn with_unused(self, unused: bool) -> Self {
73 Self { unused, ..self }
76 fn with_code(self, code: Option<DiagnosticCode>) -> Self {
81 #[derive(Debug, Copy, Clone)]
87 #[derive(Default, Debug, Clone)]
88 pub struct DiagnosticsConfig {
89 pub disable_experimental: bool,
90 pub disabled: FxHashSet<String>,
93 struct DiagnosticsContext<'a> {
94 config: &'a DiagnosticsConfig,
95 sema: Semantics<'a, RootDatabase>,
97 resolve: &'a AssistResolveStrategy,
100 pub(crate) fn diagnostics(
102 config: &DiagnosticsConfig,
103 resolve: &AssistResolveStrategy,
105 ) -> Vec<Diagnostic> {
106 let _p = profile::span("diagnostics");
107 let sema = Semantics::new(db);
108 let parse = db.parse(file_id);
109 let mut res = Vec::new();
111 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
117 .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
120 for node in parse.tree().syntax().descendants() {
121 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
122 field_shorthand::check(&mut res, file_id, &node);
124 let res = RefCell::new(res);
125 let sink_builder = DiagnosticSinkBuilder::new()
126 .on::<hir::diagnostics::MissingFields, _>(|d| {
127 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
129 .on::<hir::diagnostics::MissingOkOrSomeInTailExpr, _>(|d| {
130 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
132 .on::<hir::diagnostics::NoSuchField, _>(|d| {
133 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
135 .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| {
136 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
138 .on::<hir::diagnostics::IncorrectCase, _>(|d| {
139 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
141 .on::<hir::diagnostics::ReplaceFilterMapNextWithFindMap, _>(|d| {
142 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
144 .on::<hir::diagnostics::InactiveCode, _>(|d| {
145 // If there's inactive code somewhere in a macro, don't propagate to the call-site.
146 if d.display_source().file_id.expansion_info(db).is_some() {
150 // Override severity and mark as unused.
151 res.borrow_mut().push(
153 sema.diagnostics_display_range(d.display_source()).range,
157 .with_code(Some(d.code())),
160 .on::<UnlinkedFile, _>(|d| {
161 // Limit diagnostic to the first few characters in the file. This matches how VS Code
162 // renders it with the full span, but on other editors, and is less invasive.
163 let range = sema.diagnostics_display_range(d.display_source()).range;
164 let range = range.intersect(TextRange::up_to(TextSize::of("..."))).unwrap_or(range);
166 // Override severity and mark as unused.
167 res.borrow_mut().push(
168 Diagnostic::hint(range, d.message())
169 .with_fixes(d.fixes(&sema, resolve))
170 .with_code(Some(d.code())),
173 .on::<hir::diagnostics::UnresolvedProcMacro, _>(|d| {
174 // Use more accurate position if available.
175 let display_range = d
177 .unwrap_or_else(|| sema.diagnostics_display_range(d.display_source()).range);
179 // FIXME: it would be nice to tell the user whether proc macros are currently disabled
181 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
183 .on::<hir::diagnostics::UnresolvedMacroCall, _>(|d| {
184 let last_path_segment = sema.db.parse_or_expand(d.file).and_then(|root| {
188 .and_then(|it| it.segment())
189 .and_then(|it| it.name_ref())
190 .map(|it| InFile::new(d.file, SyntaxNodePtr::new(it.syntax())))
192 let diagnostics = last_path_segment.unwrap_or_else(|| d.display_source());
193 let display_range = sema.diagnostics_display_range(diagnostics).range;
195 .push(Diagnostic::error(display_range, d.message()).with_code(Some(d.code())));
197 .on::<hir::diagnostics::UnimplementedBuiltinMacro, _>(|d| {
198 let display_range = sema.diagnostics_display_range(d.display_source()).range;
200 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
202 // Only collect experimental diagnostics when they're enabled.
203 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
204 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
206 // Finalize the `DiagnosticSink` building process.
207 let mut sink = sink_builder
208 // Diagnostics not handled above get no fix and default treatment.
210 res.borrow_mut().push(
212 sema.diagnostics_display_range(d.display_source()).range,
215 .with_code(Some(d.code())),
219 let mut diags = Vec::new();
220 let internal_diagnostics = cfg!(test);
221 match sema.to_module_def(file_id) {
222 Some(m) => diags = m.diagnostics(db, &mut sink, internal_diagnostics),
224 sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(parse.tree().syntax()) });
230 let mut res = res.into_inner();
232 let ctx = DiagnosticsContext { config, sema, resolve };
235 AnyDiagnostic::UnresolvedModule(d) => unresolved_module::render(&ctx, &d),
237 if let Some(code) = d.code {
238 if ctx.config.disabled.contains(code.as_str()) {
248 fn diagnostic_with_fix<D: DiagnosticWithFixes>(
250 sema: &Semantics<RootDatabase>,
251 resolve: &AssistResolveStrategy,
253 Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message())
254 .with_fixes(d.fixes(sema, resolve))
255 .with_code(Some(d.code()))
258 fn warning_with_fix<D: DiagnosticWithFixes>(
260 sema: &Semantics<RootDatabase>,
261 resolve: &AssistResolveStrategy,
263 Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message())
264 .with_fixes(d.fixes(sema, resolve))
265 .with_code(Some(d.code()))
268 fn check_unnecessary_braces_in_use_statement(
269 acc: &mut Vec<Diagnostic>,
273 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
274 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
275 // If there is a comment inside the bracketed `use`,
276 // assume it is a commented out module path and don't show diagnostic.
277 if use_tree_list.has_inner_comment() {
281 let use_range = use_tree_list.syntax().text_range();
283 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
285 let to_replace = single_use_tree.syntax().text().to_string();
286 let mut edit_builder = TextEdit::builder();
287 edit_builder.delete(use_range);
288 edit_builder.insert(use_range.start(), to_replace);
289 edit_builder.finish()
293 Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
294 .with_fixes(Some(vec![fix(
296 "Remove unnecessary braces",
297 SourceChange::from_text_edit(file_id, edit),
306 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
307 single_use_tree: &ast::UseTree,
308 ) -> Option<TextEdit> {
309 let use_tree_list_node = single_use_tree.syntax().parent()?;
310 if single_use_tree.path()?.segment()?.self_token().is_some() {
311 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
312 let end = use_tree_list_node.text_range().end();
313 return Some(TextEdit::delete(TextRange::new(start, end)));
318 fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
319 let mut res = unresolved_fix(id, label, target);
320 res.source_change = Some(source_change);
324 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
325 assert!(!id.contains(' '));
327 id: AssistId(id, AssistKind::QuickFix),
328 label: Label::new(label),
337 use expect_test::Expect;
338 use hir::diagnostics::DiagnosticCode;
339 use ide_assists::AssistResolveStrategy;
340 use stdx::trim_indent;
341 use test_utils::{assert_eq_text, extract_annotations};
343 use crate::{fixture, DiagnosticsConfig};
345 /// Takes a multi-file input fixture with annotated cursor positions,
347 /// * a diagnostic is produced
348 /// * the first diagnostic fix trigger range touches the input cursor position
349 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
351 pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
352 check_nth_fix(0, ra_fixture_before, ra_fixture_after);
354 /// Takes a multi-file input fixture with annotated cursor positions,
356 /// * a diagnostic is produced
357 /// * every diagnostic fixes trigger range touches the input cursor position
358 /// * that the contents of the file containing the cursor match `after` after each diagnostic fix is applied
359 pub(crate) fn check_fixes(ra_fixture_before: &str, ra_fixtures_after: Vec<&str>) {
360 for (i, ra_fixture_after) in ra_fixtures_after.iter().enumerate() {
361 check_nth_fix(i, ra_fixture_before, ra_fixture_after)
366 fn check_nth_fix(nth: usize, ra_fixture_before: &str, ra_fixture_after: &str) {
367 let after = trim_indent(ra_fixture_after);
369 let (analysis, file_position) = fixture::position(ra_fixture_before);
370 let diagnostic = analysis
372 &DiagnosticsConfig::default(),
373 AssistResolveStrategy::All,
374 file_position.file_id,
379 let fix = &diagnostic.fixes.unwrap()[nth];
381 let source_change = fix.source_change.as_ref().unwrap();
382 let file_id = *source_change.source_file_edits.keys().next().unwrap();
383 let mut actual = analysis.file_text(file_id).unwrap().to_string();
385 for edit in source_change.source_file_edits.values() {
386 edit.apply(&mut actual);
391 assert_eq_text!(&after, &actual);
393 fix.target.contains_inclusive(file_position.offset),
394 "diagnostic fix range {:?} does not touch cursor position {:?}",
399 /// Checks that there's a diagnostic *without* fix at `$0`.
400 fn check_no_fix(ra_fixture: &str) {
401 let (analysis, file_position) = fixture::position(ra_fixture);
402 let diagnostic = analysis
404 &DiagnosticsConfig::default(),
405 AssistResolveStrategy::All,
406 file_position.file_id,
411 assert!(diagnostic.fixes.is_none(), "got a fix when none was expected: {:?}", diagnostic);
414 /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
415 /// apply to the file containing the cursor.
416 pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
417 let (analysis, files) = fixture::files(ra_fixture);
418 let diagnostics = files
420 .flat_map(|file_id| {
422 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
425 .collect::<Vec<_>>();
426 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
429 pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) {
430 let (analysis, file_id) = fixture::file(ra_fixture);
431 let diagnostics = analysis
432 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
434 expect.assert_debug_eq(&diagnostics)
437 pub(crate) fn check_diagnostics(ra_fixture: &str) {
438 let (analysis, file_id) = fixture::file(ra_fixture);
439 let diagnostics = analysis
440 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
443 let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
444 let mut actual = diagnostics
446 .filter(|d| d.code != Some(DiagnosticCode("inactive-code")))
447 .map(|d| (d.range, d.message))
448 .collect::<Vec<_>>();
449 actual.sort_by_key(|(range, _)| range.start());
450 assert_eq!(expected, actual);
454 fn test_unresolved_macro_range() {
458 //^^^ unresolved macro `foo::bar!`
464 fn unresolved_import_in_use_tree() {
465 // Only the relevant part of a nested `use` item should be highlighted.
468 use does_exist::{Exists, DoesntExist};
469 //^^^^^^^^^^^ unresolved import
471 use {does_not_exist::*, does_exist};
472 //^^^^^^^^^^^^^^^^^ unresolved import
474 use does_not_exist::{
476 //^ unresolved import
478 //^ unresolved import
480 //^ unresolved import
491 fn range_mapping_out_of_macros() {
492 // FIXME: this is very wrong, but somewhat tricky to fix.
499 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
502 let _x = id![Foo { a: $042 }];
505 pub struct Foo { pub a: i32, pub b: i32 }
512 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
515 let _x = id![Foo { a: 42 }];
518 pub struct Foo { pub a: i32, pub b: i32 }
524 fn test_check_unnecessary_braces_in_use_statement() {
525 check_no_diagnostics(
538 check_no_diagnostics(
596 mod a { mod c {} mod d { mod e {} } }
597 use a::{c, d::{e$0}};
600 mod a { mod c {} mod d { mod e {} } }
607 fn test_disabled_diagnostics() {
608 let mut config = DiagnosticsConfig::default();
609 config.disabled.insert("unresolved-module".into());
611 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
614 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
615 assert!(diagnostics.is_empty());
617 let diagnostics = analysis
618 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
620 assert!(!diagnostics.is_empty());
624 fn unlinked_file_prepend_first_item() {
625 cov_mark::check!(unlinked_file_prepend_before_first_item);
626 // Only tests the first one for `pub mod` since the rest are the same
650 fn unlinked_file_append_mod() {
651 cov_mark::check!(unlinked_file_append_to_existing_mods);
663 mod preexisting_bottom;)
677 mod preexisting_bottom;)
683 fn unlinked_file_insert_in_empty_file() {
684 cov_mark::check!(unlinked_file_empty_file);
698 fn unlinked_file_old_style_modrs() {
716 fn unlinked_file_new_style_mod() {
732 fn unlinked_file_with_cfg_off() {
733 cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
747 fn unlinked_file_with_cfg_on() {
748 check_no_diagnostics(
760 fn break_outside_of_loop() {
764 //^^^^^ break outside of loop
770 fn no_such_field_diagnostics() {
773 struct S { foo: i32, bar: () }
777 //^ Missing structure fields:
781 //^^^^^^^ no such field
789 fn no_such_field_with_feature_flag_diagnostics() {
792 //- /lib.rs crate:foo cfg:feature=foo
795 #[cfg(feature = "foo")]
800 #[cfg(feature = "foo")]
801 pub(crate) fn new(my_val: usize, bar: bool) -> Self {
804 #[cfg(not(feature = "foo"))]
805 pub(crate) fn new(my_val: usize, _bar: bool) -> Self {
814 fn no_such_field_enum_with_feature_flag_diagnostics() {
817 //- /lib.rs crate:foo cfg:feature=foo
819 #[cfg(not(feature = "foo"))]
821 #[cfg(feature = "foo")]
837 fn no_such_field_with_feature_flag_diagnostics_on_struct_lit() {
840 //- /lib.rs crate:foo cfg:feature=foo
842 #[cfg(feature = "foo")]
844 #[cfg(not(feature = "foo"))]
849 #[cfg(feature = "foo")]
850 fn new(foo: u32) -> Self {
853 #[cfg(not(feature = "foo"))]
854 fn new(bar: u32) -> Self {
857 fn new2(bar: u32) -> Self {
858 #[cfg(feature = "foo")]
859 { Self { foo: bar } }
860 #[cfg(not(feature = "foo"))]
863 fn new2(val: u32) -> Self {
865 #[cfg(feature = "foo")]
867 #[cfg(not(feature = "foo"))]
877 fn no_such_field_with_type_macro() {
880 macro_rules! Type { () => { u32 }; }
881 struct Foo { bar: Type![] }
893 fn missing_unsafe_diagnostic_with_raw_ptr() {
897 let x = &5 as *const usize;
898 unsafe { let y = *x; }
900 } //^^ This operation is unsafe and requires an unsafe function or block
906 fn missing_unsafe_diagnostic_with_unsafe_call() {
912 unsafe fn unsafe_fn(&self) {
913 let x = &5 as *const usize;
918 unsafe fn unsafe_fn() {
919 let x = &5 as *const usize;
925 //^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
926 HasUnsafe.unsafe_fn();
927 //^^^^^^^^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
930 HasUnsafe.unsafe_fn();
938 fn missing_unsafe_diagnostic_with_static_mut() {
945 static mut STATIC_MUT: Ty = Ty { a: 0 };
948 let x = STATIC_MUT.a;
949 //^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
951 let x = STATIC_MUT.a;
959 fn no_missing_unsafe_diagnostic_with_safe_intrinsic() {
962 extern "rust-intrinsic" {
963 pub fn bitreverse(x: u32) -> u32; // Safe intrinsic
964 pub fn floorf32(x: f32) -> f32; // Unsafe intrinsic
968 let _ = bitreverse(12);
969 let _ = floorf32(12.0);
970 //^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
976 // Register the required standard library types to make the tests work
977 fn add_filter_map_with_find_next_boilerplate(body: &str) -> String {
979 //- /main.rs crate:main deps:core
980 use core::iter::Iterator;
981 use core::option::Option::{self, Some, None};
984 //- /core/lib.rs crate:core
986 pub enum Option<T> { Some(T), None }
991 fn filter_map<B, F>(self, f: F) -> FilterMap where F: FnMut(Self::Item) -> Option<B> { FilterMap }
992 fn next(&mut self) -> Option<Self::Item>;
994 pub struct FilterMap {}
995 impl Iterator for FilterMap {
997 fn next(&mut self) -> i32 { 7 }
1001 format!("{}{}{}", prefix, body, suffix)
1005 fn replace_filter_map_next_with_find_map2() {
1006 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1009 let m = [1, 2, 3].iter().filter_map(|x| if *x == 2 { Some (4) } else { None }).next();
1010 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ replace filter_map(..).next() with find_map(..)
1017 fn replace_filter_map_next_with_find_map_no_diagnostic_without_next() {
1018 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1023 .filter_map(|x| if *x == 2 { Some (4) } else { None })
1031 fn replace_filter_map_next_with_find_map_no_diagnostic_with_intervening_methods() {
1032 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1037 .filter_map(|x| if *x == 2 { Some (4) } else { None })
1046 fn replace_filter_map_next_with_find_map_no_diagnostic_if_not_in_chain() {
1047 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1052 .filter_map(|x| if *x == 2 { Some (4) } else { None });
1060 fn missing_record_pat_field_diagnostic() {
1063 struct S { foo: i32, bar: () }
1065 let S { foo: _ } = s;
1066 //^ Missing structure fields:
1074 fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
1077 struct S { foo: i32, bar: () }
1078 fn baz(s: S) -> i32 {
1080 S { foo, .. } => foo,
1088 fn missing_record_pat_field_box() {
1091 struct S { s: Box<u32> }
1093 let S { box s } = a;
1100 fn missing_record_pat_field_ref() {
1105 let S { ref s } = a;
1112 fn simple_free_fn_zero() {
1117 //^^^^^^^ Expected 0 arguments, found 1
1130 fn simple_free_fn_one() {
1135 //^^^^^ Expected 1 argument, found 0
1152 impl S { fn method(&self) {} }
1156 } //^^^^^^^^^^^ Expected 1 argument, found 0
1163 impl S { fn method(&self) {} }
1174 fn method_with_arg() {
1178 impl S { fn method(&self, arg: u8) {} }
1182 } //^^^^^^^^^^ Expected 1 argument, found 0
1189 impl S { fn method(&self, arg: u8) {} }
1200 fn method_unknown_receiver() {
1201 // note: this is incorrect code, so there might be errors on this in the
1202 // future, but we shouldn't emit an argument count diagnostic here
1205 trait Foo { fn method(&self, arg: usize) {} }
1219 struct Tup(u8, u16);
1222 } //^^^^^^ Expected 2 arguments, found 1
1231 enum En { Variant(u8, u16), }
1234 } //^^^^^^^^^^^^^^ Expected 2 arguments, found 1
1240 fn enum_variant_type_macro() {
1253 //^^^^^^^^^^^^^^ Expected 1 argument, found 2
1255 //^^^^^^^^^^ Expected 1 argument, found 0
1267 fn fixed(fixed: u8);
1268 fn varargs(fixed: u8, ...);
1276 //^^^^^^^^^^^ Expected 1 argument, found 2
1289 fn arg_count_lambda() {
1295 //^^^ Expected 1 argument, found 0
1298 //^^^^^^^^^ Expected 1 argument, found 2
1305 fn cfgd_out_call_arguments() {
1308 struct C(#[cfg(FALSE)] ());
1321 C::new().method(#[cfg(FALSE)] 0);
1328 fn cfgd_out_fn_params() {
1331 fn foo(#[cfg(NEVER)] x: ()) {}
1336 fn method(#[cfg(NEVER)] self) {}
1337 fn method2(#[cfg(NEVER)] self, arg: u8) {}
1338 fn method3(self, #[cfg(NEVER)] arg: u8) {}
1342 fn fixed(fixed: u8, #[cfg(NEVER)] ...);
1343 fn varargs(#[cfg(not(NEVER))] ...);
1362 fn missing_semicolon() {
1365 fn test() -> i32 { 123; }
1366 //^^^ Remove this semicolon
1372 fn import_extern_crate_clash_with_inner_item() {
1373 // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
1377 //- /lib.rs crate:lib deps:jwt
1380 use permissions::jwt;
1384 jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
1389 pub struct Claims {}
1392 //- /jwt/lib.rs crate:jwt
1402 pub(super) mod match_check_tests {
1403 use crate::diagnostics::tests::check_diagnostics;
1411 //^^ Missing match arm
1413 //^^^^ Missing match arm
1415 match () { _ => (), }
1416 match () { () => (), }
1417 match (()) { (()) => (), }
1424 fn tuple_of_two_empty_tuple() {
1429 //^^^^^^^^ Missing match arm
1431 match ((), ()) { ((), ()) => (), }
1443 //^^^^^ Missing match arm
1444 match false { true => (), }
1445 //^^^^^ Missing match arm
1446 match (false, true) {}
1447 //^^^^^^^^^^^^^ Missing match arm
1448 match (false, true) { (true, true) => (), }
1449 //^^^^^^^^^^^^^ Missing match arm
1450 match (false, true) {
1451 //^^^^^^^^^^^^^ Missing match arm
1452 (false, true) => (),
1453 (false, false) => (),
1454 (true, false) => (),
1456 match (false, true) { (true, _x) => (), }
1457 //^^^^^^^^^^^^^ Missing match arm
1459 match false { true => (), false => (), }
1460 match (false, true) {
1462 (true, false) => (),
1465 match (false, true) {
1467 (true, false) => (),
1468 (false, true) => (),
1469 (false, false) => (),
1471 match (false, true) {
1473 (false, true) => (),
1474 (false, false) => (),
1476 match (false, true, false) {
1480 match (false, true, false) {
1484 match (false, true, false) { (..) => (), }
1491 fn tuple_of_tuple_and_bools() {
1495 match (false, ((), false)) {}
1496 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1497 match (false, ((), false)) { (true, ((), true)) => (), }
1498 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1499 match (false, ((), false)) { (true, _) => (), }
1500 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1502 match (false, ((), false)) {
1503 (true, ((), true)) => (),
1504 (true, ((), false)) => (),
1505 (false, ((), true)) => (),
1506 (false, ((), false)) => (),
1508 match (false, ((), false)) {
1509 (true, ((), true)) => (),
1510 (true, ((), false)) => (),
1522 enum Either { A, B, }
1526 //^^^^^^^^^ Missing match arm
1527 match Either::B { Either::A => (), }
1528 //^^^^^^^^^ Missing match arm
1531 //^^^^^^^^^^ Missing match arm
1536 Either::A => (), Either::B => (),
1539 Either::A => (), Either::B => (),
1547 fn enum_containing_bool() {
1550 enum Either { A(bool), B }
1554 //^^^^^^^^^ Missing match arm
1556 //^^^^^^^^^ Missing match arm
1557 Either::A(true) => (), Either::B => ()
1561 Either::A(true) => (),
1562 Either::A(false) => (),
1580 fn enum_different_sizes() {
1583 enum Either { A(bool), B(bool, bool) }
1586 match Either::A(false) {
1587 //^^^^^^^^^^^^^^^^ Missing match arm
1589 Either::B(false, _) => (),
1592 match Either::A(false) {
1594 Either::B(true, _) => (),
1595 Either::B(false, _) => (),
1597 match Either::A(false) {
1598 Either::A(true) | Either::A(false) => (),
1599 Either::B(true, _) => (),
1600 Either::B(false, _) => (),
1608 fn tuple_of_enum_no_diagnostic() {
1611 enum Either { A(bool), B(bool, bool) }
1612 enum Either2 { C, D }
1615 match (Either::A(false), Either2::C) {
1616 (Either::A(true), _) | (Either::A(false), _) => (),
1617 (Either::B(true, _), Either2::C) => (),
1618 (Either::B(false, _), Either2::C) => (),
1619 (Either::B(_, _), Either2::D) => (),
1627 fn or_pattern_no_diagnostic() {
1633 match (Either::A, Either::B) {
1634 (Either::A | Either::B, _) => (),
1641 fn mismatched_types() {
1642 // Match statements with arms that don't match the
1643 // expression pattern do not fire this diagnostic.
1646 enum Either { A, B }
1647 enum Either2 { C, D }
1652 // ^^^^^^^^^^ Internal: match check bailed out
1655 match (true, false) {
1656 (true, false, true) => (),
1657 // ^^^^^^^^^^^^^^^^^^^ Internal: match check bailed out
1660 match (true, false) { (true,) => {} }
1661 // ^^^^^^^ Internal: match check bailed out
1662 match (0) { () => () }
1663 // ^^ Internal: match check bailed out
1664 match Unresolved::Bar { Unresolved::Baz => () }
1671 fn mismatched_types_in_or_patterns() {
1675 match false { true | () => {} }
1676 // ^^^^^^^^^ Internal: match check bailed out
1677 match (false,) { (true | (),) => {} }
1678 // ^^^^^^^^^^^^ Internal: match check bailed out
1685 fn malformed_match_arm_tuple_enum_missing_pattern() {
1686 // We are testing to be sure we don't panic here when the match
1687 // arm `Either::B` is missing its pattern.
1690 enum Either { A, B(u32) }
1703 fn malformed_match_arm_extra_fields() {
1706 enum A { B(isize, isize), C }
1709 A::B(_, _, _) => (),
1710 // ^^^^^^^^^^^^^ Internal: match check bailed out
1714 // ^^^^^^^ Internal: match check bailed out
1722 fn expr_diverges() {
1725 enum Either { A, B }
1730 // ^^^^^^^^^ Internal: match check bailed out
1735 // ^^^^^^^^^ Internal: match check bailed out
1737 match loop { break Foo::A } {
1738 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1741 match loop { break Foo::A } {
1751 fn expr_partially_diverges() {
1754 enum Either<T> { A(T), B }
1756 fn foo() -> Either<!> { Either::B }
1759 Either::A(val) => val,
1771 enum Either { A { foo: bool }, B }
1774 let a = Either::A { foo: true };
1776 //^ Missing match arm
1777 match a { Either::A { foo: true } => () }
1778 //^ Missing match arm
1780 Either::A { } => (),
1781 //^^^^^^^^^ Missing structure fields:
1786 //^ Missing match arm
1787 Either::A { } => (),
1788 } //^^^^^^^^^ Missing structure fields:
1792 Either::A { foo: true } => (),
1793 Either::A { foo: false } => (),
1797 Either::A { foo: _ } => (),
1806 fn enum_record_fields_out_of_order() {
1810 A { foo: bool, bar: () },
1815 let a = Either::A { foo: true, bar: () };
1817 //^ Missing match arm
1818 Either::A { bar: (), foo: false } => (),
1819 Either::A { foo: true, bar: () } => (),
1823 Either::A { bar: (), foo: false } => (),
1824 Either::A { foo: true, bar: () } => (),
1833 fn enum_record_ellipsis() {
1837 A { foo: bool, bar: bool },
1844 //^ Missing match arm
1845 Either::A { foo: true, .. } => (),
1849 //^ Missing match arm
1850 Either::A { .. } => (),
1854 Either::A { foo: true, .. } => (),
1855 Either::A { foo: false, .. } => (),
1860 Either::A { .. } => (),
1869 fn enum_tuple_partial_ellipsis() {
1873 A(bool, bool, bool, bool),
1879 //^^^^^^^^^ Missing match arm
1880 Either::A(true, .., true) => (),
1881 Either::A(true, .., false) => (),
1882 Either::A(false, .., false) => (),
1886 //^^^^^^^^^ Missing match arm
1887 Either::A(true, .., true) => (),
1888 Either::A(true, .., false) => (),
1889 Either::A(.., true) => (),
1894 Either::A(true, .., true) => (),
1895 Either::A(true, .., false) => (),
1896 Either::A(false, .., true) => (),
1897 Either::A(false, .., false) => (),
1901 Either::A(true, .., true) => (),
1902 Either::A(true, .., false) => (),
1903 Either::A(.., true) => (),
1904 Either::A(.., false) => (),
1918 fn enum_(never: Never) {
1921 fn enum_ref(never: &Never) {
1923 //^^^^^ Missing match arm
1936 enum Option<T> { Some(T), None }
1939 // `Never` is deliberately not defined so that it's an uninferred type.
1940 match Option::<Never>::None {
1942 Some(never) => match never {},
1943 // ^^^^^^^^^^^ Internal: match check bailed out
1945 match Option::<Never>::None {
1946 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1947 Option::Some(_never) => {},
1955 fn tuple_of_bools_with_ellipsis_at_end_missing_arm() {
1959 match (false, true, false) {
1960 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1968 fn tuple_of_bools_with_ellipsis_at_beginning_missing_arm() {
1972 match (false, true, false) {
1973 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1981 fn tuple_of_bools_with_ellipsis_in_middle_missing_arm() {
1985 match (false, true, false) {
1986 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1987 (true, .., false) => (),
1994 fn record_struct() {
1996 r#"struct Foo { a: bool }
1999 //^ Missing match arm
2000 match f { Foo { a: true } => () }
2001 //^ Missing match arm
2002 match &f { Foo { a: true } => () }
2003 //^^ Missing match arm
2004 match f { Foo { a: _ } => () }
2006 Foo { a: true } => (),
2007 Foo { a: false } => (),
2010 Foo { a: true } => (),
2011 Foo { a: false } => (),
2021 r#"struct Foo(bool);
2024 //^ Missing match arm
2025 match f { Foo(true) => () }
2026 //^ Missing match arm
2042 //^ Missing match arm
2043 match f { Foo => () }
2050 fn record_struct_ellipsis() {
2052 r#"struct Foo { foo: bool, bar: bool }
2054 match f { Foo { foo: true, .. } => () }
2055 //^ Missing match arm
2057 //^ Missing match arm
2058 Foo { foo: true, .. } => (),
2059 Foo { bar: false, .. } => ()
2061 match f { Foo { .. } => () }
2063 Foo { foo: true, .. } => (),
2064 Foo { foo: false, .. } => ()
2076 enum Either { A(bool), B }
2078 //^^^^^^^^^ Missing match arm
2079 Either::A(true | false) => (),
2087 fn no_panic_at_unimplemented_subpattern_type() {
2092 match v { S{ a } => {} }
2093 match v { S{ a: _x } => {} }
2094 match v { S{ a: 'a' } => {} }
2095 //^^^^^^^^^^^ Internal: match check bailed out
2096 match v { S{..} => {} }
2099 //^ Missing match arm
2114 match true { _x @ true => {} }
2115 //^^^^ Missing match arm
2122 fn binding_ref_has_correct_type() {
2123 // Asserts `PatKind::Binding(ref _x): bool`, not &bool.
2124 // If that's not true match checking will panic with "incompatible constructors"
2125 // FIXME: make facilities to test this directly like `tests::check_infer(..)`
2130 // FIXME: this should not bail out but current behavior is such as the old algorithm.
2131 // ExprValidator::validate_match(..) checks types of top level patterns incorrecly.
2134 // ^^^^^^ Internal: match check bailed out
2147 fn enum_non_exhaustive() {
2150 //- /lib.rs crate:lib
2154 match E::A { _ => {} }
2164 //- /main.rs crate:main deps:lib
2167 match E::A { _ => {} }
2169 //^^^^ Missing match arm
2174 //^^^^ Missing match arm
2193 //^^^^ Missing match arm
2203 fn pattern_type_is_of_substitution() {
2204 cov_mark::check!(match_check_wildcard_expanded_to_substitutions);
2219 fn record_struct_no_such_field() {
2224 match f { Foo { bar } => () }
2225 // ^^^^^^^^^^^ Internal: match check bailed out
2232 fn match_ergonomics_issue_9095() {
2235 enum Foo<T> { A(T) }
2237 match &Foo::A(true) {
2246 mod false_negatives {
2247 //! The implementation of match checking here is a work in progress. As we roll this out, we
2248 //! prefer false negatives to false positives (ideally there would be no false positives). This
2249 //! test module should document known false negatives. Eventually we will have a complete
2250 //! implementation of match checking and this module will be empty.
2252 //! The reasons for documenting known false negatives:
2254 //! 1. It acts as a backlog of work that can be done to improve the behavior of the system.
2255 //! 2. It ensures the code doesn't panic when handling these cases.
2260 // We don't currently check integer exhaustiveness.
2266 // ^^ Internal: match check bailed out
2275 fn reference_patterns_at_top_level() {
2281 // ^^^^^ Internal: match check bailed out
2289 fn reference_patterns_in_fields() {
2295 // ^^^^^^^ Internal: match check bailed out
2299 // ^^^^^^^^ Internal: match check bailed out
2309 mod decl_check_tests {
2310 use crate::diagnostics::tests::check_diagnostics;
2313 fn incorrect_function_name() {
2316 fn NonSnakeCaseName() {}
2317 // ^^^^^^^^^^^^^^^^ Function `NonSnakeCaseName` should have snake_case name, e.g. `non_snake_case_name`
2323 fn incorrect_function_params() {
2326 fn foo(SomeParam: u8) {}
2327 // ^^^^^^^^^ Parameter `SomeParam` should have snake_case name, e.g. `some_param`
2329 fn foo2(ok_param: &str, CAPS_PARAM: u8) {}
2330 // ^^^^^^^^^^ Parameter `CAPS_PARAM` should have snake_case name, e.g. `caps_param`
2336 fn incorrect_variable_names() {
2340 let SOME_VALUE = 10;
2341 // ^^^^^^^^^^ Variable `SOME_VALUE` should have snake_case name, e.g. `some_value`
2342 let AnotherValue = 20;
2343 // ^^^^^^^^^^^^ Variable `AnotherValue` should have snake_case name, e.g. `another_value`
2350 fn incorrect_struct_names() {
2353 struct non_camel_case_name {}
2354 // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName`
2356 struct SCREAMING_CASE {}
2357 // ^^^^^^^^^^^^^^ Structure `SCREAMING_CASE` should have CamelCase name, e.g. `ScreamingCase`
2363 fn no_diagnostic_for_camel_cased_acronyms_in_struct_name() {
2372 fn incorrect_struct_field() {
2375 struct SomeStruct { SomeField: u8 }
2376 // ^^^^^^^^^ Field `SomeField` should have snake_case name, e.g. `some_field`
2382 fn incorrect_enum_names() {
2385 enum some_enum { Val(u8) }
2386 // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum`
2389 // ^^^^^^^^^ Enum `SOME_ENUM` should have CamelCase name, e.g. `SomeEnum`
2395 fn no_diagnostic_for_camel_cased_acronyms_in_enum_name() {
2404 fn incorrect_enum_variant_name() {
2407 enum SomeEnum { SOME_VARIANT(u8) }
2408 // ^^^^^^^^^^^^ Variant `SOME_VARIANT` should have CamelCase name, e.g. `SomeVariant`
2414 fn incorrect_const_name() {
2417 const some_weird_const: u8 = 10;
2418 // ^^^^^^^^^^^^^^^^ Constant `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2424 fn incorrect_static_name() {
2427 static some_weird_const: u8 = 10;
2428 // ^^^^^^^^^^^^^^^^ Static variable `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2434 fn fn_inside_impl_struct() {
2438 // ^^^^^^^^^^ Structure `someStruct` should have CamelCase name, e.g. `SomeStruct`
2441 fn SomeFunc(&self) {
2442 // ^^^^^^^^ Function `SomeFunc` should have snake_case name, e.g. `some_func`
2443 let WHY_VAR_IS_CAPS = 10;
2444 // ^^^^^^^^^^^^^^^ Variable `WHY_VAR_IS_CAPS` should have snake_case name, e.g. `why_var_is_caps`
2452 fn no_diagnostic_for_enum_varinats() {
2455 enum Option { Some, None }
2458 match Option::None {
2471 enum Option { Some, None }
2474 match Option::None {
2475 SOME_VAR @ None => (),
2476 // ^^^^^^^^ Variable `SOME_VAR` should have snake_case name, e.g. `some_var`
2485 fn allow_attributes() {
2488 #[allow(non_snake_case)]
2489 fn NonSnakeCaseName(SOME_VAR: u8) -> u8{
2490 // cov_flags generated output from elsewhere in this file
2493 static lower_case: u8;
2496 let OtherVar = SOME_VAR + 1;
2500 #[allow(nonstandard_style)]
2501 mod CheckNonstandardStyle {
2502 fn HiImABadFnName() {}
2507 fn HiImABadFnName() {}
2511 #![allow(non_snake_case)]
2512 fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {}
2515 #[allow(non_snake_case, non_camel_case_types)]
2516 pub struct some_type {
2521 #[allow(non_upper_case_globals)]
2522 pub const some_const: u8 = 10;
2524 #[allow(non_upper_case_globals)]
2525 pub static SomeStatic: u8 = 10;
2531 fn allow_attributes_crate_attr() {
2534 #![allow(non_snake_case)]
2537 fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {}
2545 fn bug_trait_inside_fn() {
2547 // This is broken, and in fact, should not even be looked at by this
2548 // lint in the first place. There's weird stuff going on in the
2549 // collection phase.
2550 // It's currently being brought in by:
2551 // * validate_func on `a` recursing into modules
2552 // * then it finds the trait and then the function while iterating
2554 // * then validate_func is called on Dirty
2555 // * ... which then proceeds to look at some unknown module taking no
2556 // attrs from either the impl or the fn a, and then finally to the root
2559 // It should find the attribute on the trait, but it *doesn't even see
2560 // the trait* as far as I can tell.
2568 // this comes out of bitflags, mostly
2569 #[allow(non_snake_case)]
2571 const HiImAlsoBad: u8 = 2;
2573 fn Dirty(&self) -> bool {
2586 fn bug_traits_arent_checked() {
2587 // FIXME: Traits and functions in traits aren't currently checked by
2588 // r-a, even though rustc will complain about them.
2592 // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait`
2594 // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function`
2596 // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function`
2603 fn ignores_extern_items() {
2604 cov_mark::check!(extern_func_incorrect_case_ignored);
2605 cov_mark::check!(extern_static_incorrect_case_ignored);
2609 fn NonSnakeCaseName(SOME_VAR: u8) -> u8;
2610 pub static SomeStatic: u8 = 10;
2617 fn infinite_loop_inner_items() {
2629 #[test] // Issue #8809.
2630 fn parenthesized_parameter() {
2631 check_diagnostics(r#"fn f((O): _) {}"#)