]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/diagnostics.rs
More cleanups / module docs
[rust.git] / crates / hir_ty / src / diagnostics.rs
1 //! Type inference-based diagnostics.
2 mod expr;
3 mod match_check;
4 mod unsafe_check;
5 mod decl_check;
6
7 use std::{any::Any, fmt};
8
9 use base_db::CrateId;
10 use hir_def::{DefWithBodyId, ModuleDefId};
11 use hir_expand::diagnostics::{Diagnostic, DiagnosticCode, DiagnosticSink};
12 use hir_expand::{name::Name, HirFileId, InFile};
13 use stdx::format_to;
14 use syntax::{ast, AstPtr, SyntaxNodePtr};
15
16 use crate::db::HirDatabase;
17
18 pub use crate::diagnostics::expr::{record_literal_missing_fields, record_pattern_missing_fields};
19
20 pub fn validate_module_item(
21     db: &dyn HirDatabase,
22     krate: CrateId,
23     owner: ModuleDefId,
24     sink: &mut DiagnosticSink<'_>,
25 ) {
26     let _p = profile::span("validate_module_item");
27     let mut validator = decl_check::DeclValidator::new(db, krate, sink);
28     validator.validate_item(owner);
29 }
30
31 pub fn validate_body(db: &dyn HirDatabase, owner: DefWithBodyId, sink: &mut DiagnosticSink<'_>) {
32     let _p = profile::span("validate_body");
33     let infer = db.infer(owner);
34     infer.add_diagnostics(db, owner, sink);
35     let mut validator = expr::ExprValidator::new(owner, infer.clone(), sink);
36     validator.validate_body(db);
37     let mut validator = unsafe_check::UnsafeValidator::new(owner, infer, sink);
38     validator.validate_body(db);
39 }
40
41 // Diagnostic: no-such-field
42 //
43 // This diagnostic is triggered if created structure does not have field provided in record.
44 #[derive(Debug)]
45 pub struct NoSuchField {
46     pub file: HirFileId,
47     pub field: AstPtr<ast::RecordExprField>,
48 }
49
50 impl Diagnostic for NoSuchField {
51     fn code(&self) -> DiagnosticCode {
52         DiagnosticCode("no-such-field")
53     }
54
55     fn message(&self) -> String {
56         "no such field".to_string()
57     }
58
59     fn display_source(&self) -> InFile<SyntaxNodePtr> {
60         InFile::new(self.file, self.field.clone().into())
61     }
62
63     fn as_any(&self) -> &(dyn Any + Send + 'static) {
64         self
65     }
66 }
67
68 // Diagnostic: missing-structure-fields
69 //
70 // This diagnostic is triggered if record lacks some fields that exist in the corresponding structure.
71 //
72 // Example:
73 //
74 // ```rust
75 // struct A { a: u8, b: u8 }
76 //
77 // let a = A { a: 10 };
78 // ```
79 #[derive(Debug)]
80 pub struct MissingFields {
81     pub file: HirFileId,
82     pub field_list_parent: AstPtr<ast::RecordExpr>,
83     pub field_list_parent_path: Option<AstPtr<ast::Path>>,
84     pub missed_fields: Vec<Name>,
85 }
86
87 impl Diagnostic for MissingFields {
88     fn code(&self) -> DiagnosticCode {
89         DiagnosticCode("missing-structure-fields")
90     }
91     fn message(&self) -> String {
92         let mut buf = String::from("Missing structure fields:\n");
93         for field in &self.missed_fields {
94             format_to!(buf, "- {}\n", field);
95         }
96         buf
97     }
98
99     fn display_source(&self) -> InFile<SyntaxNodePtr> {
100         InFile {
101             file_id: self.file,
102             value: self
103                 .field_list_parent_path
104                 .clone()
105                 .map(SyntaxNodePtr::from)
106                 .unwrap_or_else(|| self.field_list_parent.clone().into()),
107         }
108     }
109
110     fn as_any(&self) -> &(dyn Any + Send + 'static) {
111         self
112     }
113 }
114
115 // Diagnostic: missing-pat-fields
116 //
117 // This diagnostic is triggered if pattern lacks some fields that exist in the corresponding structure.
118 //
119 // Example:
120 //
121 // ```rust
122 // struct A { a: u8, b: u8 }
123 //
124 // let a = A { a: 10, b: 20 };
125 //
126 // if let A { a } = a {
127 //     // ...
128 // }
129 // ```
130 #[derive(Debug)]
131 pub struct MissingPatFields {
132     pub file: HirFileId,
133     pub field_list_parent: AstPtr<ast::RecordPat>,
134     pub field_list_parent_path: Option<AstPtr<ast::Path>>,
135     pub missed_fields: Vec<Name>,
136 }
137
138 impl Diagnostic for MissingPatFields {
139     fn code(&self) -> DiagnosticCode {
140         DiagnosticCode("missing-pat-fields")
141     }
142     fn message(&self) -> String {
143         let mut buf = String::from("Missing structure fields:\n");
144         for field in &self.missed_fields {
145             format_to!(buf, "- {}\n", field);
146         }
147         buf
148     }
149     fn display_source(&self) -> InFile<SyntaxNodePtr> {
150         InFile {
151             file_id: self.file,
152             value: self
153                 .field_list_parent_path
154                 .clone()
155                 .map(SyntaxNodePtr::from)
156                 .unwrap_or_else(|| self.field_list_parent.clone().into()),
157         }
158     }
159     fn as_any(&self) -> &(dyn Any + Send + 'static) {
160         self
161     }
162 }
163
164 // Diagnostic: missing-match-arm
165 //
166 // This diagnostic is triggered if `match` block is missing one or more match arms.
167 #[derive(Debug)]
168 pub struct MissingMatchArms {
169     pub file: HirFileId,
170     pub match_expr: AstPtr<ast::Expr>,
171     pub arms: AstPtr<ast::MatchArmList>,
172 }
173
174 impl Diagnostic for MissingMatchArms {
175     fn code(&self) -> DiagnosticCode {
176         DiagnosticCode("missing-match-arm")
177     }
178     fn message(&self) -> String {
179         String::from("Missing match arm")
180     }
181     fn display_source(&self) -> InFile<SyntaxNodePtr> {
182         InFile { file_id: self.file, value: self.match_expr.clone().into() }
183     }
184     fn as_any(&self) -> &(dyn Any + Send + 'static) {
185         self
186     }
187 }
188
189 // Diagnostic: missing-ok-or-some-in-tail-expr
190 //
191 // This diagnostic is triggered if a block that should return `Result` returns a value not wrapped in `Ok`,
192 // or if a block that should return `Option` returns a value not wrapped in `Some`.
193 //
194 // Example:
195 //
196 // ```rust
197 // fn foo() -> Result<u8, ()> {
198 //     10
199 // }
200 // ```
201 #[derive(Debug)]
202 pub struct MissingOkOrSomeInTailExpr {
203     pub file: HirFileId,
204     pub expr: AstPtr<ast::Expr>,
205     // `Some` or `Ok` depending on whether the return type is Result or Option
206     pub required: String,
207 }
208
209 impl Diagnostic for MissingOkOrSomeInTailExpr {
210     fn code(&self) -> DiagnosticCode {
211         DiagnosticCode("missing-ok-or-some-in-tail-expr")
212     }
213     fn message(&self) -> String {
214         format!("wrap return expression in {}", self.required)
215     }
216     fn display_source(&self) -> InFile<SyntaxNodePtr> {
217         InFile { file_id: self.file, value: self.expr.clone().into() }
218     }
219     fn as_any(&self) -> &(dyn Any + Send + 'static) {
220         self
221     }
222 }
223
224 #[derive(Debug)]
225 pub struct RemoveThisSemicolon {
226     pub file: HirFileId,
227     pub expr: AstPtr<ast::Expr>,
228 }
229
230 impl Diagnostic for RemoveThisSemicolon {
231     fn code(&self) -> DiagnosticCode {
232         DiagnosticCode("remove-this-semicolon")
233     }
234
235     fn message(&self) -> String {
236         "Remove this semicolon".to_string()
237     }
238
239     fn display_source(&self) -> InFile<SyntaxNodePtr> {
240         InFile { file_id: self.file, value: self.expr.clone().into() }
241     }
242
243     fn as_any(&self) -> &(dyn Any + Send + 'static) {
244         self
245     }
246 }
247
248 // Diagnostic: break-outside-of-loop
249 //
250 // This diagnostic is triggered if the `break` keyword is used outside of a loop.
251 #[derive(Debug)]
252 pub struct BreakOutsideOfLoop {
253     pub file: HirFileId,
254     pub expr: AstPtr<ast::Expr>,
255 }
256
257 impl Diagnostic for BreakOutsideOfLoop {
258     fn code(&self) -> DiagnosticCode {
259         DiagnosticCode("break-outside-of-loop")
260     }
261     fn message(&self) -> String {
262         "break outside of loop".to_string()
263     }
264     fn display_source(&self) -> InFile<SyntaxNodePtr> {
265         InFile { file_id: self.file, value: self.expr.clone().into() }
266     }
267     fn as_any(&self) -> &(dyn Any + Send + 'static) {
268         self
269     }
270 }
271
272 // Diagnostic: missing-unsafe
273 //
274 // This diagnostic is triggered if an operation marked as `unsafe` is used outside of an `unsafe` function or block.
275 #[derive(Debug)]
276 pub struct MissingUnsafe {
277     pub file: HirFileId,
278     pub expr: AstPtr<ast::Expr>,
279 }
280
281 impl Diagnostic for MissingUnsafe {
282     fn code(&self) -> DiagnosticCode {
283         DiagnosticCode("missing-unsafe")
284     }
285     fn message(&self) -> String {
286         format!("This operation is unsafe and requires an unsafe function or block")
287     }
288     fn display_source(&self) -> InFile<SyntaxNodePtr> {
289         InFile { file_id: self.file, value: self.expr.clone().into() }
290     }
291     fn as_any(&self) -> &(dyn Any + Send + 'static) {
292         self
293     }
294 }
295
296 // Diagnostic: mismatched-arg-count
297 //
298 // This diagnostic is triggered if a function is invoked with an incorrect amount of arguments.
299 #[derive(Debug)]
300 pub struct MismatchedArgCount {
301     pub file: HirFileId,
302     pub call_expr: AstPtr<ast::Expr>,
303     pub expected: usize,
304     pub found: usize,
305 }
306
307 impl Diagnostic for MismatchedArgCount {
308     fn code(&self) -> DiagnosticCode {
309         DiagnosticCode("mismatched-arg-count")
310     }
311     fn message(&self) -> String {
312         let s = if self.expected == 1 { "" } else { "s" };
313         format!("Expected {} argument{}, found {}", self.expected, s, self.found)
314     }
315     fn display_source(&self) -> InFile<SyntaxNodePtr> {
316         InFile { file_id: self.file, value: self.call_expr.clone().into() }
317     }
318     fn as_any(&self) -> &(dyn Any + Send + 'static) {
319         self
320     }
321     fn is_experimental(&self) -> bool {
322         true
323     }
324 }
325
326 #[derive(Debug)]
327 pub enum CaseType {
328     // `some_var`
329     LowerSnakeCase,
330     // `SOME_CONST`
331     UpperSnakeCase,
332     // `SomeStruct`
333     UpperCamelCase,
334 }
335
336 impl fmt::Display for CaseType {
337     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338         let repr = match self {
339             CaseType::LowerSnakeCase => "snake_case",
340             CaseType::UpperSnakeCase => "UPPER_SNAKE_CASE",
341             CaseType::UpperCamelCase => "CamelCase",
342         };
343
344         write!(f, "{}", repr)
345     }
346 }
347
348 #[derive(Debug)]
349 pub enum IdentType {
350     Argument,
351     Constant,
352     Enum,
353     Field,
354     Function,
355     StaticVariable,
356     Structure,
357     Variable,
358     Variant,
359 }
360
361 impl fmt::Display for IdentType {
362     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
363         let repr = match self {
364             IdentType::Argument => "Argument",
365             IdentType::Constant => "Constant",
366             IdentType::Enum => "Enum",
367             IdentType::Field => "Field",
368             IdentType::Function => "Function",
369             IdentType::StaticVariable => "Static variable",
370             IdentType::Structure => "Structure",
371             IdentType::Variable => "Variable",
372             IdentType::Variant => "Variant",
373         };
374
375         write!(f, "{}", repr)
376     }
377 }
378
379 // Diagnostic: incorrect-ident-case
380 //
381 // This diagnostic is triggered if an item name doesn't follow https://doc.rust-lang.org/1.0.0/style/style/naming/README.html[Rust naming convention].
382 #[derive(Debug)]
383 pub struct IncorrectCase {
384     pub file: HirFileId,
385     pub ident: AstPtr<ast::Name>,
386     pub expected_case: CaseType,
387     pub ident_type: IdentType,
388     pub ident_text: String,
389     pub suggested_text: String,
390 }
391
392 impl Diagnostic for IncorrectCase {
393     fn code(&self) -> DiagnosticCode {
394         DiagnosticCode("incorrect-ident-case")
395     }
396
397     fn message(&self) -> String {
398         format!(
399             "{} `{}` should have {} name, e.g. `{}`",
400             self.ident_type,
401             self.ident_text,
402             self.expected_case.to_string(),
403             self.suggested_text
404         )
405     }
406
407     fn display_source(&self) -> InFile<SyntaxNodePtr> {
408         InFile::new(self.file, self.ident.clone().into())
409     }
410
411     fn as_any(&self) -> &(dyn Any + Send + 'static) {
412         self
413     }
414
415     fn is_experimental(&self) -> bool {
416         true
417     }
418 }
419
420 // Diagnostic: replace-filter-map-next-with-find-map
421 //
422 // This diagnostic is triggered when `.filter_map(..).next()` is used, rather than the more concise `.find_map(..)`.
423 #[derive(Debug)]
424 pub struct ReplaceFilterMapNextWithFindMap {
425     pub file: HirFileId,
426     /// This expression is the whole method chain up to and including `.filter_map(..).next()`.
427     pub next_expr: AstPtr<ast::Expr>,
428 }
429
430 impl Diagnostic for ReplaceFilterMapNextWithFindMap {
431     fn code(&self) -> DiagnosticCode {
432         DiagnosticCode("replace-filter-map-next-with-find-map")
433     }
434     fn message(&self) -> String {
435         "replace filter_map(..).next() with find_map(..)".to_string()
436     }
437     fn display_source(&self) -> InFile<SyntaxNodePtr> {
438         InFile { file_id: self.file, value: self.next_expr.clone().into() }
439     }
440     fn as_any(&self) -> &(dyn Any + Send + 'static) {
441         self
442     }
443 }
444
445 #[cfg(test)]
446 mod tests {
447     use base_db::{fixture::WithFixture, FileId, SourceDatabase, SourceDatabaseExt};
448     use hir_def::{db::DefDatabase, AssocItemId, ModuleDefId};
449     use hir_expand::{
450         db::AstDatabase,
451         diagnostics::{Diagnostic, DiagnosticSinkBuilder},
452     };
453     use rustc_hash::FxHashMap;
454     use syntax::{TextRange, TextSize};
455
456     use crate::{
457         diagnostics::{validate_body, validate_module_item},
458         test_db::TestDB,
459     };
460
461     impl TestDB {
462         fn diagnostics<F: FnMut(&dyn Diagnostic)>(&self, mut cb: F) {
463             let crate_graph = self.crate_graph();
464             for krate in crate_graph.iter() {
465                 let crate_def_map = self.crate_def_map(krate);
466
467                 let mut fns = Vec::new();
468                 for (module_id, _) in crate_def_map.modules() {
469                     for decl in crate_def_map[module_id].scope.declarations() {
470                         let mut sink = DiagnosticSinkBuilder::new().build(&mut cb);
471                         validate_module_item(self, krate, decl, &mut sink);
472
473                         if let ModuleDefId::FunctionId(f) = decl {
474                             fns.push(f)
475                         }
476                     }
477
478                     for impl_id in crate_def_map[module_id].scope.impls() {
479                         let impl_data = self.impl_data(impl_id);
480                         for item in impl_data.items.iter() {
481                             if let AssocItemId::FunctionId(f) = item {
482                                 let mut sink = DiagnosticSinkBuilder::new().build(&mut cb);
483                                 validate_module_item(
484                                     self,
485                                     krate,
486                                     ModuleDefId::FunctionId(*f),
487                                     &mut sink,
488                                 );
489                                 fns.push(*f)
490                             }
491                         }
492                     }
493                 }
494
495                 for f in fns {
496                     let mut sink = DiagnosticSinkBuilder::new().build(&mut cb);
497                     validate_body(self, f.into(), &mut sink);
498                 }
499             }
500         }
501     }
502
503     pub(crate) fn check_diagnostics(ra_fixture: &str) {
504         let db = TestDB::with_files(ra_fixture);
505         let annotations = db.extract_annotations();
506
507         let mut actual: FxHashMap<FileId, Vec<(TextRange, String)>> = FxHashMap::default();
508         db.diagnostics(|d| {
509             let src = d.display_source();
510             let root = db.parse_or_expand(src.file_id).unwrap();
511             // FIXME: macros...
512             let file_id = src.file_id.original_file(&db);
513             let range = src.value.to_node(&root).text_range();
514             let message = d.message();
515             actual.entry(file_id).or_default().push((range, message));
516         });
517
518         for (file_id, diags) in actual.iter_mut() {
519             diags.sort_by_key(|it| it.0.start());
520             let text = db.file_text(*file_id);
521             // For multiline spans, place them on line start
522             for (range, content) in diags {
523                 if text[*range].contains('\n') {
524                     *range = TextRange::new(range.start(), range.start() + TextSize::from(1));
525                     *content = format!("... {}", content);
526                 }
527             }
528         }
529
530         assert_eq!(annotations, actual);
531     }
532
533     #[test]
534     fn no_such_field_diagnostics() {
535         check_diagnostics(
536             r#"
537 struct S { foo: i32, bar: () }
538 impl S {
539     fn new() -> S {
540         S {
541       //^ Missing structure fields:
542       //|    - bar
543             foo: 92,
544             baz: 62,
545           //^^^^^^^ no such field
546         }
547     }
548 }
549 "#,
550         );
551     }
552     #[test]
553     fn no_such_field_with_feature_flag_diagnostics() {
554         check_diagnostics(
555             r#"
556 //- /lib.rs crate:foo cfg:feature=foo
557 struct MyStruct {
558     my_val: usize,
559     #[cfg(feature = "foo")]
560     bar: bool,
561 }
562
563 impl MyStruct {
564     #[cfg(feature = "foo")]
565     pub(crate) fn new(my_val: usize, bar: bool) -> Self {
566         Self { my_val, bar }
567     }
568     #[cfg(not(feature = "foo"))]
569     pub(crate) fn new(my_val: usize, _bar: bool) -> Self {
570         Self { my_val }
571     }
572 }
573 "#,
574         );
575     }
576
577     #[test]
578     fn no_such_field_enum_with_feature_flag_diagnostics() {
579         check_diagnostics(
580             r#"
581 //- /lib.rs crate:foo cfg:feature=foo
582 enum Foo {
583     #[cfg(not(feature = "foo"))]
584     Buz,
585     #[cfg(feature = "foo")]
586     Bar,
587     Baz
588 }
589
590 fn test_fn(f: Foo) {
591     match f {
592         Foo::Bar => {},
593         Foo::Baz => {},
594     }
595 }
596 "#,
597         );
598     }
599
600     #[test]
601     fn no_such_field_with_feature_flag_diagnostics_on_struct_lit() {
602         check_diagnostics(
603             r#"
604 //- /lib.rs crate:foo cfg:feature=foo
605 struct S {
606     #[cfg(feature = "foo")]
607     foo: u32,
608     #[cfg(not(feature = "foo"))]
609     bar: u32,
610 }
611
612 impl S {
613     #[cfg(feature = "foo")]
614     fn new(foo: u32) -> Self {
615         Self { foo }
616     }
617     #[cfg(not(feature = "foo"))]
618     fn new(bar: u32) -> Self {
619         Self { bar }
620     }
621     fn new2(bar: u32) -> Self {
622         #[cfg(feature = "foo")]
623         { Self { foo: bar } }
624         #[cfg(not(feature = "foo"))]
625         { Self { bar } }
626     }
627     fn new2(val: u32) -> Self {
628         Self {
629             #[cfg(feature = "foo")]
630             foo: val,
631             #[cfg(not(feature = "foo"))]
632             bar: val,
633         }
634     }
635 }
636 "#,
637         );
638     }
639
640     #[test]
641     fn no_such_field_with_type_macro() {
642         check_diagnostics(
643             r#"
644 macro_rules! Type { () => { u32 }; }
645 struct Foo { bar: Type![] }
646
647 impl Foo {
648     fn new() -> Self {
649         Foo { bar: 0 }
650     }
651 }
652 "#,
653         );
654     }
655
656     #[test]
657     fn missing_record_pat_field_diagnostic() {
658         check_diagnostics(
659             r#"
660 struct S { foo: i32, bar: () }
661 fn baz(s: S) {
662     let S { foo: _ } = s;
663       //^ Missing structure fields:
664       //| - bar
665 }
666 "#,
667         );
668     }
669
670     #[test]
671     fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
672         check_diagnostics(
673             r"
674 struct S { foo: i32, bar: () }
675 fn baz(s: S) -> i32 {
676     match s {
677         S { foo, .. } => foo,
678     }
679 }
680 ",
681         )
682     }
683
684     #[test]
685     fn missing_record_pat_field_box() {
686         check_diagnostics(
687             r"
688 struct S { s: Box<u32> }
689 fn x(a: S) {
690     let S { box s } = a;
691 }
692 ",
693         )
694     }
695
696     #[test]
697     fn missing_record_pat_field_ref() {
698         check_diagnostics(
699             r"
700 struct S { s: u32 }
701 fn x(a: S) {
702     let S { ref s } = a;
703 }
704 ",
705         )
706     }
707
708     #[test]
709     fn import_extern_crate_clash_with_inner_item() {
710         // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
711
712         check_diagnostics(
713             r#"
714 //- /lib.rs crate:lib deps:jwt
715 mod permissions;
716
717 use permissions::jwt;
718
719 fn f() {
720     fn inner() {}
721     jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
722 }
723
724 //- /permissions.rs
725 pub mod jwt  {
726     pub struct Claims {}
727 }
728
729 //- /jwt/lib.rs crate:jwt
730 pub struct Claims {
731     field: u8,
732 }
733         "#,
734         );
735     }
736
737     #[test]
738     fn break_outside_of_loop() {
739         check_diagnostics(
740             r#"
741 fn foo() { break; }
742          //^^^^^ break outside of loop
743 "#,
744         );
745     }
746
747     #[test]
748     fn missing_semicolon() {
749         check_diagnostics(
750             r#"
751                 fn test() -> i32 { 123; }
752                                  //^^^ Remove this semicolon
753             "#,
754         );
755     }
756
757     // Register the required standard library types to make the tests work
758     fn add_filter_map_with_find_next_boilerplate(body: &str) -> String {
759         let prefix = r#"
760         //- /main.rs crate:main deps:core
761         use core::iter::Iterator;
762         use core::option::Option::{self, Some, None};
763         "#;
764         let suffix = r#"
765         //- /core/lib.rs crate:core
766         pub mod option {
767             pub enum Option<T> { Some(T), None }
768         }
769         pub mod iter {
770             pub trait Iterator {
771                 type Item;
772                 fn filter_map<B, F>(self, f: F) -> FilterMap where F: FnMut(Self::Item) -> Option<B> { FilterMap }
773                 fn next(&mut self) -> Option<Self::Item>;
774             }
775             pub struct FilterMap {}
776             impl Iterator for FilterMap {
777                 type Item = i32;
778                 fn next(&mut self) -> i32 { 7 }
779             }
780         }
781         "#;
782         format!("{}{}{}", prefix, body, suffix)
783     }
784
785     #[test]
786     fn replace_filter_map_next_with_find_map2() {
787         check_diagnostics(&add_filter_map_with_find_next_boilerplate(
788             r#"
789             fn foo() {
790                 let m = [1, 2, 3].iter().filter_map(|x| if *x == 2 { Some (4) } else { None }).next();
791                       //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ replace filter_map(..).next() with find_map(..)
792             }
793         "#,
794         ));
795     }
796
797     #[test]
798     fn replace_filter_map_next_with_find_map_no_diagnostic_without_next() {
799         check_diagnostics(&add_filter_map_with_find_next_boilerplate(
800             r#"
801             fn foo() {
802                 let m = [1, 2, 3]
803                     .iter()
804                     .filter_map(|x| if *x == 2 { Some (4) } else { None })
805                     .len();
806             }
807             "#,
808         ));
809     }
810
811     #[test]
812     fn replace_filter_map_next_with_find_map_no_diagnostic_with_intervening_methods() {
813         check_diagnostics(&add_filter_map_with_find_next_boilerplate(
814             r#"
815             fn foo() {
816                 let m = [1, 2, 3]
817                     .iter()
818                     .filter_map(|x| if *x == 2 { Some (4) } else { None })
819                     .map(|x| x + 2)
820                     .len();
821             }
822             "#,
823         ));
824     }
825
826     #[test]
827     fn replace_filter_map_next_with_find_map_no_diagnostic_if_not_in_chain() {
828         check_diagnostics(&add_filter_map_with_find_next_boilerplate(
829             r#"
830             fn foo() {
831                 let m = [1, 2, 3]
832                     .iter()
833                     .filter_map(|x| if *x == 2 { Some (4) } else { None });
834                 let n = m.next();
835             }
836             "#,
837         ));
838     }
839 }