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 missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
678 struct S { foo: i32, bar: () }
679 fn baz(s: S) -> i32 {
681 S { foo, .. } => foo,
689 fn missing_record_pat_field_box() {
692 struct S { s: Box<u32> }
701 fn missing_record_pat_field_ref() {
713 fn import_extern_crate_clash_with_inner_item() {
714 // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
718 //- /lib.rs crate:lib deps:jwt
721 use permissions::jwt;
725 jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
733 //- /jwt/lib.rs crate:jwt
743 pub(super) mod match_check_tests {
744 use crate::diagnostics::tests::check_diagnostics;
752 //^^ Missing match arm
754 //^^^^ Missing match arm
756 match () { _ => (), }
757 match () { () => (), }
758 match (()) { (()) => (), }
765 fn tuple_of_two_empty_tuple() {
770 //^^^^^^^^ Missing match arm
772 match ((), ()) { ((), ()) => (), }
784 //^^^^^ Missing match arm
785 match false { true => (), }
786 //^^^^^ Missing match arm
787 match (false, true) {}
788 //^^^^^^^^^^^^^ Missing match arm
789 match (false, true) { (true, true) => (), }
790 //^^^^^^^^^^^^^ Missing match arm
791 match (false, true) {
792 //^^^^^^^^^^^^^ Missing match arm
794 (false, false) => (),
797 match (false, true) { (true, _x) => (), }
798 //^^^^^^^^^^^^^ Missing match arm
800 match false { true => (), false => (), }
801 match (false, true) {
806 match (false, true) {
810 (false, false) => (),
812 match (false, true) {
815 (false, false) => (),
817 match (false, true, false) {
821 match (false, true, false) {
825 match (false, true, false) { (..) => (), }
832 fn tuple_of_tuple_and_bools() {
836 match (false, ((), false)) {}
837 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
838 match (false, ((), false)) { (true, ((), true)) => (), }
839 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
840 match (false, ((), false)) { (true, _) => (), }
841 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
843 match (false, ((), false)) {
844 (true, ((), true)) => (),
845 (true, ((), false)) => (),
846 (false, ((), true)) => (),
847 (false, ((), false)) => (),
849 match (false, ((), false)) {
850 (true, ((), true)) => (),
851 (true, ((), false)) => (),
863 enum Either { A, B, }
867 //^^^^^^^^^ Missing match arm
868 match Either::B { Either::A => (), }
869 //^^^^^^^^^ Missing match arm
872 //^^^^^^^^^^ Missing match arm
877 Either::A => (), Either::B => (),
880 Either::A => (), Either::B => (),
888 fn enum_containing_bool() {
891 enum Either { A(bool), B }
895 //^^^^^^^^^ Missing match arm
897 //^^^^^^^^^ Missing match arm
898 Either::A(true) => (), Either::B => ()
902 Either::A(true) => (),
903 Either::A(false) => (),
921 fn enum_different_sizes() {
924 enum Either { A(bool), B(bool, bool) }
927 match Either::A(false) {
928 //^^^^^^^^^^^^^^^^ Missing match arm
930 Either::B(false, _) => (),
933 match Either::A(false) {
935 Either::B(true, _) => (),
936 Either::B(false, _) => (),
938 match Either::A(false) {
939 Either::A(true) | Either::A(false) => (),
940 Either::B(true, _) => (),
941 Either::B(false, _) => (),
949 fn tuple_of_enum_no_diagnostic() {
952 enum Either { A(bool), B(bool, bool) }
953 enum Either2 { C, D }
956 match (Either::A(false), Either2::C) {
957 (Either::A(true), _) | (Either::A(false), _) => (),
958 (Either::B(true, _), Either2::C) => (),
959 (Either::B(false, _), Either2::C) => (),
960 (Either::B(_, _), Either2::D) => (),
968 fn or_pattern_no_diagnostic() {
974 match (Either::A, Either::B) {
975 (Either::A | Either::B, _) => (),
982 fn mismatched_types() {
983 // Match statements with arms that don't match the
984 // expression pattern do not fire this diagnostic.
988 enum Either2 { C, D }
993 // ^^^^^^^^^^ Internal: match check bailed out
996 match (true, false) {
997 (true, false, true) => (),
998 // ^^^^^^^^^^^^^^^^^^^ Internal: match check bailed out
1001 match (true, false) { (true,) => {} }
1002 // ^^^^^^^ Internal: match check bailed out
1003 match (0) { () => () }
1004 // ^^ Internal: match check bailed out
1005 match Unresolved::Bar { Unresolved::Baz => () }
1012 fn mismatched_types_in_or_patterns() {
1016 match false { true | () => {} }
1017 // ^^^^^^^^^ Internal: match check bailed out
1018 match (false,) { (true | (),) => {} }
1019 // ^^^^^^^^^^^^ Internal: match check bailed out
1026 fn malformed_match_arm_tuple_enum_missing_pattern() {
1027 // We are testing to be sure we don't panic here when the match
1028 // arm `Either::B` is missing its pattern.
1031 enum Either { A, B(u32) }
1044 fn malformed_match_arm_extra_fields() {
1047 enum A { B(isize, isize), C }
1050 A::B(_, _, _) => (),
1051 // ^^^^^^^^^^^^^ Internal: match check bailed out
1055 // ^^^^^^^ Internal: match check bailed out
1063 fn expr_diverges() {
1066 enum Either { A, B }
1071 // ^^^^^^^^^ Internal: match check bailed out
1076 // ^^^^^^^^^ Internal: match check bailed out
1078 match loop { break Foo::A } {
1079 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1082 match loop { break Foo::A } {
1092 fn expr_partially_diverges() {
1095 enum Either<T> { A(T), B }
1097 fn foo() -> Either<!> { Either::B }
1100 Either::A(val) => val,
1112 enum Either { A { foo: bool }, B }
1115 let a = Either::A { foo: true };
1117 //^ Missing match arm
1118 match a { Either::A { foo: true } => () }
1119 //^ Missing match arm
1121 Either::A { } => (),
1122 //^^^^^^^^^ Missing structure fields:
1127 //^ Missing match arm
1128 Either::A { } => (),
1129 } //^^^^^^^^^ Missing structure fields:
1133 Either::A { foo: true } => (),
1134 Either::A { foo: false } => (),
1138 Either::A { foo: _ } => (),
1147 fn enum_record_fields_out_of_order() {
1151 A { foo: bool, bar: () },
1156 let a = Either::A { foo: true, bar: () };
1158 //^ Missing match arm
1159 Either::A { bar: (), foo: false } => (),
1160 Either::A { foo: true, bar: () } => (),
1164 Either::A { bar: (), foo: false } => (),
1165 Either::A { foo: true, bar: () } => (),
1174 fn enum_record_ellipsis() {
1178 A { foo: bool, bar: bool },
1185 //^ Missing match arm
1186 Either::A { foo: true, .. } => (),
1190 //^ Missing match arm
1191 Either::A { .. } => (),
1195 Either::A { foo: true, .. } => (),
1196 Either::A { foo: false, .. } => (),
1201 Either::A { .. } => (),
1210 fn enum_tuple_partial_ellipsis() {
1214 A(bool, bool, bool, bool),
1220 //^^^^^^^^^ Missing match arm
1221 Either::A(true, .., true) => (),
1222 Either::A(true, .., false) => (),
1223 Either::A(false, .., false) => (),
1227 //^^^^^^^^^ Missing match arm
1228 Either::A(true, .., true) => (),
1229 Either::A(true, .., false) => (),
1230 Either::A(.., true) => (),
1235 Either::A(true, .., true) => (),
1236 Either::A(true, .., false) => (),
1237 Either::A(false, .., true) => (),
1238 Either::A(false, .., false) => (),
1242 Either::A(true, .., true) => (),
1243 Either::A(true, .., false) => (),
1244 Either::A(.., true) => (),
1245 Either::A(.., false) => (),
1259 fn enum_(never: Never) {
1262 fn enum_ref(never: &Never) {
1264 //^^^^^ Missing match arm
1277 enum Option<T> { Some(T), None }
1280 // `Never` is deliberately not defined so that it's an uninferred type.
1281 match Option::<Never>::None {
1283 Some(never) => match never {},
1284 // ^^^^^^^^^^^ Internal: match check bailed out
1286 match Option::<Never>::None {
1287 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1288 Option::Some(_never) => {},
1296 fn tuple_of_bools_with_ellipsis_at_end_missing_arm() {
1300 match (false, true, false) {
1301 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1309 fn tuple_of_bools_with_ellipsis_at_beginning_missing_arm() {
1313 match (false, true, false) {
1314 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1322 fn tuple_of_bools_with_ellipsis_in_middle_missing_arm() {
1326 match (false, true, false) {
1327 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1328 (true, .., false) => (),
1335 fn record_struct() {
1337 r#"struct Foo { a: bool }
1340 //^ Missing match arm
1341 match f { Foo { a: true } => () }
1342 //^ Missing match arm
1343 match &f { Foo { a: true } => () }
1344 //^^ Missing match arm
1345 match f { Foo { a: _ } => () }
1347 Foo { a: true } => (),
1348 Foo { a: false } => (),
1351 Foo { a: true } => (),
1352 Foo { a: false } => (),
1362 r#"struct Foo(bool);
1365 //^ Missing match arm
1366 match f { Foo(true) => () }
1367 //^ Missing match arm
1383 //^ Missing match arm
1384 match f { Foo => () }
1391 fn record_struct_ellipsis() {
1393 r#"struct Foo { foo: bool, bar: bool }
1395 match f { Foo { foo: true, .. } => () }
1396 //^ Missing match arm
1398 //^ Missing match arm
1399 Foo { foo: true, .. } => (),
1400 Foo { bar: false, .. } => ()
1402 match f { Foo { .. } => () }
1404 Foo { foo: true, .. } => (),
1405 Foo { foo: false, .. } => ()
1417 enum Either { A(bool), B }
1419 //^^^^^^^^^ Missing match arm
1420 Either::A(true | false) => (),
1428 fn no_panic_at_unimplemented_subpattern_type() {
1433 match v { S{ a } => {} }
1434 match v { S{ a: _x } => {} }
1435 match v { S{ a: 'a' } => {} }
1436 //^^^^^^^^^^^ Internal: match check bailed out
1437 match v { S{..} => {} }
1440 //^ Missing match arm
1455 match true { _x @ true => {} }
1456 //^^^^ Missing match arm
1463 fn binding_ref_has_correct_type() {
1464 // Asserts `PatKind::Binding(ref _x): bool`, not &bool.
1465 // If that's not true match checking will panic with "incompatible constructors"
1466 // FIXME: make facilities to test this directly like `tests::check_infer(..)`
1471 // FIXME: this should not bail out but current behavior is such as the old algorithm.
1472 // ExprValidator::validate_match(..) checks types of top level patterns incorrecly.
1475 // ^^^^^^ Internal: match check bailed out
1488 fn enum_non_exhaustive() {
1491 //- /lib.rs crate:lib
1495 match E::A { _ => {} }
1505 //- /main.rs crate:main deps:lib
1508 match E::A { _ => {} }
1510 //^^^^ Missing match arm
1515 //^^^^ Missing match arm
1534 //^^^^ Missing match arm
1544 fn pattern_type_is_of_substitution() {
1545 cov_mark::check!(match_check_wildcard_expanded_to_substitutions);
1560 fn record_struct_no_such_field() {
1565 match f { Foo { bar } => () }
1566 // ^^^^^^^^^^^ Internal: match check bailed out
1573 fn match_ergonomics_issue_9095() {
1576 enum Foo<T> { A(T) }
1578 match &Foo::A(true) {
1587 mod false_negatives {
1588 //! The implementation of match checking here is a work in progress. As we roll this out, we
1589 //! prefer false negatives to false positives (ideally there would be no false positives). This
1590 //! test module should document known false negatives. Eventually we will have a complete
1591 //! implementation of match checking and this module will be empty.
1593 //! The reasons for documenting known false negatives:
1595 //! 1. It acts as a backlog of work that can be done to improve the behavior of the system.
1596 //! 2. It ensures the code doesn't panic when handling these cases.
1601 // We don't currently check integer exhaustiveness.
1607 // ^^ Internal: match check bailed out
1616 fn reference_patterns_at_top_level() {
1622 // ^^^^^ Internal: match check bailed out
1630 fn reference_patterns_in_fields() {
1636 // ^^^^^^^ Internal: match check bailed out
1640 // ^^^^^^^^ Internal: match check bailed out
1650 mod decl_check_tests {
1651 use crate::diagnostics::tests::check_diagnostics;
1654 fn incorrect_function_name() {
1657 fn NonSnakeCaseName() {}
1658 // ^^^^^^^^^^^^^^^^ Function `NonSnakeCaseName` should have snake_case name, e.g. `non_snake_case_name`
1664 fn incorrect_function_params() {
1667 fn foo(SomeParam: u8) {}
1668 // ^^^^^^^^^ Parameter `SomeParam` should have snake_case name, e.g. `some_param`
1670 fn foo2(ok_param: &str, CAPS_PARAM: u8) {}
1671 // ^^^^^^^^^^ Parameter `CAPS_PARAM` should have snake_case name, e.g. `caps_param`
1677 fn incorrect_variable_names() {
1681 let SOME_VALUE = 10;
1682 // ^^^^^^^^^^ Variable `SOME_VALUE` should have snake_case name, e.g. `some_value`
1683 let AnotherValue = 20;
1684 // ^^^^^^^^^^^^ Variable `AnotherValue` should have snake_case name, e.g. `another_value`
1691 fn incorrect_struct_names() {
1694 struct non_camel_case_name {}
1695 // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName`
1697 struct SCREAMING_CASE {}
1698 // ^^^^^^^^^^^^^^ Structure `SCREAMING_CASE` should have CamelCase name, e.g. `ScreamingCase`
1704 fn no_diagnostic_for_camel_cased_acronyms_in_struct_name() {
1713 fn incorrect_struct_field() {
1716 struct SomeStruct { SomeField: u8 }
1717 // ^^^^^^^^^ Field `SomeField` should have snake_case name, e.g. `some_field`
1723 fn incorrect_enum_names() {
1726 enum some_enum { Val(u8) }
1727 // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum`
1730 // ^^^^^^^^^ Enum `SOME_ENUM` should have CamelCase name, e.g. `SomeEnum`
1736 fn no_diagnostic_for_camel_cased_acronyms_in_enum_name() {
1745 fn incorrect_enum_variant_name() {
1748 enum SomeEnum { SOME_VARIANT(u8) }
1749 // ^^^^^^^^^^^^ Variant `SOME_VARIANT` should have CamelCase name, e.g. `SomeVariant`
1755 fn incorrect_const_name() {
1758 const some_weird_const: u8 = 10;
1759 // ^^^^^^^^^^^^^^^^ Constant `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
1765 fn incorrect_static_name() {
1768 static some_weird_const: u8 = 10;
1769 // ^^^^^^^^^^^^^^^^ Static variable `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
1775 fn fn_inside_impl_struct() {
1779 // ^^^^^^^^^^ Structure `someStruct` should have CamelCase name, e.g. `SomeStruct`
1782 fn SomeFunc(&self) {
1783 // ^^^^^^^^ Function `SomeFunc` should have snake_case name, e.g. `some_func`
1784 let WHY_VAR_IS_CAPS = 10;
1785 // ^^^^^^^^^^^^^^^ Variable `WHY_VAR_IS_CAPS` should have snake_case name, e.g. `why_var_is_caps`
1793 fn no_diagnostic_for_enum_varinats() {
1796 enum Option { Some, None }
1799 match Option::None {
1812 enum Option { Some, None }
1815 match Option::None {
1816 SOME_VAR @ None => (),
1817 // ^^^^^^^^ Variable `SOME_VAR` should have snake_case name, e.g. `some_var`
1826 fn allow_attributes() {
1829 #[allow(non_snake_case)]
1830 fn NonSnakeCaseName(SOME_VAR: u8) -> u8{
1831 // cov_flags generated output from elsewhere in this file
1834 static lower_case: u8;
1837 let OtherVar = SOME_VAR + 1;
1841 #[allow(nonstandard_style)]
1842 mod CheckNonstandardStyle {
1843 fn HiImABadFnName() {}
1848 fn HiImABadFnName() {}
1852 #![allow(non_snake_case)]
1853 fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {}
1856 #[allow(non_snake_case, non_camel_case_types)]
1857 pub struct some_type {
1862 #[allow(non_upper_case_globals)]
1863 pub const some_const: u8 = 10;
1865 #[allow(non_upper_case_globals)]
1866 pub static SomeStatic: u8 = 10;
1872 fn allow_attributes_crate_attr() {
1875 #![allow(non_snake_case)]
1878 fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {}
1886 fn bug_trait_inside_fn() {
1888 // This is broken, and in fact, should not even be looked at by this
1889 // lint in the first place. There's weird stuff going on in the
1890 // collection phase.
1891 // It's currently being brought in by:
1892 // * validate_func on `a` recursing into modules
1893 // * then it finds the trait and then the function while iterating
1895 // * then validate_func is called on Dirty
1896 // * ... which then proceeds to look at some unknown module taking no
1897 // attrs from either the impl or the fn a, and then finally to the root
1900 // It should find the attribute on the trait, but it *doesn't even see
1901 // the trait* as far as I can tell.
1909 // this comes out of bitflags, mostly
1910 #[allow(non_snake_case)]
1912 const HiImAlsoBad: u8 = 2;
1914 fn Dirty(&self) -> bool {
1927 fn bug_traits_arent_checked() {
1928 // FIXME: Traits and functions in traits aren't currently checked by
1929 // r-a, even though rustc will complain about them.
1933 // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait`
1935 // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function`
1937 // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function`
1944 fn ignores_extern_items() {
1945 cov_mark::check!(extern_func_incorrect_case_ignored);
1946 cov_mark::check!(extern_static_incorrect_case_ignored);
1950 fn NonSnakeCaseName(SOME_VAR: u8) -> u8;
1951 pub static SomeStatic: u8 = 10;
1958 fn infinite_loop_inner_items() {
1970 #[test] // Issue #8809.
1971 fn parenthesized_parameter() {
1972 check_diagnostics(r#"fn f((O): _) {}"#)