]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/diagnostics.rs
internal: refactor find_map diagnostic
[rust.git] / crates / ide / src / diagnostics.rs
1 //! Collects diagnostics & fixits  for a single file.
2 //!
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.
6
7 mod break_outside_of_loop;
8 mod inactive_code;
9 mod macro_error;
10 mod mismatched_arg_count;
11 mod missing_fields;
12 mod missing_ok_or_some_in_tail_expr;
13 mod missing_unsafe;
14 mod no_such_field;
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;
23
24 mod fixes;
25 mod field_shorthand;
26 mod unlinked_file;
27
28 use std::cell::RefCell;
29
30 use hir::{
31     diagnostics::{AnyDiagnostic, Diagnostic as _, DiagnosticCode, DiagnosticSinkBuilder},
32     Semantics,
33 };
34 use ide_assists::AssistResolveStrategy;
35 use ide_db::{base_db::SourceDatabase, RootDatabase};
36 use itertools::Itertools;
37 use rustc_hash::FxHashSet;
38 use syntax::{
39     ast::{self, AstNode},
40     SyntaxNode, SyntaxNodePtr, TextRange, TextSize,
41 };
42 use text_edit::TextEdit;
43 use unlinked_file::UnlinkedFile;
44
45 use crate::{Assist, AssistId, AssistKind, FileId, Label, SourceChange};
46
47 use self::fixes::DiagnosticWithFixes;
48
49 #[derive(Debug)]
50 pub struct Diagnostic {
51     // pub name: Option<String>,
52     pub message: String,
53     pub range: TextRange,
54     pub severity: Severity,
55     pub fixes: Option<Vec<Assist>>,
56     pub unused: bool,
57     pub code: Option<DiagnosticCode>,
58     pub experimental: bool,
59 }
60
61 impl Diagnostic {
62     fn new(code: &'static str, message: impl Into<String>, range: TextRange) -> Diagnostic {
63         let message = message.into();
64         let code = Some(DiagnosticCode(code));
65         Self {
66             message,
67             range,
68             severity: Severity::Error,
69             fixes: None,
70             unused: false,
71             code,
72             experimental: false,
73         }
74     }
75
76     fn experimental(mut self) -> Diagnostic {
77         self.experimental = true;
78         self
79     }
80
81     fn severity(mut self, severity: Severity) -> Diagnostic {
82         self.severity = severity;
83         self
84     }
85
86     fn error(range: TextRange, message: String) -> Self {
87         Self {
88             message,
89             range,
90             severity: Severity::Error,
91             fixes: None,
92             unused: false,
93             code: None,
94             experimental: false,
95         }
96     }
97
98     fn hint(range: TextRange, message: String) -> Self {
99         Self {
100             message,
101             range,
102             severity: Severity::WeakWarning,
103             fixes: None,
104             unused: false,
105             code: None,
106             experimental: false,
107         }
108     }
109
110     fn with_fixes(self, fixes: Option<Vec<Assist>>) -> Self {
111         Self { fixes, ..self }
112     }
113
114     fn with_unused(self, unused: bool) -> Self {
115         Self { unused, ..self }
116     }
117
118     fn with_code(self, code: Option<DiagnosticCode>) -> Self {
119         Self { code, ..self }
120     }
121 }
122
123 #[derive(Debug, Copy, Clone)]
124 pub enum Severity {
125     Error,
126     WeakWarning,
127 }
128
129 #[derive(Default, Debug, Clone)]
130 pub struct DiagnosticsConfig {
131     pub disable_experimental: bool,
132     pub disabled: FxHashSet<String>,
133 }
134
135 struct DiagnosticsContext<'a> {
136     config: &'a DiagnosticsConfig,
137     sema: Semantics<'a, RootDatabase>,
138     #[allow(unused)]
139     resolve: &'a AssistResolveStrategy,
140 }
141
142 pub(crate) fn diagnostics(
143     db: &RootDatabase,
144     config: &DiagnosticsConfig,
145     resolve: &AssistResolveStrategy,
146     file_id: FileId,
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();
152
153     // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
154     res.extend(
155         parse
156             .errors()
157             .iter()
158             .take(128)
159             .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
160     );
161
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);
165     }
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));
170         })
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);
176
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())),
182             );
183         })
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()));
187
188     // Finalize the `DiagnosticSink` building process.
189     let mut sink = sink_builder
190         // Diagnostics not handled above get no fix and default treatment.
191         .build(|d| {
192             res.borrow_mut().push(
193                 Diagnostic::error(
194                     sema.diagnostics_display_range(d.display_source()).range,
195                     d.message(),
196                 )
197                 .with_code(Some(d.code())),
198             );
199         });
200
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),
205         None => {
206             sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(parse.tree().syntax()) });
207         }
208     }
209
210     drop(sink);
211
212     let mut res = res.into_inner();
213
214     let ctx = DiagnosticsContext { config, sema, resolve };
215     for diag in diags {
216         #[rustfmt::skip]
217         let d = match diag {
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),
233
234             AnyDiagnostic::InactiveCode(d) => match inactive_code::inactive_code(&ctx, &d) {
235                 Some(it) => it,
236                 None => continue,
237             }
238         };
239         if let Some(code) = d.code {
240             if ctx.config.disabled.contains(code.as_str()) {
241                 continue;
242             }
243         }
244         if ctx.config.disable_experimental && d.experimental {
245             continue;
246         }
247         res.push(d)
248     }
249
250     res
251 }
252
253 fn warning_with_fix<D: DiagnosticWithFixes>(
254     d: &D,
255     sema: &Semantics<RootDatabase>,
256     resolve: &AssistResolveStrategy,
257 ) -> Diagnostic {
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()))
261 }
262
263 fn check_unnecessary_braces_in_use_statement(
264     acc: &mut Vec<Diagnostic>,
265     file_id: FileId,
266     node: &SyntaxNode,
267 ) -> Option<()> {
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() {
273             return Some(());
274         }
275
276         let use_range = use_tree_list.syntax().text_range();
277         let edit =
278             text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
279                 .unwrap_or_else(|| {
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()
285                 });
286
287         acc.push(
288             Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
289                 .with_fixes(Some(vec![fix(
290                     "remove_braces",
291                     "Remove unnecessary braces",
292                     SourceChange::from_text_edit(file_id, edit),
293                     use_range,
294                 )])),
295         );
296     }
297
298     Some(())
299 }
300
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)));
309     }
310     None
311 }
312
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);
316     res
317 }
318
319 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
320     assert!(!id.contains(' '));
321     Assist {
322         id: AssistId(id, AssistKind::QuickFix),
323         label: Label::new(label),
324         group: None,
325         target,
326         source_change: None,
327     }
328 }
329
330 #[cfg(test)]
331 mod tests {
332     use expect_test::Expect;
333     use ide_assists::AssistResolveStrategy;
334     use stdx::trim_indent;
335     use test_utils::{assert_eq_text, extract_annotations};
336
337     use crate::{fixture, DiagnosticsConfig};
338
339     /// Takes a multi-file input fixture with annotated cursor positions,
340     /// and checks that:
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
344     #[track_caller]
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);
347     }
348     /// Takes a multi-file input fixture with annotated cursor positions,
349     /// and checks that:
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)
356         }
357     }
358
359     #[track_caller]
360     fn check_nth_fix(nth: usize, ra_fixture_before: &str, ra_fixture_after: &str) {
361         let after = trim_indent(ra_fixture_after);
362
363         let (analysis, file_position) = fixture::position(ra_fixture_before);
364         let diagnostic = analysis
365             .diagnostics(
366                 &DiagnosticsConfig::default(),
367                 AssistResolveStrategy::All,
368                 file_position.file_id,
369             )
370             .unwrap()
371             .pop()
372             .unwrap();
373         let fix = &diagnostic.fixes.unwrap()[nth];
374         let actual = {
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();
378
379             for edit in source_change.source_file_edits.values() {
380                 edit.apply(&mut actual);
381             }
382             actual
383         };
384
385         assert_eq_text!(&after, &actual);
386         assert!(
387             fix.target.contains_inclusive(file_position.offset),
388             "diagnostic fix range {:?} does not touch cursor position {:?}",
389             fix.target,
390             file_position.offset
391         );
392     }
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
397             .diagnostics(
398                 &DiagnosticsConfig::default(),
399                 AssistResolveStrategy::All,
400                 file_position.file_id,
401             )
402             .unwrap()
403             .pop()
404             .unwrap();
405         assert!(diagnostic.fixes.is_none(), "got a fix when none was expected: {:?}", diagnostic);
406     }
407
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)
412             .unwrap();
413         expect.assert_debug_eq(&diagnostics)
414     }
415
416     #[track_caller]
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)
421     }
422
423     #[track_caller]
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 {
427             let diagnostics =
428                 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
429
430             let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
431             let mut actual =
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);
435         }
436     }
437
438     #[test]
439     fn test_check_unnecessary_braces_in_use_statement() {
440         check_diagnostics(
441             r#"
442 use a;
443 use a::{c, d::e};
444
445 mod a {
446     mod c {}
447     mod d {
448         mod e {}
449     }
450 }
451 "#,
452         );
453         check_diagnostics(
454             r#"
455 use a;
456 use a::{
457     c,
458     // d::e
459 };
460
461 mod a {
462     mod c {}
463     mod d {
464         mod e {}
465     }
466 }
467 "#,
468         );
469         check_fix(
470             r"
471             mod b {}
472             use {$0b};
473             ",
474             r"
475             mod b {}
476             use b;
477             ",
478         );
479         check_fix(
480             r"
481             mod b {}
482             use {b$0};
483             ",
484             r"
485             mod b {}
486             use b;
487             ",
488         );
489         check_fix(
490             r"
491             mod a { mod c {} }
492             use a::{c$0};
493             ",
494             r"
495             mod a { mod c {} }
496             use a::c;
497             ",
498         );
499         check_fix(
500             r"
501             mod a {}
502             use a::{self$0};
503             ",
504             r"
505             mod a {}
506             use a;
507             ",
508         );
509         check_fix(
510             r"
511             mod a { mod c {} mod d { mod e {} } }
512             use a::{c, d::{e$0}};
513             ",
514             r"
515             mod a { mod c {} mod d { mod e {} } }
516             use a::{c, d::e};
517             ",
518         );
519     }
520
521     #[test]
522     fn test_disabled_diagnostics() {
523         let mut config = DiagnosticsConfig::default();
524         config.disabled.insert("unresolved-module".into());
525
526         let (analysis, file_id) = fixture::file(r#"mod foo;"#);
527
528         let diagnostics =
529             analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
530         assert!(diagnostics.is_empty());
531
532         let diagnostics = analysis
533             .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
534             .unwrap();
535         assert!(!diagnostics.is_empty());
536     }
537
538     #[test]
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
542         check_fixes(
543             r#"
544 //- /main.rs
545 fn f() {}
546 //- /foo.rs
547 $0
548 "#,
549             vec![
550                 r#"
551 mod foo;
552
553 fn f() {}
554 "#,
555                 r#"
556 pub mod foo;
557
558 fn f() {}
559 "#,
560             ],
561         );
562     }
563
564     #[test]
565     fn unlinked_file_append_mod() {
566         cov_mark::check!(unlinked_file_append_to_existing_mods);
567         check_fix(
568             r#"
569 //- /main.rs
570 //! Comment on top
571
572 mod preexisting;
573
574 mod preexisting2;
575
576 struct S;
577
578 mod preexisting_bottom;)
579 //- /foo.rs
580 $0
581 "#,
582             r#"
583 //! Comment on top
584
585 mod preexisting;
586
587 mod preexisting2;
588 mod foo;
589
590 struct S;
591
592 mod preexisting_bottom;)
593 "#,
594         );
595     }
596
597     #[test]
598     fn unlinked_file_insert_in_empty_file() {
599         cov_mark::check!(unlinked_file_empty_file);
600         check_fix(
601             r#"
602 //- /main.rs
603 //- /foo.rs
604 $0
605 "#,
606             r#"
607 mod foo;
608 "#,
609         );
610     }
611
612     #[test]
613     fn unlinked_file_old_style_modrs() {
614         check_fix(
615             r#"
616 //- /main.rs
617 mod submod;
618 //- /submod/mod.rs
619 // in mod.rs
620 //- /submod/foo.rs
621 $0
622 "#,
623             r#"
624 // in mod.rs
625 mod foo;
626 "#,
627         );
628     }
629
630     #[test]
631     fn unlinked_file_new_style_mod() {
632         check_fix(
633             r#"
634 //- /main.rs
635 mod submod;
636 //- /submod.rs
637 //- /submod/foo.rs
638 $0
639 "#,
640             r#"
641 mod foo;
642 "#,
643         );
644     }
645
646     #[test]
647     fn unlinked_file_with_cfg_off() {
648         cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
649         check_no_fix(
650             r#"
651 //- /main.rs
652 #[cfg(never)]
653 mod foo;
654
655 //- /foo.rs
656 $0
657 "#,
658         );
659     }
660
661     #[test]
662     fn unlinked_file_with_cfg_on() {
663         check_diagnostics(
664             r#"
665 //- /main.rs
666 #[cfg(not(never))]
667 mod foo;
668
669 //- /foo.rs
670 "#,
671         );
672     }
673
674     #[test]
675     fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
676         check_diagnostics(
677             r"
678 struct S { foo: i32, bar: () }
679 fn baz(s: S) -> i32 {
680     match s {
681         S { foo, .. } => foo,
682     }
683 }
684 ",
685         )
686     }
687
688     #[test]
689     fn missing_record_pat_field_box() {
690         check_diagnostics(
691             r"
692 struct S { s: Box<u32> }
693 fn x(a: S) {
694     let S { box s } = a;
695 }
696 ",
697         )
698     }
699
700     #[test]
701     fn missing_record_pat_field_ref() {
702         check_diagnostics(
703             r"
704 struct S { s: u32 }
705 fn x(a: S) {
706     let S { ref s } = a;
707 }
708 ",
709         )
710     }
711
712     #[test]
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.
715
716         check_diagnostics(
717             r#"
718 //- /lib.rs crate:lib deps:jwt
719 mod permissions;
720
721 use permissions::jwt;
722
723 fn f() {
724     fn inner() {}
725     jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
726 }
727
728 //- /permissions.rs
729 pub mod jwt  {
730     pub struct Claims {}
731 }
732
733 //- /jwt/lib.rs crate:jwt
734 pub struct Claims {
735     field: u8,
736 }
737         "#,
738         );
739     }
740 }
741
742 #[cfg(test)]
743 pub(super) mod match_check_tests {
744     use crate::diagnostics::tests::check_diagnostics;
745
746     #[test]
747     fn empty_tuple() {
748         check_diagnostics(
749             r#"
750 fn main() {
751     match () { }
752         //^^ Missing match arm
753     match (()) { }
754         //^^^^ Missing match arm
755
756     match () { _ => (), }
757     match () { () => (), }
758     match (()) { (()) => (), }
759 }
760 "#,
761         );
762     }
763
764     #[test]
765     fn tuple_of_two_empty_tuple() {
766         check_diagnostics(
767             r#"
768 fn main() {
769     match ((), ()) { }
770         //^^^^^^^^ Missing match arm
771
772     match ((), ()) { ((), ()) => (), }
773 }
774 "#,
775         );
776     }
777
778     #[test]
779     fn boolean() {
780         check_diagnostics(
781             r#"
782 fn test_main() {
783     match false { }
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
793         (false, true) => (),
794         (false, false) => (),
795         (true, false) => (),
796     }
797     match (false, true) { (true, _x) => (), }
798         //^^^^^^^^^^^^^ Missing match arm
799
800     match false { true => (), false => (), }
801     match (false, true) {
802         (false, _) => (),
803         (true, false) => (),
804         (_, true) => (),
805     }
806     match (false, true) {
807         (true, true) => (),
808         (true, false) => (),
809         (false, true) => (),
810         (false, false) => (),
811     }
812     match (false, true) {
813         (true, _x) => (),
814         (false, true) => (),
815         (false, false) => (),
816     }
817     match (false, true, false) {
818         (false, ..) => (),
819         (true, ..) => (),
820     }
821     match (false, true, false) {
822         (.., false) => (),
823         (.., true) => (),
824     }
825     match (false, true, false) { (..) => (), }
826 }
827 "#,
828         );
829     }
830
831     #[test]
832     fn tuple_of_tuple_and_bools() {
833         check_diagnostics(
834             r#"
835 fn main() {
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
842
843     match (false, ((), false)) {
844         (true, ((), true)) => (),
845         (true, ((), false)) => (),
846         (false, ((), true)) => (),
847         (false, ((), false)) => (),
848     }
849     match (false, ((), false)) {
850         (true, ((), true)) => (),
851         (true, ((), false)) => (),
852         (false, _) => (),
853     }
854 }
855 "#,
856         );
857     }
858
859     #[test]
860     fn enums() {
861         check_diagnostics(
862             r#"
863 enum Either { A, B, }
864
865 fn main() {
866     match Either::A { }
867         //^^^^^^^^^ Missing match arm
868     match Either::B { Either::A => (), }
869         //^^^^^^^^^ Missing match arm
870
871     match &Either::B {
872         //^^^^^^^^^^ Missing match arm
873         Either::A => (),
874     }
875
876     match Either::B {
877         Either::A => (), Either::B => (),
878     }
879     match &Either::B {
880         Either::A => (), Either::B => (),
881     }
882 }
883 "#,
884         );
885     }
886
887     #[test]
888     fn enum_containing_bool() {
889         check_diagnostics(
890             r#"
891 enum Either { A(bool), B }
892
893 fn main() {
894     match Either::B { }
895         //^^^^^^^^^ Missing match arm
896     match Either::B {
897         //^^^^^^^^^ Missing match arm
898         Either::A(true) => (), Either::B => ()
899     }
900
901     match Either::B {
902         Either::A(true) => (),
903         Either::A(false) => (),
904         Either::B => (),
905     }
906     match Either::B {
907         Either::B => (),
908         _ => (),
909     }
910     match Either::B {
911         Either::A(_) => (),
912         Either::B => (),
913     }
914
915 }
916         "#,
917         );
918     }
919
920     #[test]
921     fn enum_different_sizes() {
922         check_diagnostics(
923             r#"
924 enum Either { A(bool), B(bool, bool) }
925
926 fn main() {
927     match Either::A(false) {
928         //^^^^^^^^^^^^^^^^ Missing match arm
929         Either::A(_) => (),
930         Either::B(false, _) => (),
931     }
932
933     match Either::A(false) {
934         Either::A(_) => (),
935         Either::B(true, _) => (),
936         Either::B(false, _) => (),
937     }
938     match Either::A(false) {
939         Either::A(true) | Either::A(false) => (),
940         Either::B(true, _) => (),
941         Either::B(false, _) => (),
942     }
943 }
944 "#,
945         );
946     }
947
948     #[test]
949     fn tuple_of_enum_no_diagnostic() {
950         check_diagnostics(
951             r#"
952 enum Either { A(bool), B(bool, bool) }
953 enum Either2 { C, D }
954
955 fn main() {
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) => (),
961     }
962 }
963 "#,
964         );
965     }
966
967     #[test]
968     fn or_pattern_no_diagnostic() {
969         check_diagnostics(
970             r#"
971 enum Either {A, B}
972
973 fn main() {
974     match (Either::A, Either::B) {
975         (Either::A | Either::B, _) => (),
976     }
977 }"#,
978         )
979     }
980
981     #[test]
982     fn mismatched_types() {
983         // Match statements with arms that don't match the
984         // expression pattern do not fire this diagnostic.
985         check_diagnostics(
986             r#"
987 enum Either { A, B }
988 enum Either2 { C, D }
989
990 fn main() {
991     match Either::A {
992         Either2::C => (),
993     //  ^^^^^^^^^^ Internal: match check bailed out
994         Either2::D => (),
995     }
996     match (true, false) {
997         (true, false, true) => (),
998     //  ^^^^^^^^^^^^^^^^^^^ Internal: match check bailed out
999         (true) => (),
1000     }
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 => () }
1006 }
1007         "#,
1008         );
1009     }
1010
1011     #[test]
1012     fn mismatched_types_in_or_patterns() {
1013         check_diagnostics(
1014             r#"
1015 fn main() {
1016     match false { true | () => {} }
1017     //            ^^^^^^^^^ Internal: match check bailed out
1018     match (false,) { (true | (),) => {} }
1019     //               ^^^^^^^^^^^^ Internal: match check bailed out
1020 }
1021 "#,
1022         );
1023     }
1024
1025     #[test]
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.
1029         check_diagnostics(
1030             r#"
1031 enum Either { A, B(u32) }
1032
1033 fn main() {
1034     match Either::A {
1035         Either::A => (),
1036         Either::B() => (),
1037     }
1038 }
1039 "#,
1040         );
1041     }
1042
1043     #[test]
1044     fn malformed_match_arm_extra_fields() {
1045         check_diagnostics(
1046             r#"
1047 enum A { B(isize, isize), C }
1048 fn main() {
1049     match A::B(1, 2) {
1050         A::B(_, _, _) => (),
1051     //  ^^^^^^^^^^^^^ Internal: match check bailed out
1052     }
1053     match A::B(1, 2) {
1054         A::C(_) => (),
1055     //  ^^^^^^^ Internal: match check bailed out
1056     }
1057 }
1058 "#,
1059         );
1060     }
1061
1062     #[test]
1063     fn expr_diverges() {
1064         check_diagnostics(
1065             r#"
1066 enum Either { A, B }
1067
1068 fn main() {
1069     match loop {} {
1070         Either::A => (),
1071     //  ^^^^^^^^^ Internal: match check bailed out
1072         Either::B => (),
1073     }
1074     match loop {} {
1075         Either::A => (),
1076     //  ^^^^^^^^^ Internal: match check bailed out
1077     }
1078     match loop { break Foo::A } {
1079         //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1080         Either::A => (),
1081     }
1082     match loop { break Foo::A } {
1083         Either::A => (),
1084         Either::B => (),
1085     }
1086 }
1087 "#,
1088         );
1089     }
1090
1091     #[test]
1092     fn expr_partially_diverges() {
1093         check_diagnostics(
1094             r#"
1095 enum Either<T> { A(T), B }
1096
1097 fn foo() -> Either<!> { Either::B }
1098 fn main() -> u32 {
1099     match foo() {
1100         Either::A(val) => val,
1101         Either::B => 0,
1102     }
1103 }
1104 "#,
1105         );
1106     }
1107
1108     #[test]
1109     fn enum_record() {
1110         check_diagnostics(
1111             r#"
1112 enum Either { A { foo: bool }, B }
1113
1114 fn main() {
1115     let a = Either::A { foo: true };
1116     match a { }
1117         //^ Missing match arm
1118     match a { Either::A { foo: true } => () }
1119         //^ Missing match arm
1120     match a {
1121         Either::A { } => (),
1122       //^^^^^^^^^ Missing structure fields:
1123       //        | - foo
1124         Either::B => (),
1125     }
1126     match a {
1127         //^ Missing match arm
1128         Either::A { } => (),
1129     } //^^^^^^^^^ Missing structure fields:
1130       //        | - foo
1131
1132     match a {
1133         Either::A { foo: true } => (),
1134         Either::A { foo: false } => (),
1135         Either::B => (),
1136     }
1137     match a {
1138         Either::A { foo: _ } => (),
1139         Either::B => (),
1140     }
1141 }
1142 "#,
1143         );
1144     }
1145
1146     #[test]
1147     fn enum_record_fields_out_of_order() {
1148         check_diagnostics(
1149             r#"
1150 enum Either {
1151     A { foo: bool, bar: () },
1152     B,
1153 }
1154
1155 fn main() {
1156     let a = Either::A { foo: true, bar: () };
1157     match a {
1158         //^ Missing match arm
1159         Either::A { bar: (), foo: false } => (),
1160         Either::A { foo: true, bar: () } => (),
1161     }
1162
1163     match a {
1164         Either::A { bar: (), foo: false } => (),
1165         Either::A { foo: true, bar: () } => (),
1166         Either::B => (),
1167     }
1168 }
1169 "#,
1170         );
1171     }
1172
1173     #[test]
1174     fn enum_record_ellipsis() {
1175         check_diagnostics(
1176             r#"
1177 enum Either {
1178     A { foo: bool, bar: bool },
1179     B,
1180 }
1181
1182 fn main() {
1183     let a = Either::B;
1184     match a {
1185         //^ Missing match arm
1186         Either::A { foo: true, .. } => (),
1187         Either::B => (),
1188     }
1189     match a {
1190         //^ Missing match arm
1191         Either::A { .. } => (),
1192     }
1193
1194     match a {
1195         Either::A { foo: true, .. } => (),
1196         Either::A { foo: false, .. } => (),
1197         Either::B => (),
1198     }
1199
1200     match a {
1201         Either::A { .. } => (),
1202         Either::B => (),
1203     }
1204 }
1205 "#,
1206         );
1207     }
1208
1209     #[test]
1210     fn enum_tuple_partial_ellipsis() {
1211         check_diagnostics(
1212             r#"
1213 enum Either {
1214     A(bool, bool, bool, bool),
1215     B,
1216 }
1217
1218 fn main() {
1219     match Either::B {
1220         //^^^^^^^^^ Missing match arm
1221         Either::A(true, .., true) => (),
1222         Either::A(true, .., false) => (),
1223         Either::A(false, .., false) => (),
1224         Either::B => (),
1225     }
1226     match Either::B {
1227         //^^^^^^^^^ Missing match arm
1228         Either::A(true, .., true) => (),
1229         Either::A(true, .., false) => (),
1230         Either::A(.., true) => (),
1231         Either::B => (),
1232     }
1233
1234     match Either::B {
1235         Either::A(true, .., true) => (),
1236         Either::A(true, .., false) => (),
1237         Either::A(false, .., true) => (),
1238         Either::A(false, .., false) => (),
1239         Either::B => (),
1240     }
1241     match Either::B {
1242         Either::A(true, .., true) => (),
1243         Either::A(true, .., false) => (),
1244         Either::A(.., true) => (),
1245         Either::A(.., false) => (),
1246         Either::B => (),
1247     }
1248 }
1249 "#,
1250         );
1251     }
1252
1253     #[test]
1254     fn never() {
1255         check_diagnostics(
1256             r#"
1257 enum Never {}
1258
1259 fn enum_(never: Never) {
1260     match never {}
1261 }
1262 fn enum_ref(never: &Never) {
1263     match never {}
1264         //^^^^^ Missing match arm
1265 }
1266 fn bang(never: !) {
1267     match never {}
1268 }
1269 "#,
1270         );
1271     }
1272
1273     #[test]
1274     fn unknown_type() {
1275         check_diagnostics(
1276             r#"
1277 enum Option<T> { Some(T), None }
1278
1279 fn main() {
1280     // `Never` is deliberately not defined so that it's an uninferred type.
1281     match Option::<Never>::None {
1282         None => (),
1283         Some(never) => match never {},
1284     //  ^^^^^^^^^^^ Internal: match check bailed out
1285     }
1286     match Option::<Never>::None {
1287         //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1288         Option::Some(_never) => {},
1289     }
1290 }
1291 "#,
1292         );
1293     }
1294
1295     #[test]
1296     fn tuple_of_bools_with_ellipsis_at_end_missing_arm() {
1297         check_diagnostics(
1298             r#"
1299 fn main() {
1300     match (false, true, false) {
1301         //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1302         (false, ..) => (),
1303     }
1304 }"#,
1305         );
1306     }
1307
1308     #[test]
1309     fn tuple_of_bools_with_ellipsis_at_beginning_missing_arm() {
1310         check_diagnostics(
1311             r#"
1312 fn main() {
1313     match (false, true, false) {
1314         //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1315         (.., false) => (),
1316     }
1317 }"#,
1318         );
1319     }
1320
1321     #[test]
1322     fn tuple_of_bools_with_ellipsis_in_middle_missing_arm() {
1323         check_diagnostics(
1324             r#"
1325 fn main() {
1326     match (false, true, false) {
1327         //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1328         (true, .., false) => (),
1329     }
1330 }"#,
1331         );
1332     }
1333
1334     #[test]
1335     fn record_struct() {
1336         check_diagnostics(
1337             r#"struct Foo { a: bool }
1338 fn main(f: Foo) {
1339     match f {}
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: _ } => () }
1346     match f {
1347         Foo { a: true } => (),
1348         Foo { a: false } => (),
1349     }
1350     match &f {
1351         Foo { a: true } => (),
1352         Foo { a: false } => (),
1353     }
1354 }
1355 "#,
1356         );
1357     }
1358
1359     #[test]
1360     fn tuple_struct() {
1361         check_diagnostics(
1362             r#"struct Foo(bool);
1363 fn main(f: Foo) {
1364     match f {}
1365         //^ Missing match arm
1366     match f { Foo(true) => () }
1367         //^ Missing match arm
1368     match f {
1369         Foo(true) => (),
1370         Foo(false) => (),
1371     }
1372 }
1373 "#,
1374         );
1375     }
1376
1377     #[test]
1378     fn unit_struct() {
1379         check_diagnostics(
1380             r#"struct Foo;
1381 fn main(f: Foo) {
1382     match f {}
1383         //^ Missing match arm
1384     match f { Foo => () }
1385 }
1386 "#,
1387         );
1388     }
1389
1390     #[test]
1391     fn record_struct_ellipsis() {
1392         check_diagnostics(
1393             r#"struct Foo { foo: bool, bar: bool }
1394 fn main(f: Foo) {
1395     match f { Foo { foo: true, .. } => () }
1396         //^ Missing match arm
1397     match f {
1398         //^ Missing match arm
1399         Foo { foo: true, .. } => (),
1400         Foo { bar: false, .. } => ()
1401     }
1402     match f { Foo { .. } => () }
1403     match f {
1404         Foo { foo: true, .. } => (),
1405         Foo { foo: false, .. } => ()
1406     }
1407 }
1408 "#,
1409         );
1410     }
1411
1412     #[test]
1413     fn internal_or() {
1414         check_diagnostics(
1415             r#"
1416 fn main() {
1417     enum Either { A(bool), B }
1418     match Either::B {
1419         //^^^^^^^^^ Missing match arm
1420         Either::A(true | false) => (),
1421     }
1422 }
1423 "#,
1424         );
1425     }
1426
1427     #[test]
1428     fn no_panic_at_unimplemented_subpattern_type() {
1429         check_diagnostics(
1430             r#"
1431 struct S { a: char}
1432 fn main(v: S) {
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{..}       => {} }
1438     match v { _           => {} }
1439     match v { }
1440         //^ Missing match arm
1441 }
1442 "#,
1443         );
1444     }
1445
1446     #[test]
1447     fn binding() {
1448         check_diagnostics(
1449             r#"
1450 fn main() {
1451     match true {
1452         _x @ true => {}
1453         false     => {}
1454     }
1455     match true { _x @ true => {} }
1456         //^^^^ Missing match arm
1457 }
1458 "#,
1459         );
1460     }
1461
1462     #[test]
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(..)`
1467         check_diagnostics(
1468             r#"
1469 enum Foo { A }
1470 fn main() {
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.
1473     match Foo::A {
1474         ref _x => {}
1475     //  ^^^^^^ Internal: match check bailed out
1476         Foo::A => {}
1477     }
1478     match (true,) {
1479         (ref _x,) => {}
1480         (true,) => {}
1481     }
1482 }
1483 "#,
1484         );
1485     }
1486
1487     #[test]
1488     fn enum_non_exhaustive() {
1489         check_diagnostics(
1490             r#"
1491 //- /lib.rs crate:lib
1492 #[non_exhaustive]
1493 pub enum E { A, B }
1494 fn _local() {
1495     match E::A { _ => {} }
1496     match E::A {
1497         E::A => {}
1498         E::B => {}
1499     }
1500     match E::A {
1501         E::A | E::B => {}
1502     }
1503 }
1504
1505 //- /main.rs crate:main deps:lib
1506 use lib::E;
1507 fn main() {
1508     match E::A { _ => {} }
1509     match E::A {
1510         //^^^^ Missing match arm
1511         E::A => {}
1512         E::B => {}
1513     }
1514     match E::A {
1515         //^^^^ Missing match arm
1516         E::A | E::B => {}
1517     }
1518 }
1519 "#,
1520         );
1521     }
1522
1523     #[test]
1524     fn match_guard() {
1525         check_diagnostics(
1526             r#"
1527 fn main() {
1528     match true {
1529         true if false => {}
1530         true          => {}
1531         false         => {}
1532     }
1533     match true {
1534         //^^^^ Missing match arm
1535         true if false => {}
1536         false         => {}
1537     }
1538 }
1539 "#,
1540         );
1541     }
1542
1543     #[test]
1544     fn pattern_type_is_of_substitution() {
1545         cov_mark::check!(match_check_wildcard_expanded_to_substitutions);
1546         check_diagnostics(
1547             r#"
1548 struct Foo<T>(T);
1549 struct Bar;
1550 fn main() {
1551     match Foo(Bar) {
1552         _ | Foo(Bar) => {}
1553     }
1554 }
1555 "#,
1556         );
1557     }
1558
1559     #[test]
1560     fn record_struct_no_such_field() {
1561         check_diagnostics(
1562             r#"
1563 struct Foo { }
1564 fn main(f: Foo) {
1565     match f { Foo { bar } => () }
1566     //        ^^^^^^^^^^^ Internal: match check bailed out
1567 }
1568 "#,
1569         );
1570     }
1571
1572     #[test]
1573     fn match_ergonomics_issue_9095() {
1574         check_diagnostics(
1575             r#"
1576 enum Foo<T> { A(T) }
1577 fn main() {
1578     match &Foo::A(true) {
1579         _ => {}
1580         Foo::A(_) => {}
1581     }
1582 }
1583 "#,
1584         );
1585     }
1586
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.
1592         //!
1593         //! The reasons for documenting known false negatives:
1594         //!
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.
1597         use super::*;
1598
1599         #[test]
1600         fn integers() {
1601             // We don't currently check integer exhaustiveness.
1602             check_diagnostics(
1603                 r#"
1604 fn main() {
1605     match 5 {
1606         10 => (),
1607     //  ^^ Internal: match check bailed out
1608         11..20 => (),
1609     }
1610 }
1611 "#,
1612             );
1613         }
1614
1615         #[test]
1616         fn reference_patterns_at_top_level() {
1617             check_diagnostics(
1618                 r#"
1619 fn main() {
1620     match &false {
1621         &true => {}
1622     //  ^^^^^ Internal: match check bailed out
1623     }
1624 }
1625             "#,
1626             );
1627         }
1628
1629         #[test]
1630         fn reference_patterns_in_fields() {
1631             check_diagnostics(
1632                 r#"
1633 fn main() {
1634     match (&false,) {
1635         (true,) => {}
1636     //  ^^^^^^^ Internal: match check bailed out
1637     }
1638     match (&false,) {
1639         (&true,) => {}
1640     //  ^^^^^^^^ Internal: match check bailed out
1641     }
1642 }
1643             "#,
1644             );
1645         }
1646     }
1647 }
1648
1649 #[cfg(test)]
1650 mod decl_check_tests {
1651     use crate::diagnostics::tests::check_diagnostics;
1652
1653     #[test]
1654     fn incorrect_function_name() {
1655         check_diagnostics(
1656             r#"
1657 fn NonSnakeCaseName() {}
1658 // ^^^^^^^^^^^^^^^^ Function `NonSnakeCaseName` should have snake_case name, e.g. `non_snake_case_name`
1659 "#,
1660         );
1661     }
1662
1663     #[test]
1664     fn incorrect_function_params() {
1665         check_diagnostics(
1666             r#"
1667 fn foo(SomeParam: u8) {}
1668     // ^^^^^^^^^ Parameter `SomeParam` should have snake_case name, e.g. `some_param`
1669
1670 fn foo2(ok_param: &str, CAPS_PARAM: u8) {}
1671                      // ^^^^^^^^^^ Parameter `CAPS_PARAM` should have snake_case name, e.g. `caps_param`
1672 "#,
1673         );
1674     }
1675
1676     #[test]
1677     fn incorrect_variable_names() {
1678         check_diagnostics(
1679             r#"
1680 fn foo() {
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`
1685 }
1686 "#,
1687         );
1688     }
1689
1690     #[test]
1691     fn incorrect_struct_names() {
1692         check_diagnostics(
1693             r#"
1694 struct non_camel_case_name {}
1695     // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName`
1696
1697 struct SCREAMING_CASE {}
1698     // ^^^^^^^^^^^^^^ Structure `SCREAMING_CASE` should have CamelCase name, e.g. `ScreamingCase`
1699 "#,
1700         );
1701     }
1702
1703     #[test]
1704     fn no_diagnostic_for_camel_cased_acronyms_in_struct_name() {
1705         check_diagnostics(
1706             r#"
1707 struct AABB {}
1708 "#,
1709         );
1710     }
1711
1712     #[test]
1713     fn incorrect_struct_field() {
1714         check_diagnostics(
1715             r#"
1716 struct SomeStruct { SomeField: u8 }
1717                  // ^^^^^^^^^ Field `SomeField` should have snake_case name, e.g. `some_field`
1718 "#,
1719         );
1720     }
1721
1722     #[test]
1723     fn incorrect_enum_names() {
1724         check_diagnostics(
1725             r#"
1726 enum some_enum { Val(u8) }
1727   // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum`
1728
1729 enum SOME_ENUM {}
1730   // ^^^^^^^^^ Enum `SOME_ENUM` should have CamelCase name, e.g. `SomeEnum`
1731 "#,
1732         );
1733     }
1734
1735     #[test]
1736     fn no_diagnostic_for_camel_cased_acronyms_in_enum_name() {
1737         check_diagnostics(
1738             r#"
1739 enum AABB {}
1740 "#,
1741         );
1742     }
1743
1744     #[test]
1745     fn incorrect_enum_variant_name() {
1746         check_diagnostics(
1747             r#"
1748 enum SomeEnum { SOME_VARIANT(u8) }
1749              // ^^^^^^^^^^^^ Variant `SOME_VARIANT` should have CamelCase name, e.g. `SomeVariant`
1750 "#,
1751         );
1752     }
1753
1754     #[test]
1755     fn incorrect_const_name() {
1756         check_diagnostics(
1757             r#"
1758 const some_weird_const: u8 = 10;
1759    // ^^^^^^^^^^^^^^^^ Constant `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
1760 "#,
1761         );
1762     }
1763
1764     #[test]
1765     fn incorrect_static_name() {
1766         check_diagnostics(
1767             r#"
1768 static some_weird_const: u8 = 10;
1769     // ^^^^^^^^^^^^^^^^ Static variable `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
1770 "#,
1771         );
1772     }
1773
1774     #[test]
1775     fn fn_inside_impl_struct() {
1776         check_diagnostics(
1777             r#"
1778 struct someStruct;
1779     // ^^^^^^^^^^ Structure `someStruct` should have CamelCase name, e.g. `SomeStruct`
1780
1781 impl 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`
1786     }
1787 }
1788 "#,
1789         );
1790     }
1791
1792     #[test]
1793     fn no_diagnostic_for_enum_varinats() {
1794         check_diagnostics(
1795             r#"
1796 enum Option { Some, None }
1797
1798 fn main() {
1799     match Option::None {
1800         None => (),
1801         Some => (),
1802     }
1803 }
1804 "#,
1805         );
1806     }
1807
1808     #[test]
1809     fn non_let_bind() {
1810         check_diagnostics(
1811             r#"
1812 enum Option { Some, None }
1813
1814 fn main() {
1815     match Option::None {
1816         SOME_VAR @ None => (),
1817      // ^^^^^^^^ Variable `SOME_VAR` should have snake_case name, e.g. `some_var`
1818         Some => (),
1819     }
1820 }
1821 "#,
1822         );
1823     }
1824
1825     #[test]
1826     fn allow_attributes() {
1827         check_diagnostics(
1828             r#"
1829 #[allow(non_snake_case)]
1830 fn NonSnakeCaseName(SOME_VAR: u8) -> u8{
1831     // cov_flags generated output from elsewhere in this file
1832     extern "C" {
1833         #[no_mangle]
1834         static lower_case: u8;
1835     }
1836
1837     let OtherVar = SOME_VAR + 1;
1838     OtherVar
1839 }
1840
1841 #[allow(nonstandard_style)]
1842 mod CheckNonstandardStyle {
1843     fn HiImABadFnName() {}
1844 }
1845
1846 #[allow(bad_style)]
1847 mod CheckBadStyle {
1848     fn HiImABadFnName() {}
1849 }
1850
1851 mod F {
1852     #![allow(non_snake_case)]
1853     fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {}
1854 }
1855
1856 #[allow(non_snake_case, non_camel_case_types)]
1857 pub struct some_type {
1858     SOME_FIELD: u8,
1859     SomeField: u16,
1860 }
1861
1862 #[allow(non_upper_case_globals)]
1863 pub const some_const: u8 = 10;
1864
1865 #[allow(non_upper_case_globals)]
1866 pub static SomeStatic: u8 = 10;
1867     "#,
1868         );
1869     }
1870
1871     #[test]
1872     fn allow_attributes_crate_attr() {
1873         check_diagnostics(
1874             r#"
1875 #![allow(non_snake_case)]
1876
1877 mod F {
1878     fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {}
1879 }
1880     "#,
1881         );
1882     }
1883
1884     #[test]
1885     #[ignore]
1886     fn bug_trait_inside_fn() {
1887         // FIXME:
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
1894         //   through modules
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
1898         //   module
1899         //
1900         // It should find the attribute on the trait, but it *doesn't even see
1901         // the trait* as far as I can tell.
1902
1903         check_diagnostics(
1904             r#"
1905 trait T { fn a(); }
1906 struct U {}
1907 impl T for U {
1908     fn a() {
1909         // this comes out of bitflags, mostly
1910         #[allow(non_snake_case)]
1911         trait __BitFlags {
1912             const HiImAlsoBad: u8 = 2;
1913             #[inline]
1914             fn Dirty(&self) -> bool {
1915                 false
1916             }
1917         }
1918
1919     }
1920 }
1921     "#,
1922         );
1923     }
1924
1925     #[test]
1926     #[ignore]
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.
1930         check_diagnostics(
1931             r#"
1932 trait BAD_TRAIT {
1933     // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait`
1934     fn BAD_FUNCTION();
1935     // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function`
1936     fn BadFunction();
1937     // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function`
1938 }
1939     "#,
1940         );
1941     }
1942
1943     #[test]
1944     fn ignores_extern_items() {
1945         cov_mark::check!(extern_func_incorrect_case_ignored);
1946         cov_mark::check!(extern_static_incorrect_case_ignored);
1947         check_diagnostics(
1948             r#"
1949 extern {
1950     fn NonSnakeCaseName(SOME_VAR: u8) -> u8;
1951     pub static SomeStatic: u8 = 10;
1952 }
1953             "#,
1954         );
1955     }
1956
1957     #[test]
1958     fn infinite_loop_inner_items() {
1959         check_diagnostics(
1960             r#"
1961 fn qualify() {
1962     mod foo {
1963         use super::*;
1964     }
1965 }
1966             "#,
1967         )
1968     }
1969
1970     #[test] // Issue #8809.
1971     fn parenthesized_parameter() {
1972         check_diagnostics(r#"fn f((O): _) {}"#)
1973     }
1974 }