From e6c300892dce9202e4f21359129569536945dfea Mon Sep 17 00:00:00 2001 From: The 8472 Date: Sun, 15 Jun 2025 21:47:48 +0200 Subject: [PATCH 01/23] small iter.intersperse.fold() optimization No need to call into fold when the first item is already None, this avoids some redundant work for empty iterators. "But it uses Fuse" one might want to protest, but Fuse is specialized and may call into the inner iterator anyway. --- library/core/src/iter/adapters/intersperse.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/library/core/src/iter/adapters/intersperse.rs b/library/core/src/iter/adapters/intersperse.rs index c97a59b614f9d..843479e2a27a7 100644 --- a/library/core/src/iter/adapters/intersperse.rs +++ b/library/core/src/iter/adapters/intersperse.rs @@ -223,7 +223,16 @@ where { let mut accum = init; - let first = if started { next_item.take() } else { iter.next() }; + let first = if started { + next_item.take() + } else { + let n = iter.next(); + // skip invoking fold() for empty iterators + if n.is_none() { + return accum; + } + n + }; if let Some(x) = first { accum = f(accum, x); } From 644469e9613253321d09887ffe0fb2c98528ee21 Mon Sep 17 00:00:00 2001 From: "Tim (Theemathas) Chirananthavat" Date: Thu, 19 Jun 2025 12:04:24 +0700 Subject: [PATCH 02/23] Remove incorrect comments in `Weak` It is currently possible to create a dangling `Weak` to a DST by calling `Weak::new()` for a sized type, then doing an unsized coercion. Therefore, the comments are wrong. These comments were added in . As far as I can tell, the guarantee in the comment was only previously used in the `as_ptr` method. However, the current implementation of `as_ptr` no longer relies on this guarantee. --- library/alloc/src/rc.rs | 1 - library/alloc/src/sync.rs | 1 - 2 files changed, 2 deletions(-) diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index 4b8ea708e7e57..010d17f74762c 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -3004,7 +3004,6 @@ pub struct Weak< // `Weak::new` sets this to `usize::MAX` so that it doesn’t need // to allocate space on the heap. That's not a value a real pointer // will ever have because RcInner has alignment at least 2. - // This is only possible when `T: Sized`; unsized `T` never dangle. ptr: NonNull>, alloc: A, } diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index 17090925cfa0c..1e3c03977bd75 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -342,7 +342,6 @@ pub struct Weak< // `Weak::new` sets this to `usize::MAX` so that it doesn’t need // to allocate space on the heap. That's not a value a real pointer // will ever have because RcInner has alignment at least 2. - // This is only possible when `T: Sized`; unsized `T` never dangle. ptr: NonNull>, alloc: A, } From e40515a494dc1bbd571aafd4469657d8ea951a70 Mon Sep 17 00:00:00 2001 From: Makai Date: Sun, 22 Jun 2025 18:01:39 +0000 Subject: [PATCH 03/23] add method to retrieve body of coroutine --- compiler/rustc_smir/src/stable_mir/ty.rs | 6 + .../stable-mir/check_coroutine_body.rs | 105 ++++++++++++++++++ 2 files changed, 111 insertions(+) create mode 100644 tests/ui-fulldeps/stable-mir/check_coroutine_body.rs diff --git a/compiler/rustc_smir/src/stable_mir/ty.rs b/compiler/rustc_smir/src/stable_mir/ty.rs index 4415cd6e2e3ba..92fa97566c5ad 100644 --- a/compiler/rustc_smir/src/stable_mir/ty.rs +++ b/compiler/rustc_smir/src/stable_mir/ty.rs @@ -757,6 +757,12 @@ crate_def! { } impl CoroutineDef { + /// Retrieves the body of the coroutine definition. Returns None if the body + /// isn't available. + pub fn body(&self) -> Option { + with(|cx| cx.has_body(self.0).then(|| cx.mir_body(self.0))) + } + pub fn discriminant_for_variant(&self, args: &GenericArgs, idx: VariantIdx) -> Discr { with(|cx| cx.coroutine_discr_for_variant(*self, args, idx)) } diff --git a/tests/ui-fulldeps/stable-mir/check_coroutine_body.rs b/tests/ui-fulldeps/stable-mir/check_coroutine_body.rs new file mode 100644 index 0000000000000..677734929589d --- /dev/null +++ b/tests/ui-fulldeps/stable-mir/check_coroutine_body.rs @@ -0,0 +1,105 @@ +//@ run-pass +//! Tests stable mir API for retrieving the body of a coroutine. + +//@ ignore-stage1 +//@ ignore-cross-compile +//@ ignore-remote +//@ edition: 2024 + +#![feature(rustc_private)] +#![feature(assert_matches)] + +extern crate rustc_middle; +#[macro_use] +extern crate rustc_smir; +extern crate rustc_driver; +extern crate rustc_interface; +extern crate stable_mir; + +use std::io::Write; +use std::ops::ControlFlow; + +use stable_mir::mir::Body; +use stable_mir::ty::{RigidTy, TyKind}; + +const CRATE_NAME: &str = "crate_coroutine_body"; + +fn test_coroutine_body() -> ControlFlow<()> { + let crate_items = stable_mir::all_local_items(); + if let Some(body) = crate_items.iter().find_map(|item| { + let item_ty = item.ty(); + if let TyKind::RigidTy(RigidTy::Coroutine(def, ..)) = &item_ty.kind() { + if def.0.name() == "gbc::{closure#0}".to_string() { + def.body() + } else { + None + } + } else { + None + } + }) { + check_coroutine_body(body); + } else { + panic!("Cannot find `gbc::{{closure#0}}`. All local items are: {:#?}", crate_items); + } + + ControlFlow::Continue(()) +} + +fn check_coroutine_body(body: Body) { + let ret_ty = &body.locals()[0].ty; + let local_3 = &body.locals()[3].ty; + let local_4 = &body.locals()[4].ty; + + let TyKind::RigidTy(RigidTy::Adt(def, ..)) = &ret_ty.kind() + else { + panic!("Expected RigidTy::Adt, got: {:#?}", ret_ty); + }; + + assert_eq!("std::task::Poll", def.0.name()); + + let TyKind::RigidTy(RigidTy::Coroutine(def, ..)) = &local_3.kind() + else { + panic!("Expected RigidTy::Coroutine, got: {:#?}", local_3); + }; + + assert_eq!("gbc::{closure#0}::{closure#0}", def.0.name()); + + let TyKind::RigidTy(RigidTy::Coroutine(def, ..)) = &local_4.kind() + else { + panic!("Expected RigidTy::Coroutine, got: {:#?}", local_4); + }; + + assert_eq!("gbc::{closure#0}::{closure#0}", def.0.name()); +} + +fn main() { + let path = "coroutine_body.rs"; + generate_input(&path).unwrap(); + let args = &[ + "rustc".to_string(), + "-Cpanic=abort".to_string(), + "--edition".to_string(), + "2024".to_string(), + "--crate-name".to_string(), + CRATE_NAME.to_string(), + path.to_string(), + ]; + run!(args, test_coroutine_body).unwrap(); +} + +fn generate_input(path: &str) -> std::io::Result<()> { + let mut file = std::fs::File::create(path)?; + write!( + file, + r#" + async fn gbc() -> i32 {{ + let a = async {{ 1 }}.await; + a + }} + + fn main() {{}} + "# + )?; + Ok(()) +} From 7e683cc4d1f8dff6c777b2eecec4c1173dbff1db Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Tue, 27 May 2025 15:16:51 +0200 Subject: [PATCH 04/23] Do not emit `redundant_explicit_links` rustdoc lint if the doc comment comes from expansion --- compiler/rustc_resolve/src/rustdoc.rs | 82 +++++++++++-------- .../passes/collect_intra_doc_links.rs | 13 +-- src/librustdoc/passes/lint/bare_urls.rs | 3 +- .../passes/lint/check_code_block_syntax.rs | 2 +- src/librustdoc/passes/lint/html_tags.rs | 4 +- .../passes/lint/redundant_explicit_links.rs | 40 +++++++-- .../passes/lint/unescaped_backticks.rs | 10 ++- 7 files changed, 100 insertions(+), 54 deletions(-) diff --git a/compiler/rustc_resolve/src/rustdoc.rs b/compiler/rustc_resolve/src/rustdoc.rs index 931c6241bf214..2d84178bede90 100644 --- a/compiler/rustc_resolve/src/rustdoc.rs +++ b/compiler/rustc_resolve/src/rustdoc.rs @@ -49,6 +49,9 @@ pub struct DocFragment { pub doc: Symbol, pub kind: DocFragmentKind, pub indent: usize, + /// Because we temper with the spans context, this information cannot be correctly retrieved + /// later on. So instead, we compute it and store it here. + pub from_expansion: bool, } #[derive(Clone, Copy, Debug)] @@ -208,17 +211,18 @@ pub fn attrs_to_doc_fragments<'a, A: AttributeExt + Clone + 'a>( for (attr, item_id) in attrs { if let Some((doc_str, comment_kind)) = attr.doc_str_and_comment_kind() { let doc = beautify_doc_string(doc_str, comment_kind); - let (span, kind) = if attr.is_doc_comment() { - (attr.span(), DocFragmentKind::SugaredDoc) + let (span, kind, from_expansion) = if attr.is_doc_comment() { + let span = attr.span(); + (span, DocFragmentKind::SugaredDoc, span.from_expansion()) } else { - ( - attr.value_span() - .map(|i| i.with_ctxt(attr.span().ctxt())) - .unwrap_or(attr.span()), - DocFragmentKind::RawDoc, - ) + let attr_span = attr.span(); + let (span, from_expansion) = match attr.value_span() { + Some(sp) => (sp.with_ctxt(attr_span.ctxt()), sp.from_expansion()), + None => (attr_span, attr_span.from_expansion()), + }; + (span, DocFragmentKind::RawDoc, from_expansion) }; - let fragment = DocFragment { span, doc, kind, item_id, indent: 0 }; + let fragment = DocFragment { span, doc, kind, item_id, indent: 0, from_expansion }; doc_fragments.push(fragment); } else if !doc_only { other_attrs.push(attr.clone()); @@ -506,16 +510,21 @@ fn collect_link_data<'input, F: BrokenLinkCallback<'input>>( } /// Returns a span encompassing all the document fragments. -pub fn span_of_fragments(fragments: &[DocFragment]) -> Option { - if fragments.is_empty() { - return None; - } - let start = fragments[0].span; - if start == DUMMY_SP { +pub fn span_of_fragments_with_expansion(fragments: &[DocFragment]) -> Option<(Span, bool)> { + let Some(first_fragment) = fragments.first() else { return None }; + if first_fragment.span == DUMMY_SP { return None; } - let end = fragments.last().expect("no doc strings provided").span; - Some(start.to(end)) + let last_fragment = fragments.last().expect("no doc strings provided"); + Some(( + first_fragment.span.to(last_fragment.span), + first_fragment.from_expansion || last_fragment.from_expansion, + )) +} + +/// Returns a span encompassing all the document fragments. +pub fn span_of_fragments(fragments: &[DocFragment]) -> Option { + span_of_fragments_with_expansion(fragments).map(|(sp, _)| sp) } /// Attempts to match a range of bytes from parsed markdown to a `Span` in the source code. @@ -540,7 +549,7 @@ pub fn source_span_for_markdown_range( markdown: &str, md_range: &Range, fragments: &[DocFragment], -) -> Option { +) -> Option<(Span, bool)> { let map = tcx.sess.source_map(); source_span_for_markdown_range_inner(map, markdown, md_range, fragments) } @@ -551,7 +560,7 @@ pub fn source_span_for_markdown_range_inner( markdown: &str, md_range: &Range, fragments: &[DocFragment], -) -> Option { +) -> Option<(Span, bool)> { use rustc_span::BytePos; if let &[fragment] = &fragments @@ -562,11 +571,14 @@ pub fn source_span_for_markdown_range_inner( && let Ok(md_range_hi) = u32::try_from(md_range.end) { // Single fragment with string that contains same bytes as doc. - return Some(Span::new( - fragment.span.lo() + rustc_span::BytePos(md_range_lo), - fragment.span.lo() + rustc_span::BytePos(md_range_hi), - fragment.span.ctxt(), - fragment.span.parent(), + return Some(( + Span::new( + fragment.span.lo() + rustc_span::BytePos(md_range_lo), + fragment.span.lo() + rustc_span::BytePos(md_range_hi), + fragment.span.ctxt(), + fragment.span.parent(), + ), + fragment.from_expansion, )); } @@ -598,19 +610,21 @@ pub fn source_span_for_markdown_range_inner( { match_data = Some((i, match_start)); } else { - // Heirustic produced ambiguity, return nothing. + // Heuristic produced ambiguity, return nothing. return None; } } } if let Some((i, match_start)) = match_data { - let sp = fragments[i].span; + let fragment = &fragments[i]; + let sp = fragment.span; // we need to calculate the span start, // then use that in our calulations for the span end let lo = sp.lo() + BytePos(match_start as u32); - return Some( + return Some(( sp.with_lo(lo).with_hi(lo + BytePos((md_range.end - md_range.start) as u32)), - ); + fragment.from_expansion, + )); } return None; } @@ -664,8 +678,12 @@ pub fn source_span_for_markdown_range_inner( } } - Some(span_of_fragments(fragments)?.from_inner(InnerSpan::new( - md_range.start + start_bytes, - md_range.end + start_bytes + end_bytes, - ))) + let (span, from_expansion) = span_of_fragments_with_expansion(fragments)?; + Some(( + span.from_inner(InnerSpan::new( + md_range.start + start_bytes, + md_range.end + start_bytes + end_bytes, + )), + from_expansion, + )) } diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index 1daaba3b86c5c..ca6f67eb6dfd6 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -1387,13 +1387,15 @@ impl LinkCollector<'_, '_> { ori_link: &MarkdownLinkRange, item: &Item, ) { - let span = source_span_for_markdown_range( + let span = match source_span_for_markdown_range( self.cx.tcx, dox, ori_link.inner_range(), &item.attrs.doc_strings, - ) - .unwrap_or_else(|| item.attr_span(self.cx.tcx)); + ) { + Some((sp, _)) => sp, + None => item.attr_span(self.cx.tcx), + }; rustc_session::parse::feature_err( self.cx.tcx.sess, sym::intra_doc_pointers, @@ -1836,7 +1838,7 @@ fn report_diagnostic( let mut md_range = md_range.clone(); let sp = source_span_for_markdown_range(tcx, dox, &md_range, &item.attrs.doc_strings) - .map(|mut sp| { + .map(|(mut sp, _)| { while dox.as_bytes().get(md_range.start) == Some(&b' ') || dox.as_bytes().get(md_range.start) == Some(&b'`') { @@ -1854,7 +1856,8 @@ fn report_diagnostic( (sp, MarkdownLinkRange::Destination(md_range)) } MarkdownLinkRange::WholeLink(md_range) => ( - source_span_for_markdown_range(tcx, dox, md_range, &item.attrs.doc_strings), + source_span_for_markdown_range(tcx, dox, md_range, &item.attrs.doc_strings) + .map(|(sp, _)| sp), link_range.clone(), ), }; diff --git a/src/librustdoc/passes/lint/bare_urls.rs b/src/librustdoc/passes/lint/bare_urls.rs index 3b3ce3e92202a..f70bdf4e4fe37 100644 --- a/src/librustdoc/passes/lint/bare_urls.rs +++ b/src/librustdoc/passes/lint/bare_urls.rs @@ -18,7 +18,8 @@ use crate::html::markdown::main_body_opts; pub(super) fn visit_item(cx: &DocContext<'_>, item: &Item, hir_id: HirId, dox: &str) { let report_diag = |cx: &DocContext<'_>, msg: &'static str, range: Range| { - let maybe_sp = source_span_for_markdown_range(cx.tcx, dox, &range, &item.attrs.doc_strings); + let maybe_sp = source_span_for_markdown_range(cx.tcx, dox, &range, &item.attrs.doc_strings) + .map(|(sp, _)| sp); let sp = maybe_sp.unwrap_or_else(|| item.attr_span(cx.tcx)); cx.tcx.node_span_lint(crate::lint::BARE_URLS, hir_id, sp, |lint| { lint.primary_message(msg) diff --git a/src/librustdoc/passes/lint/check_code_block_syntax.rs b/src/librustdoc/passes/lint/check_code_block_syntax.rs index 91cddbe5a5bc7..b08533317abeb 100644 --- a/src/librustdoc/passes/lint/check_code_block_syntax.rs +++ b/src/librustdoc/passes/lint/check_code_block_syntax.rs @@ -87,7 +87,7 @@ fn check_rust_syntax( &code_block.range, &item.attrs.doc_strings, ) { - Some(sp) => (sp, true), + Some((sp, _)) => (sp, true), None => (item.attr_span(cx.tcx), false), }; diff --git a/src/librustdoc/passes/lint/html_tags.rs b/src/librustdoc/passes/lint/html_tags.rs index b9739726c9569..19cf15d40a3b4 100644 --- a/src/librustdoc/passes/lint/html_tags.rs +++ b/src/librustdoc/passes/lint/html_tags.rs @@ -16,7 +16,7 @@ pub(crate) fn visit_item(cx: &DocContext<'_>, item: &Item, hir_id: HirId, dox: & let tcx = cx.tcx; let report_diag = |msg: String, range: &Range, is_open_tag: bool| { let sp = match source_span_for_markdown_range(tcx, dox, range, &item.attrs.doc_strings) { - Some(sp) => sp, + Some((sp, _)) => sp, None => item.attr_span(tcx), }; tcx.node_span_lint(crate::lint::INVALID_HTML_TAGS, hir_id, sp, |lint| { @@ -55,7 +55,7 @@ pub(crate) fn visit_item(cx: &DocContext<'_>, item: &Item, hir_id: HirId, dox: & &(generics_start..generics_end), &item.attrs.doc_strings, ) { - Some(sp) => sp, + Some((sp, _)) => sp, None => item.attr_span(tcx), }; // Sometimes, we only extract part of a path. For example, consider this: diff --git a/src/librustdoc/passes/lint/redundant_explicit_links.rs b/src/librustdoc/passes/lint/redundant_explicit_links.rs index 6bc4374c06b1d..0482bc1058f0e 100644 --- a/src/librustdoc/passes/lint/redundant_explicit_links.rs +++ b/src/librustdoc/passes/lint/redundant_explicit_links.rs @@ -161,15 +161,26 @@ fn check_inline_or_reference_unknown_redundancy( if dest_res == display_res { let link_span = - source_span_for_markdown_range(cx.tcx, doc, &link_range, &item.attrs.doc_strings) - .unwrap_or(item.attr_span(cx.tcx)); - let explicit_span = source_span_for_markdown_range( + match source_span_for_markdown_range(cx.tcx, doc, &link_range, &item.attrs.doc_strings) + { + Some((sp, from_expansion)) => { + if from_expansion { + return None; + } + sp + } + None => item.attr_span(cx.tcx), + }; + let (explicit_span, from_expansion) = source_span_for_markdown_range( cx.tcx, doc, &offset_explicit_range(doc, link_range, open, close), &item.attrs.doc_strings, )?; - let display_span = source_span_for_markdown_range( + if from_expansion { + return None; + } + let (display_span, _) = source_span_for_markdown_range( cx.tcx, doc, resolvable_link_range, @@ -206,21 +217,32 @@ fn check_reference_redundancy( if dest_res == display_res { let link_span = - source_span_for_markdown_range(cx.tcx, doc, &link_range, &item.attrs.doc_strings) - .unwrap_or(item.attr_span(cx.tcx)); - let explicit_span = source_span_for_markdown_range( + match source_span_for_markdown_range(cx.tcx, doc, &link_range, &item.attrs.doc_strings) + { + Some((sp, from_expansion)) => { + if from_expansion { + return None; + } + sp + } + None => item.attr_span(cx.tcx), + }; + let (explicit_span, from_expansion) = source_span_for_markdown_range( cx.tcx, doc, &offset_explicit_range(doc, link_range.clone(), b'[', b']'), &item.attrs.doc_strings, )?; - let display_span = source_span_for_markdown_range( + if from_expansion { + return None; + } + let (display_span, _) = source_span_for_markdown_range( cx.tcx, doc, resolvable_link_range, &item.attrs.doc_strings, )?; - let def_span = source_span_for_markdown_range( + let (def_span, _) = source_span_for_markdown_range( cx.tcx, doc, &offset_reference_def_range(doc, dest, link_range), diff --git a/src/librustdoc/passes/lint/unescaped_backticks.rs b/src/librustdoc/passes/lint/unescaped_backticks.rs index 88f4c3ac1cd79..7f5643f4ba814 100644 --- a/src/librustdoc/passes/lint/unescaped_backticks.rs +++ b/src/librustdoc/passes/lint/unescaped_backticks.rs @@ -42,13 +42,15 @@ pub(crate) fn visit_item(cx: &DocContext<'_>, item: &Item, hir_id: HirId, dox: & // If we can't get a span of the backtick, because it is in a `#[doc = ""]` attribute, // use the span of the entire attribute as a fallback. - let span = source_span_for_markdown_range( + let span = match source_span_for_markdown_range( tcx, dox, &(backtick_index..backtick_index + 1), &item.attrs.doc_strings, - ) - .unwrap_or_else(|| item.attr_span(tcx)); + ) { + Some((sp, _)) => sp, + None => item.attr_span(tcx), + }; tcx.node_span_lint(crate::lint::UNESCAPED_BACKTICKS, hir_id, span, |lint| { lint.primary_message("unescaped backtick"); @@ -419,7 +421,7 @@ fn suggest_insertion( /// Maximum bytes of context to show around the insertion. const CONTEXT_MAX_LEN: usize = 80; - if let Some(span) = source_span_for_markdown_range( + if let Some((span, _)) = source_span_for_markdown_range( cx.tcx, dox, &(insert_index..insert_index), From a0d64177f023d0f141044dd57eace3ca386a36f1 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Tue, 27 May 2025 15:17:22 +0200 Subject: [PATCH 05/23] Add ui test for `redundant_explicit_links` rustdoc lint for items coming from expansion --- .../redundant_explicit_links-expansion.rs | 28 +++++++++++++++++++ .../redundant_explicit_links-expansion.stderr | 23 +++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 tests/rustdoc-ui/lints/redundant_explicit_links-expansion.rs create mode 100644 tests/rustdoc-ui/lints/redundant_explicit_links-expansion.stderr diff --git a/tests/rustdoc-ui/lints/redundant_explicit_links-expansion.rs b/tests/rustdoc-ui/lints/redundant_explicit_links-expansion.rs new file mode 100644 index 0000000000000..8cb75ba4e18ad --- /dev/null +++ b/tests/rustdoc-ui/lints/redundant_explicit_links-expansion.rs @@ -0,0 +1,28 @@ +// This is a regression test for . +// If the link is generated from expansion, we should not emit the lint. + +#![deny(rustdoc::redundant_explicit_links)] + +macro_rules! mac1 { + () => { + "provided by a [`BufferProvider`](crate::BufferProvider)." + }; +} + +macro_rules! mac2 { + () => { + #[doc = mac1!()] + pub struct BufferProvider; + } +} + +// Should not lint. +#[doc = mac1!()] +pub struct Foo; + +// Should not lint. +mac2!{} + +#[doc = "provided by a [`BufferProvider`](crate::BufferProvider)."] +//~^ ERROR: redundant_explicit_links +pub struct Bla; diff --git a/tests/rustdoc-ui/lints/redundant_explicit_links-expansion.stderr b/tests/rustdoc-ui/lints/redundant_explicit_links-expansion.stderr new file mode 100644 index 0000000000000..0a38ec2aa6a42 --- /dev/null +++ b/tests/rustdoc-ui/lints/redundant_explicit_links-expansion.stderr @@ -0,0 +1,23 @@ +error: redundant explicit link target + --> $DIR/redundant_explicit_links-expansion.rs:26:43 + | +LL | #[doc = "provided by a [`BufferProvider`](crate::BufferProvider)."] + | ---------------- ^^^^^^^^^^^^^^^^^^^^^ explicit target is redundant + | | + | because label contains path that resolves to same destination + | + = note: when a link's destination is not specified, + the label is used to resolve intra-doc links +note: the lint level is defined here + --> $DIR/redundant_explicit_links-expansion.rs:4:9 + | +LL | #![deny(rustdoc::redundant_explicit_links)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +help: remove explicit link target + | +LL - #[doc = "provided by a [`BufferProvider`](crate::BufferProvider)."] +LL + #[doc = "provided by a [`BufferProvider`]."] + | + +error: aborting due to 1 previous error + From 987c2ffd55fdff2cc7945adaec6468202e2d2486 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Tue, 27 May 2025 16:16:18 +0200 Subject: [PATCH 06/23] Update clippy source code to changes on `source_span_for_markdown_range` --- src/tools/clippy/clippy_lints/src/doc/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/tools/clippy/clippy_lints/src/doc/mod.rs b/src/tools/clippy/clippy_lints/src/doc/mod.rs index e0fc2fd93474f..d38588bb799a4 100644 --- a/src/tools/clippy/clippy_lints/src/doc/mod.rs +++ b/src/tools/clippy/clippy_lints/src/doc/mod.rs @@ -765,8 +765,8 @@ impl Fragments<'_> { /// get the span for the markdown range. Note that this function is not cheap, use it with /// caution. #[must_use] - fn span(&self, cx: &LateContext<'_>, range: Range) -> Option { - source_span_for_markdown_range(cx.tcx, self.doc, &range, self.fragments) + fn span(self, cx: &LateContext<'_>, range: Range) -> Option { + source_span_for_markdown_range(cx.tcx, self.doc, &range, self.fragments).map(|(sp, _)| sp) } } From 78cbcaffeadcb85e4ea5d347010b13b5c698cbbd Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Tue, 3 Jun 2025 23:00:16 +0200 Subject: [PATCH 07/23] Update tests to work with new DocFragment field and `redundant_explicit_links` new API --- compiler/rustc_resolve/src/rustdoc/tests.rs | 6 ++++-- src/librustdoc/clean/types/tests.rs | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_resolve/src/rustdoc/tests.rs b/compiler/rustc_resolve/src/rustdoc/tests.rs index 221ac907e7c9c..6a98ae0663048 100644 --- a/compiler/rustc_resolve/src/rustdoc/tests.rs +++ b/compiler/rustc_resolve/src/rustdoc/tests.rs @@ -10,7 +10,7 @@ use super::{DocFragment, DocFragmentKind, source_span_for_markdown_range_inner}; fn single_backtick() { let sm = SourceMap::new(FilePathMapping::empty()); sm.new_source_file(PathBuf::from("foo.rs").into(), r#"#[doc = "`"] fn foo() {}"#.to_string()); - let span = source_span_for_markdown_range_inner( + let (span, _) = source_span_for_markdown_range_inner( &sm, "`", &(0..1), @@ -20,6 +20,7 @@ fn single_backtick() { kind: DocFragmentKind::RawDoc, doc: sym::empty, // unused placeholder indent: 0, + from_expansion: false, }], ) .unwrap(); @@ -32,7 +33,7 @@ fn utf8() { // regression test for https://github.com/rust-lang/rust/issues/141665 let sm = SourceMap::new(FilePathMapping::empty()); sm.new_source_file(PathBuf::from("foo.rs").into(), r#"#[doc = "⚠"] fn foo() {}"#.to_string()); - let span = source_span_for_markdown_range_inner( + let (span, _) = source_span_for_markdown_range_inner( &sm, "⚠", &(0..3), @@ -42,6 +43,7 @@ fn utf8() { kind: DocFragmentKind::RawDoc, doc: sym::empty, // unused placeholder indent: 0, + from_expansion: false, }], ) .unwrap(); diff --git a/src/librustdoc/clean/types/tests.rs b/src/librustdoc/clean/types/tests.rs index 7ff5026150b16..9499507b2c0f9 100644 --- a/src/librustdoc/clean/types/tests.rs +++ b/src/librustdoc/clean/types/tests.rs @@ -10,6 +10,7 @@ fn create_doc_fragment(s: &str) -> Vec { doc: Symbol::intern(s), kind: DocFragmentKind::SugaredDoc, indent: 0, + from_expansion: false, }] } From 3b5525bc420551c9c32ad3b5b6c8d673dd25da0d Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Tue, 10 Jun 2025 14:45:10 +0200 Subject: [PATCH 08/23] Improve code and documentation --- compiler/rustc_resolve/src/rustdoc.rs | 39 ++++++++++++------- .../passes/lint/redundant_explicit_links.rs | 34 ++++++++++------ .../redundant_explicit_links-expansion.rs | 14 ++++++- .../redundant_explicit_links-expansion.stderr | 20 +++++++++- 4 files changed, 77 insertions(+), 30 deletions(-) diff --git a/compiler/rustc_resolve/src/rustdoc.rs b/compiler/rustc_resolve/src/rustdoc.rs index 2d84178bede90..3fe5db8ca5452 100644 --- a/compiler/rustc_resolve/src/rustdoc.rs +++ b/compiler/rustc_resolve/src/rustdoc.rs @@ -49,7 +49,7 @@ pub struct DocFragment { pub doc: Symbol, pub kind: DocFragmentKind, pub indent: usize, - /// Because we temper with the spans context, this information cannot be correctly retrieved + /// Because we tamper with the spans context, this information cannot be correctly retrieved /// later on. So instead, we compute it and store it here. pub from_expansion: bool, } @@ -509,16 +509,20 @@ fn collect_link_data<'input, F: BrokenLinkCallback<'input>>( display_text.map(String::into_boxed_str) } -/// Returns a span encompassing all the document fragments. +/// Returns a tuple containing a span encompassing all the document fragments and a boolean that is +/// `true` if any of the fragments are from a macro expansion. pub fn span_of_fragments_with_expansion(fragments: &[DocFragment]) -> Option<(Span, bool)> { - let Some(first_fragment) = fragments.first() else { return None }; + let (first_fragment, last_fragment) = match fragments { + [] => return None, + [first, .., last] => (first, last), + [first] => (first, first), + }; if first_fragment.span == DUMMY_SP { return None; } - let last_fragment = fragments.last().expect("no doc strings provided"); Some(( first_fragment.span.to(last_fragment.span), - first_fragment.from_expansion || last_fragment.from_expansion, + fragments.iter().any(|frag| frag.from_expansion), )) } @@ -538,12 +542,16 @@ pub fn span_of_fragments(fragments: &[DocFragment]) -> Option { /// This method will return `Some` only if one of the following is true: /// /// - The doc is made entirely from sugared doc comments, which cannot contain escapes -/// - The doc is entirely from a single doc fragment with a string literal exactly equal to `markdown`. +/// - The doc is entirely from a single doc fragment with a string literal exactly equal to +/// `markdown`. /// - The doc comes from `include_str!` -/// - The doc includes exactly one substring matching `markdown[md_range]` which is contained in a single doc fragment. +/// - The doc includes exactly one substring matching `markdown[md_range]` which is contained in a +/// single doc fragment. +/// +/// This function is defined in the compiler so it can be used by both `rustdoc` and `clippy`. /// -/// This function is defined in the compiler so it can be used by -/// both `rustdoc` and `clippy`. +/// It returns a tuple containing a span encompassing all the document fragments and a boolean that +/// is `true` if any of the *matched* fragments are from a macro expansion. pub fn source_span_for_markdown_range( tcx: TyCtxt<'_>, markdown: &str, @@ -678,12 +686,13 @@ pub fn source_span_for_markdown_range_inner( } } - let (span, from_expansion) = span_of_fragments_with_expansion(fragments)?; + let (span, _) = span_of_fragments_with_expansion(fragments)?; + let src_span = span.from_inner(InnerSpan::new( + md_range.start + start_bytes, + md_range.end + start_bytes + end_bytes, + )); Some(( - span.from_inner(InnerSpan::new( - md_range.start + start_bytes, - md_range.end + start_bytes + end_bytes, - )), - from_expansion, + src_span, + fragments.iter().any(|frag| frag.span.overlaps(src_span) && frag.from_expansion), )) } diff --git a/src/librustdoc/passes/lint/redundant_explicit_links.rs b/src/librustdoc/passes/lint/redundant_explicit_links.rs index 0482bc1058f0e..5757b6a974081 100644 --- a/src/librustdoc/passes/lint/redundant_explicit_links.rs +++ b/src/librustdoc/passes/lint/redundant_explicit_links.rs @@ -171,21 +171,26 @@ fn check_inline_or_reference_unknown_redundancy( } None => item.attr_span(cx.tcx), }; - let (explicit_span, from_expansion) = source_span_for_markdown_range( + let (explicit_span, false) = source_span_for_markdown_range( cx.tcx, doc, &offset_explicit_range(doc, link_range, open, close), &item.attrs.doc_strings, - )?; - if from_expansion { + )? + else { + // This `span` comes from macro expansion so skipping it. return None; - } - let (display_span, _) = source_span_for_markdown_range( + }; + let (display_span, false) = source_span_for_markdown_range( cx.tcx, doc, resolvable_link_range, &item.attrs.doc_strings, - )?; + )? + else { + // This `span` comes from macro expansion so skipping it. + return None; + }; cx.tcx.node_span_lint(crate::lint::REDUNDANT_EXPLICIT_LINKS, hir_id, explicit_span, |lint| { lint.primary_message("redundant explicit link target") @@ -227,21 +232,26 @@ fn check_reference_redundancy( } None => item.attr_span(cx.tcx), }; - let (explicit_span, from_expansion) = source_span_for_markdown_range( + let (explicit_span, false) = source_span_for_markdown_range( cx.tcx, doc, &offset_explicit_range(doc, link_range.clone(), b'[', b']'), &item.attrs.doc_strings, - )?; - if from_expansion { + )? + else { + // This `span` comes from macro expansion so skipping it. return None; - } - let (display_span, _) = source_span_for_markdown_range( + }; + let (display_span, false) = source_span_for_markdown_range( cx.tcx, doc, resolvable_link_range, &item.attrs.doc_strings, - )?; + )? + else { + // This `span` comes from macro expansion so skipping it. + return None; + }; let (def_span, _) = source_span_for_markdown_range( cx.tcx, doc, diff --git a/tests/rustdoc-ui/lints/redundant_explicit_links-expansion.rs b/tests/rustdoc-ui/lints/redundant_explicit_links-expansion.rs index 8cb75ba4e18ad..2e42a0a5c5d61 100644 --- a/tests/rustdoc-ui/lints/redundant_explicit_links-expansion.rs +++ b/tests/rustdoc-ui/lints/redundant_explicit_links-expansion.rs @@ -16,6 +16,12 @@ macro_rules! mac2 { } } +macro_rules! mac3 { + () => { + "Provided by" + }; +} + // Should not lint. #[doc = mac1!()] pub struct Foo; @@ -24,5 +30,11 @@ pub struct Foo; mac2!{} #[doc = "provided by a [`BufferProvider`](crate::BufferProvider)."] -//~^ ERROR: redundant_explicit_links +/// bla +//~^^ ERROR: redundant_explicit_links pub struct Bla; + +#[doc = mac3!()] +/// a [`BufferProvider`](crate::BufferProvider). +//~^ ERROR: redundant_explicit_links +pub fn f() {} diff --git a/tests/rustdoc-ui/lints/redundant_explicit_links-expansion.stderr b/tests/rustdoc-ui/lints/redundant_explicit_links-expansion.stderr index 0a38ec2aa6a42..a81931fb0732d 100644 --- a/tests/rustdoc-ui/lints/redundant_explicit_links-expansion.stderr +++ b/tests/rustdoc-ui/lints/redundant_explicit_links-expansion.stderr @@ -1,5 +1,5 @@ error: redundant explicit link target - --> $DIR/redundant_explicit_links-expansion.rs:26:43 + --> $DIR/redundant_explicit_links-expansion.rs:32:43 | LL | #[doc = "provided by a [`BufferProvider`](crate::BufferProvider)."] | ---------------- ^^^^^^^^^^^^^^^^^^^^^ explicit target is redundant @@ -19,5 +19,21 @@ LL - #[doc = "provided by a [`BufferProvider`](crate::BufferProvider)."] LL + #[doc = "provided by a [`BufferProvider`]."] | -error: aborting due to 1 previous error +error: redundant explicit link target + --> $DIR/redundant_explicit_links-expansion.rs:38:26 + | +LL | /// a [`BufferProvider`](crate::BufferProvider). + | ---------------- ^^^^^^^^^^^^^^^^^^^^^ explicit target is redundant + | | + | because label contains path that resolves to same destination + | + = note: when a link's destination is not specified, + the label is used to resolve intra-doc links +help: remove explicit link target + | +LL - /// a [`BufferProvider`](crate::BufferProvider). +LL + /// a [`BufferProvider`]. + | + +error: aborting due to 2 previous errors From 904652b2d05d967deadf201fc35e8343a822c7a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Wed, 1 May 2024 20:46:06 +0000 Subject: [PATCH 09/23] Suggest cloning `Arc` moved into closure ``` error[E0382]: borrow of moved value: `x` --> $DIR/moves-based-on-type-capture-clause-bad.rs:9:20 | LL | let x = "Hello world!".to_string(); | - move occurs because `x` has type `String`, which does not implement the `Copy` trait LL | thread::spawn(move || { | ------- value moved into closure here LL | println!("{}", x); | - variable moved due to use in closure LL | }); LL | println!("{}", x); | ^ value borrowed here after move | = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider cloning the value before moving it into the closure | LL ~ let value = x.clone(); LL ~ thread::spawn(move || { LL ~ println!("{}", value); | ``` --- .../src/diagnostics/conflict_errors.rs | 17 +++++--- .../src/diagnostics/move_errors.rs | 39 +++++++------------ .../borrowck/borrowck-move-by-capture.stderr | 2 +- ...rowck-move-moved-value-into-closure.stderr | 6 +++ ...ves-based-on-type-capture-clause-bad.fixed | 11 ++++++ .../moves-based-on-type-capture-clause-bad.rs | 1 + ...es-based-on-type-capture-clause-bad.stderr | 8 +++- tests/ui/{ => moves}/no-capture-arc.rs | 0 tests/ui/{ => moves}/no-capture-arc.stderr | 6 +++ tests/ui/moves/no-reuse-move-arc.fixed | 17 ++++++++ tests/ui/{ => moves}/no-reuse-move-arc.rs | 1 + tests/ui/{ => moves}/no-reuse-move-arc.stderr | 8 +++- .../suggestions/option-content-move3.stderr | 2 +- 13 files changed, 85 insertions(+), 33 deletions(-) create mode 100644 tests/ui/moves/moves-based-on-type-capture-clause-bad.fixed rename tests/ui/{ => moves}/no-capture-arc.rs (100%) rename tests/ui/{ => moves}/no-capture-arc.stderr (79%) create mode 100644 tests/ui/moves/no-reuse-move-arc.fixed rename tests/ui/{ => moves}/no-reuse-move-arc.rs (95%) rename tests/ui/{ => moves}/no-reuse-move-arc.stderr (75%) diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index 98dc898db232a..d1dac1c7145df 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -518,11 +518,11 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { } = move_spans && can_suggest_clone { - self.suggest_cloning(err, ty, expr, Some(move_spans)); + self.suggest_cloning(err, place.as_ref(), ty, expr, Some(move_spans)); } else if self.suggest_hoisting_call_outside_loop(err, expr) && can_suggest_clone { // The place where the type moves would be misleading to suggest clone. // #121466 - self.suggest_cloning(err, ty, expr, Some(move_spans)); + self.suggest_cloning(err, place.as_ref(), ty, expr, Some(move_spans)); } } @@ -1224,6 +1224,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { pub(crate) fn suggest_cloning( &self, err: &mut Diag<'_>, + place: PlaceRef<'tcx>, ty: Ty<'tcx>, expr: &'tcx hir::Expr<'tcx>, use_spans: Option>, @@ -1238,7 +1239,13 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { } if self.implements_clone(ty) { - self.suggest_cloning_inner(err, ty, expr); + if self.in_move_closure(expr) { + if let Some(name) = self.describe_place(place) { + self.suggest_clone_of_captured_var_in_move_closure(err, &name, use_spans); + } + } else { + self.suggest_cloning_inner(err, ty, expr); + } } else if let ty::Adt(def, args) = ty.kind() && def.did().as_local().is_some() && def.variants().iter().all(|variant| { @@ -1505,7 +1512,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { if let hir::ExprKind::AddrOf(_, _, borrowed_expr) = expr.kind && let Some(ty) = typeck_results.expr_ty_opt(borrowed_expr) { - self.suggest_cloning(&mut err, ty, borrowed_expr, Some(move_spans)); + self.suggest_cloning(&mut err, place.as_ref(), ty, borrowed_expr, Some(move_spans)); } else if typeck_results.expr_adjustments(expr).first().is_some_and(|adj| { matches!( adj.kind, @@ -1518,7 +1525,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { ) }) && let Some(ty) = typeck_results.expr_ty_opt(expr) { - self.suggest_cloning(&mut err, ty, expr, Some(move_spans)); + self.suggest_cloning(&mut err, place.as_ref(), ty, expr, Some(move_spans)); } } self.buffer_error(err); diff --git a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs index 0394a42ea9c77..caa12d5c86cc7 100644 --- a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs @@ -325,25 +325,17 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { self.cannot_move_out_of(span, &description) } - fn suggest_clone_of_captured_var_in_move_closure( + pub(in crate::diagnostics) fn suggest_clone_of_captured_var_in_move_closure( &self, err: &mut Diag<'_>, - upvar_hir_id: HirId, upvar_name: &str, use_spans: Option>, ) { let tcx = self.infcx.tcx; - let typeck_results = tcx.typeck(self.mir_def_id()); let Some(use_spans) = use_spans else { return }; // We only care about the case where a closure captured a binding. let UseSpans::ClosureUse { args_span, .. } = use_spans else { return }; let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return }; - // Fetch the type of the expression corresponding to the closure-captured binding. - let Some(captured_ty) = typeck_results.node_type_opt(upvar_hir_id) else { return }; - if !self.implements_clone(captured_ty) { - // We only suggest cloning the captured binding if the type can actually be cloned. - return; - }; // Find the closure that captured the binding. let mut expr_finder = FindExprBySpan::new(args_span, tcx); expr_finder.include_closures = true; @@ -396,7 +388,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { .indentation_before(stmt.span) .unwrap_or_else(|| " ".to_string()); err.multipart_suggestion_verbose( - "clone the value before moving it into the closure", + "consider cloning the value before moving it into the closure", vec![ ( stmt.span.shrink_to_lo(), @@ -426,7 +418,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { .indentation_before(closure_expr.span) .unwrap_or_else(|| " ".to_string()); err.multipart_suggestion_verbose( - "clone the value before moving it into the closure", + "consider cloning the value before moving it into the closure", vec![ ( closure_expr.span.shrink_to_lo(), @@ -519,20 +511,12 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { ); let closure_span = tcx.def_span(def_id); - let mut err = self - .cannot_move_out_of(span, &place_description) + self.cannot_move_out_of(span, &place_description) .with_span_label(upvar_span, "captured outer variable") .with_span_label( closure_span, format!("captured by this `{closure_kind}` closure"), - ); - self.suggest_clone_of_captured_var_in_move_closure( - &mut err, - upvar_hir_id, - &upvar_name, - use_spans, - ); - err + ) } _ => { let source = self.borrowed_content_source(deref_base); @@ -593,7 +577,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { }; if let Some(expr) = self.find_expr(span) { - self.suggest_cloning(err, place_ty, expr, None); + self.suggest_cloning(err, move_from.as_ref(), place_ty, expr, None); } err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label { @@ -625,7 +609,13 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { }; if let Some(expr) = self.find_expr(use_span) { - self.suggest_cloning(err, place_ty, expr, Some(use_spans)); + self.suggest_cloning( + err, + original_path.as_ref(), + place_ty, + expr, + Some(use_spans), + ); } err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label { @@ -828,7 +818,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { let place_desc = &format!("`{}`", self.local_names[*local].unwrap()); if let Some(expr) = self.find_expr(binding_span) { - self.suggest_cloning(err, bind_to.ty, expr, None); + let local_place: PlaceRef<'tcx> = (*local).into(); + self.suggest_cloning(err, local_place, bind_to.ty, expr, None); } err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label { diff --git a/tests/ui/borrowck/borrowck-move-by-capture.stderr b/tests/ui/borrowck/borrowck-move-by-capture.stderr index 9915acfe06537..58d5e90e990a2 100644 --- a/tests/ui/borrowck/borrowck-move-by-capture.stderr +++ b/tests/ui/borrowck/borrowck-move-by-capture.stderr @@ -12,7 +12,7 @@ LL | let _h = to_fn_once(move || -> isize { *bar }); | | move occurs because `bar` has type `Box`, which does not implement the `Copy` trait | `bar` is moved here | -help: clone the value before moving it into the closure +help: consider cloning the value before moving it into the closure | LL ~ let value = bar.clone(); LL ~ let _h = to_fn_once(move || -> isize { value }); diff --git a/tests/ui/borrowck/borrowck-move-moved-value-into-closure.stderr b/tests/ui/borrowck/borrowck-move-moved-value-into-closure.stderr index 6a77d86f250a1..5ddc6a6d82d85 100644 --- a/tests/ui/borrowck/borrowck-move-moved-value-into-closure.stderr +++ b/tests/ui/borrowck/borrowck-move-moved-value-into-closure.stderr @@ -12,6 +12,12 @@ LL | call_f(move|| { *t + 1 }); | ^^^^^^ -- use occurs due to use in closure | | | value used here after move + | +help: consider cloning the value before moving it into the closure + | +LL ~ let value = t.clone(); +LL ~ call_f(move|| { value + 1 }); + | error: aborting due to 1 previous error diff --git a/tests/ui/moves/moves-based-on-type-capture-clause-bad.fixed b/tests/ui/moves/moves-based-on-type-capture-clause-bad.fixed new file mode 100644 index 0000000000000..04a183ca96be4 --- /dev/null +++ b/tests/ui/moves/moves-based-on-type-capture-clause-bad.fixed @@ -0,0 +1,11 @@ +//@ run-rustfix +use std::thread; + +fn main() { + let x = "Hello world!".to_string(); + let value = x.clone(); + thread::spawn(move || { + println!("{}", value); + }); + println!("{}", x); //~ ERROR borrow of moved value +} diff --git a/tests/ui/moves/moves-based-on-type-capture-clause-bad.rs b/tests/ui/moves/moves-based-on-type-capture-clause-bad.rs index 9d7277c1c2499..c9a7f2c8ed805 100644 --- a/tests/ui/moves/moves-based-on-type-capture-clause-bad.rs +++ b/tests/ui/moves/moves-based-on-type-capture-clause-bad.rs @@ -1,3 +1,4 @@ +//@ run-rustfix use std::thread; fn main() { diff --git a/tests/ui/moves/moves-based-on-type-capture-clause-bad.stderr b/tests/ui/moves/moves-based-on-type-capture-clause-bad.stderr index c2b9aeab23748..17049fe67318d 100644 --- a/tests/ui/moves/moves-based-on-type-capture-clause-bad.stderr +++ b/tests/ui/moves/moves-based-on-type-capture-clause-bad.stderr @@ -1,5 +1,5 @@ error[E0382]: borrow of moved value: `x` - --> $DIR/moves-based-on-type-capture-clause-bad.rs:8:20 + --> $DIR/moves-based-on-type-capture-clause-bad.rs:9:20 | LL | let x = "Hello world!".to_string(); | - move occurs because `x` has type `String`, which does not implement the `Copy` trait @@ -12,6 +12,12 @@ LL | println!("{}", x); | ^ value borrowed here after move | = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info) +help: consider cloning the value before moving it into the closure + | +LL ~ let value = x.clone(); +LL ~ thread::spawn(move || { +LL ~ println!("{}", value); + | error: aborting due to 1 previous error diff --git a/tests/ui/no-capture-arc.rs b/tests/ui/moves/no-capture-arc.rs similarity index 100% rename from tests/ui/no-capture-arc.rs rename to tests/ui/moves/no-capture-arc.rs diff --git a/tests/ui/no-capture-arc.stderr b/tests/ui/moves/no-capture-arc.stderr similarity index 79% rename from tests/ui/no-capture-arc.stderr rename to tests/ui/moves/no-capture-arc.stderr index 9c1f5c65066fa..6d4a867fa88d0 100644 --- a/tests/ui/no-capture-arc.stderr +++ b/tests/ui/moves/no-capture-arc.stderr @@ -13,6 +13,12 @@ LL | assert_eq!((*arc_v)[2], 3); | ^^^^^ value borrowed here after move | = note: borrow occurs due to deref coercion to `Vec` +help: consider cloning the value before moving it into the closure + | +LL ~ let value = arc_v.clone(); +LL ~ thread::spawn(move|| { +LL ~ assert_eq!((*value)[3], 4); + | error: aborting due to 1 previous error diff --git a/tests/ui/moves/no-reuse-move-arc.fixed b/tests/ui/moves/no-reuse-move-arc.fixed new file mode 100644 index 0000000000000..a5dac8cc14bf2 --- /dev/null +++ b/tests/ui/moves/no-reuse-move-arc.fixed @@ -0,0 +1,17 @@ +//@ run-rustfix +use std::sync::Arc; +use std::thread; + +fn main() { + let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + let arc_v = Arc::new(v); + + let value = arc_v.clone(); + thread::spawn(move|| { + assert_eq!((*value)[3], 4); + }); + + assert_eq!((*arc_v)[2], 3); //~ ERROR borrow of moved value: `arc_v` + + println!("{:?}", *arc_v); +} diff --git a/tests/ui/no-reuse-move-arc.rs b/tests/ui/moves/no-reuse-move-arc.rs similarity index 95% rename from tests/ui/no-reuse-move-arc.rs rename to tests/ui/moves/no-reuse-move-arc.rs index 9c957a4e01b41..0d67aa56489ce 100644 --- a/tests/ui/no-reuse-move-arc.rs +++ b/tests/ui/moves/no-reuse-move-arc.rs @@ -1,3 +1,4 @@ +//@ run-rustfix use std::sync::Arc; use std::thread; diff --git a/tests/ui/no-reuse-move-arc.stderr b/tests/ui/moves/no-reuse-move-arc.stderr similarity index 75% rename from tests/ui/no-reuse-move-arc.stderr rename to tests/ui/moves/no-reuse-move-arc.stderr index 61f4837dc0e66..aff979af905e4 100644 --- a/tests/ui/no-reuse-move-arc.stderr +++ b/tests/ui/moves/no-reuse-move-arc.stderr @@ -1,5 +1,5 @@ error[E0382]: borrow of moved value: `arc_v` - --> $DIR/no-reuse-move-arc.rs:12:18 + --> $DIR/no-reuse-move-arc.rs:13:18 | LL | let arc_v = Arc::new(v); | ----- move occurs because `arc_v` has type `Arc>`, which does not implement the `Copy` trait @@ -13,6 +13,12 @@ LL | assert_eq!((*arc_v)[2], 3); | ^^^^^ value borrowed here after move | = note: borrow occurs due to deref coercion to `Vec` +help: consider cloning the value before moving it into the closure + | +LL ~ let value = arc_v.clone(); +LL ~ thread::spawn(move|| { +LL ~ assert_eq!((*value)[3], 4); + | error: aborting due to 1 previous error diff --git a/tests/ui/suggestions/option-content-move3.stderr b/tests/ui/suggestions/option-content-move3.stderr index a20dcce1ee310..faaf8a9df9d72 100644 --- a/tests/ui/suggestions/option-content-move3.stderr +++ b/tests/ui/suggestions/option-content-move3.stderr @@ -79,7 +79,7 @@ LL | let x = var; | variable moved due to use in closure | move occurs because `var` has type `NotCopyableButCloneable`, which does not implement the `Copy` trait | -help: clone the value before moving it into the closure +help: consider cloning the value before moving it into the closure | LL ~ { LL + let value = var.clone(); From f90893963063b16846fa1715b220e98e749e7b9d Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Wed, 25 Jun 2025 11:23:47 +0530 Subject: [PATCH 10/23] rename run_always to run_in_dry_run --- src/bootstrap/src/core/build_steps/setup.rs | 2 +- src/bootstrap/src/core/config/config.rs | 14 +++++++------- src/bootstrap/src/core/metadata.rs | 2 +- src/bootstrap/src/core/sanity.rs | 4 ++-- src/bootstrap/src/lib.rs | 8 ++++---- src/bootstrap/src/utils/channel.rs | 11 +++++++---- src/bootstrap/src/utils/exec.rs | 8 ++++---- src/bootstrap/src/utils/execution_context.rs | 2 +- 8 files changed, 27 insertions(+), 24 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/setup.rs b/src/bootstrap/src/core/build_steps/setup.rs index 9ce81ff9a229f..37fc85518e0ea 100644 --- a/src/bootstrap/src/core/build_steps/setup.rs +++ b/src/bootstrap/src/core/build_steps/setup.rs @@ -272,7 +272,7 @@ fn rustup_installed(builder: &Builder<'_>) -> bool { let mut rustup = command("rustup"); rustup.arg("--version"); - rustup.allow_failure().run_always().run_capture_stdout(builder).is_success() + rustup.allow_failure().run_in_dry_run().run_capture_stdout(builder).is_success() } fn stage_dir_exists(stage_path: &str) -> bool { diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index d3393afcae05a..2c07d5b89f41d 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -809,7 +809,7 @@ impl Config { config.initial_sysroot = t!(PathBuf::from_str( command(&config.initial_rustc) .args(["--print", "sysroot"]) - .run_always() + .run_in_dry_run() .run_capture_stdout(&config) .stdout() .trim() @@ -1385,11 +1385,11 @@ impl Config { // all the git commands below are actually executed, because some follow-up code // in bootstrap might depend on the submodules being checked out. Furthermore, not all // the command executions below work with an empty output (produced during dry run). - // Therefore, all commands below are marked with `run_always()`, so that they also run in + // Therefore, all commands below are marked with `run_in_dry_run()`, so that they also run in // dry run mode. let submodule_git = || { let mut cmd = helpers::git(Some(&absolute_path)); - cmd.run_always(); + cmd.run_in_dry_run(); cmd }; @@ -1399,7 +1399,7 @@ impl Config { let checked_out_hash = checked_out_hash.trim_end(); // Determine commit that the submodule *should* have. let recorded = helpers::git(Some(&self.src)) - .run_always() + .run_in_dry_run() .args(["ls-tree", "HEAD"]) .arg(relative_path) .run_capture_stdout(self) @@ -1419,7 +1419,7 @@ impl Config { helpers::git(Some(&self.src)) .allow_failure() - .run_always() + .run_in_dry_run() .args(["submodule", "-q", "sync"]) .arg(relative_path) .run(self); @@ -1430,12 +1430,12 @@ impl Config { // even though that has no relation to the upstream for the submodule. let current_branch = helpers::git(Some(&self.src)) .allow_failure() - .run_always() + .run_in_dry_run() .args(["symbolic-ref", "--short", "HEAD"]) .run_capture(self); let mut git = helpers::git(Some(&self.src)).allow_failure(); - git.run_always(); + git.run_in_dry_run(); if current_branch.is_success() { // If there is a tag named after the current branch, git will try to disambiguate by prepending `heads/` to the branch name. // This syntax isn't accepted by `branch.{branch}`. Strip it. diff --git a/src/bootstrap/src/core/metadata.rs b/src/bootstrap/src/core/metadata.rs index 2706aba5ffc8d..c79fbbeb55cc1 100644 --- a/src/bootstrap/src/core/metadata.rs +++ b/src/bootstrap/src/core/metadata.rs @@ -88,7 +88,7 @@ fn workspace_members(build: &Build) -> Vec { .arg("--no-deps") .arg("--manifest-path") .arg(build.src.join(manifest_path)); - let metadata_output = cargo.run_always().run_capture_stdout(build).stdout(); + let metadata_output = cargo.run_in_dry_run().run_capture_stdout(build).stdout(); let Output { packages, .. } = t!(serde_json::from_str(&metadata_output)); packages }; diff --git a/src/bootstrap/src/core/sanity.rs b/src/bootstrap/src/core/sanity.rs index 493f73b21fe15..958058d982bac 100644 --- a/src/bootstrap/src/core/sanity.rs +++ b/src/bootstrap/src/core/sanity.rs @@ -202,7 +202,7 @@ than building it. let stage0_supported_target_list: HashSet = command(&build.config.initial_rustc) .args(["--print", "target-list"]) - .run_always() + .run_in_dry_run() .run_capture_stdout(&build) .stdout() .lines() @@ -366,7 +366,7 @@ than building it. // Cygwin. The Cygwin build does not have generators for Visual // Studio, so detect that here and error. let out = - command("cmake").arg("--help").run_always().run_capture_stdout(&build).stdout(); + command("cmake").arg("--help").run_in_dry_run().run_capture_stdout(&build).stdout(); if !out.contains("Visual Studio") { panic!( " diff --git a/src/bootstrap/src/lib.rs b/src/bootstrap/src/lib.rs index f44fe4548a1db..13a819e43603a 100644 --- a/src/bootstrap/src/lib.rs +++ b/src/bootstrap/src/lib.rs @@ -383,7 +383,7 @@ impl Build { let in_tree_gcc_info = config.in_tree_gcc_info.clone(); let initial_target_libdir = command(&config.initial_rustc) - .run_always() + .run_in_dry_run() .args(["--print", "target-libdir"]) .run_capture_stdout(&config) .stdout() @@ -490,7 +490,7 @@ impl Build { // If local-rust is the same major.minor as the current version, then force a // local-rebuild let local_version_verbose = command(&build.initial_rustc) - .run_always() + .run_in_dry_run() .args(["--version", "--verbose"]) .run_capture_stdout(&build) .stdout(); @@ -949,7 +949,7 @@ impl Build { static SYSROOT_CACHE: OnceLock = OnceLock::new(); SYSROOT_CACHE.get_or_init(|| { command(&self.initial_rustc) - .run_always() + .run_in_dry_run() .args(["--print", "sysroot"]) .run_capture_stdout(self) .stdout() @@ -1512,7 +1512,7 @@ impl Build { "refs/remotes/origin/{}..HEAD", self.config.stage0_metadata.config.nightly_branch )) - .run_always() + .run_in_dry_run() .run_capture(self) .stdout() }); diff --git a/src/bootstrap/src/utils/channel.rs b/src/bootstrap/src/utils/channel.rs index b28ab57377408..16aa9ba0585b2 100644 --- a/src/bootstrap/src/utils/channel.rs +++ b/src/bootstrap/src/utils/channel.rs @@ -66,19 +66,22 @@ impl GitInfo { .arg("-1") .arg("--date=short") .arg("--pretty=format:%cd") - .run_always() + .run_in_dry_run() .start_capture_stdout(&exec_ctx); let mut git_hash_cmd = helpers::git(Some(dir)); - let ver_hash = - git_hash_cmd.arg("rev-parse").arg("HEAD").run_always().start_capture_stdout(&exec_ctx); + let ver_hash = git_hash_cmd + .arg("rev-parse") + .arg("HEAD") + .run_in_dry_run() + .start_capture_stdout(&exec_ctx); let mut git_short_hash_cmd = helpers::git(Some(dir)); let short_ver_hash = git_short_hash_cmd .arg("rev-parse") .arg("--short=9") .arg("HEAD") - .run_always() + .run_in_dry_run() .start_capture_stdout(&exec_ctx); GitInfo::Present(Some(Info { diff --git a/src/bootstrap/src/utils/exec.rs b/src/bootstrap/src/utils/exec.rs index 78b28ac182823..a7b92441d747e 100644 --- a/src/bootstrap/src/utils/exec.rs +++ b/src/bootstrap/src/utils/exec.rs @@ -66,7 +66,7 @@ pub struct BootstrapCommand { command: Command, pub failure_behavior: BehaviorOnFailure, // Run the command even during dry run - pub run_always: bool, + pub run_in_dry_run: bool, // This field makes sure that each command is executed (or disarmed) before it is dropped, // to avoid forgetting to execute a command. drop_bomb: DropBomb, @@ -138,8 +138,8 @@ impl<'a> BootstrapCommand { Self { failure_behavior: BehaviorOnFailure::Ignore, ..self } } - pub fn run_always(&mut self) -> &mut Self { - self.run_always = true; + pub fn run_in_dry_run(&mut self) -> &mut Self { + self.run_in_dry_run = true; self } @@ -228,7 +228,7 @@ impl From for BootstrapCommand { Self { command, failure_behavior: BehaviorOnFailure::Exit, - run_always: false, + run_in_dry_run: false, drop_bomb: DropBomb::arm(program), } } diff --git a/src/bootstrap/src/utils/execution_context.rs b/src/bootstrap/src/utils/execution_context.rs index 5b9fef3f8248b..66a4be9252e4e 100644 --- a/src/bootstrap/src/utils/execution_context.rs +++ b/src/bootstrap/src/utils/execution_context.rs @@ -93,7 +93,7 @@ impl ExecutionContext { let created_at = command.get_created_location(); let executed_at = std::panic::Location::caller(); - if self.dry_run() && !command.run_always { + if self.dry_run() && !command.run_in_dry_run { return DeferredCommand { process: None, stdout, stderr, command, executed_at }; } From 4f80053779e7006e118e7b78f2b513c62c5b8c75 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Wed, 25 Jun 2025 15:29:31 +0200 Subject: [PATCH 11/23] Update `browser-ui-test` version to `0.20.7` --- .../docker/host-x86_64/x86_64-gnu-tools/browser-ui-test.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ci/docker/host-x86_64/x86_64-gnu-tools/browser-ui-test.version b/src/ci/docker/host-x86_64/x86_64-gnu-tools/browser-ui-test.version index e15121e0f3162..f8d54d445576b 100644 --- a/src/ci/docker/host-x86_64/x86_64-gnu-tools/browser-ui-test.version +++ b/src/ci/docker/host-x86_64/x86_64-gnu-tools/browser-ui-test.version @@ -1 +1 @@ -0.20.6 \ No newline at end of file +0.20.7 \ No newline at end of file From b75b14fc262d6d81a1e54cb8fa67c33b5c2574b2 Mon Sep 17 00:00:00 2001 From: Samuel Tardieu Date: Wed, 25 Jun 2025 17:13:29 +0200 Subject: [PATCH 12/23] Add `sym::macro_pin` diagnostic item for `core::pin::pin!()` --- compiler/rustc_span/src/symbol.rs | 1 + library/core/src/pin.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index c9262d24a1717..aea756048dd20 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1616,6 +1616,7 @@ symbols! { pie, pin, pin_ergonomics, + pin_macro, platform_intrinsics, plugin, plugin_registrar, diff --git a/library/core/src/pin.rs b/library/core/src/pin.rs index ba687434bf102..b6d5f848ef039 100644 --- a/library/core/src/pin.rs +++ b/library/core/src/pin.rs @@ -1935,6 +1935,7 @@ unsafe impl PinCoerceUnsized for *mut T {} #[stable(feature = "pin_macro", since = "1.68.0")] #[rustc_macro_transparency = "semitransparent"] #[allow_internal_unstable(super_let)] +#[rustc_diagnostic_item = "pin_macro"] // `super` gets removed by rustfmt #[rustfmt::skip] pub macro pin($value:expr $(,)?) { From 83044357930a7c55f8d429bd4cd7dcb7426d4b01 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 17 Jun 2025 21:35:11 +0000 Subject: [PATCH 13/23] Compute hard errors without diagnostics in impl_intersection_has_impossible_obligation --- compiler/rustc_infer/src/traits/engine.rs | 3 +- .../src/traits/coherence.rs | 43 +++++++++++-------- tests/crashes/139905.rs | 6 --- 3 files changed, 28 insertions(+), 24 deletions(-) delete mode 100644 tests/crashes/139905.rs diff --git a/compiler/rustc_infer/src/traits/engine.rs b/compiler/rustc_infer/src/traits/engine.rs index 9e51a53ae95fa..9a66bd0574c9d 100644 --- a/compiler/rustc_infer/src/traits/engine.rs +++ b/compiler/rustc_infer/src/traits/engine.rs @@ -19,7 +19,8 @@ pub enum ScrubbedTraitError<'tcx> { TrueError, /// An ambiguity. This goal may hold if further inference is done. Ambiguity, - /// An old-solver-style cycle error, which will fatal. + /// An old-solver-style cycle error, which will fatal. This is not + /// returned by the new solver. Cycle(PredicateObligations<'tcx>), } diff --git a/compiler/rustc_trait_selection/src/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs index 81893cdcc7e68..ce5a4edeaaa06 100644 --- a/compiler/rustc_trait_selection/src/traits/coherence.rs +++ b/compiler/rustc_trait_selection/src/traits/coherence.rs @@ -356,29 +356,38 @@ fn impl_intersection_has_impossible_obligation<'a, 'cx, 'tcx>( return IntersectionHasImpossibleObligations::Yes; } - let ocx = ObligationCtxt::new_with_diagnostics(infcx); + let ocx = ObligationCtxt::new(infcx); ocx.register_obligations(obligations.iter().cloned()); + let hard_errors = ocx.select_where_possible(); + if !hard_errors.is_empty() { + assert!( + hard_errors.iter().all(|e| e.is_true_error()), + "should not have detected ambiguity during first pass" + ); + return IntersectionHasImpossibleObligations::Yes; + } + + // Make a new `ObligationCtxt` and re-prove the ambiguities with a richer + // `FulfillmentError`. This is so that we can detect overflowing obligations + // without needing to run the `BestObligation` visitor on true errors. + let ambiguities = ocx.into_pending_obligations(); + let ocx = ObligationCtxt::new_with_diagnostics(infcx); + ocx.register_obligations(ambiguities); let errors_and_ambiguities = ocx.select_all_or_error(); // We only care about the obligations that are *definitely* true errors. // Ambiguities do not prove the disjointness of two impls. let (errors, ambiguities): (Vec<_>, Vec<_>) = errors_and_ambiguities.into_iter().partition(|error| error.is_true_error()); - - if errors.is_empty() { - IntersectionHasImpossibleObligations::No { - overflowing_predicates: ambiguities - .into_iter() - .filter(|error| { - matches!( - error.code, - FulfillmentErrorCode::Ambiguity { overflow: Some(true) } - ) - }) - .map(|e| infcx.resolve_vars_if_possible(e.obligation.predicate)) - .collect(), - } - } else { - IntersectionHasImpossibleObligations::Yes + assert!(errors.is_empty(), "should not have ambiguities during second pass"); + + IntersectionHasImpossibleObligations::No { + overflowing_predicates: ambiguities + .into_iter() + .filter(|error| { + matches!(error.code, FulfillmentErrorCode::Ambiguity { overflow: Some(true) }) + }) + .map(|e| infcx.resolve_vars_if_possible(e.obligation.predicate)) + .collect(), } } else { for obligation in obligations { diff --git a/tests/crashes/139905.rs b/tests/crashes/139905.rs deleted file mode 100644 index 7da622aaabac6..0000000000000 --- a/tests/crashes/139905.rs +++ /dev/null @@ -1,6 +0,0 @@ -//@ known-bug: #139905 -trait a {} -impl a<{}> for () {} -trait c {} -impl c for () where (): a {} -impl c for () {} From 44254c8cd79810fb2ff575d88e75c979bb7f1fc4 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 17 Jun 2025 17:55:06 +0000 Subject: [PATCH 14/23] Remove some glob imports from the type system --- .../src/diagnostics/region_errors.rs | 5 +- .../src/type_check/constraint_conversion.rs | 4 +- compiler/rustc_borrowck/src/type_check/mod.rs | 4 +- .../src/check/compare_impl_item.rs | 6 +- .../rustc_hir_analysis/src/check/wfcheck.rs | 10 ++- .../src/coherence/builtin.rs | 4 +- compiler/rustc_hir_typeck/src/callee.rs | 12 ++- compiler/rustc_hir_typeck/src/coercion.rs | 8 +- compiler/rustc_hir_typeck/src/expr.rs | 5 +- .../rustc_hir_typeck/src/fn_ctxt/checks.rs | 9 +- compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs | 8 +- .../rustc_hir_typeck/src/method/confirm.rs | 14 ++- compiler/rustc_hir_typeck/src/method/mod.rs | 9 +- compiler/rustc_hir_typeck/src/method/probe.rs | 19 ++-- .../rustc_hir_typeck/src/method/suggest.rs | 10 ++- compiler/rustc_hir_typeck/src/pat.rs | 4 +- compiler/rustc_infer/src/infer/mod.rs | 56 ++++++------ .../src/infer/outlives/obligations.rs | 2 +- .../src/infer/region_constraints/mod.rs | 4 +- compiler/rustc_infer/src/infer/resolve.rs | 15 ++-- compiler/rustc_infer/src/traits/mod.rs | 2 - .../error_reporting/infer/need_type_info.rs | 8 +- .../infer/nice_region_error/mod.rs | 7 +- .../trait_impl_difference.rs | 6 +- .../src/error_reporting/infer/region.rs | 87 +++++++++++-------- .../traits/fulfillment_errors.rs | 14 +-- .../src/traits/fulfill.rs | 6 +- .../src/traits/project.rs | 21 +++-- .../src/traits/select/confirmation.rs | 33 ++++--- .../src/traits/select/mod.rs | 24 ++--- .../traits/specialize/specialization_graph.rs | 8 +- compiler/rustc_traits/src/codegen.rs | 4 +- 32 files changed, 243 insertions(+), 185 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs index d27e08573e037..a611557dc924f 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs @@ -10,7 +10,7 @@ use rustc_hir::def::Res::Def; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::VisitorExt; use rustc_hir::{PolyTraitRef, TyKind, WhereBoundPredicate}; -use rustc_infer::infer::{NllRegionVariableOrigin, RelateParamBound}; +use rustc_infer::infer::{NllRegionVariableOrigin, SubregionOrigin}; use rustc_middle::bug; use rustc_middle::hir::place::PlaceBase; use rustc_middle::mir::{AnnotationSource, ConstraintCategory, ReturnConstraint}; @@ -329,7 +329,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { self.infcx.tcx, type_test.generic_kind.to_ty(self.infcx.tcx), ); - let origin = RelateParamBound(type_test_span, generic_ty, None); + let origin = + SubregionOrigin::RelateParamBound(type_test_span, generic_ty, None); self.buffer_error(self.infcx.err_ctxt().construct_generic_bound_failure( self.body.source.def_id().expect_local(), type_test_span, diff --git a/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs b/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs index 0a114467f4325..8ed552cfa4f00 100644 --- a/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs +++ b/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs @@ -3,7 +3,7 @@ use rustc_infer::infer::canonical::QueryRegionConstraints; use rustc_infer::infer::outlives::env::RegionBoundPairs; use rustc_infer::infer::outlives::obligations::{TypeOutlives, TypeOutlivesDelegate}; use rustc_infer::infer::region_constraints::{GenericKind, VerifyBound}; -use rustc_infer::infer::{self, InferCtxt, SubregionOrigin}; +use rustc_infer::infer::{InferCtxt, SubregionOrigin}; use rustc_infer::traits::query::type_op::DeeplyNormalize; use rustc_middle::bug; use rustc_middle::ty::{ @@ -172,7 +172,7 @@ impl<'a, 'tcx> ConstraintConversion<'a, 'tcx> { ty::Region::new_var(tcx, universal_regions.implicit_region_bound()); // we don't actually use this for anything, but // the `TypeOutlives` code needs an origin. - let origin = infer::RelateParamBound(self.span, t1, None); + let origin = SubregionOrigin::RelateParamBound(self.span, t1, None); TypeOutlives::new( &mut *self, tcx, diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index 9b6dcfd17c62e..e37b5a33af82c 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -16,7 +16,7 @@ use rustc_infer::infer::canonical::QueryRegionConstraints; use rustc_infer::infer::outlives::env::RegionBoundPairs; use rustc_infer::infer::region_constraints::RegionConstraintData; use rustc_infer::infer::{ - BoundRegion, BoundRegionConversionTime, InferCtxt, NllRegionVariableOrigin, + BoundRegionConversionTime, InferCtxt, NllRegionVariableOrigin, RegionVariableOrigin, }; use rustc_infer::traits::PredicateObligations; use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor}; @@ -794,7 +794,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { }; self.infcx.next_region_var( - BoundRegion( + RegionVariableOrigin::BoundRegion( term.source_info.span, br.kind, BoundRegionConversionTime::FnCall, diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index 47681a78ecca8..372a383fb39f7 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -9,7 +9,7 @@ use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan, pluralize, struct_ use rustc_hir::def::{DefKind, Res}; use rustc_hir::intravisit::VisitorExt; use rustc_hir::{self as hir, AmbigArg, GenericParamKind, ImplItemKind, intravisit}; -use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt}; +use rustc_infer::infer::{self, BoundRegionConversionTime, InferCtxt, TyCtxtInferExt}; use rustc_infer::traits::util; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::{ @@ -311,7 +311,7 @@ fn compare_method_predicate_entailment<'tcx>( let unnormalized_impl_sig = infcx.instantiate_binder_with_fresh_vars( impl_m_span, - infer::HigherRankedType, + BoundRegionConversionTime::HigherRankedType, tcx.fn_sig(impl_m.def_id).instantiate_identity(), ); @@ -518,7 +518,7 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( param_env, infcx.instantiate_binder_with_fresh_vars( return_span, - infer::HigherRankedType, + BoundRegionConversionTime::HigherRankedType, tcx.fn_sig(impl_m.def_id).instantiate_identity(), ), ); diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index d05e381f8c86b..03d9ee556ab1c 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -11,7 +11,7 @@ use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::lang_items::LangItem; use rustc_hir::{AmbigArg, ItemKind}; use rustc_infer::infer::outlives::env::OutlivesEnvironment; -use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt}; +use rustc_infer::infer::{self, InferCtxt, SubregionOrigin, TyCtxtInferExt}; use rustc_lint_defs::builtin::SUPERTRAIT_ITEM_SHADOWING_DEFINITION; use rustc_macros::LintDiagnostic; use rustc_middle::mir::interpret::ErrorHandled; @@ -739,7 +739,7 @@ fn ty_known_to_outlive<'tcx>( infcx.register_type_outlives_constraint_inner(infer::TypeOutlivesConstraint { sub_region: region, sup_type: ty, - origin: infer::RelateParamBound(DUMMY_SP, ty, None), + origin: SubregionOrigin::RelateParamBound(DUMMY_SP, ty, None), }); }) } @@ -755,7 +755,11 @@ fn region_known_to_outlive<'tcx>( region_b: ty::Region<'tcx>, ) -> bool { test_region_obligations(tcx, id, param_env, wf_tys, |infcx| { - infcx.sub_regions(infer::RelateRegionParamBound(DUMMY_SP, None), region_b, region_a); + infcx.sub_regions( + SubregionOrigin::RelateRegionParamBound(DUMMY_SP, None), + region_b, + region_a, + ); }) } diff --git a/compiler/rustc_hir_analysis/src/coherence/builtin.rs b/compiler/rustc_hir_analysis/src/coherence/builtin.rs index 4779f4fb702b7..734c9c58c08a5 100644 --- a/compiler/rustc_hir_analysis/src/coherence/builtin.rs +++ b/compiler/rustc_hir_analysis/src/coherence/builtin.rs @@ -10,7 +10,7 @@ use rustc_hir as hir; use rustc_hir::ItemKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::lang_items::LangItem; -use rustc_infer::infer::{self, RegionResolutionError, TyCtxtInferExt}; +use rustc_infer::infer::{self, RegionResolutionError, SubregionOrigin, TyCtxtInferExt}; use rustc_infer::traits::Obligation; use rustc_middle::ty::adjustment::CoerceUnsizedInfo; use rustc_middle::ty::print::PrintTraitRefExt as _; @@ -415,7 +415,7 @@ pub(crate) fn coerce_unsized_info<'tcx>( }; let (source, target, trait_def_id, kind, field_span) = match (source.kind(), target.kind()) { (&ty::Ref(r_a, ty_a, mutbl_a), &ty::Ref(r_b, ty_b, mutbl_b)) => { - infcx.sub_regions(infer::RelateObjectBound(span), r_b, r_a); + infcx.sub_regions(SubregionOrigin::RelateObjectBound(span), r_b, r_a); let mt_a = ty::TypeAndMut { ty: ty_a, mutbl: mutbl_a }; let mt_b = ty::TypeAndMut { ty: ty_b, mutbl: mutbl_b }; check_mutbl(mt_a, mt_b, &|ty| Ty::new_imm_ref(tcx, r_b, ty)) diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index f790c51f8f195..94f16977bd9d3 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -7,7 +7,7 @@ use rustc_hir::def::{self, CtorKind, Namespace, Res}; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, HirId, LangItem}; use rustc_hir_analysis::autoderef::Autoderef; -use rustc_infer::infer; +use rustc_infer::infer::BoundRegionConversionTime; use rustc_infer::traits::{Obligation, ObligationCause, ObligationCauseCode}; use rustc_middle::ty::adjustment::{ Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, @@ -219,7 +219,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let closure_sig = args.as_closure().sig(); let closure_sig = self.instantiate_binder_with_fresh_vars( call_expr.span, - infer::FnCall, + BoundRegionConversionTime::FnCall, closure_sig, ); let adjustments = self.adjust_steps(autoderef); @@ -246,7 +246,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let closure_args = args.as_coroutine_closure(); let coroutine_closure_sig = self.instantiate_binder_with_fresh_vars( call_expr.span, - infer::FnCall, + BoundRegionConversionTime::FnCall, closure_args.coroutine_closure_sig(), ); let tupled_upvars_ty = self.next_ty_var(callee_expr.span); @@ -545,7 +545,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // renormalize the associated types at this point, since they // previously appeared within a `Binder<>` and hence would not // have been normalized before. - let fn_sig = self.instantiate_binder_with_fresh_vars(call_expr.span, infer::FnCall, fn_sig); + let fn_sig = self.instantiate_binder_with_fresh_vars( + call_expr.span, + BoundRegionConversionTime::FnCall, + fn_sig, + ); let fn_sig = self.normalize(call_expr.span, fn_sig); self.check_argument_types( diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 24092c01125fc..b34923f0847fb 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -44,7 +44,7 @@ use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer; use rustc_infer::infer::relate::RelateResult; -use rustc_infer::infer::{Coercion, DefineOpaqueTypes, InferOk, InferResult}; +use rustc_infer::infer::{DefineOpaqueTypes, InferOk, InferResult, RegionVariableOrigin}; use rustc_infer::traits::{ IfExpressionCause, MatchExpressionArmCause, Obligation, PredicateObligation, PredicateObligations, SelectionError, @@ -431,7 +431,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { } else { if r_borrow_var.is_none() { // create var lazily, at most once - let coercion = Coercion(span); + let coercion = RegionVariableOrigin::Coercion(span); let r = self.next_region_var(coercion); r_borrow_var = Some(r); // [4] above } @@ -549,7 +549,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => { coerce_mutbls(mutbl_a, mutbl_b)?; - let coercion = Coercion(self.cause.span); + let coercion = RegionVariableOrigin::Coercion(self.cause.span); let r_borrow = self.next_region_var(coercion); // We don't allow two-phase borrows here, at least for initial @@ -672,7 +672,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { return Err(TypeError::Mismatch); } } - Err(traits::Unimplemented) => { + Err(SelectionError::Unimplemented) => { debug!("coerce_unsized: early return - can't prove obligation"); return Err(TypeError::Mismatch); } diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 2bc9dadb6653b..b9f9b06e4d588 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -22,8 +22,7 @@ use rustc_hir::lang_items::LangItem; use rustc_hir::{ExprKind, HirId, QPath}; use rustc_hir_analysis::NoVariantNamed; use rustc_hir_analysis::hir_ty_lowering::{FeedConstTy, HirTyLowerer as _}; -use rustc_infer::infer; -use rustc_infer::infer::{DefineOpaqueTypes, InferOk}; +use rustc_infer::infer::{self, DefineOpaqueTypes, InferOk, RegionVariableOrigin}; use rustc_infer::traits::query::NoSolution; use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase}; use rustc_middle::ty::error::{ExpectedFound, TypeError}; @@ -705,7 +704,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // this time with enough precision to check that the value // whose address was taken can actually be made to live as long // as it needs to live. - let region = self.next_region_var(infer::BorrowRegion(expr.span)); + let region = self.next_region_var(RegionVariableOrigin::BorrowRegion(expr.span)); match kind { hir::BorrowKind::Ref => Ty::new_ref(self.tcx, region, ty, mutbl), hir::BorrowKind::Pin => Ty::new_pinned_ref(self.tcx, region, ty, mutbl), diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index 95c7f251c884c..c7b9cb470913c 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -11,7 +11,7 @@ use rustc_hir::{ExprKind, HirId, LangItem, Node, QPath}; use rustc_hir_analysis::check::potentially_plural_count; use rustc_hir_analysis::hir_ty_lowering::{HirTyLowerer, PermitVariants}; use rustc_index::IndexVec; -use rustc_infer::infer::{DefineOpaqueTypes, InferOk, TypeTrace}; +use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferOk, TypeTrace}; use rustc_middle::ty::adjustment::AllowTwoPhase; use rustc_middle::ty::error::TypeError; use rustc_middle::ty::{self, IsSuggestable, Ty, TyCtxt, TypeVisitableExt}; @@ -30,7 +30,6 @@ use crate::TupleArgumentsFlag::*; use crate::coercion::CoerceMany; use crate::errors::SuggestPtrNullMut; use crate::fn_ctxt::arg_matrix::{ArgMatrix, Compatibility, Error, ExpectedIdx, ProvidedIdx}; -use crate::fn_ctxt::infer::FnCall; use crate::gather_locals::Declaration; use crate::inline_asm::InlineAsmCtxt; use crate::method::probe::IsSuggestion; @@ -657,7 +656,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let args = self.infcx.fresh_args_for_item(call_name.span, assoc.def_id); let fn_sig = tcx.fn_sig(assoc.def_id).instantiate(tcx, args); - self.instantiate_binder_with_fresh_vars(call_name.span, FnCall, fn_sig); + self.instantiate_binder_with_fresh_vars( + call_name.span, + BoundRegionConversionTime::FnCall, + fn_sig, + ); } None }; diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs index 8c18642e54a18..c8ebbe27be6f8 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -15,7 +15,7 @@ use rustc_hir::{self as hir, HirId, ItemLocalMap}; use rustc_hir_analysis::hir_ty_lowering::{ HirTyLowerer, InherentAssocCandidate, RegionInferReason, }; -use rustc_infer::infer; +use rustc_infer::infer::{self, RegionVariableOrigin}; use rustc_infer::traits::{DynCompatibilityViolation, Obligation}; use rustc_middle::ty::{self, Const, Ty, TyCtxt, TypeVisitableExt}; use rustc_session::Session; @@ -244,8 +244,10 @@ impl<'tcx> HirTyLowerer<'tcx> for FnCtxt<'_, 'tcx> { fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx> { let v = match reason { - RegionInferReason::Param(def) => infer::RegionParameterDefinition(span, def.name), - _ => infer::MiscVariable(span), + RegionInferReason::Param(def) => { + RegionVariableOrigin::RegionParameterDefinition(span, def.name) + } + _ => RegionVariableOrigin::MiscVariable(span), }; self.next_region_var(v) } diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 53b5dff9c6b50..9563cf734f687 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -9,7 +9,9 @@ use rustc_hir_analysis::hir_ty_lowering::generics::{ use rustc_hir_analysis::hir_ty_lowering::{ FeedConstTy, GenericArgsLowerer, HirTyLowerer, IsMethodCall, RegionInferReason, }; -use rustc_infer::infer::{self, DefineOpaqueTypes, InferOk}; +use rustc_infer::infer::{ + BoundRegionConversionTime, DefineOpaqueTypes, InferOk, RegionVariableOrigin, +}; use rustc_lint::builtin::SUPERTRAIT_ITEM_SHADOWING_USAGE; use rustc_middle::traits::ObligationCauseCode; use rustc_middle::ty::adjustment::{ @@ -194,7 +196,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { match pick.autoref_or_ptr_adjustment { Some(probe::AutorefOrPtrAdjustment::Autoref { mutbl, unsize }) => { - let region = self.next_region_var(infer::Autoref(self.span)); + let region = self.next_region_var(RegionVariableOrigin::Autoref(self.span)); // Type we're wrapping in a reference, used later for unsizing let base_ty = target; @@ -239,7 +241,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { } Some(probe::AutorefOrPtrAdjustment::ReborrowPin(mutbl)) => { - let region = self.next_region_var(infer::Autoref(self.span)); + let region = self.next_region_var(RegionVariableOrigin::Autoref(self.span)); target = match target.kind() { ty::Adt(pin, args) if self.tcx.is_lang_item(pin.did(), hir::LangItem::Pin) => { @@ -752,6 +754,10 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { where T: TypeFoldable> + Copy, { - self.fcx.instantiate_binder_with_fresh_vars(self.span, infer::FnCall, value) + self.fcx.instantiate_binder_with_fresh_vars( + self.span, + BoundRegionConversionTime::FnCall, + value, + ) } } diff --git a/compiler/rustc_hir_typeck/src/method/mod.rs b/compiler/rustc_hir_typeck/src/method/mod.rs index 34bbb7d7c05e6..085e7a2f5df14 100644 --- a/compiler/rustc_hir_typeck/src/method/mod.rs +++ b/compiler/rustc_hir_typeck/src/method/mod.rs @@ -11,7 +11,7 @@ use rustc_errors::{Applicability, Diag, SubdiagMessage}; use rustc_hir as hir; use rustc_hir::def::{CtorOf, DefKind, Namespace}; use rustc_hir::def_id::DefId; -use rustc_infer::infer::{self, InferOk}; +use rustc_infer::infer::{BoundRegionConversionTime, InferOk}; use rustc_infer::traits::PredicateObligations; use rustc_middle::query::Providers; use rustc_middle::traits::ObligationCause; @@ -400,8 +400,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // function signature so that normalization does not need to deal // with bound regions. let fn_sig = tcx.fn_sig(def_id).instantiate(self.tcx, args); - let fn_sig = - self.instantiate_binder_with_fresh_vars(obligation.cause.span, infer::FnCall, fn_sig); + let fn_sig = self.instantiate_binder_with_fresh_vars( + obligation.cause.span, + BoundRegionConversionTime::FnCall, + fn_sig, + ); let InferOk { value: fn_sig, obligations: o } = self.at(&obligation.cause, self.param_env).normalize(fn_sig); diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index 589dbb531168b..be0eb13cace67 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -12,7 +12,7 @@ use rustc_hir::HirId; use rustc_hir::def::DefKind; use rustc_hir_analysis::autoderef::{self, Autoderef}; use rustc_infer::infer::canonical::{Canonical, OriginalQueryValues, QueryResponse}; -use rustc_infer::infer::{self, DefineOpaqueTypes, InferOk, TyCtxtInferExt}; +use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferOk, TyCtxtInferExt}; use rustc_infer::traits::ObligationCauseCode; use rustc_middle::middle::stability; use rustc_middle::query::Providers; @@ -995,7 +995,11 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { ty::AssocKind::Fn { .. } => self.probe(|_| { let args = self.fresh_args_for_item(self.span, method.def_id); let fty = self.tcx.fn_sig(method.def_id).instantiate(self.tcx, args); - let fty = self.instantiate_binder_with_fresh_vars(self.span, infer::FnCall, fty); + let fty = self.instantiate_binder_with_fresh_vars( + self.span, + BoundRegionConversionTime::FnCall, + fty, + ); self.can_eq(self.param_env, fty.output(), expected) }), _ => false, @@ -1756,8 +1760,11 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { CandidateSource::Trait(candidate.item.container_id(self.tcx)) } TraitCandidate(trait_ref) => self.probe(|_| { - let trait_ref = - self.instantiate_binder_with_fresh_vars(self.span, infer::FnCall, trait_ref); + let trait_ref = self.instantiate_binder_with_fresh_vars( + self.span, + BoundRegionConversionTime::FnCall, + trait_ref, + ); let (xform_self_ty, _) = self.xform_self_ty(candidate.item, trait_ref.self_ty(), trait_ref.args); // Guide the trait selection to show impls that have methods whose type matches @@ -1873,7 +1880,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { let trait_ref = self.instantiate_binder_with_fresh_vars( self.span, - infer::FnCall, + BoundRegionConversionTime::FnCall, poly_trait_ref, ); let trait_ref = ocx.normalize(cause, self.param_env, trait_ref); @@ -1936,7 +1943,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { ObjectCandidate(poly_trait_ref) | WhereClauseCandidate(poly_trait_ref) => { let trait_ref = self.instantiate_binder_with_fresh_vars( self.span, - infer::FnCall, + BoundRegionConversionTime::FnCall, poly_trait_ref, ); (xform_self_ty, xform_ret_ty) = diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index b35aef13c5255..af1137297aa7b 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -22,7 +22,7 @@ use rustc_hir::def_id::DefId; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::lang_items::LangItem; use rustc_hir::{self as hir, ExprKind, HirId, Node, PathSegment, QPath}; -use rustc_infer::infer::{self, RegionVariableOrigin}; +use rustc_infer::infer::{BoundRegionConversionTime, RegionVariableOrigin}; use rustc_middle::bug; use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams, simplify_type}; use rustc_middle::ty::print::{ @@ -1951,7 +1951,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if def_kind == DefKind::AssocFn { let ty_args = self.infcx.fresh_args_for_item(span, similar_candidate.def_id); let fn_sig = tcx.fn_sig(similar_candidate.def_id).instantiate(tcx, ty_args); - let fn_sig = self.instantiate_binder_with_fresh_vars(span, infer::FnCall, fn_sig); + let fn_sig = self.instantiate_binder_with_fresh_vars( + span, + BoundRegionConversionTime::FnCall, + fn_sig, + ); if similar_candidate.is_method() { if let Some(args) = args && fn_sig.inputs()[1..].len() == args.len() @@ -2033,7 +2037,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.tcx.fn_sig(inherent_method.def_id).instantiate(self.tcx, args); let fn_sig = self.instantiate_binder_with_fresh_vars( item_name.span, - infer::FnCall, + BoundRegionConversionTime::FnCall, fn_sig, ); let name = inherent_method.name(); diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index 432eeae8016cc..349e72090d3ea 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -16,7 +16,7 @@ use rustc_hir::{ PatExprKind, PatKind, expr_needs_parens, }; use rustc_hir_analysis::autoderef::report_autoderef_recursion_limit_error; -use rustc_infer::infer; +use rustc_infer::infer::RegionVariableOrigin; use rustc_middle::traits::PatternOriginExpr; use rustc_middle::ty::{self, Ty, TypeVisitableExt}; use rustc_middle::{bug, span_bug}; @@ -2777,7 +2777,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Create a reference type with a fresh region variable. fn new_ref_ty(&self, span: Span, mutbl: Mutability, ty: Ty<'tcx>) -> Ty<'tcx> { - let region = self.next_region_var(infer::PatternRegion(span)); + let region = self.next_region_var(RegionVariableOrigin::PatternRegion(span)); Ty::new_ref(self.tcx, region, ty, mutbl) } diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index e9b58eb959bda..c1b486194db9a 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -1,9 +1,6 @@ use std::cell::{Cell, RefCell}; use std::fmt; -pub use BoundRegionConversionTime::*; -pub use RegionVariableOrigin::*; -pub use SubregionOrigin::*; pub use at::DefineOpaqueTypes; use free_regions::RegionRelations; pub use freshen::TypeFreshener; @@ -467,21 +464,19 @@ pub struct FixupError { impl fmt::Display for FixupError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - use TyOrConstInferVar::*; - match self.unresolved { - TyInt(_) => write!( + TyOrConstInferVar::TyInt(_) => write!( f, "cannot determine the type of this integer; \ add a suffix to specify the type explicitly" ), - TyFloat(_) => write!( + TyOrConstInferVar::TyFloat(_) => write!( f, "cannot determine the type of this number; \ add a suffix to specify the type explicitly" ), - Ty(_) => write!(f, "unconstrained type"), - Const(_) => write!(f, "unconstrained const value"), + TyOrConstInferVar::Ty(_) => write!(f, "unconstrained type"), + TyOrConstInferVar::Const(_) => write!(f, "unconstrained const value"), } } } @@ -865,7 +860,10 @@ impl<'tcx> InferCtxt<'tcx> { GenericParamDefKind::Lifetime => { // Create a region inference variable for the given // region parameter definition. - self.next_region_var(RegionParameterDefinition(span, param.name)).into() + self.next_region_var(RegionVariableOrigin::RegionParameterDefinition( + span, param.name, + )) + .into() } GenericParamDefKind::Type { .. } => { // Create a type inference variable for the given @@ -1172,7 +1170,7 @@ impl<'tcx> InferCtxt<'tcx> { let arg: ty::GenericArg<'_> = match bound_var_kind { ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(), ty::BoundVariableKind::Region(br) => { - self.next_region_var(BoundRegion(span, br, lbrct)).into() + self.next_region_var(RegionVariableOrigin::BoundRegion(span, br, lbrct)).into() } ty::BoundVariableKind::Const => self.next_const_var(span).into(), }; @@ -1472,15 +1470,15 @@ impl<'tcx> TypeTrace<'tcx> { impl<'tcx> SubregionOrigin<'tcx> { pub fn span(&self) -> Span { match *self { - Subtype(ref a) => a.span(), - RelateObjectBound(a) => a, - RelateParamBound(a, ..) => a, - RelateRegionParamBound(a, _) => a, - Reborrow(a) => a, - ReferenceOutlivesReferent(_, a) => a, - CompareImplItemObligation { span, .. } => span, - AscribeUserTypeProvePredicate(span) => span, - CheckAssociatedTypeBounds { ref parent, .. } => parent.span(), + SubregionOrigin::Subtype(ref a) => a.span(), + SubregionOrigin::RelateObjectBound(a) => a, + SubregionOrigin::RelateParamBound(a, ..) => a, + SubregionOrigin::RelateRegionParamBound(a, _) => a, + SubregionOrigin::Reborrow(a) => a, + SubregionOrigin::ReferenceOutlivesReferent(_, a) => a, + SubregionOrigin::CompareImplItemObligation { span, .. } => span, + SubregionOrigin::AscribeUserTypeProvePredicate(span) => span, + SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => parent.span(), } } @@ -1528,15 +1526,15 @@ impl<'tcx> SubregionOrigin<'tcx> { impl RegionVariableOrigin { pub fn span(&self) -> Span { match *self { - MiscVariable(a) - | PatternRegion(a) - | BorrowRegion(a) - | Autoref(a) - | Coercion(a) - | RegionParameterDefinition(a, ..) - | BoundRegion(a, ..) - | UpvarRegion(_, a) => a, - Nll(..) => bug!("NLL variable used with `span`"), + RegionVariableOrigin::MiscVariable(a) + | RegionVariableOrigin::PatternRegion(a) + | RegionVariableOrigin::BorrowRegion(a) + | RegionVariableOrigin::Autoref(a) + | RegionVariableOrigin::Coercion(a) + | RegionVariableOrigin::RegionParameterDefinition(a, ..) + | RegionVariableOrigin::BoundRegion(a, ..) + | RegionVariableOrigin::UpvarRegion(_, a) => a, + RegionVariableOrigin::Nll(..) => bug!("NLL variable used with `span`"), } } } diff --git a/compiler/rustc_infer/src/infer/outlives/obligations.rs b/compiler/rustc_infer/src/infer/outlives/obligations.rs index db937b3e83eb4..f272052aaa544 100644 --- a/compiler/rustc_infer/src/infer/outlives/obligations.rs +++ b/compiler/rustc_infer/src/infer/outlives/obligations.rs @@ -141,7 +141,7 @@ impl<'tcx> InferCtxt<'tcx> { debug!(?sup_type, ?sub_region, ?cause); let origin = SubregionOrigin::from_obligation_cause(cause, || { - infer::RelateParamBound( + SubregionOrigin::RelateParamBound( cause.span, sup_type, match cause.code().peel_derives() { diff --git a/compiler/rustc_infer/src/infer/region_constraints/mod.rs b/compiler/rustc_infer/src/infer/region_constraints/mod.rs index 40e2e654b2ea7..b5bf5211dd6e0 100644 --- a/compiler/rustc_infer/src/infer/region_constraints/mod.rs +++ b/compiler/rustc_infer/src/infer/region_constraints/mod.rs @@ -14,7 +14,7 @@ use tracing::{debug, instrument}; use self::CombineMapType::*; use self::UndoLog::*; -use super::{MiscVariable, RegionVariableOrigin, Rollback, SubregionOrigin}; +use super::{RegionVariableOrigin, Rollback, SubregionOrigin}; use crate::infer::snapshot::undo_log::{InferCtxtUndoLogs, Snapshot}; use crate::infer::unify_key::{RegionVariableValue, RegionVidKey}; @@ -580,7 +580,7 @@ impl<'tcx> RegionConstraintCollector<'_, 'tcx> { let a_universe = self.universe(a); let b_universe = self.universe(b); let c_universe = cmp::max(a_universe, b_universe); - let c = self.new_region_var(c_universe, MiscVariable(origin.span())); + let c = self.new_region_var(c_universe, RegionVariableOrigin::MiscVariable(origin.span())); self.combine_map(t).insert(vars, c); self.undo_log.push(AddCombination(t, vars)); let new_r = ty::Region::new_var(tcx, c); diff --git a/compiler/rustc_infer/src/infer/resolve.rs b/compiler/rustc_infer/src/infer/resolve.rs index a95f24b5b95d0..13df23a39b967 100644 --- a/compiler/rustc_infer/src/infer/resolve.rs +++ b/compiler/rustc_infer/src/infer/resolve.rs @@ -5,6 +5,7 @@ use rustc_middle::ty::{ }; use super::{FixupError, FixupResult, InferCtxt}; +use crate::infer::TyOrConstInferVar; /////////////////////////////////////////////////////////////////////////// // OPPORTUNISTIC VAR RESOLVER @@ -144,13 +145,17 @@ impl<'a, 'tcx> FallibleTypeFolder> for FullTypeResolver<'a, 'tcx> { if !t.has_infer() { Ok(t) // micro-optimize -- if there is nothing in this type that this fold affects... } else { - use super::TyOrConstInferVar::*; - let t = self.infcx.shallow_resolve(t); match *t.kind() { - ty::Infer(ty::TyVar(vid)) => Err(FixupError { unresolved: Ty(vid) }), - ty::Infer(ty::IntVar(vid)) => Err(FixupError { unresolved: TyInt(vid) }), - ty::Infer(ty::FloatVar(vid)) => Err(FixupError { unresolved: TyFloat(vid) }), + ty::Infer(ty::TyVar(vid)) => { + Err(FixupError { unresolved: TyOrConstInferVar::Ty(vid) }) + } + ty::Infer(ty::IntVar(vid)) => { + Err(FixupError { unresolved: TyOrConstInferVar::TyInt(vid) }) + } + ty::Infer(ty::FloatVar(vid)) => { + Err(FixupError { unresolved: TyOrConstInferVar::TyFloat(vid) }) + } ty::Infer(_) => { bug!("Unexpected type in full type resolver: {:?}", t); } diff --git a/compiler/rustc_infer/src/traits/mod.rs b/compiler/rustc_infer/src/traits/mod.rs index 6d5ad96e31c90..79a4859f286fb 100644 --- a/compiler/rustc_infer/src/traits/mod.rs +++ b/compiler/rustc_infer/src/traits/mod.rs @@ -20,8 +20,6 @@ use rustc_middle::ty::{self, Ty, TyCtxt, Upcast}; use rustc_span::Span; use thin_vec::ThinVec; -pub use self::ImplSource::*; -pub use self::SelectionError::*; pub use self::engine::{FromSolverError, ScrubbedTraitError, TraitEngine}; pub(crate) use self::project::UndoLog; pub use self::project::{ diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs index bfef3340b323f..1db05ced8d2fb 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs @@ -909,11 +909,11 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { } } (GenericArgKind::Const(inner_ct), TermKind::Const(target_ct)) => { - use ty::InferConst::*; match (inner_ct.kind(), target_ct.kind()) { - (ty::ConstKind::Infer(Var(a_vid)), ty::ConstKind::Infer(Var(b_vid))) => { - self.tecx.root_const_var(a_vid) == self.tecx.root_const_var(b_vid) - } + ( + ty::ConstKind::Infer(ty::InferConst::Var(a_vid)), + ty::ConstKind::Infer(ty::InferConst::Var(b_vid)), + ) => self.tecx.root_const_var(a_vid) == self.tecx.root_const_var(b_vid), _ => false, } } diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mod.rs index e456ba0eda5c3..c0b4bdab84945 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mod.rs @@ -5,7 +5,6 @@ use rustc_span::Span; use crate::error_reporting::TypeErrCtxt; use crate::infer::RegionResolutionError; -use crate::infer::RegionResolutionError::*; mod different_lifetimes; pub mod find_anon_type; @@ -83,8 +82,10 @@ impl<'cx, 'tcx> NiceRegionError<'cx, 'tcx> { pub(super) fn regions(&self) -> Option<(Span, ty::Region<'tcx>, ty::Region<'tcx>)> { match (&self.error, self.regions) { - (Some(ConcreteFailure(origin, sub, sup)), None) => Some((origin.span(), *sub, *sup)), - (Some(SubSupConflict(_, _, origin, sub, _, sup, _)), None) => { + (Some(RegionResolutionError::ConcreteFailure(origin, sub, sup)), None) => { + Some((origin.span(), *sub, *sup)) + } + (Some(RegionResolutionError::SubSupConflict(_, _, origin, sub, _, sup, _)), None) => { Some((origin.span(), *sub, *sup)) } (None, Some((span, sub, sup))) => Some((span, sub, sup)), diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/trait_impl_difference.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/trait_impl_difference.rs index b66bd2c6ab787..f1237130c15ab 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/trait_impl_difference.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/trait_impl_difference.rs @@ -5,6 +5,7 @@ use rustc_hir::def::{Namespace, Res}; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::{Visitor, walk_ty}; use rustc_hir::{self as hir, AmbigArg}; +use rustc_infer::infer::SubregionOrigin; use rustc_middle::hir::nested_filter; use rustc_middle::traits::ObligationCauseCode; use rustc_middle::ty::error::ExpectedFound; @@ -16,7 +17,7 @@ use tracing::debug; use crate::error_reporting::infer::nice_region_error::NiceRegionError; use crate::error_reporting::infer::nice_region_error::placeholder_error::Highlighted; use crate::errors::{ConsiderBorrowingParamHelp, RelationshipHelp, TraitImplDiff}; -use crate::infer::{RegionResolutionError, Subtype, ValuePairs}; +use crate::infer::{RegionResolutionError, ValuePairs}; impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { /// Print the error message for lifetime errors when the `impl` doesn't conform to the `trait`. @@ -32,7 +33,8 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { _sup, _, ) = error.clone() - && let (Subtype(sup_trace), Subtype(sub_trace)) = (&sup_origin, &sub_origin) + && let (SubregionOrigin::Subtype(sup_trace), SubregionOrigin::Subtype(sub_trace)) = + (&sup_origin, &sub_origin) && let &ObligationCauseCode::CompareImplItem { trait_item_def_id, .. } = sub_trace.cause.code() && sub_trace.values == sup_trace.values diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs index 5c669678ccc0c..5db643ee52449 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs @@ -27,7 +27,10 @@ use crate::errors::{ }; use crate::fluent_generated as fluent; use crate::infer::region_constraints::GenericKind; -use crate::infer::{self, InferCtxt, RegionResolutionError, RegionVariableOrigin, SubregionOrigin}; +use crate::infer::{ + BoundRegionConversionTime, InferCtxt, RegionResolutionError, RegionVariableOrigin, + SubregionOrigin, +}; impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { pub fn report_region_errors( @@ -219,21 +222,21 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { pub(super) fn note_region_origin(&self, err: &mut Diag<'_>, origin: &SubregionOrigin<'tcx>) { match *origin { - infer::Subtype(ref trace) => RegionOriginNote::WithRequirement { + SubregionOrigin::Subtype(ref trace) => RegionOriginNote::WithRequirement { span: trace.cause.span, requirement: ObligationCauseAsDiagArg(trace.cause.clone()), expected_found: self.values_str(trace.values, &trace.cause, err.long_ty_path()), } .add_to_diag(err), - infer::Reborrow(span) => { + SubregionOrigin::Reborrow(span) => { RegionOriginNote::Plain { span, msg: fluent::trait_selection_reborrow } .add_to_diag(err) } - infer::RelateObjectBound(span) => { + SubregionOrigin::RelateObjectBound(span) => { RegionOriginNote::Plain { span, msg: fluent::trait_selection_relate_object_bound } .add_to_diag(err); } - infer::ReferenceOutlivesReferent(ty, span) => { + SubregionOrigin::ReferenceOutlivesReferent(ty, span) => { RegionOriginNote::WithName { span, msg: fluent::trait_selection_reference_outlives_referent, @@ -242,7 +245,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } .add_to_diag(err); } - infer::RelateParamBound(span, ty, opt_span) => { + SubregionOrigin::RelateParamBound(span, ty, opt_span) => { RegionOriginNote::WithName { span, msg: fluent::trait_selection_relate_param_bound, @@ -258,24 +261,24 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { .add_to_diag(err); } } - infer::RelateRegionParamBound(span, _) => { + SubregionOrigin::RelateRegionParamBound(span, _) => { RegionOriginNote::Plain { span, msg: fluent::trait_selection_relate_region_param_bound, } .add_to_diag(err); } - infer::CompareImplItemObligation { span, .. } => { + SubregionOrigin::CompareImplItemObligation { span, .. } => { RegionOriginNote::Plain { span, msg: fluent::trait_selection_compare_impl_item_obligation, } .add_to_diag(err); } - infer::CheckAssociatedTypeBounds { ref parent, .. } => { + SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => { self.note_region_origin(err, parent); } - infer::AscribeUserTypeProvePredicate(span) => { + SubregionOrigin::AscribeUserTypeProvePredicate(span) => { RegionOriginNote::Plain { span, msg: fluent::trait_selection_ascribe_user_type_prove_predicate, @@ -293,7 +296,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { sup: Region<'tcx>, ) -> Diag<'a> { let mut err = match origin { - infer::Subtype(box trace) => { + SubregionOrigin::Subtype(box trace) => { let terr = TypeError::RegionsDoesNotOutlive(sup, sub); let mut err = self.report_and_explain_type_error( trace, @@ -347,7 +350,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } err } - infer::Reborrow(span) => { + SubregionOrigin::Reborrow(span) => { let reference_valid = note_and_explain::RegionExplanation::new( self.tcx, generic_param_scope, @@ -369,7 +372,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { notes: reference_valid.into_iter().chain(content_valid).collect(), }) } - infer::RelateObjectBound(span) => { + SubregionOrigin::RelateObjectBound(span) => { let object_valid = note_and_explain::RegionExplanation::new( self.tcx, generic_param_scope, @@ -391,7 +394,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { notes: object_valid.into_iter().chain(pointer_valid).collect(), }) } - infer::RelateParamBound(span, ty, opt_span) => { + SubregionOrigin::RelateParamBound(span, ty, opt_span) => { let prefix = match sub.kind() { ty::ReStatic => note_and_explain::PrefixKind::TypeSatisfy, _ => note_and_explain::PrefixKind::TypeOutlive, @@ -415,7 +418,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { note, }) } - infer::RelateRegionParamBound(span, ty) => { + SubregionOrigin::RelateRegionParamBound(span, ty) => { let param_instantiated = note_and_explain::RegionExplanation::new( self.tcx, generic_param_scope, @@ -457,7 +460,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { notes: param_instantiated.into_iter().chain(param_must_outlive).collect(), }) } - infer::ReferenceOutlivesReferent(ty, span) => { + SubregionOrigin::ReferenceOutlivesReferent(ty, span) => { let pointer_valid = note_and_explain::RegionExplanation::new( self.tcx, generic_param_scope, @@ -480,7 +483,11 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { notes: pointer_valid.into_iter().chain(data_valid).collect(), }) } - infer::CompareImplItemObligation { span, impl_item_def_id, trait_item_def_id } => { + SubregionOrigin::CompareImplItemObligation { + span, + impl_item_def_id, + trait_item_def_id, + } => { let mut err = self.report_extra_impl_obligation( span, impl_item_def_id, @@ -499,7 +506,11 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } err } - infer::CheckAssociatedTypeBounds { impl_item_def_id, trait_item_def_id, parent } => { + SubregionOrigin::CheckAssociatedTypeBounds { + impl_item_def_id, + trait_item_def_id, + parent, + } => { let mut err = self.report_concrete_failure(generic_param_scope, *parent, sub, sup); // Don't mention the item name if it's an RPITIT, since that'll just confuse @@ -520,7 +531,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { ); err } - infer::AscribeUserTypeProvePredicate(span) => { + SubregionOrigin::AscribeUserTypeProvePredicate(span) => { let instantiated = note_and_explain::RegionExplanation::new( self.tcx, generic_param_scope, @@ -618,7 +629,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { // I can't think how to do better than this right now. -nikomatsakis debug!(?placeholder_origin, ?sub, ?sup, "report_placeholder_failure"); match placeholder_origin { - infer::Subtype(box ref trace) + SubregionOrigin::Subtype(box ref trace) if matches!( &trace.cause.code().peel_derives(), ObligationCauseCode::WhereClause(..) @@ -648,7 +659,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { ) } } - infer::Subtype(box trace) => { + SubregionOrigin::Subtype(box trace) => { let terr = TypeError::RegionsPlaceholderMismatch; return self.report_and_explain_type_error( trace, @@ -945,8 +956,8 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { debug!("report_sub_sup_conflict: sup_region={:?}", sup_region); debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin); - if let infer::Subtype(ref sup_trace) = sup_origin - && let infer::Subtype(ref sub_trace) = sub_origin + if let SubregionOrigin::Subtype(ref sup_trace) = sup_origin + && let SubregionOrigin::Subtype(ref sub_trace) = sub_origin && let Some((sup_expected, sup_found)) = self.values_str(sup_trace.values, &sup_trace.cause, err.long_ty_path()) && let Some((sub_expected, sub_found)) = @@ -1004,30 +1015,38 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { s }; let var_description = match var_origin { - infer::MiscVariable(_) => String::new(), - infer::PatternRegion(_) => " for pattern".to_string(), - infer::BorrowRegion(_) => " for borrow expression".to_string(), - infer::Autoref(_) => " for autoref".to_string(), - infer::Coercion(_) => " for automatic coercion".to_string(), - infer::BoundRegion(_, br, infer::FnCall) => { + RegionVariableOrigin::MiscVariable(_) => String::new(), + RegionVariableOrigin::PatternRegion(_) => " for pattern".to_string(), + RegionVariableOrigin::BorrowRegion(_) => " for borrow expression".to_string(), + RegionVariableOrigin::Autoref(_) => " for autoref".to_string(), + RegionVariableOrigin::Coercion(_) => " for automatic coercion".to_string(), + RegionVariableOrigin::BoundRegion(_, br, BoundRegionConversionTime::FnCall) => { format!(" for lifetime parameter {}in function call", br_string(br)) } - infer::BoundRegion(_, br, infer::HigherRankedType) => { + RegionVariableOrigin::BoundRegion( + _, + br, + BoundRegionConversionTime::HigherRankedType, + ) => { format!(" for lifetime parameter {}in generic type", br_string(br)) } - infer::BoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!( + RegionVariableOrigin::BoundRegion( + _, + br, + BoundRegionConversionTime::AssocTypeProjection(def_id), + ) => format!( " for lifetime parameter {}in trait containing associated type `{}`", br_string(br), self.tcx.associated_item(def_id).name() ), - infer::RegionParameterDefinition(_, name) => { + RegionVariableOrigin::RegionParameterDefinition(_, name) => { format!(" for lifetime parameter `{name}`") } - infer::UpvarRegion(ref upvar_id, _) => { + RegionVariableOrigin::UpvarRegion(ref upvar_id, _) => { let var_name = self.tcx.hir_name(upvar_id.var_path.hir_id); format!(" for capture of `{var_name}` by closure") } - infer::Nll(..) => bug!("NLL variable found in lexical phase"), + RegionVariableOrigin::Nll(..) => bug!("NLL variable found in lexical phase"), }; struct_span_code_err!( diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index 0c88bd3dcbc54..65e31557bb628 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -47,8 +47,8 @@ use crate::infer::{self, InferCtxt, InferCtxtExt as _}; use crate::traits::query::evaluate_obligation::InferCtxtExt as _; use crate::traits::{ MismatchedProjectionTypes, NormalizeExt, Obligation, ObligationCause, ObligationCauseCode, - ObligationCtxt, Overflow, PredicateObligation, SelectionContext, SelectionError, - SignatureMismatch, TraitDynIncompatible, elaborate, specialization_graph, + ObligationCtxt, PredicateObligation, SelectionContext, SelectionError, elaborate, + specialization_graph, }; impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { @@ -659,7 +659,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } } - SignatureMismatch(box SignatureMismatchData { + SelectionError::SignatureMismatch(box SignatureMismatchData { found_trait_ref, expected_trait_ref, terr: terr @ TypeError::CyclicTy(_), @@ -669,7 +669,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { expected_trait_ref, terr, ), - SignatureMismatch(box SignatureMismatchData { + SelectionError::SignatureMismatch(box SignatureMismatchData { found_trait_ref, expected_trait_ref, terr: _, @@ -690,7 +690,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { def_id, ), - TraitDynIncompatible(did) => { + SelectionError::TraitDynIncompatible(did) => { let violations = self.tcx.dyn_compatibility_violations(did); report_dyn_incompatibility(self.tcx, span, None, did, violations) } @@ -710,12 +710,12 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { // Already reported in the query. SelectionError::NotConstEvaluatable(NotConstEvaluatable::Error(guar)) | // Already reported. - Overflow(OverflowError::Error(guar)) => { + SelectionError::Overflow(OverflowError::Error(guar)) => { self.set_tainted_by_errors(guar); return guar }, - Overflow(_) => { + SelectionError::Overflow(_) => { bug!("overflow should be handled before the `report_selection_error` path"); } diff --git a/compiler/rustc_trait_selection/src/traits/fulfill.rs b/compiler/rustc_trait_selection/src/traits/fulfill.rs index 951dfb879aed7..79888ad2f066a 100644 --- a/compiler/rustc_trait_selection/src/traits/fulfill.rs +++ b/compiler/rustc_trait_selection/src/traits/fulfill.rs @@ -20,7 +20,7 @@ use super::project::{self, ProjectAndUnifyResult}; use super::select::SelectionContext; use super::{ EvaluationResult, FulfillmentError, FulfillmentErrorCode, PredicateObligation, - ScrubbedTraitError, Unimplemented, const_evaluatable, wf, + ScrubbedTraitError, const_evaluatable, wf, }; use crate::error_reporting::InferCtxtErrorExt; use crate::infer::{InferCtxt, TyOrConstInferVar}; @@ -456,7 +456,9 @@ impl<'a, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'tcx> { ty::PredicateKind::DynCompatible(trait_def_id) => { if !self.selcx.tcx().is_dyn_compatible(trait_def_id) { - ProcessResult::Error(FulfillmentErrorCode::Select(Unimplemented)) + ProcessResult::Error(FulfillmentErrorCode::Select( + SelectionError::Unimplemented, + )) } else { ProcessResult::Changed(Default::default()) } diff --git a/compiler/rustc_trait_selection/src/traits/project.rs b/compiler/rustc_trait_selection/src/traits/project.rs index 6dd80551980f7..28b5b7cf391eb 100644 --- a/compiler/rustc_trait_selection/src/traits/project.rs +++ b/compiler/rustc_trait_selection/src/traits/project.rs @@ -84,9 +84,6 @@ impl<'tcx> ProjectionCandidateSet<'tcx> { // was discarded -- this could be because of ambiguity, or because // a higher-priority candidate is already there. fn push_candidate(&mut self, candidate: ProjectionCandidate<'tcx>) -> bool { - use self::ProjectionCandidate::*; - use self::ProjectionCandidateSet::*; - // This wacky variable is just used to try and // make code readable and avoid confusing paths. // It is assigned a "value" of `()` only on those @@ -98,12 +95,12 @@ impl<'tcx> ProjectionCandidateSet<'tcx> { let convert_to_ambiguous; match self { - None => { - *self = Single(candidate); + ProjectionCandidateSet::None => { + *self = ProjectionCandidateSet::Single(candidate); return true; } - Single(current) => { + ProjectionCandidateSet::Single(current) => { // Duplicates can happen inside ParamEnv. In the case, we // perform a lazy deduplication. if current == &candidate { @@ -118,16 +115,18 @@ impl<'tcx> ProjectionCandidateSet<'tcx> { // clauses are the safer choice. See the comment on // `select::SelectionCandidate` and #21974 for more details. match (current, candidate) { - (ParamEnv(..), ParamEnv(..)) => convert_to_ambiguous = (), - (ParamEnv(..), _) => return false, - (_, ParamEnv(..)) => bug!( + (ProjectionCandidate::ParamEnv(..), ProjectionCandidate::ParamEnv(..)) => { + convert_to_ambiguous = () + } + (ProjectionCandidate::ParamEnv(..), _) => return false, + (_, ProjectionCandidate::ParamEnv(..)) => bug!( "should never prefer non-param-env candidates over param-env candidates" ), (_, _) => convert_to_ambiguous = (), } } - Ambiguous | Error(..) => { + ProjectionCandidateSet::Ambiguous | ProjectionCandidateSet::Error(..) => { return false; } } @@ -135,7 +134,7 @@ impl<'tcx> ProjectionCandidateSet<'tcx> { // We only ever get here when we moved from a single candidate // to ambiguous. let () = convert_to_ambiguous; - *self = Ambiguous; + *self = ProjectionCandidateSet::Ambiguous; false } } diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index 80f71c78993cc..3eca77b43a89a 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -11,7 +11,7 @@ use std::ops::ControlFlow; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_hir::lang_items::LangItem; -use rustc_infer::infer::{DefineOpaqueTypes, HigherRankedType, InferOk}; +use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferOk}; use rustc_infer::traits::ObligationCauseCode; use rustc_middle::traits::{BuiltinImplSource, SignatureMismatchData}; use rustc_middle::ty::{ @@ -28,8 +28,7 @@ use crate::traits::normalize::{normalize_with_depth, normalize_with_depth_to}; use crate::traits::util::{self, closure_trait_ref_and_return_type}; use crate::traits::{ ImplSource, ImplSourceUserDefinedData, Normalized, Obligation, ObligationCause, - PolyTraitObligation, PredicateObligation, Selection, SelectionError, SignatureMismatch, - TraitDynIncompatible, TraitObligation, Unimplemented, + PolyTraitObligation, PredicateObligation, Selection, SelectionError, TraitObligation, }; impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { @@ -176,7 +175,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let candidate = self.infcx.instantiate_binder_with_fresh_vars( obligation.cause.span, - HigherRankedType, + BoundRegionConversionTime::HigherRankedType, candidate, ); let mut obligations = PredicateObligations::new(); @@ -194,7 +193,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { .at(&obligation.cause, obligation.param_env) .eq(DefineOpaqueTypes::No, placeholder_trait_predicate, candidate) .map(|InferOk { obligations, .. }| obligations) - .map_err(|_| Unimplemented)?, + .map_err(|_| SelectionError::Unimplemented)?, ); // FIXME(compiler-errors): I don't think this is needed. @@ -374,7 +373,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { assume = crate::traits::evaluate_const(self.infcx, assume, obligation.param_env) } let Some(assume) = rustc_transmute::Assume::from_const(self.infcx.tcx, assume) else { - return Err(Unimplemented); + return Err(SelectionError::Unimplemented); }; let dst = predicate.trait_ref.args.type_at(0); @@ -386,7 +385,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { transmute_env.is_transmutable(rustc_transmute::Types { dst, src }, assume); let fully_flattened = match maybe_transmutable { - Answer::No(_) => Err(Unimplemented)?, + Answer::No(_) => Err(SelectionError::Unimplemented)?, Answer::If(cond) => flatten_answer_tree(self.tcx(), obligation, cond, assume), Answer::Yes => PredicateObligations::new(), }; @@ -500,7 +499,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { }); let object_trait_ref = self.infcx.instantiate_binder_with_fresh_vars( obligation.cause.span, - HigherRankedType, + BoundRegionConversionTime::HigherRankedType, object_trait_ref, ); let object_trait_ref = object_trait_ref.with_self_ty(self.tcx(), self_ty); @@ -513,7 +512,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let upcast_trait_ref = self.infcx.instantiate_binder_with_fresh_vars( obligation.cause.span, - HigherRankedType, + BoundRegionConversionTime::HigherRankedType, unnormalized_upcast_trait_ref, ); let upcast_trait_ref = normalize_with_depth_to( @@ -530,7 +529,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { .at(&obligation.cause, obligation.param_env) .eq(DefineOpaqueTypes::No, trait_predicate.trait_ref, upcast_trait_ref) .map(|InferOk { obligations, .. }| obligations) - .map_err(|_| Unimplemented)?, + .map_err(|_| SelectionError::Unimplemented)?, ); // Check supertraits hold. This is so that their associated type bounds @@ -962,7 +961,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ) -> Result, SelectionError<'tcx>> { let found_trait_ref = self.infcx.instantiate_binder_with_fresh_vars( obligation.cause.span, - HigherRankedType, + BoundRegionConversionTime::HigherRankedType, found_trait_ref, ); // Normalize the obligation and expected trait refs together, because why not @@ -986,7 +985,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { obligations }) .map_err(|terr| { - SignatureMismatch(Box::new(SignatureMismatchData { + SelectionError::SignatureMismatch(Box::new(SignatureMismatchData { expected_trait_ref: obligation_trait_ref, found_trait_ref, terr, @@ -1090,7 +1089,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { .infcx .at(&obligation.cause, obligation.param_env) .sup(DefineOpaqueTypes::Yes, target, source_trait) - .map_err(|_| Unimplemented)?; + .map_err(|_| SelectionError::Unimplemented)?; // Register one obligation for 'a: 'b. let outlives = ty::OutlivesPredicate(r_a, r_b); @@ -1109,7 +1108,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { (_, &ty::Dynamic(data, r, ty::Dyn)) => { let mut object_dids = data.auto_traits().chain(data.principal_def_id()); if let Some(did) = object_dids.find(|did| !tcx.is_dyn_compatible(*did)) { - return Err(TraitDynIncompatible(did)); + return Err(SelectionError::TraitDynIncompatible(did)); } let predicate_to_obligation = |predicate| { @@ -1189,7 +1188,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { .infcx .at(&obligation.cause, obligation.param_env) .eq(DefineOpaqueTypes::Yes, b, a) - .map_err(|_| Unimplemented)?; + .map_err(|_| SelectionError::Unimplemented)?; ImplSource::Builtin(BuiltinImplSource::Misc, obligations) } @@ -1198,7 +1197,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { (&ty::Adt(def, args_a), &ty::Adt(_, args_b)) => { let unsizing_params = tcx.unsizing_params_for_adt(def.did()); if unsizing_params.is_empty() { - return Err(Unimplemented); + return Err(SelectionError::Unimplemented); } let tail_field = def.non_enum_variant().tail(); @@ -1237,7 +1236,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { .infcx .at(&obligation.cause, obligation.param_env) .eq(DefineOpaqueTypes::Yes, target, new_struct) - .map_err(|_| Unimplemented)?; + .map_err(|_| SelectionError::Unimplemented)?; nested.extend(obligations); // Construct the nested `TailField: Unsize>` predicate. diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 9c0ccb26e53f6..973be1191ba47 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -39,7 +39,7 @@ use super::coherence::{self, Conflict}; use super::project::ProjectionTermObligation; use super::util::closure_trait_ref_and_return_type; use super::{ - ImplDerivedCause, Normalized, Obligation, ObligationCause, ObligationCauseCode, Overflow, + ImplDerivedCause, Normalized, Obligation, ObligationCause, ObligationCauseCode, PolyTraitObligation, PredicateObligation, Selection, SelectionError, SelectionResult, TraitQueryMode, const_evaluatable, project, util, wf, }; @@ -48,9 +48,7 @@ use crate::infer::{InferCtxt, InferOk, TypeFreshener}; use crate::solve::InferCtxtSelectExt as _; use crate::traits::normalize::{normalize_with_depth, normalize_with_depth_to}; use crate::traits::project::{ProjectAndUnifyResult, ProjectionCacheKeyExt}; -use crate::traits::{ - EvaluateConstErr, ProjectionCacheKey, Unimplemented, effects, sizedness_fast_path, -}; +use crate::traits::{EvaluateConstErr, ProjectionCacheKey, effects, sizedness_fast_path}; mod _match; mod candidate_assembly; @@ -454,8 +452,12 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { Ok(Some(EvaluatedCandidate { candidate: c, evaluation: eval })) } Ok(_) => Ok(None), - Err(OverflowError::Canonical) => Err(Overflow(OverflowError::Canonical)), - Err(OverflowError::Error(e)) => Err(Overflow(OverflowError::Error(e))), + Err(OverflowError::Canonical) => { + Err(SelectionError::Overflow(OverflowError::Canonical)) + } + Err(OverflowError::Error(e)) => { + Err(SelectionError::Overflow(OverflowError::Error(e))) + } }) .flat_map(Result::transpose) .collect::, _>>()?; @@ -479,7 +481,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { debug!(?stack.obligation.predicate, "found error type in predicate, treating as ambiguous"); Ok(None) } else { - Err(Unimplemented) + Err(SelectionError::Unimplemented) } } else { let has_non_region_infer = stack.obligation.predicate.has_non_region_infer(); @@ -1222,7 +1224,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { match self.candidate_from_obligation(stack) { Ok(Some(c)) => self.evaluate_candidate(stack, &c), Ok(None) => Ok(EvaluatedToAmbig), - Err(Overflow(OverflowError::Canonical)) => Err(OverflowError::Canonical), + Err(SelectionError::Overflow(OverflowError::Canonical)) => { + Err(OverflowError::Canonical) + } Err(..) => Ok(EvaluatedToErr), } } @@ -1536,7 +1540,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { return Some(res); } else if cfg!(debug_assertions) { match infcx.selection_cache.get(&(param_env, pred), tcx) { - None | Some(Err(Overflow(OverflowError::Canonical))) => {} + None | Some(Err(SelectionError::Overflow(OverflowError::Canonical))) => {} res => bug!("unexpected local cache result: {res:?}"), } } @@ -1592,7 +1596,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } if self.can_use_global_caches(param_env, cache_fresh_trait_pred) { - if let Err(Overflow(OverflowError::Canonical)) = candidate { + if let Err(SelectionError::Overflow(OverflowError::Canonical)) = candidate { // Don't cache overflow globally; we only produce this in certain modes. } else { debug!(?pred, ?candidate, "insert_candidate_cache global"); diff --git a/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs b/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs index 9452dca9a4f0f..19eb85506b6fb 100644 --- a/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs +++ b/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs @@ -273,8 +273,6 @@ impl<'tcx> Graph { // Descend the specialization tree, where `parent` is the current parent node. loop { - use self::Inserted::*; - let insert_result = self.children.entry(parent).or_default().insert( tcx, impl_def_id, @@ -283,11 +281,11 @@ impl<'tcx> Graph { )?; match insert_result { - BecameNewSibling(opt_lint) => { + Inserted::BecameNewSibling(opt_lint) => { last_lint = opt_lint; break; } - ReplaceChildren(grand_children_to_be) => { + Inserted::ReplaceChildren(grand_children_to_be) => { // We currently have // // P @@ -326,7 +324,7 @@ impl<'tcx> Graph { } break; } - ShouldRecurseOn(new_parent) => { + Inserted::ShouldRecurseOn(new_parent) => { parent = new_parent; } } diff --git a/compiler/rustc_traits/src/codegen.rs b/compiler/rustc_traits/src/codegen.rs index a0a1d4545564e..9d14401056183 100644 --- a/compiler/rustc_traits/src/codegen.rs +++ b/compiler/rustc_traits/src/codegen.rs @@ -10,7 +10,7 @@ use rustc_middle::ty::{self, PseudoCanonicalInput, TyCtxt, TypeVisitableExt, Upc use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::traits::{ ImplSource, Obligation, ObligationCause, ObligationCtxt, ScrubbedTraitError, SelectionContext, - Unimplemented, sizedness_fast_path, + SelectionError, sizedness_fast_path, }; use tracing::debug; @@ -47,7 +47,7 @@ pub(crate) fn codegen_select_candidate<'tcx>( let selection = match selcx.select(&obligation) { Ok(Some(selection)) => selection, Ok(None) => return Err(CodegenObligationError::Ambiguity), - Err(Unimplemented) => return Err(CodegenObligationError::Unimplemented), + Err(SelectionError::Unimplemented) => return Err(CodegenObligationError::Unimplemented), Err(e) => { bug!("Encountered error `{:?}` selecting `{:?}` during codegen", e, trait_ref) } From c995070b6a312ff9f481d6de55f58bfe16a76bb7 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 18 Jun 2025 18:00:30 +0000 Subject: [PATCH 15/23] rename RegionVariableOrigin::MiscVariable to RegionVariableOrigin::Misc --- compiler/rustc_borrowck/src/type_check/input_output.rs | 7 +++---- compiler/rustc_hir_analysis/src/check/check.rs | 2 +- compiler/rustc_hir_typeck/src/check.rs | 2 +- compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs | 2 +- compiler/rustc_hir_typeck/src/method/suggest.rs | 6 +++--- compiler/rustc_infer/src/infer/canonical/mod.rs | 5 +---- compiler/rustc_infer/src/infer/context.rs | 2 +- compiler/rustc_infer/src/infer/mod.rs | 4 ++-- compiler/rustc_infer/src/infer/opaque_types/mod.rs | 4 +--- compiler/rustc_infer/src/infer/region_constraints/mod.rs | 2 +- compiler/rustc_infer/src/infer/relate/generalize.rs | 7 +++---- .../src/error_reporting/infer/region.rs | 2 +- compiler/rustc_trait_selection/src/solve/delegate.rs | 2 +- 13 files changed, 20 insertions(+), 27 deletions(-) diff --git a/compiler/rustc_borrowck/src/type_check/input_output.rs b/compiler/rustc_borrowck/src/type_check/input_output.rs index 0c46e0c0c2204..99392ea19151c 100644 --- a/compiler/rustc_borrowck/src/type_check/input_output.rs +++ b/compiler/rustc_borrowck/src/type_check/input_output.rs @@ -66,10 +66,9 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { Ty::new_tup(self.tcx(), user_provided_sig.inputs()), args.tupled_upvars_ty(), args.coroutine_captures_by_ref_ty(), - self.infcx - .next_region_var(RegionVariableOrigin::MiscVariable(self.body.span), || { - RegionCtxt::Unknown - }), + self.infcx.next_region_var(RegionVariableOrigin::Misc(self.body.span), || { + RegionCtxt::Unknown + }), ); let next_ty_var = || self.infcx.next_ty_var(self.body.span); diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 485dd1d220441..f08a24514964d 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -312,7 +312,7 @@ fn check_opaque_meets_bounds<'tcx>( // here rather than using ReErased. let hidden_ty = tcx.type_of(def_id.to_def_id()).instantiate(tcx, args); let hidden_ty = fold_regions(tcx, hidden_ty, |re, _dbi| match re.kind() { - ty::ReErased => infcx.next_region_var(RegionVariableOrigin::MiscVariable(span)), + ty::ReErased => infcx.next_region_var(RegionVariableOrigin::Misc(span)), _ => re, }); diff --git a/compiler/rustc_hir_typeck/src/check.rs b/compiler/rustc_hir_typeck/src/check.rs index ac42eebf08c0d..612396858841f 100644 --- a/compiler/rustc_hir_typeck/src/check.rs +++ b/compiler/rustc_hir_typeck/src/check.rs @@ -58,7 +58,7 @@ pub(super) fn check_fn<'a, 'tcx>( let maybe_va_list = fn_sig.c_variadic.then(|| { let span = body.params.last().unwrap().span; let va_list_did = tcx.require_lang_item(LangItem::VaList, span); - let region = fcx.next_region_var(RegionVariableOrigin::MiscVariable(span)); + let region = fcx.next_region_var(RegionVariableOrigin::Misc(span)); tcx.type_of(va_list_did).instantiate(tcx, &[region.into()]) }); diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs index c8ebbe27be6f8..0c6226ce71e78 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -247,7 +247,7 @@ impl<'tcx> HirTyLowerer<'tcx> for FnCtxt<'_, 'tcx> { RegionInferReason::Param(def) => { RegionVariableOrigin::RegionParameterDefinition(span, def.name) } - _ => RegionVariableOrigin::MiscVariable(span), + _ => RegionVariableOrigin::Misc(span), }; self.next_region_var(v) } diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index af1137297aa7b..d0a48872f759c 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -2352,9 +2352,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if !arg.is_suggestable(self.tcx, true) { has_unsuggestable_args = true; match arg.kind() { - GenericArgKind::Lifetime(_) => self - .next_region_var(RegionVariableOrigin::MiscVariable(DUMMY_SP)) - .into(), + GenericArgKind::Lifetime(_) => { + self.next_region_var(RegionVariableOrigin::Misc(DUMMY_SP)).into() + } GenericArgKind::Type(_) => self.next_ty_var(DUMMY_SP).into(), GenericArgKind::Const(_) => self.next_const_var(DUMMY_SP).into(), } diff --git a/compiler/rustc_infer/src/infer/canonical/mod.rs b/compiler/rustc_infer/src/infer/canonical/mod.rs index 5dffedc709968..79a2aa54ef834 100644 --- a/compiler/rustc_infer/src/infer/canonical/mod.rs +++ b/compiler/rustc_infer/src/infer/canonical/mod.rs @@ -128,10 +128,7 @@ impl<'tcx> InferCtxt<'tcx> { } CanonicalVarKind::Region(ui) => self - .next_region_var_in_universe( - RegionVariableOrigin::MiscVariable(span), - universe_map(ui), - ) + .next_region_var_in_universe(RegionVariableOrigin::Misc(span), universe_map(ui)) .into(), CanonicalVarKind::PlaceholderRegion(ty::PlaceholderRegion { universe, bound }) => { diff --git a/compiler/rustc_infer/src/infer/context.rs b/compiler/rustc_infer/src/infer/context.rs index f7c702d321b21..bb9c88500936f 100644 --- a/compiler/rustc_infer/src/infer/context.rs +++ b/compiler/rustc_infer/src/infer/context.rs @@ -141,7 +141,7 @@ impl<'tcx> rustc_type_ir::InferCtxtLike for InferCtxt<'tcx> { } fn next_region_infer(&self) -> ty::Region<'tcx> { - self.next_region_var(RegionVariableOrigin::MiscVariable(DUMMY_SP)) + self.next_region_var(RegionVariableOrigin::Misc(DUMMY_SP)) } fn next_ty_infer(&self) -> Ty<'tcx> { diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index c1b486194db9a..bfec0d12485eb 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -400,7 +400,7 @@ pub enum RegionVariableOrigin { /// Region variables created for ill-categorized reasons. /// /// They mostly indicate places in need of refactoring. - MiscVariable(Span), + Misc(Span), /// Regions created by a `&P` or `[...]` pattern. PatternRegion(Span), @@ -1526,7 +1526,7 @@ impl<'tcx> SubregionOrigin<'tcx> { impl RegionVariableOrigin { pub fn span(&self) -> Span { match *self { - RegionVariableOrigin::MiscVariable(a) + RegionVariableOrigin::Misc(a) | RegionVariableOrigin::PatternRegion(a) | RegionVariableOrigin::BorrowRegion(a) | RegionVariableOrigin::Autoref(a) diff --git a/compiler/rustc_infer/src/infer/opaque_types/mod.rs b/compiler/rustc_infer/src/infer/opaque_types/mod.rs index 220d5e9bda2d1..220e025c3f7d6 100644 --- a/compiler/rustc_infer/src/infer/opaque_types/mod.rs +++ b/compiler/rustc_infer/src/infer/opaque_types/mod.rs @@ -262,9 +262,7 @@ impl<'tcx> InferCtxt<'tcx> { .type_of_opaque_hir_typeck(opaque_type_key.def_id) .instantiate(self.tcx, opaque_type_key.args); let actual = ty::fold_regions(tcx, actual, |re, _dbi| match re.kind() { - ty::ReErased => { - self.next_region_var(RegionVariableOrigin::MiscVariable(span)) - } + ty::ReErased => self.next_region_var(RegionVariableOrigin::Misc(span)), _ => re, }); actual diff --git a/compiler/rustc_infer/src/infer/region_constraints/mod.rs b/compiler/rustc_infer/src/infer/region_constraints/mod.rs index b5bf5211dd6e0..f4cb73685d52d 100644 --- a/compiler/rustc_infer/src/infer/region_constraints/mod.rs +++ b/compiler/rustc_infer/src/infer/region_constraints/mod.rs @@ -580,7 +580,7 @@ impl<'tcx> RegionConstraintCollector<'_, 'tcx> { let a_universe = self.universe(a); let b_universe = self.universe(b); let c_universe = cmp::max(a_universe, b_universe); - let c = self.new_region_var(c_universe, RegionVariableOrigin::MiscVariable(origin.span())); + let c = self.new_region_var(c_universe, RegionVariableOrigin::Misc(origin.span())); self.combine_map(t).insert(vars, c); self.undo_log.push(AddCombination(t, vars)); let new_r = ty::Region::new_var(tcx, c); diff --git a/compiler/rustc_infer/src/infer/relate/generalize.rs b/compiler/rustc_infer/src/infer/relate/generalize.rs index 0e17b100276a2..9e451f16a9d8b 100644 --- a/compiler/rustc_infer/src/infer/relate/generalize.rs +++ b/compiler/rustc_infer/src/infer/relate/generalize.rs @@ -603,10 +603,9 @@ impl<'tcx> TypeRelation> for Generalizer<'_, 'tcx> { } } - Ok(self.infcx.next_region_var_in_universe( - RegionVariableOrigin::MiscVariable(self.span), - self.for_universe, - )) + Ok(self + .infcx + .next_region_var_in_universe(RegionVariableOrigin::Misc(self.span), self.for_universe)) } #[instrument(level = "debug", skip(self, c2), ret)] diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs index 5db643ee52449..4fab67b01cb95 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs @@ -1015,7 +1015,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { s }; let var_description = match var_origin { - RegionVariableOrigin::MiscVariable(_) => String::new(), + RegionVariableOrigin::Misc(_) => String::new(), RegionVariableOrigin::PatternRegion(_) => " for pattern".to_string(), RegionVariableOrigin::BorrowRegion(_) => " for borrow expression".to_string(), RegionVariableOrigin::Autoref(_) => " for autoref".to_string(), diff --git a/compiler/rustc_trait_selection/src/solve/delegate.rs b/compiler/rustc_trait_selection/src/solve/delegate.rs index b247c2c2968b9..d37c954614b3a 100644 --- a/compiler/rustc_trait_selection/src/solve/delegate.rs +++ b/compiler/rustc_trait_selection/src/solve/delegate.rs @@ -154,7 +154,7 @@ impl<'tcx> rustc_next_trait_solver::delegate::SolverDelegate for SolverDelegate< ) -> ty::GenericArg<'tcx> { match arg.kind() { ty::GenericArgKind::Lifetime(_) => { - self.next_region_var(RegionVariableOrigin::MiscVariable(span)).into() + self.next_region_var(RegionVariableOrigin::Misc(span)).into() } ty::GenericArgKind::Type(_) => self.next_ty_var(span).into(), ty::GenericArgKind::Const(_) => self.next_const_var(span).into(), From 9d11fd0e10997e55b99596777b5e266b155655da Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Wed, 25 Jun 2025 18:33:01 +0200 Subject: [PATCH 16/23] codegen_fn_attrs: make comment more precise --- compiler/rustc_codegen_ssa/src/codegen_attrs.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index 7bd27eb3ef1cd..53eb6e5838244 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -446,7 +446,9 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { mixed_export_name_no_mangle_lint_state.lint_if_mixed(tcx); - // Apply the minimum function alignment here, so that individual backends don't have to. + // Apply the minimum function alignment here. This ensures that a function's alignment is + // determined by the `-C` flags of the crate it is defined in, not the `-C` flags of the crate + // it happens to be codegen'd (or const-eval'd) in. codegen_fn_attrs.alignment = Ord::max(codegen_fn_attrs.alignment, tcx.sess.opts.unstable_opts.min_function_alignment); From f1fb323dda177b0e39ef1c9dcdfc1190e7c107ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Mon, 9 Jun 2025 17:45:25 +0000 Subject: [PATCH 17/23] Do not use `gen` as binding name If we ever start testing every edition, using a new keyword unnecessarily will cause divergent output, so pre-emptively change `gen` into `generator`. --- tests/ui/coroutine/auto-trait-regions.rs | 12 ++++++------ tests/ui/coroutine/auto-trait-regions.stderr | 8 ++++---- tests/ui/coroutine/clone-impl-static.rs | 6 +++--- tests/ui/coroutine/clone-impl-static.stderr | 8 ++++---- 4 files changed, 17 insertions(+), 17 deletions(-) diff --git a/tests/ui/coroutine/auto-trait-regions.rs b/tests/ui/coroutine/auto-trait-regions.rs index f115896a473cd..736555b31bbd1 100644 --- a/tests/ui/coroutine/auto-trait-regions.rs +++ b/tests/ui/coroutine/auto-trait-regions.rs @@ -23,31 +23,31 @@ fn assert_foo(f: T) {} fn main() { // Make sure 'static is erased for coroutine interiors so we can't match it in trait selection let x: &'static _ = &OnlyFooIfStaticRef(No); - let gen = #[coroutine] move || { + let generator = #[coroutine] move || { let x = x; yield; assert_foo(x); }; - assert_foo(gen); + assert_foo(generator); //~^ ERROR implementation of `Foo` is not general enough // Allow impls which matches any lifetime let x = &OnlyFooIfRef(No); - let gen = #[coroutine] move || { + let generator = #[coroutine] move || { let x = x; yield; assert_foo(x); }; - assert_foo(gen); // ok + assert_foo(generator); // ok // Disallow impls which relates lifetimes in the coroutine interior - let gen = #[coroutine] move || { + let generator = #[coroutine] move || { let a = A(&mut true, &mut true, No); //~^ ERROR borrow may still be in use when coroutine yields //~| ERROR borrow may still be in use when coroutine yields yield; assert_foo(a); }; - assert_foo(gen); + assert_foo(generator); //~^ ERROR not general enough } diff --git a/tests/ui/coroutine/auto-trait-regions.stderr b/tests/ui/coroutine/auto-trait-regions.stderr index 77b5f3ce57c4a..7a5949de55b4b 100644 --- a/tests/ui/coroutine/auto-trait-regions.stderr +++ b/tests/ui/coroutine/auto-trait-regions.stderr @@ -33,8 +33,8 @@ LL | let gen = #[coroutine] static move || { error: implementation of `Foo` is not general enough --> $DIR/auto-trait-regions.rs:31:5 | -LL | assert_foo(gen); - | ^^^^^^^^^^^^^^^ implementation of `Foo` is not general enough +LL | assert_foo(generator); + | ^^^^^^^^^^^^^^^^^^^^^ implementation of `Foo` is not general enough | = note: `&'0 OnlyFooIfStaticRef` must implement `Foo`, for any lifetime `'0`... = note: ...but `Foo` is actually implemented for the type `&'static OnlyFooIfStaticRef` @@ -42,8 +42,8 @@ LL | assert_foo(gen); error: implementation of `Foo` is not general enough --> $DIR/auto-trait-regions.rs:51:5 | -LL | assert_foo(gen); - | ^^^^^^^^^^^^^^^ implementation of `Foo` is not general enough +LL | assert_foo(generator); + | ^^^^^^^^^^^^^^^^^^^^^ implementation of `Foo` is not general enough | = note: `Foo` would have to be implemented for the type `A<'0, '1>`, for any two lifetimes `'0` and `'1`... = note: ...but `Foo` is actually implemented for the type `A<'_, '2>`, for some specific lifetime `'2` diff --git a/tests/ui/coroutine/clone-impl-static.rs b/tests/ui/coroutine/clone-impl-static.rs index f6fadff7faf13..2f941d6559125 100644 --- a/tests/ui/coroutine/clone-impl-static.rs +++ b/tests/ui/coroutine/clone-impl-static.rs @@ -7,13 +7,13 @@ #![feature(coroutines, coroutine_clone, stmt_expr_attributes)] fn main() { - let gen = #[coroutine] + let generator = #[coroutine] static move || { yield; }; - check_copy(&gen); + check_copy(&generator); //~^ ERROR Copy` is not satisfied - check_clone(&gen); + check_clone(&generator); //~^ ERROR Clone` is not satisfied } diff --git a/tests/ui/coroutine/clone-impl-static.stderr b/tests/ui/coroutine/clone-impl-static.stderr index db1d2770346b6..9fb71fd5fd019 100644 --- a/tests/ui/coroutine/clone-impl-static.stderr +++ b/tests/ui/coroutine/clone-impl-static.stderr @@ -1,8 +1,8 @@ error[E0277]: the trait bound `{static coroutine@$DIR/clone-impl-static.rs:11:5: 11:19}: Copy` is not satisfied --> $DIR/clone-impl-static.rs:14:16 | -LL | check_copy(&gen); - | ---------- ^^^^ the trait `Copy` is not implemented for `{static coroutine@$DIR/clone-impl-static.rs:11:5: 11:19}` +LL | check_copy(&generator); + | ---------- ^^^^^^^^^^ the trait `Copy` is not implemented for `{static coroutine@$DIR/clone-impl-static.rs:11:5: 11:19}` | | | required by a bound introduced by this call | @@ -15,8 +15,8 @@ LL | fn check_copy(_x: &T) {} error[E0277]: the trait bound `{static coroutine@$DIR/clone-impl-static.rs:11:5: 11:19}: Clone` is not satisfied --> $DIR/clone-impl-static.rs:16:17 | -LL | check_clone(&gen); - | ----------- ^^^^ the trait `Clone` is not implemented for `{static coroutine@$DIR/clone-impl-static.rs:11:5: 11:19}` +LL | check_clone(&generator); + | ----------- ^^^^^^^^^^ the trait `Clone` is not implemented for `{static coroutine@$DIR/clone-impl-static.rs:11:5: 11:19}` | | | required by a bound introduced by this call | From 8c3a033d7ffb0431c87cb02452d509e2b530a472 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Mon, 9 Jun 2025 17:52:41 +0000 Subject: [PATCH 18/23] Add edition checks for some tests that had divergent output In order to expose edition dependent divergences in some tests in the test suite, add explicit `edition` annotations. Some of these tests might require additional work to *avoid* the divergences, as they might have been unintentional. These are not exhaustive changes, purely opportunistic while looking at something else. --- tests/ui/coroutine/auto-trait-regions.stderr | 16 +- ...stderr => bad-assoc-ty.edition2015.stderr} | 60 ++-- .../bad-assoc-ty.edition2021.stderr | 340 ++++++++++++++++++ tests/ui/did_you_mean/bad-assoc-ty.rs | 11 +- ...gate-unsized_fn_params.edition2015.stderr} | 8 +- ...-gate-unsized_fn_params.edition2021.stderr | 65 ++++ .../feature-gate-unsized_fn_params.rs | 7 +- ...den-erased-unsoundness.edition2015.stderr} | 2 +- ...dden-erased-unsoundness.edition2024.stderr | 10 + .../rpit-hidden-erased-unsoundness.rs | 6 +- ...hide-lifetime-for-swap.edition2015.stderr} | 2 +- ...-hide-lifetime-for-swap.edition2024.stderr | 17 + .../rpit-hide-lifetime-for-swap.rs | 6 +- ...n-should-be-impl-trait.edition2015.stderr} | 42 +-- ...rn-should-be-impl-trait.edition2021.stderr | 308 ++++++++++++++++ .../dyn-trait-return-should-be-impl-trait.rs | 13 +- ...rr => hidden-lifetimes.edition2015.stderr} | 4 +- .../hidden-lifetimes.edition2024.stderr | 26 ++ tests/ui/impl-trait/hidden-lifetimes.rs | 12 +- ... impl-fn-hrtb-bounds-2.edition2015.stderr} | 2 +- .../impl-fn-hrtb-bounds-2.edition2024.stderr | 15 + tests/ui/impl-trait/impl-fn-hrtb-bounds-2.rs | 7 +- ...n-predefined-lifetimes.edition2015.stderr} | 2 +- ...fn-predefined-lifetimes.edition2024.stderr | 11 + .../impl-fn-predefined-lifetimes.rs | 3 + ....stderr => issue-54895.edition2015.stderr} | 4 +- .../issues/issue-54895.edition2024.stderr | 27 ++ tests/ui/impl-trait/issues/issue-54895.rs | 4 + ....stderr => issue-79099.edition2015.stderr} | 4 +- .../issues/issue-79099.edition2024.stderr | 14 + tests/ui/impl-trait/issues/issue-79099.rs | 5 +- ...-use.stderr => dyn-use.edition2015.stderr} | 2 +- .../dyn-use.edition2024.stderr | 26 ++ .../impl-trait/precise-capturing/dyn-use.rs | 10 +- ...hidden-type-suggestion.edition2015.stderr} | 16 +- .../hidden-type-suggestion.edition2024.stderr | 51 +++ .../hidden-type-suggestion.rs | 15 +- ...rt-from-missing-star-2.edition2015.stderr} | 2 +- ...ort-from-missing-star-2.edition2024.stderr | 11 + .../ui/imports/import-from-missing-star-2.rs | 5 + ...unds_from_bounds_param.edition2015.stderr} | 2 +- ...ounds_from_bounds_param.edition2024.stderr | 91 +++++ .../imply_bounds_from_bounds_param.rs | 13 +- 43 files changed, 1184 insertions(+), 113 deletions(-) rename tests/ui/did_you_mean/{bad-assoc-ty.stderr => bad-assoc-ty.edition2015.stderr} (93%) create mode 100644 tests/ui/did_you_mean/bad-assoc-ty.edition2021.stderr rename tests/ui/feature-gates/{feature-gate-unsized_fn_params.stderr => feature-gate-unsized_fn_params.edition2015.stderr} (91%) create mode 100644 tests/ui/feature-gates/feature-gate-unsized_fn_params.edition2021.stderr rename tests/ui/impl-trait/alias-liveness/{rpit-hidden-erased-unsoundness.stderr => rpit-hidden-erased-unsoundness.edition2015.stderr} (93%) create mode 100644 tests/ui/impl-trait/alias-liveness/rpit-hidden-erased-unsoundness.edition2024.stderr rename tests/ui/impl-trait/alias-liveness/{rpit-hide-lifetime-for-swap.stderr => rpit-hide-lifetime-for-swap.edition2015.stderr} (94%) create mode 100644 tests/ui/impl-trait/alias-liveness/rpit-hide-lifetime-for-swap.edition2024.stderr rename tests/ui/impl-trait/{dyn-trait-return-should-be-impl-trait.stderr => dyn-trait-return-should-be-impl-trait.edition2015.stderr} (92%) create mode 100644 tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.edition2021.stderr rename tests/ui/impl-trait/{hidden-lifetimes.stderr => hidden-lifetimes.edition2015.stderr} (95%) create mode 100644 tests/ui/impl-trait/hidden-lifetimes.edition2024.stderr rename tests/ui/impl-trait/{impl-fn-hrtb-bounds-2.stderr => impl-fn-hrtb-bounds-2.edition2015.stderr} (91%) create mode 100644 tests/ui/impl-trait/impl-fn-hrtb-bounds-2.edition2024.stderr rename tests/ui/impl-trait/{impl-fn-predefined-lifetimes.stderr => impl-fn-predefined-lifetimes.edition2015.stderr} (89%) create mode 100644 tests/ui/impl-trait/impl-fn-predefined-lifetimes.edition2024.stderr rename tests/ui/impl-trait/issues/{issue-54895.stderr => issue-54895.edition2015.stderr} (87%) create mode 100644 tests/ui/impl-trait/issues/issue-54895.edition2024.stderr rename tests/ui/impl-trait/issues/{issue-79099.stderr => issue-79099.edition2015.stderr} (95%) create mode 100644 tests/ui/impl-trait/issues/issue-79099.edition2024.stderr rename tests/ui/impl-trait/precise-capturing/{dyn-use.stderr => dyn-use.edition2015.stderr} (90%) create mode 100644 tests/ui/impl-trait/precise-capturing/dyn-use.edition2024.stderr rename tests/ui/impl-trait/precise-capturing/{hidden-type-suggestion.stderr => hidden-type-suggestion.edition2015.stderr} (93%) create mode 100644 tests/ui/impl-trait/precise-capturing/hidden-type-suggestion.edition2024.stderr rename tests/ui/imports/{import-from-missing-star-2.stderr => import-from-missing-star-2.edition2015.stderr} (89%) create mode 100644 tests/ui/imports/import-from-missing-star-2.edition2024.stderr rename tests/ui/type-alias-impl-trait/{imply_bounds_from_bounds_param.stderr => imply_bounds_from_bounds_param.edition2015.stderr} (93%) create mode 100644 tests/ui/type-alias-impl-trait/imply_bounds_from_bounds_param.edition2024.stderr diff --git a/tests/ui/coroutine/auto-trait-regions.stderr b/tests/ui/coroutine/auto-trait-regions.stderr index 7a5949de55b4b..beb689d868d46 100644 --- a/tests/ui/coroutine/auto-trait-regions.stderr +++ b/tests/ui/coroutine/auto-trait-regions.stderr @@ -1,8 +1,8 @@ error[E0626]: borrow may still be in use when coroutine yields --> $DIR/auto-trait-regions.rs:45:19 | -LL | let gen = #[coroutine] move || { - | ------- within this coroutine +LL | let generator = #[coroutine] move || { + | ------- within this coroutine LL | let a = A(&mut true, &mut true, No); | ^^^^^^^^^ ... @@ -11,14 +11,14 @@ LL | yield; | help: add `static` to mark this coroutine as unmovable | -LL | let gen = #[coroutine] static move || { - | ++++++ +LL | let generator = #[coroutine] static move || { + | ++++++ error[E0626]: borrow may still be in use when coroutine yields --> $DIR/auto-trait-regions.rs:45:30 | -LL | let gen = #[coroutine] move || { - | ------- within this coroutine +LL | let generator = #[coroutine] move || { + | ------- within this coroutine LL | let a = A(&mut true, &mut true, No); | ^^^^^^^^^ ... @@ -27,8 +27,8 @@ LL | yield; | help: add `static` to mark this coroutine as unmovable | -LL | let gen = #[coroutine] static move || { - | ++++++ +LL | let generator = #[coroutine] static move || { + | ++++++ error: implementation of `Foo` is not general enough --> $DIR/auto-trait-regions.rs:31:5 diff --git a/tests/ui/did_you_mean/bad-assoc-ty.stderr b/tests/ui/did_you_mean/bad-assoc-ty.edition2015.stderr similarity index 93% rename from tests/ui/did_you_mean/bad-assoc-ty.stderr rename to tests/ui/did_you_mean/bad-assoc-ty.edition2015.stderr index 7e34f4d35b4e6..0835f766a824d 100644 --- a/tests/ui/did_you_mean/bad-assoc-ty.stderr +++ b/tests/ui/did_you_mean/bad-assoc-ty.edition2015.stderr @@ -1,5 +1,5 @@ error: missing angle brackets in associated item path - --> $DIR/bad-assoc-ty.rs:1:10 + --> $DIR/bad-assoc-ty.rs:5:10 | LL | type A = [u8; 4]::AssocTy; | ^^^^^^^ @@ -10,7 +10,7 @@ LL | type A = <[u8; 4]>::AssocTy; | + + error: missing angle brackets in associated item path - --> $DIR/bad-assoc-ty.rs:5:10 + --> $DIR/bad-assoc-ty.rs:9:10 | LL | type B = [u8]::AssocTy; | ^^^^ @@ -21,7 +21,7 @@ LL | type B = <[u8]>::AssocTy; | + + error: missing angle brackets in associated item path - --> $DIR/bad-assoc-ty.rs:9:10 + --> $DIR/bad-assoc-ty.rs:13:10 | LL | type C = (u8)::AssocTy; | ^^^^ @@ -32,7 +32,7 @@ LL | type C = <(u8)>::AssocTy; | + + error: missing angle brackets in associated item path - --> $DIR/bad-assoc-ty.rs:13:10 + --> $DIR/bad-assoc-ty.rs:17:10 | LL | type D = (u8, u8)::AssocTy; | ^^^^^^^^ @@ -43,7 +43,7 @@ LL | type D = <(u8, u8)>::AssocTy; | + + error: missing angle brackets in associated item path - --> $DIR/bad-assoc-ty.rs:17:10 + --> $DIR/bad-assoc-ty.rs:21:10 | LL | type E = _::AssocTy; | ^ @@ -54,7 +54,7 @@ LL | type E = <_>::AssocTy; | + + error: missing angle brackets in associated item path - --> $DIR/bad-assoc-ty.rs:21:19 + --> $DIR/bad-assoc-ty.rs:25:19 | LL | type F = &'static (u8)::AssocTy; | ^^^^ @@ -65,7 +65,7 @@ LL | type F = &'static <(u8)>::AssocTy; | + + error: missing angle brackets in associated item path - --> $DIR/bad-assoc-ty.rs:27:10 + --> $DIR/bad-assoc-ty.rs:31:10 | LL | type G = dyn 'static + (Send)::AssocTy; | ^^^^^^^^^^^^^^^^^^^^ @@ -76,7 +76,7 @@ LL | type G = ::AssocTy; | + + error: missing angle brackets in associated item path - --> $DIR/bad-assoc-ty.rs:46:10 + --> $DIR/bad-assoc-ty.rs:51:10 | LL | type I = ty!()::AssocTy; | ^^^^^ @@ -87,7 +87,7 @@ LL | type I = ::AssocTy; | + + error: missing angle brackets in associated item path - --> $DIR/bad-assoc-ty.rs:39:19 + --> $DIR/bad-assoc-ty.rs:44:19 | LL | ($ty: ty) => ($ty::AssocTy); | ^^^ @@ -102,7 +102,7 @@ LL | ($ty: ty) => (<$ty>::AssocTy); | + + error[E0223]: ambiguous associated type - --> $DIR/bad-assoc-ty.rs:1:10 + --> $DIR/bad-assoc-ty.rs:5:10 | LL | type A = [u8; 4]::AssocTy; | ^^^^^^^^^^^^^^^^ @@ -114,7 +114,7 @@ LL + type A = <[u8; 4] as Example>::AssocTy; | error[E0223]: ambiguous associated type - --> $DIR/bad-assoc-ty.rs:5:10 + --> $DIR/bad-assoc-ty.rs:9:10 | LL | type B = [u8]::AssocTy; | ^^^^^^^^^^^^^ @@ -126,7 +126,7 @@ LL + type B = <[u8] as Example>::AssocTy; | error[E0223]: ambiguous associated type - --> $DIR/bad-assoc-ty.rs:9:10 + --> $DIR/bad-assoc-ty.rs:13:10 | LL | type C = (u8)::AssocTy; | ^^^^^^^^^^^^^ @@ -138,7 +138,7 @@ LL + type C = ::AssocTy; | error[E0223]: ambiguous associated type - --> $DIR/bad-assoc-ty.rs:13:10 + --> $DIR/bad-assoc-ty.rs:17:10 | LL | type D = (u8, u8)::AssocTy; | ^^^^^^^^^^^^^^^^^ @@ -150,13 +150,13 @@ LL + type D = <(u8, u8) as Example>::AssocTy; | error[E0121]: the placeholder `_` is not allowed within types on item signatures for type aliases - --> $DIR/bad-assoc-ty.rs:17:10 + --> $DIR/bad-assoc-ty.rs:21:10 | LL | type E = _::AssocTy; | ^ not allowed in type signatures error[E0223]: ambiguous associated type - --> $DIR/bad-assoc-ty.rs:21:19 + --> $DIR/bad-assoc-ty.rs:25:19 | LL | type F = &'static (u8)::AssocTy; | ^^^^^^^^^^^^^ @@ -168,7 +168,7 @@ LL + type F = &'static ::AssocTy; | error[E0223]: ambiguous associated type - --> $DIR/bad-assoc-ty.rs:27:10 + --> $DIR/bad-assoc-ty.rs:31:10 | LL | type G = dyn 'static + (Send)::AssocTy; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -180,7 +180,7 @@ LL + type G = <(dyn Send + 'static) as Example>::AssocTy; | warning: trait objects without an explicit `dyn` are deprecated - --> $DIR/bad-assoc-ty.rs:33:10 + --> $DIR/bad-assoc-ty.rs:37:10 | LL | type H = Fn(u8) -> (u8)::Output; | ^^^^^^^^^^^^^^ @@ -194,7 +194,7 @@ LL | type H = (u8)>::Output; | ++++ + error[E0223]: ambiguous associated type - --> $DIR/bad-assoc-ty.rs:33:10 + --> $DIR/bad-assoc-ty.rs:37:10 | LL | type H = Fn(u8) -> (u8)::Output; | ^^^^^^^^^^^^^^^^^^^^^^ @@ -209,7 +209,7 @@ LL + type H = <(dyn Fn(u8) -> u8 + 'static) as IntoFuture>::Output; | error[E0223]: ambiguous associated type - --> $DIR/bad-assoc-ty.rs:39:19 + --> $DIR/bad-assoc-ty.rs:44:19 | LL | ($ty: ty) => ($ty::AssocTy); | ^^^^^^^^^^^^ @@ -225,7 +225,7 @@ LL + ($ty: ty) => (::AssocTy); | error[E0223]: ambiguous associated type - --> $DIR/bad-assoc-ty.rs:46:10 + --> $DIR/bad-assoc-ty.rs:51:10 | LL | type I = ty!()::AssocTy; | ^^^^^^^^^^^^^^ @@ -237,7 +237,7 @@ LL + type I = ::AssocTy; | error[E0121]: the placeholder `_` is not allowed within types on item signatures for functions - --> $DIR/bad-assoc-ty.rs:51:13 + --> $DIR/bad-assoc-ty.rs:56:13 | LL | fn foo>(x: X) {} | ^ ^ not allowed in type signatures @@ -245,7 +245,7 @@ LL | fn foo>(x: X) {} | not allowed in type signatures error[E0121]: the placeholder `_` is not allowed within types on item signatures for functions - --> $DIR/bad-assoc-ty.rs:54:34 + --> $DIR/bad-assoc-ty.rs:59:34 | LL | fn bar(_: F) where F: Fn() -> _ {} | ^ not allowed in type signatures @@ -257,7 +257,7 @@ LL + fn bar(_: F) where F: Fn() -> T {} | error[E0121]: the placeholder `_` is not allowed within types on item signatures for functions - --> $DIR/bad-assoc-ty.rs:57:19 + --> $DIR/bad-assoc-ty.rs:62:19 | LL | fn baz _>(_: F) {} | ^ not allowed in type signatures @@ -269,7 +269,7 @@ LL + fn baz T, T>(_: F) {} | error[E0121]: the placeholder `_` is not allowed within types on item signatures for structs - --> $DIR/bad-assoc-ty.rs:60:33 + --> $DIR/bad-assoc-ty.rs:65:33 | LL | struct L(F) where F: Fn() -> _; | ^ not allowed in type signatures @@ -281,7 +281,7 @@ LL + struct L(F) where F: Fn() -> T; | error[E0121]: the placeholder `_` is not allowed within types on item signatures for functions - --> $DIR/bad-assoc-ty.rs:82:38 + --> $DIR/bad-assoc-ty.rs:87:38 | LL | fn foo(_: F) where F: Fn() -> _ {} | ^ not allowed in type signatures @@ -293,7 +293,7 @@ LL + fn foo(_: F) where F: Fn() -> T {} | error[E0121]: the placeholder `_` is not allowed within types on item signatures for structs - --> $DIR/bad-assoc-ty.rs:62:30 + --> $DIR/bad-assoc-ty.rs:67:30 | LL | struct M where F: Fn() -> _ { | ^ not allowed in type signatures @@ -305,7 +305,7 @@ LL + struct M where F: Fn() -> T { | error[E0121]: the placeholder `_` is not allowed within types on item signatures for enums - --> $DIR/bad-assoc-ty.rs:66:28 + --> $DIR/bad-assoc-ty.rs:71:28 | LL | enum N where F: Fn() -> _ { | ^ not allowed in type signatures @@ -317,7 +317,7 @@ LL + enum N where F: Fn() -> T { | error[E0121]: the placeholder `_` is not allowed within types on item signatures for unions - --> $DIR/bad-assoc-ty.rs:71:29 + --> $DIR/bad-assoc-ty.rs:76:29 | LL | union O where F: Fn() -> _ { | ^ not allowed in type signatures @@ -329,7 +329,7 @@ LL + union O where F: Fn() -> T { | error[E0740]: field must implement `Copy` or be wrapped in `ManuallyDrop<...>` to be used in a union - --> $DIR/bad-assoc-ty.rs:73:5 + --> $DIR/bad-assoc-ty.rs:78:5 | LL | foo: F, | ^^^^^^ @@ -341,7 +341,7 @@ LL | foo: std::mem::ManuallyDrop, | +++++++++++++++++++++++ + error[E0121]: the placeholder `_` is not allowed within types on item signatures for traits - --> $DIR/bad-assoc-ty.rs:77:29 + --> $DIR/bad-assoc-ty.rs:82:29 | LL | trait P where F: Fn() -> _ { | ^ not allowed in type signatures diff --git a/tests/ui/did_you_mean/bad-assoc-ty.edition2021.stderr b/tests/ui/did_you_mean/bad-assoc-ty.edition2021.stderr new file mode 100644 index 0000000000000..3cc403f9ac429 --- /dev/null +++ b/tests/ui/did_you_mean/bad-assoc-ty.edition2021.stderr @@ -0,0 +1,340 @@ +error: missing angle brackets in associated item path + --> $DIR/bad-assoc-ty.rs:5:10 + | +LL | type A = [u8; 4]::AssocTy; + | ^^^^^^^ + | +help: types that don't start with an identifier need to be surrounded with angle brackets in qualified paths + | +LL | type A = <[u8; 4]>::AssocTy; + | + + + +error: missing angle brackets in associated item path + --> $DIR/bad-assoc-ty.rs:9:10 + | +LL | type B = [u8]::AssocTy; + | ^^^^ + | +help: types that don't start with an identifier need to be surrounded with angle brackets in qualified paths + | +LL | type B = <[u8]>::AssocTy; + | + + + +error: missing angle brackets in associated item path + --> $DIR/bad-assoc-ty.rs:13:10 + | +LL | type C = (u8)::AssocTy; + | ^^^^ + | +help: types that don't start with an identifier need to be surrounded with angle brackets in qualified paths + | +LL | type C = <(u8)>::AssocTy; + | + + + +error: missing angle brackets in associated item path + --> $DIR/bad-assoc-ty.rs:17:10 + | +LL | type D = (u8, u8)::AssocTy; + | ^^^^^^^^ + | +help: types that don't start with an identifier need to be surrounded with angle brackets in qualified paths + | +LL | type D = <(u8, u8)>::AssocTy; + | + + + +error: missing angle brackets in associated item path + --> $DIR/bad-assoc-ty.rs:21:10 + | +LL | type E = _::AssocTy; + | ^ + | +help: types that don't start with an identifier need to be surrounded with angle brackets in qualified paths + | +LL | type E = <_>::AssocTy; + | + + + +error: missing angle brackets in associated item path + --> $DIR/bad-assoc-ty.rs:25:19 + | +LL | type F = &'static (u8)::AssocTy; + | ^^^^ + | +help: types that don't start with an identifier need to be surrounded with angle brackets in qualified paths + | +LL | type F = &'static <(u8)>::AssocTy; + | + + + +error: missing angle brackets in associated item path + --> $DIR/bad-assoc-ty.rs:31:10 + | +LL | type G = dyn 'static + (Send)::AssocTy; + | ^^^^^^^^^^^^^^^^^^^^ + | +help: types that don't start with an identifier need to be surrounded with angle brackets in qualified paths + | +LL | type G = ::AssocTy; + | + + + +error: missing angle brackets in associated item path + --> $DIR/bad-assoc-ty.rs:51:10 + | +LL | type I = ty!()::AssocTy; + | ^^^^^ + | +help: types that don't start with an identifier need to be surrounded with angle brackets in qualified paths + | +LL | type I = ::AssocTy; + | + + + +error: missing angle brackets in associated item path + --> $DIR/bad-assoc-ty.rs:44:19 + | +LL | ($ty: ty) => ($ty::AssocTy); + | ^^^ +... +LL | type J = ty!(u8); + | ------- in this macro invocation + | + = note: this error originates in the macro `ty` (in Nightly builds, run with -Z macro-backtrace for more info) +help: types that don't start with an identifier need to be surrounded with angle brackets in qualified paths + | +LL | ($ty: ty) => (<$ty>::AssocTy); + | + + + +error[E0223]: ambiguous associated type + --> $DIR/bad-assoc-ty.rs:5:10 + | +LL | type A = [u8; 4]::AssocTy; + | ^^^^^^^^^^^^^^^^ + | +help: if there were a trait named `Example` with associated type `AssocTy` implemented for `[u8; 4]`, you could use the fully-qualified path + | +LL - type A = [u8; 4]::AssocTy; +LL + type A = <[u8; 4] as Example>::AssocTy; + | + +error[E0223]: ambiguous associated type + --> $DIR/bad-assoc-ty.rs:9:10 + | +LL | type B = [u8]::AssocTy; + | ^^^^^^^^^^^^^ + | +help: if there were a trait named `Example` with associated type `AssocTy` implemented for `[u8]`, you could use the fully-qualified path + | +LL - type B = [u8]::AssocTy; +LL + type B = <[u8] as Example>::AssocTy; + | + +error[E0223]: ambiguous associated type + --> $DIR/bad-assoc-ty.rs:13:10 + | +LL | type C = (u8)::AssocTy; + | ^^^^^^^^^^^^^ + | +help: if there were a trait named `Example` with associated type `AssocTy` implemented for `u8`, you could use the fully-qualified path + | +LL - type C = (u8)::AssocTy; +LL + type C = ::AssocTy; + | + +error[E0223]: ambiguous associated type + --> $DIR/bad-assoc-ty.rs:17:10 + | +LL | type D = (u8, u8)::AssocTy; + | ^^^^^^^^^^^^^^^^^ + | +help: if there were a trait named `Example` with associated type `AssocTy` implemented for `(u8, u8)`, you could use the fully-qualified path + | +LL - type D = (u8, u8)::AssocTy; +LL + type D = <(u8, u8) as Example>::AssocTy; + | + +error[E0121]: the placeholder `_` is not allowed within types on item signatures for type aliases + --> $DIR/bad-assoc-ty.rs:21:10 + | +LL | type E = _::AssocTy; + | ^ not allowed in type signatures + +error[E0223]: ambiguous associated type + --> $DIR/bad-assoc-ty.rs:25:19 + | +LL | type F = &'static (u8)::AssocTy; + | ^^^^^^^^^^^^^ + | +help: if there were a trait named `Example` with associated type `AssocTy` implemented for `u8`, you could use the fully-qualified path + | +LL - type F = &'static (u8)::AssocTy; +LL + type F = &'static ::AssocTy; + | + +error[E0223]: ambiguous associated type + --> $DIR/bad-assoc-ty.rs:31:10 + | +LL | type G = dyn 'static + (Send)::AssocTy; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: if there were a trait named `Example` with associated type `AssocTy` implemented for `(dyn Send + 'static)`, you could use the fully-qualified path + | +LL - type G = dyn 'static + (Send)::AssocTy; +LL + type G = <(dyn Send + 'static) as Example>::AssocTy; + | + +error[E0782]: expected a type, found a trait + --> $DIR/bad-assoc-ty.rs:37:10 + | +LL | type H = Fn(u8) -> (u8)::Output; + | ^^^^^^^^^^^^^^ + | +help: you can add the `dyn` keyword if you want a trait object + | +LL | type H = (u8)>::Output; + | ++++ + + +error[E0223]: ambiguous associated type + --> $DIR/bad-assoc-ty.rs:44:19 + | +LL | ($ty: ty) => ($ty::AssocTy); + | ^^^^^^^^^^^^ +... +LL | type J = ty!(u8); + | ------- in this macro invocation + | + = note: this error originates in the macro `ty` (in Nightly builds, run with -Z macro-backtrace for more info) +help: if there were a trait named `Example` with associated type `AssocTy` implemented for `u8`, you could use the fully-qualified path + | +LL - ($ty: ty) => ($ty::AssocTy); +LL + ($ty: ty) => (::AssocTy); + | + +error[E0223]: ambiguous associated type + --> $DIR/bad-assoc-ty.rs:51:10 + | +LL | type I = ty!()::AssocTy; + | ^^^^^^^^^^^^^^ + | +help: if there were a trait named `Example` with associated type `AssocTy` implemented for `u8`, you could use the fully-qualified path + | +LL - type I = ty!()::AssocTy; +LL + type I = ::AssocTy; + | + +error[E0121]: the placeholder `_` is not allowed within types on item signatures for functions + --> $DIR/bad-assoc-ty.rs:56:13 + | +LL | fn foo>(x: X) {} + | ^ ^ not allowed in type signatures + | | + | not allowed in type signatures + +error[E0121]: the placeholder `_` is not allowed within types on item signatures for functions + --> $DIR/bad-assoc-ty.rs:59:34 + | +LL | fn bar(_: F) where F: Fn() -> _ {} + | ^ not allowed in type signatures + | +help: use type parameters instead + | +LL - fn bar(_: F) where F: Fn() -> _ {} +LL + fn bar(_: F) where F: Fn() -> T {} + | + +error[E0121]: the placeholder `_` is not allowed within types on item signatures for functions + --> $DIR/bad-assoc-ty.rs:62:19 + | +LL | fn baz _>(_: F) {} + | ^ not allowed in type signatures + | +help: use type parameters instead + | +LL - fn baz _>(_: F) {} +LL + fn baz T, T>(_: F) {} + | + +error[E0121]: the placeholder `_` is not allowed within types on item signatures for structs + --> $DIR/bad-assoc-ty.rs:65:33 + | +LL | struct L(F) where F: Fn() -> _; + | ^ not allowed in type signatures + | +help: use type parameters instead + | +LL - struct L(F) where F: Fn() -> _; +LL + struct L(F) where F: Fn() -> T; + | + +error[E0121]: the placeholder `_` is not allowed within types on item signatures for functions + --> $DIR/bad-assoc-ty.rs:87:38 + | +LL | fn foo(_: F) where F: Fn() -> _ {} + | ^ not allowed in type signatures + | +help: use type parameters instead + | +LL - fn foo(_: F) where F: Fn() -> _ {} +LL + fn foo(_: F) where F: Fn() -> T {} + | + +error[E0121]: the placeholder `_` is not allowed within types on item signatures for structs + --> $DIR/bad-assoc-ty.rs:67:30 + | +LL | struct M where F: Fn() -> _ { + | ^ not allowed in type signatures + | +help: use type parameters instead + | +LL - struct M where F: Fn() -> _ { +LL + struct M where F: Fn() -> T { + | + +error[E0121]: the placeholder `_` is not allowed within types on item signatures for enums + --> $DIR/bad-assoc-ty.rs:71:28 + | +LL | enum N where F: Fn() -> _ { + | ^ not allowed in type signatures + | +help: use type parameters instead + | +LL - enum N where F: Fn() -> _ { +LL + enum N where F: Fn() -> T { + | + +error[E0121]: the placeholder `_` is not allowed within types on item signatures for unions + --> $DIR/bad-assoc-ty.rs:76:29 + | +LL | union O where F: Fn() -> _ { + | ^ not allowed in type signatures + | +help: use type parameters instead + | +LL - union O where F: Fn() -> _ { +LL + union O where F: Fn() -> T { + | + +error[E0740]: field must implement `Copy` or be wrapped in `ManuallyDrop<...>` to be used in a union + --> $DIR/bad-assoc-ty.rs:78:5 + | +LL | foo: F, + | ^^^^^^ + | + = note: union fields must not have drop side-effects, which is currently enforced via either `Copy` or `ManuallyDrop<...>` +help: wrap the field type in `ManuallyDrop<...>` + | +LL | foo: std::mem::ManuallyDrop, + | +++++++++++++++++++++++ + + +error[E0121]: the placeholder `_` is not allowed within types on item signatures for traits + --> $DIR/bad-assoc-ty.rs:82:29 + | +LL | trait P where F: Fn() -> _ { + | ^ not allowed in type signatures + | +help: use type parameters instead + | +LL - trait P where F: Fn() -> _ { +LL + trait P where F: Fn() -> T { + | + +error: aborting due to 29 previous errors + +Some errors have detailed explanations: E0121, E0223, E0740, E0782. +For more information about an error, try `rustc --explain E0121`. diff --git a/tests/ui/did_you_mean/bad-assoc-ty.rs b/tests/ui/did_you_mean/bad-assoc-ty.rs index 5a559b01ea281..6e56cba24e1ba 100644 --- a/tests/ui/did_you_mean/bad-assoc-ty.rs +++ b/tests/ui/did_you_mean/bad-assoc-ty.rs @@ -1,3 +1,7 @@ +//@revisions: edition2015 edition2021 +//@[edition2015] edition:2015 +//@[edition2021] edition:2021 + type A = [u8; 4]::AssocTy; //~^ ERROR missing angle brackets in associated item path //~| ERROR ambiguous associated type @@ -31,9 +35,10 @@ type G = dyn 'static + (Send)::AssocTy; // This is actually a legal path with fn-like generic arguments in the middle! // Recovery should not apply in this context. type H = Fn(u8) -> (u8)::Output; -//~^ ERROR ambiguous associated type -//~| WARN trait objects without an explicit `dyn` are deprecated -//~| WARN this is accepted in the current edition +//[edition2015]~^ ERROR ambiguous associated type +//[edition2015]~| WARN trait objects without an explicit `dyn` are deprecated +//[edition2015]~| WARN this is accepted in the current edition +//[edition2021]~^^^^ ERROR expected a type, found a trait macro_rules! ty { ($ty: ty) => ($ty::AssocTy); diff --git a/tests/ui/feature-gates/feature-gate-unsized_fn_params.stderr b/tests/ui/feature-gates/feature-gate-unsized_fn_params.edition2015.stderr similarity index 91% rename from tests/ui/feature-gates/feature-gate-unsized_fn_params.stderr rename to tests/ui/feature-gates/feature-gate-unsized_fn_params.edition2015.stderr index 30f9585176802..ac2d1ffa86849 100644 --- a/tests/ui/feature-gates/feature-gate-unsized_fn_params.stderr +++ b/tests/ui/feature-gates/feature-gate-unsized_fn_params.edition2015.stderr @@ -1,5 +1,5 @@ error[E0277]: the size for values of type `(dyn Foo + 'static)` cannot be known at compilation time - --> $DIR/feature-gate-unsized_fn_params.rs:17:11 + --> $DIR/feature-gate-unsized_fn_params.rs:20:11 | LL | fn foo(x: dyn Foo) { | ^^^^^^^ doesn't have a size known at compile-time @@ -17,7 +17,7 @@ LL | fn foo(x: &dyn Foo) { | + error[E0277]: the size for values of type `(dyn Foo + 'static)` cannot be known at compilation time - --> $DIR/feature-gate-unsized_fn_params.rs:21:11 + --> $DIR/feature-gate-unsized_fn_params.rs:24:11 | LL | fn bar(x: Foo) { | ^^^ doesn't have a size known at compile-time @@ -34,7 +34,7 @@ LL | fn bar(x: &dyn Foo) { | ++++ error[E0277]: the size for values of type `[()]` cannot be known at compilation time - --> $DIR/feature-gate-unsized_fn_params.rs:25:11 + --> $DIR/feature-gate-unsized_fn_params.rs:30:11 | LL | fn qux(_: [()]) {} | ^^^^ doesn't have a size known at compile-time @@ -47,7 +47,7 @@ LL | fn qux(_: &[()]) {} | + error[E0277]: the size for values of type `(dyn Foo + 'static)` cannot be known at compilation time - --> $DIR/feature-gate-unsized_fn_params.rs:29:9 + --> $DIR/feature-gate-unsized_fn_params.rs:34:9 | LL | foo(*x); | ^^ doesn't have a size known at compile-time diff --git a/tests/ui/feature-gates/feature-gate-unsized_fn_params.edition2021.stderr b/tests/ui/feature-gates/feature-gate-unsized_fn_params.edition2021.stderr new file mode 100644 index 0000000000000..12411f695f421 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-unsized_fn_params.edition2021.stderr @@ -0,0 +1,65 @@ +error[E0782]: expected a type, found a trait + --> $DIR/feature-gate-unsized_fn_params.rs:24:11 + | +LL | fn bar(x: Foo) { + | ^^^ + | +help: use a new generic type parameter, constrained by `Foo` + | +LL - fn bar(x: Foo) { +LL + fn bar(x: T) { + | +help: you can also use an opaque type, but users won't be able to specify the type parameter when calling the `fn`, having to rely exclusively on type inference + | +LL | fn bar(x: impl Foo) { + | ++++ +help: alternatively, use a trait object to accept any type that implements `Foo`, accessing its methods at runtime using dynamic dispatch + | +LL | fn bar(x: &dyn Foo) { + | ++++ + +error[E0277]: the size for values of type `(dyn Foo + 'static)` cannot be known at compilation time + --> $DIR/feature-gate-unsized_fn_params.rs:20:11 + | +LL | fn foo(x: dyn Foo) { + | ^^^^^^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `(dyn Foo + 'static)` + = help: unsized fn params are gated as an unstable feature +help: you can use `impl Trait` as the argument type + | +LL - fn foo(x: dyn Foo) { +LL + fn foo(x: impl Foo) { + | +help: function arguments must have a statically known size, borrowed types always have a known size + | +LL | fn foo(x: &dyn Foo) { + | + + +error[E0277]: the size for values of type `[()]` cannot be known at compilation time + --> $DIR/feature-gate-unsized_fn_params.rs:30:11 + | +LL | fn qux(_: [()]) {} + | ^^^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `[()]` + = help: unsized fn params are gated as an unstable feature +help: function arguments must have a statically known size, borrowed slices always have a known size + | +LL | fn qux(_: &[()]) {} + | + + +error[E0277]: the size for values of type `(dyn Foo + 'static)` cannot be known at compilation time + --> $DIR/feature-gate-unsized_fn_params.rs:34:9 + | +LL | foo(*x); + | ^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `(dyn Foo + 'static)` + = note: all function arguments must have a statically known size + = help: unsized fn params are gated as an unstable feature + +error: aborting due to 4 previous errors + +Some errors have detailed explanations: E0277, E0782. +For more information about an error, try `rustc --explain E0277`. diff --git a/tests/ui/feature-gates/feature-gate-unsized_fn_params.rs b/tests/ui/feature-gates/feature-gate-unsized_fn_params.rs index c04e57843d4b2..3c5f932e89189 100644 --- a/tests/ui/feature-gates/feature-gate-unsized_fn_params.rs +++ b/tests/ui/feature-gates/feature-gate-unsized_fn_params.rs @@ -1,3 +1,6 @@ +//@revisions: edition2015 edition2021 +//@[edition2015] edition:2015 +//@[edition2021] edition:2021 #![allow(unused, bare_trait_objects)] #[repr(align(256))] struct A { @@ -18,7 +21,9 @@ fn foo(x: dyn Foo) { //~ ERROR [E0277] x.foo() } -fn bar(x: Foo) { //~ ERROR [E0277] +fn bar(x: Foo) { +//[edition2015]~^ ERROR [E0277] +//[edition2021]~^^ ERROR expected a type, found a trait x.foo() } diff --git a/tests/ui/impl-trait/alias-liveness/rpit-hidden-erased-unsoundness.stderr b/tests/ui/impl-trait/alias-liveness/rpit-hidden-erased-unsoundness.edition2015.stderr similarity index 93% rename from tests/ui/impl-trait/alias-liveness/rpit-hidden-erased-unsoundness.stderr rename to tests/ui/impl-trait/alias-liveness/rpit-hidden-erased-unsoundness.edition2015.stderr index a2d00edbb6d95..68b4e2ed39fb6 100644 --- a/tests/ui/impl-trait/alias-liveness/rpit-hidden-erased-unsoundness.stderr +++ b/tests/ui/impl-trait/alias-liveness/rpit-hidden-erased-unsoundness.edition2015.stderr @@ -1,5 +1,5 @@ error[E0700]: hidden type for `impl Sized + 'a` captures lifetime that does not appear in bounds - --> $DIR/rpit-hidden-erased-unsoundness.rs:16:5 + --> $DIR/rpit-hidden-erased-unsoundness.rs:19:5 | LL | fn step2<'a, 'b: 'a>() -> impl Sized + 'a { | -- --------------- opaque type defined here diff --git a/tests/ui/impl-trait/alias-liveness/rpit-hidden-erased-unsoundness.edition2024.stderr b/tests/ui/impl-trait/alias-liveness/rpit-hidden-erased-unsoundness.edition2024.stderr new file mode 100644 index 0000000000000..6c0c178958270 --- /dev/null +++ b/tests/ui/impl-trait/alias-liveness/rpit-hidden-erased-unsoundness.edition2024.stderr @@ -0,0 +1,10 @@ +error: lifetime may not live long enough + --> $DIR/rpit-hidden-erased-unsoundness.rs:24:5 + | +LL | fn step3<'a, 'b: 'a>() -> impl Send + 'a { + | -- lifetime `'b` defined here +LL | step2::<'a, 'b>() + | ^^^^^^^^^^^^^^^^^ returning this value requires that `'b` must outlive `'static` + +error: aborting due to 1 previous error + diff --git a/tests/ui/impl-trait/alias-liveness/rpit-hidden-erased-unsoundness.rs b/tests/ui/impl-trait/alias-liveness/rpit-hidden-erased-unsoundness.rs index 6863a3c73badf..3338063d8c68c 100644 --- a/tests/ui/impl-trait/alias-liveness/rpit-hidden-erased-unsoundness.rs +++ b/tests/ui/impl-trait/alias-liveness/rpit-hidden-erased-unsoundness.rs @@ -1,3 +1,6 @@ +//@revisions: edition2015 edition2024 +//@[edition2015] edition:2015 +//@[edition2024] edition:2024 // This test should never pass! #![feature(type_alias_impl_trait)] @@ -14,11 +17,12 @@ fn step1<'a, 'b: 'a>() -> impl Sized + Captures<'b> + 'a { fn step2<'a, 'b: 'a>() -> impl Sized + 'a { step1::<'a, 'b>() - //~^ ERROR hidden type for `impl Sized + 'a` captures lifetime that does not appear in bounds + //[edition2015]~^ ERROR hidden type for `impl Sized + 'a` captures lifetime that does not appear in bounds } fn step3<'a, 'b: 'a>() -> impl Send + 'a { step2::<'a, 'b>() + //[edition2024]~^ ERROR lifetime may not live long enough // This should not be Send unless `'b: 'static` } diff --git a/tests/ui/impl-trait/alias-liveness/rpit-hide-lifetime-for-swap.stderr b/tests/ui/impl-trait/alias-liveness/rpit-hide-lifetime-for-swap.edition2015.stderr similarity index 94% rename from tests/ui/impl-trait/alias-liveness/rpit-hide-lifetime-for-swap.stderr rename to tests/ui/impl-trait/alias-liveness/rpit-hide-lifetime-for-swap.edition2015.stderr index a1e92e5338469..769a878a45c77 100644 --- a/tests/ui/impl-trait/alias-liveness/rpit-hide-lifetime-for-swap.stderr +++ b/tests/ui/impl-trait/alias-liveness/rpit-hide-lifetime-for-swap.edition2015.stderr @@ -1,5 +1,5 @@ error[E0700]: hidden type for `impl Swap + 'a` captures lifetime that does not appear in bounds - --> $DIR/rpit-hide-lifetime-for-swap.rs:17:5 + --> $DIR/rpit-hide-lifetime-for-swap.rs:20:5 | LL | fn hide<'a, 'b: 'a, T: 'static>(x: Rc>) -> impl Swap + 'a { | -- -------------- opaque type defined here diff --git a/tests/ui/impl-trait/alias-liveness/rpit-hide-lifetime-for-swap.edition2024.stderr b/tests/ui/impl-trait/alias-liveness/rpit-hide-lifetime-for-swap.edition2024.stderr new file mode 100644 index 0000000000000..6109184250bbe --- /dev/null +++ b/tests/ui/impl-trait/alias-liveness/rpit-hide-lifetime-for-swap.edition2024.stderr @@ -0,0 +1,17 @@ +error[E0597]: `x` does not live long enough + --> $DIR/rpit-hide-lifetime-for-swap.rs:27:38 + | +LL | let x = [1, 2, 3]; + | - binding `x` declared here +LL | let short = Rc::new(RefCell::new(&x)); + | ^^ borrowed value does not live long enough +... +LL | let res: &'static [i32; 3] = *long.borrow(); + | ----------------- type annotation requires that `x` is borrowed for `'static` +LL | res +LL | } + | - `x` dropped here while still borrowed + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0597`. diff --git a/tests/ui/impl-trait/alias-liveness/rpit-hide-lifetime-for-swap.rs b/tests/ui/impl-trait/alias-liveness/rpit-hide-lifetime-for-swap.rs index 4de2ffbb80870..c4eaec478b840 100644 --- a/tests/ui/impl-trait/alias-liveness/rpit-hide-lifetime-for-swap.rs +++ b/tests/ui/impl-trait/alias-liveness/rpit-hide-lifetime-for-swap.rs @@ -1,3 +1,6 @@ +//@revisions: edition2015 edition2024 +//@[edition2015] edition:2015 +//@[edition2024] edition:2024 // This test should never pass! use std::cell::RefCell; @@ -15,13 +18,14 @@ impl Swap for Rc> { fn hide<'a, 'b: 'a, T: 'static>(x: Rc>) -> impl Swap + 'a { x - //~^ ERROR hidden type for `impl Swap + 'a` captures lifetime that does not appear in bounds + //[edition2015]~^ ERROR hidden type for `impl Swap + 'a` captures lifetime that does not appear in bounds } fn dangle() -> &'static [i32; 3] { let long = Rc::new(RefCell::new(&[4, 5, 6])); let x = [1, 2, 3]; let short = Rc::new(RefCell::new(&x)); + //[edition2024]~^ ERROR `x` does not live long enough hide(long.clone()).swap(hide(short)); let res: &'static [i32; 3] = *long.borrow(); res diff --git a/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.stderr b/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.edition2015.stderr similarity index 92% rename from tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.stderr rename to tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.edition2015.stderr index 304d7d43b78b3..64f0b201ca284 100644 --- a/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.stderr +++ b/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.edition2015.stderr @@ -1,5 +1,5 @@ error[E0277]: the size for values of type `(dyn Trait + 'static)` cannot be known at compilation time - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:7:13 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:10:13 | LL | fn fuz() -> (usize, Trait) { (42, Struct) } | ^^^^^^^^^^^^^^ doesn't have a size known at compile-time @@ -9,7 +9,7 @@ LL | fn fuz() -> (usize, Trait) { (42, Struct) } = note: the return type of a function must have a statically known size error[E0277]: the size for values of type `(dyn Trait + 'static)` cannot be known at compilation time - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:11:13 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:15:13 | LL | fn bar() -> (usize, dyn Trait) { (42, Struct) } | ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time @@ -19,7 +19,7 @@ LL | fn bar() -> (usize, dyn Trait) { (42, Struct) } = note: the return type of a function must have a statically known size error[E0746]: return type cannot be a trait object without pointer indirection - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:15:13 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:19:13 | LL | fn bap() -> Trait { Struct } | ^^^^^ doesn't have a size known at compile-time @@ -34,7 +34,7 @@ LL | fn bap() -> Box { Box::new(Struct) } | +++++++ + +++++++++ + error[E0746]: return type cannot be a trait object without pointer indirection - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:17:13 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:22:13 | LL | fn ban() -> dyn Trait { Struct } | ^^^^^^^^^ doesn't have a size known at compile-time @@ -50,7 +50,7 @@ LL | fn ban() -> Box { Box::new(Struct) } | ++++ + +++++++++ + error[E0746]: return type cannot be a trait object without pointer indirection - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:19:13 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:24:13 | LL | fn bak() -> dyn Trait { unimplemented!() } | ^^^^^^^^^ doesn't have a size known at compile-time @@ -66,7 +66,7 @@ LL | fn bak() -> Box { Box::new(unimplemented!()) } | ++++ + +++++++++ + error[E0746]: return type cannot be a trait object without pointer indirection - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:21:13 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:26:13 | LL | fn bal() -> dyn Trait { | ^^^^^^^^^ doesn't have a size known at compile-time @@ -86,7 +86,7 @@ LL ~ Box::new(42) | error[E0746]: return type cannot be a trait object without pointer indirection - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:27:13 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:32:13 | LL | fn bax() -> dyn Trait { | ^^^^^^^^^ doesn't have a size known at compile-time @@ -106,7 +106,7 @@ LL ~ Box::new(42) | error[E0746]: return type cannot be a trait object without pointer indirection - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:62:13 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:67:13 | LL | fn bat() -> dyn Trait { | ^^^^^^^^^ doesn't have a size known at compile-time @@ -126,7 +126,7 @@ LL ~ Box::new(42) | error[E0746]: return type cannot be a trait object without pointer indirection - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:68:13 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:73:13 | LL | fn bay() -> dyn Trait { | ^^^^^^^^^ doesn't have a size known at compile-time @@ -146,7 +146,7 @@ LL ~ Box::new(42) | error[E0308]: mismatched types - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:7:35 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:10:35 | LL | fn fuz() -> (usize, Trait) { (42, Struct) } | ^^^^^^ expected `dyn Trait`, found `Struct` @@ -156,7 +156,7 @@ LL | fn fuz() -> (usize, Trait) { (42, Struct) } = help: `Struct` implements `Trait` so you could box the found value and coerce it to the trait object `Box`, you will have to change the expected type as well error[E0277]: the size for values of type `(dyn Trait + 'static)` cannot be known at compilation time - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:7:30 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:10:30 | LL | fn fuz() -> (usize, Trait) { (42, Struct) } | ^^^^^^^^^^^^ doesn't have a size known at compile-time @@ -166,7 +166,7 @@ LL | fn fuz() -> (usize, Trait) { (42, Struct) } = note: tuples must have a statically known size to be initialized error[E0308]: mismatched types - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:11:39 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:15:39 | LL | fn bar() -> (usize, dyn Trait) { (42, Struct) } | ^^^^^^ expected `dyn Trait`, found `Struct` @@ -176,7 +176,7 @@ LL | fn bar() -> (usize, dyn Trait) { (42, Struct) } = help: `Struct` implements `Trait` so you could box the found value and coerce it to the trait object `Box`, you will have to change the expected type as well error[E0277]: the size for values of type `(dyn Trait + 'static)` cannot be known at compilation time - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:11:34 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:15:34 | LL | fn bar() -> (usize, dyn Trait) { (42, Struct) } | ^^^^^^^^^^^^ doesn't have a size known at compile-time @@ -186,7 +186,7 @@ LL | fn bar() -> (usize, dyn Trait) { (42, Struct) } = note: tuples must have a statically known size to be initialized error[E0308]: mismatched types - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:36:16 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:41:16 | LL | fn bam() -> Box { | -------------- expected `Box<(dyn Trait + 'static)>` because of return type @@ -203,7 +203,7 @@ LL | return Box::new(Struct); | +++++++++ + error[E0308]: mismatched types - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:38:5 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:43:5 | LL | fn bam() -> Box { | -------------- expected `Box<(dyn Trait + 'static)>` because of return type @@ -220,7 +220,7 @@ LL | Box::new(42) | +++++++++ + error[E0308]: mismatched types - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:42:16 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:47:16 | LL | fn baq() -> Box { | -------------- expected `Box<(dyn Trait + 'static)>` because of return type @@ -237,7 +237,7 @@ LL | return Box::new(0); | +++++++++ + error[E0308]: mismatched types - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:44:5 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:49:5 | LL | fn baq() -> Box { | -------------- expected `Box<(dyn Trait + 'static)>` because of return type @@ -254,7 +254,7 @@ LL | Box::new(42) | +++++++++ + error[E0308]: mismatched types - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:48:9 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:53:9 | LL | fn baz() -> Box { | -------------- expected `Box<(dyn Trait + 'static)>` because of return type @@ -271,7 +271,7 @@ LL | Box::new(Struct) | +++++++++ + error[E0308]: mismatched types - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:50:9 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:55:9 | LL | fn baz() -> Box { | -------------- expected `Box<(dyn Trait + 'static)>` because of return type @@ -288,7 +288,7 @@ LL | Box::new(42) | +++++++++ + error[E0308]: mismatched types - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:55:9 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:60:9 | LL | fn baw() -> Box { | -------------- expected `Box<(dyn Trait + 'static)>` because of return type @@ -305,7 +305,7 @@ LL | Box::new(0) | +++++++++ + error[E0308]: mismatched types - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:57:9 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:62:9 | LL | fn baw() -> Box { | -------------- expected `Box<(dyn Trait + 'static)>` because of return type diff --git a/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.edition2021.stderr b/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.edition2021.stderr new file mode 100644 index 0000000000000..5811431b49406 --- /dev/null +++ b/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.edition2021.stderr @@ -0,0 +1,308 @@ +error[E0782]: expected a type, found a trait + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:10:21 + | +LL | fn fuz() -> (usize, Trait) { (42, Struct) } + | ^^^^^ + | +help: you can add the `dyn` keyword if you want a trait object + | +LL | fn fuz() -> (usize, dyn Trait) { (42, Struct) } + | +++ + +error[E0277]: the size for values of type `(dyn Trait + 'static)` cannot be known at compilation time + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:15:13 + | +LL | fn bar() -> (usize, dyn Trait) { (42, Struct) } + | ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time + | + = help: within `(usize, (dyn Trait + 'static))`, the trait `Sized` is not implemented for `(dyn Trait + 'static)` + = note: required because it appears within the type `(usize, (dyn Trait + 'static))` + = note: the return type of a function must have a statically known size + +error[E0782]: expected a type, found a trait + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:19:13 + | +LL | fn bap() -> Trait { Struct } + | ^^^^^ + | +help: use `impl Trait` to return an opaque type, as long as you return a single underlying type + | +LL | fn bap() -> impl Trait { Struct } + | ++++ +help: alternatively, you can return an owned trait object + | +LL | fn bap() -> Box { Struct } + | +++++++ + + +error[E0746]: return type cannot be a trait object without pointer indirection + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:22:13 + | +LL | fn ban() -> dyn Trait { Struct } + | ^^^^^^^^^ doesn't have a size known at compile-time + | +help: consider returning an `impl Trait` instead of a `dyn Trait` + | +LL - fn ban() -> dyn Trait { Struct } +LL + fn ban() -> impl Trait { Struct } + | +help: alternatively, box the return type, and wrap all of the returned values in `Box::new` + | +LL | fn ban() -> Box { Box::new(Struct) } + | ++++ + +++++++++ + + +error[E0746]: return type cannot be a trait object without pointer indirection + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:24:13 + | +LL | fn bak() -> dyn Trait { unimplemented!() } + | ^^^^^^^^^ doesn't have a size known at compile-time + | +help: consider returning an `impl Trait` instead of a `dyn Trait` + | +LL - fn bak() -> dyn Trait { unimplemented!() } +LL + fn bak() -> impl Trait { unimplemented!() } + | +help: alternatively, box the return type, and wrap all of the returned values in `Box::new` + | +LL | fn bak() -> Box { Box::new(unimplemented!()) } + | ++++ + +++++++++ + + +error[E0746]: return type cannot be a trait object without pointer indirection + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:26:13 + | +LL | fn bal() -> dyn Trait { + | ^^^^^^^^^ doesn't have a size known at compile-time + | +help: consider returning an `impl Trait` instead of a `dyn Trait` + | +LL - fn bal() -> dyn Trait { +LL + fn bal() -> impl Trait { + | +help: alternatively, box the return type, and wrap all of the returned values in `Box::new` + | +LL ~ fn bal() -> Box { +LL | if true { +LL ~ return Box::new(Struct); +LL | } +LL ~ Box::new(42) + | + +error[E0746]: return type cannot be a trait object without pointer indirection + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:32:13 + | +LL | fn bax() -> dyn Trait { + | ^^^^^^^^^ doesn't have a size known at compile-time + | +help: consider returning an `impl Trait` instead of a `dyn Trait` + | +LL - fn bax() -> dyn Trait { +LL + fn bax() -> impl Trait { + | +help: alternatively, box the return type, and wrap all of the returned values in `Box::new` + | +LL ~ fn bax() -> Box { +LL | if true { +LL ~ Box::new(Struct) +LL | } else { +LL ~ Box::new(42) + | + +error[E0746]: return type cannot be a trait object without pointer indirection + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:67:13 + | +LL | fn bat() -> dyn Trait { + | ^^^^^^^^^ doesn't have a size known at compile-time + | +help: consider returning an `impl Trait` instead of a `dyn Trait` + | +LL - fn bat() -> dyn Trait { +LL + fn bat() -> impl Trait { + | +help: alternatively, box the return type, and wrap all of the returned values in `Box::new` + | +LL ~ fn bat() -> Box { +LL | if true { +LL ~ return Box::new(0); +LL | } +LL ~ Box::new(42) + | + +error[E0746]: return type cannot be a trait object without pointer indirection + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:73:13 + | +LL | fn bay() -> dyn Trait { + | ^^^^^^^^^ doesn't have a size known at compile-time + | +help: consider returning an `impl Trait` instead of a `dyn Trait` + | +LL - fn bay() -> dyn Trait { +LL + fn bay() -> impl Trait { + | +help: alternatively, box the return type, and wrap all of the returned values in `Box::new` + | +LL ~ fn bay() -> Box { +LL | if true { +LL ~ Box::new(0) +LL | } else { +LL ~ Box::new(42) + | + +error[E0308]: mismatched types + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:15:39 + | +LL | fn bar() -> (usize, dyn Trait) { (42, Struct) } + | ^^^^^^ expected `dyn Trait`, found `Struct` + | + = note: expected trait object `(dyn Trait + 'static)` + found struct `Struct` + = help: `Struct` implements `Trait` so you could box the found value and coerce it to the trait object `Box`, you will have to change the expected type as well + +error[E0277]: the size for values of type `(dyn Trait + 'static)` cannot be known at compilation time + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:15:34 + | +LL | fn bar() -> (usize, dyn Trait) { (42, Struct) } + | ^^^^^^^^^^^^ doesn't have a size known at compile-time + | + = help: within `(usize, (dyn Trait + 'static))`, the trait `Sized` is not implemented for `(dyn Trait + 'static)` + = note: required because it appears within the type `(usize, (dyn Trait + 'static))` + = note: tuples must have a statically known size to be initialized + +error[E0308]: mismatched types + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:41:16 + | +LL | fn bam() -> Box { + | -------------- expected `Box<(dyn Trait + 'static)>` because of return type +LL | if true { +LL | return Struct; + | ^^^^^^ expected `Box`, found `Struct` + | + = note: expected struct `Box<(dyn Trait + 'static)>` + found struct `Struct` + = note: for more on the distinction between the stack and the heap, read https://doc.rust-lang.org/book/ch15-01-box.html, https://doc.rust-lang.org/rust-by-example/std/box.html, and https://doc.rust-lang.org/std/boxed/index.html +help: store this in the heap by calling `Box::new` + | +LL | return Box::new(Struct); + | +++++++++ + + +error[E0308]: mismatched types + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:43:5 + | +LL | fn bam() -> Box { + | -------------- expected `Box<(dyn Trait + 'static)>` because of return type +... +LL | 42 + | ^^ expected `Box`, found integer + | + = note: expected struct `Box<(dyn Trait + 'static)>` + found type `{integer}` + = note: for more on the distinction between the stack and the heap, read https://doc.rust-lang.org/book/ch15-01-box.html, https://doc.rust-lang.org/rust-by-example/std/box.html, and https://doc.rust-lang.org/std/boxed/index.html +help: store this in the heap by calling `Box::new` + | +LL | Box::new(42) + | +++++++++ + + +error[E0308]: mismatched types + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:47:16 + | +LL | fn baq() -> Box { + | -------------- expected `Box<(dyn Trait + 'static)>` because of return type +LL | if true { +LL | return 0; + | ^ expected `Box`, found integer + | + = note: expected struct `Box<(dyn Trait + 'static)>` + found type `{integer}` + = note: for more on the distinction between the stack and the heap, read https://doc.rust-lang.org/book/ch15-01-box.html, https://doc.rust-lang.org/rust-by-example/std/box.html, and https://doc.rust-lang.org/std/boxed/index.html +help: store this in the heap by calling `Box::new` + | +LL | return Box::new(0); + | +++++++++ + + +error[E0308]: mismatched types + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:49:5 + | +LL | fn baq() -> Box { + | -------------- expected `Box<(dyn Trait + 'static)>` because of return type +... +LL | 42 + | ^^ expected `Box`, found integer + | + = note: expected struct `Box<(dyn Trait + 'static)>` + found type `{integer}` + = note: for more on the distinction between the stack and the heap, read https://doc.rust-lang.org/book/ch15-01-box.html, https://doc.rust-lang.org/rust-by-example/std/box.html, and https://doc.rust-lang.org/std/boxed/index.html +help: store this in the heap by calling `Box::new` + | +LL | Box::new(42) + | +++++++++ + + +error[E0308]: mismatched types + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:53:9 + | +LL | fn baz() -> Box { + | -------------- expected `Box<(dyn Trait + 'static)>` because of return type +LL | if true { +LL | Struct + | ^^^^^^ expected `Box`, found `Struct` + | + = note: expected struct `Box<(dyn Trait + 'static)>` + found struct `Struct` + = note: for more on the distinction between the stack and the heap, read https://doc.rust-lang.org/book/ch15-01-box.html, https://doc.rust-lang.org/rust-by-example/std/box.html, and https://doc.rust-lang.org/std/boxed/index.html +help: store this in the heap by calling `Box::new` + | +LL | Box::new(Struct) + | +++++++++ + + +error[E0308]: mismatched types + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:55:9 + | +LL | fn baz() -> Box { + | -------------- expected `Box<(dyn Trait + 'static)>` because of return type +... +LL | 42 + | ^^ expected `Box`, found integer + | + = note: expected struct `Box<(dyn Trait + 'static)>` + found type `{integer}` + = note: for more on the distinction between the stack and the heap, read https://doc.rust-lang.org/book/ch15-01-box.html, https://doc.rust-lang.org/rust-by-example/std/box.html, and https://doc.rust-lang.org/std/boxed/index.html +help: store this in the heap by calling `Box::new` + | +LL | Box::new(42) + | +++++++++ + + +error[E0308]: mismatched types + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:60:9 + | +LL | fn baw() -> Box { + | -------------- expected `Box<(dyn Trait + 'static)>` because of return type +LL | if true { +LL | 0 + | ^ expected `Box`, found integer + | + = note: expected struct `Box<(dyn Trait + 'static)>` + found type `{integer}` + = note: for more on the distinction between the stack and the heap, read https://doc.rust-lang.org/book/ch15-01-box.html, https://doc.rust-lang.org/rust-by-example/std/box.html, and https://doc.rust-lang.org/std/boxed/index.html +help: store this in the heap by calling `Box::new` + | +LL | Box::new(0) + | +++++++++ + + +error[E0308]: mismatched types + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:62:9 + | +LL | fn baw() -> Box { + | -------------- expected `Box<(dyn Trait + 'static)>` because of return type +... +LL | 42 + | ^^ expected `Box`, found integer + | + = note: expected struct `Box<(dyn Trait + 'static)>` + found type `{integer}` + = note: for more on the distinction between the stack and the heap, read https://doc.rust-lang.org/book/ch15-01-box.html, https://doc.rust-lang.org/rust-by-example/std/box.html, and https://doc.rust-lang.org/std/boxed/index.html +help: store this in the heap by calling `Box::new` + | +LL | Box::new(42) + | +++++++++ + + +error: aborting due to 19 previous errors + +Some errors have detailed explanations: E0277, E0308, E0746, E0782. +For more information about an error, try `rustc --explain E0277`. diff --git a/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.rs b/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.rs index ccf0a1ad3d443..aa1f871d8eaab 100644 --- a/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.rs +++ b/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.rs @@ -1,3 +1,6 @@ +//@revisions: edition2015 edition2021 +//@[edition2015] edition:2015 +//@[edition2021] edition:2021 #![allow(bare_trait_objects)] struct Struct; trait Trait {} @@ -5,15 +8,17 @@ impl Trait for Struct {} impl Trait for u32 {} fn fuz() -> (usize, Trait) { (42, Struct) } -//~^ ERROR E0277 -//~| ERROR E0277 -//~| ERROR E0308 +//[edition2015]~^ ERROR E0277 +//[edition2015]~| ERROR E0277 +//[edition2015]~| ERROR E0308 +//[edition2021]~^^^^ ERROR expected a type, found a trait fn bar() -> (usize, dyn Trait) { (42, Struct) } //~^ ERROR E0277 //~| ERROR E0277 //~| ERROR E0308 fn bap() -> Trait { Struct } -//~^ ERROR E0746 +//[edition2015]~^ ERROR E0746 +//[edition2021]~^^ ERROR expected a type, found a trait fn ban() -> dyn Trait { Struct } //~^ ERROR E0746 fn bak() -> dyn Trait { unimplemented!() } //~ ERROR E0746 diff --git a/tests/ui/impl-trait/hidden-lifetimes.stderr b/tests/ui/impl-trait/hidden-lifetimes.edition2015.stderr similarity index 95% rename from tests/ui/impl-trait/hidden-lifetimes.stderr rename to tests/ui/impl-trait/hidden-lifetimes.edition2015.stderr index 70d8c816ecb44..b63115f76588f 100644 --- a/tests/ui/impl-trait/hidden-lifetimes.stderr +++ b/tests/ui/impl-trait/hidden-lifetimes.edition2015.stderr @@ -1,5 +1,5 @@ error[E0700]: hidden type for `impl Swap + 'a` captures lifetime that does not appear in bounds - --> $DIR/hidden-lifetimes.rs:29:5 + --> $DIR/hidden-lifetimes.rs:33:5 | LL | fn hide_ref<'a, 'b, T: 'static>(x: &'a mut &'b T) -> impl Swap + 'a { | -- -------------- opaque type defined here @@ -14,7 +14,7 @@ LL | fn hide_ref<'a, 'b, T: 'static>(x: &'a mut &'b T) -> impl Swap + 'a + use<' | ++++++++++++++++ error[E0700]: hidden type for `impl Swap + 'a` captures lifetime that does not appear in bounds - --> $DIR/hidden-lifetimes.rs:46:5 + --> $DIR/hidden-lifetimes.rs:50:5 | LL | fn hide_rc_refcell<'a, 'b: 'a, T: 'static>(x: Rc>) -> impl Swap + 'a { | -- -------------- opaque type defined here diff --git a/tests/ui/impl-trait/hidden-lifetimes.edition2024.stderr b/tests/ui/impl-trait/hidden-lifetimes.edition2024.stderr new file mode 100644 index 0000000000000..d585bb50b13f7 --- /dev/null +++ b/tests/ui/impl-trait/hidden-lifetimes.edition2024.stderr @@ -0,0 +1,26 @@ +error[E0515]: cannot return value referencing local variable `x` + --> $DIR/hidden-lifetimes.rs:41:5 + | +LL | hide_ref(&mut res).swap(hide_ref(&mut &x)); + | -- `x` is borrowed here +LL | res + | ^^^ returns a value referencing data owned by the current function + +error[E0597]: `x` does not live long enough + --> $DIR/hidden-lifetimes.rs:57:38 + | +LL | let x = [1, 2, 3]; + | - binding `x` declared here +LL | let short = Rc::new(RefCell::new(&x)); + | ^^ borrowed value does not live long enough +LL | hide_rc_refcell(long.clone()).swap(hide_rc_refcell(short)); +LL | let res: &'static [i32; 3] = *long.borrow(); + | ----------------- type annotation requires that `x` is borrowed for `'static` +LL | res +LL | } + | - `x` dropped here while still borrowed + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0515, E0597. +For more information about an error, try `rustc --explain E0515`. diff --git a/tests/ui/impl-trait/hidden-lifetimes.rs b/tests/ui/impl-trait/hidden-lifetimes.rs index ae07c89276861..b50c43bd3fa00 100644 --- a/tests/ui/impl-trait/hidden-lifetimes.rs +++ b/tests/ui/impl-trait/hidden-lifetimes.rs @@ -1,3 +1,7 @@ +//@revisions: edition2015 edition2024 +//@[edition2015] edition:2015 +//@[edition2024] edition:2024 + // Test to show what happens if we were not careful and allowed invariant // lifetimes to escape though an impl trait. // @@ -27,14 +31,14 @@ impl Swap for Rc> { // `&'a mut &'l T` are the same type. fn hide_ref<'a, 'b, T: 'static>(x: &'a mut &'b T) -> impl Swap + 'a { x - //~^ ERROR hidden type + //[edition2015]~^ ERROR hidden type } fn dangle_ref() -> &'static [i32; 3] { let mut res = &[4, 5, 6]; let x = [1, 2, 3]; hide_ref(&mut res).swap(hide_ref(&mut &x)); - res + res //[edition2024]~ ERROR cannot return value referencing local variable `x` } // Here we are hiding `'b` making the caller believe that `Rc>` @@ -44,13 +48,13 @@ fn dangle_ref() -> &'static [i32; 3] { // only has a single lifetime. fn hide_rc_refcell<'a, 'b: 'a, T: 'static>(x: Rc>) -> impl Swap + 'a { x - //~^ ERROR hidden type + //[edition2015]~^ ERROR hidden type } fn dangle_rc_refcell() -> &'static [i32; 3] { let long = Rc::new(RefCell::new(&[4, 5, 6])); let x = [1, 2, 3]; - let short = Rc::new(RefCell::new(&x)); + let short = Rc::new(RefCell::new(&x)); //[edition2024]~ ERROR `x` does not live long enough hide_rc_refcell(long.clone()).swap(hide_rc_refcell(short)); let res: &'static [i32; 3] = *long.borrow(); res diff --git a/tests/ui/impl-trait/impl-fn-hrtb-bounds-2.stderr b/tests/ui/impl-trait/impl-fn-hrtb-bounds-2.edition2015.stderr similarity index 91% rename from tests/ui/impl-trait/impl-fn-hrtb-bounds-2.stderr rename to tests/ui/impl-trait/impl-fn-hrtb-bounds-2.edition2015.stderr index 4e453c108d4bb..4ba59826231c5 100644 --- a/tests/ui/impl-trait/impl-fn-hrtb-bounds-2.stderr +++ b/tests/ui/impl-trait/impl-fn-hrtb-bounds-2.edition2015.stderr @@ -1,5 +1,5 @@ error[E0700]: hidden type for `impl Debug` captures lifetime that does not appear in bounds - --> $DIR/impl-fn-hrtb-bounds-2.rs:5:9 + --> $DIR/impl-fn-hrtb-bounds-2.rs:8:9 | LL | fn a() -> impl Fn(&u8) -> impl Debug { | ---------- opaque type defined here diff --git a/tests/ui/impl-trait/impl-fn-hrtb-bounds-2.edition2024.stderr b/tests/ui/impl-trait/impl-fn-hrtb-bounds-2.edition2024.stderr new file mode 100644 index 0000000000000..c7aedfe96bb9b --- /dev/null +++ b/tests/ui/impl-trait/impl-fn-hrtb-bounds-2.edition2024.stderr @@ -0,0 +1,15 @@ +error[E0657]: `impl Trait` cannot capture higher-ranked lifetime from outer `impl Trait` + --> $DIR/impl-fn-hrtb-bounds-2.rs:7:27 + | +LL | fn a() -> impl Fn(&u8) -> impl Debug { + | ^^^^^^^^^^ `impl Trait` implicitly captures all lifetimes in scope + | +note: lifetime declared here + --> $DIR/impl-fn-hrtb-bounds-2.rs:7:19 + | +LL | fn a() -> impl Fn(&u8) -> impl Debug { + | ^ + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0657`. diff --git a/tests/ui/impl-trait/impl-fn-hrtb-bounds-2.rs b/tests/ui/impl-trait/impl-fn-hrtb-bounds-2.rs index b0aeded0ef75a..f4bfbdeb9f379 100644 --- a/tests/ui/impl-trait/impl-fn-hrtb-bounds-2.rs +++ b/tests/ui/impl-trait/impl-fn-hrtb-bounds-2.rs @@ -1,8 +1,11 @@ +//@revisions: edition2015 edition2024 +//@[edition2015] edition:2015 +//@[edition2024] edition:2024 #![feature(impl_trait_in_fn_trait_return)] use std::fmt::Debug; -fn a() -> impl Fn(&u8) -> impl Debug { - |x| x //~ ERROR hidden type for `impl Debug` captures lifetime that does not appear in bounds +fn a() -> impl Fn(&u8) -> impl Debug { //[edition2024]~ ERROR `impl Trait` cannot capture higher-ranked lifetime from outer `impl Trait` + |x| x //[edition2015]~ ERROR hidden type for `impl Debug` captures lifetime that does not appear in bounds } fn main() {} diff --git a/tests/ui/impl-trait/impl-fn-predefined-lifetimes.stderr b/tests/ui/impl-trait/impl-fn-predefined-lifetimes.edition2015.stderr similarity index 89% rename from tests/ui/impl-trait/impl-fn-predefined-lifetimes.stderr rename to tests/ui/impl-trait/impl-fn-predefined-lifetimes.edition2015.stderr index 6064b09ef0927..94476bcfbe88e 100644 --- a/tests/ui/impl-trait/impl-fn-predefined-lifetimes.stderr +++ b/tests/ui/impl-trait/impl-fn-predefined-lifetimes.edition2015.stderr @@ -1,5 +1,5 @@ error[E0792]: expected generic lifetime parameter, found `'_` - --> $DIR/impl-fn-predefined-lifetimes.rs:5:9 + --> $DIR/impl-fn-predefined-lifetimes.rs:8:9 | LL | fn a<'a>() -> impl Fn(&'a u8) -> (impl Debug + '_) { | -- this generic parameter must be used with a generic lifetime parameter diff --git a/tests/ui/impl-trait/impl-fn-predefined-lifetimes.edition2024.stderr b/tests/ui/impl-trait/impl-fn-predefined-lifetimes.edition2024.stderr new file mode 100644 index 0000000000000..2f1eacb0c34fa --- /dev/null +++ b/tests/ui/impl-trait/impl-fn-predefined-lifetimes.edition2024.stderr @@ -0,0 +1,11 @@ +error[E0792]: expected generic lifetime parameter, found `'_` + --> $DIR/impl-fn-predefined-lifetimes.rs:8:9 + | +LL | fn a<'a>() -> impl Fn(&'a u8) -> (impl Debug + '_) { + | -- this generic parameter must be used with a generic lifetime parameter +LL | |x| x + | ^ + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0792`. diff --git a/tests/ui/impl-trait/impl-fn-predefined-lifetimes.rs b/tests/ui/impl-trait/impl-fn-predefined-lifetimes.rs index 199cbbf4fcc9b..b2963cc10fa85 100644 --- a/tests/ui/impl-trait/impl-fn-predefined-lifetimes.rs +++ b/tests/ui/impl-trait/impl-fn-predefined-lifetimes.rs @@ -1,3 +1,6 @@ +//@revisions: edition2015 edition2024 +//@[edition2015] edition:2015 +//@[edition2024] edition:2024 #![feature(impl_trait_in_fn_trait_return)] use std::fmt::Debug; diff --git a/tests/ui/impl-trait/issues/issue-54895.stderr b/tests/ui/impl-trait/issues/issue-54895.edition2015.stderr similarity index 87% rename from tests/ui/impl-trait/issues/issue-54895.stderr rename to tests/ui/impl-trait/issues/issue-54895.edition2015.stderr index 64b425328e3ab..27a3c6c8b7ce0 100644 --- a/tests/ui/impl-trait/issues/issue-54895.stderr +++ b/tests/ui/impl-trait/issues/issue-54895.edition2015.stderr @@ -1,11 +1,11 @@ error[E0657]: `impl Trait` cannot capture higher-ranked lifetime from outer `impl Trait` - --> $DIR/issue-54895.rs:15:53 + --> $DIR/issue-54895.rs:18:53 | LL | fn f() -> impl for<'a> Trait<'a, Out = impl Sized + 'a> { | ^^ | note: lifetime declared here - --> $DIR/issue-54895.rs:15:20 + --> $DIR/issue-54895.rs:18:20 | LL | fn f() -> impl for<'a> Trait<'a, Out = impl Sized + 'a> { | ^^ diff --git a/tests/ui/impl-trait/issues/issue-54895.edition2024.stderr b/tests/ui/impl-trait/issues/issue-54895.edition2024.stderr new file mode 100644 index 0000000000000..54aa29e62d880 --- /dev/null +++ b/tests/ui/impl-trait/issues/issue-54895.edition2024.stderr @@ -0,0 +1,27 @@ +error[E0657]: `impl Trait` cannot capture higher-ranked lifetime from outer `impl Trait` + --> $DIR/issue-54895.rs:18:40 + | +LL | fn f() -> impl for<'a> Trait<'a, Out = impl Sized + 'a> { + | ^^^^^^^^^^^^^^^ `impl Trait` implicitly captures all lifetimes in scope + | +note: lifetime declared here + --> $DIR/issue-54895.rs:18:20 + | +LL | fn f() -> impl for<'a> Trait<'a, Out = impl Sized + 'a> { + | ^^ + +error[E0657]: `impl Trait` cannot capture higher-ranked lifetime from outer `impl Trait` + --> $DIR/issue-54895.rs:18:53 + | +LL | fn f() -> impl for<'a> Trait<'a, Out = impl Sized + 'a> { + | ^^ + | +note: lifetime declared here + --> $DIR/issue-54895.rs:18:20 + | +LL | fn f() -> impl for<'a> Trait<'a, Out = impl Sized + 'a> { + | ^^ + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0657`. diff --git a/tests/ui/impl-trait/issues/issue-54895.rs b/tests/ui/impl-trait/issues/issue-54895.rs index 13c0038ce4340..bc1841209e170 100644 --- a/tests/ui/impl-trait/issues/issue-54895.rs +++ b/tests/ui/impl-trait/issues/issue-54895.rs @@ -1,3 +1,6 @@ +//@revisions: edition2015 edition2024 +//@[edition2015] edition:2015 +//@[edition2024] edition:2024 trait Trait<'a> { type Out; fn call(&'a self) -> Self::Out; @@ -14,6 +17,7 @@ impl<'a> Trait<'a> for X { fn f() -> impl for<'a> Trait<'a, Out = impl Sized + 'a> { //~^ ERROR `impl Trait` cannot capture higher-ranked lifetime from outer `impl Trait` + //[edition2024]~^^ ERROR `impl Trait` cannot capture higher-ranked lifetime from outer `impl Trait` X(()) } diff --git a/tests/ui/impl-trait/issues/issue-79099.stderr b/tests/ui/impl-trait/issues/issue-79099.edition2015.stderr similarity index 95% rename from tests/ui/impl-trait/issues/issue-79099.stderr rename to tests/ui/impl-trait/issues/issue-79099.edition2015.stderr index d7c0c494454c4..ee1a479310d62 100644 --- a/tests/ui/impl-trait/issues/issue-79099.stderr +++ b/tests/ui/impl-trait/issues/issue-79099.edition2015.stderr @@ -1,5 +1,5 @@ error: expected identifier, found `1` - --> $DIR/issue-79099.rs:3:65 + --> $DIR/issue-79099.rs:6:65 | LL | let f: impl core::future::Future = async { 1 }; | ----- ^ expected identifier @@ -10,7 +10,7 @@ LL | let f: impl core::future::Future = async { 1 }; = note: for more on editions, read https://doc.rust-lang.org/edition-guide error[E0562]: `impl Trait` is not allowed in the type of variable bindings - --> $DIR/issue-79099.rs:3:16 + --> $DIR/issue-79099.rs:6:16 | LL | let f: impl core::future::Future = async { 1 }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/impl-trait/issues/issue-79099.edition2024.stderr b/tests/ui/impl-trait/issues/issue-79099.edition2024.stderr new file mode 100644 index 0000000000000..3e422e2513613 --- /dev/null +++ b/tests/ui/impl-trait/issues/issue-79099.edition2024.stderr @@ -0,0 +1,14 @@ +error[E0562]: `impl Trait` is not allowed in the type of variable bindings + --> $DIR/issue-79099.rs:6:16 + | +LL | let f: impl core::future::Future = async { 1 }; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: `impl Trait` is only allowed in arguments and return types of functions and methods + = note: see issue #63065 for more information + = help: add `#![feature(impl_trait_in_bindings)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0562`. diff --git a/tests/ui/impl-trait/issues/issue-79099.rs b/tests/ui/impl-trait/issues/issue-79099.rs index c2bad59045b22..8426298620ff1 100644 --- a/tests/ui/impl-trait/issues/issue-79099.rs +++ b/tests/ui/impl-trait/issues/issue-79099.rs @@ -1,8 +1,11 @@ +//@revisions: edition2015 edition2024 +//@[edition2015] edition:2015 +//@[edition2024] edition:2024 struct Bug { V1: [(); { let f: impl core::future::Future = async { 1 }; //~^ ERROR `impl Trait` is not allowed in the type of variable bindings - //~| ERROR expected identifier + //[edition2015]~| ERROR expected identifier 1 }], } diff --git a/tests/ui/impl-trait/precise-capturing/dyn-use.stderr b/tests/ui/impl-trait/precise-capturing/dyn-use.edition2015.stderr similarity index 90% rename from tests/ui/impl-trait/precise-capturing/dyn-use.stderr rename to tests/ui/impl-trait/precise-capturing/dyn-use.edition2015.stderr index d8903fc412910..9951e9e09657d 100644 --- a/tests/ui/impl-trait/precise-capturing/dyn-use.stderr +++ b/tests/ui/impl-trait/precise-capturing/dyn-use.edition2015.stderr @@ -1,5 +1,5 @@ error: expected one of `!`, `(`, `::`, `<`, `where`, or `{`, found keyword `use` - --> $DIR/dyn-use.rs:1:26 + --> $DIR/dyn-use.rs:4:26 | LL | fn dyn() -> &'static dyn use<> { &() } | ^^^ expected one of `!`, `(`, `::`, `<`, `where`, or `{` diff --git a/tests/ui/impl-trait/precise-capturing/dyn-use.edition2024.stderr b/tests/ui/impl-trait/precise-capturing/dyn-use.edition2024.stderr new file mode 100644 index 0000000000000..cb3fe4cb5836a --- /dev/null +++ b/tests/ui/impl-trait/precise-capturing/dyn-use.edition2024.stderr @@ -0,0 +1,26 @@ +error: expected identifier, found keyword `dyn` + --> $DIR/dyn-use.rs:4:4 + | +LL | fn dyn() -> &'static dyn use<> { &() } + | ^^^ expected identifier, found keyword + | +help: escape `dyn` to use it as an identifier + | +LL | fn r#dyn() -> &'static dyn use<> { &() } + | ++ + +error: `use<...>` precise capturing syntax not allowed in `dyn` trait object bounds + --> $DIR/dyn-use.rs:4:26 + | +LL | fn dyn() -> &'static dyn use<> { &() } + | ^^^^^ + +error[E0224]: at least one trait is required for an object type + --> $DIR/dyn-use.rs:4:22 + | +LL | fn dyn() -> &'static dyn use<> { &() } + | ^^^^^^^^^ + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0224`. diff --git a/tests/ui/impl-trait/precise-capturing/dyn-use.rs b/tests/ui/impl-trait/precise-capturing/dyn-use.rs index fb2f83e2d21cf..0b6a9467ff7c3 100644 --- a/tests/ui/impl-trait/precise-capturing/dyn-use.rs +++ b/tests/ui/impl-trait/precise-capturing/dyn-use.rs @@ -1,2 +1,10 @@ +//@revisions: edition2015 edition2024 +//@[edition2015] edition:2015 +//@[edition2024] edition:2024 fn dyn() -> &'static dyn use<> { &() } -//~^ ERROR expected one of `!`, `(`, `::`, `<`, `where`, or `{`, found keyword `use` +//[edition2015]~^ ERROR expected one of `!`, `(`, `::`, `<`, `where`, or `{`, found keyword `use` +//[edition2024]~^^ ERROR expected identifier, found keyword `dyn` +//[edition2024]~| ERROR `use<...>` precise capturing syntax not allowed in `dyn` trait object bounds +//[edition2024]~| ERROR at least one trait is required for an object type + +fn main() {} diff --git a/tests/ui/impl-trait/precise-capturing/hidden-type-suggestion.stderr b/tests/ui/impl-trait/precise-capturing/hidden-type-suggestion.edition2015.stderr similarity index 93% rename from tests/ui/impl-trait/precise-capturing/hidden-type-suggestion.stderr rename to tests/ui/impl-trait/precise-capturing/hidden-type-suggestion.edition2015.stderr index 0d8fa650df47b..c16722bb80f52 100644 --- a/tests/ui/impl-trait/precise-capturing/hidden-type-suggestion.stderr +++ b/tests/ui/impl-trait/precise-capturing/hidden-type-suggestion.edition2015.stderr @@ -1,5 +1,5 @@ error[E0700]: hidden type for `impl Sized` captures lifetime that does not appear in bounds - --> $DIR/hidden-type-suggestion.rs:3:5 + --> $DIR/hidden-type-suggestion.rs:6:5 | LL | fn lifetime<'a, 'b>(x: &'a ()) -> impl Sized + use<'b> { | -- -------------------- opaque type defined here @@ -15,7 +15,7 @@ LL | fn lifetime<'a, 'b>(x: &'a ()) -> impl Sized + use<'b, 'a> { | ++++ error[E0700]: hidden type for `impl Sized` captures lifetime that does not appear in bounds - --> $DIR/hidden-type-suggestion.rs:9:5 + --> $DIR/hidden-type-suggestion.rs:12:5 | LL | fn param<'a, T>(x: &'a ()) -> impl Sized + use { | -- ------------------- opaque type defined here @@ -31,7 +31,7 @@ LL | fn param<'a, T>(x: &'a ()) -> impl Sized + use<'a, T> { | +++ error[E0700]: hidden type for `impl Sized` captures lifetime that does not appear in bounds - --> $DIR/hidden-type-suggestion.rs:15:5 + --> $DIR/hidden-type-suggestion.rs:18:5 | LL | fn empty<'a>(x: &'a ()) -> impl Sized + use<> { | -- ------------------ opaque type defined here @@ -47,7 +47,7 @@ LL | fn empty<'a>(x: &'a ()) -> impl Sized + use<'a> { | ++ error[E0700]: hidden type for `impl Captures<'captured>` captures lifetime that does not appear in bounds - --> $DIR/hidden-type-suggestion.rs:24:5 + --> $DIR/hidden-type-suggestion.rs:27:5 | LL | fn missing<'a, 'captured, 'not_captured, Captured>(x: &'a ()) -> impl Captures<'captured> { | -- ------------------------ opaque type defined here @@ -63,7 +63,7 @@ LL | fn missing<'a, 'captured, 'not_captured, Captured>(x: &'a ()) -> impl Captu | ++++++++++++++++++++++++++++++ error[E0700]: hidden type for `impl Sized` captures lifetime that does not appear in bounds - --> $DIR/hidden-type-suggestion.rs:30:5 + --> $DIR/hidden-type-suggestion.rs:33:5 | LL | fn no_params_yet(_: impl Sized, y: &()) -> impl Sized { | --- ---------- opaque type defined here @@ -74,7 +74,7 @@ LL | y | ^ | note: you could use a `use<...>` bound to explicitly capture `'_`, but argument-position `impl Trait`s are not nameable - --> $DIR/hidden-type-suggestion.rs:28:21 + --> $DIR/hidden-type-suggestion.rs:31:21 | LL | fn no_params_yet(_: impl Sized, y: &()) -> impl Sized { | ^^^^^^^^^^ @@ -85,7 +85,7 @@ LL + fn no_params_yet(_: T, y: &()) -> impl Sized + use<'_, T> { | error[E0700]: hidden type for `impl Sized` captures lifetime that does not appear in bounds - --> $DIR/hidden-type-suggestion.rs:36:5 + --> $DIR/hidden-type-suggestion.rs:39:5 | LL | fn yes_params_yet<'a, T>(_: impl Sized, y: &'a ()) -> impl Sized { | -- ---------- opaque type defined here @@ -96,7 +96,7 @@ LL | y | ^ | note: you could use a `use<...>` bound to explicitly capture `'a`, but argument-position `impl Trait`s are not nameable - --> $DIR/hidden-type-suggestion.rs:34:29 + --> $DIR/hidden-type-suggestion.rs:37:29 | LL | fn yes_params_yet<'a, T>(_: impl Sized, y: &'a ()) -> impl Sized { | ^^^^^^^^^^ diff --git a/tests/ui/impl-trait/precise-capturing/hidden-type-suggestion.edition2024.stderr b/tests/ui/impl-trait/precise-capturing/hidden-type-suggestion.edition2024.stderr new file mode 100644 index 0000000000000..308dc9b00fcd4 --- /dev/null +++ b/tests/ui/impl-trait/precise-capturing/hidden-type-suggestion.edition2024.stderr @@ -0,0 +1,51 @@ +error[E0700]: hidden type for `impl Sized` captures lifetime that does not appear in bounds + --> $DIR/hidden-type-suggestion.rs:6:5 + | +LL | fn lifetime<'a, 'b>(x: &'a ()) -> impl Sized + use<'b> { + | -- -------------------- opaque type defined here + | | + | hidden type `&'a ()` captures the lifetime `'a` as defined here +LL | +LL | x + | ^ + | +help: add `'a` to the `use<...>` bound to explicitly capture it + | +LL | fn lifetime<'a, 'b>(x: &'a ()) -> impl Sized + use<'b, 'a> { + | ++++ + +error[E0700]: hidden type for `impl Sized` captures lifetime that does not appear in bounds + --> $DIR/hidden-type-suggestion.rs:12:5 + | +LL | fn param<'a, T>(x: &'a ()) -> impl Sized + use { + | -- ------------------- opaque type defined here + | | + | hidden type `&'a ()` captures the lifetime `'a` as defined here +LL | +LL | x + | ^ + | +help: add `'a` to the `use<...>` bound to explicitly capture it + | +LL | fn param<'a, T>(x: &'a ()) -> impl Sized + use<'a, T> { + | +++ + +error[E0700]: hidden type for `impl Sized` captures lifetime that does not appear in bounds + --> $DIR/hidden-type-suggestion.rs:18:5 + | +LL | fn empty<'a>(x: &'a ()) -> impl Sized + use<> { + | -- ------------------ opaque type defined here + | | + | hidden type `&'a ()` captures the lifetime `'a` as defined here +LL | +LL | x + | ^ + | +help: add `'a` to the `use<...>` bound to explicitly capture it + | +LL | fn empty<'a>(x: &'a ()) -> impl Sized + use<'a> { + | ++ + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0700`. diff --git a/tests/ui/impl-trait/precise-capturing/hidden-type-suggestion.rs b/tests/ui/impl-trait/precise-capturing/hidden-type-suggestion.rs index d34c613559611..9712eac859ab9 100644 --- a/tests/ui/impl-trait/precise-capturing/hidden-type-suggestion.rs +++ b/tests/ui/impl-trait/precise-capturing/hidden-type-suggestion.rs @@ -1,3 +1,6 @@ +//@revisions: edition2015 edition2024 +//@[edition2015] edition:2015 +//@[edition2024] edition:2024 fn lifetime<'a, 'b>(x: &'a ()) -> impl Sized + use<'b> { //~^ HELP add `'a` to the `use<...>` bound x @@ -20,21 +23,21 @@ trait Captures<'a> {} impl Captures<'_> for T {} fn missing<'a, 'captured, 'not_captured, Captured>(x: &'a ()) -> impl Captures<'captured> { -//~^ HELP add a `use<...>` bound +//[edition2015]~^ HELP add a `use<...>` bound x -//~^ ERROR hidden type for +//[edition2015]~^ ERROR hidden type for } fn no_params_yet(_: impl Sized, y: &()) -> impl Sized { -//~^ HELP add a `use<...>` bound +//[edition2015]~^ HELP add a `use<...>` bound y -//~^ ERROR hidden type for +//[edition2015]~^ ERROR hidden type for } fn yes_params_yet<'a, T>(_: impl Sized, y: &'a ()) -> impl Sized { -//~^ HELP add a `use<...>` bound +//[edition2015]~^ HELP add a `use<...>` bound y -//~^ ERROR hidden type for +//[edition2015]~^ ERROR hidden type for } fn main() {} diff --git a/tests/ui/imports/import-from-missing-star-2.stderr b/tests/ui/imports/import-from-missing-star-2.edition2015.stderr similarity index 89% rename from tests/ui/imports/import-from-missing-star-2.stderr rename to tests/ui/imports/import-from-missing-star-2.edition2015.stderr index 9fe2bdbcfa279..cd1a9581d3061 100644 --- a/tests/ui/imports/import-from-missing-star-2.stderr +++ b/tests/ui/imports/import-from-missing-star-2.edition2015.stderr @@ -1,5 +1,5 @@ error[E0432]: unresolved import `spam` - --> $DIR/import-from-missing-star-2.rs:2:9 + --> $DIR/import-from-missing-star-2.rs:6:9 | LL | use spam::*; | ^^^^ use of unresolved module or unlinked crate `spam` diff --git a/tests/ui/imports/import-from-missing-star-2.edition2024.stderr b/tests/ui/imports/import-from-missing-star-2.edition2024.stderr new file mode 100644 index 0000000000000..086b7a576b228 --- /dev/null +++ b/tests/ui/imports/import-from-missing-star-2.edition2024.stderr @@ -0,0 +1,11 @@ +error[E0432]: unresolved import `spam` + --> $DIR/import-from-missing-star-2.rs:6:9 + | +LL | use spam::*; + | ^^^^ use of unresolved module or unlinked crate `spam` + | + = help: you might be missing a crate named `spam` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0432`. diff --git a/tests/ui/imports/import-from-missing-star-2.rs b/tests/ui/imports/import-from-missing-star-2.rs index cb341b0b0ca42..9dad2d4886b8b 100644 --- a/tests/ui/imports/import-from-missing-star-2.rs +++ b/tests/ui/imports/import-from-missing-star-2.rs @@ -1,5 +1,10 @@ +//@revisions: edition2015 edition2024 +//@[edition2015] edition:2015 +//@[edition2024] edition:2024 mod foo { +//[edition2015]~^ HELP you might be missing a crate named `spam`, add it to your project and import it in your code use spam::*; //~ ERROR unresolved import `spam` [E0432] + //[edition2024]~^ HELP you might be missing a crate named `spam` } fn main() { diff --git a/tests/ui/type-alias-impl-trait/imply_bounds_from_bounds_param.stderr b/tests/ui/type-alias-impl-trait/imply_bounds_from_bounds_param.edition2015.stderr similarity index 93% rename from tests/ui/type-alias-impl-trait/imply_bounds_from_bounds_param.stderr rename to tests/ui/type-alias-impl-trait/imply_bounds_from_bounds_param.edition2015.stderr index 0bf9dccfad85e..4f1e769bc6c40 100644 --- a/tests/ui/type-alias-impl-trait/imply_bounds_from_bounds_param.stderr +++ b/tests/ui/type-alias-impl-trait/imply_bounds_from_bounds_param.edition2015.stderr @@ -1,5 +1,5 @@ error[E0700]: hidden type for `impl PlusOne` captures lifetime that does not appear in bounds - --> $DIR/imply_bounds_from_bounds_param.rs:26:5 + --> $DIR/imply_bounds_from_bounds_param.rs:29:5 | LL | fn test<'a>(y: &'a mut i32) -> impl PlusOne { | -- ------------ opaque type defined here diff --git a/tests/ui/type-alias-impl-trait/imply_bounds_from_bounds_param.edition2024.stderr b/tests/ui/type-alias-impl-trait/imply_bounds_from_bounds_param.edition2024.stderr new file mode 100644 index 0000000000000..a7135e8f05f43 --- /dev/null +++ b/tests/ui/type-alias-impl-trait/imply_bounds_from_bounds_param.edition2024.stderr @@ -0,0 +1,91 @@ +error[E0499]: cannot borrow `z` as mutable more than once at a time + --> $DIR/imply_bounds_from_bounds_param.rs:36:27 + | +LL | let mut thing = test(&mut z); + | ------ first mutable borrow occurs here +LL | let mut thing2 = test(&mut z); + | ^^^^^^ second mutable borrow occurs here +LL | thing.plus_one(); + | ----- first borrow later used here + | +note: this call may capture more lifetimes than intended, because Rust 2024 has adjusted the `impl Trait` lifetime capture rules + --> $DIR/imply_bounds_from_bounds_param.rs:35:21 + | +LL | let mut thing = test(&mut z); + | ^^^^^^^^^^^^ +help: use the precise capturing `use<...>` syntax to make the captures explicit + | +LL | fn test<'a>(y: &'a mut i32) -> impl PlusOne + use<> { + | +++++++ + +error[E0502]: cannot borrow `z` as immutable because it is also borrowed as mutable + --> $DIR/imply_bounds_from_bounds_param.rs:38:5 + | +LL | let mut thing = test(&mut z); + | ------ mutable borrow occurs here +... +LL | assert_eq!(z, 43); + | ^^^^^^^^^^^^^^^^^ immutable borrow occurs here +... +LL | thing.plus_one(); + | ----- mutable borrow later used here + | +note: this call may capture more lifetimes than intended, because Rust 2024 has adjusted the `impl Trait` lifetime capture rules + --> $DIR/imply_bounds_from_bounds_param.rs:35:21 + | +LL | let mut thing = test(&mut z); + | ^^^^^^^^^^^^ + = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info) +help: use the precise capturing `use<...>` syntax to make the captures explicit + | +LL | fn test<'a>(y: &'a mut i32) -> impl PlusOne + use<> { + | +++++++ + +error[E0502]: cannot borrow `z` as immutable because it is also borrowed as mutable + --> $DIR/imply_bounds_from_bounds_param.rs:40:5 + | +LL | let mut thing = test(&mut z); + | ------ mutable borrow occurs here +... +LL | assert_eq!(z, 44); + | ^^^^^^^^^^^^^^^^^ immutable borrow occurs here +LL | thing.plus_one(); + | ----- mutable borrow later used here + | +note: this call may capture more lifetimes than intended, because Rust 2024 has adjusted the `impl Trait` lifetime capture rules + --> $DIR/imply_bounds_from_bounds_param.rs:35:21 + | +LL | let mut thing = test(&mut z); + | ^^^^^^^^^^^^ + = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info) +help: use the precise capturing `use<...>` syntax to make the captures explicit + | +LL | fn test<'a>(y: &'a mut i32) -> impl PlusOne + use<> { + | +++++++ + +error[E0502]: cannot borrow `z` as immutable because it is also borrowed as mutable + --> $DIR/imply_bounds_from_bounds_param.rs:42:5 + | +LL | let mut thing = test(&mut z); + | ------ mutable borrow occurs here +... +LL | assert_eq!(z, 45); + | ^^^^^^^^^^^^^^^^^ immutable borrow occurs here +LL | } + | - mutable borrow might be used here, when `thing` is dropped and runs the destructor for type `impl PlusOne` + | +note: this call may capture more lifetimes than intended, because Rust 2024 has adjusted the `impl Trait` lifetime capture rules + --> $DIR/imply_bounds_from_bounds_param.rs:35:21 + | +LL | let mut thing = test(&mut z); + | ^^^^^^^^^^^^ + = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info) +help: use the precise capturing `use<...>` syntax to make the captures explicit + | +LL | fn test<'a>(y: &'a mut i32) -> impl PlusOne + use<> { + | +++++++ + +error: aborting due to 4 previous errors + +Some errors have detailed explanations: E0499, E0502. +For more information about an error, try `rustc --explain E0499`. diff --git a/tests/ui/type-alias-impl-trait/imply_bounds_from_bounds_param.rs b/tests/ui/type-alias-impl-trait/imply_bounds_from_bounds_param.rs index 5d5645077c2a4..672019ba73ac6 100644 --- a/tests/ui/type-alias-impl-trait/imply_bounds_from_bounds_param.rs +++ b/tests/ui/type-alias-impl-trait/imply_bounds_from_bounds_param.rs @@ -1,3 +1,6 @@ +//@revisions: edition2015 edition2024 +//@[edition2015] edition:2015 +//@[edition2024] edition:2024 #![feature(impl_trait_in_assoc_type)] trait Callable { @@ -24,17 +27,17 @@ impl Callable for T { fn test<'a>(y: &'a mut i32) -> impl PlusOne { <&'a mut i32 as Callable>::call(y) - //~^ ERROR hidden type for `impl PlusOne` captures lifetime that does not appear in bounds + //[edition2015]~^ ERROR hidden type for `impl PlusOne` captures lifetime that does not appear in bounds } fn main() { let mut z = 42; let mut thing = test(&mut z); - let mut thing2 = test(&mut z); + let mut thing2 = test(&mut z); //[edition2024]~ ERROR cannot borrow `z` as mutable more than once thing.plus_one(); - assert_eq!(z, 43); + assert_eq!(z, 43); //[edition2024]~ ERROR cannot borrow `z` as immutable thing2.plus_one(); - assert_eq!(z, 44); + assert_eq!(z, 44); //[edition2024]~ ERROR cannot borrow `z` as immutable thing.plus_one(); - assert_eq!(z, 45); + assert_eq!(z, 45); //[edition2024]~ ERROR cannot borrow `z` as immutable } From 233882128bda3d1912d339afeca985637f94485c Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Tue, 10 Jun 2025 21:57:34 -0700 Subject: [PATCH 19/23] tests: Do not run afoul of asm.validity.non-exhaustive in input-stats --- tests/ui/stats/input-stats.rs | 5 ++++- tests/ui/stats/input-stats.stderr | 12 ++++++------ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/tests/ui/stats/input-stats.rs b/tests/ui/stats/input-stats.rs index e760e2894e318..4e8e25eb73674 100644 --- a/tests/ui/stats/input-stats.rs +++ b/tests/ui/stats/input-stats.rs @@ -1,6 +1,7 @@ //@ check-pass //@ compile-flags: -Zinput-stats //@ only-64bit +//@ needs-asm-support // layout randomization affects the hir stat output //@ needs-deterministic-layouts // @@ -49,5 +50,7 @@ fn main() { _ => {} } - unsafe { asm!("mov rdi, 1"); } + // NOTE(workingjubilee): do GPUs support NOPs? remove this cfg if they do + #[cfg(not(any(target_arch = "nvptx64", target_arch = "amdgpu")))] + unsafe { asm!("nop"); } } diff --git a/tests/ui/stats/input-stats.stderr b/tests/ui/stats/input-stats.stderr index b3b8784fa270f..eb038bbcaf1a2 100644 --- a/tests/ui/stats/input-stats.stderr +++ b/tests/ui/stats/input-stats.stderr @@ -15,7 +15,7 @@ ast-stats - Ptr 64 (NN.N%) 1 ast-stats - Ref 64 (NN.N%) 1 ast-stats - ImplicitSelf 128 (NN.N%) 2 ast-stats - Path 640 (NN.N%) 10 -ast-stats PathSegment 864 (NN.N%) 36 24 +ast-stats PathSegment 888 (NN.N%) 37 24 ast-stats Expr 648 (NN.N%) 9 72 ast-stats - InlineAsm 72 (NN.N%) 1 ast-stats - Match 72 (NN.N%) 1 @@ -41,9 +41,9 @@ ast-stats - Let 32 (NN.N%) 1 ast-stats - Semi 32 (NN.N%) 1 ast-stats - Expr 96 (NN.N%) 3 ast-stats Param 160 (NN.N%) 4 40 -ast-stats Attribute 128 (NN.N%) 4 32 +ast-stats Attribute 160 (NN.N%) 5 32 ast-stats - DocComment 32 (NN.N%) 1 -ast-stats - Normal 96 (NN.N%) 3 +ast-stats - Normal 128 (NN.N%) 4 ast-stats InlineAsm 120 (NN.N%) 1 120 ast-stats FnDecl 120 (NN.N%) 5 24 ast-stats Local 96 (NN.N%) 1 96 @@ -57,7 +57,7 @@ ast-stats GenericArgs 40 (NN.N%) 1 40 ast-stats - AngleBracketed 40 (NN.N%) 1 ast-stats Crate 40 (NN.N%) 1 40 ast-stats ---------------------------------------------------------------- -ast-stats Total 7_416 127 +ast-stats Total 7_472 129 ast-stats ================================================================ hir-stats ================================================================ hir-stats HIR STATS: input_stats @@ -93,7 +93,7 @@ hir-stats - Binding 216 (NN.N%) 3 hir-stats Block 288 (NN.N%) 6 48 hir-stats GenericBound 256 (NN.N%) 4 64 hir-stats - Trait 256 (NN.N%) 4 -hir-stats Attribute 160 (NN.N%) 4 40 +hir-stats Attribute 200 (NN.N%) 5 40 hir-stats Variant 144 (NN.N%) 2 72 hir-stats GenericArgs 144 (NN.N%) 3 48 hir-stats FieldDef 128 (NN.N%) 2 64 @@ -119,5 +119,5 @@ hir-stats Mod 32 (NN.N%) 1 32 hir-stats Lifetime 28 (NN.N%) 1 28 hir-stats ForeignItemRef 24 (NN.N%) 1 24 hir-stats ---------------------------------------------------------------- -hir-stats Total 8_676 172 +hir-stats Total 8_716 173 hir-stats ================================================================ From 1dfc8406dcb742453b36daf0ce7486183b1da79c Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Tue, 20 May 2025 20:23:47 +0200 Subject: [PATCH 20/23] make `tidy-alphabetical` use a natural sort --- compiler/rustc_ast/src/ast.rs | 2 +- .../rustc_const_eval/src/interpret/operand.rs | 4 +- .../rustc_const_eval/src/interpret/place.rs | 2 +- compiler/rustc_hir/src/hir.rs | 2 +- compiler/rustc_lint_defs/src/builtin.rs | 2 +- compiler/rustc_middle/src/ty/context.rs | 2 +- .../rustc_middle/src/ty/structural_impls.rs | 12 +- compiler/rustc_target/src/target_features.rs | 48 +++--- compiler/rustc_type_ir/src/lang_items.rs | 2 +- compiler/rustc_type_ir/src/macros.rs | 4 +- library/core/src/lib.rs | 2 +- library/coretests/tests/lib.rs | 2 +- library/std/src/io/error.rs | 2 +- library/std/src/lib.rs | 2 +- library/std/src/sys/pal/windows/api.rs | 6 +- library/std/tests/run-time-detect.rs | 8 +- src/bootstrap/src/core/build_steps/dist.rs | 10 +- src/tools/tidy/src/alphabetical.rs | 59 ++++++- src/tools/tidy/src/alphabetical/tests.rs | 147 ++++++++++++++++++ 19 files changed, 260 insertions(+), 58 deletions(-) diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index ab8dac1602666..d9272986a7e09 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -4064,9 +4064,9 @@ mod size_asserts { static_assert_size!(MetaItemLit, 40); static_assert_size!(Param, 40); static_assert_size!(Pat, 72); + static_assert_size!(PatKind, 48); static_assert_size!(Path, 24); static_assert_size!(PathSegment, 24); - static_assert_size!(PatKind, 48); static_assert_size!(Stmt, 32); static_assert_size!(StmtKind, 16); static_assert_size!(Ty, 64); diff --git a/compiler/rustc_const_eval/src/interpret/operand.rs b/compiler/rustc_const_eval/src/interpret/operand.rs index 77667ba823a7b..337b161767631 100644 --- a/compiler/rustc_const_eval/src/interpret/operand.rs +++ b/compiler/rustc_const_eval/src/interpret/operand.rs @@ -878,9 +878,9 @@ mod size_asserts { use super::*; // tidy-alphabetical-start - static_assert_size!(Immediate, 48); static_assert_size!(ImmTy<'_>, 64); - static_assert_size!(Operand, 56); + static_assert_size!(Immediate, 48); static_assert_size!(OpTy<'_>, 72); + static_assert_size!(Operand, 56); // tidy-alphabetical-end } diff --git a/compiler/rustc_const_eval/src/interpret/place.rs b/compiler/rustc_const_eval/src/interpret/place.rs index f5d3de7b1b270..e4885af7faf48 100644 --- a/compiler/rustc_const_eval/src/interpret/place.rs +++ b/compiler/rustc_const_eval/src/interpret/place.rs @@ -1056,9 +1056,9 @@ mod size_asserts { use super::*; // tidy-alphabetical-start + static_assert_size!(MPlaceTy<'_>, 64); static_assert_size!(MemPlace, 48); static_assert_size!(MemPlaceMeta, 24); - static_assert_size!(MPlaceTy<'_>, 64); static_assert_size!(Place, 48); static_assert_size!(PlaceTy<'_>, 64); // tidy-alphabetical-end diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 679904c7cfe4e..88e0ee1cc0be2 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -4992,9 +4992,9 @@ mod size_asserts { static_assert_size!(LetStmt<'_>, 72); static_assert_size!(Param<'_>, 32); static_assert_size!(Pat<'_>, 72); + static_assert_size!(PatKind<'_>, 48); static_assert_size!(Path<'_>, 40); static_assert_size!(PathSegment<'_>, 48); - static_assert_size!(PatKind<'_>, 48); static_assert_size!(QPath<'_>, 24); static_assert_size!(Res, 12); static_assert_size!(Stmt<'_>, 32); diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index 5fa00fcc4a0c3..10ac14a2fbfc5 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -131,8 +131,8 @@ declare_lint_pass! { UNUSED_IMPORTS, UNUSED_LABELS, UNUSED_LIFETIMES, - UNUSED_MACRO_RULES, UNUSED_MACROS, + UNUSED_MACRO_RULES, UNUSED_MUT, UNUSED_QUALIFICATIONS, UNUSED_UNSAFE, diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index c5f4b95cbbe61..2319de60d7879 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -774,8 +774,8 @@ bidirectional_lang_item_map! { Future, FutureOutput, Iterator, - Metadata, MetaSized, + Metadata, Option, PointeeSized, PointeeTrait, diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 000ba7b6fa794..1214731a3b2ed 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -230,9 +230,9 @@ TrivialLiftImpls! { usize, u64, // tidy-alphabetical-start + crate::mir::Promoted, crate::mir::interpret::AllocId, crate::mir::interpret::Scalar, - crate::mir::Promoted, rustc_abi::ExternAbi, rustc_abi::Size, rustc_hir::Safety, @@ -267,9 +267,6 @@ TrivialTypeTraversalImpls! { crate::mir::SwitchTargets, crate::traits::IsConstable, crate::traits::OverflowError, - crate::ty::abstract_const::NotConstEvaluatable, - crate::ty::adjustment::AutoBorrowMutability, - crate::ty::adjustment::PointerCoercion, crate::ty::AdtKind, crate::ty::AssocItem, crate::ty::AssocKind, @@ -281,15 +278,18 @@ TrivialTypeTraversalImpls! { crate::ty::Placeholder, crate::ty::UserTypeAnnotationIndex, crate::ty::ValTree<'tcx>, + crate::ty::abstract_const::NotConstEvaluatable, + crate::ty::adjustment::AutoBorrowMutability, + crate::ty::adjustment::PointerCoercion, rustc_abi::FieldIdx, rustc_abi::VariantIdx, rustc_ast::InlineAsmOptions, rustc_ast::InlineAsmTemplatePiece, rustc_hir::CoroutineKind, - rustc_hir::def_id::LocalDefId, rustc_hir::HirId, rustc_hir::MatchSource, rustc_hir::RangeEnd, + rustc_hir::def_id::LocalDefId, rustc_span::Ident, rustc_span::Span, rustc_span::Symbol, @@ -303,9 +303,9 @@ TrivialTypeTraversalImpls! { // interners). TrivialTypeTraversalAndLiftImpls! { // tidy-alphabetical-start - crate::ty::instance::ReifyReason, crate::ty::ParamConst, crate::ty::ParamTy, + crate::ty::instance::ReifyReason, rustc_hir::def_id::DefId, // tidy-alphabetical-end } diff --git a/compiler/rustc_target/src/target_features.rs b/compiler/rustc_target/src/target_features.rs index 3eea1e070a669..b2af99228fe6d 100644 --- a/compiler/rustc_target/src/target_features.rs +++ b/compiler/rustc_target/src/target_features.rs @@ -212,9 +212,6 @@ static AARCH64_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("flagm2", Unstable(sym::aarch64_unstable_target_feature), &[]), // We forbid directly toggling just `fp-armv8`; it must be toggled with `neon`. ("fp-armv8", Stability::Forbidden { reason: "Rust ties `fp-armv8` to `neon`" }, &[]), - // FEAT_FP16 - // Rust ties FP and Neon: https://github.com/rust-lang/rust/pull/91608 - ("fp16", Stable, &["neon"]), // FEAT_FP8 ("fp8", Unstable(sym::aarch64_unstable_target_feature), &["faminmax", "lut", "bf16"]), // FEAT_FP8DOT2 @@ -223,6 +220,9 @@ static AARCH64_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("fp8dot4", Unstable(sym::aarch64_unstable_target_feature), &["fp8fma"]), // FEAT_FP8FMA ("fp8fma", Unstable(sym::aarch64_unstable_target_feature), &["fp8"]), + // FEAT_FP16 + // Rust ties FP and Neon: https://github.com/rust-lang/rust/pull/91608 + ("fp16", Stable, &["neon"]), // FEAT_FRINTTS ("frintts", Stable, &[]), // FEAT_HBC @@ -236,10 +236,10 @@ static AARCH64_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("lor", Stable, &[]), // FEAT_LSE ("lse", Stable, &[]), - // FEAT_LSE128 - ("lse128", Unstable(sym::aarch64_unstable_target_feature), &["lse"]), // FEAT_LSE2 ("lse2", Unstable(sym::aarch64_unstable_target_feature), &[]), + // FEAT_LSE128 + ("lse128", Unstable(sym::aarch64_unstable_target_feature), &["lse"]), // FEAT_LUT ("lut", Unstable(sym::aarch64_unstable_target_feature), &[]), // FEAT_MOPS @@ -283,14 +283,14 @@ static AARCH64_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("sme", Unstable(sym::aarch64_unstable_target_feature), &["bf16"]), // FEAT_SME_B16B16 ("sme-b16b16", Unstable(sym::aarch64_unstable_target_feature), &["bf16", "sme2", "sve-b16b16"]), - // FEAT_SME_F16F16 - ("sme-f16f16", Unstable(sym::aarch64_unstable_target_feature), &["sme2"]), - // FEAT_SME_F64F64 - ("sme-f64f64", Unstable(sym::aarch64_unstable_target_feature), &["sme"]), // FEAT_SME_F8F16 ("sme-f8f16", Unstable(sym::aarch64_unstable_target_feature), &["sme-f8f32"]), // FEAT_SME_F8F32 ("sme-f8f32", Unstable(sym::aarch64_unstable_target_feature), &["sme2", "fp8"]), + // FEAT_SME_F16F16 + ("sme-f16f16", Unstable(sym::aarch64_unstable_target_feature), &["sme2"]), + // FEAT_SME_F64F64 + ("sme-f64f64", Unstable(sym::aarch64_unstable_target_feature), &["sme"]), // FEAT_SME_FA64 ("sme-fa64", Unstable(sym::aarch64_unstable_target_feature), &["sme", "sve2"]), // FEAT_SME_I16I64 @@ -376,8 +376,8 @@ static X86_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("amx-avx512", Unstable(sym::x86_amx_intrinsics), &["amx-tile"]), ("amx-bf16", Unstable(sym::x86_amx_intrinsics), &["amx-tile"]), ("amx-complex", Unstable(sym::x86_amx_intrinsics), &["amx-tile"]), - ("amx-fp16", Unstable(sym::x86_amx_intrinsics), &["amx-tile"]), ("amx-fp8", Unstable(sym::x86_amx_intrinsics), &["amx-tile"]), + ("amx-fp16", Unstable(sym::x86_amx_intrinsics), &["amx-tile"]), ("amx-int8", Unstable(sym::x86_amx_intrinsics), &["amx-tile"]), ("amx-movrs", Unstable(sym::x86_amx_intrinsics), &["amx-tile"]), ("amx-tf32", Unstable(sym::x86_amx_intrinsics), &["amx-tile"]), @@ -385,6 +385,7 @@ static X86_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("amx-transpose", Unstable(sym::x86_amx_intrinsics), &["amx-tile"]), ("apxf", Unstable(sym::apx_target_feature), &[]), ("avx", Stable, &["sse4.2"]), + ("avx2", Stable, &["avx"]), ( "avx10.1", Unstable(sym::avx10_target_feature), @@ -405,7 +406,6 @@ static X86_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ], ), ("avx10.2", Unstable(sym::avx10_target_feature), &["avx10.1"]), - ("avx2", Stable, &["avx"]), ("avx512bf16", Stable, &["avx512bw"]), ("avx512bitalg", Stable, &["avx512bw"]), ("avx512bw", Stable, &["avx512f"]), @@ -423,8 +423,8 @@ static X86_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("avxifma", Stable, &["avx2"]), ("avxneconvert", Stable, &["avx2"]), ("avxvnni", Stable, &["avx2"]), - ("avxvnniint16", Stable, &["avx2"]), ("avxvnniint8", Stable, &["avx2"]), + ("avxvnniint16", Stable, &["avx2"]), ("bmi1", Stable, &[]), ("bmi2", Stable, &[]), ("cmpxchg16b", Stable, &[]), @@ -498,12 +498,12 @@ static POWERPC_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("altivec", Unstable(sym::powerpc_target_feature), &[]), ("msync", Unstable(sym::powerpc_target_feature), &[]), ("partword-atomics", Unstable(sym::powerpc_target_feature), &[]), - ("power10-vector", Unstable(sym::powerpc_target_feature), &["power9-vector"]), ("power8-altivec", Unstable(sym::powerpc_target_feature), &["altivec"]), ("power8-crypto", Unstable(sym::powerpc_target_feature), &["power8-altivec"]), ("power8-vector", Unstable(sym::powerpc_target_feature), &["vsx", "power8-altivec"]), ("power9-altivec", Unstable(sym::powerpc_target_feature), &["power8-altivec"]), ("power9-vector", Unstable(sym::powerpc_target_feature), &["power8-vector", "power9-altivec"]), + ("power10-vector", Unstable(sym::powerpc_target_feature), &["power9-vector"]), ("quadword-atomics", Unstable(sym::powerpc_target_feature), &[]), ("vsx", Unstable(sym::powerpc_target_feature), &["altivec"]), // tidy-alphabetical-end @@ -535,8 +535,8 @@ static RISCV_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("unaligned-scalar-mem", Unstable(sym::riscv_target_feature), &[]), ("unaligned-vector-mem", Unstable(sym::riscv_target_feature), &[]), ("v", Unstable(sym::riscv_target_feature), &["zvl128b", "zve64d"]), - ("za128rs", Unstable(sym::riscv_target_feature), &[]), ("za64rs", Unstable(sym::riscv_target_feature), &["za128rs"]), // Za64rs ⊃ Za128rs + ("za128rs", Unstable(sym::riscv_target_feature), &[]), ("zaamo", Unstable(sym::riscv_target_feature), &[]), ("zabha", Unstable(sym::riscv_target_feature), &["zaamo"]), ("zacas", Unstable(sym::riscv_target_feature), &["zaamo"]), @@ -613,18 +613,18 @@ static RISCV_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("zvksg", Unstable(sym::riscv_target_feature), &["zvks", "zvkg"]), ("zvksh", Unstable(sym::riscv_target_feature), &["zve32x"]), ("zvkt", Unstable(sym::riscv_target_feature), &[]), - ("zvl1024b", Unstable(sym::riscv_target_feature), &["zvl512b"]), + ("zvl32b", Unstable(sym::riscv_target_feature), &[]), + ("zvl64b", Unstable(sym::riscv_target_feature), &["zvl32b"]), ("zvl128b", Unstable(sym::riscv_target_feature), &["zvl64b"]), - ("zvl16384b", Unstable(sym::riscv_target_feature), &["zvl8192b"]), - ("zvl2048b", Unstable(sym::riscv_target_feature), &["zvl1024b"]), ("zvl256b", Unstable(sym::riscv_target_feature), &["zvl128b"]), - ("zvl32768b", Unstable(sym::riscv_target_feature), &["zvl16384b"]), - ("zvl32b", Unstable(sym::riscv_target_feature), &[]), - ("zvl4096b", Unstable(sym::riscv_target_feature), &["zvl2048b"]), ("zvl512b", Unstable(sym::riscv_target_feature), &["zvl256b"]), - ("zvl64b", Unstable(sym::riscv_target_feature), &["zvl32b"]), - ("zvl65536b", Unstable(sym::riscv_target_feature), &["zvl32768b"]), + ("zvl1024b", Unstable(sym::riscv_target_feature), &["zvl512b"]), + ("zvl2048b", Unstable(sym::riscv_target_feature), &["zvl1024b"]), + ("zvl4096b", Unstable(sym::riscv_target_feature), &["zvl2048b"]), ("zvl8192b", Unstable(sym::riscv_target_feature), &["zvl4096b"]), + ("zvl16384b", Unstable(sym::riscv_target_feature), &["zvl8192b"]), + ("zvl32768b", Unstable(sym::riscv_target_feature), &["zvl16384b"]), + ("zvl65536b", Unstable(sym::riscv_target_feature), &["zvl32768b"]), // tidy-alphabetical-end ]; @@ -651,13 +651,13 @@ const BPF_FEATURES: &[(&str, Stability, ImpliedFeatures)] = static CSKY_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ // tidy-alphabetical-start - ("10e60", Unstable(sym::csky_target_feature), &["7e10"]), ("2e3", Unstable(sym::csky_target_feature), &["e2"]), ("3e3r1", Unstable(sym::csky_target_feature), &[]), ("3e3r2", Unstable(sym::csky_target_feature), &["3e3r1", "doloop"]), ("3e3r3", Unstable(sym::csky_target_feature), &["doloop"]), ("3e7", Unstable(sym::csky_target_feature), &["2e3"]), ("7e10", Unstable(sym::csky_target_feature), &["3e7"]), + ("10e60", Unstable(sym::csky_target_feature), &["7e10"]), ("cache", Unstable(sym::csky_target_feature), &[]), ("doloop", Unstable(sym::csky_target_feature), &[]), ("dsp1e2", Unstable(sym::csky_target_feature), &[]), @@ -726,12 +726,12 @@ const IBMZ_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("guarded-storage", Unstable(sym::s390x_target_feature), &[]), ("high-word", Unstable(sym::s390x_target_feature), &[]), // LLVM does not define message-security-assist-extension versions 1, 2, 6, 10 and 11. - ("message-security-assist-extension12", Unstable(sym::s390x_target_feature), &[]), ("message-security-assist-extension3", Unstable(sym::s390x_target_feature), &[]), ("message-security-assist-extension4", Unstable(sym::s390x_target_feature), &[]), ("message-security-assist-extension5", Unstable(sym::s390x_target_feature), &[]), ("message-security-assist-extension8", Unstable(sym::s390x_target_feature), &["message-security-assist-extension3"]), ("message-security-assist-extension9", Unstable(sym::s390x_target_feature), &["message-security-assist-extension3", "message-security-assist-extension4"]), + ("message-security-assist-extension12", Unstable(sym::s390x_target_feature), &[]), ("miscellaneous-extensions-2", Unstable(sym::s390x_target_feature), &[]), ("miscellaneous-extensions-3", Unstable(sym::s390x_target_feature), &[]), ("miscellaneous-extensions-4", Unstable(sym::s390x_target_feature), &[]), diff --git a/compiler/rustc_type_ir/src/lang_items.rs b/compiler/rustc_type_ir/src/lang_items.rs index 3ee6e07b7a5e0..f9994448e282f 100644 --- a/compiler/rustc_type_ir/src/lang_items.rs +++ b/compiler/rustc_type_ir/src/lang_items.rs @@ -29,8 +29,8 @@ pub enum TraitSolverLangItem { Future, FutureOutput, Iterator, - Metadata, MetaSized, + Metadata, Option, PointeeSized, PointeeTrait, diff --git a/compiler/rustc_type_ir/src/macros.rs b/compiler/rustc_type_ir/src/macros.rs index c8c293121ca0a..9064f13eb45e9 100644 --- a/compiler/rustc_type_ir/src/macros.rs +++ b/compiler/rustc_type_ir/src/macros.rs @@ -53,11 +53,11 @@ TrivialTypeTraversalImpls! { crate::BoundConstness, crate::DebruijnIndex, crate::PredicatePolarity, + crate::UniverseIndex, + crate::Variance, crate::solve::BuiltinImplSource, crate::solve::Certainty, crate::solve::GoalSource, - crate::UniverseIndex, - crate::Variance, rustc_ast_ir::Mutability, // tidy-alphabetical-end } diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index 39d5399101da6..6e160eddecb97 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -150,8 +150,8 @@ #![feature(doc_cfg_hide)] #![feature(doc_notable_trait)] #![feature(extern_types)] -#![feature(f128)] #![feature(f16)] +#![feature(f128)] #![feature(freeze_impls)] #![feature(fundamental)] #![feature(if_let_guard)] diff --git a/library/coretests/tests/lib.rs b/library/coretests/tests/lib.rs index 5449132413b54..b8a5ff620a495 100644 --- a/library/coretests/tests/lib.rs +++ b/library/coretests/tests/lib.rs @@ -34,8 +34,8 @@ #![feature(exact_size_is_empty)] #![feature(extend_one)] #![feature(extern_types)] -#![feature(f128)] #![feature(f16)] +#![feature(f128)] #![feature(float_algebraic)] #![feature(float_gamma)] #![feature(float_minimum_maximum)] diff --git a/library/std/src/io/error.rs b/library/std/src/io/error.rs index d43976ecc9e5c..562fdbf4ff76d 100644 --- a/library/std/src/io/error.rs +++ b/library/std/src/io/error.rs @@ -462,8 +462,8 @@ impl ErrorKind { Deadlock => "deadlock", DirectoryNotEmpty => "directory not empty", ExecutableFileBusy => "executable file busy", - FilesystemLoop => "filesystem loop or indirection limit (e.g. symlink loop)", FileTooLarge => "file too large", + FilesystemLoop => "filesystem loop or indirection limit (e.g. symlink loop)", HostUnreachable => "host unreachable", InProgress => "in progress", Interrupted => "operation interrupted", diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 13fb08a9210b6..311b2cb932392 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -290,8 +290,8 @@ #![feature(doc_notable_trait)] #![feature(dropck_eyepatch)] #![feature(extended_varargs_abi_support)] -#![feature(f128)] #![feature(f16)] +#![feature(f128)] #![feature(ffi_const)] #![feature(formatting_options)] #![feature(if_let_guard)] diff --git a/library/std/src/sys/pal/windows/api.rs b/library/std/src/sys/pal/windows/api.rs index 6b5f9aeace28a..773455c572f70 100644 --- a/library/std/src/sys/pal/windows/api.rs +++ b/library/std/src/sys/pal/windows/api.rs @@ -271,20 +271,20 @@ impl WinError { // tidy-alphabetical-start pub const ACCESS_DENIED: Self = Self::new(c::ERROR_ACCESS_DENIED); pub const ALREADY_EXISTS: Self = Self::new(c::ERROR_ALREADY_EXISTS); - pub const BAD_NET_NAME: Self = Self::new(c::ERROR_BAD_NET_NAME); pub const BAD_NETPATH: Self = Self::new(c::ERROR_BAD_NETPATH); + pub const BAD_NET_NAME: Self = Self::new(c::ERROR_BAD_NET_NAME); pub const CANT_ACCESS_FILE: Self = Self::new(c::ERROR_CANT_ACCESS_FILE); pub const DELETE_PENDING: Self = Self::new(c::ERROR_DELETE_PENDING); - pub const DIR_NOT_EMPTY: Self = Self::new(c::ERROR_DIR_NOT_EMPTY); pub const DIRECTORY: Self = Self::new(c::ERROR_DIRECTORY); + pub const DIR_NOT_EMPTY: Self = Self::new(c::ERROR_DIR_NOT_EMPTY); pub const FILE_NOT_FOUND: Self = Self::new(c::ERROR_FILE_NOT_FOUND); pub const INSUFFICIENT_BUFFER: Self = Self::new(c::ERROR_INSUFFICIENT_BUFFER); pub const INVALID_FUNCTION: Self = Self::new(c::ERROR_INVALID_FUNCTION); pub const INVALID_HANDLE: Self = Self::new(c::ERROR_INVALID_HANDLE); pub const INVALID_PARAMETER: Self = Self::new(c::ERROR_INVALID_PARAMETER); - pub const NO_MORE_FILES: Self = Self::new(c::ERROR_NO_MORE_FILES); pub const NOT_FOUND: Self = Self::new(c::ERROR_NOT_FOUND); pub const NOT_SUPPORTED: Self = Self::new(c::ERROR_NOT_SUPPORTED); + pub const NO_MORE_FILES: Self = Self::new(c::ERROR_NO_MORE_FILES); pub const OPERATION_ABORTED: Self = Self::new(c::ERROR_OPERATION_ABORTED); pub const PATH_NOT_FOUND: Self = Self::new(c::ERROR_PATH_NOT_FOUND); pub const SHARING_VIOLATION: Self = Self::new(c::ERROR_SHARING_VIOLATION); diff --git a/library/std/tests/run-time-detect.rs b/library/std/tests/run-time-detect.rs index e59ae2f3d7f18..ae0c3385d2ad9 100644 --- a/library/std/tests/run-time-detect.rs +++ b/library/std/tests/run-time-detect.rs @@ -57,18 +57,18 @@ fn aarch64_linux() { println!("fhm: {}", is_aarch64_feature_detected!("fhm")); println!("flagm2: {}", is_aarch64_feature_detected!("flagm2")); println!("flagm: {}", is_aarch64_feature_detected!("flagm")); - println!("fp16: {}", is_aarch64_feature_detected!("fp16")); println!("fp8: {}", is_aarch64_feature_detected!("fp8")); println!("fp8dot2: {}", is_aarch64_feature_detected!("fp8dot2")); println!("fp8dot4: {}", is_aarch64_feature_detected!("fp8dot4")); println!("fp8fma: {}", is_aarch64_feature_detected!("fp8fma")); + println!("fp16: {}", is_aarch64_feature_detected!("fp16")); println!("fpmr: {}", is_aarch64_feature_detected!("fpmr")); println!("frintts: {}", is_aarch64_feature_detected!("frintts")); println!("hbc: {}", is_aarch64_feature_detected!("hbc")); println!("i8mm: {}", is_aarch64_feature_detected!("i8mm")); println!("jsconv: {}", is_aarch64_feature_detected!("jsconv")); - println!("lse128: {}", is_aarch64_feature_detected!("lse128")); println!("lse2: {}", is_aarch64_feature_detected!("lse2")); + println!("lse128: {}", is_aarch64_feature_detected!("lse128")); println!("lse: {}", is_aarch64_feature_detected!("lse")); println!("lut: {}", is_aarch64_feature_detected!("lut")); println!("mops: {}", is_aarch64_feature_detected!("mops")); @@ -87,10 +87,10 @@ fn aarch64_linux() { println!("sha3: {}", is_aarch64_feature_detected!("sha3")); println!("sm4: {}", is_aarch64_feature_detected!("sm4")); println!("sme-b16b16: {}", is_aarch64_feature_detected!("sme-b16b16")); - println!("sme-f16f16: {}", is_aarch64_feature_detected!("sme-f16f16")); - println!("sme-f64f64: {}", is_aarch64_feature_detected!("sme-f64f64")); println!("sme-f8f16: {}", is_aarch64_feature_detected!("sme-f8f16")); println!("sme-f8f32: {}", is_aarch64_feature_detected!("sme-f8f32")); + println!("sme-f16f16: {}", is_aarch64_feature_detected!("sme-f16f16")); + println!("sme-f64f64: {}", is_aarch64_feature_detected!("sme-f64f64")); println!("sme-fa64: {}", is_aarch64_feature_detected!("sme-fa64")); println!("sme-i16i64: {}", is_aarch64_feature_detected!("sme-i16i64")); println!("sme-lutv2: {}", is_aarch64_feature_detected!("sme-lutv2")); diff --git a/src/bootstrap/src/core/build_steps/dist.rs b/src/bootstrap/src/core/build_steps/dist.rs index e0f632eda0e29..2f5601e017a86 100644 --- a/src/bootstrap/src/core/build_steps/dist.rs +++ b/src/bootstrap/src/core/build_steps/dist.rs @@ -1036,18 +1036,18 @@ impl Step for PlainSourceTarball { let src_files = [ // tidy-alphabetical-start ".gitmodules", - "bootstrap.example.toml", - "Cargo.lock", - "Cargo.toml", - "configure", "CONTRIBUTING.md", "COPYRIGHT", + "Cargo.lock", + "Cargo.toml", "LICENSE-APACHE", - "license-metadata.json", "LICENSE-MIT", "README.md", "RELEASES.md", "REUSE.toml", + "bootstrap.example.toml", + "configure", + "license-metadata.json", "x", "x.ps1", "x.py", diff --git a/src/tools/tidy/src/alphabetical.rs b/src/tools/tidy/src/alphabetical.rs index a29286fa2c596..141083290c6c8 100644 --- a/src/tools/tidy/src/alphabetical.rs +++ b/src/tools/tidy/src/alphabetical.rs @@ -19,7 +19,9 @@ //! If a line ends with an opening delimiter, we effectively join the following line to it before //! checking it. E.g. `foo(\nbar)` is treated like `foo(bar)`. +use std::cmp::Ordering; use std::fmt::Display; +use std::iter::Peekable; use std::path::Path; use crate::walk::{filter_dirs, walk}; @@ -99,9 +101,9 @@ fn check_section<'a>( continue; } - let prev_line_trimmed_lowercase = prev_line.trim_start_matches(' ').to_lowercase(); + let prev_line_trimmed_lowercase = prev_line.trim_start_matches(' '); - if trimmed_line.to_lowercase() < prev_line_trimmed_lowercase { + if version_sort(&trimmed_line, &prev_line_trimmed_lowercase).is_lt() { tidy_error_ext!(err, bad, "{file}:{}: line not in alphabetical order", idx + 1); } @@ -143,3 +145,56 @@ pub fn check(path: &Path, bad: &mut bool) { check_lines(file, lines, &mut crate::tidy_error, bad) }); } + +fn consume_numeric_prefix>(it: &mut Peekable) -> String { + let mut result = String::new(); + + while let Some(&c) = it.peek() { + if !c.is_numeric() { + break; + } + + result.push(c); + it.next(); + } + + result +} + +// A sorting function that is case-sensitive, and sorts sequences of digits by their numeric value, +// so that `9` sorts before `12`. +fn version_sort(a: &str, b: &str) -> Ordering { + let mut it1 = a.chars().peekable(); + let mut it2 = b.chars().peekable(); + + while let (Some(x), Some(y)) = (it1.peek(), it2.peek()) { + match (x.is_numeric(), y.is_numeric()) { + (true, true) => { + let num1: String = consume_numeric_prefix(it1.by_ref()); + let num2: String = consume_numeric_prefix(it2.by_ref()); + + let int1: u64 = num1.parse().unwrap(); + let int2: u64 = num2.parse().unwrap(); + + // Compare strings when the numeric value is equal to handle "00" versus "0". + match int1.cmp(&int2).then_with(|| num1.cmp(&num2)) { + Ordering::Equal => continue, + different => return different, + } + } + (false, false) => match x.cmp(y) { + Ordering::Equal => { + it1.next(); + it2.next(); + continue; + } + different => return different, + }, + (false, true) | (true, false) => { + return x.cmp(y); + } + } + } + + it1.next().cmp(&it2.next()) +} diff --git a/src/tools/tidy/src/alphabetical/tests.rs b/src/tools/tidy/src/alphabetical/tests.rs index 29e89a693bfa0..4d05bc33cedc3 100644 --- a/src/tools/tidy/src/alphabetical/tests.rs +++ b/src/tools/tidy/src/alphabetical/tests.rs @@ -3,6 +3,7 @@ use std::str::from_utf8; use super::*; +#[track_caller] fn test(lines: &str, name: &str, expected_msg: &str, expected_bad: bool) { let mut actual_msg = Vec::new(); let mut actual_bad = false; @@ -15,10 +16,12 @@ fn test(lines: &str, name: &str, expected_msg: &str, expected_bad: bool) { assert_eq!(expected_bad, actual_bad); } +#[track_caller] fn good(lines: &str) { test(lines, "good", "", false); } +#[track_caller] fn bad(lines: &str, expected_msg: &str) { test(lines, "bad", expected_msg, true); } @@ -187,3 +190,147 @@ fn test_double_end() { "; bad(lines, "bad:5 found `tidy-alphabetical-end` expecting `tidy-alphabetical-start`"); } + +#[test] +fn test_numeric_good() { + good( + "\ + # tidy-alphabetical-start + rustc_ast = { path = \"../rustc_ast\" } + rustc_ast_lowering = { path = \"../rustc_ast_lowering\" } + # tidy-alphabetical-end + ", + ); + + good( + "\ + # tidy-alphabetical-start + fp-armv8 + fp16 + # tidy-alphabetical-end + ", + ); + + good( + "\ + # tidy-alphabetical-start + item1 + item2 + item10 + # tidy-alphabetical-end + ", + ); + + good( + "\ + # tidy-alphabetical-start + foo + foo_ + # tidy-alphabetical-end + ", + ); + + good( + "\ + # tidy-alphabetical-start + foo-bar + foo_bar + # tidy-alphabetical-end + ", + ); + + good( + "\ + # tidy-alphabetical-start + sme-lutv2 + sme2 + # tidy-alphabetical-end + ", + ); + + good( + "\ + # tidy-alphabetical-start + v5te + v6 + v6k + v6t2 + # tidy-alphabetical-end + ", + ); + + good( + "\ + # tidy-alphabetical-start + zve64d + zve64f + # tidy-alphabetical-end + ", + ); + + // Case is significant. + good( + "\ + # tidy-alphabetical-start + _ZYXW + _abcd + # tidy-alphabetical-end + ", + ); + + good( + "\ + # tidy-alphabetical-start + v0 + v00 + v000 + # tidy-alphabetical-end + ", + ); + + good( + "\ + # tidy-alphabetical-start + w005s09t + w5s009t + # tidy-alphabetical-end + ", + ); + + good( + "\ + # tidy-alphabetical-start + v0s + v00t + # tidy-alphabetical-end + ", + ); +} + +#[test] +fn test_numeric_bad() { + let lines = "\ + # tidy-alphabetical-start + item1 + item10 + item2 + # tidy-alphabetical-end + "; + bad(lines, "bad:4: line not in alphabetical order"); + + let lines = "\ + # tidy-alphabetical-start + zve64f + zve64d + # tidy-alphabetical-end + "; + bad(lines, "bad:3: line not in alphabetical order"); + + let lines = "\ + # tidy-alphabetical-start + 000 + 00 + # tidy-alphabetical-end + "; + bad(lines, "bad:3: line not in alphabetical order"); +} From 12e1f3db98c2b8c11c748281d40f4b5962207c2f Mon Sep 17 00:00:00 2001 From: Oneirical Date: Mon, 23 Jun 2025 14:42:46 -0400 Subject: [PATCH 21/23] Rewrite .gitattributes CRLF ui tests into run-make tests --- .../json-bom-plus-crlf-multifile.stderr | 114 ++++++++++++++++++ .../json-bom-plus-crlf-multifile/rmake.rs | 72 +++++++++++ .../json-bom-plus-crlf.stderr | 114 ++++++++++++++++++ tests/run-make/json-bom-plus-crlf/rmake.rs | 63 ++++++++++ .../rmake.rs | 39 ++++++ .../rmake.rs | 21 ++++ .../trailing-carriage-return-in-string.stderr | 6 +- tests/ui/.gitattributes | 5 - .../json/json-bom-plus-crlf-multifile-aux.rs | 27 ----- tests/ui/json/json-bom-plus-crlf-multifile.rs | 18 --- .../json/json-bom-plus-crlf-multifile.stderr | 114 ------------------ tests/ui/json/json-bom-plus-crlf.rs | 32 ----- tests/ui/json/json-bom-plus-crlf.stderr | 114 ------------------ ...line-endings-string-literal-doc-comment.rs | 38 ------ .../trailing-carriage-return-in-string.rs | 14 --- 15 files changed, 426 insertions(+), 365 deletions(-) create mode 100644 tests/run-make/json-bom-plus-crlf-multifile/json-bom-plus-crlf-multifile.stderr create mode 100644 tests/run-make/json-bom-plus-crlf-multifile/rmake.rs create mode 100644 tests/run-make/json-bom-plus-crlf/json-bom-plus-crlf.stderr create mode 100644 tests/run-make/json-bom-plus-crlf/rmake.rs create mode 100644 tests/run-make/lexer-crlf-line-endings-string-literal-doc-comment/rmake.rs create mode 100644 tests/run-make/trailing-carriage-return-in-string/rmake.rs rename tests/{ui/parser => run-make/trailing-carriage-return-in-string}/trailing-carriage-return-in-string.stderr (56%) delete mode 100644 tests/ui/json/json-bom-plus-crlf-multifile-aux.rs delete mode 100644 tests/ui/json/json-bom-plus-crlf-multifile.rs delete mode 100644 tests/ui/json/json-bom-plus-crlf-multifile.stderr delete mode 100644 tests/ui/json/json-bom-plus-crlf.rs delete mode 100644 tests/ui/json/json-bom-plus-crlf.stderr delete mode 100644 tests/ui/lexer/lexer-crlf-line-endings-string-literal-doc-comment.rs delete mode 100644 tests/ui/parser/trailing-carriage-return-in-string.rs diff --git a/tests/run-make/json-bom-plus-crlf-multifile/json-bom-plus-crlf-multifile.stderr b/tests/run-make/json-bom-plus-crlf-multifile/json-bom-plus-crlf-multifile.stderr new file mode 100644 index 0000000000000..2701d56d81647 --- /dev/null +++ b/tests/run-make/json-bom-plus-crlf-multifile/json-bom-plus-crlf-multifile.stderr @@ -0,0 +1,114 @@ +{"$message_type":"diagnostic","message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. + +Erroneous code examples: + +```compile_fail,E0308 +fn plus_one(x: i32) -> i32 { + x + 1 +} + +plus_one(\"Not a number\"); +// ^^^^^^^^^^^^^^ expected `i32`, found `&str` + +if \"Not a bool\" { +// ^^^^^^^^^^^^ expected `bool`, found `&str` +} + +let x: f32 = \"Not a float\"; +// --- ^^^^^^^^^^^^^ expected `f32`, found `&str` +// | +// expected due to this +``` + +This error occurs when an expression was used in a place where the compiler +expected an expression of a different type. It can occur in several cases, the +most common being when calling a function and passing an argument which has a +different type than the matching type in the function declaration. +"},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":true,"text":[{"text":"let s : String = 1; // Error in the middle of line.","highlight_start":XX,"highlight_end":XX}],"label":"expected `String`, found integer","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":false,"text":[{"text":"let s : String = 1; // Error in the middle of line.","highlight_start":XX,"highlight_end":XX}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[{"message":"try using a conversion method","code":null,"level":"help","spans":[{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":true,"text":[{"text":"let s : String = 1; // Error in the middle of line.","highlight_start":XX,"highlight_end":XX}],"label":null,"suggested_replacement":".to_string()","suggestion_applicability":"MaybeIncorrect","expansion":null}],"children":[],"rendered":null}],"rendered":"$DIR/json-bom-plus-crlf-multifile-aux.rs:LL:CC: error[E0308]: mismatched types: expected `String`, found integer +"} +{"$message_type":"diagnostic","message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. + +Erroneous code examples: + +```compile_fail,E0308 +fn plus_one(x: i32) -> i32 { + x + 1 +} + +plus_one(\"Not a number\"); +// ^^^^^^^^^^^^^^ expected `i32`, found `&str` + +if \"Not a bool\" { +// ^^^^^^^^^^^^ expected `bool`, found `&str` +} + +let x: f32 = \"Not a float\"; +// --- ^^^^^^^^^^^^^ expected `f32`, found `&str` +// | +// expected due to this +``` + +This error occurs when an expression was used in a place where the compiler +expected an expression of a different type. It can occur in several cases, the +most common being when calling a function and passing an argument which has a +different type than the matching type in the function declaration. +"},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":true,"text":[{"text":"let s : String = 1","highlight_start":XX,"highlight_end":XX}],"label":"expected `String`, found integer","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":false,"text":[{"text":"let s : String = 1","highlight_start":XX,"highlight_end":XX}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[{"message":"try using a conversion method","code":null,"level":"help","spans":[{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":true,"text":[{"text":"let s : String = 1","highlight_start":XX,"highlight_end":XX}],"label":null,"suggested_replacement":".to_string()","suggestion_applicability":"MaybeIncorrect","expansion":null}],"children":[],"rendered":null}],"rendered":"$DIR/json-bom-plus-crlf-multifile-aux.rs:LL:CC: error[E0308]: mismatched types: expected `String`, found integer +"} +{"$message_type":"diagnostic","message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. + +Erroneous code examples: + +```compile_fail,E0308 +fn plus_one(x: i32) -> i32 { + x + 1 +} + +plus_one(\"Not a number\"); +// ^^^^^^^^^^^^^^ expected `i32`, found `&str` + +if \"Not a bool\" { +// ^^^^^^^^^^^^ expected `bool`, found `&str` +} + +let x: f32 = \"Not a float\"; +// --- ^^^^^^^^^^^^^ expected `f32`, found `&str` +// | +// expected due to this +``` + +This error occurs when an expression was used in a place where the compiler +expected an expression of a different type. It can occur in several cases, the +most common being when calling a function and passing an argument which has a +different type than the matching type in the function declaration. +"},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":true,"text":[{"text":"1; // Error after the newline.","highlight_start":XX,"highlight_end":XX}],"label":"expected `String`, found integer","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":false,"text":[{"text":"let s : String =","highlight_start":XX,"highlight_end":XX}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[{"message":"try using a conversion method","code":null,"level":"help","spans":[{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":true,"text":[{"text":"1; // Error after the newline.","highlight_start":XX,"highlight_end":XX}],"label":null,"suggested_replacement":".to_string()","suggestion_applicability":"MaybeIncorrect","expansion":null}],"children":[],"rendered":null}],"rendered":"$DIR/json-bom-plus-crlf-multifile-aux.rs:LL:CC: error[E0308]: mismatched types: expected `String`, found integer +"} +{"$message_type":"diagnostic","message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. + +Erroneous code examples: + +```compile_fail,E0308 +fn plus_one(x: i32) -> i32 { + x + 1 +} + +plus_one(\"Not a number\"); +// ^^^^^^^^^^^^^^ expected `i32`, found `&str` + +if \"Not a bool\" { +// ^^^^^^^^^^^^ expected `bool`, found `&str` +} + +let x: f32 = \"Not a float\"; +// --- ^^^^^^^^^^^^^ expected `f32`, found `&str` +// | +// expected due to this +``` + +This error occurs when an expression was used in a place where the compiler +expected an expression of a different type. It can occur in several cases, the +most common being when calling a function and passing an argument which has a +different type than the matching type in the function declaration. +"},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":true,"text":[{"text":"let s : String = (","highlight_start":XX,"highlight_end":XX},{"text":"); // Error spanning the newline.","highlight_start":XX,"highlight_end":XX}],"label":"expected `String`, found `()`","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":false,"text":[{"text":"let s : String = (","highlight_start":XX,"highlight_end":XX}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[],"rendered":"$DIR/json-bom-plus-crlf-multifile-aux.rs:LL:CC: error[E0308]: mismatched types: expected `String`, found `()` +"} +{"$message_type":"diagnostic","message":"aborting due to 4 previous errors","code":null,"level":"error","spans":[],"children":[],"rendered":"error: aborting due to 4 previous errors +"} diff --git a/tests/run-make/json-bom-plus-crlf-multifile/rmake.rs b/tests/run-make/json-bom-plus-crlf-multifile/rmake.rs new file mode 100644 index 0000000000000..594b1914210b0 --- /dev/null +++ b/tests/run-make/json-bom-plus-crlf-multifile/rmake.rs @@ -0,0 +1,72 @@ +//@ reference: input.byte-order-mark +//@ reference: input.crlf + +use run_make_support::{cwd, diff, rfs, rustc}; + +fn main() { + let aux_content = "\u{FEFF}\ +pub fn test() {\r\n\ +\r\n\ + let s : String = 1; // Error in the middle of line.\r\n\ +\r\n\ + let s : String = 1\r\n\ + ; // Error before the newline.\r\n\ +\r\n\ + let s : String =\r\n\ +1; // Error after the newline.\r\n\ +\r\n\ + let s : String = (\r\n\ + ); // Error spanning the newline.\r\n\ +}\r\n"; + + rfs::write(cwd().join("json-bom-plus-crlf-multifile-aux.rs"), aux_content); + + let aux_bytes = rfs::read(cwd().join("json-bom-plus-crlf-multifile-aux.rs")); + assert!(aux_bytes.starts_with(b"\xEF\xBB\xBF"), "File must start with UTF-8 BOM"); + assert!(aux_bytes.windows(2).any(|w| w == b"\r\n"), "File must contain CRLF line endings"); + + let main_content = "\u{FEFF}\ +#[path = \"json-bom-plus-crlf-multifile-aux.rs\"]\r\n\ +mod json_bom_plus_crlf_multifile_aux;\r\n\ +\r\n\ +fn main() {\r\n\ + json_bom_plus_crlf_multifile_aux::test();\r\n\ +}\r\n"; + + rfs::write(cwd().join("json-bom-plus-crlf-multifile.rs"), main_content); + + let output = rustc() + .input(cwd().join("json-bom-plus-crlf-multifile.rs")) + .json("diagnostic-short") + .error_format("json") + .ui_testing() + .run_fail() + .stderr_utf8(); + + diff() + .expected_file("json-bom-plus-crlf-multifile.stderr") + .actual_text("stderr", &output) + .normalize(r"\\n", "\n") + .normalize(r"\\r\\n", "\n") + .normalize(r#""line_start":\d+"#, r#""line_start":LL"#) + .normalize(r#""line_end":\d+"#, r#""line_end":LL"#) + .normalize(r#""column_start":\d+"#, r#""column_start":CC"#) + .normalize(r#""column_end":\d+"#, r#""column_end":CC"#) + .normalize(r#""byte_start":\d+"#, r#""byte_start":XXX"#) + .normalize(r#""byte_end":\d+"#, r#""byte_end":XXX"#) + .normalize(r#""highlight_start":\d+"#, r#""highlight_start":XX"#) + .normalize(r#""highlight_end":\d+"#, r#""highlight_end":XX"#) + .normalize( + r#""file_name":"[^"]*json-bom-plus-crlf-multifile-aux\.rs""#, + r#""file_name":"$$DIR/json-bom-plus-crlf-multifile-aux.rs""#, + ) + .normalize( + r#""rendered":"(?:[^"]*/)?json-bom-plus-crlf-multifile-aux\.rs:\d+:\d+:"#, + r#""rendered":"$$DIR/json-bom-plus-crlf-multifile-aux.rs:LL:CC:"#, + ) + .normalize( + r#""rendered":"(?:[^"]*/)?json-bom-plus-crlf-multifile-aux\.rs:\d+:\d+ error"#, + r#""rendered":"$$DIR/json-bom-plus-crlf-multifile-aux.rs:LL:CC error"#, + ) + .run(); +} diff --git a/tests/run-make/json-bom-plus-crlf/json-bom-plus-crlf.stderr b/tests/run-make/json-bom-plus-crlf/json-bom-plus-crlf.stderr new file mode 100644 index 0000000000000..b76e27ab239dd --- /dev/null +++ b/tests/run-make/json-bom-plus-crlf/json-bom-plus-crlf.stderr @@ -0,0 +1,114 @@ +{"$message_type":"diagnostic","message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. + +Erroneous code examples: + +```compile_fail,E0308 +fn plus_one(x: i32) -> i32 { + x + 1 +} + +plus_one(\"Not a number\"); +// ^^^^^^^^^^^^^^ expected `i32`, found `&str` + +if \"Not a bool\" { +// ^^^^^^^^^^^^ expected `bool`, found `&str` +} + +let x: f32 = \"Not a float\"; +// --- ^^^^^^^^^^^^^ expected `f32`, found `&str` +// | +// expected due to this +``` + +This error occurs when an expression was used in a place where the compiler +expected an expression of a different type. It can occur in several cases, the +most common being when calling a function and passing an argument which has a +different type than the matching type in the function declaration. +"},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":true,"text":[{"text":"let s : String = 1; // Error in the middle of line.","highlight_start":XX,"highlight_end":XX}],"label":"expected `String`, found integer","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":false,"text":[{"text":"let s : String = 1; // Error in the middle of line.","highlight_start":XX,"highlight_end":XX}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[{"message":"try using a conversion method","code":null,"level":"help","spans":[{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":true,"text":[{"text":"let s : String = 1; // Error in the middle of line.","highlight_start":XX,"highlight_end":XX}],"label":null,"suggested_replacement":".to_string()","suggestion_applicability":"MaybeIncorrect","expansion":null}],"children":[],"rendered":null}],"rendered":"$DIR/json-bom-plus-crlf.rs:LL:CC: error[E0308]: mismatched types: expected `String`, found integer +"} +{"$message_type":"diagnostic","message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. + +Erroneous code examples: + +```compile_fail,E0308 +fn plus_one(x: i32) -> i32 { + x + 1 +} + +plus_one(\"Not a number\"); +// ^^^^^^^^^^^^^^ expected `i32`, found `&str` + +if \"Not a bool\" { +// ^^^^^^^^^^^^ expected `bool`, found `&str` +} + +let x: f32 = \"Not a float\"; +// --- ^^^^^^^^^^^^^ expected `f32`, found `&str` +// | +// expected due to this +``` + +This error occurs when an expression was used in a place where the compiler +expected an expression of a different type. It can occur in several cases, the +most common being when calling a function and passing an argument which has a +different type than the matching type in the function declaration. +"},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":true,"text":[{"text":"let s : String = 1","highlight_start":XX,"highlight_end":XX}],"label":"expected `String`, found integer","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":false,"text":[{"text":"let s : String = 1","highlight_start":XX,"highlight_end":XX}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[{"message":"try using a conversion method","code":null,"level":"help","spans":[{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":true,"text":[{"text":"let s : String = 1","highlight_start":XX,"highlight_end":XX}],"label":null,"suggested_replacement":".to_string()","suggestion_applicability":"MaybeIncorrect","expansion":null}],"children":[],"rendered":null}],"rendered":"$DIR/json-bom-plus-crlf.rs:LL:CC: error[E0308]: mismatched types: expected `String`, found integer +"} +{"$message_type":"diagnostic","message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. + +Erroneous code examples: + +```compile_fail,E0308 +fn plus_one(x: i32) -> i32 { + x + 1 +} + +plus_one(\"Not a number\"); +// ^^^^^^^^^^^^^^ expected `i32`, found `&str` + +if \"Not a bool\" { +// ^^^^^^^^^^^^ expected `bool`, found `&str` +} + +let x: f32 = \"Not a float\"; +// --- ^^^^^^^^^^^^^ expected `f32`, found `&str` +// | +// expected due to this +``` + +This error occurs when an expression was used in a place where the compiler +expected an expression of a different type. It can occur in several cases, the +most common being when calling a function and passing an argument which has a +different type than the matching type in the function declaration. +"},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":true,"text":[{"text":"1; // Error after the newline.","highlight_start":XX,"highlight_end":XX}],"label":"expected `String`, found integer","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":false,"text":[{"text":"let s : String =","highlight_start":XX,"highlight_end":XX}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[{"message":"try using a conversion method","code":null,"level":"help","spans":[{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":true,"text":[{"text":"1; // Error after the newline.","highlight_start":XX,"highlight_end":XX}],"label":null,"suggested_replacement":".to_string()","suggestion_applicability":"MaybeIncorrect","expansion":null}],"children":[],"rendered":null}],"rendered":"$DIR/json-bom-plus-crlf.rs:LL:CC: error[E0308]: mismatched types: expected `String`, found integer +"} +{"$message_type":"diagnostic","message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. + +Erroneous code examples: + +```compile_fail,E0308 +fn plus_one(x: i32) -> i32 { + x + 1 +} + +plus_one(\"Not a number\"); +// ^^^^^^^^^^^^^^ expected `i32`, found `&str` + +if \"Not a bool\" { +// ^^^^^^^^^^^^ expected `bool`, found `&str` +} + +let x: f32 = \"Not a float\"; +// --- ^^^^^^^^^^^^^ expected `f32`, found `&str` +// | +// expected due to this +``` + +This error occurs when an expression was used in a place where the compiler +expected an expression of a different type. It can occur in several cases, the +most common being when calling a function and passing an argument which has a +different type than the matching type in the function declaration. +"},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":true,"text":[{"text":"let s : String = (","highlight_start":XX,"highlight_end":XX},{"text":"); // Error spanning the newline.","highlight_start":XX,"highlight_end":XX}],"label":"expected `String`, found `()`","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":XXX,"byte_end":XXX,"line_start":LL,"line_end":LL,"column_start":CC,"column_end":CC,"is_primary":false,"text":[{"text":"let s : String = (","highlight_start":XX,"highlight_end":XX}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[],"rendered":"$DIR/json-bom-plus-crlf.rs:LL:CC: error[E0308]: mismatched types: expected `String`, found `()` +"} +{"$message_type":"diagnostic","message":"aborting due to 4 previous errors","code":null,"level":"error","spans":[],"children":[],"rendered":"error: aborting due to 4 previous errors +"} diff --git a/tests/run-make/json-bom-plus-crlf/rmake.rs b/tests/run-make/json-bom-plus-crlf/rmake.rs new file mode 100644 index 0000000000000..5d0cd30057dd8 --- /dev/null +++ b/tests/run-make/json-bom-plus-crlf/rmake.rs @@ -0,0 +1,63 @@ +//@ reference: input.byte-order-mark +//@ reference: input.crlf + +use run_make_support::{cwd, diff, rfs, rustc}; + +fn main() { + let main_content = "\u{FEFF}\ +fn main() {\r\n\ +\r\n\ + let s : String = 1; // Error in the middle of line.\r\n\ +\r\n\ + let s : String = 1\r\n\ + ; // Error before the newline.\r\n\ +\r\n\ + let s : String =\r\n\ +1; // Error after the newline.\r\n\ +\r\n\ + let s : String = (\r\n\ + ); // Error spanning the newline.\r\n\ +}\r\n"; + + let main_path = cwd().join("json-bom-plus-crlf.rs"); + rfs::write(&main_path, main_content); + + let main_bytes = rfs::read(&main_path); + assert!(main_bytes.starts_with(b"\xEF\xBB\xBF"), "File must start with UTF-8 BOM"); + assert!(main_bytes.windows(2).any(|w| w == b"\r\n"), "File must contain CRLF line endings"); + + let output = rustc() + .input(&main_path) + .json("diagnostic-short") + .error_format("json") + .ui_testing() + .run_fail() + .stderr_utf8(); + + diff() + .expected_file("json-bom-plus-crlf.stderr") + .actual_text("stderr", &output) + .normalize(r"\\n", "\n") + .normalize(r"\\r\\n", "\n") + .normalize(r#""line_start":\d+"#, r#""line_start":LL"#) + .normalize(r#""line_end":\d+"#, r#""line_end":LL"#) + .normalize(r#""column_start":\d+"#, r#""column_start":CC"#) + .normalize(r#""column_end":\d+"#, r#""column_end":CC"#) + .normalize(r#""byte_start":\d+"#, r#""byte_start":XXX"#) + .normalize(r#""byte_end":\d+"#, r#""byte_end":XXX"#) + .normalize(r#""highlight_start":\d+"#, r#""highlight_start":XX"#) + .normalize(r#""highlight_end":\d+"#, r#""highlight_end":XX"#) + .normalize( + r#""file_name":"[^"]*json-bom-plus-crlf\.rs""#, + r#""file_name":"$$DIR/json-bom-plus-crlf.rs""#, + ) + .normalize( + r#""rendered":"(?:[^"]*/)?json-bom-plus-crlf\.rs:\d+:\d+:"#, + r#""rendered":"$$DIR/json-bom-plus-crlf.rs:LL:CC:"#, + ) + .normalize( + r#""rendered":"(?:[^"]*/)?json-bom-plus-crlf\.rs:\d+:\d+ error"#, + r#""rendered":"$$DIR/json-bom-plus-crlf.rs:LL:CC error"#, + ) + .run(); +} diff --git a/tests/run-make/lexer-crlf-line-endings-string-literal-doc-comment/rmake.rs b/tests/run-make/lexer-crlf-line-endings-string-literal-doc-comment/rmake.rs new file mode 100644 index 0000000000000..77962dd7185af --- /dev/null +++ b/tests/run-make/lexer-crlf-line-endings-string-literal-doc-comment/rmake.rs @@ -0,0 +1,39 @@ +//@ reference: input.crlf + +use run_make_support::{cwd, rfs, run, rustc}; + +fn main() { + let test_content = "/// Doc comment that ends in CRLF\r\n\ +pub fn foo() {}\r\n\ +\r\n\ +/** Block doc comment that\r\n\ + * contains CRLF characters\r\n\ + */\r\n\ +pub fn bar() {}\r\n\ +\r\n\ +fn main() {\r\n\ + let s = \"string\r\nliteral\";\r\n\ + assert_eq!(s, \"string\\nliteral\");\r\n\ +\r\n\ + let s = \"literal with \\\r\n\ + escaped newline\";\r\n\ + assert_eq!(s, \"literal with escaped newline\");\r\n\ +\r\n\ + let s = r\"string\r\nliteral\";\r\n\ + assert_eq!(s, \"string\\nliteral\");\r\n\ + let s = br\"byte string\r\nliteral\";\r\n\ + assert_eq!(s, \"byte string\\nliteral\".as_bytes());\r\n\ +\r\n\ + // validate that our source file has CRLF endings\r\n\ + let source = include_str!(file!());\r\n\ + assert!(source.contains(\"string\\r\\nliteral\"));\r\n\ +}\r\n"; + + let test_path = cwd().join("lexer-crlf-line-endings-string-literal-doc-comment.rs"); + rfs::write(&test_path, test_content); + + let test_bytes = rfs::read(&test_path); + assert!(test_bytes.windows(2).any(|w| w == b"\r\n"), "File must contain CRLF line endings"); + + rustc().input(&test_path).run(); +} diff --git a/tests/run-make/trailing-carriage-return-in-string/rmake.rs b/tests/run-make/trailing-carriage-return-in-string/rmake.rs new file mode 100644 index 0000000000000..66fb0191e84ec --- /dev/null +++ b/tests/run-make/trailing-carriage-return-in-string/rmake.rs @@ -0,0 +1,21 @@ +use run_make_support::{cwd, diff, rfs, rustc}; + +fn main() { + let test_content = "fn main() {\n\ + // \\r\\n\n\ + let ok = \"This is \\\r\n a test\";\n\ + // \\r only\n\ + let bad = \"This is \\\r a test\";\n\ +}\n"; + + let test_path = cwd().join("trailing-carriage-return-in-string.rs"); + rfs::write(&test_path, test_content); + + let output = rustc().input(&test_path).ui_testing().run_fail().stderr_utf8(); + + diff() + .expected_file("trailing-carriage-return-in-string.stderr") + .actual_text("stderr", &output) + .normalize(r#"--> [^\n]+"#, "--> trailing-carriage-return-in-string.rs:LL:CC") + .run(); +} diff --git a/tests/ui/parser/trailing-carriage-return-in-string.stderr b/tests/run-make/trailing-carriage-return-in-string/trailing-carriage-return-in-string.stderr similarity index 56% rename from tests/ui/parser/trailing-carriage-return-in-string.stderr rename to tests/run-make/trailing-carriage-return-in-string/trailing-carriage-return-in-string.stderr index c5949432af893..4adafc08e0450 100644 --- a/tests/ui/parser/trailing-carriage-return-in-string.stderr +++ b/tests/run-make/trailing-carriage-return-in-string/trailing-carriage-return-in-string.stderr @@ -1,8 +1,8 @@ error: unknown character escape: `\r` - --> $DIR/trailing-carriage-return-in-string.rs:10:25 + --> trailing-carriage-return-in-string.rs:LL:CC | -LL | let bad = "This is \␍ a test"; - | ^ unknown character escape +LL | let bad = "This is \␍ a test"; + | ^ unknown character escape | = help: this is an isolated carriage return; consider checking your editor and version control settings diff --git a/tests/ui/.gitattributes b/tests/ui/.gitattributes index 9ea3d3fb0e1f1..e72d32c601a75 100644 --- a/tests/ui/.gitattributes +++ b/tests/ui/.gitattributes @@ -1,6 +1 @@ -lexer-crlf-line-endings-string-literal-doc-comment.rs -text -json-bom-plus-crlf.rs -text -json-bom-plus-crlf-multifile.rs -text -json-bom-plus-crlf-multifile-aux.rs -text -trailing-carriage-return-in-string.rs -text *.bin -text diff --git a/tests/ui/json/json-bom-plus-crlf-multifile-aux.rs b/tests/ui/json/json-bom-plus-crlf-multifile-aux.rs deleted file mode 100644 index 94b1e188ced97..0000000000000 --- a/tests/ui/json/json-bom-plus-crlf-multifile-aux.rs +++ /dev/null @@ -1,27 +0,0 @@ -// (This line has BOM so it's ignored by compiletest for directives) -// -//@ ignore-test Not a test. Used by other tests -// ignore-tidy-cr - -// For easier verifying, the byte offsets in this file should match those -// in the json-bom-plus-crlf.rs - given the actual fn is identical (just with -// a different, but equally sized name), the easiest way to do this is to -// ensure the two files are of equal size on disk. -// Padding............................ - -// N.B., this file needs CRLF line endings. The .gitattributes file in -// this directory should enforce it. - -pub fn test() { - - let s : String = 1; // Error in the middle of line. - - let s : String = 1 - ; // Error before the newline. - - let s : String = -1; // Error after the newline. - - let s : String = ( - ); // Error spanning the newline. -} diff --git a/tests/ui/json/json-bom-plus-crlf-multifile.rs b/tests/ui/json/json-bom-plus-crlf-multifile.rs deleted file mode 100644 index 074a2583e8276..0000000000000 --- a/tests/ui/json/json-bom-plus-crlf-multifile.rs +++ /dev/null @@ -1,18 +0,0 @@ -// (This line has BOM so it's ignored by compiletest for directives) -// -//@ compile-flags: --json=diagnostic-short --error-format=json -//@ reference: input.byte-order-mark -//@ reference: input.crlf -// ignore-tidy-cr - -#[path = "json-bom-plus-crlf-multifile-aux.rs"] -mod json_bom_plus_crlf_multifile_aux; - -fn main() { - json_bom_plus_crlf_multifile_aux::test(); -} - -//~? ERROR mismatched types -//~? ERROR mismatched types -//~? ERROR mismatched types -//~? ERROR mismatched types diff --git a/tests/ui/json/json-bom-plus-crlf-multifile.stderr b/tests/ui/json/json-bom-plus-crlf-multifile.stderr deleted file mode 100644 index 9c88a7e5a2564..0000000000000 --- a/tests/ui/json/json-bom-plus-crlf-multifile.stderr +++ /dev/null @@ -1,114 +0,0 @@ -{"$message_type":"diagnostic","message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. - -Erroneous code examples: - -```compile_fail,E0308 -fn plus_one(x: i32) -> i32 { - x + 1 -} - -plus_one(\"Not a number\"); -// ^^^^^^^^^^^^^^ expected `i32`, found `&str` - -if \"Not a bool\" { -// ^^^^^^^^^^^^ expected `bool`, found `&str` -} - -let x: f32 = \"Not a float\"; -// --- ^^^^^^^^^^^^^ expected `f32`, found `&str` -// | -// expected due to this -``` - -This error occurs when an expression was used in a place where the compiler -expected an expression of a different type. It can occur in several cases, the -most common being when calling a function and passing an argument which has a -different type than the matching type in the function declaration. -"},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":622,"byte_end":623,"line_start":17,"line_end":17,"column_start":22,"column_end":23,"is_primary":true,"text":[{"text":" let s : String = 1; // Error in the middle of line.","highlight_start":22,"highlight_end":23}],"label":"expected `String`, found integer","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":613,"byte_end":619,"line_start":17,"line_end":17,"column_start":13,"column_end":19,"is_primary":false,"text":[{"text":" let s : String = 1; // Error in the middle of line.","highlight_start":13,"highlight_end":19}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[{"message":"try using a conversion method","code":null,"level":"help","spans":[{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":623,"byte_end":623,"line_start":17,"line_end":17,"column_start":23,"column_end":23,"is_primary":true,"text":[{"text":" let s : String = 1; // Error in the middle of line.","highlight_start":23,"highlight_end":23}],"label":null,"suggested_replacement":".to_string()","suggestion_applicability":"MaybeIncorrect","expansion":null}],"children":[],"rendered":null}],"rendered":"$DIR/json-bom-plus-crlf-multifile-aux.rs:17:22: error[E0308]: mismatched types: expected `String`, found integer -"} -{"$message_type":"diagnostic","message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. - -Erroneous code examples: - -```compile_fail,E0308 -fn plus_one(x: i32) -> i32 { - x + 1 -} - -plus_one(\"Not a number\"); -// ^^^^^^^^^^^^^^ expected `i32`, found `&str` - -if \"Not a bool\" { -// ^^^^^^^^^^^^ expected `bool`, found `&str` -} - -let x: f32 = \"Not a float\"; -// --- ^^^^^^^^^^^^^ expected `f32`, found `&str` -// | -// expected due to this -``` - -This error occurs when an expression was used in a place where the compiler -expected an expression of a different type. It can occur in several cases, the -most common being when calling a function and passing an argument which has a -different type than the matching type in the function declaration. -"},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":682,"byte_end":683,"line_start":19,"line_end":19,"column_start":22,"column_end":23,"is_primary":true,"text":[{"text":" let s : String = 1","highlight_start":22,"highlight_end":23}],"label":"expected `String`, found integer","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":673,"byte_end":679,"line_start":19,"line_end":19,"column_start":13,"column_end":19,"is_primary":false,"text":[{"text":" let s : String = 1","highlight_start":13,"highlight_end":19}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[{"message":"try using a conversion method","code":null,"level":"help","spans":[{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":683,"byte_end":683,"line_start":19,"line_end":19,"column_start":23,"column_end":23,"is_primary":true,"text":[{"text":" let s : String = 1","highlight_start":23,"highlight_end":23}],"label":null,"suggested_replacement":".to_string()","suggestion_applicability":"MaybeIncorrect","expansion":null}],"children":[],"rendered":null}],"rendered":"$DIR/json-bom-plus-crlf-multifile-aux.rs:19:22: error[E0308]: mismatched types: expected `String`, found integer -"} -{"$message_type":"diagnostic","message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. - -Erroneous code examples: - -```compile_fail,E0308 -fn plus_one(x: i32) -> i32 { - x + 1 -} - -plus_one(\"Not a number\"); -// ^^^^^^^^^^^^^^ expected `i32`, found `&str` - -if \"Not a bool\" { -// ^^^^^^^^^^^^ expected `bool`, found `&str` -} - -let x: f32 = \"Not a float\"; -// --- ^^^^^^^^^^^^^ expected `f32`, found `&str` -// | -// expected due to this -``` - -This error occurs when an expression was used in a place where the compiler -expected an expression of a different type. It can occur in several cases, the -most common being when calling a function and passing an argument which has a -different type than the matching type in the function declaration. -"},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":746,"byte_end":747,"line_start":23,"line_end":23,"column_start":1,"column_end":2,"is_primary":true,"text":[{"text":"1; // Error after the newline.","highlight_start":1,"highlight_end":2}],"label":"expected `String`, found integer","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":736,"byte_end":742,"line_start":22,"line_end":22,"column_start":13,"column_end":19,"is_primary":false,"text":[{"text":" let s : String =","highlight_start":13,"highlight_end":19}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[{"message":"try using a conversion method","code":null,"level":"help","spans":[{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":747,"byte_end":747,"line_start":23,"line_end":23,"column_start":2,"column_end":2,"is_primary":true,"text":[{"text":"1; // Error after the newline.","highlight_start":2,"highlight_end":2}],"label":null,"suggested_replacement":".to_string()","suggestion_applicability":"MaybeIncorrect","expansion":null}],"children":[],"rendered":null}],"rendered":"$DIR/json-bom-plus-crlf-multifile-aux.rs:23:1: error[E0308]: mismatched types: expected `String`, found integer -"} -{"$message_type":"diagnostic","message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. - -Erroneous code examples: - -```compile_fail,E0308 -fn plus_one(x: i32) -> i32 { - x + 1 -} - -plus_one(\"Not a number\"); -// ^^^^^^^^^^^^^^ expected `i32`, found `&str` - -if \"Not a bool\" { -// ^^^^^^^^^^^^ expected `bool`, found `&str` -} - -let x: f32 = \"Not a float\"; -// --- ^^^^^^^^^^^^^ expected `f32`, found `&str` -// | -// expected due to this -``` - -This error occurs when an expression was used in a place where the compiler -expected an expression of a different type. It can occur in several cases, the -most common being when calling a function and passing an argument which has a -different type than the matching type in the function declaration. -"},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":802,"byte_end":810,"line_start":25,"line_end":26,"column_start":22,"column_end":6,"is_primary":true,"text":[{"text":" let s : String = (","highlight_start":22,"highlight_end":23},{"text":" ); // Error spanning the newline.","highlight_start":1,"highlight_end":6}],"label":"expected `String`, found `()`","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":793,"byte_end":799,"line_start":25,"line_end":25,"column_start":13,"column_end":19,"is_primary":false,"text":[{"text":" let s : String = (","highlight_start":13,"highlight_end":19}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[],"rendered":"$DIR/json-bom-plus-crlf-multifile-aux.rs:25:22: error[E0308]: mismatched types: expected `String`, found `()` -"} -{"$message_type":"diagnostic","message":"aborting due to 4 previous errors","code":null,"level":"error","spans":[],"children":[],"rendered":"error: aborting due to 4 previous errors -"} diff --git a/tests/ui/json/json-bom-plus-crlf.rs b/tests/ui/json/json-bom-plus-crlf.rs deleted file mode 100644 index 900a92f368298..0000000000000 --- a/tests/ui/json/json-bom-plus-crlf.rs +++ /dev/null @@ -1,32 +0,0 @@ -// (This line has BOM so it's ignored by compiletest for directives) -// -//@ compile-flags: --json=diagnostic-short --error-format=json -//@ reference: input.byte-order-mark -//@ reference: input.crlf -// ignore-tidy-cr - -// For easier verifying, the byte offsets in this file should match those -// in the json_bom_plus_crlf_multifile_aux.rs - given the actual fn is -// identical (just with a different, but equally sized name), the easiest way -// to do this is to ensure the two files are of equal size on disk. - -// N.B., this file needs CRLF line endings. The .gitattributes file in -// this directory should enforce it. - -fn main() { - - let s : String = 1; // Error in the middle of line. - //~^ ERROR mismatched types - - let s : String = 1 - ; // Error before the newline. - //~^^ ERROR mismatched types - - let s : String = -1; // Error after the newline. - //~^ ERROR mismatched types - - let s : String = ( - ); // Error spanning the newline. - //~^^ ERROR mismatched types -} diff --git a/tests/ui/json/json-bom-plus-crlf.stderr b/tests/ui/json/json-bom-plus-crlf.stderr deleted file mode 100644 index 59f0e8178f0e3..0000000000000 --- a/tests/ui/json/json-bom-plus-crlf.stderr +++ /dev/null @@ -1,114 +0,0 @@ -{"$message_type":"diagnostic","message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. - -Erroneous code examples: - -```compile_fail,E0308 -fn plus_one(x: i32) -> i32 { - x + 1 -} - -plus_one(\"Not a number\"); -// ^^^^^^^^^^^^^^ expected `i32`, found `&str` - -if \"Not a bool\" { -// ^^^^^^^^^^^^ expected `bool`, found `&str` -} - -let x: f32 = \"Not a float\"; -// --- ^^^^^^^^^^^^^ expected `f32`, found `&str` -// | -// expected due to this -``` - -This error occurs when an expression was used in a place where the compiler -expected an expression of a different type. It can occur in several cases, the -most common being when calling a function and passing an argument which has a -different type than the matching type in the function declaration. -"},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":672,"byte_end":673,"line_start":18,"line_end":18,"column_start":22,"column_end":23,"is_primary":true,"text":[{"text":" let s : String = 1; // Error in the middle of line.","highlight_start":22,"highlight_end":23}],"label":"expected `String`, found integer","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":663,"byte_end":669,"line_start":18,"line_end":18,"column_start":13,"column_end":19,"is_primary":false,"text":[{"text":" let s : String = 1; // Error in the middle of line.","highlight_start":13,"highlight_end":19}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[{"message":"try using a conversion method","code":null,"level":"help","spans":[{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":673,"byte_end":673,"line_start":18,"line_end":18,"column_start":23,"column_end":23,"is_primary":true,"text":[{"text":" let s : String = 1; // Error in the middle of line.","highlight_start":23,"highlight_end":23}],"label":null,"suggested_replacement":".to_string()","suggestion_applicability":"MaybeIncorrect","expansion":null}],"children":[],"rendered":null}],"rendered":"$DIR/json-bom-plus-crlf.rs:18:22: error[E0308]: mismatched types: expected `String`, found integer -"} -{"$message_type":"diagnostic","message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. - -Erroneous code examples: - -```compile_fail,E0308 -fn plus_one(x: i32) -> i32 { - x + 1 -} - -plus_one(\"Not a number\"); -// ^^^^^^^^^^^^^^ expected `i32`, found `&str` - -if \"Not a bool\" { -// ^^^^^^^^^^^^ expected `bool`, found `&str` -} - -let x: f32 = \"Not a float\"; -// --- ^^^^^^^^^^^^^ expected `f32`, found `&str` -// | -// expected due to this -``` - -This error occurs when an expression was used in a place where the compiler -expected an expression of a different type. It can occur in several cases, the -most common being when calling a function and passing an argument which has a -different type than the matching type in the function declaration. -"},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":765,"byte_end":766,"line_start":21,"line_end":21,"column_start":22,"column_end":23,"is_primary":true,"text":[{"text":" let s : String = 1","highlight_start":22,"highlight_end":23}],"label":"expected `String`, found integer","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":756,"byte_end":762,"line_start":21,"line_end":21,"column_start":13,"column_end":19,"is_primary":false,"text":[{"text":" let s : String = 1","highlight_start":13,"highlight_end":19}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[{"message":"try using a conversion method","code":null,"level":"help","spans":[{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":766,"byte_end":766,"line_start":21,"line_end":21,"column_start":23,"column_end":23,"is_primary":true,"text":[{"text":" let s : String = 1","highlight_start":23,"highlight_end":23}],"label":null,"suggested_replacement":".to_string()","suggestion_applicability":"MaybeIncorrect","expansion":null}],"children":[],"rendered":null}],"rendered":"$DIR/json-bom-plus-crlf.rs:21:22: error[E0308]: mismatched types: expected `String`, found integer -"} -{"$message_type":"diagnostic","message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. - -Erroneous code examples: - -```compile_fail,E0308 -fn plus_one(x: i32) -> i32 { - x + 1 -} - -plus_one(\"Not a number\"); -// ^^^^^^^^^^^^^^ expected `i32`, found `&str` - -if \"Not a bool\" { -// ^^^^^^^^^^^^ expected `bool`, found `&str` -} - -let x: f32 = \"Not a float\"; -// --- ^^^^^^^^^^^^^ expected `f32`, found `&str` -// | -// expected due to this -``` - -This error occurs when an expression was used in a place where the compiler -expected an expression of a different type. It can occur in several cases, the -most common being when calling a function and passing an argument which has a -different type than the matching type in the function declaration. -"},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":863,"byte_end":864,"line_start":26,"line_end":26,"column_start":1,"column_end":2,"is_primary":true,"text":[{"text":"1; // Error after the newline.","highlight_start":1,"highlight_end":2}],"label":"expected `String`, found integer","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":853,"byte_end":859,"line_start":25,"line_end":25,"column_start":13,"column_end":19,"is_primary":false,"text":[{"text":" let s : String =","highlight_start":13,"highlight_end":19}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[{"message":"try using a conversion method","code":null,"level":"help","spans":[{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":864,"byte_end":864,"line_start":26,"line_end":26,"column_start":2,"column_end":2,"is_primary":true,"text":[{"text":"1; // Error after the newline.","highlight_start":2,"highlight_end":2}],"label":null,"suggested_replacement":".to_string()","suggestion_applicability":"MaybeIncorrect","expansion":null}],"children":[],"rendered":null}],"rendered":"$DIR/json-bom-plus-crlf.rs:26:1: error[E0308]: mismatched types: expected `String`, found integer -"} -{"$message_type":"diagnostic","message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. - -Erroneous code examples: - -```compile_fail,E0308 -fn plus_one(x: i32) -> i32 { - x + 1 -} - -plus_one(\"Not a number\"); -// ^^^^^^^^^^^^^^ expected `i32`, found `&str` - -if \"Not a bool\" { -// ^^^^^^^^^^^^ expected `bool`, found `&str` -} - -let x: f32 = \"Not a float\"; -// --- ^^^^^^^^^^^^^ expected `f32`, found `&str` -// | -// expected due to this -``` - -This error occurs when an expression was used in a place where the compiler -expected an expression of a different type. It can occur in several cases, the -most common being when calling a function and passing an argument which has a -different type than the matching type in the function declaration. -"},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":952,"byte_end":960,"line_start":29,"line_end":30,"column_start":22,"column_end":6,"is_primary":true,"text":[{"text":" let s : String = (","highlight_start":22,"highlight_end":23},{"text":" ); // Error spanning the newline.","highlight_start":1,"highlight_end":6}],"label":"expected `String`, found `()`","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":943,"byte_end":949,"line_start":29,"line_end":29,"column_start":13,"column_end":19,"is_primary":false,"text":[{"text":" let s : String = (","highlight_start":13,"highlight_end":19}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[],"rendered":"$DIR/json-bom-plus-crlf.rs:29:22: error[E0308]: mismatched types: expected `String`, found `()` -"} -{"$message_type":"diagnostic","message":"aborting due to 4 previous errors","code":null,"level":"error","spans":[],"children":[],"rendered":"error: aborting due to 4 previous errors -"} diff --git a/tests/ui/lexer/lexer-crlf-line-endings-string-literal-doc-comment.rs b/tests/ui/lexer/lexer-crlf-line-endings-string-literal-doc-comment.rs deleted file mode 100644 index ee193a58ce1b2..0000000000000 --- a/tests/ui/lexer/lexer-crlf-line-endings-string-literal-doc-comment.rs +++ /dev/null @@ -1,38 +0,0 @@ -//@ run-pass -//@ reference: input.crlf -// ignore-tidy-cr -// ignore-tidy-cr (repeated again because of tidy bug) -// license is ignored because tidy can't handle the CRLF here properly. - -// N.B., this file needs CRLF line endings. The .gitattributes file in -// this directory should enforce it. - - -/// Doc comment that ends in CRLF -pub fn foo() {} - -/** Block doc comment that - * contains CRLF characters - */ -pub fn bar() {} - -fn main() { - let s = "string -literal"; - assert_eq!(s, "string\nliteral"); - - let s = "literal with \ - escaped newline"; - assert_eq!(s, "literal with escaped newline"); - - let s = r"string -literal"; - assert_eq!(s, "string\nliteral"); - let s = br"byte string -literal"; - assert_eq!(s, "byte string\nliteral".as_bytes()); - - // validate that our source file has CRLF endings - let source = include_str!("lexer-crlf-line-endings-string-literal-doc-comment.rs"); - assert!(source.contains("string\r\nliteral")); -} diff --git a/tests/ui/parser/trailing-carriage-return-in-string.rs b/tests/ui/parser/trailing-carriage-return-in-string.rs deleted file mode 100644 index 5d3c31944064a..0000000000000 --- a/tests/ui/parser/trailing-carriage-return-in-string.rs +++ /dev/null @@ -1,14 +0,0 @@ -// Issue #11669 - -// ignore-tidy-cr - -fn main() { - // \r\n - let ok = "This is \ - a test"; - // \r only - let bad = "This is \ a test"; - //~^ ERROR unknown character escape: `\r` - //~| HELP this is an isolated carriage return - -} From 1aa5e174b4b4c290d8baa99d0b0cc2d8d3f117a0 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Thu, 26 Jun 2025 08:40:09 +0800 Subject: [PATCH 22/23] Expand const-stabilized API links --- RELEASES.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/RELEASES.md b/RELEASES.md index 8a6bb214d2d52..27ac68252df03 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -69,8 +69,12 @@ These previously stable APIs are now stable in const contexts: - [`NonNull::replace`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.replace) - [`<*mut T>::replace`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.replace) -- [`std::ptr::swap_nonoverlapping`](https://github.com/rust-lang/rust/pull/137280) -- [`Cell::{replace, get, get_mut, from_mut, as_slice_of_cells}`](https://github.com/rust-lang/rust/pull/137928) +- [`std::ptr::swap_nonoverlapping`](https://doc.rust-lang.org/stable/std/ptr/fn.swap_nonoverlapping.html) +- [`Cell::replace`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.replace) +- [`Cell::get`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.get) +- [`Cell::get_mut`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.get_mut) +- [`Cell::from_mut`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.from_mut) +- [`Cell::as_slice_of_cells`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#method.as_slice_of_cells) From 59e1a3cbf589032f95eb1c9453025cca6eee2420 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 25 Jun 2025 16:11:28 +0000 Subject: [PATCH 23/23] Simplify IfCause --- compiler/rustc_hir_typeck/src/_match.rs | 99 +------------------ compiler/rustc_hir_typeck/src/coercion.rs | 46 ++++----- compiler/rustc_hir_typeck/src/expr.rs | 14 +-- compiler/rustc_infer/src/infer/mod.rs | 15 +-- compiler/rustc_middle/src/traits/mod.rs | 18 +--- .../src/error_reporting/infer/mod.rs | 61 +++++++++--- .../error_reporting/infer/note_and_explain.rs | 42 +++++--- .../src/error_reporting/infer/suggest.rs | 24 +++-- .../expr/if/if-else-chain-missing-else.stderr | 21 ++-- tests/ui/expr/if/if-else-type-mismatch.stderr | 17 ++-- tests/ui/inference/deref-suggestion.stderr | 27 +++-- tests/ui/suggestions/return-bindings.stderr | 16 +-- .../typeck/consider-borrowing-141810-1.stderr | 25 +++-- .../typeck/consider-borrowing-141810-2.stderr | 21 ++-- .../typeck/consider-borrowing-141810-3.stderr | 21 ++-- 15 files changed, 202 insertions(+), 265 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/_match.rs b/compiler/rustc_hir_typeck/src/_match.rs index 4ac260cb15f45..6467adb54dab0 100644 --- a/compiler/rustc_hir_typeck/src/_match.rs +++ b/compiler/rustc_hir_typeck/src/_match.rs @@ -1,12 +1,12 @@ use rustc_errors::{Applicability, Diag}; use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::def_id::LocalDefId; -use rustc_hir::{self as hir, ExprKind, PatKind}; +use rustc_hir::{self as hir, ExprKind, HirId, PatKind}; use rustc_hir_pretty::ty_to_string; use rustc_middle::ty::{self, Ty}; use rustc_span::Span; use rustc_trait_selection::traits::{ - IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode, + MatchExpressionArmCause, ObligationCause, ObligationCauseCode, }; use tracing::{debug, instrument}; @@ -414,105 +414,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub(crate) fn if_cause( &self, - span: Span, - cond_span: Span, - then_expr: &'tcx hir::Expr<'tcx>, + expr_id: HirId, else_expr: &'tcx hir::Expr<'tcx>, - then_ty: Ty<'tcx>, - else_ty: Ty<'tcx>, tail_defines_return_position_impl_trait: Option, ) -> ObligationCause<'tcx> { - let mut outer_span = if self.tcx.sess.source_map().is_multiline(span) { - // The `if`/`else` isn't in one line in the output, include some context to make it - // clear it is an if/else expression: - // ``` - // LL | let x = if true { - // | _____________- - // LL || 10i32 - // || ----- expected because of this - // LL || } else { - // LL || 10u32 - // || ^^^^^ expected `i32`, found `u32` - // LL || }; - // ||_____- `if` and `else` have incompatible types - // ``` - Some(span) - } else { - // The entire expression is in one line, only point at the arms - // ``` - // LL | let x = if true { 10i32 } else { 10u32 }; - // | ----- ^^^^^ expected `i32`, found `u32` - // | | - // | expected because of this - // ``` - None - }; - - let (error_sp, else_id) = if let ExprKind::Block(block, _) = &else_expr.kind { - let block = block.innermost_block(); - - // Avoid overlapping spans that aren't as readable: - // ``` - // 2 | let x = if true { - // | _____________- - // 3 | | 3 - // | | - expected because of this - // 4 | | } else { - // | |____________^ - // 5 | || - // 6 | || }; - // | || ^ - // | ||_____| - // | |______if and else have incompatible types - // | expected integer, found `()` - // ``` - // by not pointing at the entire expression: - // ``` - // 2 | let x = if true { - // | ------- `if` and `else` have incompatible types - // 3 | 3 - // | - expected because of this - // 4 | } else { - // | ____________^ - // 5 | | - // 6 | | }; - // | |_____^ expected integer, found `()` - // ``` - if block.expr.is_none() - && block.stmts.is_empty() - && let Some(outer_span) = &mut outer_span - && let Some(cond_span) = cond_span.find_ancestor_inside(*outer_span) - { - *outer_span = outer_span.with_hi(cond_span.hi()) - } - - (self.find_block_span(block), block.hir_id) - } else { - (else_expr.span, else_expr.hir_id) - }; - - let then_id = if let ExprKind::Block(block, _) = &then_expr.kind { - let block = block.innermost_block(); - // Exclude overlapping spans - if block.expr.is_none() && block.stmts.is_empty() { - outer_span = None; - } - block.hir_id - } else { - then_expr.hir_id - }; + let error_sp = self.find_block_span_from_hir_id(else_expr.hir_id); // Finally construct the cause: self.cause( error_sp, - ObligationCauseCode::IfExpression(Box::new(IfExpressionCause { - else_id, - then_id, - then_ty, - else_ty, - outer_span, - tail_defines_return_position_impl_trait, - })), + ObligationCauseCode::IfExpression { expr_id, tail_defines_return_position_impl_trait }, ) } diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 0ce0bc313c770..a936741526325 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -46,8 +46,7 @@ use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer; use rustc_infer::infer::relate::RelateResult; use rustc_infer::infer::{Coercion, DefineOpaqueTypes, InferOk, InferResult}; use rustc_infer::traits::{ - IfExpressionCause, ImplSource, MatchExpressionArmCause, Obligation, PredicateObligation, - PredicateObligations, SelectionError, + MatchExpressionArmCause, Obligation, PredicateObligation, PredicateObligations, SelectionError, }; use rustc_middle::span_bug; use rustc_middle::ty::adjustment::{ @@ -59,7 +58,7 @@ use rustc_span::{BytePos, DUMMY_SP, DesugaringKind, Span}; use rustc_trait_selection::infer::InferCtxtExt as _; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; use rustc_trait_selection::traits::{ - self, NormalizeExt, ObligationCause, ObligationCauseCode, ObligationCtxt, + self, ImplSource, NormalizeExt, ObligationCause, ObligationCauseCode, ObligationCtxt, }; use smallvec::{SmallVec, smallvec}; use tracing::{debug, instrument}; @@ -1719,14 +1718,17 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { ); } } - ObligationCauseCode::IfExpression(box IfExpressionCause { - then_id, - else_id, - then_ty, - else_ty, + ObligationCauseCode::IfExpression { + expr_id, tail_defines_return_position_impl_trait: Some(rpit_def_id), - .. - }) => { + } => { + let hir::Node::Expr(hir::Expr { + kind: hir::ExprKind::If(_, then_expr, Some(else_expr)), + .. + }) = fcx.tcx.hir_node(expr_id) + else { + unreachable!(); + }; err = fcx.err_ctxt().report_mismatched_types( cause, fcx.param_env, @@ -1734,24 +1736,12 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { found, coercion_error, ); - let then_span = fcx.find_block_span_from_hir_id(then_id); - let else_span = fcx.find_block_span_from_hir_id(else_id); - // don't suggest wrapping either blocks in `if .. {} else {}` - let is_empty_arm = |id| { - let hir::Node::Block(blk) = fcx.tcx.hir_node(id) else { - return false; - }; - if blk.expr.is_some() || !blk.stmts.is_empty() { - return false; - } - let Some((_, hir::Node::Expr(expr))) = - fcx.tcx.hir_parent_iter(id).nth(1) - else { - return false; - }; - matches!(expr.kind, hir::ExprKind::If(..)) - }; - if !is_empty_arm(then_id) && !is_empty_arm(else_id) { + let then_span = fcx.find_block_span_from_hir_id(then_expr.hir_id); + let else_span = fcx.find_block_span_from_hir_id(else_expr.hir_id); + // Don't suggest wrapping whole block in `Box::new`. + if then_span != then_expr.span && else_span != else_expr.span { + let then_ty = fcx.typeck_results.borrow().expr_ty(then_expr); + let else_ty = fcx.typeck_results.borrow().expr_ty(else_expr); self.suggest_boxing_tail_for_return_position_impl_trait( fcx, &mut err, diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 2bc9dadb6653b..3a0d57dca1273 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -583,7 +583,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ascribed_ty } ExprKind::If(cond, then_expr, opt_else_expr) => { - self.check_expr_if(cond, then_expr, opt_else_expr, expr.span, expected) + self.check_expr_if(expr.hir_id, cond, then_expr, opt_else_expr, expr.span, expected) } ExprKind::DropTemps(e) => self.check_expr_with_expectation(e, expected), ExprKind::Array(args) => self.check_expr_array(args, expected, expr), @@ -1343,6 +1343,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // or 'if-else' expression. fn check_expr_if( &self, + expr_id: HirId, cond_expr: &'tcx hir::Expr<'tcx>, then_expr: &'tcx hir::Expr<'tcx>, opt_else_expr: Option<&'tcx hir::Expr<'tcx>>, @@ -1382,15 +1383,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let tail_defines_return_position_impl_trait = self.return_position_impl_trait_from_match_expectation(orig_expected); - let if_cause = self.if_cause( - sp, - cond_expr.span, - then_expr, - else_expr, - then_ty, - else_ty, - tail_defines_return_position_impl_trait, - ); + let if_cause = + self.if_cause(expr_id, else_expr, tail_defines_return_position_impl_trait); coerce.coerce(self, &if_cause, else_expr, else_ty); diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index e9b58eb959bda..491efba9eb020 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -35,7 +35,7 @@ use rustc_middle::ty::{ PseudoCanonicalInput, Term, TermKind, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypingEnv, TypingMode, fold_regions, }; -use rustc_span::{Span, Symbol}; +use rustc_span::{DUMMY_SP, Span, Symbol}; use snapshot::undo_log::InferCtxtUndoLogs; use tracing::{debug, instrument}; use type_variable::TypeVariableOrigin; @@ -1557,15 +1557,16 @@ impl<'tcx> InferCtxt<'tcx> { } } - /// Given a [`hir::HirId`] for a block, get the span of its last expression - /// or statement, peeling off any inner blocks. + /// Given a [`hir::HirId`] for a block (or an expr of a block), get the span + /// of its last expression or statement, peeling off any inner blocks. pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span { match self.tcx.hir_node(hir_id) { - hir::Node::Block(blk) => self.find_block_span(blk), - // The parser was in a weird state if either of these happen, but - // it's better not to panic. + hir::Node::Block(blk) + | hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(blk, _), .. }) => { + self.find_block_span(blk) + } hir::Node::Expr(e) => e.span, - _ => rustc_span::DUMMY_SP, + _ => DUMMY_SP, } } } diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index d877bd5c626ce..1a5a9765ce7a4 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -332,7 +332,11 @@ pub enum ObligationCauseCode<'tcx> { }, /// Computing common supertype in an if expression - IfExpression(Box>), + IfExpression { + expr_id: HirId, + // Is the expectation of this match expression an RPIT? + tail_defines_return_position_impl_trait: Option, + }, /// Computing common supertype of an if expression with no else counter-part IfExpressionWithNoElse, @@ -550,18 +554,6 @@ pub struct PatternOriginExpr { pub peeled_prefix_suggestion_parentheses: bool, } -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -#[derive(TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)] -pub struct IfExpressionCause<'tcx> { - pub then_id: HirId, - pub else_id: HirId, - pub then_ty: Ty<'tcx>, - pub else_ty: Ty<'tcx>, - pub outer_span: Option, - // Is the expectation of this match expression an RPIT? - pub tail_defines_return_position_impl_trait: Option, -} - #[derive(Clone, Debug, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)] #[derive(TypeVisitable, TypeFoldable)] pub struct DerivedCause<'tcx> { diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs index 2c16672d78641..bc464b099e291 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs @@ -82,9 +82,7 @@ use crate::infer; use crate::infer::relate::{self, RelateResult, TypeRelation}; use crate::infer::{InferCtxt, InferCtxtExt as _, TypeTrace, ValuePairs}; use crate::solve::deeply_normalize_for_diagnostics; -use crate::traits::{ - IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode, -}; +use crate::traits::{MatchExpressionArmCause, ObligationCause, ObligationCauseCode}; mod note_and_explain; mod suggest; @@ -613,18 +611,28 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } } }, - ObligationCauseCode::IfExpression(box IfExpressionCause { - then_id, - else_id, - then_ty, - else_ty, - outer_span, - .. - }) => { - let then_span = self.find_block_span_from_hir_id(then_id); - let else_span = self.find_block_span_from_hir_id(else_id); - if let hir::Node::Expr(e) = self.tcx.hir_node(else_id) - && let hir::ExprKind::If(_cond, _then, None) = e.kind + ObligationCauseCode::IfExpression { expr_id, .. } => { + let hir::Node::Expr(&hir::Expr { + kind: hir::ExprKind::If(cond_expr, then_expr, Some(else_expr)), + span: expr_span, + .. + }) = self.tcx.hir_node(expr_id) + else { + return; + }; + let then_span = self.find_block_span_from_hir_id(then_expr.hir_id); + let then_ty = self + .typeck_results + .as_ref() + .expect("if expression only expected inside FnCtxt") + .expr_ty(then_expr); + let else_span = self.find_block_span_from_hir_id(else_expr.hir_id); + let else_ty = self + .typeck_results + .as_ref() + .expect("if expression only expected inside FnCtxt") + .expr_ty(else_expr); + if let hir::ExprKind::If(_cond, _then, None) = else_expr.kind && else_ty.is_unit() { // Account for `let x = if a { 1 } else if b { 2 };` @@ -632,9 +640,32 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { err.note("consider adding an `else` block that evaluates to the expected type"); } err.span_label(then_span, "expected because of this"); + + let outer_span = if self.tcx.sess.source_map().is_multiline(expr_span) { + if then_span.hi() == expr_span.hi() || else_span.hi() == expr_span.hi() { + // Point at condition only if either block has the same end point as + // the whole expression, since that'll cause awkward overlapping spans. + Some(expr_span.shrink_to_lo().to(cond_expr.peel_drop_temps().span)) + } else { + Some(expr_span) + } + } else { + None + }; if let Some(sp) = outer_span { err.span_label(sp, "`if` and `else` have incompatible types"); } + + let then_id = if let hir::ExprKind::Block(then_blk, _) = then_expr.kind { + then_blk.hir_id + } else { + then_expr.hir_id + }; + let else_id = if let hir::ExprKind::Block(else_blk, _) = else_expr.kind { + else_blk.hir_id + } else { + else_expr.hir_id + }; if let Some(subdiag) = self.suggest_remove_semi_or_return_binding( Some(then_id), then_ty, diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs index be508c8cee13e..0a4a9144c9407 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs @@ -420,19 +420,33 @@ impl Trait for X { } // If two if arms can be coerced to a trait object, provide a structured // suggestion. - let ObligationCauseCode::IfExpression(cause) = cause.code() else { + let ObligationCauseCode::IfExpression { expr_id, .. } = cause.code() else { return; }; - let hir::Node::Block(blk) = self.tcx.hir_node(cause.then_id) else { - return; - }; - let Some(then) = blk.expr else { - return; - }; - let hir::Node::Block(blk) = self.tcx.hir_node(cause.else_id) else { - return; - }; - let Some(else_) = blk.expr else { + let hir::Node::Expr(&hir::Expr { + kind: + hir::ExprKind::If( + _, + &hir::Expr { + kind: + hir::ExprKind::Block( + &hir::Block { expr: Some(then), .. }, + _, + ), + .. + }, + Some(&hir::Expr { + kind: + hir::ExprKind::Block( + &hir::Block { expr: Some(else_), .. }, + _, + ), + .. + }), + ), + .. + }) = self.tcx.hir_node(*expr_id) + else { return; }; let expected = match values.found.kind() { @@ -486,8 +500,10 @@ impl Trait for X { } } (ty::Adt(_, _), ty::Adt(def, args)) - if let ObligationCauseCode::IfExpression(cause) = cause.code() - && let hir::Node::Block(blk) = self.tcx.hir_node(cause.then_id) + if let ObligationCauseCode::IfExpression { expr_id, .. } = cause.code() + && let hir::Node::Expr(if_expr) = self.tcx.hir_node(*expr_id) + && let hir::ExprKind::If(_, then_expr, _) = if_expr.kind + && let hir::ExprKind::Block(blk, _) = then_expr.kind && let Some(then) = blk.expr && def.is_box() && let boxed_ty = args.type_at(0) diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs index 3804c13acce8e..c0daf08ce079f 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs @@ -8,9 +8,7 @@ use rustc_errors::{Applicability, Diag}; use rustc_hir as hir; use rustc_hir::def::Res; use rustc_hir::{MatchSource, Node}; -use rustc_middle::traits::{ - IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode, -}; +use rustc_middle::traits::{MatchExpressionArmCause, ObligationCause, ObligationCauseCode}; use rustc_middle::ty::error::TypeError; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::{self as ty, GenericArgKind, IsSuggestable, Ty, TypeVisitableExt}; @@ -196,8 +194,14 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { (Some(exp), Some(found)) if self.same_type_modulo_infer(exp, found) => match cause .code() { - ObligationCauseCode::IfExpression(box IfExpressionCause { then_id, .. }) => { - let then_span = self.find_block_span_from_hir_id(*then_id); + ObligationCauseCode::IfExpression { expr_id, .. } => { + let hir::Node::Expr(hir::Expr { + kind: hir::ExprKind::If(_, then_expr, _), .. + }) = self.tcx.hir_node(*expr_id) + else { + return; + }; + let then_span = self.find_block_span_from_hir_id(then_expr.hir_id); Some(ConsiderAddingAwait::BothFuturesSugg { first: then_span.shrink_to_hi(), second: exp_span.shrink_to_hi(), @@ -232,8 +236,14 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { span: then_span.shrink_to_hi(), }) } - ObligationCauseCode::IfExpression(box IfExpressionCause { then_id, .. }) => { - let then_span = self.find_block_span_from_hir_id(*then_id); + ObligationCauseCode::IfExpression { expr_id, .. } => { + let hir::Node::Expr(hir::Expr { + kind: hir::ExprKind::If(_, then_expr, _), .. + }) = self.tcx.hir_node(*expr_id) + else { + return; + }; + let then_span = self.find_block_span_from_hir_id(then_expr.hir_id); Some(ConsiderAddingAwait::FutureSugg { span: then_span.shrink_to_hi() }) } ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause { diff --git a/tests/ui/expr/if/if-else-chain-missing-else.stderr b/tests/ui/expr/if/if-else-chain-missing-else.stderr index 374c4927e3003..6c437120d391d 100644 --- a/tests/ui/expr/if/if-else-chain-missing-else.stderr +++ b/tests/ui/expr/if/if-else-chain-missing-else.stderr @@ -1,18 +1,15 @@ error[E0308]: `if` and `else` have incompatible types --> $DIR/if-else-chain-missing-else.rs:12:12 | -LL | let x = if let Ok(x) = res { - | ______________- -LL | | x - | | - expected because of this -LL | | } else if let Err(e) = res { - | | ____________^ -LL | || return Err(e); -LL | || }; - | || ^ - | ||_____| - | |_____`if` and `else` have incompatible types - | expected `i32`, found `()` +LL | let x = if let Ok(x) = res { + | ------------------ `if` and `else` have incompatible types +LL | x + | - expected because of this +LL | } else if let Err(e) = res { + | ____________^ +LL | | return Err(e); +LL | | }; + | |_____^ expected `i32`, found `()` | = note: `if` expressions without `else` evaluate to `()` = note: consider adding an `else` block that evaluates to the expected type diff --git a/tests/ui/expr/if/if-else-type-mismatch.stderr b/tests/ui/expr/if/if-else-type-mismatch.stderr index 1cf94c98800bb..56181267a3189 100644 --- a/tests/ui/expr/if/if-else-type-mismatch.stderr +++ b/tests/ui/expr/if/if-else-type-mismatch.stderr @@ -92,13 +92,16 @@ LL | | }; error[E0308]: `if` and `else` have incompatible types --> $DIR/if-else-type-mismatch.rs:37:9 | -LL | let _ = if true { - | _____________________- -LL | | -LL | | } else { - | |_____- expected because of this -LL | 11u32 - | ^^^^^ expected `()`, found `u32` +LL | let _ = if true { + | ______________- - + | | _____________________| +LL | || +LL | || } else { + | ||_____- expected because of this +LL | | 11u32 + | | ^^^^^ expected `()`, found `u32` +LL | | }; + | |______- `if` and `else` have incompatible types error[E0308]: `if` and `else` have incompatible types --> $DIR/if-else-type-mismatch.rs:42:12 diff --git a/tests/ui/inference/deref-suggestion.stderr b/tests/ui/inference/deref-suggestion.stderr index 096989db0b4e8..8ccd28198afc4 100644 --- a/tests/ui/inference/deref-suggestion.stderr +++ b/tests/ui/inference/deref-suggestion.stderr @@ -164,21 +164,18 @@ LL | *b error[E0308]: `if` and `else` have incompatible types --> $DIR/deref-suggestion.rs:69:12 | -LL | let val = if true { - | ________________- -LL | | *a - | | -- expected because of this -LL | | } else if true { - | | ____________^ -LL | || -LL | || b -LL | || } else { -LL | || &0 -LL | || }; - | || ^ - | ||_____| - | |_____`if` and `else` have incompatible types - | expected `i32`, found `&{integer}` +LL | let val = if true { + | ------- `if` and `else` have incompatible types +LL | *a + | -- expected because of this +LL | } else if true { + | ____________^ +LL | | +LL | | b +LL | | } else { +LL | | &0 +LL | | }; + | |_____^ expected `i32`, found `&{integer}` error[E0308]: mismatched types --> $DIR/deref-suggestion.rs:81:15 diff --git a/tests/ui/suggestions/return-bindings.stderr b/tests/ui/suggestions/return-bindings.stderr index 8e396d17dc072..651998043e108 100644 --- a/tests/ui/suggestions/return-bindings.stderr +++ b/tests/ui/suggestions/return-bindings.stderr @@ -62,12 +62,16 @@ LL ~ error[E0308]: `if` and `else` have incompatible types --> $DIR/return-bindings.rs:30:9 | -LL | let s = if let Some(s) = opt_str { - | ______________________________________- -LL | | } else { - | |_____- expected because of this -LL | String::new() - | ^^^^^^^^^^^^^ expected `()`, found `String` +LL | let s = if let Some(s) = opt_str { + | ______________- - + | | ______________________________________| +LL | || } else { + | ||_____- expected because of this +LL | | String::new() + | | ^^^^^^^^^^^^^ expected `()`, found `String` +LL | | +LL | | }; + | |______- `if` and `else` have incompatible types | help: consider returning the local binding `s` | diff --git a/tests/ui/typeck/consider-borrowing-141810-1.stderr b/tests/ui/typeck/consider-borrowing-141810-1.stderr index 9291721ac7123..35ca6793eee0d 100644 --- a/tests/ui/typeck/consider-borrowing-141810-1.stderr +++ b/tests/ui/typeck/consider-borrowing-141810-1.stderr @@ -1,20 +1,17 @@ error[E0308]: `if` and `else` have incompatible types --> $DIR/consider-borrowing-141810-1.rs:4:12 | -LL | let x = if true { - | ______________- -LL | | &true - | | ----- expected because of this -LL | | } else if false { - | | ____________^ -LL | || true -LL | || } else { -LL | || true -LL | || }; - | || ^ - | ||_____| - | |_____`if` and `else` have incompatible types - | expected `&bool`, found `bool` +LL | let x = if true { + | ------- `if` and `else` have incompatible types +LL | &true + | ----- expected because of this +LL | } else if false { + | ____________^ +LL | | true +LL | | } else { +LL | | true +LL | | }; + | |_____^ expected `&bool`, found `bool` | help: consider borrowing here | diff --git a/tests/ui/typeck/consider-borrowing-141810-2.stderr b/tests/ui/typeck/consider-borrowing-141810-2.stderr index dd229897283b4..44ecb5a4a945a 100644 --- a/tests/ui/typeck/consider-borrowing-141810-2.stderr +++ b/tests/ui/typeck/consider-borrowing-141810-2.stderr @@ -1,18 +1,15 @@ error[E0308]: `if` and `else` have incompatible types --> $DIR/consider-borrowing-141810-2.rs:4:12 | -LL | let x = if true { - | ______________- -LL | | &() - | | --- expected because of this -LL | | } else if false { - | | ____________^ -LL | || } else { -LL | || }; - | || ^ - | ||_____| - | |_____`if` and `else` have incompatible types - | expected `&()`, found `()` +LL | let x = if true { + | ------- `if` and `else` have incompatible types +LL | &() + | --- expected because of this +LL | } else if false { + | ____________^ +LL | | } else { +LL | | }; + | |_____^ expected `&()`, found `()` error: aborting due to 1 previous error diff --git a/tests/ui/typeck/consider-borrowing-141810-3.stderr b/tests/ui/typeck/consider-borrowing-141810-3.stderr index 0b0c5f191a0d3..3adf8ba1a8924 100644 --- a/tests/ui/typeck/consider-borrowing-141810-3.stderr +++ b/tests/ui/typeck/consider-borrowing-141810-3.stderr @@ -1,18 +1,15 @@ error[E0308]: `if` and `else` have incompatible types --> $DIR/consider-borrowing-141810-3.rs:4:12 | -LL | let x = if true { - | ______________- -LL | | &() - | | --- expected because of this -LL | | } else if false { - | | ____________^ -LL | || -LL | || }; - | || ^ - | ||_____| - | |_____`if` and `else` have incompatible types - | expected `&()`, found `()` +LL | let x = if true { + | ------- `if` and `else` have incompatible types +LL | &() + | --- expected because of this +LL | } else if false { + | ____________^ +LL | | +LL | | }; + | |_____^ expected `&()`, found `()` | = note: `if` expressions without `else` evaluate to `()` = note: consider adding an `else` block that evaluates to the expected type