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