]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/diagnostics.rs
internal: move missing_fields diagnostics
[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_diagnostic() {
1060         check_diagnostics(
1061             r#"
1062 struct S { foo: i32, bar: () }
1063 fn baz(s: S) {
1064     let S { foo: _ } = s;
1065       //^ Missing structure fields:
1066       //| - bar
1067 }
1068 "#,
1069         );
1070     }
1071
1072     #[test]
1073     fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
1074         check_diagnostics(
1075             r"
1076 struct S { foo: i32, bar: () }
1077 fn baz(s: S) -> i32 {
1078     match s {
1079         S { foo, .. } => foo,
1080     }
1081 }
1082 ",
1083         )
1084     }
1085
1086     #[test]
1087     fn missing_record_pat_field_box() {
1088         check_diagnostics(
1089             r"
1090 struct S { s: Box<u32> }
1091 fn x(a: S) {
1092     let S { box s } = a;
1093 }
1094 ",
1095         )
1096     }
1097
1098     #[test]
1099     fn missing_record_pat_field_ref() {
1100         check_diagnostics(
1101             r"
1102 struct S { s: u32 }
1103 fn x(a: S) {
1104     let S { ref s } = a;
1105 }
1106 ",
1107         )
1108     }
1109
1110     #[test]
1111     fn simple_free_fn_zero() {
1112         check_diagnostics(
1113             r#"
1114 fn zero() {}
1115 fn f() { zero(1); }
1116        //^^^^^^^ Expected 0 arguments, found 1
1117 "#,
1118         );
1119
1120         check_diagnostics(
1121             r#"
1122 fn zero() {}
1123 fn f() { zero(); }
1124 "#,
1125         );
1126     }
1127
1128     #[test]
1129     fn simple_free_fn_one() {
1130         check_diagnostics(
1131             r#"
1132 fn one(arg: u8) {}
1133 fn f() { one(); }
1134        //^^^^^ Expected 1 argument, found 0
1135 "#,
1136         );
1137
1138         check_diagnostics(
1139             r#"
1140 fn one(arg: u8) {}
1141 fn f() { one(1); }
1142 "#,
1143         );
1144     }
1145
1146     #[test]
1147     fn method_as_fn() {
1148         check_diagnostics(
1149             r#"
1150 struct S;
1151 impl S { fn method(&self) {} }
1152
1153 fn f() {
1154     S::method();
1155 } //^^^^^^^^^^^ Expected 1 argument, found 0
1156 "#,
1157         );
1158
1159         check_diagnostics(
1160             r#"
1161 struct S;
1162 impl S { fn method(&self) {} }
1163
1164 fn f() {
1165     S::method(&S);
1166     S.method();
1167 }
1168 "#,
1169         );
1170     }
1171
1172     #[test]
1173     fn method_with_arg() {
1174         check_diagnostics(
1175             r#"
1176 struct S;
1177 impl S { fn method(&self, arg: u8) {} }
1178
1179             fn f() {
1180                 S.method();
1181             } //^^^^^^^^^^ Expected 1 argument, found 0
1182             "#,
1183         );
1184
1185         check_diagnostics(
1186             r#"
1187 struct S;
1188 impl S { fn method(&self, arg: u8) {} }
1189
1190 fn f() {
1191     S::method(&S, 0);
1192     S.method(1);
1193 }
1194 "#,
1195         );
1196     }
1197
1198     #[test]
1199     fn method_unknown_receiver() {
1200         // note: this is incorrect code, so there might be errors on this in the
1201         // future, but we shouldn't emit an argument count diagnostic here
1202         check_diagnostics(
1203             r#"
1204 trait Foo { fn method(&self, arg: usize) {} }
1205
1206 fn f() {
1207     let x;
1208     x.method();
1209 }
1210 "#,
1211         );
1212     }
1213
1214     #[test]
1215     fn tuple_struct() {
1216         check_diagnostics(
1217             r#"
1218 struct Tup(u8, u16);
1219 fn f() {
1220     Tup(0);
1221 } //^^^^^^ Expected 2 arguments, found 1
1222 "#,
1223         )
1224     }
1225
1226     #[test]
1227     fn enum_variant() {
1228         check_diagnostics(
1229             r#"
1230 enum En { Variant(u8, u16), }
1231 fn f() {
1232     En::Variant(0);
1233 } //^^^^^^^^^^^^^^ Expected 2 arguments, found 1
1234 "#,
1235         )
1236     }
1237
1238     #[test]
1239     fn enum_variant_type_macro() {
1240         check_diagnostics(
1241             r#"
1242 macro_rules! Type {
1243     () => { u32 };
1244 }
1245 enum Foo {
1246     Bar(Type![])
1247 }
1248 impl Foo {
1249     fn new() {
1250         Foo::Bar(0);
1251         Foo::Bar(0, 1);
1252       //^^^^^^^^^^^^^^ Expected 1 argument, found 2
1253         Foo::Bar();
1254       //^^^^^^^^^^ Expected 1 argument, found 0
1255     }
1256 }
1257         "#,
1258         );
1259     }
1260
1261     #[test]
1262     fn varargs() {
1263         check_diagnostics(
1264             r#"
1265 extern "C" {
1266     fn fixed(fixed: u8);
1267     fn varargs(fixed: u8, ...);
1268     fn varargs2(...);
1269 }
1270
1271 fn f() {
1272     unsafe {
1273         fixed(0);
1274         fixed(0, 1);
1275       //^^^^^^^^^^^ Expected 1 argument, found 2
1276         varargs(0);
1277         varargs(0, 1);
1278         varargs2();
1279         varargs2(0);
1280         varargs2(0, 1);
1281     }
1282 }
1283         "#,
1284         )
1285     }
1286
1287     #[test]
1288     fn arg_count_lambda() {
1289         check_diagnostics(
1290             r#"
1291 fn main() {
1292     let f = |()| ();
1293     f();
1294   //^^^ Expected 1 argument, found 0
1295     f(());
1296     f((), ());
1297   //^^^^^^^^^ Expected 1 argument, found 2
1298 }
1299 "#,
1300         )
1301     }
1302
1303     #[test]
1304     fn cfgd_out_call_arguments() {
1305         check_diagnostics(
1306             r#"
1307 struct C(#[cfg(FALSE)] ());
1308 impl C {
1309     fn new() -> Self {
1310         Self(
1311             #[cfg(FALSE)]
1312             (),
1313         )
1314     }
1315
1316     fn method(&self) {}
1317 }
1318
1319 fn main() {
1320     C::new().method(#[cfg(FALSE)] 0);
1321 }
1322             "#,
1323         );
1324     }
1325
1326     #[test]
1327     fn cfgd_out_fn_params() {
1328         check_diagnostics(
1329             r#"
1330 fn foo(#[cfg(NEVER)] x: ()) {}
1331
1332 struct S;
1333
1334 impl S {
1335     fn method(#[cfg(NEVER)] self) {}
1336     fn method2(#[cfg(NEVER)] self, arg: u8) {}
1337     fn method3(self, #[cfg(NEVER)] arg: u8) {}
1338 }
1339
1340 extern "C" {
1341     fn fixed(fixed: u8, #[cfg(NEVER)] ...);
1342     fn varargs(#[cfg(not(NEVER))] ...);
1343 }
1344
1345 fn main() {
1346     foo();
1347     S::method();
1348     S::method2(0);
1349     S::method3(S);
1350     S.method3();
1351     unsafe {
1352         fixed(0);
1353         varargs(1, 2, 3);
1354     }
1355 }
1356             "#,
1357         )
1358     }
1359
1360     #[test]
1361     fn missing_semicolon() {
1362         check_diagnostics(
1363             r#"
1364                 fn test() -> i32 { 123; }
1365                                  //^^^ Remove this semicolon
1366             "#,
1367         );
1368     }
1369
1370     #[test]
1371     fn import_extern_crate_clash_with_inner_item() {
1372         // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
1373
1374         check_diagnostics(
1375             r#"
1376 //- /lib.rs crate:lib deps:jwt
1377 mod permissions;
1378
1379 use permissions::jwt;
1380
1381 fn f() {
1382     fn inner() {}
1383     jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
1384 }
1385
1386 //- /permissions.rs
1387 pub mod jwt  {
1388     pub struct Claims {}
1389 }
1390
1391 //- /jwt/lib.rs crate:jwt
1392 pub struct Claims {
1393     field: u8,
1394 }
1395         "#,
1396         );
1397     }
1398 }
1399
1400 #[cfg(test)]
1401 pub(super) mod match_check_tests {
1402     use crate::diagnostics::tests::check_diagnostics;
1403
1404     #[test]
1405     fn empty_tuple() {
1406         check_diagnostics(
1407             r#"
1408 fn main() {
1409     match () { }
1410         //^^ Missing match arm
1411     match (()) { }
1412         //^^^^ Missing match arm
1413
1414     match () { _ => (), }
1415     match () { () => (), }
1416     match (()) { (()) => (), }
1417 }
1418 "#,
1419         );
1420     }
1421
1422     #[test]
1423     fn tuple_of_two_empty_tuple() {
1424         check_diagnostics(
1425             r#"
1426 fn main() {
1427     match ((), ()) { }
1428         //^^^^^^^^ Missing match arm
1429
1430     match ((), ()) { ((), ()) => (), }
1431 }
1432 "#,
1433         );
1434     }
1435
1436     #[test]
1437     fn boolean() {
1438         check_diagnostics(
1439             r#"
1440 fn test_main() {
1441     match false { }
1442         //^^^^^ Missing match arm
1443     match false { true => (), }
1444         //^^^^^ Missing match arm
1445     match (false, true) {}
1446         //^^^^^^^^^^^^^ Missing match arm
1447     match (false, true) { (true, true) => (), }
1448         //^^^^^^^^^^^^^ Missing match arm
1449     match (false, true) {
1450         //^^^^^^^^^^^^^ Missing match arm
1451         (false, true) => (),
1452         (false, false) => (),
1453         (true, false) => (),
1454     }
1455     match (false, true) { (true, _x) => (), }
1456         //^^^^^^^^^^^^^ Missing match arm
1457
1458     match false { true => (), false => (), }
1459     match (false, true) {
1460         (false, _) => (),
1461         (true, false) => (),
1462         (_, true) => (),
1463     }
1464     match (false, true) {
1465         (true, true) => (),
1466         (true, false) => (),
1467         (false, true) => (),
1468         (false, false) => (),
1469     }
1470     match (false, true) {
1471         (true, _x) => (),
1472         (false, true) => (),
1473         (false, false) => (),
1474     }
1475     match (false, true, false) {
1476         (false, ..) => (),
1477         (true, ..) => (),
1478     }
1479     match (false, true, false) {
1480         (.., false) => (),
1481         (.., true) => (),
1482     }
1483     match (false, true, false) { (..) => (), }
1484 }
1485 "#,
1486         );
1487     }
1488
1489     #[test]
1490     fn tuple_of_tuple_and_bools() {
1491         check_diagnostics(
1492             r#"
1493 fn main() {
1494     match (false, ((), false)) {}
1495         //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1496     match (false, ((), false)) { (true, ((), true)) => (), }
1497         //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1498     match (false, ((), false)) { (true, _) => (), }
1499         //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1500
1501     match (false, ((), false)) {
1502         (true, ((), true)) => (),
1503         (true, ((), false)) => (),
1504         (false, ((), true)) => (),
1505         (false, ((), false)) => (),
1506     }
1507     match (false, ((), false)) {
1508         (true, ((), true)) => (),
1509         (true, ((), false)) => (),
1510         (false, _) => (),
1511     }
1512 }
1513 "#,
1514         );
1515     }
1516
1517     #[test]
1518     fn enums() {
1519         check_diagnostics(
1520             r#"
1521 enum Either { A, B, }
1522
1523 fn main() {
1524     match Either::A { }
1525         //^^^^^^^^^ Missing match arm
1526     match Either::B { Either::A => (), }
1527         //^^^^^^^^^ Missing match arm
1528
1529     match &Either::B {
1530         //^^^^^^^^^^ Missing match arm
1531         Either::A => (),
1532     }
1533
1534     match Either::B {
1535         Either::A => (), Either::B => (),
1536     }
1537     match &Either::B {
1538         Either::A => (), Either::B => (),
1539     }
1540 }
1541 "#,
1542         );
1543     }
1544
1545     #[test]
1546     fn enum_containing_bool() {
1547         check_diagnostics(
1548             r#"
1549 enum Either { A(bool), B }
1550
1551 fn main() {
1552     match Either::B { }
1553         //^^^^^^^^^ Missing match arm
1554     match Either::B {
1555         //^^^^^^^^^ Missing match arm
1556         Either::A(true) => (), Either::B => ()
1557     }
1558
1559     match Either::B {
1560         Either::A(true) => (),
1561         Either::A(false) => (),
1562         Either::B => (),
1563     }
1564     match Either::B {
1565         Either::B => (),
1566         _ => (),
1567     }
1568     match Either::B {
1569         Either::A(_) => (),
1570         Either::B => (),
1571     }
1572
1573 }
1574         "#,
1575         );
1576     }
1577
1578     #[test]
1579     fn enum_different_sizes() {
1580         check_diagnostics(
1581             r#"
1582 enum Either { A(bool), B(bool, bool) }
1583
1584 fn main() {
1585     match Either::A(false) {
1586         //^^^^^^^^^^^^^^^^ Missing match arm
1587         Either::A(_) => (),
1588         Either::B(false, _) => (),
1589     }
1590
1591     match Either::A(false) {
1592         Either::A(_) => (),
1593         Either::B(true, _) => (),
1594         Either::B(false, _) => (),
1595     }
1596     match Either::A(false) {
1597         Either::A(true) | Either::A(false) => (),
1598         Either::B(true, _) => (),
1599         Either::B(false, _) => (),
1600     }
1601 }
1602 "#,
1603         );
1604     }
1605
1606     #[test]
1607     fn tuple_of_enum_no_diagnostic() {
1608         check_diagnostics(
1609             r#"
1610 enum Either { A(bool), B(bool, bool) }
1611 enum Either2 { C, D }
1612
1613 fn main() {
1614     match (Either::A(false), Either2::C) {
1615         (Either::A(true), _) | (Either::A(false), _) => (),
1616         (Either::B(true, _), Either2::C) => (),
1617         (Either::B(false, _), Either2::C) => (),
1618         (Either::B(_, _), Either2::D) => (),
1619     }
1620 }
1621 "#,
1622         );
1623     }
1624
1625     #[test]
1626     fn or_pattern_no_diagnostic() {
1627         check_diagnostics(
1628             r#"
1629 enum Either {A, B}
1630
1631 fn main() {
1632     match (Either::A, Either::B) {
1633         (Either::A | Either::B, _) => (),
1634     }
1635 }"#,
1636         )
1637     }
1638
1639     #[test]
1640     fn mismatched_types() {
1641         // Match statements with arms that don't match the
1642         // expression pattern do not fire this diagnostic.
1643         check_diagnostics(
1644             r#"
1645 enum Either { A, B }
1646 enum Either2 { C, D }
1647
1648 fn main() {
1649     match Either::A {
1650         Either2::C => (),
1651     //  ^^^^^^^^^^ Internal: match check bailed out
1652         Either2::D => (),
1653     }
1654     match (true, false) {
1655         (true, false, true) => (),
1656     //  ^^^^^^^^^^^^^^^^^^^ Internal: match check bailed out
1657         (true) => (),
1658     }
1659     match (true, false) { (true,) => {} }
1660     //                    ^^^^^^^ Internal: match check bailed out
1661     match (0) { () => () }
1662             //  ^^ Internal: match check bailed out
1663     match Unresolved::Bar { Unresolved::Baz => () }
1664 }
1665         "#,
1666         );
1667     }
1668
1669     #[test]
1670     fn mismatched_types_in_or_patterns() {
1671         check_diagnostics(
1672             r#"
1673 fn main() {
1674     match false { true | () => {} }
1675     //            ^^^^^^^^^ Internal: match check bailed out
1676     match (false,) { (true | (),) => {} }
1677     //               ^^^^^^^^^^^^ Internal: match check bailed out
1678 }
1679 "#,
1680         );
1681     }
1682
1683     #[test]
1684     fn malformed_match_arm_tuple_enum_missing_pattern() {
1685         // We are testing to be sure we don't panic here when the match
1686         // arm `Either::B` is missing its pattern.
1687         check_diagnostics(
1688             r#"
1689 enum Either { A, B(u32) }
1690
1691 fn main() {
1692     match Either::A {
1693         Either::A => (),
1694         Either::B() => (),
1695     }
1696 }
1697 "#,
1698         );
1699     }
1700
1701     #[test]
1702     fn malformed_match_arm_extra_fields() {
1703         check_diagnostics(
1704             r#"
1705 enum A { B(isize, isize), C }
1706 fn main() {
1707     match A::B(1, 2) {
1708         A::B(_, _, _) => (),
1709     //  ^^^^^^^^^^^^^ Internal: match check bailed out
1710     }
1711     match A::B(1, 2) {
1712         A::C(_) => (),
1713     //  ^^^^^^^ Internal: match check bailed out
1714     }
1715 }
1716 "#,
1717         );
1718     }
1719
1720     #[test]
1721     fn expr_diverges() {
1722         check_diagnostics(
1723             r#"
1724 enum Either { A, B }
1725
1726 fn main() {
1727     match loop {} {
1728         Either::A => (),
1729     //  ^^^^^^^^^ Internal: match check bailed out
1730         Either::B => (),
1731     }
1732     match loop {} {
1733         Either::A => (),
1734     //  ^^^^^^^^^ Internal: match check bailed out
1735     }
1736     match loop { break Foo::A } {
1737         //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1738         Either::A => (),
1739     }
1740     match loop { break Foo::A } {
1741         Either::A => (),
1742         Either::B => (),
1743     }
1744 }
1745 "#,
1746         );
1747     }
1748
1749     #[test]
1750     fn expr_partially_diverges() {
1751         check_diagnostics(
1752             r#"
1753 enum Either<T> { A(T), B }
1754
1755 fn foo() -> Either<!> { Either::B }
1756 fn main() -> u32 {
1757     match foo() {
1758         Either::A(val) => val,
1759         Either::B => 0,
1760     }
1761 }
1762 "#,
1763         );
1764     }
1765
1766     #[test]
1767     fn enum_record() {
1768         check_diagnostics(
1769             r#"
1770 enum Either { A { foo: bool }, B }
1771
1772 fn main() {
1773     let a = Either::A { foo: true };
1774     match a { }
1775         //^ Missing match arm
1776     match a { Either::A { foo: true } => () }
1777         //^ Missing match arm
1778     match a {
1779         Either::A { } => (),
1780       //^^^^^^^^^ Missing structure fields:
1781       //        | - foo
1782         Either::B => (),
1783     }
1784     match a {
1785         //^ Missing match arm
1786         Either::A { } => (),
1787     } //^^^^^^^^^ Missing structure fields:
1788       //        | - foo
1789
1790     match a {
1791         Either::A { foo: true } => (),
1792         Either::A { foo: false } => (),
1793         Either::B => (),
1794     }
1795     match a {
1796         Either::A { foo: _ } => (),
1797         Either::B => (),
1798     }
1799 }
1800 "#,
1801         );
1802     }
1803
1804     #[test]
1805     fn enum_record_fields_out_of_order() {
1806         check_diagnostics(
1807             r#"
1808 enum Either {
1809     A { foo: bool, bar: () },
1810     B,
1811 }
1812
1813 fn main() {
1814     let a = Either::A { foo: true, bar: () };
1815     match a {
1816         //^ Missing match arm
1817         Either::A { bar: (), foo: false } => (),
1818         Either::A { foo: true, bar: () } => (),
1819     }
1820
1821     match a {
1822         Either::A { bar: (), foo: false } => (),
1823         Either::A { foo: true, bar: () } => (),
1824         Either::B => (),
1825     }
1826 }
1827 "#,
1828         );
1829     }
1830
1831     #[test]
1832     fn enum_record_ellipsis() {
1833         check_diagnostics(
1834             r#"
1835 enum Either {
1836     A { foo: bool, bar: bool },
1837     B,
1838 }
1839
1840 fn main() {
1841     let a = Either::B;
1842     match a {
1843         //^ Missing match arm
1844         Either::A { foo: true, .. } => (),
1845         Either::B => (),
1846     }
1847     match a {
1848         //^ Missing match arm
1849         Either::A { .. } => (),
1850     }
1851
1852     match a {
1853         Either::A { foo: true, .. } => (),
1854         Either::A { foo: false, .. } => (),
1855         Either::B => (),
1856     }
1857
1858     match a {
1859         Either::A { .. } => (),
1860         Either::B => (),
1861     }
1862 }
1863 "#,
1864         );
1865     }
1866
1867     #[test]
1868     fn enum_tuple_partial_ellipsis() {
1869         check_diagnostics(
1870             r#"
1871 enum Either {
1872     A(bool, bool, bool, bool),
1873     B,
1874 }
1875
1876 fn main() {
1877     match Either::B {
1878         //^^^^^^^^^ Missing match arm
1879         Either::A(true, .., true) => (),
1880         Either::A(true, .., false) => (),
1881         Either::A(false, .., false) => (),
1882         Either::B => (),
1883     }
1884     match Either::B {
1885         //^^^^^^^^^ Missing match arm
1886         Either::A(true, .., true) => (),
1887         Either::A(true, .., false) => (),
1888         Either::A(.., true) => (),
1889         Either::B => (),
1890     }
1891
1892     match Either::B {
1893         Either::A(true, .., true) => (),
1894         Either::A(true, .., false) => (),
1895         Either::A(false, .., true) => (),
1896         Either::A(false, .., false) => (),
1897         Either::B => (),
1898     }
1899     match Either::B {
1900         Either::A(true, .., true) => (),
1901         Either::A(true, .., false) => (),
1902         Either::A(.., true) => (),
1903         Either::A(.., false) => (),
1904         Either::B => (),
1905     }
1906 }
1907 "#,
1908         );
1909     }
1910
1911     #[test]
1912     fn never() {
1913         check_diagnostics(
1914             r#"
1915 enum Never {}
1916
1917 fn enum_(never: Never) {
1918     match never {}
1919 }
1920 fn enum_ref(never: &Never) {
1921     match never {}
1922         //^^^^^ Missing match arm
1923 }
1924 fn bang(never: !) {
1925     match never {}
1926 }
1927 "#,
1928         );
1929     }
1930
1931     #[test]
1932     fn unknown_type() {
1933         check_diagnostics(
1934             r#"
1935 enum Option<T> { Some(T), None }
1936
1937 fn main() {
1938     // `Never` is deliberately not defined so that it's an uninferred type.
1939     match Option::<Never>::None {
1940         None => (),
1941         Some(never) => match never {},
1942     //  ^^^^^^^^^^^ Internal: match check bailed out
1943     }
1944     match Option::<Never>::None {
1945         //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1946         Option::Some(_never) => {},
1947     }
1948 }
1949 "#,
1950         );
1951     }
1952
1953     #[test]
1954     fn tuple_of_bools_with_ellipsis_at_end_missing_arm() {
1955         check_diagnostics(
1956             r#"
1957 fn main() {
1958     match (false, true, false) {
1959         //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1960         (false, ..) => (),
1961     }
1962 }"#,
1963         );
1964     }
1965
1966     #[test]
1967     fn tuple_of_bools_with_ellipsis_at_beginning_missing_arm() {
1968         check_diagnostics(
1969             r#"
1970 fn main() {
1971     match (false, true, false) {
1972         //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1973         (.., false) => (),
1974     }
1975 }"#,
1976         );
1977     }
1978
1979     #[test]
1980     fn tuple_of_bools_with_ellipsis_in_middle_missing_arm() {
1981         check_diagnostics(
1982             r#"
1983 fn main() {
1984     match (false, true, false) {
1985         //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1986         (true, .., false) => (),
1987     }
1988 }"#,
1989         );
1990     }
1991
1992     #[test]
1993     fn record_struct() {
1994         check_diagnostics(
1995             r#"struct Foo { a: bool }
1996 fn main(f: Foo) {
1997     match f {}
1998         //^ Missing match arm
1999     match f { Foo { a: true } => () }
2000         //^ Missing match arm
2001     match &f { Foo { a: true } => () }
2002         //^^ Missing match arm
2003     match f { Foo { a: _ } => () }
2004     match f {
2005         Foo { a: true } => (),
2006         Foo { a: false } => (),
2007     }
2008     match &f {
2009         Foo { a: true } => (),
2010         Foo { a: false } => (),
2011     }
2012 }
2013 "#,
2014         );
2015     }
2016
2017     #[test]
2018     fn tuple_struct() {
2019         check_diagnostics(
2020             r#"struct Foo(bool);
2021 fn main(f: Foo) {
2022     match f {}
2023         //^ Missing match arm
2024     match f { Foo(true) => () }
2025         //^ Missing match arm
2026     match f {
2027         Foo(true) => (),
2028         Foo(false) => (),
2029     }
2030 }
2031 "#,
2032         );
2033     }
2034
2035     #[test]
2036     fn unit_struct() {
2037         check_diagnostics(
2038             r#"struct Foo;
2039 fn main(f: Foo) {
2040     match f {}
2041         //^ Missing match arm
2042     match f { Foo => () }
2043 }
2044 "#,
2045         );
2046     }
2047
2048     #[test]
2049     fn record_struct_ellipsis() {
2050         check_diagnostics(
2051             r#"struct Foo { foo: bool, bar: bool }
2052 fn main(f: Foo) {
2053     match f { Foo { foo: true, .. } => () }
2054         //^ Missing match arm
2055     match f {
2056         //^ Missing match arm
2057         Foo { foo: true, .. } => (),
2058         Foo { bar: false, .. } => ()
2059     }
2060     match f { Foo { .. } => () }
2061     match f {
2062         Foo { foo: true, .. } => (),
2063         Foo { foo: false, .. } => ()
2064     }
2065 }
2066 "#,
2067         );
2068     }
2069
2070     #[test]
2071     fn internal_or() {
2072         check_diagnostics(
2073             r#"
2074 fn main() {
2075     enum Either { A(bool), B }
2076     match Either::B {
2077         //^^^^^^^^^ Missing match arm
2078         Either::A(true | false) => (),
2079     }
2080 }
2081 "#,
2082         );
2083     }
2084
2085     #[test]
2086     fn no_panic_at_unimplemented_subpattern_type() {
2087         check_diagnostics(
2088             r#"
2089 struct S { a: char}
2090 fn main(v: S) {
2091     match v { S{ a }      => {} }
2092     match v { S{ a: _x }  => {} }
2093     match v { S{ a: 'a' } => {} }
2094             //^^^^^^^^^^^ Internal: match check bailed out
2095     match v { S{..}       => {} }
2096     match v { _           => {} }
2097     match v { }
2098         //^ Missing match arm
2099 }
2100 "#,
2101         );
2102     }
2103
2104     #[test]
2105     fn binding() {
2106         check_diagnostics(
2107             r#"
2108 fn main() {
2109     match true {
2110         _x @ true => {}
2111         false     => {}
2112     }
2113     match true { _x @ true => {} }
2114         //^^^^ Missing match arm
2115 }
2116 "#,
2117         );
2118     }
2119
2120     #[test]
2121     fn binding_ref_has_correct_type() {
2122         // Asserts `PatKind::Binding(ref _x): bool`, not &bool.
2123         // If that's not true match checking will panic with "incompatible constructors"
2124         // FIXME: make facilities to test this directly like `tests::check_infer(..)`
2125         check_diagnostics(
2126             r#"
2127 enum Foo { A }
2128 fn main() {
2129     // FIXME: this should not bail out but current behavior is such as the old algorithm.
2130     // ExprValidator::validate_match(..) checks types of top level patterns incorrecly.
2131     match Foo::A {
2132         ref _x => {}
2133     //  ^^^^^^ Internal: match check bailed out
2134         Foo::A => {}
2135     }
2136     match (true,) {
2137         (ref _x,) => {}
2138         (true,) => {}
2139     }
2140 }
2141 "#,
2142         );
2143     }
2144
2145     #[test]
2146     fn enum_non_exhaustive() {
2147         check_diagnostics(
2148             r#"
2149 //- /lib.rs crate:lib
2150 #[non_exhaustive]
2151 pub enum E { A, B }
2152 fn _local() {
2153     match E::A { _ => {} }
2154     match E::A {
2155         E::A => {}
2156         E::B => {}
2157     }
2158     match E::A {
2159         E::A | E::B => {}
2160     }
2161 }
2162
2163 //- /main.rs crate:main deps:lib
2164 use lib::E;
2165 fn main() {
2166     match E::A { _ => {} }
2167     match E::A {
2168         //^^^^ Missing match arm
2169         E::A => {}
2170         E::B => {}
2171     }
2172     match E::A {
2173         //^^^^ Missing match arm
2174         E::A | E::B => {}
2175     }
2176 }
2177 "#,
2178         );
2179     }
2180
2181     #[test]
2182     fn match_guard() {
2183         check_diagnostics(
2184             r#"
2185 fn main() {
2186     match true {
2187         true if false => {}
2188         true          => {}
2189         false         => {}
2190     }
2191     match true {
2192         //^^^^ Missing match arm
2193         true if false => {}
2194         false         => {}
2195     }
2196 }
2197 "#,
2198         );
2199     }
2200
2201     #[test]
2202     fn pattern_type_is_of_substitution() {
2203         cov_mark::check!(match_check_wildcard_expanded_to_substitutions);
2204         check_diagnostics(
2205             r#"
2206 struct Foo<T>(T);
2207 struct Bar;
2208 fn main() {
2209     match Foo(Bar) {
2210         _ | Foo(Bar) => {}
2211     }
2212 }
2213 "#,
2214         );
2215     }
2216
2217     #[test]
2218     fn record_struct_no_such_field() {
2219         check_diagnostics(
2220             r#"
2221 struct Foo { }
2222 fn main(f: Foo) {
2223     match f { Foo { bar } => () }
2224     //        ^^^^^^^^^^^ Internal: match check bailed out
2225 }
2226 "#,
2227         );
2228     }
2229
2230     #[test]
2231     fn match_ergonomics_issue_9095() {
2232         check_diagnostics(
2233             r#"
2234 enum Foo<T> { A(T) }
2235 fn main() {
2236     match &Foo::A(true) {
2237         _ => {}
2238         Foo::A(_) => {}
2239     }
2240 }
2241 "#,
2242         );
2243     }
2244
2245     mod false_negatives {
2246         //! The implementation of match checking here is a work in progress. As we roll this out, we
2247         //! prefer false negatives to false positives (ideally there would be no false positives). This
2248         //! test module should document known false negatives. Eventually we will have a complete
2249         //! implementation of match checking and this module will be empty.
2250         //!
2251         //! The reasons for documenting known false negatives:
2252         //!
2253         //!   1. It acts as a backlog of work that can be done to improve the behavior of the system.
2254         //!   2. It ensures the code doesn't panic when handling these cases.
2255         use super::*;
2256
2257         #[test]
2258         fn integers() {
2259             // We don't currently check integer exhaustiveness.
2260             check_diagnostics(
2261                 r#"
2262 fn main() {
2263     match 5 {
2264         10 => (),
2265     //  ^^ Internal: match check bailed out
2266         11..20 => (),
2267     }
2268 }
2269 "#,
2270             );
2271         }
2272
2273         #[test]
2274         fn reference_patterns_at_top_level() {
2275             check_diagnostics(
2276                 r#"
2277 fn main() {
2278     match &false {
2279         &true => {}
2280     //  ^^^^^ Internal: match check bailed out
2281     }
2282 }
2283             "#,
2284             );
2285         }
2286
2287         #[test]
2288         fn reference_patterns_in_fields() {
2289             check_diagnostics(
2290                 r#"
2291 fn main() {
2292     match (&false,) {
2293         (true,) => {}
2294     //  ^^^^^^^ Internal: match check bailed out
2295     }
2296     match (&false,) {
2297         (&true,) => {}
2298     //  ^^^^^^^^ Internal: match check bailed out
2299     }
2300 }
2301             "#,
2302             );
2303         }
2304     }
2305 }
2306
2307 #[cfg(test)]
2308 mod decl_check_tests {
2309     use crate::diagnostics::tests::check_diagnostics;
2310
2311     #[test]
2312     fn incorrect_function_name() {
2313         check_diagnostics(
2314             r#"
2315 fn NonSnakeCaseName() {}
2316 // ^^^^^^^^^^^^^^^^ Function `NonSnakeCaseName` should have snake_case name, e.g. `non_snake_case_name`
2317 "#,
2318         );
2319     }
2320
2321     #[test]
2322     fn incorrect_function_params() {
2323         check_diagnostics(
2324             r#"
2325 fn foo(SomeParam: u8) {}
2326     // ^^^^^^^^^ Parameter `SomeParam` should have snake_case name, e.g. `some_param`
2327
2328 fn foo2(ok_param: &str, CAPS_PARAM: u8) {}
2329                      // ^^^^^^^^^^ Parameter `CAPS_PARAM` should have snake_case name, e.g. `caps_param`
2330 "#,
2331         );
2332     }
2333
2334     #[test]
2335     fn incorrect_variable_names() {
2336         check_diagnostics(
2337             r#"
2338 fn foo() {
2339     let SOME_VALUE = 10;
2340      // ^^^^^^^^^^ Variable `SOME_VALUE` should have snake_case name, e.g. `some_value`
2341     let AnotherValue = 20;
2342      // ^^^^^^^^^^^^ Variable `AnotherValue` should have snake_case name, e.g. `another_value`
2343 }
2344 "#,
2345         );
2346     }
2347
2348     #[test]
2349     fn incorrect_struct_names() {
2350         check_diagnostics(
2351             r#"
2352 struct non_camel_case_name {}
2353     // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName`
2354
2355 struct SCREAMING_CASE {}
2356     // ^^^^^^^^^^^^^^ Structure `SCREAMING_CASE` should have CamelCase name, e.g. `ScreamingCase`
2357 "#,
2358         );
2359     }
2360
2361     #[test]
2362     fn no_diagnostic_for_camel_cased_acronyms_in_struct_name() {
2363         check_diagnostics(
2364             r#"
2365 struct AABB {}
2366 "#,
2367         );
2368     }
2369
2370     #[test]
2371     fn incorrect_struct_field() {
2372         check_diagnostics(
2373             r#"
2374 struct SomeStruct { SomeField: u8 }
2375                  // ^^^^^^^^^ Field `SomeField` should have snake_case name, e.g. `some_field`
2376 "#,
2377         );
2378     }
2379
2380     #[test]
2381     fn incorrect_enum_names() {
2382         check_diagnostics(
2383             r#"
2384 enum some_enum { Val(u8) }
2385   // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum`
2386
2387 enum SOME_ENUM {}
2388   // ^^^^^^^^^ Enum `SOME_ENUM` should have CamelCase name, e.g. `SomeEnum`
2389 "#,
2390         );
2391     }
2392
2393     #[test]
2394     fn no_diagnostic_for_camel_cased_acronyms_in_enum_name() {
2395         check_diagnostics(
2396             r#"
2397 enum AABB {}
2398 "#,
2399         );
2400     }
2401
2402     #[test]
2403     fn incorrect_enum_variant_name() {
2404         check_diagnostics(
2405             r#"
2406 enum SomeEnum { SOME_VARIANT(u8) }
2407              // ^^^^^^^^^^^^ Variant `SOME_VARIANT` should have CamelCase name, e.g. `SomeVariant`
2408 "#,
2409         );
2410     }
2411
2412     #[test]
2413     fn incorrect_const_name() {
2414         check_diagnostics(
2415             r#"
2416 const some_weird_const: u8 = 10;
2417    // ^^^^^^^^^^^^^^^^ Constant `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2418 "#,
2419         );
2420     }
2421
2422     #[test]
2423     fn incorrect_static_name() {
2424         check_diagnostics(
2425             r#"
2426 static some_weird_const: u8 = 10;
2427     // ^^^^^^^^^^^^^^^^ Static variable `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2428 "#,
2429         );
2430     }
2431
2432     #[test]
2433     fn fn_inside_impl_struct() {
2434         check_diagnostics(
2435             r#"
2436 struct someStruct;
2437     // ^^^^^^^^^^ Structure `someStruct` should have CamelCase name, e.g. `SomeStruct`
2438
2439 impl someStruct {
2440     fn SomeFunc(&self) {
2441     // ^^^^^^^^ Function `SomeFunc` should have snake_case name, e.g. `some_func`
2442         let WHY_VAR_IS_CAPS = 10;
2443          // ^^^^^^^^^^^^^^^ Variable `WHY_VAR_IS_CAPS` should have snake_case name, e.g. `why_var_is_caps`
2444     }
2445 }
2446 "#,
2447         );
2448     }
2449
2450     #[test]
2451     fn no_diagnostic_for_enum_varinats() {
2452         check_diagnostics(
2453             r#"
2454 enum Option { Some, None }
2455
2456 fn main() {
2457     match Option::None {
2458         None => (),
2459         Some => (),
2460     }
2461 }
2462 "#,
2463         );
2464     }
2465
2466     #[test]
2467     fn non_let_bind() {
2468         check_diagnostics(
2469             r#"
2470 enum Option { Some, None }
2471
2472 fn main() {
2473     match Option::None {
2474         SOME_VAR @ None => (),
2475      // ^^^^^^^^ Variable `SOME_VAR` should have snake_case name, e.g. `some_var`
2476         Some => (),
2477     }
2478 }
2479 "#,
2480         );
2481     }
2482
2483     #[test]
2484     fn allow_attributes() {
2485         check_diagnostics(
2486             r#"
2487 #[allow(non_snake_case)]
2488 fn NonSnakeCaseName(SOME_VAR: u8) -> u8{
2489     // cov_flags generated output from elsewhere in this file
2490     extern "C" {
2491         #[no_mangle]
2492         static lower_case: u8;
2493     }
2494
2495     let OtherVar = SOME_VAR + 1;
2496     OtherVar
2497 }
2498
2499 #[allow(nonstandard_style)]
2500 mod CheckNonstandardStyle {
2501     fn HiImABadFnName() {}
2502 }
2503
2504 #[allow(bad_style)]
2505 mod CheckBadStyle {
2506     fn HiImABadFnName() {}
2507 }
2508
2509 mod F {
2510     #![allow(non_snake_case)]
2511     fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {}
2512 }
2513
2514 #[allow(non_snake_case, non_camel_case_types)]
2515 pub struct some_type {
2516     SOME_FIELD: u8,
2517     SomeField: u16,
2518 }
2519
2520 #[allow(non_upper_case_globals)]
2521 pub const some_const: u8 = 10;
2522
2523 #[allow(non_upper_case_globals)]
2524 pub static SomeStatic: u8 = 10;
2525     "#,
2526         );
2527     }
2528
2529     #[test]
2530     fn allow_attributes_crate_attr() {
2531         check_diagnostics(
2532             r#"
2533 #![allow(non_snake_case)]
2534
2535 mod F {
2536     fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {}
2537 }
2538     "#,
2539         );
2540     }
2541
2542     #[test]
2543     #[ignore]
2544     fn bug_trait_inside_fn() {
2545         // FIXME:
2546         // This is broken, and in fact, should not even be looked at by this
2547         // lint in the first place. There's weird stuff going on in the
2548         // collection phase.
2549         // It's currently being brought in by:
2550         // * validate_func on `a` recursing into modules
2551         // * then it finds the trait and then the function while iterating
2552         //   through modules
2553         // * then validate_func is called on Dirty
2554         // * ... which then proceeds to look at some unknown module taking no
2555         //   attrs from either the impl or the fn a, and then finally to the root
2556         //   module
2557         //
2558         // It should find the attribute on the trait, but it *doesn't even see
2559         // the trait* as far as I can tell.
2560
2561         check_diagnostics(
2562             r#"
2563 trait T { fn a(); }
2564 struct U {}
2565 impl T for U {
2566     fn a() {
2567         // this comes out of bitflags, mostly
2568         #[allow(non_snake_case)]
2569         trait __BitFlags {
2570             const HiImAlsoBad: u8 = 2;
2571             #[inline]
2572             fn Dirty(&self) -> bool {
2573                 false
2574             }
2575         }
2576
2577     }
2578 }
2579     "#,
2580         );
2581     }
2582
2583     #[test]
2584     #[ignore]
2585     fn bug_traits_arent_checked() {
2586         // FIXME: Traits and functions in traits aren't currently checked by
2587         // r-a, even though rustc will complain about them.
2588         check_diagnostics(
2589             r#"
2590 trait BAD_TRAIT {
2591     // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait`
2592     fn BAD_FUNCTION();
2593     // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function`
2594     fn BadFunction();
2595     // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function`
2596 }
2597     "#,
2598         );
2599     }
2600
2601     #[test]
2602     fn ignores_extern_items() {
2603         cov_mark::check!(extern_func_incorrect_case_ignored);
2604         cov_mark::check!(extern_static_incorrect_case_ignored);
2605         check_diagnostics(
2606             r#"
2607 extern {
2608     fn NonSnakeCaseName(SOME_VAR: u8) -> u8;
2609     pub static SomeStatic: u8 = 10;
2610 }
2611             "#,
2612         );
2613     }
2614
2615     #[test]
2616     fn infinite_loop_inner_items() {
2617         check_diagnostics(
2618             r#"
2619 fn qualify() {
2620     mod foo {
2621         use super::*;
2622     }
2623 }
2624             "#,
2625         )
2626     }
2627
2628     #[test] // Issue #8809.
2629     fn parenthesized_parameter() {
2630         check_diagnostics(r#"fn f((O): _) {}"#)
2631     }
2632 }