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;
15 use std::cell::RefCell;
19 diagnostics::{AnyDiagnostic, Diagnostic as _, DiagnosticCode, DiagnosticSinkBuilder},
22 use ide_assists::AssistResolveStrategy;
23 use ide_db::{base_db::SourceDatabase, RootDatabase};
24 use itertools::Itertools;
25 use rustc_hash::FxHashSet;
28 SyntaxNode, SyntaxNodePtr, TextRange, TextSize,
30 use text_edit::TextEdit;
31 use unlinked_file::UnlinkedFile;
33 use crate::{Assist, AssistId, AssistKind, FileId, Label, SourceChange};
35 use self::fixes::DiagnosticWithFixes;
38 pub struct Diagnostic {
39 // pub name: Option<String>,
42 pub severity: Severity,
43 pub fixes: Option<Vec<Assist>>,
45 pub code: Option<DiagnosticCode>,
49 fn new(code: &'static str, message: impl Into<String>, range: TextRange) -> Diagnostic {
50 let message = message.into();
51 let code = Some(DiagnosticCode(code));
52 Self { message, range, severity: Severity::Error, fixes: None, unused: false, code }
55 fn error(range: TextRange, message: String) -> Self {
56 Self { message, range, severity: Severity::Error, fixes: None, unused: false, code: None }
59 fn hint(range: TextRange, message: String) -> Self {
63 severity: Severity::WeakWarning,
70 fn with_fixes(self, fixes: Option<Vec<Assist>>) -> Self {
71 Self { fixes, ..self }
74 fn with_unused(self, unused: bool) -> Self {
75 Self { unused, ..self }
78 fn with_code(self, code: Option<DiagnosticCode>) -> Self {
83 #[derive(Debug, Copy, Clone)]
89 #[derive(Default, Debug, Clone)]
90 pub struct DiagnosticsConfig {
91 pub disable_experimental: bool,
92 pub disabled: FxHashSet<String>,
95 struct DiagnosticsContext<'a> {
96 config: &'a DiagnosticsConfig,
97 sema: Semantics<'a, RootDatabase>,
99 resolve: &'a AssistResolveStrategy,
102 pub(crate) fn diagnostics(
104 config: &DiagnosticsConfig,
105 resolve: &AssistResolveStrategy,
107 ) -> Vec<Diagnostic> {
108 let _p = profile::span("diagnostics");
109 let sema = Semantics::new(db);
110 let parse = db.parse(file_id);
111 let mut res = Vec::new();
113 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
119 .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
122 for node in parse.tree().syntax().descendants() {
123 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
124 field_shorthand::check(&mut res, file_id, &node);
126 let res = RefCell::new(res);
127 let sink_builder = DiagnosticSinkBuilder::new()
128 .on::<hir::diagnostics::MissingOkOrSomeInTailExpr, _>(|d| {
129 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
131 .on::<hir::diagnostics::NoSuchField, _>(|d| {
132 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
134 .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| {
135 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
137 .on::<hir::diagnostics::IncorrectCase, _>(|d| {
138 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
140 .on::<hir::diagnostics::ReplaceFilterMapNextWithFindMap, _>(|d| {
141 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
143 .on::<hir::diagnostics::InactiveCode, _>(|d| {
144 // If there's inactive code somewhere in a macro, don't propagate to the call-site.
145 if d.display_source().file_id.expansion_info(db).is_some() {
149 // Override severity and mark as unused.
150 res.borrow_mut().push(
152 sema.diagnostics_display_range(d.display_source()).range,
156 .with_code(Some(d.code())),
159 .on::<UnlinkedFile, _>(|d| {
160 // Limit diagnostic to the first few characters in the file. This matches how VS Code
161 // renders it with the full span, but on other editors, and is less invasive.
162 let range = sema.diagnostics_display_range(d.display_source()).range;
163 let range = range.intersect(TextRange::up_to(TextSize::of("..."))).unwrap_or(range);
165 // Override severity and mark as unused.
166 res.borrow_mut().push(
167 Diagnostic::hint(range, d.message())
168 .with_fixes(d.fixes(&sema, resolve))
169 .with_code(Some(d.code())),
172 .on::<hir::diagnostics::UnresolvedProcMacro, _>(|d| {
173 // Use more accurate position if available.
174 let display_range = d
176 .unwrap_or_else(|| sema.diagnostics_display_range(d.display_source()).range);
178 // FIXME: it would be nice to tell the user whether proc macros are currently disabled
180 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
182 .on::<hir::diagnostics::UnresolvedMacroCall, _>(|d| {
183 let last_path_segment = sema.db.parse_or_expand(d.file).and_then(|root| {
187 .and_then(|it| it.segment())
188 .and_then(|it| it.name_ref())
189 .map(|it| InFile::new(d.file, SyntaxNodePtr::new(it.syntax())))
191 let diagnostics = last_path_segment.unwrap_or_else(|| d.display_source());
192 let display_range = sema.diagnostics_display_range(diagnostics).range;
194 .push(Diagnostic::error(display_range, d.message()).with_code(Some(d.code())));
196 .on::<hir::diagnostics::UnimplementedBuiltinMacro, _>(|d| {
197 let display_range = sema.diagnostics_display_range(d.display_source()).range;
199 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
201 // Only collect experimental diagnostics when they're enabled.
202 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
203 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
205 // Finalize the `DiagnosticSink` building process.
206 let mut sink = sink_builder
207 // Diagnostics not handled above get no fix and default treatment.
209 res.borrow_mut().push(
211 sema.diagnostics_display_range(d.display_source()).range,
214 .with_code(Some(d.code())),
218 let mut diags = Vec::new();
219 let internal_diagnostics = cfg!(test);
220 match sema.to_module_def(file_id) {
221 Some(m) => diags = m.diagnostics(db, &mut sink, internal_diagnostics),
223 sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(parse.tree().syntax()) });
229 let mut res = res.into_inner();
231 let ctx = DiagnosticsContext { config, sema, resolve };
235 AnyDiagnostic::UnresolvedModule(d) => unresolved_module::unresolved_module(&ctx, &d),
236 AnyDiagnostic::UnresolvedExternCrate(d) => unresolved_extern_crate::unresolved_extern_crate(&ctx, &d),
237 AnyDiagnostic::MissingFields(d) => missing_fields::missing_fields(&ctx, &d),
239 if let Some(code) = d.code {
240 if ctx.config.disabled.contains(code.as_str()) {
250 fn diagnostic_with_fix<D: DiagnosticWithFixes>(
252 sema: &Semantics<RootDatabase>,
253 resolve: &AssistResolveStrategy,
255 Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message())
256 .with_fixes(d.fixes(sema, resolve))
257 .with_code(Some(d.code()))
260 fn warning_with_fix<D: DiagnosticWithFixes>(
262 sema: &Semantics<RootDatabase>,
263 resolve: &AssistResolveStrategy,
265 Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message())
266 .with_fixes(d.fixes(sema, resolve))
267 .with_code(Some(d.code()))
270 fn check_unnecessary_braces_in_use_statement(
271 acc: &mut Vec<Diagnostic>,
275 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
276 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
277 // If there is a comment inside the bracketed `use`,
278 // assume it is a commented out module path and don't show diagnostic.
279 if use_tree_list.has_inner_comment() {
283 let use_range = use_tree_list.syntax().text_range();
285 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
287 let to_replace = single_use_tree.syntax().text().to_string();
288 let mut edit_builder = TextEdit::builder();
289 edit_builder.delete(use_range);
290 edit_builder.insert(use_range.start(), to_replace);
291 edit_builder.finish()
295 Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
296 .with_fixes(Some(vec![fix(
298 "Remove unnecessary braces",
299 SourceChange::from_text_edit(file_id, edit),
308 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
309 single_use_tree: &ast::UseTree,
310 ) -> Option<TextEdit> {
311 let use_tree_list_node = single_use_tree.syntax().parent()?;
312 if single_use_tree.path()?.segment()?.self_token().is_some() {
313 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
314 let end = use_tree_list_node.text_range().end();
315 return Some(TextEdit::delete(TextRange::new(start, end)));
320 fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
321 let mut res = unresolved_fix(id, label, target);
322 res.source_change = Some(source_change);
326 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
327 assert!(!id.contains(' '));
329 id: AssistId(id, AssistKind::QuickFix),
330 label: Label::new(label),
339 use expect_test::Expect;
340 use hir::diagnostics::DiagnosticCode;
341 use ide_assists::AssistResolveStrategy;
342 use stdx::trim_indent;
343 use test_utils::{assert_eq_text, extract_annotations};
345 use crate::{fixture, DiagnosticsConfig};
347 /// Takes a multi-file input fixture with annotated cursor positions,
349 /// * a diagnostic is produced
350 /// * the first diagnostic fix trigger range touches the input cursor position
351 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
353 pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
354 check_nth_fix(0, ra_fixture_before, ra_fixture_after);
356 /// Takes a multi-file input fixture with annotated cursor positions,
358 /// * a diagnostic is produced
359 /// * every diagnostic fixes trigger range touches the input cursor position
360 /// * that the contents of the file containing the cursor match `after` after each diagnostic fix is applied
361 pub(crate) fn check_fixes(ra_fixture_before: &str, ra_fixtures_after: Vec<&str>) {
362 for (i, ra_fixture_after) in ra_fixtures_after.iter().enumerate() {
363 check_nth_fix(i, ra_fixture_before, ra_fixture_after)
368 fn check_nth_fix(nth: usize, ra_fixture_before: &str, ra_fixture_after: &str) {
369 let after = trim_indent(ra_fixture_after);
371 let (analysis, file_position) = fixture::position(ra_fixture_before);
372 let diagnostic = analysis
374 &DiagnosticsConfig::default(),
375 AssistResolveStrategy::All,
376 file_position.file_id,
381 let fix = &diagnostic.fixes.unwrap()[nth];
383 let source_change = fix.source_change.as_ref().unwrap();
384 let file_id = *source_change.source_file_edits.keys().next().unwrap();
385 let mut actual = analysis.file_text(file_id).unwrap().to_string();
387 for edit in source_change.source_file_edits.values() {
388 edit.apply(&mut actual);
393 assert_eq_text!(&after, &actual);
395 fix.target.contains_inclusive(file_position.offset),
396 "diagnostic fix range {:?} does not touch cursor position {:?}",
401 /// Checks that there's a diagnostic *without* fix at `$0`.
402 fn check_no_fix(ra_fixture: &str) {
403 let (analysis, file_position) = fixture::position(ra_fixture);
404 let diagnostic = analysis
406 &DiagnosticsConfig::default(),
407 AssistResolveStrategy::All,
408 file_position.file_id,
413 assert!(diagnostic.fixes.is_none(), "got a fix when none was expected: {:?}", diagnostic);
416 /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
417 /// apply to the file containing the cursor.
418 pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
419 let (analysis, files) = fixture::files(ra_fixture);
420 let diagnostics = files
422 .flat_map(|file_id| {
424 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
427 .collect::<Vec<_>>();
428 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
431 pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) {
432 let (analysis, file_id) = fixture::file(ra_fixture);
433 let diagnostics = analysis
434 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
436 expect.assert_debug_eq(&diagnostics)
439 pub(crate) fn check_diagnostics(ra_fixture: &str) {
440 let (analysis, file_id) = fixture::file(ra_fixture);
441 let diagnostics = analysis
442 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
445 let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
446 let mut actual = diagnostics
448 .filter(|d| d.code != Some(DiagnosticCode("inactive-code")))
449 .map(|d| (d.range, d.message))
450 .collect::<Vec<_>>();
451 actual.sort_by_key(|(range, _)| range.start());
452 assert_eq!(expected, actual);
456 fn test_unresolved_macro_range() {
460 //^^^ unresolved macro `foo::bar!`
466 fn unresolved_import_in_use_tree() {
467 // Only the relevant part of a nested `use` item should be highlighted.
470 use does_exist::{Exists, DoesntExist};
471 //^^^^^^^^^^^ unresolved import
473 use {does_not_exist::*, does_exist};
474 //^^^^^^^^^^^^^^^^^ unresolved import
476 use does_not_exist::{
478 //^ unresolved import
480 //^ unresolved import
482 //^ unresolved import
493 fn range_mapping_out_of_macros() {
494 // FIXME: this is very wrong, but somewhat tricky to fix.
501 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
504 let _x = id![Foo { a: $042 }];
507 pub struct Foo { pub a: i32, pub b: i32 }
514 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
517 let _x = id![Foo { a: 42 }];
520 pub struct Foo { pub a: i32, pub b: i32 }
526 fn test_check_unnecessary_braces_in_use_statement() {
527 check_no_diagnostics(
540 check_no_diagnostics(
598 mod a { mod c {} mod d { mod e {} } }
599 use a::{c, d::{e$0}};
602 mod a { mod c {} mod d { mod e {} } }
609 fn test_disabled_diagnostics() {
610 let mut config = DiagnosticsConfig::default();
611 config.disabled.insert("unresolved-module".into());
613 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
616 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
617 assert!(diagnostics.is_empty());
619 let diagnostics = analysis
620 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
622 assert!(!diagnostics.is_empty());
626 fn unlinked_file_prepend_first_item() {
627 cov_mark::check!(unlinked_file_prepend_before_first_item);
628 // Only tests the first one for `pub mod` since the rest are the same
652 fn unlinked_file_append_mod() {
653 cov_mark::check!(unlinked_file_append_to_existing_mods);
665 mod preexisting_bottom;)
679 mod preexisting_bottom;)
685 fn unlinked_file_insert_in_empty_file() {
686 cov_mark::check!(unlinked_file_empty_file);
700 fn unlinked_file_old_style_modrs() {
718 fn unlinked_file_new_style_mod() {
734 fn unlinked_file_with_cfg_off() {
735 cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
749 fn unlinked_file_with_cfg_on() {
750 check_no_diagnostics(
762 fn break_outside_of_loop() {
766 //^^^^^ break outside of loop
772 fn no_such_field_diagnostics() {
775 struct S { foo: i32, bar: () }
779 //^ Missing structure fields:
783 //^^^^^^^ no such field
791 fn no_such_field_with_feature_flag_diagnostics() {
794 //- /lib.rs crate:foo cfg:feature=foo
797 #[cfg(feature = "foo")]
802 #[cfg(feature = "foo")]
803 pub(crate) fn new(my_val: usize, bar: bool) -> Self {
806 #[cfg(not(feature = "foo"))]
807 pub(crate) fn new(my_val: usize, _bar: bool) -> Self {
816 fn no_such_field_enum_with_feature_flag_diagnostics() {
819 //- /lib.rs crate:foo cfg:feature=foo
821 #[cfg(not(feature = "foo"))]
823 #[cfg(feature = "foo")]
839 fn no_such_field_with_feature_flag_diagnostics_on_struct_lit() {
842 //- /lib.rs crate:foo cfg:feature=foo
844 #[cfg(feature = "foo")]
846 #[cfg(not(feature = "foo"))]
851 #[cfg(feature = "foo")]
852 fn new(foo: u32) -> Self {
855 #[cfg(not(feature = "foo"))]
856 fn new(bar: u32) -> Self {
859 fn new2(bar: u32) -> Self {
860 #[cfg(feature = "foo")]
861 { Self { foo: bar } }
862 #[cfg(not(feature = "foo"))]
865 fn new2(val: u32) -> Self {
867 #[cfg(feature = "foo")]
869 #[cfg(not(feature = "foo"))]
879 fn no_such_field_with_type_macro() {
882 macro_rules! Type { () => { u32 }; }
883 struct Foo { bar: Type![] }
895 fn missing_unsafe_diagnostic_with_raw_ptr() {
899 let x = &5 as *const usize;
900 unsafe { let y = *x; }
902 } //^^ This operation is unsafe and requires an unsafe function or block
908 fn missing_unsafe_diagnostic_with_unsafe_call() {
914 unsafe fn unsafe_fn(&self) {
915 let x = &5 as *const usize;
920 unsafe fn unsafe_fn() {
921 let x = &5 as *const usize;
927 //^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
928 HasUnsafe.unsafe_fn();
929 //^^^^^^^^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
932 HasUnsafe.unsafe_fn();
940 fn missing_unsafe_diagnostic_with_static_mut() {
947 static mut STATIC_MUT: Ty = Ty { a: 0 };
950 let x = STATIC_MUT.a;
951 //^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
953 let x = STATIC_MUT.a;
961 fn no_missing_unsafe_diagnostic_with_safe_intrinsic() {
964 extern "rust-intrinsic" {
965 pub fn bitreverse(x: u32) -> u32; // Safe intrinsic
966 pub fn floorf32(x: f32) -> f32; // Unsafe intrinsic
970 let _ = bitreverse(12);
971 let _ = floorf32(12.0);
972 //^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
978 // Register the required standard library types to make the tests work
979 fn add_filter_map_with_find_next_boilerplate(body: &str) -> String {
981 //- /main.rs crate:main deps:core
982 use core::iter::Iterator;
983 use core::option::Option::{self, Some, None};
986 //- /core/lib.rs crate:core
988 pub enum Option<T> { Some(T), None }
993 fn filter_map<B, F>(self, f: F) -> FilterMap where F: FnMut(Self::Item) -> Option<B> { FilterMap }
994 fn next(&mut self) -> Option<Self::Item>;
996 pub struct FilterMap {}
997 impl Iterator for FilterMap {
999 fn next(&mut self) -> i32 { 7 }
1003 format!("{}{}{}", prefix, body, suffix)
1007 fn replace_filter_map_next_with_find_map2() {
1008 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1011 let m = [1, 2, 3].iter().filter_map(|x| if *x == 2 { Some (4) } else { None }).next();
1012 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ replace filter_map(..).next() with find_map(..)
1019 fn replace_filter_map_next_with_find_map_no_diagnostic_without_next() {
1020 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1025 .filter_map(|x| if *x == 2 { Some (4) } else { None })
1033 fn replace_filter_map_next_with_find_map_no_diagnostic_with_intervening_methods() {
1034 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1039 .filter_map(|x| if *x == 2 { Some (4) } else { None })
1048 fn replace_filter_map_next_with_find_map_no_diagnostic_if_not_in_chain() {
1049 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1054 .filter_map(|x| if *x == 2 { Some (4) } else { None });
1062 fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
1065 struct S { foo: i32, bar: () }
1066 fn baz(s: S) -> i32 {
1068 S { foo, .. } => foo,
1076 fn missing_record_pat_field_box() {
1079 struct S { s: Box<u32> }
1081 let S { box s } = a;
1088 fn missing_record_pat_field_ref() {
1093 let S { ref s } = a;
1100 fn simple_free_fn_zero() {
1105 //^^^^^^^ Expected 0 arguments, found 1
1118 fn simple_free_fn_one() {
1123 //^^^^^ Expected 1 argument, found 0
1140 impl S { fn method(&self) {} }
1144 } //^^^^^^^^^^^ Expected 1 argument, found 0
1151 impl S { fn method(&self) {} }
1162 fn method_with_arg() {
1166 impl S { fn method(&self, arg: u8) {} }
1170 } //^^^^^^^^^^ Expected 1 argument, found 0
1177 impl S { fn method(&self, arg: u8) {} }
1188 fn method_unknown_receiver() {
1189 // note: this is incorrect code, so there might be errors on this in the
1190 // future, but we shouldn't emit an argument count diagnostic here
1193 trait Foo { fn method(&self, arg: usize) {} }
1207 struct Tup(u8, u16);
1210 } //^^^^^^ Expected 2 arguments, found 1
1219 enum En { Variant(u8, u16), }
1222 } //^^^^^^^^^^^^^^ Expected 2 arguments, found 1
1228 fn enum_variant_type_macro() {
1241 //^^^^^^^^^^^^^^ Expected 1 argument, found 2
1243 //^^^^^^^^^^ Expected 1 argument, found 0
1255 fn fixed(fixed: u8);
1256 fn varargs(fixed: u8, ...);
1264 //^^^^^^^^^^^ Expected 1 argument, found 2
1277 fn arg_count_lambda() {
1283 //^^^ Expected 1 argument, found 0
1286 //^^^^^^^^^ Expected 1 argument, found 2
1293 fn cfgd_out_call_arguments() {
1296 struct C(#[cfg(FALSE)] ());
1309 C::new().method(#[cfg(FALSE)] 0);
1316 fn cfgd_out_fn_params() {
1319 fn foo(#[cfg(NEVER)] x: ()) {}
1324 fn method(#[cfg(NEVER)] self) {}
1325 fn method2(#[cfg(NEVER)] self, arg: u8) {}
1326 fn method3(self, #[cfg(NEVER)] arg: u8) {}
1330 fn fixed(fixed: u8, #[cfg(NEVER)] ...);
1331 fn varargs(#[cfg(not(NEVER))] ...);
1350 fn missing_semicolon() {
1353 fn test() -> i32 { 123; }
1354 //^^^ Remove this semicolon
1360 fn import_extern_crate_clash_with_inner_item() {
1361 // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
1365 //- /lib.rs crate:lib deps:jwt
1368 use permissions::jwt;
1372 jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
1377 pub struct Claims {}
1380 //- /jwt/lib.rs crate:jwt
1390 pub(super) mod match_check_tests {
1391 use crate::diagnostics::tests::check_diagnostics;
1399 //^^ Missing match arm
1401 //^^^^ Missing match arm
1403 match () { _ => (), }
1404 match () { () => (), }
1405 match (()) { (()) => (), }
1412 fn tuple_of_two_empty_tuple() {
1417 //^^^^^^^^ Missing match arm
1419 match ((), ()) { ((), ()) => (), }
1431 //^^^^^ Missing match arm
1432 match false { true => (), }
1433 //^^^^^ Missing match arm
1434 match (false, true) {}
1435 //^^^^^^^^^^^^^ Missing match arm
1436 match (false, true) { (true, true) => (), }
1437 //^^^^^^^^^^^^^ Missing match arm
1438 match (false, true) {
1439 //^^^^^^^^^^^^^ Missing match arm
1440 (false, true) => (),
1441 (false, false) => (),
1442 (true, false) => (),
1444 match (false, true) { (true, _x) => (), }
1445 //^^^^^^^^^^^^^ Missing match arm
1447 match false { true => (), false => (), }
1448 match (false, true) {
1450 (true, false) => (),
1453 match (false, true) {
1455 (true, false) => (),
1456 (false, true) => (),
1457 (false, false) => (),
1459 match (false, true) {
1461 (false, true) => (),
1462 (false, false) => (),
1464 match (false, true, false) {
1468 match (false, true, false) {
1472 match (false, true, false) { (..) => (), }
1479 fn tuple_of_tuple_and_bools() {
1483 match (false, ((), false)) {}
1484 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1485 match (false, ((), false)) { (true, ((), true)) => (), }
1486 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1487 match (false, ((), false)) { (true, _) => (), }
1488 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1490 match (false, ((), false)) {
1491 (true, ((), true)) => (),
1492 (true, ((), false)) => (),
1493 (false, ((), true)) => (),
1494 (false, ((), false)) => (),
1496 match (false, ((), false)) {
1497 (true, ((), true)) => (),
1498 (true, ((), false)) => (),
1510 enum Either { A, B, }
1514 //^^^^^^^^^ Missing match arm
1515 match Either::B { Either::A => (), }
1516 //^^^^^^^^^ Missing match arm
1519 //^^^^^^^^^^ Missing match arm
1524 Either::A => (), Either::B => (),
1527 Either::A => (), Either::B => (),
1535 fn enum_containing_bool() {
1538 enum Either { A(bool), B }
1542 //^^^^^^^^^ Missing match arm
1544 //^^^^^^^^^ Missing match arm
1545 Either::A(true) => (), Either::B => ()
1549 Either::A(true) => (),
1550 Either::A(false) => (),
1568 fn enum_different_sizes() {
1571 enum Either { A(bool), B(bool, bool) }
1574 match Either::A(false) {
1575 //^^^^^^^^^^^^^^^^ Missing match arm
1577 Either::B(false, _) => (),
1580 match Either::A(false) {
1582 Either::B(true, _) => (),
1583 Either::B(false, _) => (),
1585 match Either::A(false) {
1586 Either::A(true) | Either::A(false) => (),
1587 Either::B(true, _) => (),
1588 Either::B(false, _) => (),
1596 fn tuple_of_enum_no_diagnostic() {
1599 enum Either { A(bool), B(bool, bool) }
1600 enum Either2 { C, D }
1603 match (Either::A(false), Either2::C) {
1604 (Either::A(true), _) | (Either::A(false), _) => (),
1605 (Either::B(true, _), Either2::C) => (),
1606 (Either::B(false, _), Either2::C) => (),
1607 (Either::B(_, _), Either2::D) => (),
1615 fn or_pattern_no_diagnostic() {
1621 match (Either::A, Either::B) {
1622 (Either::A | Either::B, _) => (),
1629 fn mismatched_types() {
1630 // Match statements with arms that don't match the
1631 // expression pattern do not fire this diagnostic.
1634 enum Either { A, B }
1635 enum Either2 { C, D }
1640 // ^^^^^^^^^^ Internal: match check bailed out
1643 match (true, false) {
1644 (true, false, true) => (),
1645 // ^^^^^^^^^^^^^^^^^^^ Internal: match check bailed out
1648 match (true, false) { (true,) => {} }
1649 // ^^^^^^^ Internal: match check bailed out
1650 match (0) { () => () }
1651 // ^^ Internal: match check bailed out
1652 match Unresolved::Bar { Unresolved::Baz => () }
1659 fn mismatched_types_in_or_patterns() {
1663 match false { true | () => {} }
1664 // ^^^^^^^^^ Internal: match check bailed out
1665 match (false,) { (true | (),) => {} }
1666 // ^^^^^^^^^^^^ Internal: match check bailed out
1673 fn malformed_match_arm_tuple_enum_missing_pattern() {
1674 // We are testing to be sure we don't panic here when the match
1675 // arm `Either::B` is missing its pattern.
1678 enum Either { A, B(u32) }
1691 fn malformed_match_arm_extra_fields() {
1694 enum A { B(isize, isize), C }
1697 A::B(_, _, _) => (),
1698 // ^^^^^^^^^^^^^ Internal: match check bailed out
1702 // ^^^^^^^ Internal: match check bailed out
1710 fn expr_diverges() {
1713 enum Either { A, B }
1718 // ^^^^^^^^^ Internal: match check bailed out
1723 // ^^^^^^^^^ Internal: match check bailed out
1725 match loop { break Foo::A } {
1726 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1729 match loop { break Foo::A } {
1739 fn expr_partially_diverges() {
1742 enum Either<T> { A(T), B }
1744 fn foo() -> Either<!> { Either::B }
1747 Either::A(val) => val,
1759 enum Either { A { foo: bool }, B }
1762 let a = Either::A { foo: true };
1764 //^ Missing match arm
1765 match a { Either::A { foo: true } => () }
1766 //^ Missing match arm
1768 Either::A { } => (),
1769 //^^^^^^^^^ Missing structure fields:
1774 //^ Missing match arm
1775 Either::A { } => (),
1776 } //^^^^^^^^^ Missing structure fields:
1780 Either::A { foo: true } => (),
1781 Either::A { foo: false } => (),
1785 Either::A { foo: _ } => (),
1794 fn enum_record_fields_out_of_order() {
1798 A { foo: bool, bar: () },
1803 let a = Either::A { foo: true, bar: () };
1805 //^ Missing match arm
1806 Either::A { bar: (), foo: false } => (),
1807 Either::A { foo: true, bar: () } => (),
1811 Either::A { bar: (), foo: false } => (),
1812 Either::A { foo: true, bar: () } => (),
1821 fn enum_record_ellipsis() {
1825 A { foo: bool, bar: bool },
1832 //^ Missing match arm
1833 Either::A { foo: true, .. } => (),
1837 //^ Missing match arm
1838 Either::A { .. } => (),
1842 Either::A { foo: true, .. } => (),
1843 Either::A { foo: false, .. } => (),
1848 Either::A { .. } => (),
1857 fn enum_tuple_partial_ellipsis() {
1861 A(bool, bool, bool, bool),
1867 //^^^^^^^^^ Missing match arm
1868 Either::A(true, .., true) => (),
1869 Either::A(true, .., false) => (),
1870 Either::A(false, .., false) => (),
1874 //^^^^^^^^^ Missing match arm
1875 Either::A(true, .., true) => (),
1876 Either::A(true, .., false) => (),
1877 Either::A(.., true) => (),
1882 Either::A(true, .., true) => (),
1883 Either::A(true, .., false) => (),
1884 Either::A(false, .., true) => (),
1885 Either::A(false, .., false) => (),
1889 Either::A(true, .., true) => (),
1890 Either::A(true, .., false) => (),
1891 Either::A(.., true) => (),
1892 Either::A(.., false) => (),
1906 fn enum_(never: Never) {
1909 fn enum_ref(never: &Never) {
1911 //^^^^^ Missing match arm
1924 enum Option<T> { Some(T), None }
1927 // `Never` is deliberately not defined so that it's an uninferred type.
1928 match Option::<Never>::None {
1930 Some(never) => match never {},
1931 // ^^^^^^^^^^^ Internal: match check bailed out
1933 match Option::<Never>::None {
1934 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1935 Option::Some(_never) => {},
1943 fn tuple_of_bools_with_ellipsis_at_end_missing_arm() {
1947 match (false, true, false) {
1948 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1956 fn tuple_of_bools_with_ellipsis_at_beginning_missing_arm() {
1960 match (false, true, false) {
1961 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1969 fn tuple_of_bools_with_ellipsis_in_middle_missing_arm() {
1973 match (false, true, false) {
1974 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1975 (true, .., false) => (),
1982 fn record_struct() {
1984 r#"struct Foo { a: bool }
1987 //^ Missing match arm
1988 match f { Foo { a: true } => () }
1989 //^ Missing match arm
1990 match &f { Foo { a: true } => () }
1991 //^^ Missing match arm
1992 match f { Foo { a: _ } => () }
1994 Foo { a: true } => (),
1995 Foo { a: false } => (),
1998 Foo { a: true } => (),
1999 Foo { a: false } => (),
2009 r#"struct Foo(bool);
2012 //^ Missing match arm
2013 match f { Foo(true) => () }
2014 //^ Missing match arm
2030 //^ Missing match arm
2031 match f { Foo => () }
2038 fn record_struct_ellipsis() {
2040 r#"struct Foo { foo: bool, bar: bool }
2042 match f { Foo { foo: true, .. } => () }
2043 //^ Missing match arm
2045 //^ Missing match arm
2046 Foo { foo: true, .. } => (),
2047 Foo { bar: false, .. } => ()
2049 match f { Foo { .. } => () }
2051 Foo { foo: true, .. } => (),
2052 Foo { foo: false, .. } => ()
2064 enum Either { A(bool), B }
2066 //^^^^^^^^^ Missing match arm
2067 Either::A(true | false) => (),
2075 fn no_panic_at_unimplemented_subpattern_type() {
2080 match v { S{ a } => {} }
2081 match v { S{ a: _x } => {} }
2082 match v { S{ a: 'a' } => {} }
2083 //^^^^^^^^^^^ Internal: match check bailed out
2084 match v { S{..} => {} }
2087 //^ Missing match arm
2102 match true { _x @ true => {} }
2103 //^^^^ Missing match arm
2110 fn binding_ref_has_correct_type() {
2111 // Asserts `PatKind::Binding(ref _x): bool`, not &bool.
2112 // If that's not true match checking will panic with "incompatible constructors"
2113 // FIXME: make facilities to test this directly like `tests::check_infer(..)`
2118 // FIXME: this should not bail out but current behavior is such as the old algorithm.
2119 // ExprValidator::validate_match(..) checks types of top level patterns incorrecly.
2122 // ^^^^^^ Internal: match check bailed out
2135 fn enum_non_exhaustive() {
2138 //- /lib.rs crate:lib
2142 match E::A { _ => {} }
2152 //- /main.rs crate:main deps:lib
2155 match E::A { _ => {} }
2157 //^^^^ Missing match arm
2162 //^^^^ Missing match arm
2181 //^^^^ Missing match arm
2191 fn pattern_type_is_of_substitution() {
2192 cov_mark::check!(match_check_wildcard_expanded_to_substitutions);
2207 fn record_struct_no_such_field() {
2212 match f { Foo { bar } => () }
2213 // ^^^^^^^^^^^ Internal: match check bailed out
2220 fn match_ergonomics_issue_9095() {
2223 enum Foo<T> { A(T) }
2225 match &Foo::A(true) {
2234 mod false_negatives {
2235 //! The implementation of match checking here is a work in progress. As we roll this out, we
2236 //! prefer false negatives to false positives (ideally there would be no false positives). This
2237 //! test module should document known false negatives. Eventually we will have a complete
2238 //! implementation of match checking and this module will be empty.
2240 //! The reasons for documenting known false negatives:
2242 //! 1. It acts as a backlog of work that can be done to improve the behavior of the system.
2243 //! 2. It ensures the code doesn't panic when handling these cases.
2248 // We don't currently check integer exhaustiveness.
2254 // ^^ Internal: match check bailed out
2263 fn reference_patterns_at_top_level() {
2269 // ^^^^^ Internal: match check bailed out
2277 fn reference_patterns_in_fields() {
2283 // ^^^^^^^ Internal: match check bailed out
2287 // ^^^^^^^^ Internal: match check bailed out
2297 mod decl_check_tests {
2298 use crate::diagnostics::tests::check_diagnostics;
2301 fn incorrect_function_name() {
2304 fn NonSnakeCaseName() {}
2305 // ^^^^^^^^^^^^^^^^ Function `NonSnakeCaseName` should have snake_case name, e.g. `non_snake_case_name`
2311 fn incorrect_function_params() {
2314 fn foo(SomeParam: u8) {}
2315 // ^^^^^^^^^ Parameter `SomeParam` should have snake_case name, e.g. `some_param`
2317 fn foo2(ok_param: &str, CAPS_PARAM: u8) {}
2318 // ^^^^^^^^^^ Parameter `CAPS_PARAM` should have snake_case name, e.g. `caps_param`
2324 fn incorrect_variable_names() {
2328 let SOME_VALUE = 10;
2329 // ^^^^^^^^^^ Variable `SOME_VALUE` should have snake_case name, e.g. `some_value`
2330 let AnotherValue = 20;
2331 // ^^^^^^^^^^^^ Variable `AnotherValue` should have snake_case name, e.g. `another_value`
2338 fn incorrect_struct_names() {
2341 struct non_camel_case_name {}
2342 // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName`
2344 struct SCREAMING_CASE {}
2345 // ^^^^^^^^^^^^^^ Structure `SCREAMING_CASE` should have CamelCase name, e.g. `ScreamingCase`
2351 fn no_diagnostic_for_camel_cased_acronyms_in_struct_name() {
2360 fn incorrect_struct_field() {
2363 struct SomeStruct { SomeField: u8 }
2364 // ^^^^^^^^^ Field `SomeField` should have snake_case name, e.g. `some_field`
2370 fn incorrect_enum_names() {
2373 enum some_enum { Val(u8) }
2374 // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum`
2377 // ^^^^^^^^^ Enum `SOME_ENUM` should have CamelCase name, e.g. `SomeEnum`
2383 fn no_diagnostic_for_camel_cased_acronyms_in_enum_name() {
2392 fn incorrect_enum_variant_name() {
2395 enum SomeEnum { SOME_VARIANT(u8) }
2396 // ^^^^^^^^^^^^ Variant `SOME_VARIANT` should have CamelCase name, e.g. `SomeVariant`
2402 fn incorrect_const_name() {
2405 const some_weird_const: u8 = 10;
2406 // ^^^^^^^^^^^^^^^^ Constant `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2412 fn incorrect_static_name() {
2415 static some_weird_const: u8 = 10;
2416 // ^^^^^^^^^^^^^^^^ Static variable `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2422 fn fn_inside_impl_struct() {
2426 // ^^^^^^^^^^ Structure `someStruct` should have CamelCase name, e.g. `SomeStruct`
2429 fn SomeFunc(&self) {
2430 // ^^^^^^^^ Function `SomeFunc` should have snake_case name, e.g. `some_func`
2431 let WHY_VAR_IS_CAPS = 10;
2432 // ^^^^^^^^^^^^^^^ Variable `WHY_VAR_IS_CAPS` should have snake_case name, e.g. `why_var_is_caps`
2440 fn no_diagnostic_for_enum_varinats() {
2443 enum Option { Some, None }
2446 match Option::None {
2459 enum Option { Some, None }
2462 match Option::None {
2463 SOME_VAR @ None => (),
2464 // ^^^^^^^^ Variable `SOME_VAR` should have snake_case name, e.g. `some_var`
2473 fn allow_attributes() {
2476 #[allow(non_snake_case)]
2477 fn NonSnakeCaseName(SOME_VAR: u8) -> u8{
2478 // cov_flags generated output from elsewhere in this file
2481 static lower_case: u8;
2484 let OtherVar = SOME_VAR + 1;
2488 #[allow(nonstandard_style)]
2489 mod CheckNonstandardStyle {
2490 fn HiImABadFnName() {}
2495 fn HiImABadFnName() {}
2499 #![allow(non_snake_case)]
2500 fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {}
2503 #[allow(non_snake_case, non_camel_case_types)]
2504 pub struct some_type {
2509 #[allow(non_upper_case_globals)]
2510 pub const some_const: u8 = 10;
2512 #[allow(non_upper_case_globals)]
2513 pub static SomeStatic: u8 = 10;
2519 fn allow_attributes_crate_attr() {
2522 #![allow(non_snake_case)]
2525 fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {}
2533 fn bug_trait_inside_fn() {
2535 // This is broken, and in fact, should not even be looked at by this
2536 // lint in the first place. There's weird stuff going on in the
2537 // collection phase.
2538 // It's currently being brought in by:
2539 // * validate_func on `a` recursing into modules
2540 // * then it finds the trait and then the function while iterating
2542 // * then validate_func is called on Dirty
2543 // * ... which then proceeds to look at some unknown module taking no
2544 // attrs from either the impl or the fn a, and then finally to the root
2547 // It should find the attribute on the trait, but it *doesn't even see
2548 // the trait* as far as I can tell.
2556 // this comes out of bitflags, mostly
2557 #[allow(non_snake_case)]
2559 const HiImAlsoBad: u8 = 2;
2561 fn Dirty(&self) -> bool {
2574 fn bug_traits_arent_checked() {
2575 // FIXME: Traits and functions in traits aren't currently checked by
2576 // r-a, even though rustc will complain about them.
2580 // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait`
2582 // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function`
2584 // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function`
2591 fn ignores_extern_items() {
2592 cov_mark::check!(extern_func_incorrect_case_ignored);
2593 cov_mark::check!(extern_static_incorrect_case_ignored);
2597 fn NonSnakeCaseName(SOME_VAR: u8) -> u8;
2598 pub static SomeStatic: u8 = 10;
2605 fn infinite_loop_inner_items() {
2617 #[test] // Issue #8809.
2618 fn parenthesized_parameter() {
2619 check_diagnostics(r#"fn f((O): _) {}"#)