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