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_no_diagnostic_if_not_exhaustive() {
1062 struct S { foo: i32, bar: () }
1063 fn baz(s: S) -> i32 {
1065 S { foo, .. } => foo,
1073 fn missing_record_pat_field_box() {
1076 struct S { s: Box<u32> }
1078 let S { box s } = a;
1085 fn missing_record_pat_field_ref() {
1090 let S { ref s } = a;
1097 fn simple_free_fn_zero() {
1102 //^^^^^^^ Expected 0 arguments, found 1
1115 fn simple_free_fn_one() {
1120 //^^^^^ Expected 1 argument, found 0
1137 impl S { fn method(&self) {} }
1141 } //^^^^^^^^^^^ Expected 1 argument, found 0
1148 impl S { fn method(&self) {} }
1159 fn method_with_arg() {
1163 impl S { fn method(&self, arg: u8) {} }
1167 } //^^^^^^^^^^ Expected 1 argument, found 0
1174 impl S { fn method(&self, arg: u8) {} }
1185 fn method_unknown_receiver() {
1186 // note: this is incorrect code, so there might be errors on this in the
1187 // future, but we shouldn't emit an argument count diagnostic here
1190 trait Foo { fn method(&self, arg: usize) {} }
1204 struct Tup(u8, u16);
1207 } //^^^^^^ Expected 2 arguments, found 1
1216 enum En { Variant(u8, u16), }
1219 } //^^^^^^^^^^^^^^ Expected 2 arguments, found 1
1225 fn enum_variant_type_macro() {
1238 //^^^^^^^^^^^^^^ Expected 1 argument, found 2
1240 //^^^^^^^^^^ Expected 1 argument, found 0
1252 fn fixed(fixed: u8);
1253 fn varargs(fixed: u8, ...);
1261 //^^^^^^^^^^^ Expected 1 argument, found 2
1274 fn arg_count_lambda() {
1280 //^^^ Expected 1 argument, found 0
1283 //^^^^^^^^^ Expected 1 argument, found 2
1290 fn cfgd_out_call_arguments() {
1293 struct C(#[cfg(FALSE)] ());
1306 C::new().method(#[cfg(FALSE)] 0);
1313 fn cfgd_out_fn_params() {
1316 fn foo(#[cfg(NEVER)] x: ()) {}
1321 fn method(#[cfg(NEVER)] self) {}
1322 fn method2(#[cfg(NEVER)] self, arg: u8) {}
1323 fn method3(self, #[cfg(NEVER)] arg: u8) {}
1327 fn fixed(fixed: u8, #[cfg(NEVER)] ...);
1328 fn varargs(#[cfg(not(NEVER))] ...);
1347 fn missing_semicolon() {
1350 fn test() -> i32 { 123; }
1351 //^^^ Remove this semicolon
1357 fn import_extern_crate_clash_with_inner_item() {
1358 // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
1362 //- /lib.rs crate:lib deps:jwt
1365 use permissions::jwt;
1369 jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
1374 pub struct Claims {}
1377 //- /jwt/lib.rs crate:jwt
1387 pub(super) mod match_check_tests {
1388 use crate::diagnostics::tests::check_diagnostics;
1396 //^^ Missing match arm
1398 //^^^^ Missing match arm
1400 match () { _ => (), }
1401 match () { () => (), }
1402 match (()) { (()) => (), }
1409 fn tuple_of_two_empty_tuple() {
1414 //^^^^^^^^ Missing match arm
1416 match ((), ()) { ((), ()) => (), }
1428 //^^^^^ Missing match arm
1429 match false { true => (), }
1430 //^^^^^ Missing match arm
1431 match (false, true) {}
1432 //^^^^^^^^^^^^^ Missing match arm
1433 match (false, true) { (true, true) => (), }
1434 //^^^^^^^^^^^^^ Missing match arm
1435 match (false, true) {
1436 //^^^^^^^^^^^^^ Missing match arm
1437 (false, true) => (),
1438 (false, false) => (),
1439 (true, false) => (),
1441 match (false, true) { (true, _x) => (), }
1442 //^^^^^^^^^^^^^ Missing match arm
1444 match false { true => (), false => (), }
1445 match (false, true) {
1447 (true, false) => (),
1450 match (false, true) {
1452 (true, false) => (),
1453 (false, true) => (),
1454 (false, false) => (),
1456 match (false, true) {
1458 (false, true) => (),
1459 (false, false) => (),
1461 match (false, true, false) {
1465 match (false, true, false) {
1469 match (false, true, false) { (..) => (), }
1476 fn tuple_of_tuple_and_bools() {
1480 match (false, ((), false)) {}
1481 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1482 match (false, ((), false)) { (true, ((), true)) => (), }
1483 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1484 match (false, ((), false)) { (true, _) => (), }
1485 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1487 match (false, ((), false)) {
1488 (true, ((), true)) => (),
1489 (true, ((), false)) => (),
1490 (false, ((), true)) => (),
1491 (false, ((), false)) => (),
1493 match (false, ((), false)) {
1494 (true, ((), true)) => (),
1495 (true, ((), false)) => (),
1507 enum Either { A, B, }
1511 //^^^^^^^^^ Missing match arm
1512 match Either::B { Either::A => (), }
1513 //^^^^^^^^^ Missing match arm
1516 //^^^^^^^^^^ Missing match arm
1521 Either::A => (), Either::B => (),
1524 Either::A => (), Either::B => (),
1532 fn enum_containing_bool() {
1535 enum Either { A(bool), B }
1539 //^^^^^^^^^ Missing match arm
1541 //^^^^^^^^^ Missing match arm
1542 Either::A(true) => (), Either::B => ()
1546 Either::A(true) => (),
1547 Either::A(false) => (),
1565 fn enum_different_sizes() {
1568 enum Either { A(bool), B(bool, bool) }
1571 match Either::A(false) {
1572 //^^^^^^^^^^^^^^^^ Missing match arm
1574 Either::B(false, _) => (),
1577 match Either::A(false) {
1579 Either::B(true, _) => (),
1580 Either::B(false, _) => (),
1582 match Either::A(false) {
1583 Either::A(true) | Either::A(false) => (),
1584 Either::B(true, _) => (),
1585 Either::B(false, _) => (),
1593 fn tuple_of_enum_no_diagnostic() {
1596 enum Either { A(bool), B(bool, bool) }
1597 enum Either2 { C, D }
1600 match (Either::A(false), Either2::C) {
1601 (Either::A(true), _) | (Either::A(false), _) => (),
1602 (Either::B(true, _), Either2::C) => (),
1603 (Either::B(false, _), Either2::C) => (),
1604 (Either::B(_, _), Either2::D) => (),
1612 fn or_pattern_no_diagnostic() {
1618 match (Either::A, Either::B) {
1619 (Either::A | Either::B, _) => (),
1626 fn mismatched_types() {
1627 // Match statements with arms that don't match the
1628 // expression pattern do not fire this diagnostic.
1631 enum Either { A, B }
1632 enum Either2 { C, D }
1637 // ^^^^^^^^^^ Internal: match check bailed out
1640 match (true, false) {
1641 (true, false, true) => (),
1642 // ^^^^^^^^^^^^^^^^^^^ Internal: match check bailed out
1645 match (true, false) { (true,) => {} }
1646 // ^^^^^^^ Internal: match check bailed out
1647 match (0) { () => () }
1648 // ^^ Internal: match check bailed out
1649 match Unresolved::Bar { Unresolved::Baz => () }
1656 fn mismatched_types_in_or_patterns() {
1660 match false { true | () => {} }
1661 // ^^^^^^^^^ Internal: match check bailed out
1662 match (false,) { (true | (),) => {} }
1663 // ^^^^^^^^^^^^ Internal: match check bailed out
1670 fn malformed_match_arm_tuple_enum_missing_pattern() {
1671 // We are testing to be sure we don't panic here when the match
1672 // arm `Either::B` is missing its pattern.
1675 enum Either { A, B(u32) }
1688 fn malformed_match_arm_extra_fields() {
1691 enum A { B(isize, isize), C }
1694 A::B(_, _, _) => (),
1695 // ^^^^^^^^^^^^^ Internal: match check bailed out
1699 // ^^^^^^^ Internal: match check bailed out
1707 fn expr_diverges() {
1710 enum Either { A, B }
1715 // ^^^^^^^^^ Internal: match check bailed out
1720 // ^^^^^^^^^ Internal: match check bailed out
1722 match loop { break Foo::A } {
1723 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1726 match loop { break Foo::A } {
1736 fn expr_partially_diverges() {
1739 enum Either<T> { A(T), B }
1741 fn foo() -> Either<!> { Either::B }
1744 Either::A(val) => val,
1756 enum Either { A { foo: bool }, B }
1759 let a = Either::A { foo: true };
1761 //^ Missing match arm
1762 match a { Either::A { foo: true } => () }
1763 //^ Missing match arm
1765 Either::A { } => (),
1766 //^^^^^^^^^ Missing structure fields:
1771 //^ Missing match arm
1772 Either::A { } => (),
1773 } //^^^^^^^^^ Missing structure fields:
1777 Either::A { foo: true } => (),
1778 Either::A { foo: false } => (),
1782 Either::A { foo: _ } => (),
1791 fn enum_record_fields_out_of_order() {
1795 A { foo: bool, bar: () },
1800 let a = Either::A { foo: true, bar: () };
1802 //^ Missing match arm
1803 Either::A { bar: (), foo: false } => (),
1804 Either::A { foo: true, bar: () } => (),
1808 Either::A { bar: (), foo: false } => (),
1809 Either::A { foo: true, bar: () } => (),
1818 fn enum_record_ellipsis() {
1822 A { foo: bool, bar: bool },
1829 //^ Missing match arm
1830 Either::A { foo: true, .. } => (),
1834 //^ Missing match arm
1835 Either::A { .. } => (),
1839 Either::A { foo: true, .. } => (),
1840 Either::A { foo: false, .. } => (),
1845 Either::A { .. } => (),
1854 fn enum_tuple_partial_ellipsis() {
1858 A(bool, bool, bool, bool),
1864 //^^^^^^^^^ Missing match arm
1865 Either::A(true, .., true) => (),
1866 Either::A(true, .., false) => (),
1867 Either::A(false, .., false) => (),
1871 //^^^^^^^^^ Missing match arm
1872 Either::A(true, .., true) => (),
1873 Either::A(true, .., false) => (),
1874 Either::A(.., true) => (),
1879 Either::A(true, .., true) => (),
1880 Either::A(true, .., false) => (),
1881 Either::A(false, .., true) => (),
1882 Either::A(false, .., false) => (),
1886 Either::A(true, .., true) => (),
1887 Either::A(true, .., false) => (),
1888 Either::A(.., true) => (),
1889 Either::A(.., false) => (),
1903 fn enum_(never: Never) {
1906 fn enum_ref(never: &Never) {
1908 //^^^^^ Missing match arm
1921 enum Option<T> { Some(T), None }
1924 // `Never` is deliberately not defined so that it's an uninferred type.
1925 match Option::<Never>::None {
1927 Some(never) => match never {},
1928 // ^^^^^^^^^^^ Internal: match check bailed out
1930 match Option::<Never>::None {
1931 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1932 Option::Some(_never) => {},
1940 fn tuple_of_bools_with_ellipsis_at_end_missing_arm() {
1944 match (false, true, false) {
1945 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1953 fn tuple_of_bools_with_ellipsis_at_beginning_missing_arm() {
1957 match (false, true, false) {
1958 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1966 fn tuple_of_bools_with_ellipsis_in_middle_missing_arm() {
1970 match (false, true, false) {
1971 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1972 (true, .., false) => (),
1979 fn record_struct() {
1981 r#"struct Foo { a: bool }
1984 //^ Missing match arm
1985 match f { Foo { a: true } => () }
1986 //^ Missing match arm
1987 match &f { Foo { a: true } => () }
1988 //^^ Missing match arm
1989 match f { Foo { a: _ } => () }
1991 Foo { a: true } => (),
1992 Foo { a: false } => (),
1995 Foo { a: true } => (),
1996 Foo { a: false } => (),
2006 r#"struct Foo(bool);
2009 //^ Missing match arm
2010 match f { Foo(true) => () }
2011 //^ Missing match arm
2027 //^ Missing match arm
2028 match f { Foo => () }
2035 fn record_struct_ellipsis() {
2037 r#"struct Foo { foo: bool, bar: bool }
2039 match f { Foo { foo: true, .. } => () }
2040 //^ Missing match arm
2042 //^ Missing match arm
2043 Foo { foo: true, .. } => (),
2044 Foo { bar: false, .. } => ()
2046 match f { Foo { .. } => () }
2048 Foo { foo: true, .. } => (),
2049 Foo { foo: false, .. } => ()
2061 enum Either { A(bool), B }
2063 //^^^^^^^^^ Missing match arm
2064 Either::A(true | false) => (),
2072 fn no_panic_at_unimplemented_subpattern_type() {
2077 match v { S{ a } => {} }
2078 match v { S{ a: _x } => {} }
2079 match v { S{ a: 'a' } => {} }
2080 //^^^^^^^^^^^ Internal: match check bailed out
2081 match v { S{..} => {} }
2084 //^ Missing match arm
2099 match true { _x @ true => {} }
2100 //^^^^ Missing match arm
2107 fn binding_ref_has_correct_type() {
2108 // Asserts `PatKind::Binding(ref _x): bool`, not &bool.
2109 // If that's not true match checking will panic with "incompatible constructors"
2110 // FIXME: make facilities to test this directly like `tests::check_infer(..)`
2115 // FIXME: this should not bail out but current behavior is such as the old algorithm.
2116 // ExprValidator::validate_match(..) checks types of top level patterns incorrecly.
2119 // ^^^^^^ Internal: match check bailed out
2132 fn enum_non_exhaustive() {
2135 //- /lib.rs crate:lib
2139 match E::A { _ => {} }
2149 //- /main.rs crate:main deps:lib
2152 match E::A { _ => {} }
2154 //^^^^ Missing match arm
2159 //^^^^ Missing match arm
2178 //^^^^ Missing match arm
2188 fn pattern_type_is_of_substitution() {
2189 cov_mark::check!(match_check_wildcard_expanded_to_substitutions);
2204 fn record_struct_no_such_field() {
2209 match f { Foo { bar } => () }
2210 // ^^^^^^^^^^^ Internal: match check bailed out
2217 fn match_ergonomics_issue_9095() {
2220 enum Foo<T> { A(T) }
2222 match &Foo::A(true) {
2231 mod false_negatives {
2232 //! The implementation of match checking here is a work in progress. As we roll this out, we
2233 //! prefer false negatives to false positives (ideally there would be no false positives). This
2234 //! test module should document known false negatives. Eventually we will have a complete
2235 //! implementation of match checking and this module will be empty.
2237 //! The reasons for documenting known false negatives:
2239 //! 1. It acts as a backlog of work that can be done to improve the behavior of the system.
2240 //! 2. It ensures the code doesn't panic when handling these cases.
2245 // We don't currently check integer exhaustiveness.
2251 // ^^ Internal: match check bailed out
2260 fn reference_patterns_at_top_level() {
2266 // ^^^^^ Internal: match check bailed out
2274 fn reference_patterns_in_fields() {
2280 // ^^^^^^^ Internal: match check bailed out
2284 // ^^^^^^^^ Internal: match check bailed out
2294 mod decl_check_tests {
2295 use crate::diagnostics::tests::check_diagnostics;
2298 fn incorrect_function_name() {
2301 fn NonSnakeCaseName() {}
2302 // ^^^^^^^^^^^^^^^^ Function `NonSnakeCaseName` should have snake_case name, e.g. `non_snake_case_name`
2308 fn incorrect_function_params() {
2311 fn foo(SomeParam: u8) {}
2312 // ^^^^^^^^^ Parameter `SomeParam` should have snake_case name, e.g. `some_param`
2314 fn foo2(ok_param: &str, CAPS_PARAM: u8) {}
2315 // ^^^^^^^^^^ Parameter `CAPS_PARAM` should have snake_case name, e.g. `caps_param`
2321 fn incorrect_variable_names() {
2325 let SOME_VALUE = 10;
2326 // ^^^^^^^^^^ Variable `SOME_VALUE` should have snake_case name, e.g. `some_value`
2327 let AnotherValue = 20;
2328 // ^^^^^^^^^^^^ Variable `AnotherValue` should have snake_case name, e.g. `another_value`
2335 fn incorrect_struct_names() {
2338 struct non_camel_case_name {}
2339 // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName`
2341 struct SCREAMING_CASE {}
2342 // ^^^^^^^^^^^^^^ Structure `SCREAMING_CASE` should have CamelCase name, e.g. `ScreamingCase`
2348 fn no_diagnostic_for_camel_cased_acronyms_in_struct_name() {
2357 fn incorrect_struct_field() {
2360 struct SomeStruct { SomeField: u8 }
2361 // ^^^^^^^^^ Field `SomeField` should have snake_case name, e.g. `some_field`
2367 fn incorrect_enum_names() {
2370 enum some_enum { Val(u8) }
2371 // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum`
2374 // ^^^^^^^^^ Enum `SOME_ENUM` should have CamelCase name, e.g. `SomeEnum`
2380 fn no_diagnostic_for_camel_cased_acronyms_in_enum_name() {
2389 fn incorrect_enum_variant_name() {
2392 enum SomeEnum { SOME_VARIANT(u8) }
2393 // ^^^^^^^^^^^^ Variant `SOME_VARIANT` should have CamelCase name, e.g. `SomeVariant`
2399 fn incorrect_const_name() {
2402 const some_weird_const: u8 = 10;
2403 // ^^^^^^^^^^^^^^^^ Constant `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2409 fn incorrect_static_name() {
2412 static some_weird_const: u8 = 10;
2413 // ^^^^^^^^^^^^^^^^ Static variable `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2419 fn fn_inside_impl_struct() {
2423 // ^^^^^^^^^^ Structure `someStruct` should have CamelCase name, e.g. `SomeStruct`
2426 fn SomeFunc(&self) {
2427 // ^^^^^^^^ Function `SomeFunc` should have snake_case name, e.g. `some_func`
2428 let WHY_VAR_IS_CAPS = 10;
2429 // ^^^^^^^^^^^^^^^ Variable `WHY_VAR_IS_CAPS` should have snake_case name, e.g. `why_var_is_caps`
2437 fn no_diagnostic_for_enum_varinats() {
2440 enum Option { Some, None }
2443 match Option::None {
2456 enum Option { Some, None }
2459 match Option::None {
2460 SOME_VAR @ None => (),
2461 // ^^^^^^^^ Variable `SOME_VAR` should have snake_case name, e.g. `some_var`
2470 fn allow_attributes() {
2473 #[allow(non_snake_case)]
2474 fn NonSnakeCaseName(SOME_VAR: u8) -> u8{
2475 // cov_flags generated output from elsewhere in this file
2478 static lower_case: u8;
2481 let OtherVar = SOME_VAR + 1;
2485 #[allow(nonstandard_style)]
2486 mod CheckNonstandardStyle {
2487 fn HiImABadFnName() {}
2492 fn HiImABadFnName() {}
2496 #![allow(non_snake_case)]
2497 fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {}
2500 #[allow(non_snake_case, non_camel_case_types)]
2501 pub struct some_type {
2506 #[allow(non_upper_case_globals)]
2507 pub const some_const: u8 = 10;
2509 #[allow(non_upper_case_globals)]
2510 pub static SomeStatic: u8 = 10;
2516 fn allow_attributes_crate_attr() {
2519 #![allow(non_snake_case)]
2522 fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {}
2530 fn bug_trait_inside_fn() {
2532 // This is broken, and in fact, should not even be looked at by this
2533 // lint in the first place. There's weird stuff going on in the
2534 // collection phase.
2535 // It's currently being brought in by:
2536 // * validate_func on `a` recursing into modules
2537 // * then it finds the trait and then the function while iterating
2539 // * then validate_func is called on Dirty
2540 // * ... which then proceeds to look at some unknown module taking no
2541 // attrs from either the impl or the fn a, and then finally to the root
2544 // It should find the attribute on the trait, but it *doesn't even see
2545 // the trait* as far as I can tell.
2553 // this comes out of bitflags, mostly
2554 #[allow(non_snake_case)]
2556 const HiImAlsoBad: u8 = 2;
2558 fn Dirty(&self) -> bool {
2571 fn bug_traits_arent_checked() {
2572 // FIXME: Traits and functions in traits aren't currently checked by
2573 // r-a, even though rustc will complain about them.
2577 // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait`
2579 // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function`
2581 // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function`
2588 fn ignores_extern_items() {
2589 cov_mark::check!(extern_func_incorrect_case_ignored);
2590 cov_mark::check!(extern_static_incorrect_case_ignored);
2594 fn NonSnakeCaseName(SOME_VAR: u8) -> u8;
2595 pub static SomeStatic: u8 = 10;
2602 fn infinite_loop_inner_items() {
2614 #[test] // Issue #8809.
2615 fn parenthesized_parameter() {
2616 check_diagnostics(r#"fn f((O): _) {}"#)