]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/diagnostics.rs
internal: move inference diagnostics to hir
[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 fixes;
8 mod field_shorthand;
9 mod unlinked_file;
10
11 use std::cell::RefCell;
12
13 use hir::{
14     db::AstDatabase,
15     diagnostics::{Diagnostic as _, DiagnosticCode, DiagnosticSinkBuilder},
16     InFile, Semantics,
17 };
18 use ide_assists::AssistResolveStrategy;
19 use ide_db::{base_db::SourceDatabase, RootDatabase};
20 use itertools::Itertools;
21 use rustc_hash::FxHashSet;
22 use syntax::{
23     ast::{self, AstNode},
24     SyntaxNode, SyntaxNodePtr, TextRange, TextSize,
25 };
26 use text_edit::TextEdit;
27 use unlinked_file::UnlinkedFile;
28
29 use crate::{Assist, AssistId, AssistKind, FileId, Label, SourceChange};
30
31 use self::fixes::DiagnosticWithFixes;
32
33 #[derive(Debug)]
34 pub struct Diagnostic {
35     // pub name: Option<String>,
36     pub message: String,
37     pub range: TextRange,
38     pub severity: Severity,
39     pub fixes: Option<Vec<Assist>>,
40     pub unused: bool,
41     pub code: Option<DiagnosticCode>,
42 }
43
44 impl Diagnostic {
45     fn error(range: TextRange, message: String) -> Self {
46         Self { message, range, severity: Severity::Error, fixes: None, unused: false, code: None }
47     }
48
49     fn hint(range: TextRange, message: String) -> Self {
50         Self {
51             message,
52             range,
53             severity: Severity::WeakWarning,
54             fixes: None,
55             unused: false,
56             code: None,
57         }
58     }
59
60     fn with_fixes(self, fixes: Option<Vec<Assist>>) -> Self {
61         Self { fixes, ..self }
62     }
63
64     fn with_unused(self, unused: bool) -> Self {
65         Self { unused, ..self }
66     }
67
68     fn with_code(self, code: Option<DiagnosticCode>) -> Self {
69         Self { code, ..self }
70     }
71 }
72
73 #[derive(Debug, Copy, Clone)]
74 pub enum Severity {
75     Error,
76     WeakWarning,
77 }
78
79 #[derive(Default, Debug, Clone)]
80 pub struct DiagnosticsConfig {
81     pub disable_experimental: bool,
82     pub disabled: FxHashSet<String>,
83 }
84
85 pub(crate) fn diagnostics(
86     db: &RootDatabase,
87     config: &DiagnosticsConfig,
88     resolve: &AssistResolveStrategy,
89     file_id: FileId,
90 ) -> Vec<Diagnostic> {
91     let _p = profile::span("diagnostics");
92     let sema = Semantics::new(db);
93     let parse = db.parse(file_id);
94     let mut res = Vec::new();
95
96     // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
97     res.extend(
98         parse
99             .errors()
100             .iter()
101             .take(128)
102             .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
103     );
104
105     for node in parse.tree().syntax().descendants() {
106         check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
107         field_shorthand::check(&mut res, file_id, &node);
108     }
109     let res = RefCell::new(res);
110     let sink_builder = DiagnosticSinkBuilder::new()
111         .on::<hir::diagnostics::UnresolvedModule, _>(|d| {
112             res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
113         })
114         .on::<hir::diagnostics::MissingFields, _>(|d| {
115             res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
116         })
117         .on::<hir::diagnostics::MissingOkOrSomeInTailExpr, _>(|d| {
118             res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
119         })
120         .on::<hir::diagnostics::NoSuchField, _>(|d| {
121             res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
122         })
123         .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| {
124             res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
125         })
126         .on::<hir::diagnostics::IncorrectCase, _>(|d| {
127             res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
128         })
129         .on::<hir::diagnostics::ReplaceFilterMapNextWithFindMap, _>(|d| {
130             res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
131         })
132         .on::<hir::diagnostics::InactiveCode, _>(|d| {
133             // If there's inactive code somewhere in a macro, don't propagate to the call-site.
134             if d.display_source().file_id.expansion_info(db).is_some() {
135                 return;
136             }
137
138             // Override severity and mark as unused.
139             res.borrow_mut().push(
140                 Diagnostic::hint(
141                     sema.diagnostics_display_range(d.display_source()).range,
142                     d.message(),
143                 )
144                 .with_unused(true)
145                 .with_code(Some(d.code())),
146             );
147         })
148         .on::<UnlinkedFile, _>(|d| {
149             // Limit diagnostic to the first few characters in the file. This matches how VS Code
150             // renders it with the full span, but on other editors, and is less invasive.
151             let range = sema.diagnostics_display_range(d.display_source()).range;
152             let range = range.intersect(TextRange::up_to(TextSize::of("..."))).unwrap_or(range);
153
154             // Override severity and mark as unused.
155             res.borrow_mut().push(
156                 Diagnostic::hint(range, d.message())
157                     .with_fixes(d.fixes(&sema, resolve))
158                     .with_code(Some(d.code())),
159             );
160         })
161         .on::<hir::diagnostics::UnresolvedProcMacro, _>(|d| {
162             // Use more accurate position if available.
163             let display_range = d
164                 .precise_location
165                 .unwrap_or_else(|| sema.diagnostics_display_range(d.display_source()).range);
166
167             // FIXME: it would be nice to tell the user whether proc macros are currently disabled
168             res.borrow_mut()
169                 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
170         })
171         .on::<hir::diagnostics::UnresolvedMacroCall, _>(|d| {
172             let last_path_segment = sema.db.parse_or_expand(d.file).and_then(|root| {
173                 d.node
174                     .to_node(&root)
175                     .path()
176                     .and_then(|it| it.segment())
177                     .and_then(|it| it.name_ref())
178                     .map(|it| InFile::new(d.file, SyntaxNodePtr::new(it.syntax())))
179             });
180             let diagnostics = last_path_segment.unwrap_or_else(|| d.display_source());
181             let display_range = sema.diagnostics_display_range(diagnostics).range;
182             res.borrow_mut()
183                 .push(Diagnostic::error(display_range, d.message()).with_code(Some(d.code())));
184         })
185         .on::<hir::diagnostics::UnimplementedBuiltinMacro, _>(|d| {
186             let display_range = sema.diagnostics_display_range(d.display_source()).range;
187             res.borrow_mut()
188                 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
189         })
190         // Only collect experimental diagnostics when they're enabled.
191         .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
192         .filter(|diag| !config.disabled.contains(diag.code().as_str()));
193
194     // Finalize the `DiagnosticSink` building process.
195     let mut sink = sink_builder
196         // Diagnostics not handled above get no fix and default treatment.
197         .build(|d| {
198             res.borrow_mut().push(
199                 Diagnostic::error(
200                     sema.diagnostics_display_range(d.display_source()).range,
201                     d.message(),
202                 )
203                 .with_code(Some(d.code())),
204             );
205         });
206
207     match sema.to_module_def(file_id) {
208         Some(m) => m.diagnostics(db, &mut sink),
209         None => {
210             sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(&parse.tree().syntax()) });
211         }
212     }
213
214     drop(sink);
215     res.into_inner()
216 }
217
218 fn diagnostic_with_fix<D: DiagnosticWithFixes>(
219     d: &D,
220     sema: &Semantics<RootDatabase>,
221     resolve: &AssistResolveStrategy,
222 ) -> Diagnostic {
223     Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message())
224         .with_fixes(d.fixes(&sema, resolve))
225         .with_code(Some(d.code()))
226 }
227
228 fn warning_with_fix<D: DiagnosticWithFixes>(
229     d: &D,
230     sema: &Semantics<RootDatabase>,
231     resolve: &AssistResolveStrategy,
232 ) -> Diagnostic {
233     Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message())
234         .with_fixes(d.fixes(&sema, resolve))
235         .with_code(Some(d.code()))
236 }
237
238 fn check_unnecessary_braces_in_use_statement(
239     acc: &mut Vec<Diagnostic>,
240     file_id: FileId,
241     node: &SyntaxNode,
242 ) -> Option<()> {
243     let use_tree_list = ast::UseTreeList::cast(node.clone())?;
244     if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
245         // If there is a comment inside the bracketed `use`,
246         // assume it is a commented out module path and don't show diagnostic.
247         if use_tree_list.has_inner_comment() {
248             return Some(());
249         }
250
251         let use_range = use_tree_list.syntax().text_range();
252         let edit =
253             text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
254                 .unwrap_or_else(|| {
255                     let to_replace = single_use_tree.syntax().text().to_string();
256                     let mut edit_builder = TextEdit::builder();
257                     edit_builder.delete(use_range);
258                     edit_builder.insert(use_range.start(), to_replace);
259                     edit_builder.finish()
260                 });
261
262         acc.push(
263             Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
264                 .with_fixes(Some(vec![fix(
265                     "remove_braces",
266                     "Remove unnecessary braces",
267                     SourceChange::from_text_edit(file_id, edit),
268                     use_range,
269                 )])),
270         );
271     }
272
273     Some(())
274 }
275
276 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
277     single_use_tree: &ast::UseTree,
278 ) -> Option<TextEdit> {
279     let use_tree_list_node = single_use_tree.syntax().parent()?;
280     if single_use_tree.path()?.segment()?.self_token().is_some() {
281         let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
282         let end = use_tree_list_node.text_range().end();
283         return Some(TextEdit::delete(TextRange::new(start, end)));
284     }
285     None
286 }
287
288 fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
289     let mut res = unresolved_fix(id, label, target);
290     res.source_change = Some(source_change);
291     res
292 }
293
294 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
295     assert!(!id.contains(' '));
296     Assist {
297         id: AssistId(id, AssistKind::QuickFix),
298         label: Label::new(label),
299         group: None,
300         target,
301         source_change: None,
302     }
303 }
304
305 #[cfg(test)]
306 mod tests {
307     use expect_test::Expect;
308     use hir::diagnostics::DiagnosticCode;
309     use ide_assists::AssistResolveStrategy;
310     use stdx::trim_indent;
311     use test_utils::{assert_eq_text, extract_annotations};
312
313     use crate::{fixture, DiagnosticsConfig};
314
315     /// Takes a multi-file input fixture with annotated cursor positions,
316     /// and checks that:
317     ///  * a diagnostic is produced
318     ///  * the first diagnostic fix trigger range touches the input cursor position
319     ///  * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
320     #[track_caller]
321     pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
322         check_nth_fix(0, ra_fixture_before, ra_fixture_after);
323     }
324     /// Takes a multi-file input fixture with annotated cursor positions,
325     /// and checks that:
326     ///  * a diagnostic is produced
327     ///  * every diagnostic fixes trigger range touches the input cursor position
328     ///  * that the contents of the file containing the cursor match `after` after each diagnostic fix is applied
329     pub(crate) fn check_fixes(ra_fixture_before: &str, ra_fixtures_after: Vec<&str>) {
330         for (i, ra_fixture_after) in ra_fixtures_after.iter().enumerate() {
331             check_nth_fix(i, ra_fixture_before, ra_fixture_after)
332         }
333     }
334
335     #[track_caller]
336     fn check_nth_fix(nth: usize, ra_fixture_before: &str, ra_fixture_after: &str) {
337         let after = trim_indent(ra_fixture_after);
338
339         let (analysis, file_position) = fixture::position(ra_fixture_before);
340         let diagnostic = analysis
341             .diagnostics(
342                 &DiagnosticsConfig::default(),
343                 AssistResolveStrategy::All,
344                 file_position.file_id,
345             )
346             .unwrap()
347             .pop()
348             .unwrap();
349         let fix = &diagnostic.fixes.unwrap()[nth];
350         let actual = {
351             let source_change = fix.source_change.as_ref().unwrap();
352             let file_id = *source_change.source_file_edits.keys().next().unwrap();
353             let mut actual = analysis.file_text(file_id).unwrap().to_string();
354
355             for edit in source_change.source_file_edits.values() {
356                 edit.apply(&mut actual);
357             }
358             actual
359         };
360
361         assert_eq_text!(&after, &actual);
362         assert!(
363             fix.target.contains_inclusive(file_position.offset),
364             "diagnostic fix range {:?} does not touch cursor position {:?}",
365             fix.target,
366             file_position.offset
367         );
368     }
369     /// Checks that there's a diagnostic *without* fix at `$0`.
370     fn check_no_fix(ra_fixture: &str) {
371         let (analysis, file_position) = fixture::position(ra_fixture);
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         assert!(diagnostic.fixes.is_none(), "got a fix when none was expected: {:?}", diagnostic);
382     }
383
384     /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
385     /// apply to the file containing the cursor.
386     pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
387         let (analysis, files) = fixture::files(ra_fixture);
388         let diagnostics = files
389             .into_iter()
390             .flat_map(|file_id| {
391                 analysis
392                     .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
393                     .unwrap()
394             })
395             .collect::<Vec<_>>();
396         assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
397     }
398
399     pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) {
400         let (analysis, file_id) = fixture::file(ra_fixture);
401         let diagnostics = analysis
402             .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
403             .unwrap();
404         expect.assert_debug_eq(&diagnostics)
405     }
406
407     pub(crate) fn check_diagnostics(ra_fixture: &str) {
408         let (analysis, file_id) = fixture::file(ra_fixture);
409         let diagnostics = analysis
410             .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
411             .unwrap();
412
413         let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
414         let mut actual = diagnostics
415             .into_iter()
416             .filter(|d| d.code != Some(DiagnosticCode("inactive-code")))
417             .map(|d| (d.range, d.message))
418             .collect::<Vec<_>>();
419         actual.sort_by_key(|(range, _)| range.start());
420         assert_eq!(expected, actual);
421     }
422
423     #[test]
424     fn test_unresolved_macro_range() {
425         check_diagnostics(
426             r#"
427 foo::bar!(92);
428    //^^^ unresolved macro `foo::bar!`
429 "#,
430         );
431     }
432
433     #[test]
434     fn unresolved_import_in_use_tree() {
435         // Only the relevant part of a nested `use` item should be highlighted.
436         check_diagnostics(
437             r#"
438 use does_exist::{Exists, DoesntExist};
439                        //^^^^^^^^^^^ unresolved import
440
441 use {does_not_exist::*, does_exist};
442    //^^^^^^^^^^^^^^^^^ unresolved import
443
444 use does_not_exist::{
445     a,
446   //^ unresolved import
447     b,
448   //^ unresolved import
449     c,
450   //^ unresolved import
451 };
452
453 mod does_exist {
454     pub struct Exists;
455 }
456 "#,
457         );
458     }
459
460     #[test]
461     fn range_mapping_out_of_macros() {
462         // FIXME: this is very wrong, but somewhat tricky to fix.
463         check_fix(
464             r#"
465 fn some() {}
466 fn items() {}
467 fn here() {}
468
469 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
470
471 fn main() {
472     let _x = id![Foo { a: $042 }];
473 }
474
475 pub struct Foo { pub a: i32, pub b: i32 }
476 "#,
477             r#"
478 fn some(, b: () ) {}
479 fn items() {}
480 fn here() {}
481
482 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
483
484 fn main() {
485     let _x = id![Foo { a: 42 }];
486 }
487
488 pub struct Foo { pub a: i32, pub b: i32 }
489 "#,
490         );
491     }
492
493     #[test]
494     fn test_check_unnecessary_braces_in_use_statement() {
495         check_no_diagnostics(
496             r#"
497 use a;
498 use a::{c, d::e};
499
500 mod a {
501     mod c {}
502     mod d {
503         mod e {}
504     }
505 }
506 "#,
507         );
508         check_no_diagnostics(
509             r#"
510 use a;
511 use a::{
512     c,
513     // d::e
514 };
515
516 mod a {
517     mod c {}
518     mod d {
519         mod e {}
520     }
521 }
522 "#,
523         );
524         check_fix(
525             r"
526             mod b {}
527             use {$0b};
528             ",
529             r"
530             mod b {}
531             use b;
532             ",
533         );
534         check_fix(
535             r"
536             mod b {}
537             use {b$0};
538             ",
539             r"
540             mod b {}
541             use b;
542             ",
543         );
544         check_fix(
545             r"
546             mod a { mod c {} }
547             use a::{c$0};
548             ",
549             r"
550             mod a { mod c {} }
551             use a::c;
552             ",
553         );
554         check_fix(
555             r"
556             mod a {}
557             use a::{self$0};
558             ",
559             r"
560             mod a {}
561             use a;
562             ",
563         );
564         check_fix(
565             r"
566             mod a { mod c {} mod d { mod e {} } }
567             use a::{c, d::{e$0}};
568             ",
569             r"
570             mod a { mod c {} mod d { mod e {} } }
571             use a::{c, d::e};
572             ",
573         );
574     }
575
576     #[test]
577     fn test_disabled_diagnostics() {
578         let mut config = DiagnosticsConfig::default();
579         config.disabled.insert("unresolved-module".into());
580
581         let (analysis, file_id) = fixture::file(r#"mod foo;"#);
582
583         let diagnostics =
584             analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
585         assert!(diagnostics.is_empty());
586
587         let diagnostics = analysis
588             .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
589             .unwrap();
590         assert!(!diagnostics.is_empty());
591     }
592
593     #[test]
594     fn unlinked_file_prepend_first_item() {
595         cov_mark::check!(unlinked_file_prepend_before_first_item);
596         // Only tests the first one for `pub mod` since the rest are the same
597         check_fixes(
598             r#"
599 //- /main.rs
600 fn f() {}
601 //- /foo.rs
602 $0
603 "#,
604             vec![
605                 r#"
606 mod foo;
607
608 fn f() {}
609 "#,
610                 r#"
611 pub mod foo;
612
613 fn f() {}
614 "#,
615             ],
616         );
617     }
618
619     #[test]
620     fn unlinked_file_append_mod() {
621         cov_mark::check!(unlinked_file_append_to_existing_mods);
622         check_fix(
623             r#"
624 //- /main.rs
625 //! Comment on top
626
627 mod preexisting;
628
629 mod preexisting2;
630
631 struct S;
632
633 mod preexisting_bottom;)
634 //- /foo.rs
635 $0
636 "#,
637             r#"
638 //! Comment on top
639
640 mod preexisting;
641
642 mod preexisting2;
643 mod foo;
644
645 struct S;
646
647 mod preexisting_bottom;)
648 "#,
649         );
650     }
651
652     #[test]
653     fn unlinked_file_insert_in_empty_file() {
654         cov_mark::check!(unlinked_file_empty_file);
655         check_fix(
656             r#"
657 //- /main.rs
658 //- /foo.rs
659 $0
660 "#,
661             r#"
662 mod foo;
663 "#,
664         );
665     }
666
667     #[test]
668     fn unlinked_file_old_style_modrs() {
669         check_fix(
670             r#"
671 //- /main.rs
672 mod submod;
673 //- /submod/mod.rs
674 // in mod.rs
675 //- /submod/foo.rs
676 $0
677 "#,
678             r#"
679 // in mod.rs
680 mod foo;
681 "#,
682         );
683     }
684
685     #[test]
686     fn unlinked_file_new_style_mod() {
687         check_fix(
688             r#"
689 //- /main.rs
690 mod submod;
691 //- /submod.rs
692 //- /submod/foo.rs
693 $0
694 "#,
695             r#"
696 mod foo;
697 "#,
698         );
699     }
700
701     #[test]
702     fn unlinked_file_with_cfg_off() {
703         cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
704         check_no_fix(
705             r#"
706 //- /main.rs
707 #[cfg(never)]
708 mod foo;
709
710 //- /foo.rs
711 $0
712 "#,
713         );
714     }
715
716     #[test]
717     fn unlinked_file_with_cfg_on() {
718         check_no_diagnostics(
719             r#"
720 //- /main.rs
721 #[cfg(not(never))]
722 mod foo;
723
724 //- /foo.rs
725 "#,
726         );
727     }
728
729     #[test]
730     fn break_outside_of_loop() {
731         check_diagnostics(
732             r#"
733 fn foo() { break; }
734          //^^^^^ break outside of loop
735 "#,
736         );
737     }
738
739     #[test]
740     fn no_such_field_diagnostics() {
741         check_diagnostics(
742             r#"
743 struct S { foo: i32, bar: () }
744 impl S {
745     fn new() -> S {
746         S {
747       //^ Missing structure fields:
748       //|    - bar
749             foo: 92,
750             baz: 62,
751           //^^^^^^^ no such field
752         }
753     }
754 }
755 "#,
756         );
757     }
758     #[test]
759     fn no_such_field_with_feature_flag_diagnostics() {
760         check_diagnostics(
761             r#"
762 //- /lib.rs crate:foo cfg:feature=foo
763 struct MyStruct {
764     my_val: usize,
765     #[cfg(feature = "foo")]
766     bar: bool,
767 }
768
769 impl MyStruct {
770     #[cfg(feature = "foo")]
771     pub(crate) fn new(my_val: usize, bar: bool) -> Self {
772         Self { my_val, bar }
773     }
774     #[cfg(not(feature = "foo"))]
775     pub(crate) fn new(my_val: usize, _bar: bool) -> Self {
776         Self { my_val }
777     }
778 }
779 "#,
780         );
781     }
782
783     #[test]
784     fn no_such_field_enum_with_feature_flag_diagnostics() {
785         check_diagnostics(
786             r#"
787 //- /lib.rs crate:foo cfg:feature=foo
788 enum Foo {
789     #[cfg(not(feature = "foo"))]
790     Buz,
791     #[cfg(feature = "foo")]
792     Bar,
793     Baz
794 }
795
796 fn test_fn(f: Foo) {
797     match f {
798         Foo::Bar => {},
799         Foo::Baz => {},
800     }
801 }
802 "#,
803         );
804     }
805
806     #[test]
807     fn no_such_field_with_feature_flag_diagnostics_on_struct_lit() {
808         check_diagnostics(
809             r#"
810 //- /lib.rs crate:foo cfg:feature=foo
811 struct S {
812     #[cfg(feature = "foo")]
813     foo: u32,
814     #[cfg(not(feature = "foo"))]
815     bar: u32,
816 }
817
818 impl S {
819     #[cfg(feature = "foo")]
820     fn new(foo: u32) -> Self {
821         Self { foo }
822     }
823     #[cfg(not(feature = "foo"))]
824     fn new(bar: u32) -> Self {
825         Self { bar }
826     }
827     fn new2(bar: u32) -> Self {
828         #[cfg(feature = "foo")]
829         { Self { foo: bar } }
830         #[cfg(not(feature = "foo"))]
831         { Self { bar } }
832     }
833     fn new2(val: u32) -> Self {
834         Self {
835             #[cfg(feature = "foo")]
836             foo: val,
837             #[cfg(not(feature = "foo"))]
838             bar: val,
839         }
840     }
841 }
842 "#,
843         );
844     }
845
846     #[test]
847     fn no_such_field_with_type_macro() {
848         check_diagnostics(
849             r#"
850 macro_rules! Type { () => { u32 }; }
851 struct Foo { bar: Type![] }
852
853 impl Foo {
854     fn new() -> Self {
855         Foo { bar: 0 }
856     }
857 }
858 "#,
859         );
860     }
861 }