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.
7 mod break_outside_of_loop;
10 mod mismatched_arg_count;
12 mod missing_ok_or_some_in_tail_expr;
15 mod remove_this_semicolon;
16 mod replace_filter_map_next_with_find_map;
17 mod unimplemented_builtin_macro;
18 mod unresolved_extern_crate;
19 mod unresolved_import;
20 mod unresolved_macro_call;
21 mod unresolved_module;
22 mod unresolved_proc_macro;
28 use std::cell::RefCell;
31 diagnostics::{AnyDiagnostic, Diagnostic as _, DiagnosticCode, DiagnosticSinkBuilder},
34 use ide_assists::AssistResolveStrategy;
35 use ide_db::{base_db::SourceDatabase, RootDatabase};
36 use itertools::Itertools;
37 use rustc_hash::FxHashSet;
40 SyntaxNode, SyntaxNodePtr, TextRange, TextSize,
42 use text_edit::TextEdit;
43 use unlinked_file::UnlinkedFile;
45 use crate::{Assist, AssistId, AssistKind, FileId, Label, SourceChange};
47 use self::fixes::DiagnosticWithFixes;
50 pub struct Diagnostic {
51 // pub name: Option<String>,
54 pub severity: Severity,
55 pub fixes: Option<Vec<Assist>>,
57 pub code: Option<DiagnosticCode>,
58 pub experimental: bool,
62 fn new(code: &'static str, message: impl Into<String>, range: TextRange) -> Diagnostic {
63 let message = message.into();
64 let code = Some(DiagnosticCode(code));
68 severity: Severity::Error,
76 fn experimental(mut self) -> Diagnostic {
77 self.experimental = true;
81 fn severity(mut self, severity: Severity) -> Diagnostic {
82 self.severity = severity;
86 fn error(range: TextRange, message: String) -> Self {
90 severity: Severity::Error,
98 fn hint(range: TextRange, message: String) -> Self {
102 severity: Severity::WeakWarning,
110 fn with_fixes(self, fixes: Option<Vec<Assist>>) -> Self {
111 Self { fixes, ..self }
114 fn with_unused(self, unused: bool) -> Self {
115 Self { unused, ..self }
118 fn with_code(self, code: Option<DiagnosticCode>) -> Self {
119 Self { code, ..self }
123 #[derive(Debug, Copy, Clone)]
129 #[derive(Default, Debug, Clone)]
130 pub struct DiagnosticsConfig {
131 pub disable_experimental: bool,
132 pub disabled: FxHashSet<String>,
135 struct DiagnosticsContext<'a> {
136 config: &'a DiagnosticsConfig,
137 sema: Semantics<'a, RootDatabase>,
139 resolve: &'a AssistResolveStrategy,
142 pub(crate) fn diagnostics(
144 config: &DiagnosticsConfig,
145 resolve: &AssistResolveStrategy,
147 ) -> Vec<Diagnostic> {
148 let _p = profile::span("diagnostics");
149 let sema = Semantics::new(db);
150 let parse = db.parse(file_id);
151 let mut res = Vec::new();
153 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
159 .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
162 for node in parse.tree().syntax().descendants() {
163 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
164 field_shorthand::check(&mut res, file_id, &node);
166 let res = RefCell::new(res);
167 let sink_builder = DiagnosticSinkBuilder::new()
168 .on::<hir::diagnostics::IncorrectCase, _>(|d| {
169 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
171 .on::<UnlinkedFile, _>(|d| {
172 // Limit diagnostic to the first few characters in the file. This matches how VS Code
173 // renders it with the full span, but on other editors, and is less invasive.
174 let range = sema.diagnostics_display_range(d.display_source()).range;
175 let range = range.intersect(TextRange::up_to(TextSize::of("..."))).unwrap_or(range);
177 // Override severity and mark as unused.
178 res.borrow_mut().push(
179 Diagnostic::hint(range, d.message())
180 .with_fixes(d.fixes(&sema, resolve))
181 .with_code(Some(d.code())),
184 // Only collect experimental diagnostics when they're enabled.
185 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
186 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
188 // Finalize the `DiagnosticSink` building process.
189 let mut sink = sink_builder
190 // Diagnostics not handled above get no fix and default treatment.
192 res.borrow_mut().push(
194 sema.diagnostics_display_range(d.display_source()).range,
197 .with_code(Some(d.code())),
201 let mut diags = Vec::new();
202 let internal_diagnostics = cfg!(test);
203 match sema.to_module_def(file_id) {
204 Some(m) => diags = m.diagnostics(db, &mut sink, internal_diagnostics),
206 sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(parse.tree().syntax()) });
212 let mut res = res.into_inner();
214 let ctx = DiagnosticsContext { config, sema, resolve };
218 AnyDiagnostic::BreakOutsideOfLoop(d) => break_outside_of_loop::break_outside_of_loop(&ctx, &d),
219 AnyDiagnostic::MacroError(d) => macro_error::macro_error(&ctx, &d),
220 AnyDiagnostic::MismatchedArgCount(d) => mismatched_arg_count::mismatched_arg_count(&ctx, &d),
221 AnyDiagnostic::MissingFields(d) => missing_fields::missing_fields(&ctx, &d),
222 AnyDiagnostic::MissingOkOrSomeInTailExpr(d) => missing_ok_or_some_in_tail_expr::missing_ok_or_some_in_tail_expr(&ctx, &d),
223 AnyDiagnostic::MissingUnsafe(d) => missing_unsafe::missing_unsafe(&ctx, &d),
224 AnyDiagnostic::NoSuchField(d) => no_such_field::no_such_field(&ctx, &d),
225 AnyDiagnostic::RemoveThisSemicolon(d) => remove_this_semicolon::remove_this_semicolon(&ctx, &d),
226 AnyDiagnostic::ReplaceFilterMapNextWithFindMap(d) => replace_filter_map_next_with_find_map::replace_filter_map_next_with_find_map(&ctx, &d),
227 AnyDiagnostic::UnimplementedBuiltinMacro(d) => unimplemented_builtin_macro::unimplemented_builtin_macro(&ctx, &d),
228 AnyDiagnostic::UnresolvedExternCrate(d) => unresolved_extern_crate::unresolved_extern_crate(&ctx, &d),
229 AnyDiagnostic::UnresolvedImport(d) => unresolved_import::unresolved_import(&ctx, &d),
230 AnyDiagnostic::UnresolvedMacroCall(d) => unresolved_macro_call::unresolved_macro_call(&ctx, &d),
231 AnyDiagnostic::UnresolvedModule(d) => unresolved_module::unresolved_module(&ctx, &d),
232 AnyDiagnostic::UnresolvedProcMacro(d) => unresolved_proc_macro::unresolved_proc_macro(&ctx, &d),
234 AnyDiagnostic::InactiveCode(d) => match inactive_code::inactive_code(&ctx, &d) {
239 if let Some(code) = d.code {
240 if ctx.config.disabled.contains(code.as_str()) {
244 if ctx.config.disable_experimental && d.experimental {
253 fn warning_with_fix<D: DiagnosticWithFixes>(
255 sema: &Semantics<RootDatabase>,
256 resolve: &AssistResolveStrategy,
258 Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message())
259 .with_fixes(d.fixes(sema, resolve))
260 .with_code(Some(d.code()))
263 fn check_unnecessary_braces_in_use_statement(
264 acc: &mut Vec<Diagnostic>,
268 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
269 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
270 // If there is a comment inside the bracketed `use`,
271 // assume it is a commented out module path and don't show diagnostic.
272 if use_tree_list.has_inner_comment() {
276 let use_range = use_tree_list.syntax().text_range();
278 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
280 let to_replace = single_use_tree.syntax().text().to_string();
281 let mut edit_builder = TextEdit::builder();
282 edit_builder.delete(use_range);
283 edit_builder.insert(use_range.start(), to_replace);
284 edit_builder.finish()
288 Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
289 .with_fixes(Some(vec![fix(
291 "Remove unnecessary braces",
292 SourceChange::from_text_edit(file_id, edit),
301 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
302 single_use_tree: &ast::UseTree,
303 ) -> Option<TextEdit> {
304 let use_tree_list_node = single_use_tree.syntax().parent()?;
305 if single_use_tree.path()?.segment()?.self_token().is_some() {
306 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
307 let end = use_tree_list_node.text_range().end();
308 return Some(TextEdit::delete(TextRange::new(start, end)));
313 fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
314 let mut res = unresolved_fix(id, label, target);
315 res.source_change = Some(source_change);
319 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
320 assert!(!id.contains(' '));
322 id: AssistId(id, AssistKind::QuickFix),
323 label: Label::new(label),
332 use expect_test::Expect;
333 use ide_assists::AssistResolveStrategy;
334 use stdx::trim_indent;
335 use test_utils::{assert_eq_text, extract_annotations};
337 use crate::{fixture, DiagnosticsConfig};
339 /// Takes a multi-file input fixture with annotated cursor positions,
341 /// * a diagnostic is produced
342 /// * the first diagnostic fix trigger range touches the input cursor position
343 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
345 pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
346 check_nth_fix(0, ra_fixture_before, ra_fixture_after);
348 /// Takes a multi-file input fixture with annotated cursor positions,
350 /// * a diagnostic is produced
351 /// * every diagnostic fixes trigger range touches the input cursor position
352 /// * that the contents of the file containing the cursor match `after` after each diagnostic fix is applied
353 pub(crate) fn check_fixes(ra_fixture_before: &str, ra_fixtures_after: Vec<&str>) {
354 for (i, ra_fixture_after) in ra_fixtures_after.iter().enumerate() {
355 check_nth_fix(i, ra_fixture_before, ra_fixture_after)
360 fn check_nth_fix(nth: usize, ra_fixture_before: &str, ra_fixture_after: &str) {
361 let after = trim_indent(ra_fixture_after);
363 let (analysis, file_position) = fixture::position(ra_fixture_before);
364 let diagnostic = analysis
366 &DiagnosticsConfig::default(),
367 AssistResolveStrategy::All,
368 file_position.file_id,
373 let fix = &diagnostic.fixes.unwrap()[nth];
375 let source_change = fix.source_change.as_ref().unwrap();
376 let file_id = *source_change.source_file_edits.keys().next().unwrap();
377 let mut actual = analysis.file_text(file_id).unwrap().to_string();
379 for edit in source_change.source_file_edits.values() {
380 edit.apply(&mut actual);
385 assert_eq_text!(&after, &actual);
387 fix.target.contains_inclusive(file_position.offset),
388 "diagnostic fix range {:?} does not touch cursor position {:?}",
393 /// Checks that there's a diagnostic *without* fix at `$0`.
394 fn check_no_fix(ra_fixture: &str) {
395 let (analysis, file_position) = fixture::position(ra_fixture);
396 let diagnostic = analysis
398 &DiagnosticsConfig::default(),
399 AssistResolveStrategy::All,
400 file_position.file_id,
405 assert!(diagnostic.fixes.is_none(), "got a fix when none was expected: {:?}", diagnostic);
408 pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) {
409 let (analysis, file_id) = fixture::file(ra_fixture);
410 let diagnostics = analysis
411 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
413 expect.assert_debug_eq(&diagnostics)
417 pub(crate) fn check_diagnostics(ra_fixture: &str) {
418 let mut config = DiagnosticsConfig::default();
419 config.disabled.insert("inactive-code".to_string());
420 check_diagnostics_with_config(config, ra_fixture)
424 pub(crate) fn check_diagnostics_with_config(config: DiagnosticsConfig, ra_fixture: &str) {
425 let (analysis, files) = fixture::files(ra_fixture);
426 for file_id in files {
428 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
430 let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
432 diagnostics.into_iter().map(|d| (d.range, d.message)).collect::<Vec<_>>();
433 actual.sort_by_key(|(range, _)| range.start());
434 assert_eq!(expected, actual);
439 fn test_check_unnecessary_braces_in_use_statement() {
511 mod a { mod c {} mod d { mod e {} } }
512 use a::{c, d::{e$0}};
515 mod a { mod c {} mod d { mod e {} } }
522 fn test_disabled_diagnostics() {
523 let mut config = DiagnosticsConfig::default();
524 config.disabled.insert("unresolved-module".into());
526 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
529 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
530 assert!(diagnostics.is_empty());
532 let diagnostics = analysis
533 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
535 assert!(!diagnostics.is_empty());
539 fn unlinked_file_prepend_first_item() {
540 cov_mark::check!(unlinked_file_prepend_before_first_item);
541 // Only tests the first one for `pub mod` since the rest are the same
565 fn unlinked_file_append_mod() {
566 cov_mark::check!(unlinked_file_append_to_existing_mods);
578 mod preexisting_bottom;)
592 mod preexisting_bottom;)
598 fn unlinked_file_insert_in_empty_file() {
599 cov_mark::check!(unlinked_file_empty_file);
613 fn unlinked_file_old_style_modrs() {
631 fn unlinked_file_new_style_mod() {
647 fn unlinked_file_with_cfg_off() {
648 cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
662 fn unlinked_file_with_cfg_on() {
675 fn import_extern_crate_clash_with_inner_item() {
676 // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
680 //- /lib.rs crate:lib deps:jwt
683 use permissions::jwt;
687 jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
695 //- /jwt/lib.rs crate:jwt
705 pub(super) mod match_check_tests {
706 use crate::diagnostics::tests::check_diagnostics;
714 //^^ Missing match arm
716 //^^^^ Missing match arm
718 match () { _ => (), }
719 match () { () => (), }
720 match (()) { (()) => (), }
727 fn tuple_of_two_empty_tuple() {
732 //^^^^^^^^ Missing match arm
734 match ((), ()) { ((), ()) => (), }
746 //^^^^^ Missing match arm
747 match false { true => (), }
748 //^^^^^ Missing match arm
749 match (false, true) {}
750 //^^^^^^^^^^^^^ Missing match arm
751 match (false, true) { (true, true) => (), }
752 //^^^^^^^^^^^^^ Missing match arm
753 match (false, true) {
754 //^^^^^^^^^^^^^ Missing match arm
756 (false, false) => (),
759 match (false, true) { (true, _x) => (), }
760 //^^^^^^^^^^^^^ Missing match arm
762 match false { true => (), false => (), }
763 match (false, true) {
768 match (false, true) {
772 (false, false) => (),
774 match (false, true) {
777 (false, false) => (),
779 match (false, true, false) {
783 match (false, true, false) {
787 match (false, true, false) { (..) => (), }
794 fn tuple_of_tuple_and_bools() {
798 match (false, ((), false)) {}
799 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
800 match (false, ((), false)) { (true, ((), true)) => (), }
801 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
802 match (false, ((), false)) { (true, _) => (), }
803 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
805 match (false, ((), false)) {
806 (true, ((), true)) => (),
807 (true, ((), false)) => (),
808 (false, ((), true)) => (),
809 (false, ((), false)) => (),
811 match (false, ((), false)) {
812 (true, ((), true)) => (),
813 (true, ((), false)) => (),
825 enum Either { A, B, }
829 //^^^^^^^^^ Missing match arm
830 match Either::B { Either::A => (), }
831 //^^^^^^^^^ Missing match arm
834 //^^^^^^^^^^ Missing match arm
839 Either::A => (), Either::B => (),
842 Either::A => (), Either::B => (),
850 fn enum_containing_bool() {
853 enum Either { A(bool), B }
857 //^^^^^^^^^ Missing match arm
859 //^^^^^^^^^ Missing match arm
860 Either::A(true) => (), Either::B => ()
864 Either::A(true) => (),
865 Either::A(false) => (),
883 fn enum_different_sizes() {
886 enum Either { A(bool), B(bool, bool) }
889 match Either::A(false) {
890 //^^^^^^^^^^^^^^^^ Missing match arm
892 Either::B(false, _) => (),
895 match Either::A(false) {
897 Either::B(true, _) => (),
898 Either::B(false, _) => (),
900 match Either::A(false) {
901 Either::A(true) | Either::A(false) => (),
902 Either::B(true, _) => (),
903 Either::B(false, _) => (),
911 fn tuple_of_enum_no_diagnostic() {
914 enum Either { A(bool), B(bool, bool) }
915 enum Either2 { C, D }
918 match (Either::A(false), Either2::C) {
919 (Either::A(true), _) | (Either::A(false), _) => (),
920 (Either::B(true, _), Either2::C) => (),
921 (Either::B(false, _), Either2::C) => (),
922 (Either::B(_, _), Either2::D) => (),
930 fn or_pattern_no_diagnostic() {
936 match (Either::A, Either::B) {
937 (Either::A | Either::B, _) => (),
944 fn mismatched_types() {
945 // Match statements with arms that don't match the
946 // expression pattern do not fire this diagnostic.
950 enum Either2 { C, D }
955 // ^^^^^^^^^^ Internal: match check bailed out
958 match (true, false) {
959 (true, false, true) => (),
960 // ^^^^^^^^^^^^^^^^^^^ Internal: match check bailed out
963 match (true, false) { (true,) => {} }
964 // ^^^^^^^ Internal: match check bailed out
965 match (0) { () => () }
966 // ^^ Internal: match check bailed out
967 match Unresolved::Bar { Unresolved::Baz => () }
974 fn mismatched_types_in_or_patterns() {
978 match false { true | () => {} }
979 // ^^^^^^^^^ Internal: match check bailed out
980 match (false,) { (true | (),) => {} }
981 // ^^^^^^^^^^^^ Internal: match check bailed out
988 fn malformed_match_arm_tuple_enum_missing_pattern() {
989 // We are testing to be sure we don't panic here when the match
990 // arm `Either::B` is missing its pattern.
993 enum Either { A, B(u32) }
1006 fn malformed_match_arm_extra_fields() {
1009 enum A { B(isize, isize), C }
1012 A::B(_, _, _) => (),
1013 // ^^^^^^^^^^^^^ Internal: match check bailed out
1017 // ^^^^^^^ Internal: match check bailed out
1025 fn expr_diverges() {
1028 enum Either { A, B }
1033 // ^^^^^^^^^ Internal: match check bailed out
1038 // ^^^^^^^^^ Internal: match check bailed out
1040 match loop { break Foo::A } {
1041 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1044 match loop { break Foo::A } {
1054 fn expr_partially_diverges() {
1057 enum Either<T> { A(T), B }
1059 fn foo() -> Either<!> { Either::B }
1062 Either::A(val) => val,
1074 enum Either { A { foo: bool }, B }
1077 let a = Either::A { foo: true };
1079 //^ Missing match arm
1080 match a { Either::A { foo: true } => () }
1081 //^ Missing match arm
1083 Either::A { } => (),
1084 //^^^^^^^^^ Missing structure fields:
1089 //^ Missing match arm
1090 Either::A { } => (),
1091 } //^^^^^^^^^ Missing structure fields:
1095 Either::A { foo: true } => (),
1096 Either::A { foo: false } => (),
1100 Either::A { foo: _ } => (),
1109 fn enum_record_fields_out_of_order() {
1113 A { foo: bool, bar: () },
1118 let a = Either::A { foo: true, bar: () };
1120 //^ Missing match arm
1121 Either::A { bar: (), foo: false } => (),
1122 Either::A { foo: true, bar: () } => (),
1126 Either::A { bar: (), foo: false } => (),
1127 Either::A { foo: true, bar: () } => (),
1136 fn enum_record_ellipsis() {
1140 A { foo: bool, bar: bool },
1147 //^ Missing match arm
1148 Either::A { foo: true, .. } => (),
1152 //^ Missing match arm
1153 Either::A { .. } => (),
1157 Either::A { foo: true, .. } => (),
1158 Either::A { foo: false, .. } => (),
1163 Either::A { .. } => (),
1172 fn enum_tuple_partial_ellipsis() {
1176 A(bool, bool, bool, bool),
1182 //^^^^^^^^^ Missing match arm
1183 Either::A(true, .., true) => (),
1184 Either::A(true, .., false) => (),
1185 Either::A(false, .., false) => (),
1189 //^^^^^^^^^ Missing match arm
1190 Either::A(true, .., true) => (),
1191 Either::A(true, .., false) => (),
1192 Either::A(.., true) => (),
1197 Either::A(true, .., true) => (),
1198 Either::A(true, .., false) => (),
1199 Either::A(false, .., true) => (),
1200 Either::A(false, .., false) => (),
1204 Either::A(true, .., true) => (),
1205 Either::A(true, .., false) => (),
1206 Either::A(.., true) => (),
1207 Either::A(.., false) => (),
1221 fn enum_(never: Never) {
1224 fn enum_ref(never: &Never) {
1226 //^^^^^ Missing match arm
1239 enum Option<T> { Some(T), None }
1242 // `Never` is deliberately not defined so that it's an uninferred type.
1243 match Option::<Never>::None {
1245 Some(never) => match never {},
1246 // ^^^^^^^^^^^ Internal: match check bailed out
1248 match Option::<Never>::None {
1249 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1250 Option::Some(_never) => {},
1258 fn tuple_of_bools_with_ellipsis_at_end_missing_arm() {
1262 match (false, true, false) {
1263 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1271 fn tuple_of_bools_with_ellipsis_at_beginning_missing_arm() {
1275 match (false, true, false) {
1276 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1284 fn tuple_of_bools_with_ellipsis_in_middle_missing_arm() {
1288 match (false, true, false) {
1289 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1290 (true, .., false) => (),
1297 fn record_struct() {
1299 r#"struct Foo { a: bool }
1302 //^ Missing match arm
1303 match f { Foo { a: true } => () }
1304 //^ Missing match arm
1305 match &f { Foo { a: true } => () }
1306 //^^ Missing match arm
1307 match f { Foo { a: _ } => () }
1309 Foo { a: true } => (),
1310 Foo { a: false } => (),
1313 Foo { a: true } => (),
1314 Foo { a: false } => (),
1324 r#"struct Foo(bool);
1327 //^ Missing match arm
1328 match f { Foo(true) => () }
1329 //^ Missing match arm
1345 //^ Missing match arm
1346 match f { Foo => () }
1353 fn record_struct_ellipsis() {
1355 r#"struct Foo { foo: bool, bar: bool }
1357 match f { Foo { foo: true, .. } => () }
1358 //^ Missing match arm
1360 //^ Missing match arm
1361 Foo { foo: true, .. } => (),
1362 Foo { bar: false, .. } => ()
1364 match f { Foo { .. } => () }
1366 Foo { foo: true, .. } => (),
1367 Foo { foo: false, .. } => ()
1379 enum Either { A(bool), B }
1381 //^^^^^^^^^ Missing match arm
1382 Either::A(true | false) => (),
1390 fn no_panic_at_unimplemented_subpattern_type() {
1395 match v { S{ a } => {} }
1396 match v { S{ a: _x } => {} }
1397 match v { S{ a: 'a' } => {} }
1398 //^^^^^^^^^^^ Internal: match check bailed out
1399 match v { S{..} => {} }
1402 //^ Missing match arm
1417 match true { _x @ true => {} }
1418 //^^^^ Missing match arm
1425 fn binding_ref_has_correct_type() {
1426 // Asserts `PatKind::Binding(ref _x): bool`, not &bool.
1427 // If that's not true match checking will panic with "incompatible constructors"
1428 // FIXME: make facilities to test this directly like `tests::check_infer(..)`
1433 // FIXME: this should not bail out but current behavior is such as the old algorithm.
1434 // ExprValidator::validate_match(..) checks types of top level patterns incorrecly.
1437 // ^^^^^^ Internal: match check bailed out
1450 fn enum_non_exhaustive() {
1453 //- /lib.rs crate:lib
1457 match E::A { _ => {} }
1467 //- /main.rs crate:main deps:lib
1470 match E::A { _ => {} }
1472 //^^^^ Missing match arm
1477 //^^^^ Missing match arm
1496 //^^^^ Missing match arm
1506 fn pattern_type_is_of_substitution() {
1507 cov_mark::check!(match_check_wildcard_expanded_to_substitutions);
1522 fn record_struct_no_such_field() {
1527 match f { Foo { bar } => () }
1528 // ^^^^^^^^^^^ Internal: match check bailed out
1535 fn match_ergonomics_issue_9095() {
1538 enum Foo<T> { A(T) }
1540 match &Foo::A(true) {
1549 mod false_negatives {
1550 //! The implementation of match checking here is a work in progress. As we roll this out, we
1551 //! prefer false negatives to false positives (ideally there would be no false positives). This
1552 //! test module should document known false negatives. Eventually we will have a complete
1553 //! implementation of match checking and this module will be empty.
1555 //! The reasons for documenting known false negatives:
1557 //! 1. It acts as a backlog of work that can be done to improve the behavior of the system.
1558 //! 2. It ensures the code doesn't panic when handling these cases.
1563 // We don't currently check integer exhaustiveness.
1569 // ^^ Internal: match check bailed out
1578 fn reference_patterns_at_top_level() {
1584 // ^^^^^ Internal: match check bailed out
1592 fn reference_patterns_in_fields() {
1598 // ^^^^^^^ Internal: match check bailed out
1602 // ^^^^^^^^ Internal: match check bailed out
1612 mod decl_check_tests {
1613 use crate::diagnostics::tests::check_diagnostics;
1616 fn incorrect_function_name() {
1619 fn NonSnakeCaseName() {}
1620 // ^^^^^^^^^^^^^^^^ Function `NonSnakeCaseName` should have snake_case name, e.g. `non_snake_case_name`
1626 fn incorrect_function_params() {
1629 fn foo(SomeParam: u8) {}
1630 // ^^^^^^^^^ Parameter `SomeParam` should have snake_case name, e.g. `some_param`
1632 fn foo2(ok_param: &str, CAPS_PARAM: u8) {}
1633 // ^^^^^^^^^^ Parameter `CAPS_PARAM` should have snake_case name, e.g. `caps_param`
1639 fn incorrect_variable_names() {
1643 let SOME_VALUE = 10;
1644 // ^^^^^^^^^^ Variable `SOME_VALUE` should have snake_case name, e.g. `some_value`
1645 let AnotherValue = 20;
1646 // ^^^^^^^^^^^^ Variable `AnotherValue` should have snake_case name, e.g. `another_value`
1653 fn incorrect_struct_names() {
1656 struct non_camel_case_name {}
1657 // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName`
1659 struct SCREAMING_CASE {}
1660 // ^^^^^^^^^^^^^^ Structure `SCREAMING_CASE` should have CamelCase name, e.g. `ScreamingCase`
1666 fn no_diagnostic_for_camel_cased_acronyms_in_struct_name() {
1675 fn incorrect_struct_field() {
1678 struct SomeStruct { SomeField: u8 }
1679 // ^^^^^^^^^ Field `SomeField` should have snake_case name, e.g. `some_field`
1685 fn incorrect_enum_names() {
1688 enum some_enum { Val(u8) }
1689 // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum`
1692 // ^^^^^^^^^ Enum `SOME_ENUM` should have CamelCase name, e.g. `SomeEnum`
1698 fn no_diagnostic_for_camel_cased_acronyms_in_enum_name() {
1707 fn incorrect_enum_variant_name() {
1710 enum SomeEnum { SOME_VARIANT(u8) }
1711 // ^^^^^^^^^^^^ Variant `SOME_VARIANT` should have CamelCase name, e.g. `SomeVariant`
1717 fn incorrect_const_name() {
1720 const some_weird_const: u8 = 10;
1721 // ^^^^^^^^^^^^^^^^ Constant `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
1727 fn incorrect_static_name() {
1730 static some_weird_const: u8 = 10;
1731 // ^^^^^^^^^^^^^^^^ Static variable `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
1737 fn fn_inside_impl_struct() {
1741 // ^^^^^^^^^^ Structure `someStruct` should have CamelCase name, e.g. `SomeStruct`
1744 fn SomeFunc(&self) {
1745 // ^^^^^^^^ Function `SomeFunc` should have snake_case name, e.g. `some_func`
1746 let WHY_VAR_IS_CAPS = 10;
1747 // ^^^^^^^^^^^^^^^ Variable `WHY_VAR_IS_CAPS` should have snake_case name, e.g. `why_var_is_caps`
1755 fn no_diagnostic_for_enum_varinats() {
1758 enum Option { Some, None }
1761 match Option::None {
1774 enum Option { Some, None }
1777 match Option::None {
1778 SOME_VAR @ None => (),
1779 // ^^^^^^^^ Variable `SOME_VAR` should have snake_case name, e.g. `some_var`
1788 fn allow_attributes() {
1791 #[allow(non_snake_case)]
1792 fn NonSnakeCaseName(SOME_VAR: u8) -> u8{
1793 // cov_flags generated output from elsewhere in this file
1796 static lower_case: u8;
1799 let OtherVar = SOME_VAR + 1;
1803 #[allow(nonstandard_style)]
1804 mod CheckNonstandardStyle {
1805 fn HiImABadFnName() {}
1810 fn HiImABadFnName() {}
1814 #![allow(non_snake_case)]
1815 fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {}
1818 #[allow(non_snake_case, non_camel_case_types)]
1819 pub struct some_type {
1824 #[allow(non_upper_case_globals)]
1825 pub const some_const: u8 = 10;
1827 #[allow(non_upper_case_globals)]
1828 pub static SomeStatic: u8 = 10;
1834 fn allow_attributes_crate_attr() {
1837 #![allow(non_snake_case)]
1840 fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {}
1848 fn bug_trait_inside_fn() {
1850 // This is broken, and in fact, should not even be looked at by this
1851 // lint in the first place. There's weird stuff going on in the
1852 // collection phase.
1853 // It's currently being brought in by:
1854 // * validate_func on `a` recursing into modules
1855 // * then it finds the trait and then the function while iterating
1857 // * then validate_func is called on Dirty
1858 // * ... which then proceeds to look at some unknown module taking no
1859 // attrs from either the impl or the fn a, and then finally to the root
1862 // It should find the attribute on the trait, but it *doesn't even see
1863 // the trait* as far as I can tell.
1871 // this comes out of bitflags, mostly
1872 #[allow(non_snake_case)]
1874 const HiImAlsoBad: u8 = 2;
1876 fn Dirty(&self) -> bool {
1889 fn bug_traits_arent_checked() {
1890 // FIXME: Traits and functions in traits aren't currently checked by
1891 // r-a, even though rustc will complain about them.
1895 // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait`
1897 // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function`
1899 // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function`
1906 fn ignores_extern_items() {
1907 cov_mark::check!(extern_func_incorrect_case_ignored);
1908 cov_mark::check!(extern_static_incorrect_case_ignored);
1912 fn NonSnakeCaseName(SOME_VAR: u8) -> u8;
1913 pub static SomeStatic: u8 = 10;
1920 fn infinite_loop_inner_items() {
1932 #[test] // Issue #8809.
1933 fn parenthesized_parameter() {
1934 check_diagnostics(r#"fn f((O): _) {}"#)