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.
14 use std::cell::RefCell;
18 diagnostics::{AnyDiagnostic, Diagnostic as _, DiagnosticCode, DiagnosticSinkBuilder},
21 use ide_assists::AssistResolveStrategy;
22 use ide_db::{base_db::SourceDatabase, RootDatabase};
23 use itertools::Itertools;
24 use rustc_hash::FxHashSet;
27 SyntaxNode, SyntaxNodePtr, TextRange, TextSize,
29 use text_edit::TextEdit;
30 use unlinked_file::UnlinkedFile;
32 use crate::{Assist, AssistId, AssistKind, FileId, Label, SourceChange};
34 use self::fixes::DiagnosticWithFixes;
37 pub struct Diagnostic {
38 // pub name: Option<String>,
41 pub severity: Severity,
42 pub fixes: Option<Vec<Assist>>,
44 pub code: Option<DiagnosticCode>,
48 fn new(code: &'static str, message: impl Into<String>, range: TextRange) -> Diagnostic {
49 let message = message.into();
50 let code = Some(DiagnosticCode(code));
51 Self { message, range, severity: Severity::Error, fixes: None, unused: false, code }
54 fn error(range: TextRange, message: String) -> Self {
55 Self { message, range, severity: Severity::Error, fixes: None, unused: false, code: None }
58 fn hint(range: TextRange, message: String) -> Self {
62 severity: Severity::WeakWarning,
69 fn with_fixes(self, fixes: Option<Vec<Assist>>) -> Self {
70 Self { fixes, ..self }
73 fn with_unused(self, unused: bool) -> Self {
74 Self { unused, ..self }
77 fn with_code(self, code: Option<DiagnosticCode>) -> Self {
82 #[derive(Debug, Copy, Clone)]
88 #[derive(Default, Debug, Clone)]
89 pub struct DiagnosticsConfig {
90 pub disable_experimental: bool,
91 pub disabled: FxHashSet<String>,
94 struct DiagnosticsContext<'a> {
95 config: &'a DiagnosticsConfig,
96 sema: Semantics<'a, RootDatabase>,
98 resolve: &'a AssistResolveStrategy,
101 pub(crate) fn diagnostics(
103 config: &DiagnosticsConfig,
104 resolve: &AssistResolveStrategy,
106 ) -> Vec<Diagnostic> {
107 let _p = profile::span("diagnostics");
108 let sema = Semantics::new(db);
109 let parse = db.parse(file_id);
110 let mut res = Vec::new();
112 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
118 .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
121 for node in parse.tree().syntax().descendants() {
122 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
123 field_shorthand::check(&mut res, file_id, &node);
125 let res = RefCell::new(res);
126 let sink_builder = DiagnosticSinkBuilder::new()
127 .on::<hir::diagnostics::MissingOkOrSomeInTailExpr, _>(|d| {
128 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
130 .on::<hir::diagnostics::NoSuchField, _>(|d| {
131 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
133 .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| {
134 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
136 .on::<hir::diagnostics::IncorrectCase, _>(|d| {
137 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
139 .on::<hir::diagnostics::ReplaceFilterMapNextWithFindMap, _>(|d| {
140 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
142 .on::<hir::diagnostics::InactiveCode, _>(|d| {
143 // If there's inactive code somewhere in a macro, don't propagate to the call-site.
144 if d.display_source().file_id.expansion_info(db).is_some() {
148 // Override severity and mark as unused.
149 res.borrow_mut().push(
151 sema.diagnostics_display_range(d.display_source()).range,
155 .with_code(Some(d.code())),
158 .on::<UnlinkedFile, _>(|d| {
159 // Limit diagnostic to the first few characters in the file. This matches how VS Code
160 // renders it with the full span, but on other editors, and is less invasive.
161 let range = sema.diagnostics_display_range(d.display_source()).range;
162 let range = range.intersect(TextRange::up_to(TextSize::of("..."))).unwrap_or(range);
164 // Override severity and mark as unused.
165 res.borrow_mut().push(
166 Diagnostic::hint(range, d.message())
167 .with_fixes(d.fixes(&sema, resolve))
168 .with_code(Some(d.code())),
171 .on::<hir::diagnostics::UnresolvedProcMacro, _>(|d| {
172 // Use more accurate position if available.
173 let display_range = d
175 .unwrap_or_else(|| sema.diagnostics_display_range(d.display_source()).range);
177 // FIXME: it would be nice to tell the user whether proc macros are currently disabled
179 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
181 .on::<hir::diagnostics::UnresolvedMacroCall, _>(|d| {
182 let last_path_segment = sema.db.parse_or_expand(d.file).and_then(|root| {
186 .and_then(|it| it.segment())
187 .and_then(|it| it.name_ref())
188 .map(|it| InFile::new(d.file, SyntaxNodePtr::new(it.syntax())))
190 let diagnostics = last_path_segment.unwrap_or_else(|| d.display_source());
191 let display_range = sema.diagnostics_display_range(diagnostics).range;
193 .push(Diagnostic::error(display_range, d.message()).with_code(Some(d.code())));
195 .on::<hir::diagnostics::UnimplementedBuiltinMacro, _>(|d| {
196 let display_range = sema.diagnostics_display_range(d.display_source()).range;
198 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
200 // Only collect experimental diagnostics when they're enabled.
201 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
202 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
204 // Finalize the `DiagnosticSink` building process.
205 let mut sink = sink_builder
206 // Diagnostics not handled above get no fix and default treatment.
208 res.borrow_mut().push(
210 sema.diagnostics_display_range(d.display_source()).range,
213 .with_code(Some(d.code())),
217 let mut diags = Vec::new();
218 let internal_diagnostics = cfg!(test);
219 match sema.to_module_def(file_id) {
220 Some(m) => diags = m.diagnostics(db, &mut sink, internal_diagnostics),
222 sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(parse.tree().syntax()) });
228 let mut res = res.into_inner();
230 let ctx = DiagnosticsContext { config, sema, resolve };
233 AnyDiagnostic::UnresolvedModule(d) => unresolved_module::unresolved_module(&ctx, &d),
234 AnyDiagnostic::MissingFields(d) => missing_fields::missing_fields(&ctx, &d),
236 if let Some(code) = d.code {
237 if ctx.config.disabled.contains(code.as_str()) {
247 fn diagnostic_with_fix<D: DiagnosticWithFixes>(
249 sema: &Semantics<RootDatabase>,
250 resolve: &AssistResolveStrategy,
252 Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message())
253 .with_fixes(d.fixes(sema, resolve))
254 .with_code(Some(d.code()))
257 fn warning_with_fix<D: DiagnosticWithFixes>(
259 sema: &Semantics<RootDatabase>,
260 resolve: &AssistResolveStrategy,
262 Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message())
263 .with_fixes(d.fixes(sema, resolve))
264 .with_code(Some(d.code()))
267 fn check_unnecessary_braces_in_use_statement(
268 acc: &mut Vec<Diagnostic>,
272 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
273 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
274 // If there is a comment inside the bracketed `use`,
275 // assume it is a commented out module path and don't show diagnostic.
276 if use_tree_list.has_inner_comment() {
280 let use_range = use_tree_list.syntax().text_range();
282 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
284 let to_replace = single_use_tree.syntax().text().to_string();
285 let mut edit_builder = TextEdit::builder();
286 edit_builder.delete(use_range);
287 edit_builder.insert(use_range.start(), to_replace);
288 edit_builder.finish()
292 Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
293 .with_fixes(Some(vec![fix(
295 "Remove unnecessary braces",
296 SourceChange::from_text_edit(file_id, edit),
305 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
306 single_use_tree: &ast::UseTree,
307 ) -> Option<TextEdit> {
308 let use_tree_list_node = single_use_tree.syntax().parent()?;
309 if single_use_tree.path()?.segment()?.self_token().is_some() {
310 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
311 let end = use_tree_list_node.text_range().end();
312 return Some(TextEdit::delete(TextRange::new(start, end)));
317 fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
318 let mut res = unresolved_fix(id, label, target);
319 res.source_change = Some(source_change);
323 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
324 assert!(!id.contains(' '));
326 id: AssistId(id, AssistKind::QuickFix),
327 label: Label::new(label),
336 use expect_test::Expect;
337 use hir::diagnostics::DiagnosticCode;
338 use ide_assists::AssistResolveStrategy;
339 use stdx::trim_indent;
340 use test_utils::{assert_eq_text, extract_annotations};
342 use crate::{fixture, DiagnosticsConfig};
344 /// Takes a multi-file input fixture with annotated cursor positions,
346 /// * a diagnostic is produced
347 /// * the first diagnostic fix trigger range touches the input cursor position
348 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
350 pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
351 check_nth_fix(0, ra_fixture_before, ra_fixture_after);
353 /// Takes a multi-file input fixture with annotated cursor positions,
355 /// * a diagnostic is produced
356 /// * every diagnostic fixes trigger range touches the input cursor position
357 /// * that the contents of the file containing the cursor match `after` after each diagnostic fix is applied
358 pub(crate) fn check_fixes(ra_fixture_before: &str, ra_fixtures_after: Vec<&str>) {
359 for (i, ra_fixture_after) in ra_fixtures_after.iter().enumerate() {
360 check_nth_fix(i, ra_fixture_before, ra_fixture_after)
365 fn check_nth_fix(nth: usize, ra_fixture_before: &str, ra_fixture_after: &str) {
366 let after = trim_indent(ra_fixture_after);
368 let (analysis, file_position) = fixture::position(ra_fixture_before);
369 let diagnostic = analysis
371 &DiagnosticsConfig::default(),
372 AssistResolveStrategy::All,
373 file_position.file_id,
378 let fix = &diagnostic.fixes.unwrap()[nth];
380 let source_change = fix.source_change.as_ref().unwrap();
381 let file_id = *source_change.source_file_edits.keys().next().unwrap();
382 let mut actual = analysis.file_text(file_id).unwrap().to_string();
384 for edit in source_change.source_file_edits.values() {
385 edit.apply(&mut actual);
390 assert_eq_text!(&after, &actual);
392 fix.target.contains_inclusive(file_position.offset),
393 "diagnostic fix range {:?} does not touch cursor position {:?}",
398 /// Checks that there's a diagnostic *without* fix at `$0`.
399 fn check_no_fix(ra_fixture: &str) {
400 let (analysis, file_position) = fixture::position(ra_fixture);
401 let diagnostic = analysis
403 &DiagnosticsConfig::default(),
404 AssistResolveStrategy::All,
405 file_position.file_id,
410 assert!(diagnostic.fixes.is_none(), "got a fix when none was expected: {:?}", diagnostic);
413 /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
414 /// apply to the file containing the cursor.
415 pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
416 let (analysis, files) = fixture::files(ra_fixture);
417 let diagnostics = files
419 .flat_map(|file_id| {
421 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
424 .collect::<Vec<_>>();
425 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
428 pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) {
429 let (analysis, file_id) = fixture::file(ra_fixture);
430 let diagnostics = analysis
431 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
433 expect.assert_debug_eq(&diagnostics)
436 pub(crate) fn check_diagnostics(ra_fixture: &str) {
437 let (analysis, file_id) = fixture::file(ra_fixture);
438 let diagnostics = analysis
439 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
442 let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
443 let mut actual = diagnostics
445 .filter(|d| d.code != Some(DiagnosticCode("inactive-code")))
446 .map(|d| (d.range, d.message))
447 .collect::<Vec<_>>();
448 actual.sort_by_key(|(range, _)| range.start());
449 assert_eq!(expected, actual);
453 fn test_unresolved_macro_range() {
457 //^^^ unresolved macro `foo::bar!`
463 fn unresolved_import_in_use_tree() {
464 // Only the relevant part of a nested `use` item should be highlighted.
467 use does_exist::{Exists, DoesntExist};
468 //^^^^^^^^^^^ unresolved import
470 use {does_not_exist::*, does_exist};
471 //^^^^^^^^^^^^^^^^^ unresolved import
473 use does_not_exist::{
475 //^ unresolved import
477 //^ unresolved import
479 //^ unresolved import
490 fn range_mapping_out_of_macros() {
491 // FIXME: this is very wrong, but somewhat tricky to fix.
498 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
501 let _x = id![Foo { a: $042 }];
504 pub struct Foo { pub a: i32, pub b: i32 }
511 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
514 let _x = id![Foo { a: 42 }];
517 pub struct Foo { pub a: i32, pub b: i32 }
523 fn test_check_unnecessary_braces_in_use_statement() {
524 check_no_diagnostics(
537 check_no_diagnostics(
595 mod a { mod c {} mod d { mod e {} } }
596 use a::{c, d::{e$0}};
599 mod a { mod c {} mod d { mod e {} } }
606 fn test_disabled_diagnostics() {
607 let mut config = DiagnosticsConfig::default();
608 config.disabled.insert("unresolved-module".into());
610 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
613 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
614 assert!(diagnostics.is_empty());
616 let diagnostics = analysis
617 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
619 assert!(!diagnostics.is_empty());
623 fn unlinked_file_prepend_first_item() {
624 cov_mark::check!(unlinked_file_prepend_before_first_item);
625 // Only tests the first one for `pub mod` since the rest are the same
649 fn unlinked_file_append_mod() {
650 cov_mark::check!(unlinked_file_append_to_existing_mods);
662 mod preexisting_bottom;)
676 mod preexisting_bottom;)
682 fn unlinked_file_insert_in_empty_file() {
683 cov_mark::check!(unlinked_file_empty_file);
697 fn unlinked_file_old_style_modrs() {
715 fn unlinked_file_new_style_mod() {
731 fn unlinked_file_with_cfg_off() {
732 cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
746 fn unlinked_file_with_cfg_on() {
747 check_no_diagnostics(
759 fn break_outside_of_loop() {
763 //^^^^^ break outside of loop
769 fn no_such_field_diagnostics() {
772 struct S { foo: i32, bar: () }
776 //^ Missing structure fields:
780 //^^^^^^^ no such field
788 fn no_such_field_with_feature_flag_diagnostics() {
791 //- /lib.rs crate:foo cfg:feature=foo
794 #[cfg(feature = "foo")]
799 #[cfg(feature = "foo")]
800 pub(crate) fn new(my_val: usize, bar: bool) -> Self {
803 #[cfg(not(feature = "foo"))]
804 pub(crate) fn new(my_val: usize, _bar: bool) -> Self {
813 fn no_such_field_enum_with_feature_flag_diagnostics() {
816 //- /lib.rs crate:foo cfg:feature=foo
818 #[cfg(not(feature = "foo"))]
820 #[cfg(feature = "foo")]
836 fn no_such_field_with_feature_flag_diagnostics_on_struct_lit() {
839 //- /lib.rs crate:foo cfg:feature=foo
841 #[cfg(feature = "foo")]
843 #[cfg(not(feature = "foo"))]
848 #[cfg(feature = "foo")]
849 fn new(foo: u32) -> Self {
852 #[cfg(not(feature = "foo"))]
853 fn new(bar: u32) -> Self {
856 fn new2(bar: u32) -> Self {
857 #[cfg(feature = "foo")]
858 { Self { foo: bar } }
859 #[cfg(not(feature = "foo"))]
862 fn new2(val: u32) -> Self {
864 #[cfg(feature = "foo")]
866 #[cfg(not(feature = "foo"))]
876 fn no_such_field_with_type_macro() {
879 macro_rules! Type { () => { u32 }; }
880 struct Foo { bar: Type![] }
892 fn missing_unsafe_diagnostic_with_raw_ptr() {
896 let x = &5 as *const usize;
897 unsafe { let y = *x; }
899 } //^^ This operation is unsafe and requires an unsafe function or block
905 fn missing_unsafe_diagnostic_with_unsafe_call() {
911 unsafe fn unsafe_fn(&self) {
912 let x = &5 as *const usize;
917 unsafe fn unsafe_fn() {
918 let x = &5 as *const usize;
924 //^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
925 HasUnsafe.unsafe_fn();
926 //^^^^^^^^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
929 HasUnsafe.unsafe_fn();
937 fn missing_unsafe_diagnostic_with_static_mut() {
944 static mut STATIC_MUT: Ty = Ty { a: 0 };
947 let x = STATIC_MUT.a;
948 //^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
950 let x = STATIC_MUT.a;
958 fn no_missing_unsafe_diagnostic_with_safe_intrinsic() {
961 extern "rust-intrinsic" {
962 pub fn bitreverse(x: u32) -> u32; // Safe intrinsic
963 pub fn floorf32(x: f32) -> f32; // Unsafe intrinsic
967 let _ = bitreverse(12);
968 let _ = floorf32(12.0);
969 //^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
975 // Register the required standard library types to make the tests work
976 fn add_filter_map_with_find_next_boilerplate(body: &str) -> String {
978 //- /main.rs crate:main deps:core
979 use core::iter::Iterator;
980 use core::option::Option::{self, Some, None};
983 //- /core/lib.rs crate:core
985 pub enum Option<T> { Some(T), None }
990 fn filter_map<B, F>(self, f: F) -> FilterMap where F: FnMut(Self::Item) -> Option<B> { FilterMap }
991 fn next(&mut self) -> Option<Self::Item>;
993 pub struct FilterMap {}
994 impl Iterator for FilterMap {
996 fn next(&mut self) -> i32 { 7 }
1000 format!("{}{}{}", prefix, body, suffix)
1004 fn replace_filter_map_next_with_find_map2() {
1005 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1008 let m = [1, 2, 3].iter().filter_map(|x| if *x == 2 { Some (4) } else { None }).next();
1009 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ replace filter_map(..).next() with find_map(..)
1016 fn replace_filter_map_next_with_find_map_no_diagnostic_without_next() {
1017 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1022 .filter_map(|x| if *x == 2 { Some (4) } else { None })
1030 fn replace_filter_map_next_with_find_map_no_diagnostic_with_intervening_methods() {
1031 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1036 .filter_map(|x| if *x == 2 { Some (4) } else { None })
1045 fn replace_filter_map_next_with_find_map_no_diagnostic_if_not_in_chain() {
1046 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1051 .filter_map(|x| if *x == 2 { Some (4) } else { None });
1059 fn missing_record_pat_field_diagnostic() {
1062 struct S { foo: i32, bar: () }
1064 let S { foo: _ } = s;
1065 //^ Missing structure fields:
1073 fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
1076 struct S { foo: i32, bar: () }
1077 fn baz(s: S) -> i32 {
1079 S { foo, .. } => foo,
1087 fn missing_record_pat_field_box() {
1090 struct S { s: Box<u32> }
1092 let S { box s } = a;
1099 fn missing_record_pat_field_ref() {
1104 let S { ref s } = a;
1111 fn simple_free_fn_zero() {
1116 //^^^^^^^ Expected 0 arguments, found 1
1129 fn simple_free_fn_one() {
1134 //^^^^^ Expected 1 argument, found 0
1151 impl S { fn method(&self) {} }
1155 } //^^^^^^^^^^^ Expected 1 argument, found 0
1162 impl S { fn method(&self) {} }
1173 fn method_with_arg() {
1177 impl S { fn method(&self, arg: u8) {} }
1181 } //^^^^^^^^^^ Expected 1 argument, found 0
1188 impl S { fn method(&self, arg: u8) {} }
1199 fn method_unknown_receiver() {
1200 // note: this is incorrect code, so there might be errors on this in the
1201 // future, but we shouldn't emit an argument count diagnostic here
1204 trait Foo { fn method(&self, arg: usize) {} }
1218 struct Tup(u8, u16);
1221 } //^^^^^^ Expected 2 arguments, found 1
1230 enum En { Variant(u8, u16), }
1233 } //^^^^^^^^^^^^^^ Expected 2 arguments, found 1
1239 fn enum_variant_type_macro() {
1252 //^^^^^^^^^^^^^^ Expected 1 argument, found 2
1254 //^^^^^^^^^^ Expected 1 argument, found 0
1266 fn fixed(fixed: u8);
1267 fn varargs(fixed: u8, ...);
1275 //^^^^^^^^^^^ Expected 1 argument, found 2
1288 fn arg_count_lambda() {
1294 //^^^ Expected 1 argument, found 0
1297 //^^^^^^^^^ Expected 1 argument, found 2
1304 fn cfgd_out_call_arguments() {
1307 struct C(#[cfg(FALSE)] ());
1320 C::new().method(#[cfg(FALSE)] 0);
1327 fn cfgd_out_fn_params() {
1330 fn foo(#[cfg(NEVER)] x: ()) {}
1335 fn method(#[cfg(NEVER)] self) {}
1336 fn method2(#[cfg(NEVER)] self, arg: u8) {}
1337 fn method3(self, #[cfg(NEVER)] arg: u8) {}
1341 fn fixed(fixed: u8, #[cfg(NEVER)] ...);
1342 fn varargs(#[cfg(not(NEVER))] ...);
1361 fn missing_semicolon() {
1364 fn test() -> i32 { 123; }
1365 //^^^ Remove this semicolon
1371 fn import_extern_crate_clash_with_inner_item() {
1372 // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
1376 //- /lib.rs crate:lib deps:jwt
1379 use permissions::jwt;
1383 jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
1388 pub struct Claims {}
1391 //- /jwt/lib.rs crate:jwt
1401 pub(super) mod match_check_tests {
1402 use crate::diagnostics::tests::check_diagnostics;
1410 //^^ Missing match arm
1412 //^^^^ Missing match arm
1414 match () { _ => (), }
1415 match () { () => (), }
1416 match (()) { (()) => (), }
1423 fn tuple_of_two_empty_tuple() {
1428 //^^^^^^^^ Missing match arm
1430 match ((), ()) { ((), ()) => (), }
1442 //^^^^^ Missing match arm
1443 match false { true => (), }
1444 //^^^^^ Missing match arm
1445 match (false, true) {}
1446 //^^^^^^^^^^^^^ Missing match arm
1447 match (false, true) { (true, true) => (), }
1448 //^^^^^^^^^^^^^ Missing match arm
1449 match (false, true) {
1450 //^^^^^^^^^^^^^ Missing match arm
1451 (false, true) => (),
1452 (false, false) => (),
1453 (true, false) => (),
1455 match (false, true) { (true, _x) => (), }
1456 //^^^^^^^^^^^^^ Missing match arm
1458 match false { true => (), false => (), }
1459 match (false, true) {
1461 (true, false) => (),
1464 match (false, true) {
1466 (true, false) => (),
1467 (false, true) => (),
1468 (false, false) => (),
1470 match (false, true) {
1472 (false, true) => (),
1473 (false, false) => (),
1475 match (false, true, false) {
1479 match (false, true, false) {
1483 match (false, true, false) { (..) => (), }
1490 fn tuple_of_tuple_and_bools() {
1494 match (false, ((), false)) {}
1495 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1496 match (false, ((), false)) { (true, ((), true)) => (), }
1497 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1498 match (false, ((), false)) { (true, _) => (), }
1499 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1501 match (false, ((), false)) {
1502 (true, ((), true)) => (),
1503 (true, ((), false)) => (),
1504 (false, ((), true)) => (),
1505 (false, ((), false)) => (),
1507 match (false, ((), false)) {
1508 (true, ((), true)) => (),
1509 (true, ((), false)) => (),
1521 enum Either { A, B, }
1525 //^^^^^^^^^ Missing match arm
1526 match Either::B { Either::A => (), }
1527 //^^^^^^^^^ Missing match arm
1530 //^^^^^^^^^^ Missing match arm
1535 Either::A => (), Either::B => (),
1538 Either::A => (), Either::B => (),
1546 fn enum_containing_bool() {
1549 enum Either { A(bool), B }
1553 //^^^^^^^^^ Missing match arm
1555 //^^^^^^^^^ Missing match arm
1556 Either::A(true) => (), Either::B => ()
1560 Either::A(true) => (),
1561 Either::A(false) => (),
1579 fn enum_different_sizes() {
1582 enum Either { A(bool), B(bool, bool) }
1585 match Either::A(false) {
1586 //^^^^^^^^^^^^^^^^ Missing match arm
1588 Either::B(false, _) => (),
1591 match Either::A(false) {
1593 Either::B(true, _) => (),
1594 Either::B(false, _) => (),
1596 match Either::A(false) {
1597 Either::A(true) | Either::A(false) => (),
1598 Either::B(true, _) => (),
1599 Either::B(false, _) => (),
1607 fn tuple_of_enum_no_diagnostic() {
1610 enum Either { A(bool), B(bool, bool) }
1611 enum Either2 { C, D }
1614 match (Either::A(false), Either2::C) {
1615 (Either::A(true), _) | (Either::A(false), _) => (),
1616 (Either::B(true, _), Either2::C) => (),
1617 (Either::B(false, _), Either2::C) => (),
1618 (Either::B(_, _), Either2::D) => (),
1626 fn or_pattern_no_diagnostic() {
1632 match (Either::A, Either::B) {
1633 (Either::A | Either::B, _) => (),
1640 fn mismatched_types() {
1641 // Match statements with arms that don't match the
1642 // expression pattern do not fire this diagnostic.
1645 enum Either { A, B }
1646 enum Either2 { C, D }
1651 // ^^^^^^^^^^ Internal: match check bailed out
1654 match (true, false) {
1655 (true, false, true) => (),
1656 // ^^^^^^^^^^^^^^^^^^^ Internal: match check bailed out
1659 match (true, false) { (true,) => {} }
1660 // ^^^^^^^ Internal: match check bailed out
1661 match (0) { () => () }
1662 // ^^ Internal: match check bailed out
1663 match Unresolved::Bar { Unresolved::Baz => () }
1670 fn mismatched_types_in_or_patterns() {
1674 match false { true | () => {} }
1675 // ^^^^^^^^^ Internal: match check bailed out
1676 match (false,) { (true | (),) => {} }
1677 // ^^^^^^^^^^^^ Internal: match check bailed out
1684 fn malformed_match_arm_tuple_enum_missing_pattern() {
1685 // We are testing to be sure we don't panic here when the match
1686 // arm `Either::B` is missing its pattern.
1689 enum Either { A, B(u32) }
1702 fn malformed_match_arm_extra_fields() {
1705 enum A { B(isize, isize), C }
1708 A::B(_, _, _) => (),
1709 // ^^^^^^^^^^^^^ Internal: match check bailed out
1713 // ^^^^^^^ Internal: match check bailed out
1721 fn expr_diverges() {
1724 enum Either { A, B }
1729 // ^^^^^^^^^ Internal: match check bailed out
1734 // ^^^^^^^^^ Internal: match check bailed out
1736 match loop { break Foo::A } {
1737 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1740 match loop { break Foo::A } {
1750 fn expr_partially_diverges() {
1753 enum Either<T> { A(T), B }
1755 fn foo() -> Either<!> { Either::B }
1758 Either::A(val) => val,
1770 enum Either { A { foo: bool }, B }
1773 let a = Either::A { foo: true };
1775 //^ Missing match arm
1776 match a { Either::A { foo: true } => () }
1777 //^ Missing match arm
1779 Either::A { } => (),
1780 //^^^^^^^^^ Missing structure fields:
1785 //^ Missing match arm
1786 Either::A { } => (),
1787 } //^^^^^^^^^ Missing structure fields:
1791 Either::A { foo: true } => (),
1792 Either::A { foo: false } => (),
1796 Either::A { foo: _ } => (),
1805 fn enum_record_fields_out_of_order() {
1809 A { foo: bool, bar: () },
1814 let a = Either::A { foo: true, bar: () };
1816 //^ Missing match arm
1817 Either::A { bar: (), foo: false } => (),
1818 Either::A { foo: true, bar: () } => (),
1822 Either::A { bar: (), foo: false } => (),
1823 Either::A { foo: true, bar: () } => (),
1832 fn enum_record_ellipsis() {
1836 A { foo: bool, bar: bool },
1843 //^ Missing match arm
1844 Either::A { foo: true, .. } => (),
1848 //^ Missing match arm
1849 Either::A { .. } => (),
1853 Either::A { foo: true, .. } => (),
1854 Either::A { foo: false, .. } => (),
1859 Either::A { .. } => (),
1868 fn enum_tuple_partial_ellipsis() {
1872 A(bool, bool, bool, bool),
1878 //^^^^^^^^^ Missing match arm
1879 Either::A(true, .., true) => (),
1880 Either::A(true, .., false) => (),
1881 Either::A(false, .., false) => (),
1885 //^^^^^^^^^ Missing match arm
1886 Either::A(true, .., true) => (),
1887 Either::A(true, .., false) => (),
1888 Either::A(.., true) => (),
1893 Either::A(true, .., true) => (),
1894 Either::A(true, .., false) => (),
1895 Either::A(false, .., true) => (),
1896 Either::A(false, .., false) => (),
1900 Either::A(true, .., true) => (),
1901 Either::A(true, .., false) => (),
1902 Either::A(.., true) => (),
1903 Either::A(.., false) => (),
1917 fn enum_(never: Never) {
1920 fn enum_ref(never: &Never) {
1922 //^^^^^ Missing match arm
1935 enum Option<T> { Some(T), None }
1938 // `Never` is deliberately not defined so that it's an uninferred type.
1939 match Option::<Never>::None {
1941 Some(never) => match never {},
1942 // ^^^^^^^^^^^ Internal: match check bailed out
1944 match Option::<Never>::None {
1945 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1946 Option::Some(_never) => {},
1954 fn tuple_of_bools_with_ellipsis_at_end_missing_arm() {
1958 match (false, true, false) {
1959 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1967 fn tuple_of_bools_with_ellipsis_at_beginning_missing_arm() {
1971 match (false, true, false) {
1972 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1980 fn tuple_of_bools_with_ellipsis_in_middle_missing_arm() {
1984 match (false, true, false) {
1985 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1986 (true, .., false) => (),
1993 fn record_struct() {
1995 r#"struct Foo { a: bool }
1998 //^ Missing match arm
1999 match f { Foo { a: true } => () }
2000 //^ Missing match arm
2001 match &f { Foo { a: true } => () }
2002 //^^ Missing match arm
2003 match f { Foo { a: _ } => () }
2005 Foo { a: true } => (),
2006 Foo { a: false } => (),
2009 Foo { a: true } => (),
2010 Foo { a: false } => (),
2020 r#"struct Foo(bool);
2023 //^ Missing match arm
2024 match f { Foo(true) => () }
2025 //^ Missing match arm
2041 //^ Missing match arm
2042 match f { Foo => () }
2049 fn record_struct_ellipsis() {
2051 r#"struct Foo { foo: bool, bar: bool }
2053 match f { Foo { foo: true, .. } => () }
2054 //^ Missing match arm
2056 //^ Missing match arm
2057 Foo { foo: true, .. } => (),
2058 Foo { bar: false, .. } => ()
2060 match f { Foo { .. } => () }
2062 Foo { foo: true, .. } => (),
2063 Foo { foo: false, .. } => ()
2075 enum Either { A(bool), B }
2077 //^^^^^^^^^ Missing match arm
2078 Either::A(true | false) => (),
2086 fn no_panic_at_unimplemented_subpattern_type() {
2091 match v { S{ a } => {} }
2092 match v { S{ a: _x } => {} }
2093 match v { S{ a: 'a' } => {} }
2094 //^^^^^^^^^^^ Internal: match check bailed out
2095 match v { S{..} => {} }
2098 //^ Missing match arm
2113 match true { _x @ true => {} }
2114 //^^^^ Missing match arm
2121 fn binding_ref_has_correct_type() {
2122 // Asserts `PatKind::Binding(ref _x): bool`, not &bool.
2123 // If that's not true match checking will panic with "incompatible constructors"
2124 // FIXME: make facilities to test this directly like `tests::check_infer(..)`
2129 // FIXME: this should not bail out but current behavior is such as the old algorithm.
2130 // ExprValidator::validate_match(..) checks types of top level patterns incorrecly.
2133 // ^^^^^^ Internal: match check bailed out
2146 fn enum_non_exhaustive() {
2149 //- /lib.rs crate:lib
2153 match E::A { _ => {} }
2163 //- /main.rs crate:main deps:lib
2166 match E::A { _ => {} }
2168 //^^^^ Missing match arm
2173 //^^^^ Missing match arm
2192 //^^^^ Missing match arm
2202 fn pattern_type_is_of_substitution() {
2203 cov_mark::check!(match_check_wildcard_expanded_to_substitutions);
2218 fn record_struct_no_such_field() {
2223 match f { Foo { bar } => () }
2224 // ^^^^^^^^^^^ Internal: match check bailed out
2231 fn match_ergonomics_issue_9095() {
2234 enum Foo<T> { A(T) }
2236 match &Foo::A(true) {
2245 mod false_negatives {
2246 //! The implementation of match checking here is a work in progress. As we roll this out, we
2247 //! prefer false negatives to false positives (ideally there would be no false positives). This
2248 //! test module should document known false negatives. Eventually we will have a complete
2249 //! implementation of match checking and this module will be empty.
2251 //! The reasons for documenting known false negatives:
2253 //! 1. It acts as a backlog of work that can be done to improve the behavior of the system.
2254 //! 2. It ensures the code doesn't panic when handling these cases.
2259 // We don't currently check integer exhaustiveness.
2265 // ^^ Internal: match check bailed out
2274 fn reference_patterns_at_top_level() {
2280 // ^^^^^ Internal: match check bailed out
2288 fn reference_patterns_in_fields() {
2294 // ^^^^^^^ Internal: match check bailed out
2298 // ^^^^^^^^ Internal: match check bailed out
2308 mod decl_check_tests {
2309 use crate::diagnostics::tests::check_diagnostics;
2312 fn incorrect_function_name() {
2315 fn NonSnakeCaseName() {}
2316 // ^^^^^^^^^^^^^^^^ Function `NonSnakeCaseName` should have snake_case name, e.g. `non_snake_case_name`
2322 fn incorrect_function_params() {
2325 fn foo(SomeParam: u8) {}
2326 // ^^^^^^^^^ Parameter `SomeParam` should have snake_case name, e.g. `some_param`
2328 fn foo2(ok_param: &str, CAPS_PARAM: u8) {}
2329 // ^^^^^^^^^^ Parameter `CAPS_PARAM` should have snake_case name, e.g. `caps_param`
2335 fn incorrect_variable_names() {
2339 let SOME_VALUE = 10;
2340 // ^^^^^^^^^^ Variable `SOME_VALUE` should have snake_case name, e.g. `some_value`
2341 let AnotherValue = 20;
2342 // ^^^^^^^^^^^^ Variable `AnotherValue` should have snake_case name, e.g. `another_value`
2349 fn incorrect_struct_names() {
2352 struct non_camel_case_name {}
2353 // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName`
2355 struct SCREAMING_CASE {}
2356 // ^^^^^^^^^^^^^^ Structure `SCREAMING_CASE` should have CamelCase name, e.g. `ScreamingCase`
2362 fn no_diagnostic_for_camel_cased_acronyms_in_struct_name() {
2371 fn incorrect_struct_field() {
2374 struct SomeStruct { SomeField: u8 }
2375 // ^^^^^^^^^ Field `SomeField` should have snake_case name, e.g. `some_field`
2381 fn incorrect_enum_names() {
2384 enum some_enum { Val(u8) }
2385 // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum`
2388 // ^^^^^^^^^ Enum `SOME_ENUM` should have CamelCase name, e.g. `SomeEnum`
2394 fn no_diagnostic_for_camel_cased_acronyms_in_enum_name() {
2403 fn incorrect_enum_variant_name() {
2406 enum SomeEnum { SOME_VARIANT(u8) }
2407 // ^^^^^^^^^^^^ Variant `SOME_VARIANT` should have CamelCase name, e.g. `SomeVariant`
2413 fn incorrect_const_name() {
2416 const some_weird_const: u8 = 10;
2417 // ^^^^^^^^^^^^^^^^ Constant `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2423 fn incorrect_static_name() {
2426 static some_weird_const: u8 = 10;
2427 // ^^^^^^^^^^^^^^^^ Static variable `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2433 fn fn_inside_impl_struct() {
2437 // ^^^^^^^^^^ Structure `someStruct` should have CamelCase name, e.g. `SomeStruct`
2440 fn SomeFunc(&self) {
2441 // ^^^^^^^^ Function `SomeFunc` should have snake_case name, e.g. `some_func`
2442 let WHY_VAR_IS_CAPS = 10;
2443 // ^^^^^^^^^^^^^^^ Variable `WHY_VAR_IS_CAPS` should have snake_case name, e.g. `why_var_is_caps`
2451 fn no_diagnostic_for_enum_varinats() {
2454 enum Option { Some, None }
2457 match Option::None {
2470 enum Option { Some, None }
2473 match Option::None {
2474 SOME_VAR @ None => (),
2475 // ^^^^^^^^ Variable `SOME_VAR` should have snake_case name, e.g. `some_var`
2484 fn allow_attributes() {
2487 #[allow(non_snake_case)]
2488 fn NonSnakeCaseName(SOME_VAR: u8) -> u8{
2489 // cov_flags generated output from elsewhere in this file
2492 static lower_case: u8;
2495 let OtherVar = SOME_VAR + 1;
2499 #[allow(nonstandard_style)]
2500 mod CheckNonstandardStyle {
2501 fn HiImABadFnName() {}
2506 fn HiImABadFnName() {}
2510 #![allow(non_snake_case)]
2511 fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {}
2514 #[allow(non_snake_case, non_camel_case_types)]
2515 pub struct some_type {
2520 #[allow(non_upper_case_globals)]
2521 pub const some_const: u8 = 10;
2523 #[allow(non_upper_case_globals)]
2524 pub static SomeStatic: u8 = 10;
2530 fn allow_attributes_crate_attr() {
2533 #![allow(non_snake_case)]
2536 fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {}
2544 fn bug_trait_inside_fn() {
2546 // This is broken, and in fact, should not even be looked at by this
2547 // lint in the first place. There's weird stuff going on in the
2548 // collection phase.
2549 // It's currently being brought in by:
2550 // * validate_func on `a` recursing into modules
2551 // * then it finds the trait and then the function while iterating
2553 // * then validate_func is called on Dirty
2554 // * ... which then proceeds to look at some unknown module taking no
2555 // attrs from either the impl or the fn a, and then finally to the root
2558 // It should find the attribute on the trait, but it *doesn't even see
2559 // the trait* as far as I can tell.
2567 // this comes out of bitflags, mostly
2568 #[allow(non_snake_case)]
2570 const HiImAlsoBad: u8 = 2;
2572 fn Dirty(&self) -> bool {
2585 fn bug_traits_arent_checked() {
2586 // FIXME: Traits and functions in traits aren't currently checked by
2587 // r-a, even though rustc will complain about them.
2591 // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait`
2593 // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function`
2595 // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function`
2602 fn ignores_extern_items() {
2603 cov_mark::check!(extern_func_incorrect_case_ignored);
2604 cov_mark::check!(extern_static_incorrect_case_ignored);
2608 fn NonSnakeCaseName(SOME_VAR: u8) -> u8;
2609 pub static SomeStatic: u8 = 10;
2616 fn infinite_loop_inner_items() {
2628 #[test] // Issue #8809.
2629 fn parenthesized_parameter() {
2630 check_diagnostics(r#"fn f((O): _) {}"#)