1 //! Collects diagnostics & fixits for a single file.
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.
8 mod unresolved_extern_crate;
16 use std::cell::RefCell;
20 diagnostics::{AnyDiagnostic, Diagnostic as _, DiagnosticCode, DiagnosticSinkBuilder},
23 use ide_assists::AssistResolveStrategy;
24 use ide_db::{base_db::SourceDatabase, RootDatabase};
25 use itertools::Itertools;
26 use rustc_hash::FxHashSet;
29 SyntaxNode, SyntaxNodePtr, TextRange, TextSize,
31 use text_edit::TextEdit;
32 use unlinked_file::UnlinkedFile;
34 use crate::{Assist, AssistId, AssistKind, FileId, Label, SourceChange};
36 use self::fixes::DiagnosticWithFixes;
39 pub struct Diagnostic {
40 // pub name: Option<String>,
43 pub severity: Severity,
44 pub fixes: Option<Vec<Assist>>,
46 pub code: Option<DiagnosticCode>,
47 pub experimental: bool,
51 fn new(code: &'static str, message: impl Into<String>, range: TextRange) -> Diagnostic {
52 let message = message.into();
53 let code = Some(DiagnosticCode(code));
57 severity: Severity::Error,
65 fn experimental(mut self) -> Diagnostic {
66 self.experimental = true;
70 fn error(range: TextRange, message: String) -> Self {
74 severity: Severity::Error,
82 fn hint(range: TextRange, message: String) -> Self {
86 severity: Severity::WeakWarning,
94 fn with_fixes(self, fixes: Option<Vec<Assist>>) -> Self {
95 Self { fixes, ..self }
98 fn with_unused(self, unused: bool) -> Self {
99 Self { unused, ..self }
102 fn with_code(self, code: Option<DiagnosticCode>) -> Self {
103 Self { code, ..self }
107 #[derive(Debug, Copy, Clone)]
113 #[derive(Default, Debug, Clone)]
114 pub struct DiagnosticsConfig {
115 pub disable_experimental: bool,
116 pub disabled: FxHashSet<String>,
119 struct DiagnosticsContext<'a> {
120 config: &'a DiagnosticsConfig,
121 sema: Semantics<'a, RootDatabase>,
123 resolve: &'a AssistResolveStrategy,
126 pub(crate) fn diagnostics(
128 config: &DiagnosticsConfig,
129 resolve: &AssistResolveStrategy,
131 ) -> Vec<Diagnostic> {
132 let _p = profile::span("diagnostics");
133 let sema = Semantics::new(db);
134 let parse = db.parse(file_id);
135 let mut res = Vec::new();
137 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
143 .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
146 for node in parse.tree().syntax().descendants() {
147 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
148 field_shorthand::check(&mut res, file_id, &node);
150 let res = RefCell::new(res);
151 let sink_builder = DiagnosticSinkBuilder::new()
152 .on::<hir::diagnostics::MissingOkOrSomeInTailExpr, _>(|d| {
153 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
155 .on::<hir::diagnostics::NoSuchField, _>(|d| {
156 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
158 .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| {
159 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
161 .on::<hir::diagnostics::IncorrectCase, _>(|d| {
162 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
164 .on::<hir::diagnostics::ReplaceFilterMapNextWithFindMap, _>(|d| {
165 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
167 .on::<hir::diagnostics::InactiveCode, _>(|d| {
168 // If there's inactive code somewhere in a macro, don't propagate to the call-site.
169 if d.display_source().file_id.expansion_info(db).is_some() {
173 // Override severity and mark as unused.
174 res.borrow_mut().push(
176 sema.diagnostics_display_range(d.display_source()).range,
180 .with_code(Some(d.code())),
183 .on::<UnlinkedFile, _>(|d| {
184 // Limit diagnostic to the first few characters in the file. This matches how VS Code
185 // renders it with the full span, but on other editors, and is less invasive.
186 let range = sema.diagnostics_display_range(d.display_source()).range;
187 let range = range.intersect(TextRange::up_to(TextSize::of("..."))).unwrap_or(range);
189 // Override severity and mark as unused.
190 res.borrow_mut().push(
191 Diagnostic::hint(range, d.message())
192 .with_fixes(d.fixes(&sema, resolve))
193 .with_code(Some(d.code())),
196 .on::<hir::diagnostics::UnresolvedProcMacro, _>(|d| {
197 // Use more accurate position if available.
198 let display_range = d
200 .unwrap_or_else(|| sema.diagnostics_display_range(d.display_source()).range);
202 // FIXME: it would be nice to tell the user whether proc macros are currently disabled
204 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
206 .on::<hir::diagnostics::UnresolvedMacroCall, _>(|d| {
207 let last_path_segment = sema.db.parse_or_expand(d.file).and_then(|root| {
211 .and_then(|it| it.segment())
212 .and_then(|it| it.name_ref())
213 .map(|it| InFile::new(d.file, SyntaxNodePtr::new(it.syntax())))
215 let diagnostics = last_path_segment.unwrap_or_else(|| d.display_source());
216 let display_range = sema.diagnostics_display_range(diagnostics).range;
218 .push(Diagnostic::error(display_range, d.message()).with_code(Some(d.code())));
220 .on::<hir::diagnostics::UnimplementedBuiltinMacro, _>(|d| {
221 let display_range = sema.diagnostics_display_range(d.display_source()).range;
223 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
225 // Only collect experimental diagnostics when they're enabled.
226 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
227 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
229 // Finalize the `DiagnosticSink` building process.
230 let mut sink = sink_builder
231 // Diagnostics not handled above get no fix and default treatment.
233 res.borrow_mut().push(
235 sema.diagnostics_display_range(d.display_source()).range,
238 .with_code(Some(d.code())),
242 let mut diags = Vec::new();
243 let internal_diagnostics = cfg!(test);
244 match sema.to_module_def(file_id) {
245 Some(m) => diags = m.diagnostics(db, &mut sink, internal_diagnostics),
247 sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(parse.tree().syntax()) });
253 let mut res = res.into_inner();
255 let ctx = DiagnosticsContext { config, sema, resolve };
259 AnyDiagnostic::UnresolvedModule(d) => unresolved_module::unresolved_module(&ctx, &d),
260 AnyDiagnostic::UnresolvedExternCrate(d) => unresolved_extern_crate::unresolved_extern_crate(&ctx, &d),
261 AnyDiagnostic::UnresolvedImport(d) => unresolved_import::unresolved_import(&ctx, &d),
262 AnyDiagnostic::MissingFields(d) => missing_fields::missing_fields(&ctx, &d),
264 if let Some(code) = d.code {
265 if ctx.config.disabled.contains(code.as_str()) {
269 if ctx.config.disable_experimental && d.experimental {
278 fn diagnostic_with_fix<D: DiagnosticWithFixes>(
280 sema: &Semantics<RootDatabase>,
281 resolve: &AssistResolveStrategy,
283 Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message())
284 .with_fixes(d.fixes(sema, resolve))
285 .with_code(Some(d.code()))
288 fn warning_with_fix<D: DiagnosticWithFixes>(
290 sema: &Semantics<RootDatabase>,
291 resolve: &AssistResolveStrategy,
293 Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message())
294 .with_fixes(d.fixes(sema, resolve))
295 .with_code(Some(d.code()))
298 fn check_unnecessary_braces_in_use_statement(
299 acc: &mut Vec<Diagnostic>,
303 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
304 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
305 // If there is a comment inside the bracketed `use`,
306 // assume it is a commented out module path and don't show diagnostic.
307 if use_tree_list.has_inner_comment() {
311 let use_range = use_tree_list.syntax().text_range();
313 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
315 let to_replace = single_use_tree.syntax().text().to_string();
316 let mut edit_builder = TextEdit::builder();
317 edit_builder.delete(use_range);
318 edit_builder.insert(use_range.start(), to_replace);
319 edit_builder.finish()
323 Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
324 .with_fixes(Some(vec![fix(
326 "Remove unnecessary braces",
327 SourceChange::from_text_edit(file_id, edit),
336 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
337 single_use_tree: &ast::UseTree,
338 ) -> Option<TextEdit> {
339 let use_tree_list_node = single_use_tree.syntax().parent()?;
340 if single_use_tree.path()?.segment()?.self_token().is_some() {
341 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
342 let end = use_tree_list_node.text_range().end();
343 return Some(TextEdit::delete(TextRange::new(start, end)));
348 fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
349 let mut res = unresolved_fix(id, label, target);
350 res.source_change = Some(source_change);
354 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
355 assert!(!id.contains(' '));
357 id: AssistId(id, AssistKind::QuickFix),
358 label: Label::new(label),
367 use expect_test::Expect;
368 use hir::diagnostics::DiagnosticCode;
369 use ide_assists::AssistResolveStrategy;
370 use stdx::trim_indent;
371 use test_utils::{assert_eq_text, extract_annotations};
373 use crate::{fixture, DiagnosticsConfig};
375 /// Takes a multi-file input fixture with annotated cursor positions,
377 /// * a diagnostic is produced
378 /// * the first diagnostic fix trigger range touches the input cursor position
379 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
381 pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
382 check_nth_fix(0, ra_fixture_before, ra_fixture_after);
384 /// Takes a multi-file input fixture with annotated cursor positions,
386 /// * a diagnostic is produced
387 /// * every diagnostic fixes trigger range touches the input cursor position
388 /// * that the contents of the file containing the cursor match `after` after each diagnostic fix is applied
389 pub(crate) fn check_fixes(ra_fixture_before: &str, ra_fixtures_after: Vec<&str>) {
390 for (i, ra_fixture_after) in ra_fixtures_after.iter().enumerate() {
391 check_nth_fix(i, ra_fixture_before, ra_fixture_after)
396 fn check_nth_fix(nth: usize, ra_fixture_before: &str, ra_fixture_after: &str) {
397 let after = trim_indent(ra_fixture_after);
399 let (analysis, file_position) = fixture::position(ra_fixture_before);
400 let diagnostic = analysis
402 &DiagnosticsConfig::default(),
403 AssistResolveStrategy::All,
404 file_position.file_id,
409 let fix = &diagnostic.fixes.unwrap()[nth];
411 let source_change = fix.source_change.as_ref().unwrap();
412 let file_id = *source_change.source_file_edits.keys().next().unwrap();
413 let mut actual = analysis.file_text(file_id).unwrap().to_string();
415 for edit in source_change.source_file_edits.values() {
416 edit.apply(&mut actual);
421 assert_eq_text!(&after, &actual);
423 fix.target.contains_inclusive(file_position.offset),
424 "diagnostic fix range {:?} does not touch cursor position {:?}",
429 /// Checks that there's a diagnostic *without* fix at `$0`.
430 fn check_no_fix(ra_fixture: &str) {
431 let (analysis, file_position) = fixture::position(ra_fixture);
432 let diagnostic = analysis
434 &DiagnosticsConfig::default(),
435 AssistResolveStrategy::All,
436 file_position.file_id,
441 assert!(diagnostic.fixes.is_none(), "got a fix when none was expected: {:?}", diagnostic);
444 /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
445 /// apply to the file containing the cursor.
446 pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
447 let (analysis, files) = fixture::files(ra_fixture);
448 let diagnostics = files
450 .flat_map(|file_id| {
452 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
455 .collect::<Vec<_>>();
456 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
459 pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) {
460 let (analysis, file_id) = fixture::file(ra_fixture);
461 let diagnostics = analysis
462 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
464 expect.assert_debug_eq(&diagnostics)
467 pub(crate) fn check_diagnostics(ra_fixture: &str) {
468 let (analysis, file_id) = fixture::file(ra_fixture);
469 let diagnostics = analysis
470 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
473 let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
474 let mut actual = diagnostics
476 .filter(|d| d.code != Some(DiagnosticCode("inactive-code")))
477 .map(|d| (d.range, d.message))
478 .collect::<Vec<_>>();
479 actual.sort_by_key(|(range, _)| range.start());
480 assert_eq!(expected, actual);
484 fn test_unresolved_macro_range() {
488 //^^^ unresolved macro `foo::bar!`
494 fn range_mapping_out_of_macros() {
495 // FIXME: this is very wrong, but somewhat tricky to fix.
502 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
505 let _x = id![Foo { a: $042 }];
508 pub struct Foo { pub a: i32, pub b: i32 }
515 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
518 let _x = id![Foo { a: 42 }];
521 pub struct Foo { pub a: i32, pub b: i32 }
527 fn test_check_unnecessary_braces_in_use_statement() {
528 check_no_diagnostics(
541 check_no_diagnostics(
599 mod a { mod c {} mod d { mod e {} } }
600 use a::{c, d::{e$0}};
603 mod a { mod c {} mod d { mod e {} } }
610 fn test_disabled_diagnostics() {
611 let mut config = DiagnosticsConfig::default();
612 config.disabled.insert("unresolved-module".into());
614 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
617 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
618 assert!(diagnostics.is_empty());
620 let diagnostics = analysis
621 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
623 assert!(!diagnostics.is_empty());
627 fn unlinked_file_prepend_first_item() {
628 cov_mark::check!(unlinked_file_prepend_before_first_item);
629 // Only tests the first one for `pub mod` since the rest are the same
653 fn unlinked_file_append_mod() {
654 cov_mark::check!(unlinked_file_append_to_existing_mods);
666 mod preexisting_bottom;)
680 mod preexisting_bottom;)
686 fn unlinked_file_insert_in_empty_file() {
687 cov_mark::check!(unlinked_file_empty_file);
701 fn unlinked_file_old_style_modrs() {
719 fn unlinked_file_new_style_mod() {
735 fn unlinked_file_with_cfg_off() {
736 cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
750 fn unlinked_file_with_cfg_on() {
751 check_no_diagnostics(
763 fn break_outside_of_loop() {
767 //^^^^^ break outside of loop
773 fn no_such_field_diagnostics() {
776 struct S { foo: i32, bar: () }
780 //^ Missing structure fields:
784 //^^^^^^^ no such field
792 fn no_such_field_with_feature_flag_diagnostics() {
795 //- /lib.rs crate:foo cfg:feature=foo
798 #[cfg(feature = "foo")]
803 #[cfg(feature = "foo")]
804 pub(crate) fn new(my_val: usize, bar: bool) -> Self {
807 #[cfg(not(feature = "foo"))]
808 pub(crate) fn new(my_val: usize, _bar: bool) -> Self {
817 fn no_such_field_enum_with_feature_flag_diagnostics() {
820 //- /lib.rs crate:foo cfg:feature=foo
822 #[cfg(not(feature = "foo"))]
824 #[cfg(feature = "foo")]
840 fn no_such_field_with_feature_flag_diagnostics_on_struct_lit() {
843 //- /lib.rs crate:foo cfg:feature=foo
845 #[cfg(feature = "foo")]
847 #[cfg(not(feature = "foo"))]
852 #[cfg(feature = "foo")]
853 fn new(foo: u32) -> Self {
856 #[cfg(not(feature = "foo"))]
857 fn new(bar: u32) -> Self {
860 fn new2(bar: u32) -> Self {
861 #[cfg(feature = "foo")]
862 { Self { foo: bar } }
863 #[cfg(not(feature = "foo"))]
866 fn new2(val: u32) -> Self {
868 #[cfg(feature = "foo")]
870 #[cfg(not(feature = "foo"))]
880 fn no_such_field_with_type_macro() {
883 macro_rules! Type { () => { u32 }; }
884 struct Foo { bar: Type![] }
896 fn missing_unsafe_diagnostic_with_raw_ptr() {
900 let x = &5 as *const usize;
901 unsafe { let y = *x; }
903 } //^^ This operation is unsafe and requires an unsafe function or block
909 fn missing_unsafe_diagnostic_with_unsafe_call() {
915 unsafe fn unsafe_fn(&self) {
916 let x = &5 as *const usize;
921 unsafe fn unsafe_fn() {
922 let x = &5 as *const usize;
928 //^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
929 HasUnsafe.unsafe_fn();
930 //^^^^^^^^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
933 HasUnsafe.unsafe_fn();
941 fn missing_unsafe_diagnostic_with_static_mut() {
948 static mut STATIC_MUT: Ty = Ty { a: 0 };
951 let x = STATIC_MUT.a;
952 //^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
954 let x = STATIC_MUT.a;
962 fn no_missing_unsafe_diagnostic_with_safe_intrinsic() {
965 extern "rust-intrinsic" {
966 pub fn bitreverse(x: u32) -> u32; // Safe intrinsic
967 pub fn floorf32(x: f32) -> f32; // Unsafe intrinsic
971 let _ = bitreverse(12);
972 let _ = floorf32(12.0);
973 //^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
979 // Register the required standard library types to make the tests work
980 fn add_filter_map_with_find_next_boilerplate(body: &str) -> String {
982 //- /main.rs crate:main deps:core
983 use core::iter::Iterator;
984 use core::option::Option::{self, Some, None};
987 //- /core/lib.rs crate:core
989 pub enum Option<T> { Some(T), None }
994 fn filter_map<B, F>(self, f: F) -> FilterMap where F: FnMut(Self::Item) -> Option<B> { FilterMap }
995 fn next(&mut self) -> Option<Self::Item>;
997 pub struct FilterMap {}
998 impl Iterator for FilterMap {
1000 fn next(&mut self) -> i32 { 7 }
1004 format!("{}{}{}", prefix, body, suffix)
1008 fn replace_filter_map_next_with_find_map2() {
1009 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1012 let m = [1, 2, 3].iter().filter_map(|x| if *x == 2 { Some (4) } else { None }).next();
1013 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ replace filter_map(..).next() with find_map(..)
1020 fn replace_filter_map_next_with_find_map_no_diagnostic_without_next() {
1021 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1026 .filter_map(|x| if *x == 2 { Some (4) } else { None })
1034 fn replace_filter_map_next_with_find_map_no_diagnostic_with_intervening_methods() {
1035 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1040 .filter_map(|x| if *x == 2 { Some (4) } else { None })
1049 fn replace_filter_map_next_with_find_map_no_diagnostic_if_not_in_chain() {
1050 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
1055 .filter_map(|x| if *x == 2 { Some (4) } else { None });
1063 fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
1066 struct S { foo: i32, bar: () }
1067 fn baz(s: S) -> i32 {
1069 S { foo, .. } => foo,
1077 fn missing_record_pat_field_box() {
1080 struct S { s: Box<u32> }
1082 let S { box s } = a;
1089 fn missing_record_pat_field_ref() {
1094 let S { ref s } = a;
1101 fn simple_free_fn_zero() {
1106 //^^^^^^^ Expected 0 arguments, found 1
1119 fn simple_free_fn_one() {
1124 //^^^^^ Expected 1 argument, found 0
1141 impl S { fn method(&self) {} }
1145 } //^^^^^^^^^^^ Expected 1 argument, found 0
1152 impl S { fn method(&self) {} }
1163 fn method_with_arg() {
1167 impl S { fn method(&self, arg: u8) {} }
1171 } //^^^^^^^^^^ Expected 1 argument, found 0
1178 impl S { fn method(&self, arg: u8) {} }
1189 fn method_unknown_receiver() {
1190 // note: this is incorrect code, so there might be errors on this in the
1191 // future, but we shouldn't emit an argument count diagnostic here
1194 trait Foo { fn method(&self, arg: usize) {} }
1208 struct Tup(u8, u16);
1211 } //^^^^^^ Expected 2 arguments, found 1
1220 enum En { Variant(u8, u16), }
1223 } //^^^^^^^^^^^^^^ Expected 2 arguments, found 1
1229 fn enum_variant_type_macro() {
1242 //^^^^^^^^^^^^^^ Expected 1 argument, found 2
1244 //^^^^^^^^^^ Expected 1 argument, found 0
1256 fn fixed(fixed: u8);
1257 fn varargs(fixed: u8, ...);
1265 //^^^^^^^^^^^ Expected 1 argument, found 2
1278 fn arg_count_lambda() {
1284 //^^^ Expected 1 argument, found 0
1287 //^^^^^^^^^ Expected 1 argument, found 2
1294 fn cfgd_out_call_arguments() {
1297 struct C(#[cfg(FALSE)] ());
1310 C::new().method(#[cfg(FALSE)] 0);
1317 fn cfgd_out_fn_params() {
1320 fn foo(#[cfg(NEVER)] x: ()) {}
1325 fn method(#[cfg(NEVER)] self) {}
1326 fn method2(#[cfg(NEVER)] self, arg: u8) {}
1327 fn method3(self, #[cfg(NEVER)] arg: u8) {}
1331 fn fixed(fixed: u8, #[cfg(NEVER)] ...);
1332 fn varargs(#[cfg(not(NEVER))] ...);
1351 fn missing_semicolon() {
1354 fn test() -> i32 { 123; }
1355 //^^^ Remove this semicolon
1361 fn import_extern_crate_clash_with_inner_item() {
1362 // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
1366 //- /lib.rs crate:lib deps:jwt
1369 use permissions::jwt;
1373 jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
1378 pub struct Claims {}
1381 //- /jwt/lib.rs crate:jwt
1391 pub(super) mod match_check_tests {
1392 use crate::diagnostics::tests::check_diagnostics;
1400 //^^ Missing match arm
1402 //^^^^ Missing match arm
1404 match () { _ => (), }
1405 match () { () => (), }
1406 match (()) { (()) => (), }
1413 fn tuple_of_two_empty_tuple() {
1418 //^^^^^^^^ Missing match arm
1420 match ((), ()) { ((), ()) => (), }
1432 //^^^^^ Missing match arm
1433 match false { true => (), }
1434 //^^^^^ Missing match arm
1435 match (false, true) {}
1436 //^^^^^^^^^^^^^ Missing match arm
1437 match (false, true) { (true, true) => (), }
1438 //^^^^^^^^^^^^^ Missing match arm
1439 match (false, true) {
1440 //^^^^^^^^^^^^^ Missing match arm
1441 (false, true) => (),
1442 (false, false) => (),
1443 (true, false) => (),
1445 match (false, true) { (true, _x) => (), }
1446 //^^^^^^^^^^^^^ Missing match arm
1448 match false { true => (), false => (), }
1449 match (false, true) {
1451 (true, false) => (),
1454 match (false, true) {
1456 (true, false) => (),
1457 (false, true) => (),
1458 (false, false) => (),
1460 match (false, true) {
1462 (false, true) => (),
1463 (false, false) => (),
1465 match (false, true, false) {
1469 match (false, true, false) {
1473 match (false, true, false) { (..) => (), }
1480 fn tuple_of_tuple_and_bools() {
1484 match (false, ((), false)) {}
1485 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1486 match (false, ((), false)) { (true, ((), true)) => (), }
1487 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1488 match (false, ((), false)) { (true, _) => (), }
1489 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1491 match (false, ((), false)) {
1492 (true, ((), true)) => (),
1493 (true, ((), false)) => (),
1494 (false, ((), true)) => (),
1495 (false, ((), false)) => (),
1497 match (false, ((), false)) {
1498 (true, ((), true)) => (),
1499 (true, ((), false)) => (),
1511 enum Either { A, B, }
1515 //^^^^^^^^^ Missing match arm
1516 match Either::B { Either::A => (), }
1517 //^^^^^^^^^ Missing match arm
1520 //^^^^^^^^^^ Missing match arm
1525 Either::A => (), Either::B => (),
1528 Either::A => (), Either::B => (),
1536 fn enum_containing_bool() {
1539 enum Either { A(bool), B }
1543 //^^^^^^^^^ Missing match arm
1545 //^^^^^^^^^ Missing match arm
1546 Either::A(true) => (), Either::B => ()
1550 Either::A(true) => (),
1551 Either::A(false) => (),
1569 fn enum_different_sizes() {
1572 enum Either { A(bool), B(bool, bool) }
1575 match Either::A(false) {
1576 //^^^^^^^^^^^^^^^^ Missing match arm
1578 Either::B(false, _) => (),
1581 match Either::A(false) {
1583 Either::B(true, _) => (),
1584 Either::B(false, _) => (),
1586 match Either::A(false) {
1587 Either::A(true) | Either::A(false) => (),
1588 Either::B(true, _) => (),
1589 Either::B(false, _) => (),
1597 fn tuple_of_enum_no_diagnostic() {
1600 enum Either { A(bool), B(bool, bool) }
1601 enum Either2 { C, D }
1604 match (Either::A(false), Either2::C) {
1605 (Either::A(true), _) | (Either::A(false), _) => (),
1606 (Either::B(true, _), Either2::C) => (),
1607 (Either::B(false, _), Either2::C) => (),
1608 (Either::B(_, _), Either2::D) => (),
1616 fn or_pattern_no_diagnostic() {
1622 match (Either::A, Either::B) {
1623 (Either::A | Either::B, _) => (),
1630 fn mismatched_types() {
1631 // Match statements with arms that don't match the
1632 // expression pattern do not fire this diagnostic.
1635 enum Either { A, B }
1636 enum Either2 { C, D }
1641 // ^^^^^^^^^^ Internal: match check bailed out
1644 match (true, false) {
1645 (true, false, true) => (),
1646 // ^^^^^^^^^^^^^^^^^^^ Internal: match check bailed out
1649 match (true, false) { (true,) => {} }
1650 // ^^^^^^^ Internal: match check bailed out
1651 match (0) { () => () }
1652 // ^^ Internal: match check bailed out
1653 match Unresolved::Bar { Unresolved::Baz => () }
1660 fn mismatched_types_in_or_patterns() {
1664 match false { true | () => {} }
1665 // ^^^^^^^^^ Internal: match check bailed out
1666 match (false,) { (true | (),) => {} }
1667 // ^^^^^^^^^^^^ Internal: match check bailed out
1674 fn malformed_match_arm_tuple_enum_missing_pattern() {
1675 // We are testing to be sure we don't panic here when the match
1676 // arm `Either::B` is missing its pattern.
1679 enum Either { A, B(u32) }
1692 fn malformed_match_arm_extra_fields() {
1695 enum A { B(isize, isize), C }
1698 A::B(_, _, _) => (),
1699 // ^^^^^^^^^^^^^ Internal: match check bailed out
1703 // ^^^^^^^ Internal: match check bailed out
1711 fn expr_diverges() {
1714 enum Either { A, B }
1719 // ^^^^^^^^^ Internal: match check bailed out
1724 // ^^^^^^^^^ Internal: match check bailed out
1726 match loop { break Foo::A } {
1727 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1730 match loop { break Foo::A } {
1740 fn expr_partially_diverges() {
1743 enum Either<T> { A(T), B }
1745 fn foo() -> Either<!> { Either::B }
1748 Either::A(val) => val,
1760 enum Either { A { foo: bool }, B }
1763 let a = Either::A { foo: true };
1765 //^ Missing match arm
1766 match a { Either::A { foo: true } => () }
1767 //^ Missing match arm
1769 Either::A { } => (),
1770 //^^^^^^^^^ Missing structure fields:
1775 //^ Missing match arm
1776 Either::A { } => (),
1777 } //^^^^^^^^^ Missing structure fields:
1781 Either::A { foo: true } => (),
1782 Either::A { foo: false } => (),
1786 Either::A { foo: _ } => (),
1795 fn enum_record_fields_out_of_order() {
1799 A { foo: bool, bar: () },
1804 let a = Either::A { foo: true, bar: () };
1806 //^ Missing match arm
1807 Either::A { bar: (), foo: false } => (),
1808 Either::A { foo: true, bar: () } => (),
1812 Either::A { bar: (), foo: false } => (),
1813 Either::A { foo: true, bar: () } => (),
1822 fn enum_record_ellipsis() {
1826 A { foo: bool, bar: bool },
1833 //^ Missing match arm
1834 Either::A { foo: true, .. } => (),
1838 //^ Missing match arm
1839 Either::A { .. } => (),
1843 Either::A { foo: true, .. } => (),
1844 Either::A { foo: false, .. } => (),
1849 Either::A { .. } => (),
1858 fn enum_tuple_partial_ellipsis() {
1862 A(bool, bool, bool, bool),
1868 //^^^^^^^^^ Missing match arm
1869 Either::A(true, .., true) => (),
1870 Either::A(true, .., false) => (),
1871 Either::A(false, .., false) => (),
1875 //^^^^^^^^^ Missing match arm
1876 Either::A(true, .., true) => (),
1877 Either::A(true, .., false) => (),
1878 Either::A(.., true) => (),
1883 Either::A(true, .., true) => (),
1884 Either::A(true, .., false) => (),
1885 Either::A(false, .., true) => (),
1886 Either::A(false, .., false) => (),
1890 Either::A(true, .., true) => (),
1891 Either::A(true, .., false) => (),
1892 Either::A(.., true) => (),
1893 Either::A(.., false) => (),
1907 fn enum_(never: Never) {
1910 fn enum_ref(never: &Never) {
1912 //^^^^^ Missing match arm
1925 enum Option<T> { Some(T), None }
1928 // `Never` is deliberately not defined so that it's an uninferred type.
1929 match Option::<Never>::None {
1931 Some(never) => match never {},
1932 // ^^^^^^^^^^^ Internal: match check bailed out
1934 match Option::<Never>::None {
1935 //^^^^^^^^^^^^^^^^^^^^^ Missing match arm
1936 Option::Some(_never) => {},
1944 fn tuple_of_bools_with_ellipsis_at_end_missing_arm() {
1948 match (false, true, false) {
1949 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1957 fn tuple_of_bools_with_ellipsis_at_beginning_missing_arm() {
1961 match (false, true, false) {
1962 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1970 fn tuple_of_bools_with_ellipsis_in_middle_missing_arm() {
1974 match (false, true, false) {
1975 //^^^^^^^^^^^^^^^^^^^^ Missing match arm
1976 (true, .., false) => (),
1983 fn record_struct() {
1985 r#"struct Foo { a: bool }
1988 //^ Missing match arm
1989 match f { Foo { a: true } => () }
1990 //^ Missing match arm
1991 match &f { Foo { a: true } => () }
1992 //^^ Missing match arm
1993 match f { Foo { a: _ } => () }
1995 Foo { a: true } => (),
1996 Foo { a: false } => (),
1999 Foo { a: true } => (),
2000 Foo { a: false } => (),
2010 r#"struct Foo(bool);
2013 //^ Missing match arm
2014 match f { Foo(true) => () }
2015 //^ Missing match arm
2031 //^ Missing match arm
2032 match f { Foo => () }
2039 fn record_struct_ellipsis() {
2041 r#"struct Foo { foo: bool, bar: bool }
2043 match f { Foo { foo: true, .. } => () }
2044 //^ Missing match arm
2046 //^ Missing match arm
2047 Foo { foo: true, .. } => (),
2048 Foo { bar: false, .. } => ()
2050 match f { Foo { .. } => () }
2052 Foo { foo: true, .. } => (),
2053 Foo { foo: false, .. } => ()
2065 enum Either { A(bool), B }
2067 //^^^^^^^^^ Missing match arm
2068 Either::A(true | false) => (),
2076 fn no_panic_at_unimplemented_subpattern_type() {
2081 match v { S{ a } => {} }
2082 match v { S{ a: _x } => {} }
2083 match v { S{ a: 'a' } => {} }
2084 //^^^^^^^^^^^ Internal: match check bailed out
2085 match v { S{..} => {} }
2088 //^ Missing match arm
2103 match true { _x @ true => {} }
2104 //^^^^ Missing match arm
2111 fn binding_ref_has_correct_type() {
2112 // Asserts `PatKind::Binding(ref _x): bool`, not &bool.
2113 // If that's not true match checking will panic with "incompatible constructors"
2114 // FIXME: make facilities to test this directly like `tests::check_infer(..)`
2119 // FIXME: this should not bail out but current behavior is such as the old algorithm.
2120 // ExprValidator::validate_match(..) checks types of top level patterns incorrecly.
2123 // ^^^^^^ Internal: match check bailed out
2136 fn enum_non_exhaustive() {
2139 //- /lib.rs crate:lib
2143 match E::A { _ => {} }
2153 //- /main.rs crate:main deps:lib
2156 match E::A { _ => {} }
2158 //^^^^ Missing match arm
2163 //^^^^ Missing match arm
2182 //^^^^ Missing match arm
2192 fn pattern_type_is_of_substitution() {
2193 cov_mark::check!(match_check_wildcard_expanded_to_substitutions);
2208 fn record_struct_no_such_field() {
2213 match f { Foo { bar } => () }
2214 // ^^^^^^^^^^^ Internal: match check bailed out
2221 fn match_ergonomics_issue_9095() {
2224 enum Foo<T> { A(T) }
2226 match &Foo::A(true) {
2235 mod false_negatives {
2236 //! The implementation of match checking here is a work in progress. As we roll this out, we
2237 //! prefer false negatives to false positives (ideally there would be no false positives). This
2238 //! test module should document known false negatives. Eventually we will have a complete
2239 //! implementation of match checking and this module will be empty.
2241 //! The reasons for documenting known false negatives:
2243 //! 1. It acts as a backlog of work that can be done to improve the behavior of the system.
2244 //! 2. It ensures the code doesn't panic when handling these cases.
2249 // We don't currently check integer exhaustiveness.
2255 // ^^ Internal: match check bailed out
2264 fn reference_patterns_at_top_level() {
2270 // ^^^^^ Internal: match check bailed out
2278 fn reference_patterns_in_fields() {
2284 // ^^^^^^^ Internal: match check bailed out
2288 // ^^^^^^^^ Internal: match check bailed out
2298 mod decl_check_tests {
2299 use crate::diagnostics::tests::check_diagnostics;
2302 fn incorrect_function_name() {
2305 fn NonSnakeCaseName() {}
2306 // ^^^^^^^^^^^^^^^^ Function `NonSnakeCaseName` should have snake_case name, e.g. `non_snake_case_name`
2312 fn incorrect_function_params() {
2315 fn foo(SomeParam: u8) {}
2316 // ^^^^^^^^^ Parameter `SomeParam` should have snake_case name, e.g. `some_param`
2318 fn foo2(ok_param: &str, CAPS_PARAM: u8) {}
2319 // ^^^^^^^^^^ Parameter `CAPS_PARAM` should have snake_case name, e.g. `caps_param`
2325 fn incorrect_variable_names() {
2329 let SOME_VALUE = 10;
2330 // ^^^^^^^^^^ Variable `SOME_VALUE` should have snake_case name, e.g. `some_value`
2331 let AnotherValue = 20;
2332 // ^^^^^^^^^^^^ Variable `AnotherValue` should have snake_case name, e.g. `another_value`
2339 fn incorrect_struct_names() {
2342 struct non_camel_case_name {}
2343 // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName`
2345 struct SCREAMING_CASE {}
2346 // ^^^^^^^^^^^^^^ Structure `SCREAMING_CASE` should have CamelCase name, e.g. `ScreamingCase`
2352 fn no_diagnostic_for_camel_cased_acronyms_in_struct_name() {
2361 fn incorrect_struct_field() {
2364 struct SomeStruct { SomeField: u8 }
2365 // ^^^^^^^^^ Field `SomeField` should have snake_case name, e.g. `some_field`
2371 fn incorrect_enum_names() {
2374 enum some_enum { Val(u8) }
2375 // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum`
2378 // ^^^^^^^^^ Enum `SOME_ENUM` should have CamelCase name, e.g. `SomeEnum`
2384 fn no_diagnostic_for_camel_cased_acronyms_in_enum_name() {
2393 fn incorrect_enum_variant_name() {
2396 enum SomeEnum { SOME_VARIANT(u8) }
2397 // ^^^^^^^^^^^^ Variant `SOME_VARIANT` should have CamelCase name, e.g. `SomeVariant`
2403 fn incorrect_const_name() {
2406 const some_weird_const: u8 = 10;
2407 // ^^^^^^^^^^^^^^^^ Constant `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2413 fn incorrect_static_name() {
2416 static some_weird_const: u8 = 10;
2417 // ^^^^^^^^^^^^^^^^ Static variable `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST`
2423 fn fn_inside_impl_struct() {
2427 // ^^^^^^^^^^ Structure `someStruct` should have CamelCase name, e.g. `SomeStruct`
2430 fn SomeFunc(&self) {
2431 // ^^^^^^^^ Function `SomeFunc` should have snake_case name, e.g. `some_func`
2432 let WHY_VAR_IS_CAPS = 10;
2433 // ^^^^^^^^^^^^^^^ Variable `WHY_VAR_IS_CAPS` should have snake_case name, e.g. `why_var_is_caps`
2441 fn no_diagnostic_for_enum_varinats() {
2444 enum Option { Some, None }
2447 match Option::None {
2460 enum Option { Some, None }
2463 match Option::None {
2464 SOME_VAR @ None => (),
2465 // ^^^^^^^^ Variable `SOME_VAR` should have snake_case name, e.g. `some_var`
2474 fn allow_attributes() {
2477 #[allow(non_snake_case)]
2478 fn NonSnakeCaseName(SOME_VAR: u8) -> u8{
2479 // cov_flags generated output from elsewhere in this file
2482 static lower_case: u8;
2485 let OtherVar = SOME_VAR + 1;
2489 #[allow(nonstandard_style)]
2490 mod CheckNonstandardStyle {
2491 fn HiImABadFnName() {}
2496 fn HiImABadFnName() {}
2500 #![allow(non_snake_case)]
2501 fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {}
2504 #[allow(non_snake_case, non_camel_case_types)]
2505 pub struct some_type {
2510 #[allow(non_upper_case_globals)]
2511 pub const some_const: u8 = 10;
2513 #[allow(non_upper_case_globals)]
2514 pub static SomeStatic: u8 = 10;
2520 fn allow_attributes_crate_attr() {
2523 #![allow(non_snake_case)]
2526 fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {}
2534 fn bug_trait_inside_fn() {
2536 // This is broken, and in fact, should not even be looked at by this
2537 // lint in the first place. There's weird stuff going on in the
2538 // collection phase.
2539 // It's currently being brought in by:
2540 // * validate_func on `a` recursing into modules
2541 // * then it finds the trait and then the function while iterating
2543 // * then validate_func is called on Dirty
2544 // * ... which then proceeds to look at some unknown module taking no
2545 // attrs from either the impl or the fn a, and then finally to the root
2548 // It should find the attribute on the trait, but it *doesn't even see
2549 // the trait* as far as I can tell.
2557 // this comes out of bitflags, mostly
2558 #[allow(non_snake_case)]
2560 const HiImAlsoBad: u8 = 2;
2562 fn Dirty(&self) -> bool {
2575 fn bug_traits_arent_checked() {
2576 // FIXME: Traits and functions in traits aren't currently checked by
2577 // r-a, even though rustc will complain about them.
2581 // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait`
2583 // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function`
2585 // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function`
2592 fn ignores_extern_items() {
2593 cov_mark::check!(extern_func_incorrect_case_ignored);
2594 cov_mark::check!(extern_static_incorrect_case_ignored);
2598 fn NonSnakeCaseName(SOME_VAR: u8) -> u8;
2599 pub static SomeStatic: u8 = 10;
2606 fn infinite_loop_inner_items() {
2618 #[test] // Issue #8809.
2619 fn parenthesized_parameter() {
2620 check_diagnostics(r#"fn f((O): _) {}"#)