]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/diagnostics.rs
internal: unified missing fields 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 unresolved_module;
8 mod missing_fields;
9
10 mod fixes;
11 mod field_shorthand;
12 mod unlinked_file;
13
14 use std::cell::RefCell;
15
16 use hir::{
17     db::AstDatabase,
18     diagnostics::{AnyDiagnostic, Diagnostic as _, DiagnosticCode, DiagnosticSinkBuilder},
19     InFile, Semantics,
20 };
21 use ide_assists::AssistResolveStrategy;
22 use ide_db::{base_db::SourceDatabase, RootDatabase};
23 use itertools::Itertools;
24 use rustc_hash::FxHashSet;
25 use syntax::{
26     ast::{self, AstNode},
27     SyntaxNode, SyntaxNodePtr, TextRange, TextSize,
28 };
29 use text_edit::TextEdit;
30 use unlinked_file::UnlinkedFile;
31
32 use crate::{Assist, AssistId, AssistKind, FileId, Label, SourceChange};
33
34 use self::fixes::DiagnosticWithFixes;
35
36 #[derive(Debug)]
37 pub struct Diagnostic {
38     // pub name: Option<String>,
39     pub message: String,
40     pub range: TextRange,
41     pub severity: Severity,
42     pub fixes: Option<Vec<Assist>>,
43     pub unused: bool,
44     pub code: Option<DiagnosticCode>,
45 }
46
47 impl Diagnostic {
48     fn new(code: &'static str, message: impl Into<String>, range: TextRange) -> Diagnostic {
49         let message = message.into();
50         let code = Some(DiagnosticCode(code));
51         Self { message, range, severity: Severity::Error, fixes: None, unused: false, code }
52     }
53
54     fn error(range: TextRange, message: String) -> Self {
55         Self { message, range, severity: Severity::Error, fixes: None, unused: false, code: None }
56     }
57
58     fn hint(range: TextRange, message: String) -> Self {
59         Self {
60             message,
61             range,
62             severity: Severity::WeakWarning,
63             fixes: None,
64             unused: false,
65             code: None,
66         }
67     }
68
69     fn with_fixes(self, fixes: Option<Vec<Assist>>) -> Self {
70         Self { fixes, ..self }
71     }
72
73     fn with_unused(self, unused: bool) -> Self {
74         Self { unused, ..self }
75     }
76
77     fn with_code(self, code: Option<DiagnosticCode>) -> Self {
78         Self { code, ..self }
79     }
80 }
81
82 #[derive(Debug, Copy, Clone)]
83 pub enum Severity {
84     Error,
85     WeakWarning,
86 }
87
88 #[derive(Default, Debug, Clone)]
89 pub struct DiagnosticsConfig {
90     pub disable_experimental: bool,
91     pub disabled: FxHashSet<String>,
92 }
93
94 struct DiagnosticsContext<'a> {
95     config: &'a DiagnosticsConfig,
96     sema: Semantics<'a, RootDatabase>,
97     #[allow(unused)]
98     resolve: &'a AssistResolveStrategy,
99 }
100
101 pub(crate) fn diagnostics(
102     db: &RootDatabase,
103     config: &DiagnosticsConfig,
104     resolve: &AssistResolveStrategy,
105     file_id: FileId,
106 ) -> Vec<Diagnostic> {
107     let _p = profile::span("diagnostics");
108     let sema = Semantics::new(db);
109     let parse = db.parse(file_id);
110     let mut res = Vec::new();
111
112     // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
113     res.extend(
114         parse
115             .errors()
116             .iter()
117             .take(128)
118             .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
119     );
120
121     for node in parse.tree().syntax().descendants() {
122         check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
123         field_shorthand::check(&mut res, file_id, &node);
124     }
125     let res = RefCell::new(res);
126     let sink_builder = DiagnosticSinkBuilder::new()
127         .on::<hir::diagnostics::MissingOkOrSomeInTailExpr, _>(|d| {
128             res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
129         })
130         .on::<hir::diagnostics::NoSuchField, _>(|d| {
131             res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
132         })
133         .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| {
134             res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
135         })
136         .on::<hir::diagnostics::IncorrectCase, _>(|d| {
137             res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
138         })
139         .on::<hir::diagnostics::ReplaceFilterMapNextWithFindMap, _>(|d| {
140             res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
141         })
142         .on::<hir::diagnostics::InactiveCode, _>(|d| {
143             // If there's inactive code somewhere in a macro, don't propagate to the call-site.
144             if d.display_source().file_id.expansion_info(db).is_some() {
145                 return;
146             }
147
148             // Override severity and mark as unused.
149             res.borrow_mut().push(
150                 Diagnostic::hint(
151                     sema.diagnostics_display_range(d.display_source()).range,
152                     d.message(),
153                 )
154                 .with_unused(true)
155                 .with_code(Some(d.code())),
156             );
157         })
158         .on::<UnlinkedFile, _>(|d| {
159             // Limit diagnostic to the first few characters in the file. This matches how VS Code
160             // renders it with the full span, but on other editors, and is less invasive.
161             let range = sema.diagnostics_display_range(d.display_source()).range;
162             let range = range.intersect(TextRange::up_to(TextSize::of("..."))).unwrap_or(range);
163
164             // Override severity and mark as unused.
165             res.borrow_mut().push(
166                 Diagnostic::hint(range, d.message())
167                     .with_fixes(d.fixes(&sema, resolve))
168                     .with_code(Some(d.code())),
169             );
170         })
171         .on::<hir::diagnostics::UnresolvedProcMacro, _>(|d| {
172             // Use more accurate position if available.
173             let display_range = d
174                 .precise_location
175                 .unwrap_or_else(|| sema.diagnostics_display_range(d.display_source()).range);
176
177             // FIXME: it would be nice to tell the user whether proc macros are currently disabled
178             res.borrow_mut()
179                 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
180         })
181         .on::<hir::diagnostics::UnresolvedMacroCall, _>(|d| {
182             let last_path_segment = sema.db.parse_or_expand(d.file).and_then(|root| {
183                 d.node
184                     .to_node(&root)
185                     .path()
186                     .and_then(|it| it.segment())
187                     .and_then(|it| it.name_ref())
188                     .map(|it| InFile::new(d.file, SyntaxNodePtr::new(it.syntax())))
189             });
190             let diagnostics = last_path_segment.unwrap_or_else(|| d.display_source());
191             let display_range = sema.diagnostics_display_range(diagnostics).range;
192             res.borrow_mut()
193                 .push(Diagnostic::error(display_range, d.message()).with_code(Some(d.code())));
194         })
195         .on::<hir::diagnostics::UnimplementedBuiltinMacro, _>(|d| {
196             let display_range = sema.diagnostics_display_range(d.display_source()).range;
197             res.borrow_mut()
198                 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
199         })
200         // Only collect experimental diagnostics when they're enabled.
201         .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
202         .filter(|diag| !config.disabled.contains(diag.code().as_str()));
203
204     // Finalize the `DiagnosticSink` building process.
205     let mut sink = sink_builder
206         // Diagnostics not handled above get no fix and default treatment.
207         .build(|d| {
208             res.borrow_mut().push(
209                 Diagnostic::error(
210                     sema.diagnostics_display_range(d.display_source()).range,
211                     d.message(),
212                 )
213                 .with_code(Some(d.code())),
214             );
215         });
216
217     let mut diags = Vec::new();
218     let internal_diagnostics = cfg!(test);
219     match sema.to_module_def(file_id) {
220         Some(m) => diags = m.diagnostics(db, &mut sink, internal_diagnostics),
221         None => {
222             sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(parse.tree().syntax()) });
223         }
224     }
225
226     drop(sink);
227
228     let mut res = res.into_inner();
229
230     let ctx = DiagnosticsContext { config, sema, resolve };
231     for diag in diags {
232         let d = match diag {
233             AnyDiagnostic::UnresolvedModule(d) => unresolved_module::unresolved_module(&ctx, &d),
234             AnyDiagnostic::MissingFields(d) => missing_fields::missing_fields(&ctx, &d),
235         };
236         if let Some(code) = d.code {
237             if ctx.config.disabled.contains(code.as_str()) {
238                 continue;
239             }
240         }
241         res.push(d)
242     }
243
244     res
245 }
246
247 fn diagnostic_with_fix<D: DiagnosticWithFixes>(
248     d: &D,
249     sema: &Semantics<RootDatabase>,
250     resolve: &AssistResolveStrategy,
251 ) -> Diagnostic {
252     Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message())
253         .with_fixes(d.fixes(sema, resolve))
254         .with_code(Some(d.code()))
255 }
256
257 fn warning_with_fix<D: DiagnosticWithFixes>(
258     d: &D,
259     sema: &Semantics<RootDatabase>,
260     resolve: &AssistResolveStrategy,
261 ) -> Diagnostic {
262     Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message())
263         .with_fixes(d.fixes(sema, resolve))
264         .with_code(Some(d.code()))
265 }
266
267 fn check_unnecessary_braces_in_use_statement(
268     acc: &mut Vec<Diagnostic>,
269     file_id: FileId,
270     node: &SyntaxNode,
271 ) -> Option<()> {
272     let use_tree_list = ast::UseTreeList::cast(node.clone())?;
273     if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
274         // If there is a comment inside the bracketed `use`,
275         // assume it is a commented out module path and don't show diagnostic.
276         if use_tree_list.has_inner_comment() {
277             return Some(());
278         }
279
280         let use_range = use_tree_list.syntax().text_range();
281         let edit =
282             text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
283                 .unwrap_or_else(|| {
284                     let to_replace = single_use_tree.syntax().text().to_string();
285                     let mut edit_builder = TextEdit::builder();
286                     edit_builder.delete(use_range);
287                     edit_builder.insert(use_range.start(), to_replace);
288                     edit_builder.finish()
289                 });
290
291         acc.push(
292             Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
293                 .with_fixes(Some(vec![fix(
294                     "remove_braces",
295                     "Remove unnecessary braces",
296                     SourceChange::from_text_edit(file_id, edit),
297                     use_range,
298                 )])),
299         );
300     }
301
302     Some(())
303 }
304
305 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
306     single_use_tree: &ast::UseTree,
307 ) -> Option<TextEdit> {
308     let use_tree_list_node = single_use_tree.syntax().parent()?;
309     if single_use_tree.path()?.segment()?.self_token().is_some() {
310         let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
311         let end = use_tree_list_node.text_range().end();
312         return Some(TextEdit::delete(TextRange::new(start, end)));
313     }
314     None
315 }
316
317 fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
318     let mut res = unresolved_fix(id, label, target);
319     res.source_change = Some(source_change);
320     res
321 }
322
323 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
324     assert!(!id.contains(' '));
325     Assist {
326         id: AssistId(id, AssistKind::QuickFix),
327         label: Label::new(label),
328         group: None,
329         target,
330         source_change: None,
331     }
332 }
333
334 #[cfg(test)]
335 mod tests {
336     use expect_test::Expect;
337     use hir::diagnostics::DiagnosticCode;
338     use ide_assists::AssistResolveStrategy;
339     use stdx::trim_indent;
340     use test_utils::{assert_eq_text, extract_annotations};
341
342     use crate::{fixture, DiagnosticsConfig};
343
344     /// Takes a multi-file input fixture with annotated cursor positions,
345     /// and checks that:
346     ///  * a diagnostic is produced
347     ///  * the first diagnostic fix trigger range touches the input cursor position
348     ///  * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
349     #[track_caller]
350     pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
351         check_nth_fix(0, ra_fixture_before, ra_fixture_after);
352     }
353     /// Takes a multi-file input fixture with annotated cursor positions,
354     /// and checks that:
355     ///  * a diagnostic is produced
356     ///  * every diagnostic fixes trigger range touches the input cursor position
357     ///  * that the contents of the file containing the cursor match `after` after each diagnostic fix is applied
358     pub(crate) fn check_fixes(ra_fixture_before: &str, ra_fixtures_after: Vec<&str>) {
359         for (i, ra_fixture_after) in ra_fixtures_after.iter().enumerate() {
360             check_nth_fix(i, ra_fixture_before, ra_fixture_after)
361         }
362     }
363
364     #[track_caller]
365     fn check_nth_fix(nth: usize, ra_fixture_before: &str, ra_fixture_after: &str) {
366         let after = trim_indent(ra_fixture_after);
367
368         let (analysis, file_position) = fixture::position(ra_fixture_before);
369         let diagnostic = analysis
370             .diagnostics(
371                 &DiagnosticsConfig::default(),
372                 AssistResolveStrategy::All,
373                 file_position.file_id,
374             )
375             .unwrap()
376             .pop()
377             .unwrap();
378         let fix = &diagnostic.fixes.unwrap()[nth];
379         let actual = {
380             let source_change = fix.source_change.as_ref().unwrap();
381             let file_id = *source_change.source_file_edits.keys().next().unwrap();
382             let mut actual = analysis.file_text(file_id).unwrap().to_string();
383
384             for edit in source_change.source_file_edits.values() {
385                 edit.apply(&mut actual);
386             }
387             actual
388         };
389
390         assert_eq_text!(&after, &actual);
391         assert!(
392             fix.target.contains_inclusive(file_position.offset),
393             "diagnostic fix range {:?} does not touch cursor position {:?}",
394             fix.target,
395             file_position.offset
396         );
397     }
398     /// Checks that there's a diagnostic *without* fix at `$0`.
399     fn check_no_fix(ra_fixture: &str) {
400         let (analysis, file_position) = fixture::position(ra_fixture);
401         let diagnostic = analysis
402             .diagnostics(
403                 &DiagnosticsConfig::default(),
404                 AssistResolveStrategy::All,
405                 file_position.file_id,
406             )
407             .unwrap()
408             .pop()
409             .unwrap();
410         assert!(diagnostic.fixes.is_none(), "got a fix when none was expected: {:?}", diagnostic);
411     }
412
413     /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
414     /// apply to the file containing the cursor.
415     pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
416         let (analysis, files) = fixture::files(ra_fixture);
417         let diagnostics = files
418             .into_iter()
419             .flat_map(|file_id| {
420                 analysis
421                     .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
422                     .unwrap()
423             })
424             .collect::<Vec<_>>();
425         assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
426     }
427
428     pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) {
429         let (analysis, file_id) = fixture::file(ra_fixture);
430         let diagnostics = analysis
431             .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
432             .unwrap();
433         expect.assert_debug_eq(&diagnostics)
434     }
435
436     pub(crate) fn check_diagnostics(ra_fixture: &str) {
437         let (analysis, file_id) = fixture::file(ra_fixture);
438         let diagnostics = analysis
439             .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
440             .unwrap();
441
442         let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
443         let mut actual = diagnostics
444             .into_iter()
445             .filter(|d| d.code != Some(DiagnosticCode("inactive-code")))
446             .map(|d| (d.range, d.message))
447             .collect::<Vec<_>>();
448         actual.sort_by_key(|(range, _)| range.start());
449         assert_eq!(expected, actual);
450     }
451
452     #[test]
453     fn test_unresolved_macro_range() {
454         check_diagnostics(
455             r#"
456 foo::bar!(92);
457    //^^^ unresolved macro `foo::bar!`
458 "#,
459         );
460     }
461
462     #[test]
463     fn unresolved_import_in_use_tree() {
464         // Only the relevant part of a nested `use` item should be highlighted.
465         check_diagnostics(
466             r#"
467 use does_exist::{Exists, DoesntExist};
468                        //^^^^^^^^^^^ unresolved import
469
470 use {does_not_exist::*, does_exist};
471    //^^^^^^^^^^^^^^^^^ unresolved import
472
473 use does_not_exist::{
474     a,
475   //^ unresolved import
476     b,
477   //^ unresolved import
478     c,
479   //^ unresolved import
480 };
481
482 mod does_exist {
483     pub struct Exists;
484 }
485 "#,
486         );
487     }
488
489     #[test]
490     fn range_mapping_out_of_macros() {
491         // FIXME: this is very wrong, but somewhat tricky to fix.
492         check_fix(
493             r#"
494 fn some() {}
495 fn items() {}
496 fn here() {}
497
498 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
499
500 fn main() {
501     let _x = id![Foo { a: $042 }];
502 }
503
504 pub struct Foo { pub a: i32, pub b: i32 }
505 "#,
506             r#"
507 fn some(, b: () ) {}
508 fn items() {}
509 fn here() {}
510
511 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
512
513 fn main() {
514     let _x = id![Foo { a: 42 }];
515 }
516
517 pub struct Foo { pub a: i32, pub b: i32 }
518 "#,
519         );
520     }
521
522     #[test]
523     fn test_check_unnecessary_braces_in_use_statement() {
524         check_no_diagnostics(
525             r#"
526 use a;
527 use a::{c, d::e};
528
529 mod a {
530     mod c {}
531     mod d {
532         mod e {}
533     }
534 }
535 "#,
536         );
537         check_no_diagnostics(
538             r#"
539 use a;
540 use a::{
541     c,
542     // d::e
543 };
544
545 mod a {
546     mod c {}
547     mod d {
548         mod e {}
549     }
550 }
551 "#,
552         );
553         check_fix(
554             r"
555             mod b {}
556             use {$0b};
557             ",
558             r"
559             mod b {}
560             use b;
561             ",
562         );
563         check_fix(
564             r"
565             mod b {}
566             use {b$0};
567             ",
568             r"
569             mod b {}
570             use b;
571             ",
572         );
573         check_fix(
574             r"
575             mod a { mod c {} }
576             use a::{c$0};
577             ",
578             r"
579             mod a { mod c {} }
580             use a::c;
581             ",
582         );
583         check_fix(
584             r"
585             mod a {}
586             use a::{self$0};
587             ",
588             r"
589             mod a {}
590             use a;
591             ",
592         );
593         check_fix(
594             r"
595             mod a { mod c {} mod d { mod e {} } }
596             use a::{c, d::{e$0}};
597             ",
598             r"
599             mod a { mod c {} mod d { mod e {} } }
600             use a::{c, d::e};
601             ",
602         );
603     }
604
605     #[test]
606     fn test_disabled_diagnostics() {
607         let mut config = DiagnosticsConfig::default();
608         config.disabled.insert("unresolved-module".into());
609
610         let (analysis, file_id) = fixture::file(r#"mod foo;"#);
611
612         let diagnostics =
613             analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
614         assert!(diagnostics.is_empty());
615
616         let diagnostics = analysis
617             .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
618             .unwrap();
619         assert!(!diagnostics.is_empty());
620     }
621
622     #[test]
623     fn unlinked_file_prepend_first_item() {
624         cov_mark::check!(unlinked_file_prepend_before_first_item);
625         // Only tests the first one for `pub mod` since the rest are the same
626         check_fixes(
627             r#"
628 //- /main.rs
629 fn f() {}
630 //- /foo.rs
631 $0
632 "#,
633             vec![
634                 r#"
635 mod foo;
636
637 fn f() {}
638 "#,
639                 r#"
640 pub mod foo;
641
642 fn f() {}
643 "#,
644             ],
645         );
646     }
647
648     #[test]
649     fn unlinked_file_append_mod() {
650         cov_mark::check!(unlinked_file_append_to_existing_mods);
651         check_fix(
652             r#"
653 //- /main.rs
654 //! Comment on top
655
656 mod preexisting;
657
658 mod preexisting2;
659
660 struct S;
661
662 mod preexisting_bottom;)
663 //- /foo.rs
664 $0
665 "#,
666             r#"
667 //! Comment on top
668
669 mod preexisting;
670
671 mod preexisting2;
672 mod foo;
673
674 struct S;
675
676 mod preexisting_bottom;)
677 "#,
678         );
679     }
680
681     #[test]
682     fn unlinked_file_insert_in_empty_file() {
683         cov_mark::check!(unlinked_file_empty_file);
684         check_fix(
685             r#"
686 //- /main.rs
687 //- /foo.rs
688 $0
689 "#,
690             r#"
691 mod foo;
692 "#,
693         );
694     }
695
696     #[test]
697     fn unlinked_file_old_style_modrs() {
698         check_fix(
699             r#"
700 //- /main.rs
701 mod submod;
702 //- /submod/mod.rs
703 // in mod.rs
704 //- /submod/foo.rs
705 $0
706 "#,
707             r#"
708 // in mod.rs
709 mod foo;
710 "#,
711         );
712     }
713
714     #[test]
715     fn unlinked_file_new_style_mod() {
716         check_fix(
717             r#"
718 //- /main.rs
719 mod submod;
720 //- /submod.rs
721 //- /submod/foo.rs
722 $0
723 "#,
724             r#"
725 mod foo;
726 "#,
727         );
728     }
729
730     #[test]
731     fn unlinked_file_with_cfg_off() {
732         cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
733         check_no_fix(
734             r#"
735 //- /main.rs
736 #[cfg(never)]
737 mod foo;
738
739 //- /foo.rs
740 $0
741 "#,
742         );
743     }
744
745     #[test]
746     fn unlinked_file_with_cfg_on() {
747         check_no_diagnostics(
748             r#"
749 //- /main.rs
750 #[cfg(not(never))]
751 mod foo;
752
753 //- /foo.rs
754 "#,
755         );
756     }
757
758     #[test]
759     fn break_outside_of_loop() {
760         check_diagnostics(
761             r#"
762 fn foo() { break; }
763          //^^^^^ break outside of loop
764 "#,
765         );
766     }
767
768     #[test]
769     fn no_such_field_diagnostics() {
770         check_diagnostics(
771             r#"
772 struct S { foo: i32, bar: () }
773 impl S {
774     fn new() -> S {
775         S {
776       //^ Missing structure fields:
777       //|    - bar
778             foo: 92,
779             baz: 62,
780           //^^^^^^^ no such field
781         }
782     }
783 }
784 "#,
785         );
786     }
787     #[test]
788     fn no_such_field_with_feature_flag_diagnostics() {
789         check_diagnostics(
790             r#"
791 //- /lib.rs crate:foo cfg:feature=foo
792 struct MyStruct {
793     my_val: usize,
794     #[cfg(feature = "foo")]
795     bar: bool,
796 }
797
798 impl MyStruct {
799     #[cfg(feature = "foo")]
800     pub(crate) fn new(my_val: usize, bar: bool) -> Self {
801         Self { my_val, bar }
802     }
803     #[cfg(not(feature = "foo"))]
804     pub(crate) fn new(my_val: usize, _bar: bool) -> Self {
805         Self { my_val }
806     }
807 }
808 "#,
809         );
810     }
811
812     #[test]
813     fn no_such_field_enum_with_feature_flag_diagnostics() {
814         check_diagnostics(
815             r#"
816 //- /lib.rs crate:foo cfg:feature=foo
817 enum Foo {
818     #[cfg(not(feature = "foo"))]
819     Buz,
820     #[cfg(feature = "foo")]
821     Bar,
822     Baz
823 }
824
825 fn test_fn(f: Foo) {
826     match f {
827         Foo::Bar => {},
828         Foo::Baz => {},
829     }
830 }
831 "#,
832         );
833     }
834
835     #[test]
836     fn no_such_field_with_feature_flag_diagnostics_on_struct_lit() {
837         check_diagnostics(
838             r#"
839 //- /lib.rs crate:foo cfg:feature=foo
840 struct S {
841     #[cfg(feature = "foo")]
842     foo: u32,
843     #[cfg(not(feature = "foo"))]
844     bar: u32,
845 }
846
847 impl S {
848     #[cfg(feature = "foo")]
849     fn new(foo: u32) -> Self {
850         Self { foo }
851     }
852     #[cfg(not(feature = "foo"))]
853     fn new(bar: u32) -> Self {
854         Self { bar }
855     }
856     fn new2(bar: u32) -> Self {
857         #[cfg(feature = "foo")]
858         { Self { foo: bar } }
859         #[cfg(not(feature = "foo"))]
860         { Self { bar } }
861     }
862     fn new2(val: u32) -> Self {
863         Self {
864             #[cfg(feature = "foo")]
865             foo: val,
866             #[cfg(not(feature = "foo"))]
867             bar: val,
868         }
869     }
870 }
871 "#,
872         );
873     }
874
875     #[test]
876     fn no_such_field_with_type_macro() {
877         check_diagnostics(
878             r#"
879 macro_rules! Type { () => { u32 }; }
880 struct Foo { bar: Type![] }
881
882 impl Foo {
883     fn new() -> Self {
884         Foo { bar: 0 }
885     }
886 }
887 "#,
888         );
889     }
890
891     #[test]
892     fn missing_unsafe_diagnostic_with_raw_ptr() {
893         check_diagnostics(
894             r#"
895 fn main() {
896     let x = &5 as *const usize;
897     unsafe { let y = *x; }
898     let z = *x;
899 }         //^^ This operation is unsafe and requires an unsafe function or block
900 "#,
901         )
902     }
903
904     #[test]
905     fn missing_unsafe_diagnostic_with_unsafe_call() {
906         check_diagnostics(
907             r#"
908 struct HasUnsafe;
909
910 impl HasUnsafe {
911     unsafe fn unsafe_fn(&self) {
912         let x = &5 as *const usize;
913         let y = *x;
914     }
915 }
916
917 unsafe fn unsafe_fn() {
918     let x = &5 as *const usize;
919     let y = *x;
920 }
921
922 fn main() {
923     unsafe_fn();
924   //^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
925     HasUnsafe.unsafe_fn();
926   //^^^^^^^^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
927     unsafe {
928         unsafe_fn();
929         HasUnsafe.unsafe_fn();
930     }
931 }
932 "#,
933         );
934     }
935
936     #[test]
937     fn missing_unsafe_diagnostic_with_static_mut() {
938         check_diagnostics(
939             r#"
940 struct Ty {
941     a: u8,
942 }
943
944 static mut STATIC_MUT: Ty = Ty { a: 0 };
945
946 fn main() {
947     let x = STATIC_MUT.a;
948           //^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
949     unsafe {
950         let x = STATIC_MUT.a;
951     }
952 }
953 "#,
954         );
955     }
956
957     #[test]
958     fn no_missing_unsafe_diagnostic_with_safe_intrinsic() {
959         check_diagnostics(
960             r#"
961 extern "rust-intrinsic" {
962     pub fn bitreverse(x: u32) -> u32; // Safe intrinsic
963     pub fn floorf32(x: f32) -> f32; // Unsafe intrinsic
964 }
965
966 fn main() {
967     let _ = bitreverse(12);
968     let _ = floorf32(12.0);
969           //^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
970 }
971 "#,
972         );
973     }
974
975     // Register the required standard library types to make the tests work
976     fn add_filter_map_with_find_next_boilerplate(body: &str) -> String {
977         let prefix = r#"
978         //- /main.rs crate:main deps:core
979         use core::iter::Iterator;
980         use core::option::Option::{self, Some, None};
981         "#;
982         let suffix = r#"
983         //- /core/lib.rs crate:core
984         pub mod option {
985             pub enum Option<T> { Some(T), None }
986         }
987         pub mod iter {
988             pub trait Iterator {
989                 type Item;
990                 fn filter_map<B, F>(self, f: F) -> FilterMap where F: FnMut(Self::Item) -> Option<B> { FilterMap }
991                 fn next(&mut self) -> Option<Self::Item>;
992             }
993             pub struct FilterMap {}
994             impl Iterator for FilterMap {
995                 type Item = i32;
996                 fn next(&mut self) -> i32 { 7 }
997             }
998         }
999         "#;
1000         format!("{}{}{}", prefix, body, suffix)
1001     }
1002
1003     #[test]
1004     fn replace_filter_map_next_with_find_map2() {
1005         check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1006             r#"
1007             fn foo() {
1008                 let m = [1, 2, 3].iter().filter_map(|x| if *x == 2 { Some (4) } else { None }).next();
1009                       //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ replace filter_map(..).next() with find_map(..)
1010             }
1011         "#,
1012         ));
1013     }
1014
1015     #[test]
1016     fn replace_filter_map_next_with_find_map_no_diagnostic_without_next() {
1017         check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1018             r#"
1019             fn foo() {
1020                 let m = [1, 2, 3]
1021                     .iter()
1022                     .filter_map(|x| if *x == 2 { Some (4) } else { None })
1023                     .len();
1024             }
1025             "#,
1026         ));
1027     }
1028
1029     #[test]
1030     fn replace_filter_map_next_with_find_map_no_diagnostic_with_intervening_methods() {
1031         check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1032             r#"
1033             fn foo() {
1034                 let m = [1, 2, 3]
1035                     .iter()
1036                     .filter_map(|x| if *x == 2 { Some (4) } else { None })
1037                     .map(|x| x + 2)
1038                     .len();
1039             }
1040             "#,
1041         ));
1042     }
1043
1044     #[test]
1045     fn replace_filter_map_next_with_find_map_no_diagnostic_if_not_in_chain() {
1046         check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1047             r#"
1048             fn foo() {
1049                 let m = [1, 2, 3]
1050                     .iter()
1051                     .filter_map(|x| if *x == 2 { Some (4) } else { None });
1052                 let n = m.next();
1053             }
1054             "#,
1055         ));
1056     }
1057
1058     #[test]
1059     fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
1060         check_diagnostics(
1061             r"
1062 struct S { foo: i32, bar: () }
1063 fn baz(s: S) -> i32 {
1064     match s {
1065         S { foo, .. } => foo,
1066     }
1067 }
1068 ",
1069         )
1070     }
1071
1072     #[test]
1073     fn missing_record_pat_field_box() {
1074         check_diagnostics(
1075             r"
1076 struct S { s: Box<u32> }
1077 fn x(a: S) {
1078     let S { box s } = a;
1079 }
1080 ",
1081         )
1082     }
1083
1084     #[test]
1085     fn missing_record_pat_field_ref() {
1086         check_diagnostics(
1087             r"
1088 struct S { s: u32 }
1089 fn x(a: S) {
1090     let S { ref s } = a;
1091 }
1092 ",
1093         )
1094     }
1095
1096     #[test]
1097     fn simple_free_fn_zero() {
1098         check_diagnostics(
1099             r#"
1100 fn zero() {}
1101 fn f() { zero(1); }
1102        //^^^^^^^ Expected 0 arguments, found 1
1103 "#,
1104         );
1105
1106         check_diagnostics(
1107             r#"
1108 fn zero() {}
1109 fn f() { zero(); }
1110 "#,
1111         );
1112     }
1113
1114     #[test]
1115     fn simple_free_fn_one() {
1116         check_diagnostics(
1117             r#"
1118 fn one(arg: u8) {}
1119 fn f() { one(); }
1120        //^^^^^ Expected 1 argument, found 0
1121 "#,
1122         );
1123
1124         check_diagnostics(
1125             r#"
1126 fn one(arg: u8) {}
1127 fn f() { one(1); }
1128 "#,
1129         );
1130     }
1131
1132     #[test]
1133     fn method_as_fn() {
1134         check_diagnostics(
1135             r#"
1136 struct S;
1137 impl S { fn method(&self) {} }
1138
1139 fn f() {
1140     S::method();
1141 } //^^^^^^^^^^^ Expected 1 argument, found 0
1142 "#,
1143         );
1144
1145         check_diagnostics(
1146             r#"
1147 struct S;
1148 impl S { fn method(&self) {} }
1149
1150 fn f() {
1151     S::method(&S);
1152     S.method();
1153 }
1154 "#,
1155         );
1156     }
1157
1158     #[test]
1159     fn method_with_arg() {
1160         check_diagnostics(
1161             r#"
1162 struct S;
1163 impl S { fn method(&self, arg: u8) {} }
1164
1165             fn f() {
1166                 S.method();
1167             } //^^^^^^^^^^ Expected 1 argument, found 0
1168             "#,
1169         );
1170
1171         check_diagnostics(
1172             r#"
1173 struct S;
1174 impl S { fn method(&self, arg: u8) {} }
1175
1176 fn f() {
1177     S::method(&S, 0);
1178     S.method(1);
1179 }
1180 "#,
1181         );
1182     }
1183
1184     #[test]
1185     fn method_unknown_receiver() {
1186         // note: this is incorrect code, so there might be errors on this in the
1187         // future, but we shouldn't emit an argument count diagnostic here
1188         check_diagnostics(
1189             r#"
1190 trait Foo { fn method(&self, arg: usize) {} }
1191
1192 fn f() {
1193     let x;
1194     x.method();
1195 }
1196 "#,
1197         );
1198     }
1199
1200     #[test]
1201     fn tuple_struct() {
1202         check_diagnostics(
1203             r#"
1204 struct Tup(u8, u16);
1205 fn f() {
1206     Tup(0);
1207 } //^^^^^^ Expected 2 arguments, found 1
1208 "#,
1209         )
1210     }
1211
1212     #[test]
1213     fn enum_variant() {
1214         check_diagnostics(
1215             r#"
1216 enum En { Variant(u8, u16), }
1217 fn f() {
1218     En::Variant(0);
1219 } //^^^^^^^^^^^^^^ Expected 2 arguments, found 1
1220 "#,
1221         )
1222     }
1223
1224     #[test]
1225     fn enum_variant_type_macro() {
1226         check_diagnostics(
1227             r#"
1228 macro_rules! Type {
1229     () => { u32 };
1230 }
1231 enum Foo {
1232     Bar(Type![])
1233 }
1234 impl Foo {
1235     fn new() {
1236         Foo::Bar(0);
1237         Foo::Bar(0, 1);
1238       //^^^^^^^^^^^^^^ Expected 1 argument, found 2
1239         Foo::Bar();
1240       //^^^^^^^^^^ Expected 1 argument, found 0
1241     }
1242 }
1243         "#,
1244         );
1245     }
1246
1247     #[test]
1248     fn varargs() {
1249         check_diagnostics(
1250             r#"
1251 extern "C" {
1252     fn fixed(fixed: u8);
1253     fn varargs(fixed: u8, ...);
1254     fn varargs2(...);
1255 }
1256
1257 fn f() {
1258     unsafe {
1259         fixed(0);
1260         fixed(0, 1);
1261       //^^^^^^^^^^^ Expected 1 argument, found 2
1262         varargs(0);
1263         varargs(0, 1);
1264         varargs2();
1265         varargs2(0);
1266         varargs2(0, 1);
1267     }
1268 }
1269         "#,
1270         )
1271     }
1272
1273     #[test]
1274     fn arg_count_lambda() {
1275         check_diagnostics(
1276             r#"
1277 fn main() {
1278     let f = |()| ();
1279     f();
1280   //^^^ Expected 1 argument, found 0
1281     f(());
1282     f((), ());
1283   //^^^^^^^^^ Expected 1 argument, found 2
1284 }
1285 "#,
1286         )
1287     }
1288
1289     #[test]
1290     fn cfgd_out_call_arguments() {
1291         check_diagnostics(
1292             r#"
1293 struct C(#[cfg(FALSE)] ());
1294 impl C {
1295     fn new() -> Self {
1296         Self(
1297             #[cfg(FALSE)]
1298             (),
1299         )
1300     }
1301
1302     fn method(&self) {}
1303 }
1304
1305 fn main() {
1306     C::new().method(#[cfg(FALSE)] 0);
1307 }
1308             "#,
1309         );
1310     }
1311
1312     #[test]
1313     fn cfgd_out_fn_params() {
1314         check_diagnostics(
1315             r#"
1316 fn foo(#[cfg(NEVER)] x: ()) {}
1317
1318 struct S;
1319
1320 impl S {
1321     fn method(#[cfg(NEVER)] self) {}
1322     fn method2(#[cfg(NEVER)] self, arg: u8) {}
1323     fn method3(self, #[cfg(NEVER)] arg: u8) {}
1324 }
1325
1326 extern "C" {
1327     fn fixed(fixed: u8, #[cfg(NEVER)] ...);
1328     fn varargs(#[cfg(not(NEVER))] ...);
1329 }
1330
1331 fn main() {
1332     foo();
1333     S::method();
1334     S::method2(0);
1335     S::method3(S);
1336     S.method3();
1337     unsafe {
1338         fixed(0);
1339         varargs(1, 2, 3);
1340     }
1341 }
1342             "#,
1343         )
1344     }
1345
1346     #[test]
1347     fn missing_semicolon() {
1348         check_diagnostics(
1349             r#"
1350                 fn test() -> i32 { 123; }
1351                                  //^^^ Remove this semicolon
1352             "#,
1353         );
1354     }
1355
1356     #[test]
1357     fn import_extern_crate_clash_with_inner_item() {
1358         // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
1359
1360         check_diagnostics(
1361             r#"
1362 //- /lib.rs crate:lib deps:jwt
1363 mod permissions;
1364
1365 use permissions::jwt;
1366
1367 fn f() {
1368     fn inner() {}
1369     jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
1370 }
1371
1372 //- /permissions.rs
1373 pub mod jwt  {
1374     pub struct Claims {}
1375 }
1376
1377 //- /jwt/lib.rs crate:jwt
1378 pub struct Claims {
1379     field: u8,
1380 }
1381         "#,
1382         );
1383     }
1384 }
1385
1386 #[cfg(test)]
1387 pub(super) mod match_check_tests {
1388     use crate::diagnostics::tests::check_diagnostics;
1389
1390     #[test]
1391     fn empty_tuple() {
1392         check_diagnostics(
1393             r#"
1394 fn main() {
1395     match () { }
1396         //^^ Missing match arm
1397     match (()) { }
1398         //^^^^ Missing match arm
1399
1400     match () { _ => (), }
1401     match () { () => (), }
1402     match (()) { (()) => (), }
1403 }
1404 "#,
1405         );
1406     }
1407
1408     #[test]
1409     fn tuple_of_two_empty_tuple() {
1410         check_diagnostics(
1411             r#"
1412 fn main() {
1413     match ((), ()) { }
1414         //^^^^^^^^ Missing match arm
1415
1416     match ((), ()) { ((), ()) => (), }
1417 }
1418 "#,
1419         );
1420     }
1421
1422     #[test]
1423     fn boolean() {
1424         check_diagnostics(
1425             r#"
1426 fn test_main() {
1427     match false { }
1428         //^^^^^ Missing match arm
1429     match false { true => (), }
1430         //^^^^^ Missing match arm
1431     match (false, true) {}
1432         //^^^^^^^^^^^^^ Missing match arm
1433     match (false, true) { (true, true) => (), }
1434         //^^^^^^^^^^^^^ Missing match arm
1435     match (false, true) {
1436         //^^^^^^^^^^^^^ Missing match arm
1437         (false, true) => (),
1438         (false, false) => (),
1439         (true, false) => (),
1440     }
1441     match (false, true) { (true, _x) => (), }
1442         //^^^^^^^^^^^^^ Missing match arm
1443
1444     match false { true => (), false => (), }
1445     match (false, true) {
1446         (false, _) => (),
1447         (true, false) => (),
1448         (_, true) => (),
1449     }
1450     match (false, true) {
1451         (true, true) => (),
1452         (true, false) => (),
1453         (false, true) => (),
1454         (false, false) => (),
1455     }
1456     match (false, true) {
1457         (true, _x) => (),
1458         (false, true) => (),
1459         (false, false) => (),
1460     }
1461     match (false, true, false) {
1462         (false, ..) => (),
1463         (true, ..) => (),
1464     }
1465     match (false, true, false) {
1466         (.., false) => (),
1467         (.., true) => (),
1468     }
1469     match (false, true, false) { (..) => (), }
1470 }
1471 "#,
1472         );
1473     }
1474
1475     #[test]
1476     fn tuple_of_tuple_and_bools() {
1477         check_diagnostics(
1478             r#"
1479 fn main() {
1480     match (false, ((), false)) {}
1481         //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1482     match (false, ((), false)) { (true, ((), true)) => (), }
1483         //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1484     match (false, ((), false)) { (true, _) => (), }
1485         //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1486
1487     match (false, ((), false)) {
1488         (true, ((), true)) => (),
1489         (true, ((), false)) => (),
1490         (false, ((), true)) => (),
1491         (false, ((), false)) => (),
1492     }
1493     match (false, ((), false)) {
1494         (true, ((), true)) => (),
1495         (true, ((), false)) => (),
1496         (false, _) => (),
1497     }
1498 }
1499 "#,
1500         );
1501     }
1502
1503     #[test]
1504     fn enums() {
1505         check_diagnostics(
1506             r#"
1507 enum Either { A, B, }
1508
1509 fn main() {
1510     match Either::A { }
1511         //^^^^^^^^^ Missing match arm
1512     match Either::B { Either::A => (), }
1513         //^^^^^^^^^ Missing match arm
1514
1515     match &Either::B {
1516         //^^^^^^^^^^ Missing match arm
1517         Either::A => (),
1518     }
1519
1520     match Either::B {
1521         Either::A => (), Either::B => (),
1522     }
1523     match &Either::B {
1524         Either::A => (), Either::B => (),
1525     }
1526 }
1527 "#,
1528         );
1529     }
1530
1531     #[test]
1532     fn enum_containing_bool() {
1533         check_diagnostics(
1534             r#"
1535 enum Either { A(bool), B }
1536
1537 fn main() {
1538     match Either::B { }
1539         //^^^^^^^^^ Missing match arm
1540     match Either::B {
1541         //^^^^^^^^^ Missing match arm
1542         Either::A(true) => (), Either::B => ()
1543     }
1544
1545     match Either::B {
1546         Either::A(true) => (),
1547         Either::A(false) => (),
1548         Either::B => (),
1549     }
1550     match Either::B {
1551         Either::B => (),
1552         _ => (),
1553     }
1554     match Either::B {
1555         Either::A(_) => (),
1556         Either::B => (),
1557     }
1558
1559 }
1560         "#,
1561         );
1562     }
1563
1564     #[test]
1565     fn enum_different_sizes() {
1566         check_diagnostics(
1567             r#"
1568 enum Either { A(bool), B(bool, bool) }
1569
1570 fn main() {
1571     match Either::A(false) {
1572         //^^^^^^^^^^^^^^^^ Missing match arm
1573         Either::A(_) => (),
1574         Either::B(false, _) => (),
1575     }
1576
1577     match Either::A(false) {
1578         Either::A(_) => (),
1579         Either::B(true, _) => (),
1580         Either::B(false, _) => (),
1581     }
1582     match Either::A(false) {
1583         Either::A(true) | Either::A(false) => (),
1584         Either::B(true, _) => (),
1585         Either::B(false, _) => (),
1586     }
1587 }
1588 "#,
1589         );
1590     }
1591
1592     #[test]
1593     fn tuple_of_enum_no_diagnostic() {
1594         check_diagnostics(
1595             r#"
1596 enum Either { A(bool), B(bool, bool) }
1597 enum Either2 { C, D }
1598
1599 fn main() {
1600     match (Either::A(false), Either2::C) {
1601         (Either::A(true), _) | (Either::A(false), _) => (),
1602         (Either::B(true, _), Either2::C) => (),
1603         (Either::B(false, _), Either2::C) => (),
1604         (Either::B(_, _), Either2::D) => (),
1605     }
1606 }
1607 "#,
1608         );
1609     }
1610
1611     #[test]
1612     fn or_pattern_no_diagnostic() {
1613         check_diagnostics(
1614             r#"
1615 enum Either {A, B}
1616
1617 fn main() {
1618     match (Either::A, Either::B) {
1619         (Either::A | Either::B, _) => (),
1620     }
1621 }"#,
1622         )
1623     }
1624
1625     #[test]
1626     fn mismatched_types() {
1627         // Match statements with arms that don't match the
1628         // expression pattern do not fire this diagnostic.
1629         check_diagnostics(
1630             r#"
1631 enum Either { A, B }
1632 enum Either2 { C, D }
1633
1634 fn main() {
1635     match Either::A {
1636         Either2::C => (),
1637     //  ^^^^^^^^^^ Internal: match check bailed out
1638         Either2::D => (),
1639     }
1640     match (true, false) {
1641         (true, false, true) => (),
1642     //  ^^^^^^^^^^^^^^^^^^^ Internal: match check bailed out
1643         (true) => (),
1644     }
1645     match (true, false) { (true,) => {} }
1646     //                    ^^^^^^^ Internal: match check bailed out
1647     match (0) { () => () }
1648             //  ^^ Internal: match check bailed out
1649     match Unresolved::Bar { Unresolved::Baz => () }
1650 }
1651         "#,
1652         );
1653     }
1654
1655     #[test]
1656     fn mismatched_types_in_or_patterns() {
1657         check_diagnostics(
1658             r#"
1659 fn main() {
1660     match false { true | () => {} }
1661     //            ^^^^^^^^^ Internal: match check bailed out
1662     match (false,) { (true | (),) => {} }
1663     //               ^^^^^^^^^^^^ Internal: match check bailed out
1664 }
1665 "#,
1666         );
1667     }
1668
1669     #[test]
1670     fn malformed_match_arm_tuple_enum_missing_pattern() {
1671         // We are testing to be sure we don't panic here when the match
1672         // arm `Either::B` is missing its pattern.
1673         check_diagnostics(
1674             r#"
1675 enum Either { A, B(u32) }
1676
1677 fn main() {
1678     match Either::A {
1679         Either::A => (),
1680         Either::B() => (),
1681     }
1682 }
1683 "#,
1684         );
1685     }
1686
1687     #[test]
1688     fn malformed_match_arm_extra_fields() {
1689         check_diagnostics(
1690             r#"
1691 enum A { B(isize, isize), C }
1692 fn main() {
1693     match A::B(1, 2) {
1694         A::B(_, _, _) => (),
1695     //  ^^^^^^^^^^^^^ Internal: match check bailed out
1696     }
1697     match A::B(1, 2) {
1698         A::C(_) => (),
1699     //  ^^^^^^^ Internal: match check bailed out
1700     }
1701 }
1702 "#,
1703         );
1704     }
1705
1706     #[test]
1707     fn expr_diverges() {
1708         check_diagnostics(
1709             r#"
1710 enum Either { A, B }
1711
1712 fn main() {
1713     match loop {} {
1714         Either::A => (),
1715     //  ^^^^^^^^^ Internal: match check bailed out
1716         Either::B => (),
1717     }
1718     match loop {} {
1719         Either::A => (),
1720     //  ^^^^^^^^^ Internal: match check bailed out
1721     }
1722     match loop { break Foo::A } {
1723         //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1724         Either::A => (),
1725     }
1726     match loop { break Foo::A } {
1727         Either::A => (),
1728         Either::B => (),
1729     }
1730 }
1731 "#,
1732         );
1733     }
1734
1735     #[test]
1736     fn expr_partially_diverges() {
1737         check_diagnostics(
1738             r#"
1739 enum Either<T> { A(T), B }
1740
1741 fn foo() -> Either<!> { Either::B }
1742 fn main() -> u32 {
1743     match foo() {
1744         Either::A(val) => val,
1745         Either::B => 0,
1746     }
1747 }
1748 "#,
1749         );
1750     }
1751
1752     #[test]
1753     fn enum_record() {
1754         check_diagnostics(
1755             r#"
1756 enum Either { A { foo: bool }, B }
1757
1758 fn main() {
1759     let a = Either::A { foo: true };
1760     match a { }
1761         //^ Missing match arm
1762     match a { Either::A { foo: true } => () }
1763         //^ Missing match arm
1764     match a {
1765         Either::A { } => (),
1766       //^^^^^^^^^ Missing structure fields:
1767       //        | - foo
1768         Either::B => (),
1769     }
1770     match a {
1771         //^ Missing match arm
1772         Either::A { } => (),
1773     } //^^^^^^^^^ Missing structure fields:
1774       //        | - foo
1775
1776     match a {
1777         Either::A { foo: true } => (),
1778         Either::A { foo: false } => (),
1779         Either::B => (),
1780     }
1781     match a {
1782         Either::A { foo: _ } => (),
1783         Either::B => (),
1784     }
1785 }
1786 "#,
1787         );
1788     }
1789
1790     #[test]
1791     fn enum_record_fields_out_of_order() {
1792         check_diagnostics(
1793             r#"
1794 enum Either {
1795     A { foo: bool, bar: () },
1796     B,
1797 }
1798
1799 fn main() {
1800     let a = Either::A { foo: true, bar: () };
1801     match a {
1802         //^ Missing match arm
1803         Either::A { bar: (), foo: false } => (),
1804         Either::A { foo: true, bar: () } => (),
1805     }
1806
1807     match a {
1808         Either::A { bar: (), foo: false } => (),
1809         Either::A { foo: true, bar: () } => (),
1810         Either::B => (),
1811     }
1812 }
1813 "#,
1814         );
1815     }
1816
1817     #[test]
1818     fn enum_record_ellipsis() {
1819         check_diagnostics(
1820             r#"
1821 enum Either {
1822     A { foo: bool, bar: bool },
1823     B,
1824 }
1825
1826 fn main() {
1827     let a = Either::B;
1828     match a {
1829         //^ Missing match arm
1830         Either::A { foo: true, .. } => (),
1831         Either::B => (),
1832     }
1833     match a {
1834         //^ Missing match arm
1835         Either::A { .. } => (),
1836     }
1837
1838     match a {
1839         Either::A { foo: true, .. } => (),
1840         Either::A { foo: false, .. } => (),
1841         Either::B => (),
1842     }
1843
1844     match a {
1845         Either::A { .. } => (),
1846         Either::B => (),
1847     }
1848 }
1849 "#,
1850         );
1851     }
1852
1853     #[test]
1854     fn enum_tuple_partial_ellipsis() {
1855         check_diagnostics(
1856             r#"
1857 enum Either {
1858     A(bool, bool, bool, bool),
1859     B,
1860 }
1861
1862 fn main() {
1863     match Either::B {
1864         //^^^^^^^^^ Missing match arm
1865         Either::A(true, .., true) => (),
1866         Either::A(true, .., false) => (),
1867         Either::A(false, .., false) => (),
1868         Either::B => (),
1869     }
1870     match Either::B {
1871         //^^^^^^^^^ Missing match arm
1872         Either::A(true, .., true) => (),
1873         Either::A(true, .., false) => (),
1874         Either::A(.., true) => (),
1875         Either::B => (),
1876     }
1877
1878     match Either::B {
1879         Either::A(true, .., true) => (),
1880         Either::A(true, .., false) => (),
1881         Either::A(false, .., true) => (),
1882         Either::A(false, .., false) => (),
1883         Either::B => (),
1884     }
1885     match Either::B {
1886         Either::A(true, .., true) => (),
1887         Either::A(true, .., false) => (),
1888         Either::A(.., true) => (),
1889         Either::A(.., false) => (),
1890         Either::B => (),
1891     }
1892 }
1893 "#,
1894         );
1895     }
1896
1897     #[test]
1898     fn never() {
1899         check_diagnostics(
1900             r#"
1901 enum Never {}
1902
1903 fn enum_(never: Never) {
1904     match never {}
1905 }
1906 fn enum_ref(never: &Never) {
1907     match never {}
1908         //^^^^^ Missing match arm
1909 }
1910 fn bang(never: !) {
1911     match never {}
1912 }
1913 "#,
1914         );
1915     }
1916
1917     #[test]
1918     fn unknown_type() {
1919         check_diagnostics(
1920             r#"
1921 enum Option<T> { Some(T), None }
1922
1923 fn main() {
1924     // `Never` is deliberately not defined so that it's an uninferred type.
1925     match Option::<Never>::None {
1926         None => (),
1927         Some(never) => match never {},
1928     //  ^^^^^^^^^^^ Internal: match check bailed out
1929     }
1930     match Option::<Never>::None {
1931         //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1932         Option::Some(_never) => {},
1933     }
1934 }
1935 "#,
1936         );
1937     }
1938
1939     #[test]
1940     fn tuple_of_bools_with_ellipsis_at_end_missing_arm() {
1941         check_diagnostics(
1942             r#"
1943 fn main() {
1944     match (false, true, false) {
1945         //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1946         (false, ..) => (),
1947     }
1948 }"#,
1949         );
1950     }
1951
1952     #[test]
1953     fn tuple_of_bools_with_ellipsis_at_beginning_missing_arm() {
1954         check_diagnostics(
1955             r#"
1956 fn main() {
1957     match (false, true, false) {
1958         //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1959         (.., false) => (),
1960     }
1961 }"#,
1962         );
1963     }
1964
1965     #[test]
1966     fn tuple_of_bools_with_ellipsis_in_middle_missing_arm() {
1967         check_diagnostics(
1968             r#"
1969 fn main() {
1970     match (false, true, false) {
1971         //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1972         (true, .., false) => (),
1973     }
1974 }"#,
1975         );
1976     }
1977
1978     #[test]
1979     fn record_struct() {
1980         check_diagnostics(
1981             r#"struct Foo { a: bool }
1982 fn main(f: Foo) {
1983     match f {}
1984         //^ Missing match arm
1985     match f { Foo { a: true } => () }
1986         //^ Missing match arm
1987     match &f { Foo { a: true } => () }
1988         //^^ Missing match arm
1989     match f { Foo { a: _ } => () }
1990     match f {
1991         Foo { a: true } => (),
1992         Foo { a: false } => (),
1993     }
1994     match &f {
1995         Foo { a: true } => (),
1996         Foo { a: false } => (),
1997     }
1998 }
1999 "#,
2000         );
2001     }
2002
2003     #[test]
2004     fn tuple_struct() {
2005         check_diagnostics(
2006             r#"struct Foo(bool);
2007 fn main(f: Foo) {
2008     match f {}
2009         //^ Missing match arm
2010     match f { Foo(true) => () }
2011         //^ Missing match arm
2012     match f {
2013         Foo(true) => (),
2014         Foo(false) => (),
2015     }
2016 }
2017 "#,
2018         );
2019     }
2020
2021     #[test]
2022     fn unit_struct() {
2023         check_diagnostics(
2024             r#"struct Foo;
2025 fn main(f: Foo) {
2026     match f {}
2027         //^ Missing match arm
2028     match f { Foo => () }
2029 }
2030 "#,
2031         );
2032     }
2033
2034     #[test]
2035     fn record_struct_ellipsis() {
2036         check_diagnostics(
2037             r#"struct Foo { foo: bool, bar: bool }
2038 fn main(f: Foo) {
2039     match f { Foo { foo: true, .. } => () }
2040         //^ Missing match arm
2041     match f {
2042         //^ Missing match arm
2043         Foo { foo: true, .. } => (),
2044         Foo { bar: false, .. } => ()
2045     }
2046     match f { Foo { .. } => () }
2047     match f {
2048         Foo { foo: true, .. } => (),
2049         Foo { foo: false, .. } => ()
2050     }
2051 }
2052 "#,
2053         );
2054     }
2055
2056     #[test]
2057     fn internal_or() {
2058         check_diagnostics(
2059             r#"
2060 fn main() {
2061     enum Either { A(bool), B }
2062     match Either::B {
2063         //^^^^^^^^^ Missing match arm
2064         Either::A(true | false) => (),
2065     }
2066 }
2067 "#,
2068         );
2069     }
2070
2071     #[test]
2072     fn no_panic_at_unimplemented_subpattern_type() {
2073         check_diagnostics(
2074             r#"
2075 struct S { a: char}
2076 fn main(v: S) {
2077     match v { S{ a }      => {} }
2078     match v { S{ a: _x }  => {} }
2079     match v { S{ a: 'a' } => {} }
2080             //^^^^^^^^^^^ Internal: match check bailed out
2081     match v { S{..}       => {} }
2082     match v { _           => {} }
2083     match v { }
2084         //^ Missing match arm
2085 }
2086 "#,
2087         );
2088     }
2089
2090     #[test]
2091     fn binding() {
2092         check_diagnostics(
2093             r#"
2094 fn main() {
2095     match true {
2096         _x @ true => {}
2097         false     => {}
2098     }
2099     match true { _x @ true => {} }
2100         //^^^^ Missing match arm
2101 }
2102 "#,
2103         );
2104     }
2105
2106     #[test]
2107     fn binding_ref_has_correct_type() {
2108         // Asserts `PatKind::Binding(ref _x): bool`, not &bool.
2109         // If that's not true match checking will panic with "incompatible constructors"
2110         // FIXME: make facilities to test this directly like `tests::check_infer(..)`
2111         check_diagnostics(
2112             r#"
2113 enum Foo { A }
2114 fn main() {
2115     // FIXME: this should not bail out but current behavior is such as the old algorithm.
2116     // ExprValidator::validate_match(..) checks types of top level patterns incorrecly.
2117     match Foo::A {
2118         ref _x => {}
2119     //  ^^^^^^ Internal: match check bailed out
2120         Foo::A => {}
2121     }
2122     match (true,) {
2123         (ref _x,) => {}
2124         (true,) => {}
2125     }
2126 }
2127 "#,
2128         );
2129     }
2130
2131     #[test]
2132     fn enum_non_exhaustive() {
2133         check_diagnostics(
2134             r#"
2135 //- /lib.rs crate:lib
2136 #[non_exhaustive]
2137 pub enum E { A, B }
2138 fn _local() {
2139     match E::A { _ => {} }
2140     match E::A {
2141         E::A => {}
2142         E::B => {}
2143     }
2144     match E::A {
2145         E::A | E::B => {}
2146     }
2147 }
2148
2149 //- /main.rs crate:main deps:lib
2150 use lib::E;
2151 fn main() {
2152     match E::A { _ => {} }
2153     match E::A {
2154         //^^^^ Missing match arm
2155         E::A => {}
2156         E::B => {}
2157     }
2158     match E::A {
2159         //^^^^ Missing match arm
2160         E::A | E::B => {}
2161     }
2162 }
2163 "#,
2164         );
2165     }
2166
2167     #[test]
2168     fn match_guard() {
2169         check_diagnostics(
2170             r#"
2171 fn main() {
2172     match true {
2173         true if false => {}
2174         true          => {}
2175         false         => {}
2176     }
2177     match true {
2178         //^^^^ Missing match arm
2179         true if false => {}
2180         false         => {}
2181     }
2182 }
2183 "#,
2184         );
2185     }
2186
2187     #[test]
2188     fn pattern_type_is_of_substitution() {
2189         cov_mark::check!(match_check_wildcard_expanded_to_substitutions);
2190         check_diagnostics(
2191             r#"
2192 struct Foo<T>(T);
2193 struct Bar;
2194 fn main() {
2195     match Foo(Bar) {
2196         _ | Foo(Bar) => {}
2197     }
2198 }
2199 "#,
2200         );
2201     }
2202
2203     #[test]
2204     fn record_struct_no_such_field() {
2205         check_diagnostics(
2206             r#"
2207 struct Foo { }
2208 fn main(f: Foo) {
2209     match f { Foo { bar } => () }
2210     //        ^^^^^^^^^^^ Internal: match check bailed out
2211 }
2212 "#,
2213         );
2214     }
2215
2216     #[test]
2217     fn match_ergonomics_issue_9095() {
2218         check_diagnostics(
2219             r#"
2220 enum Foo<T> { A(T) }
2221 fn main() {
2222     match &Foo::A(true) {
2223         _ => {}
2224         Foo::A(_) => {}
2225     }
2226 }
2227 "#,
2228         );
2229     }
2230
2231     mod false_negatives {
2232         //! The implementation of match checking here is a work in progress. As we roll this out, we
2233         //! prefer false negatives to false positives (ideally there would be no false positives). This
2234         //! test module should document known false negatives. Eventually we will have a complete
2235         //! implementation of match checking and this module will be empty.
2236         //!
2237         //! The reasons for documenting known false negatives:
2238         //!
2239         //!   1. It acts as a backlog of work that can be done to improve the behavior of the system.
2240         //!   2. It ensures the code doesn't panic when handling these cases.
2241         use super::*;
2242
2243         #[test]
2244         fn integers() {
2245             // We don't currently check integer exhaustiveness.
2246             check_diagnostics(
2247                 r#"
2248 fn main() {
2249     match 5 {
2250         10 => (),
2251     //  ^^ Internal: match check bailed out
2252         11..20 => (),
2253     }
2254 }
2255 "#,
2256             );
2257         }
2258
2259         #[test]
2260         fn reference_patterns_at_top_level() {
2261             check_diagnostics(
2262                 r#"
2263 fn main() {
2264     match &false {
2265         &true => {}
2266     //  ^^^^^ Internal: match check bailed out
2267     }
2268 }
2269             "#,
2270             );
2271         }
2272
2273         #[test]
2274         fn reference_patterns_in_fields() {
2275             check_diagnostics(
2276                 r#"
2277 fn main() {
2278     match (&false,) {
2279         (true,) => {}
2280     //  ^^^^^^^ Internal: match check bailed out
2281     }
2282     match (&false,) {
2283         (&true,) => {}
2284     //  ^^^^^^^^ Internal: match check bailed out
2285     }
2286 }
2287             "#,
2288             );
2289         }
2290     }
2291 }
2292
2293 #[cfg(test)]
2294 mod decl_check_tests {
2295     use crate::diagnostics::tests::check_diagnostics;
2296
2297     #[test]
2298     fn incorrect_function_name() {
2299         check_diagnostics(
2300             r#"
2301 fn NonSnakeCaseName() {}
2302 // ^^^^^^^^^^^^^^^^ Function `NonSnakeCaseName` should have snake_case name, e.g. `non_snake_case_name`
2303 "#,
2304         );
2305     }
2306
2307     #[test]
2308     fn incorrect_function_params() {
2309         check_diagnostics(
2310             r#"
2311 fn foo(SomeParam: u8) {}
2312     // ^^^^^^^^^ Parameter `SomeParam` should have snake_case name, e.g. `some_param`
2313
2314 fn foo2(ok_param: &str, CAPS_PARAM: u8) {}
2315                      // ^^^^^^^^^^ Parameter `CAPS_PARAM` should have snake_case name, e.g. `caps_param`
2316 "#,
2317         );
2318     }
2319
2320     #[test]
2321     fn incorrect_variable_names() {
2322         check_diagnostics(
2323             r#"
2324 fn foo() {
2325     let SOME_VALUE = 10;
2326      // ^^^^^^^^^^ Variable `SOME_VALUE` should have snake_case name, e.g. `some_value`
2327     let AnotherValue = 20;
2328      // ^^^^^^^^^^^^ Variable `AnotherValue` should have snake_case name, e.g. `another_value`
2329 }
2330 "#,
2331         );
2332     }
2333
2334     #[test]
2335     fn incorrect_struct_names() {
2336         check_diagnostics(
2337             r#"
2338 struct non_camel_case_name {}
2339     // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName`
2340
2341 struct SCREAMING_CASE {}
2342     // ^^^^^^^^^^^^^^ Structure `SCREAMING_CASE` should have CamelCase name, e.g. `ScreamingCase`
2343 "#,
2344         );
2345     }
2346
2347     #[test]
2348     fn no_diagnostic_for_camel_cased_acronyms_in_struct_name() {
2349         check_diagnostics(
2350             r#"
2351 struct AABB {}
2352 "#,
2353         );
2354     }
2355
2356     #[test]
2357     fn incorrect_struct_field() {
2358         check_diagnostics(
2359             r#"
2360 struct SomeStruct { SomeField: u8 }
2361                  // ^^^^^^^^^ Field `SomeField` should have snake_case name, e.g. `some_field`
2362 "#,
2363         );
2364     }
2365
2366     #[test]
2367     fn incorrect_enum_names() {
2368         check_diagnostics(
2369             r#"
2370 enum some_enum { Val(u8) }
2371   // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum`
2372
2373 enum SOME_ENUM {}
2374   // ^^^^^^^^^ Enum `SOME_ENUM` should have CamelCase name, e.g. `SomeEnum`
2375 "#,
2376         );
2377     }
2378
2379     #[test]
2380     fn no_diagnostic_for_camel_cased_acronyms_in_enum_name() {
2381         check_diagnostics(
2382             r#"
2383 enum AABB {}
2384 "#,
2385         );
2386     }
2387
2388     #[test]
2389     fn incorrect_enum_variant_name() {
2390         check_diagnostics(
2391             r#"
2392 enum SomeEnum { SOME_VARIANT(u8) }
2393              // ^^^^^^^^^^^^ Variant `SOME_VARIANT` should have CamelCase name, e.g. `SomeVariant`
2394 "#,
2395         );
2396     }
2397
2398     #[test]
2399     fn incorrect_const_name() {
2400         check_diagnostics(
2401             r#"
2402 const some_weird_const: u8 = 10;
2403    // ^^^^^^^^^^^^^^^^ Constant `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2404 "#,
2405         );
2406     }
2407
2408     #[test]
2409     fn incorrect_static_name() {
2410         check_diagnostics(
2411             r#"
2412 static some_weird_const: u8 = 10;
2413     // ^^^^^^^^^^^^^^^^ Static variable `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2414 "#,
2415         );
2416     }
2417
2418     #[test]
2419     fn fn_inside_impl_struct() {
2420         check_diagnostics(
2421             r#"
2422 struct someStruct;
2423     // ^^^^^^^^^^ Structure `someStruct` should have CamelCase name, e.g. `SomeStruct`
2424
2425 impl someStruct {
2426     fn SomeFunc(&self) {
2427     // ^^^^^^^^ Function `SomeFunc` should have snake_case name, e.g. `some_func`
2428         let WHY_VAR_IS_CAPS = 10;
2429          // ^^^^^^^^^^^^^^^ Variable `WHY_VAR_IS_CAPS` should have snake_case name, e.g. `why_var_is_caps`
2430     }
2431 }
2432 "#,
2433         );
2434     }
2435
2436     #[test]
2437     fn no_diagnostic_for_enum_varinats() {
2438         check_diagnostics(
2439             r#"
2440 enum Option { Some, None }
2441
2442 fn main() {
2443     match Option::None {
2444         None => (),
2445         Some => (),
2446     }
2447 }
2448 "#,
2449         );
2450     }
2451
2452     #[test]
2453     fn non_let_bind() {
2454         check_diagnostics(
2455             r#"
2456 enum Option { Some, None }
2457
2458 fn main() {
2459     match Option::None {
2460         SOME_VAR @ None => (),
2461      // ^^^^^^^^ Variable `SOME_VAR` should have snake_case name, e.g. `some_var`
2462         Some => (),
2463     }
2464 }
2465 "#,
2466         );
2467     }
2468
2469     #[test]
2470     fn allow_attributes() {
2471         check_diagnostics(
2472             r#"
2473 #[allow(non_snake_case)]
2474 fn NonSnakeCaseName(SOME_VAR: u8) -> u8{
2475     // cov_flags generated output from elsewhere in this file
2476     extern "C" {
2477         #[no_mangle]
2478         static lower_case: u8;
2479     }
2480
2481     let OtherVar = SOME_VAR + 1;
2482     OtherVar
2483 }
2484
2485 #[allow(nonstandard_style)]
2486 mod CheckNonstandardStyle {
2487     fn HiImABadFnName() {}
2488 }
2489
2490 #[allow(bad_style)]
2491 mod CheckBadStyle {
2492     fn HiImABadFnName() {}
2493 }
2494
2495 mod F {
2496     #![allow(non_snake_case)]
2497     fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {}
2498 }
2499
2500 #[allow(non_snake_case, non_camel_case_types)]
2501 pub struct some_type {
2502     SOME_FIELD: u8,
2503     SomeField: u16,
2504 }
2505
2506 #[allow(non_upper_case_globals)]
2507 pub const some_const: u8 = 10;
2508
2509 #[allow(non_upper_case_globals)]
2510 pub static SomeStatic: u8 = 10;
2511     "#,
2512         );
2513     }
2514
2515     #[test]
2516     fn allow_attributes_crate_attr() {
2517         check_diagnostics(
2518             r#"
2519 #![allow(non_snake_case)]
2520
2521 mod F {
2522     fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {}
2523 }
2524     "#,
2525         );
2526     }
2527
2528     #[test]
2529     #[ignore]
2530     fn bug_trait_inside_fn() {
2531         // FIXME:
2532         // This is broken, and in fact, should not even be looked at by this
2533         // lint in the first place. There's weird stuff going on in the
2534         // collection phase.
2535         // It's currently being brought in by:
2536         // * validate_func on `a` recursing into modules
2537         // * then it finds the trait and then the function while iterating
2538         //   through modules
2539         // * then validate_func is called on Dirty
2540         // * ... which then proceeds to look at some unknown module taking no
2541         //   attrs from either the impl or the fn a, and then finally to the root
2542         //   module
2543         //
2544         // It should find the attribute on the trait, but it *doesn't even see
2545         // the trait* as far as I can tell.
2546
2547         check_diagnostics(
2548             r#"
2549 trait T { fn a(); }
2550 struct U {}
2551 impl T for U {
2552     fn a() {
2553         // this comes out of bitflags, mostly
2554         #[allow(non_snake_case)]
2555         trait __BitFlags {
2556             const HiImAlsoBad: u8 = 2;
2557             #[inline]
2558             fn Dirty(&self) -> bool {
2559                 false
2560             }
2561         }
2562
2563     }
2564 }
2565     "#,
2566         );
2567     }
2568
2569     #[test]
2570     #[ignore]
2571     fn bug_traits_arent_checked() {
2572         // FIXME: Traits and functions in traits aren't currently checked by
2573         // r-a, even though rustc will complain about them.
2574         check_diagnostics(
2575             r#"
2576 trait BAD_TRAIT {
2577     // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait`
2578     fn BAD_FUNCTION();
2579     // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function`
2580     fn BadFunction();
2581     // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function`
2582 }
2583     "#,
2584         );
2585     }
2586
2587     #[test]
2588     fn ignores_extern_items() {
2589         cov_mark::check!(extern_func_incorrect_case_ignored);
2590         cov_mark::check!(extern_static_incorrect_case_ignored);
2591         check_diagnostics(
2592             r#"
2593 extern {
2594     fn NonSnakeCaseName(SOME_VAR: u8) -> u8;
2595     pub static SomeStatic: u8 = 10;
2596 }
2597             "#,
2598         );
2599     }
2600
2601     #[test]
2602     fn infinite_loop_inner_items() {
2603         check_diagnostics(
2604             r#"
2605 fn qualify() {
2606     mod foo {
2607         use super::*;
2608     }
2609 }
2610             "#,
2611         )
2612     }
2613
2614     #[test] // Issue #8809.
2615     fn parenthesized_parameter() {
2616         check_diagnostics(r#"fn f((O): _) {}"#)
2617     }
2618 }