]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/diagnostics.rs
minor
[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 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.
677
678         check_diagnostics(
679             r#"
680 //- /lib.rs crate:lib deps:jwt
681 mod permissions;
682
683 use permissions::jwt;
684
685 fn f() {
686     fn inner() {}
687     jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
688 }
689
690 //- /permissions.rs
691 pub mod jwt  {
692     pub struct Claims {}
693 }
694
695 //- /jwt/lib.rs crate:jwt
696 pub struct Claims {
697     field: u8,
698 }
699         "#,
700         );
701     }
702 }
703
704 #[cfg(test)]
705 pub(super) mod match_check_tests {
706     use crate::diagnostics::tests::check_diagnostics;
707
708     #[test]
709     fn empty_tuple() {
710         check_diagnostics(
711             r#"
712 fn main() {
713     match () { }
714         //^^ Missing match arm
715     match (()) { }
716         //^^^^ Missing match arm
717
718     match () { _ => (), }
719     match () { () => (), }
720     match (()) { (()) => (), }
721 }
722 "#,
723         );
724     }
725
726     #[test]
727     fn tuple_of_two_empty_tuple() {
728         check_diagnostics(
729             r#"
730 fn main() {
731     match ((), ()) { }
732         //^^^^^^^^ Missing match arm
733
734     match ((), ()) { ((), ()) => (), }
735 }
736 "#,
737         );
738     }
739
740     #[test]
741     fn boolean() {
742         check_diagnostics(
743             r#"
744 fn test_main() {
745     match false { }
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
755         (false, true) => (),
756         (false, false) => (),
757         (true, false) => (),
758     }
759     match (false, true) { (true, _x) => (), }
760         //^^^^^^^^^^^^^ Missing match arm
761
762     match false { true => (), false => (), }
763     match (false, true) {
764         (false, _) => (),
765         (true, false) => (),
766         (_, true) => (),
767     }
768     match (false, true) {
769         (true, true) => (),
770         (true, false) => (),
771         (false, true) => (),
772         (false, false) => (),
773     }
774     match (false, true) {
775         (true, _x) => (),
776         (false, true) => (),
777         (false, false) => (),
778     }
779     match (false, true, false) {
780         (false, ..) => (),
781         (true, ..) => (),
782     }
783     match (false, true, false) {
784         (.., false) => (),
785         (.., true) => (),
786     }
787     match (false, true, false) { (..) => (), }
788 }
789 "#,
790         );
791     }
792
793     #[test]
794     fn tuple_of_tuple_and_bools() {
795         check_diagnostics(
796             r#"
797 fn main() {
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
804
805     match (false, ((), false)) {
806         (true, ((), true)) => (),
807         (true, ((), false)) => (),
808         (false, ((), true)) => (),
809         (false, ((), false)) => (),
810     }
811     match (false, ((), false)) {
812         (true, ((), true)) => (),
813         (true, ((), false)) => (),
814         (false, _) => (),
815     }
816 }
817 "#,
818         );
819     }
820
821     #[test]
822     fn enums() {
823         check_diagnostics(
824             r#"
825 enum Either { A, B, }
826
827 fn main() {
828     match Either::A { }
829         //^^^^^^^^^ Missing match arm
830     match Either::B { Either::A => (), }
831         //^^^^^^^^^ Missing match arm
832
833     match &Either::B {
834         //^^^^^^^^^^ Missing match arm
835         Either::A => (),
836     }
837
838     match Either::B {
839         Either::A => (), Either::B => (),
840     }
841     match &Either::B {
842         Either::A => (), Either::B => (),
843     }
844 }
845 "#,
846         );
847     }
848
849     #[test]
850     fn enum_containing_bool() {
851         check_diagnostics(
852             r#"
853 enum Either { A(bool), B }
854
855 fn main() {
856     match Either::B { }
857         //^^^^^^^^^ Missing match arm
858     match Either::B {
859         //^^^^^^^^^ Missing match arm
860         Either::A(true) => (), Either::B => ()
861     }
862
863     match Either::B {
864         Either::A(true) => (),
865         Either::A(false) => (),
866         Either::B => (),
867     }
868     match Either::B {
869         Either::B => (),
870         _ => (),
871     }
872     match Either::B {
873         Either::A(_) => (),
874         Either::B => (),
875     }
876
877 }
878         "#,
879         );
880     }
881
882     #[test]
883     fn enum_different_sizes() {
884         check_diagnostics(
885             r#"
886 enum Either { A(bool), B(bool, bool) }
887
888 fn main() {
889     match Either::A(false) {
890         //^^^^^^^^^^^^^^^^ Missing match arm
891         Either::A(_) => (),
892         Either::B(false, _) => (),
893     }
894
895     match Either::A(false) {
896         Either::A(_) => (),
897         Either::B(true, _) => (),
898         Either::B(false, _) => (),
899     }
900     match Either::A(false) {
901         Either::A(true) | Either::A(false) => (),
902         Either::B(true, _) => (),
903         Either::B(false, _) => (),
904     }
905 }
906 "#,
907         );
908     }
909
910     #[test]
911     fn tuple_of_enum_no_diagnostic() {
912         check_diagnostics(
913             r#"
914 enum Either { A(bool), B(bool, bool) }
915 enum Either2 { C, D }
916
917 fn main() {
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) => (),
923     }
924 }
925 "#,
926         );
927     }
928
929     #[test]
930     fn or_pattern_no_diagnostic() {
931         check_diagnostics(
932             r#"
933 enum Either {A, B}
934
935 fn main() {
936     match (Either::A, Either::B) {
937         (Either::A | Either::B, _) => (),
938     }
939 }"#,
940         )
941     }
942
943     #[test]
944     fn mismatched_types() {
945         // Match statements with arms that don't match the
946         // expression pattern do not fire this diagnostic.
947         check_diagnostics(
948             r#"
949 enum Either { A, B }
950 enum Either2 { C, D }
951
952 fn main() {
953     match Either::A {
954         Either2::C => (),
955     //  ^^^^^^^^^^ Internal: match check bailed out
956         Either2::D => (),
957     }
958     match (true, false) {
959         (true, false, true) => (),
960     //  ^^^^^^^^^^^^^^^^^^^ Internal: match check bailed out
961         (true) => (),
962     }
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 => () }
968 }
969         "#,
970         );
971     }
972
973     #[test]
974     fn mismatched_types_in_or_patterns() {
975         check_diagnostics(
976             r#"
977 fn main() {
978     match false { true | () => {} }
979     //            ^^^^^^^^^ Internal: match check bailed out
980     match (false,) { (true | (),) => {} }
981     //               ^^^^^^^^^^^^ Internal: match check bailed out
982 }
983 "#,
984         );
985     }
986
987     #[test]
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.
991         check_diagnostics(
992             r#"
993 enum Either { A, B(u32) }
994
995 fn main() {
996     match Either::A {
997         Either::A => (),
998         Either::B() => (),
999     }
1000 }
1001 "#,
1002         );
1003     }
1004
1005     #[test]
1006     fn malformed_match_arm_extra_fields() {
1007         check_diagnostics(
1008             r#"
1009 enum A { B(isize, isize), C }
1010 fn main() {
1011     match A::B(1, 2) {
1012         A::B(_, _, _) => (),
1013     //  ^^^^^^^^^^^^^ Internal: match check bailed out
1014     }
1015     match A::B(1, 2) {
1016         A::C(_) => (),
1017     //  ^^^^^^^ Internal: match check bailed out
1018     }
1019 }
1020 "#,
1021         );
1022     }
1023
1024     #[test]
1025     fn expr_diverges() {
1026         check_diagnostics(
1027             r#"
1028 enum Either { A, B }
1029
1030 fn main() {
1031     match loop {} {
1032         Either::A => (),
1033     //  ^^^^^^^^^ Internal: match check bailed out
1034         Either::B => (),
1035     }
1036     match loop {} {
1037         Either::A => (),
1038     //  ^^^^^^^^^ Internal: match check bailed out
1039     }
1040     match loop { break Foo::A } {
1041         //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1042         Either::A => (),
1043     }
1044     match loop { break Foo::A } {
1045         Either::A => (),
1046         Either::B => (),
1047     }
1048 }
1049 "#,
1050         );
1051     }
1052
1053     #[test]
1054     fn expr_partially_diverges() {
1055         check_diagnostics(
1056             r#"
1057 enum Either<T> { A(T), B }
1058
1059 fn foo() -> Either<!> { Either::B }
1060 fn main() -> u32 {
1061     match foo() {
1062         Either::A(val) => val,
1063         Either::B => 0,
1064     }
1065 }
1066 "#,
1067         );
1068     }
1069
1070     #[test]
1071     fn enum_record() {
1072         check_diagnostics(
1073             r#"
1074 enum Either { A { foo: bool }, B }
1075
1076 fn main() {
1077     let a = Either::A { foo: true };
1078     match a { }
1079         //^ Missing match arm
1080     match a { Either::A { foo: true } => () }
1081         //^ Missing match arm
1082     match a {
1083         Either::A { } => (),
1084       //^^^^^^^^^ Missing structure fields:
1085       //        | - foo
1086         Either::B => (),
1087     }
1088     match a {
1089         //^ Missing match arm
1090         Either::A { } => (),
1091     } //^^^^^^^^^ Missing structure fields:
1092       //        | - foo
1093
1094     match a {
1095         Either::A { foo: true } => (),
1096         Either::A { foo: false } => (),
1097         Either::B => (),
1098     }
1099     match a {
1100         Either::A { foo: _ } => (),
1101         Either::B => (),
1102     }
1103 }
1104 "#,
1105         );
1106     }
1107
1108     #[test]
1109     fn enum_record_fields_out_of_order() {
1110         check_diagnostics(
1111             r#"
1112 enum Either {
1113     A { foo: bool, bar: () },
1114     B,
1115 }
1116
1117 fn main() {
1118     let a = Either::A { foo: true, bar: () };
1119     match a {
1120         //^ Missing match arm
1121         Either::A { bar: (), foo: false } => (),
1122         Either::A { foo: true, bar: () } => (),
1123     }
1124
1125     match a {
1126         Either::A { bar: (), foo: false } => (),
1127         Either::A { foo: true, bar: () } => (),
1128         Either::B => (),
1129     }
1130 }
1131 "#,
1132         );
1133     }
1134
1135     #[test]
1136     fn enum_record_ellipsis() {
1137         check_diagnostics(
1138             r#"
1139 enum Either {
1140     A { foo: bool, bar: bool },
1141     B,
1142 }
1143
1144 fn main() {
1145     let a = Either::B;
1146     match a {
1147         //^ Missing match arm
1148         Either::A { foo: true, .. } => (),
1149         Either::B => (),
1150     }
1151     match a {
1152         //^ Missing match arm
1153         Either::A { .. } => (),
1154     }
1155
1156     match a {
1157         Either::A { foo: true, .. } => (),
1158         Either::A { foo: false, .. } => (),
1159         Either::B => (),
1160     }
1161
1162     match a {
1163         Either::A { .. } => (),
1164         Either::B => (),
1165     }
1166 }
1167 "#,
1168         );
1169     }
1170
1171     #[test]
1172     fn enum_tuple_partial_ellipsis() {
1173         check_diagnostics(
1174             r#"
1175 enum Either {
1176     A(bool, bool, bool, bool),
1177     B,
1178 }
1179
1180 fn main() {
1181     match Either::B {
1182         //^^^^^^^^^ Missing match arm
1183         Either::A(true, .., true) => (),
1184         Either::A(true, .., false) => (),
1185         Either::A(false, .., false) => (),
1186         Either::B => (),
1187     }
1188     match Either::B {
1189         //^^^^^^^^^ Missing match arm
1190         Either::A(true, .., true) => (),
1191         Either::A(true, .., false) => (),
1192         Either::A(.., true) => (),
1193         Either::B => (),
1194     }
1195
1196     match Either::B {
1197         Either::A(true, .., true) => (),
1198         Either::A(true, .., false) => (),
1199         Either::A(false, .., true) => (),
1200         Either::A(false, .., false) => (),
1201         Either::B => (),
1202     }
1203     match Either::B {
1204         Either::A(true, .., true) => (),
1205         Either::A(true, .., false) => (),
1206         Either::A(.., true) => (),
1207         Either::A(.., false) => (),
1208         Either::B => (),
1209     }
1210 }
1211 "#,
1212         );
1213     }
1214
1215     #[test]
1216     fn never() {
1217         check_diagnostics(
1218             r#"
1219 enum Never {}
1220
1221 fn enum_(never: Never) {
1222     match never {}
1223 }
1224 fn enum_ref(never: &Never) {
1225     match never {}
1226         //^^^^^ Missing match arm
1227 }
1228 fn bang(never: !) {
1229     match never {}
1230 }
1231 "#,
1232         );
1233     }
1234
1235     #[test]
1236     fn unknown_type() {
1237         check_diagnostics(
1238             r#"
1239 enum Option<T> { Some(T), None }
1240
1241 fn main() {
1242     // `Never` is deliberately not defined so that it's an uninferred type.
1243     match Option::<Never>::None {
1244         None => (),
1245         Some(never) => match never {},
1246     //  ^^^^^^^^^^^ Internal: match check bailed out
1247     }
1248     match Option::<Never>::None {
1249         //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1250         Option::Some(_never) => {},
1251     }
1252 }
1253 "#,
1254         );
1255     }
1256
1257     #[test]
1258     fn tuple_of_bools_with_ellipsis_at_end_missing_arm() {
1259         check_diagnostics(
1260             r#"
1261 fn main() {
1262     match (false, true, false) {
1263         //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1264         (false, ..) => (),
1265     }
1266 }"#,
1267         );
1268     }
1269
1270     #[test]
1271     fn tuple_of_bools_with_ellipsis_at_beginning_missing_arm() {
1272         check_diagnostics(
1273             r#"
1274 fn main() {
1275     match (false, true, false) {
1276         //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1277         (.., false) => (),
1278     }
1279 }"#,
1280         );
1281     }
1282
1283     #[test]
1284     fn tuple_of_bools_with_ellipsis_in_middle_missing_arm() {
1285         check_diagnostics(
1286             r#"
1287 fn main() {
1288     match (false, true, false) {
1289         //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1290         (true, .., false) => (),
1291     }
1292 }"#,
1293         );
1294     }
1295
1296     #[test]
1297     fn record_struct() {
1298         check_diagnostics(
1299             r#"struct Foo { a: bool }
1300 fn main(f: Foo) {
1301     match f {}
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: _ } => () }
1308     match f {
1309         Foo { a: true } => (),
1310         Foo { a: false } => (),
1311     }
1312     match &f {
1313         Foo { a: true } => (),
1314         Foo { a: false } => (),
1315     }
1316 }
1317 "#,
1318         );
1319     }
1320
1321     #[test]
1322     fn tuple_struct() {
1323         check_diagnostics(
1324             r#"struct Foo(bool);
1325 fn main(f: Foo) {
1326     match f {}
1327         //^ Missing match arm
1328     match f { Foo(true) => () }
1329         //^ Missing match arm
1330     match f {
1331         Foo(true) => (),
1332         Foo(false) => (),
1333     }
1334 }
1335 "#,
1336         );
1337     }
1338
1339     #[test]
1340     fn unit_struct() {
1341         check_diagnostics(
1342             r#"struct Foo;
1343 fn main(f: Foo) {
1344     match f {}
1345         //^ Missing match arm
1346     match f { Foo => () }
1347 }
1348 "#,
1349         );
1350     }
1351
1352     #[test]
1353     fn record_struct_ellipsis() {
1354         check_diagnostics(
1355             r#"struct Foo { foo: bool, bar: bool }
1356 fn main(f: Foo) {
1357     match f { Foo { foo: true, .. } => () }
1358         //^ Missing match arm
1359     match f {
1360         //^ Missing match arm
1361         Foo { foo: true, .. } => (),
1362         Foo { bar: false, .. } => ()
1363     }
1364     match f { Foo { .. } => () }
1365     match f {
1366         Foo { foo: true, .. } => (),
1367         Foo { foo: false, .. } => ()
1368     }
1369 }
1370 "#,
1371         );
1372     }
1373
1374     #[test]
1375     fn internal_or() {
1376         check_diagnostics(
1377             r#"
1378 fn main() {
1379     enum Either { A(bool), B }
1380     match Either::B {
1381         //^^^^^^^^^ Missing match arm
1382         Either::A(true | false) => (),
1383     }
1384 }
1385 "#,
1386         );
1387     }
1388
1389     #[test]
1390     fn no_panic_at_unimplemented_subpattern_type() {
1391         check_diagnostics(
1392             r#"
1393 struct S { a: char}
1394 fn main(v: S) {
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{..}       => {} }
1400     match v { _           => {} }
1401     match v { }
1402         //^ Missing match arm
1403 }
1404 "#,
1405         );
1406     }
1407
1408     #[test]
1409     fn binding() {
1410         check_diagnostics(
1411             r#"
1412 fn main() {
1413     match true {
1414         _x @ true => {}
1415         false     => {}
1416     }
1417     match true { _x @ true => {} }
1418         //^^^^ Missing match arm
1419 }
1420 "#,
1421         );
1422     }
1423
1424     #[test]
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(..)`
1429         check_diagnostics(
1430             r#"
1431 enum Foo { A }
1432 fn main() {
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.
1435     match Foo::A {
1436         ref _x => {}
1437     //  ^^^^^^ Internal: match check bailed out
1438         Foo::A => {}
1439     }
1440     match (true,) {
1441         (ref _x,) => {}
1442         (true,) => {}
1443     }
1444 }
1445 "#,
1446         );
1447     }
1448
1449     #[test]
1450     fn enum_non_exhaustive() {
1451         check_diagnostics(
1452             r#"
1453 //- /lib.rs crate:lib
1454 #[non_exhaustive]
1455 pub enum E { A, B }
1456 fn _local() {
1457     match E::A { _ => {} }
1458     match E::A {
1459         E::A => {}
1460         E::B => {}
1461     }
1462     match E::A {
1463         E::A | E::B => {}
1464     }
1465 }
1466
1467 //- /main.rs crate:main deps:lib
1468 use lib::E;
1469 fn main() {
1470     match E::A { _ => {} }
1471     match E::A {
1472         //^^^^ Missing match arm
1473         E::A => {}
1474         E::B => {}
1475     }
1476     match E::A {
1477         //^^^^ Missing match arm
1478         E::A | E::B => {}
1479     }
1480 }
1481 "#,
1482         );
1483     }
1484
1485     #[test]
1486     fn match_guard() {
1487         check_diagnostics(
1488             r#"
1489 fn main() {
1490     match true {
1491         true if false => {}
1492         true          => {}
1493         false         => {}
1494     }
1495     match true {
1496         //^^^^ Missing match arm
1497         true if false => {}
1498         false         => {}
1499     }
1500 }
1501 "#,
1502         );
1503     }
1504
1505     #[test]
1506     fn pattern_type_is_of_substitution() {
1507         cov_mark::check!(match_check_wildcard_expanded_to_substitutions);
1508         check_diagnostics(
1509             r#"
1510 struct Foo<T>(T);
1511 struct Bar;
1512 fn main() {
1513     match Foo(Bar) {
1514         _ | Foo(Bar) => {}
1515     }
1516 }
1517 "#,
1518         );
1519     }
1520
1521     #[test]
1522     fn record_struct_no_such_field() {
1523         check_diagnostics(
1524             r#"
1525 struct Foo { }
1526 fn main(f: Foo) {
1527     match f { Foo { bar } => () }
1528     //        ^^^^^^^^^^^ Internal: match check bailed out
1529 }
1530 "#,
1531         );
1532     }
1533
1534     #[test]
1535     fn match_ergonomics_issue_9095() {
1536         check_diagnostics(
1537             r#"
1538 enum Foo<T> { A(T) }
1539 fn main() {
1540     match &Foo::A(true) {
1541         _ => {}
1542         Foo::A(_) => {}
1543     }
1544 }
1545 "#,
1546         );
1547     }
1548
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.
1554         //!
1555         //! The reasons for documenting known false negatives:
1556         //!
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.
1559         use super::*;
1560
1561         #[test]
1562         fn integers() {
1563             // We don't currently check integer exhaustiveness.
1564             check_diagnostics(
1565                 r#"
1566 fn main() {
1567     match 5 {
1568         10 => (),
1569     //  ^^ Internal: match check bailed out
1570         11..20 => (),
1571     }
1572 }
1573 "#,
1574             );
1575         }
1576
1577         #[test]
1578         fn reference_patterns_at_top_level() {
1579             check_diagnostics(
1580                 r#"
1581 fn main() {
1582     match &false {
1583         &true => {}
1584     //  ^^^^^ Internal: match check bailed out
1585     }
1586 }
1587             "#,
1588             );
1589         }
1590
1591         #[test]
1592         fn reference_patterns_in_fields() {
1593             check_diagnostics(
1594                 r#"
1595 fn main() {
1596     match (&false,) {
1597         (true,) => {}
1598     //  ^^^^^^^ Internal: match check bailed out
1599     }
1600     match (&false,) {
1601         (&true,) => {}
1602     //  ^^^^^^^^ Internal: match check bailed out
1603     }
1604 }
1605             "#,
1606             );
1607         }
1608     }
1609 }
1610
1611 #[cfg(test)]
1612 mod decl_check_tests {
1613     use crate::diagnostics::tests::check_diagnostics;
1614
1615     #[test]
1616     fn incorrect_function_name() {
1617         check_diagnostics(
1618             r#"
1619 fn NonSnakeCaseName() {}
1620 // ^^^^^^^^^^^^^^^^ Function `NonSnakeCaseName` should have snake_case name, e.g. `non_snake_case_name`
1621 "#,
1622         );
1623     }
1624
1625     #[test]
1626     fn incorrect_function_params() {
1627         check_diagnostics(
1628             r#"
1629 fn foo(SomeParam: u8) {}
1630     // ^^^^^^^^^ Parameter `SomeParam` should have snake_case name, e.g. `some_param`
1631
1632 fn foo2(ok_param: &str, CAPS_PARAM: u8) {}
1633                      // ^^^^^^^^^^ Parameter `CAPS_PARAM` should have snake_case name, e.g. `caps_param`
1634 "#,
1635         );
1636     }
1637
1638     #[test]
1639     fn incorrect_variable_names() {
1640         check_diagnostics(
1641             r#"
1642 fn foo() {
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`
1647 }
1648 "#,
1649         );
1650     }
1651
1652     #[test]
1653     fn incorrect_struct_names() {
1654         check_diagnostics(
1655             r#"
1656 struct non_camel_case_name {}
1657     // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName`
1658
1659 struct SCREAMING_CASE {}
1660     // ^^^^^^^^^^^^^^ Structure `SCREAMING_CASE` should have CamelCase name, e.g. `ScreamingCase`
1661 "#,
1662         );
1663     }
1664
1665     #[test]
1666     fn no_diagnostic_for_camel_cased_acronyms_in_struct_name() {
1667         check_diagnostics(
1668             r#"
1669 struct AABB {}
1670 "#,
1671         );
1672     }
1673
1674     #[test]
1675     fn incorrect_struct_field() {
1676         check_diagnostics(
1677             r#"
1678 struct SomeStruct { SomeField: u8 }
1679                  // ^^^^^^^^^ Field `SomeField` should have snake_case name, e.g. `some_field`
1680 "#,
1681         );
1682     }
1683
1684     #[test]
1685     fn incorrect_enum_names() {
1686         check_diagnostics(
1687             r#"
1688 enum some_enum { Val(u8) }
1689   // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum`
1690
1691 enum SOME_ENUM {}
1692   // ^^^^^^^^^ Enum `SOME_ENUM` should have CamelCase name, e.g. `SomeEnum`
1693 "#,
1694         );
1695     }
1696
1697     #[test]
1698     fn no_diagnostic_for_camel_cased_acronyms_in_enum_name() {
1699         check_diagnostics(
1700             r#"
1701 enum AABB {}
1702 "#,
1703         );
1704     }
1705
1706     #[test]
1707     fn incorrect_enum_variant_name() {
1708         check_diagnostics(
1709             r#"
1710 enum SomeEnum { SOME_VARIANT(u8) }
1711              // ^^^^^^^^^^^^ Variant `SOME_VARIANT` should have CamelCase name, e.g. `SomeVariant`
1712 "#,
1713         );
1714     }
1715
1716     #[test]
1717     fn incorrect_const_name() {
1718         check_diagnostics(
1719             r#"
1720 const some_weird_const: u8 = 10;
1721    // ^^^^^^^^^^^^^^^^ Constant `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
1722 "#,
1723         );
1724     }
1725
1726     #[test]
1727     fn incorrect_static_name() {
1728         check_diagnostics(
1729             r#"
1730 static some_weird_const: u8 = 10;
1731     // ^^^^^^^^^^^^^^^^ Static variable `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
1732 "#,
1733         );
1734     }
1735
1736     #[test]
1737     fn fn_inside_impl_struct() {
1738         check_diagnostics(
1739             r#"
1740 struct someStruct;
1741     // ^^^^^^^^^^ Structure `someStruct` should have CamelCase name, e.g. `SomeStruct`
1742
1743 impl 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`
1748     }
1749 }
1750 "#,
1751         );
1752     }
1753
1754     #[test]
1755     fn no_diagnostic_for_enum_varinats() {
1756         check_diagnostics(
1757             r#"
1758 enum Option { Some, None }
1759
1760 fn main() {
1761     match Option::None {
1762         None => (),
1763         Some => (),
1764     }
1765 }
1766 "#,
1767         );
1768     }
1769
1770     #[test]
1771     fn non_let_bind() {
1772         check_diagnostics(
1773             r#"
1774 enum Option { Some, None }
1775
1776 fn main() {
1777     match Option::None {
1778         SOME_VAR @ None => (),
1779      // ^^^^^^^^ Variable `SOME_VAR` should have snake_case name, e.g. `some_var`
1780         Some => (),
1781     }
1782 }
1783 "#,
1784         );
1785     }
1786
1787     #[test]
1788     fn allow_attributes() {
1789         check_diagnostics(
1790             r#"
1791 #[allow(non_snake_case)]
1792 fn NonSnakeCaseName(SOME_VAR: u8) -> u8{
1793     // cov_flags generated output from elsewhere in this file
1794     extern "C" {
1795         #[no_mangle]
1796         static lower_case: u8;
1797     }
1798
1799     let OtherVar = SOME_VAR + 1;
1800     OtherVar
1801 }
1802
1803 #[allow(nonstandard_style)]
1804 mod CheckNonstandardStyle {
1805     fn HiImABadFnName() {}
1806 }
1807
1808 #[allow(bad_style)]
1809 mod CheckBadStyle {
1810     fn HiImABadFnName() {}
1811 }
1812
1813 mod F {
1814     #![allow(non_snake_case)]
1815     fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {}
1816 }
1817
1818 #[allow(non_snake_case, non_camel_case_types)]
1819 pub struct some_type {
1820     SOME_FIELD: u8,
1821     SomeField: u16,
1822 }
1823
1824 #[allow(non_upper_case_globals)]
1825 pub const some_const: u8 = 10;
1826
1827 #[allow(non_upper_case_globals)]
1828 pub static SomeStatic: u8 = 10;
1829     "#,
1830         );
1831     }
1832
1833     #[test]
1834     fn allow_attributes_crate_attr() {
1835         check_diagnostics(
1836             r#"
1837 #![allow(non_snake_case)]
1838
1839 mod F {
1840     fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {}
1841 }
1842     "#,
1843         );
1844     }
1845
1846     #[test]
1847     #[ignore]
1848     fn bug_trait_inside_fn() {
1849         // FIXME:
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
1856         //   through modules
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
1860         //   module
1861         //
1862         // It should find the attribute on the trait, but it *doesn't even see
1863         // the trait* as far as I can tell.
1864
1865         check_diagnostics(
1866             r#"
1867 trait T { fn a(); }
1868 struct U {}
1869 impl T for U {
1870     fn a() {
1871         // this comes out of bitflags, mostly
1872         #[allow(non_snake_case)]
1873         trait __BitFlags {
1874             const HiImAlsoBad: u8 = 2;
1875             #[inline]
1876             fn Dirty(&self) -> bool {
1877                 false
1878             }
1879         }
1880
1881     }
1882 }
1883     "#,
1884         );
1885     }
1886
1887     #[test]
1888     #[ignore]
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.
1892         check_diagnostics(
1893             r#"
1894 trait BAD_TRAIT {
1895     // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait`
1896     fn BAD_FUNCTION();
1897     // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function`
1898     fn BadFunction();
1899     // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function`
1900 }
1901     "#,
1902         );
1903     }
1904
1905     #[test]
1906     fn ignores_extern_items() {
1907         cov_mark::check!(extern_func_incorrect_case_ignored);
1908         cov_mark::check!(extern_static_incorrect_case_ignored);
1909         check_diagnostics(
1910             r#"
1911 extern {
1912     fn NonSnakeCaseName(SOME_VAR: u8) -> u8;
1913     pub static SomeStatic: u8 = 10;
1914 }
1915             "#,
1916         );
1917     }
1918
1919     #[test]
1920     fn infinite_loop_inner_items() {
1921         check_diagnostics(
1922             r#"
1923 fn qualify() {
1924     mod foo {
1925         use super::*;
1926     }
1927 }
1928             "#,
1929         )
1930     }
1931
1932     #[test] // Issue #8809.
1933     fn parenthesized_parameter() {
1934         check_diagnostics(r#"fn f((O): _) {}"#)
1935     }
1936 }