// be added explicitly if necessary, see the error in `fn link_rlib`) compiled // as an executable due to `--test`. Use whole-archive implicitly, like before // the introduction of native lib modifiers. <del> || (bundle != Some(false) && sess.opts.test) </del> <ins> || (whole_archive == None && bundle != Some(false) && sess.opts.test) </ins> { cmd.link_whole_staticlib( name,


# ignore-cross-compile -- compiling C++ code does not work well when cross-compiling <del> # This test case makes sure that native libraries are linked with --whole-archive semantics # when the `-bundle,+whole-archive` modifiers are applied to them. </del> <ins> # This test case makes sure that native libraries are linked with appropriate semantics # when the `[+-]bundle,[+-]whole-archive` modifiers are applied to them. </ins> # # The test works by checking that the resulting executables produce the expected output, # part of which is emitted by otherwise unreferenced C code. If +whole-archive didn't work


-include ../../run-make-fulldeps/tools.mk <del> all: $(TMPDIR)/$(call BIN,directly_linked) $(TMPDIR)/$(call BIN,indirectly_linked) $(TMPDIR)/$(call BIN,indirectly_linked_via_attr) </del> <ins> all: $(TMPDIR)/$(call BIN,directly_linked)  $(TMPDIR)/$(call BIN,directly_linked_test_plus_whole_archive)  $(TMPDIR)/$(call BIN,directly_linked_test_minus_whole_archive)  $(TMPDIR)/$(call BIN,indirectly_linked)  $(TMPDIR)/$(call BIN,indirectly_linked_via_attr) </ins> $(call RUN,directly_linked) | $(CGREP) 'static-initializer.directly_linked.' <ins> $(call RUN,directly_linked_test_plus_whole_archive) --nocapture | $(CGREP) 'static-initializer.' $(call RUN,directly_linked_test_minus_whole_archive) --nocapture | $(CGREP) -v 'static-initializer.' </ins> $(call RUN,indirectly_linked) | $(CGREP) 'static-initializer.indirectly_linked.' $(call RUN,indirectly_linked_via_attr) | $(CGREP) 'static-initializer.native_lib_in_src.'


$(TMPDIR)/$(call BIN,directly_linked): $(call NATIVE_STATICLIB,c_static_lib_with_constructor) $(RUSTC) directly_linked.rs -l static:+whole-archive=c_static_lib_with_constructor <ins> # Native lib linked into test executable, +whole-archive $(TMPDIR)/$(call BIN,directly_linked_test_plus_whole_archive): $(call NATIVE_STATICLIB,c_static_lib_with_constructor) $(RUSTC) directly_linked_test_plus_whole_archive.rs --test -l static:+whole-archive=c_static_lib_with_constructor # Native lib linked into test executable, -whole-archive $(TMPDIR)/$(call BIN,directly_linked_test_minus_whole_archive): $(call NATIVE_STATICLIB,c_static_lib_with_constructor) $(RUSTC) directly_linked_test_minus_whole_archive.rs --test -l static:-whole-archive=c_static_lib_with_constructor </ins> # Native lib linked into RLIB via `-l static:-bundle,+whole-archive`, RLIB linked into executable $(TMPDIR)/$(call BIN,indirectly_linked): $(TMPDIR)/librlib_with_cmdline_native_lib.rlib $(RUSTC) indirectly_linked.rs


<ins> use std::io::Write; #[test] fn test_thing() { print!("ran the test"); std::io::stdout().flush().unwrap(); } </ins>


} } Err(coercion_error) => { <ins> // Mark that we've failed to coerce the types here to suppress // any superfluous errors we might encounter while trying to // emit or provide suggestions on how to fix the initial error. fcx.set_tainted_by_errors(); </ins> let (expected, found) = if label_expression_as_expected { // In the case where this is a "forced unit", like // `break`, we want to call the `()` "expected"


<ins> #![recursion_limit = "5"] // To reduce noise //expect incompatible type error when ambiguous traits are in scope //and not an overflow error on the span in the main function. struct Ratio<T>(T); pub trait Pow { fn pow(self) -> Self; } impl<'a, T> Pow for &'a Ratio<T> where &'a T: Pow, { fn pow(self) -> Self { self } } fn downcast<'a, W: ?Sized>() -> std::io::Result<&'a W> { todo!() } struct Other; fn main() -> std::io::Result<()> { let other: Other = downcast()?;//~ERROR 28:24: 28:35: `?` operator has incompatible types Ok(()) } </ins>


<ins> error[E0308]: `?` operator has incompatible types --> $DIR/issue-100246.rs:28:24 | LL |     let other: Other = downcast()?; |                        ^^^^^^^^^^^ expected struct `Other`, found reference | = note: `?` operator cannot convert from `&_` to `Other` = note: expected struct `Other` found reference `&_` error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. </ins>


} #[cfg(not(no_global_oom_handling))] <ins> #[stable(feature = "vec_from_array_ref", since = "CURRENT_RUSTC_VERSION")] impl<T: Clone, const N: usize> From<&[T; N]> for Vec<T> { /// Allocate a `Vec<T>` and fill it by cloning `s`'s items. /// /// # Examples /// /// ``` /// assert_eq!(Vec::from(&[1, 2, 3]), vec![1, 2, 3]); /// ``` fn from(s: &[T; N]) -> Vec<T> { Self::from(s.as_slice()) } } #[cfg(not(no_global_oom_handling))] #[stable(feature = "vec_from_array_ref", since = "CURRENT_RUSTC_VERSION")] impl<T: Clone, const N: usize> From<&mut [T; N]> for Vec<T> { /// Allocate a `Vec<T>` and fill it by cloning `s`'s items. /// /// # Examples /// /// ``` /// assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]); /// ``` fn from(s: &mut [T; N]) -> Vec<T> { Self::from(s.as_mut_slice()) } } #[cfg(not(no_global_oom_handling))] </ins> #[stable(feature = "vec_from_array", since = "1.44.0")] impl<T, const N: usize> From<[T; N]> for Vec<T> { /// Allocate a `Vec<T>` and move `s`'s items into it.


// Ensure all ZSTs have been freed. assert!(alloc.state.borrow().0.is_empty()); } <ins> #[test] fn test_vec_from_array_ref() { assert_eq!(Vec::from(&[1, 2, 3]), vec![1, 2, 3]); } #[test] fn test_vec_from_array_mut_ref() { assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]); } </ins>


let ai = &self.expected_indices; let ii = &self.provided_indices; <ins> // Issue: 100478, when we end the iteration, // `next_unmatched_idx` will point to the index of the first unmatched let mut next_unmatched_idx = 0; </ins> for i in 0..cmp::max(ai.len(), ii.len()) { <del> // If we eliminate the last row, any left-over inputs are considered missing </del> <ins> // If we eliminate the last row, any left-over arguments are considered missing </ins> if i >= mat.len() { <del> return Some(Issue::Missing(i)); </del> <ins> return Some(Issue::Missing(next_unmatched_idx)); </ins> } <del> // If we eliminate the last column, any left-over arguments are extra </del> <ins> // If we eliminate the last column, any left-over inputs are extra </ins> if mat[i].len() == 0 { <del> return Some(Issue::Extra(i)); </del> <ins> return Some(Issue::Extra(next_unmatched_idx)); </ins> } // Make sure we don't pass the bounds of our matrix


let is_input = i < ii.len(); if is_arg && is_input && matches!(mat[i][i], Compatibility::Compatible) { // This is a satisfied input, so move along <ins> next_unmatched_idx += 1; </ins> continue; }


if is_input { for j in 0..ai.len() { // If we find at least one argument that could satisfy this input <del> // this argument isn't useless </del> <ins> // this input isn't useless </ins> if matches!(mat[i][j], Compatibility::Compatible) { useless = false; break;


if matches!(c, Compatibility::Compatible) { Some(i) } else { None } }) .collect(); <del> if compat.len() != 1 { // this could go into multiple slots, don't bother exploring both </del> <ins> if compat.len() < 1 { // try to find a cycle even when this could go into multiple slots, see #101097 </ins> is_cycle = false; break; }


} while !self.provided_indices.is_empty() || !self.expected_indices.is_empty() { <del> match self.find_issue() { </del> <ins> let res = self.find_issue(); match res { </ins> Some(Issue::Invalid(idx)) => { let compatibility = self.compatibility_matrix[idx][idx].clone(); let input_idx = self.provided_indices[idx];


None => { // We didn't find any issues, so we need to push the algorithm forward // First, eliminate any arguments that currently satisfy their inputs <del> for (inp, arg) in self.eliminate_satisfied() { </del> <ins> let eliminated = self.eliminate_satisfied(); assert!(!eliminated.is_empty(), "didn't eliminated any indice in this round"); for (inp, arg) in eliminated { </ins> matched_inputs[arg] = Some(inp); } }


<ins> use std::sync::Arc; macro_rules! GenT { ($name:tt) => { #[derive(Default, Debug)] struct $name { #[allow(unused)] val: i32, } impl $name { #[allow(unused)] fn new(val: i32) -> Self { $name { val } } } }; } GenT!(T1); GenT!(T2); GenT!(T3); GenT!(T4); GenT!(T5); GenT!(T6); GenT!(T7); GenT!(T8); #[allow(unused)] fn foo(p1: T1, p2: Arc<T2>, p3: T3, p4: Arc<T4>, p5: T5, p6: T6, p7: T7, p8: Arc<T8>) {} fn three_diff(_a: T1, _b: T2, _c: T3) {} fn four_shuffle(_a: T1, _b: T2, _c: T3, _d: T4) {} fn main() { three_diff(T2::new(0)); //~ ERROR this function takes four_shuffle(T3::default(), T4::default(), T1::default(), T2::default()); //~ ERROR 35:5: 35:17: arguments to this function are incorrect [E0308] four_shuffle(T3::default(), T2::default(), T1::default(), T3::default()); //~ ERROR 36:5: 36:17: arguments to this function are incorrect [E0308] let p1 = T1::new(0); let p2 = Arc::new(T2::new(0)); let p3 = T3::new(0); let p4 = Arc::new(T4::new(1)); let p5 = T5::new(0); let p6 = T6::new(0); let p7 = T7::new(0); let p8 = Arc::default(); foo( //~^ 47:5: 47:8: this function takes 8 arguments but 7 arguments were supplied [E0061] p1, //p2, p3, p4, p5, p6, p7, p8, ); } </ins>


<ins> error[E0061]: this function takes 3 arguments but 1 argument was supplied --> $DIR/issue-100478.rs:34:5 | LL |     three_diff(T2::new(0)); |     ^^^^^^^^^^------------ |               || |               |an argument of type `T1` is missing |               an argument of type `T3` is missing | note: function defined here --> $DIR/issue-100478.rs:30:4 | LL | fn three_diff(_a: T1, _b: T2, _c: T3) {} |    ^^^^^^^^^^ ------  ------  ------ help: provide the arguments | LL |     three_diff(/* T1 */, T2::new(0), /* T3 */); |               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error[E0308]: arguments to this function are incorrect --> $DIR/issue-100478.rs:35:5 | LL |     four_shuffle(T3::default(), T4::default(), T1::default(), T2::default()); |     ^^^^^^^^^^^^ -------------  -------------  -------------  ------------- expected `T4`, found `T2` |                  |              |              | |                  |              |              expected `T3`, found `T1` |                  |              expected `T2`, found `T4` |                  expected `T1`, found `T3` | note: function defined here --> $DIR/issue-100478.rs:31:4 | LL | fn four_shuffle(_a: T1, _b: T2, _c: T3, _d: T4) {} |    ^^^^^^^^^^^^ ------  ------  ------  ------ help: did you mean | LL |     four_shuffle(T1::default(), T2::default(), T3::default(), T4::default()); |                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error[E0308]: arguments to this function are incorrect --> $DIR/issue-100478.rs:36:5 | LL |     four_shuffle(T3::default(), T2::default(), T1::default(), T3::default()); |     ^^^^^^^^^^^^ -------------                 -------------  ------------- expected struct `T4`, found struct `T3` |                  |                             | |                  |                             expected `T3`, found `T1` |                  expected `T1`, found `T3` | note: function defined here --> $DIR/issue-100478.rs:31:4 | LL | fn four_shuffle(_a: T1, _b: T2, _c: T3, _d: T4) {} |    ^^^^^^^^^^^^ ------  ------  ------  ------ help: swap these arguments | LL |     four_shuffle(T1::default(), T2::default(), T3::default(), /* T4 */); |                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error[E0061]: this function takes 8 arguments but 7 arguments were supplied --> $DIR/issue-100478.rs:47:5 | LL |     foo( |     ^^^ ... LL |         p3, p4, p5, p6, p7, p8, |         -- an argument of type `Arc<T2>` is missing | note: function defined here --> $DIR/issue-100478.rs:29:4 | LL | fn foo(p1: T1, p2: Arc<T2>, p3: T3, p4: Arc<T4>, p5: T5, p6: T6, p7: T7, p8: Arc<T8>) {} |    ^^^ ------  -----------  ------  -----------  ------  ------  ------  ----------- help: provide the argument | LL |     foo(p1, /* Arc<T2> */, p3, p4, p5, p6, p7, p8); |        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error: aborting due to 4 previous errors Some errors have detailed explanations: E0061, E0308. For more information about an error, try `rustc --explain E0061`. </ins>


<ins> struct A; struct B; struct C; struct D; fn f( a1: A, a2: A, b1: B, b2: B, c1: C, c2: C, ) {} fn main() { f(C, A, A, A, B, B, C); //~ ERROR this function takes 6 arguments but 7 arguments were supplied [E0061] f(C, C, A, A, B, B);  //~ ERROR arguments to this function are incorrect [E0308] f(A, A, D, D, B, B);  //~ arguments to this function are incorrect [E0308] f(C, C, B, B, A, A);  //~ arguments to this function are incorrect [E0308] f(C, C, A, B, A, A);  //~ arguments to this function are incorrect [E0308] } </ins>


<ins> error[E0061]: this function takes 6 arguments but 7 arguments were supplied --> $DIR/issue-101097.rs:16:5 | LL |     f(C, A, A, A, B, B, C); |     ^ -     -  -  - expected `C`, found `B` |       |     |  | |       |     |  argument of type `A` unexpected |       |     expected `B`, found `A` |       expected `A`, found `C` | note: function defined here --> $DIR/issue-101097.rs:6:4 | LL | fn f( |    ^ LL |     a1: A, |     ----- LL |     a2: A, |     ----- LL |     b1: B, |     ----- LL |     b2: B, |     ----- LL |     c1: C, |     ----- LL |     c2: C, |     ----- help: did you mean | LL |     f(A, A, B, B, C, C); |      ~~~~~~~~~~~~~~~~~~ error[E0308]: arguments to this function are incorrect --> $DIR/issue-101097.rs:17:5 | LL |     f(C, C, A, A, B, B); |     ^ | note: function defined here --> $DIR/issue-101097.rs:6:4 | LL | fn f( |    ^ LL |     a1: A, |     ----- LL |     a2: A, |     ----- LL |     b1: B, |     ----- LL |     b2: B, |     ----- LL |     c1: C, |     ----- LL |     c2: C, |     ----- help: did you mean | LL |     f(A, A, B, B, C, C); |      ~~~~~~~~~~~~~~~~~~ error[E0308]: arguments to this function are incorrect --> $DIR/issue-101097.rs:18:5 | LL |     f(A, A, D, D, B, B); |     ^       -  -  ---- two arguments of type `C` and `C` are missing |             |  | |             |  argument of type `D` unexpected |             argument of type `D` unexpected | note: function defined here --> $DIR/issue-101097.rs:6:4 | LL | fn f( |    ^ LL |     a1: A, |     ----- LL |     a2: A, |     ----- LL |     b1: B, |     ----- LL |     b2: B, |     ----- LL |     c1: C, |     ----- LL |     c2: C, |     ----- help: did you mean | LL |     f(A, A, B, B, /* C */, /* C */); |      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error[E0308]: arguments to this function are incorrect --> $DIR/issue-101097.rs:19:5 | LL |     f(C, C, B, B, A, A); |     ^ -  -        -  - expected `C`, found `A` |       |  |        | |       |  |        expected `C`, found `A` |       |  expected `A`, found `C` |       expected `A`, found `C` | note: function defined here --> $DIR/issue-101097.rs:6:4 | LL | fn f( |    ^ LL |     a1: A, |     ----- LL |     a2: A, |     ----- LL |     b1: B, |     ----- LL |     b2: B, |     ----- LL |     c1: C, |     ----- LL |     c2: C, |     ----- help: did you mean | LL |     f(A, A, B, B, C, C); |      ~~~~~~~~~~~~~~~~~~ error[E0308]: arguments to this function are incorrect --> $DIR/issue-101097.rs:20:5 | LL |     f(C, C, A, B, A, A); |     ^ -  -  -     -  - expected `C`, found `A` |       |  |  |     | |       |  |  |     expected `C`, found `A` |       |  |  expected struct `B`, found struct `A` |       |  expected `A`, found `C` |       expected `A`, found `C` | note: function defined here --> $DIR/issue-101097.rs:6:4 | LL | fn f( |    ^ LL |     a1: A, |     ----- LL |     a2: A, |     ----- LL |     b1: B, |     ----- LL |     b2: B, |     ----- LL |     c1: C, |     ----- LL |     c2: C, |     ----- help: did you mean | LL |     f(A, A, /* B */, B, C, C); |      ~~~~~~~~~~~~~~~~~~~~~~~~ error: aborting due to 5 previous errors Some errors have detailed explanations: E0061, E0308. For more information about an error, try `rustc --explain E0061`. </ins>


// NOTE: generics must be cleaned before args let generics = clean_generics(generics, cx); let args = clean_args_from_types_and_body_id(cx, sig.decl.inputs, body_id); <del> let decl = clean_fn_decl_with_args(cx, sig.decl, args); </del> <ins> let mut decl = clean_fn_decl_with_args(cx, sig.decl, args); if sig.header.is_async() { decl.output = decl.sugared_async_return_type(); } </ins> (generics, decl) }); Box::new(Function { decl, generics })


///   <br>Used to determine line-wrapping. /// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is ///   necessary. <del> /// * `asyncness`: Whether the function is async or not. </del> pub(crate) fn full_print<'a, 'tcx: 'a>( &'a self, header_len: usize, indent: usize, <del> asyncness: hir::IsAsync, </del> cx: &'a Context<'tcx>, ) -> impl fmt::Display + 'a + Captures<'tcx> { <del> display_fn(move |f| self.inner_full_print(header_len, indent, asyncness, f, cx)) </del> <ins> display_fn(move |f| self.inner_full_print(header_len, indent, f, cx)) </ins> } fn inner_full_print( &self, header_len: usize, indent: usize, <del> asyncness: hir::IsAsync, </del> f: &mut fmt::Formatter<'_>, cx: &Context<'_>, ) -> fmt::Result {


args_plain.push_str(", ..."); } <del> let arrow_plain; let arrow = if let hir::IsAsync::Async = asyncness { let output = self.sugared_async_return_type(); arrow_plain = format!("{:#}", output.print(cx)); if f.alternate() { arrow_plain.clone() } else { format!("{}", output.print(cx)) } } else { arrow_plain = format!("{:#}", self.output.print(cx)); if f.alternate() { arrow_plain.clone() } else { format!("{}", self.output.print(cx)) } }; </del> <ins> let arrow_plain = format!("{:#}", self.output.print(cx)); let arrow = if f.alternate() { arrow_plain.clone() } else { format!("{}", self.output.print(cx)) }; </ins> let declaration_len = header_len + args_plain.len() + arrow_plain.len(); let output = if declaration_len > 80 {


href = href, name = name, generics = g.print(cx), <del> decl = d.full_print(header_len, indent, header.asyncness, cx), </del> <ins> decl = d.full_print(header_len, indent, cx), </ins> notable_traits = notable_traits_decl(d, cx), where_clause = print_where_clause(g, cx, indent, end_newline), )


name = name, generics = f.generics.print(cx), where_clause = print_where_clause(&f.generics, cx, 0, Ending::Newline), <del> decl = f.decl.full_print(header_len, 0, header.asyncness, cx), </del> <ins> decl = f.decl.full_print(header_len, 0, cx), </ins> notable_traits = notable_traits_decl(&f.decl, cx), ); });


<ins> // edition:2021 // ignore-tidy-linelength // Regression test for <https://github.com/rust-lang/rust/issues/101199> use std::future::Future; // @is "$.index[*][?(@.name=='get_int')].inner.decl.output" '{"inner": "i32", "kind": "primitive"}' // @is "$.index[*][?(@.name=='get_int')].inner.header.async" false pub fn get_int() -> i32 { 42 } // @is "$.index[*][?(@.name=='get_int_async')].inner.decl.output" '{"inner": "i32", "kind": "primitive"}' // @is "$.index[*][?(@.name=='get_int_async')].inner.header.async" true pub async fn get_int_async() -> i32 { 42 } // @is "$.index[*][?(@.name=='get_int_future')].inner.decl.output.kind" '"impl_trait"' // @is "$.index[*][?(@.name=='get_int_future')].inner.decl.output.inner[0].trait_bound.trait.name" '"Future"' // @is "$.index[*][?(@.name=='get_int_future')].inner.decl.output.inner[0].trait_bound.trait.args.angle_bracketed.bindings[0].name" '"Output"' // @is "$.index[*][?(@.name=='get_int_future')].inner.decl.output.inner[0].trait_bound.trait.args.angle_bracketed.bindings[0].binding.equality.type" '{"inner": "i32", "kind": "primitive"}' // @is "$.index[*][?(@.name=='get_int_future')].inner.header.async" false pub fn get_int_future() -> impl Future<Output = i32> { async { 42 } } // @is "$.index[*][?(@.name=='get_int_future_async')].inner.decl.output.kind" '"impl_trait"' // @is "$.index[*][?(@.name=='get_int_future_async')].inner.decl.output.inner[0].trait_bound.trait.name" '"Future"' // @is "$.index[*][?(@.name=='get_int_future_async')].inner.decl.output.inner[0].trait_bound.trait.args.angle_bracketed.bindings[0].name" '"Output"' // @is "$.index[*][?(@.name=='get_int_future_async')].inner.decl.output.inner[0].trait_bound.trait.args.angle_bracketed.bindings[0].binding.equality.type" '{"inner": "i32", "kind": "primitive"}' // @is "$.index[*][?(@.name=='get_int_future_async')].inner.header.async" true pub async fn get_int_future_async() -> impl Future<Output = i32> { async { 42 } } </ins>


<ins> // check-pass // edition:2021 // aux-build:test-macros.rs #![no_std] // Don't load unnecessary hygiene information from std extern crate std; #[macro_use] extern crate test_macros; macro_rules! foo { ($($path:ident)::*) => ( test_macros::recollect!( $($path)::* ) ) } macro_rules! baz { () => ( foo!($crate::BAR) ) } pub const BAR: u32 = 19; fn main(){ std::println!("{}", baz!()); } </ins>


kw::Extern, kw::Impl, kw::Unsafe, <ins> kw::Const, </ins> kw::Static, kw::Union, kw::Macro,


<ins> // run-rustfix mod test { pub const X: i32 = 123; //~^ ERROR expected one of `!` or `::`, found keyword `const` } fn main() { println!("{}", test::X); } </ins>


<ins> // run-rustfix mod test { public const X: i32 = 123; //~^ ERROR expected one of `!` or `::`, found keyword `const` } fn main() { println!("{}", test::X); } </ins>


<ins> error: expected one of `!` or `::`, found keyword `const` --> $DIR/public-instead-of-pub-3.rs:3:12 | LL |     public const X: i32 = 123; |            ^^^^^ expected one of `!` or `::` | help: write `pub` instead of `public` to make the item public | LL |     pub const X: i32 = 123; |     ~~~ error: aborting due to previous error </ins>


} /// When encountering an fn-like type, try accessing the output of the type <del> /// // and suggesting calling it if it satisfies a predicate (i.e. if the </del> <ins> /// and suggesting calling it if it satisfies a predicate (i.e. if the </ins> /// output has a method or a field): /// ```compile_fail,E0308 /// fn foo(x: usize) -> usize { x }


} else { err.span_suggestion(sp, &msg, suggestion, applicability); } <ins> } else if self.suggest_else_fn_with_closure(err, expr, found, expected) { </ins> } else if self.suggest_fn_call(err, expr, found, |output| self.can_coerce(output, expected)) && let ty::FnDef(def_id, ..) = &found.kind() && let Some(sp) = self.tcx.hir().span_if_local(*def_id)


} } <ins> /// issue #102320, for `unwrap_or` with closure as argument, suggest `unwrap_or_else` /// FIXME: currently not working for suggesting `map_or_else`, see #102408 pub(crate) fn suggest_else_fn_with_closure( &self, err: &mut Diagnostic, expr: &hir::Expr<'_>, found: Ty<'tcx>, expected: Ty<'tcx>, ) -> bool { let Some((_def_id_or_name, output, _inputs)) = self.extract_callable_info(expr, found) else { return false; }; if !self.can_coerce(output, expected) { return false; } let parent = self.tcx.hir().get_parent_node(expr.hir_id); if  let Some(Node::Expr(call_expr)) = self.tcx.hir().find(parent) && let hir::ExprKind::MethodCall( hir::PathSegment { ident: method_name, .. }, self_expr, args, .., ) = call_expr.kind && let Some(self_ty) = self.typeck_results.borrow().expr_ty_opt(self_expr) { let new_name = Ident { name: Symbol::intern(&format!("{}_else", method_name.as_str())), span: method_name.span, }; let probe = self.lookup_probe( expr.span, new_name, self_ty, self_expr, ProbeScope::TraitsInScope, ); // check the method arguments number if let Ok(pick) = probe && let fn_sig = self.tcx.fn_sig(pick.item.def_id) && let fn_args = fn_sig.skip_binder().inputs() && fn_args.len() == args.len() + 1 { err.span_suggestion_verbose( method_name.span.shrink_to_hi(), &format!("try calling `{}` instead", new_name.name.as_str()), "_else", Applicability::MaybeIncorrect, ); return true; } } false } </ins> /// Checks whether there is a local type somewhere in the chain of /// autoderefs of `rcvr_ty`. fn type_derefs_to_local(


<ins> // run-rustfix fn main() { let x = "com.example.app"; let y: Option<&str> = None; let _s = y.unwrap_or_else(|| x.split('.').nth(1).unwrap()); //~^ ERROR: mismatched types [E0308] } </ins>


<ins> // run-rustfix fn main() { let x = "com.example.app"; let y: Option<&str> = None; let _s = y.unwrap_or(|| x.split('.').nth(1).unwrap()); //~^ ERROR: mismatched types [E0308] } </ins>


<ins> error[E0308]: mismatched types --> $DIR/sugg-else-for-closure.rs:6:26 | LL |     let _s = y.unwrap_or(|| x.split('.').nth(1).unwrap()); |                --------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `&str`, found closure |                | |                arguments to this function are incorrect | = note: expected reference `&str` found closure `[closure@$DIR/sugg-else-for-closure.rs:6:26: 6:28]` note: associated function defined here --> $SRC_DIR/core/src/option.rs:LL:COL | LL |     pub const fn unwrap_or(self, default: T) -> T |                  ^^^^^^^^^ help: try calling `unwrap_or_else` instead | LL |     let _s = y.unwrap_or_else(|| x.split('.').nth(1).unwrap()); |                         +++++ error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. </ins>


use crate::fmt; use crate::io; use crate::marker::PhantomData; <del> use crate::mem; </del> <ins> use crate::mem::{self, forget}; </ins> use crate::num::NonZeroU64; use crate::num::NonZeroUsize; use crate::panic;


imp::Thread::sleep(dur) } <ins> /// Used to ensure that `park` and `park_timeout` do not unwind, as that can /// cause undefined behaviour if not handled correctly (see #102398 for context). struct PanicGuard; impl Drop for PanicGuard { fn drop(&mut self) { rtabort!("an irrecoverable error occurred while synchronizing threads") } } </ins> /// Blocks unless or until the current thread's token is made available. /// /// A call to `park` does not guarantee that the thread will remain parked <del> /// forever, and callers should be prepared for this possibility. </del> <ins> /// forever, and callers should be prepared for this possibility. However, /// it is guaranteed that this function will not panic (it may abort the /// process if the implementation encounters some rare errors). </ins> /// /// # park and unpark ///


/// [`thread::park_timeout`]: park_timeout #[stable(feature = "rust1", since = "1.0.0")] pub fn park() { <ins> let guard = PanicGuard; </ins> // SAFETY: park_timeout is called on the parker owned by this thread. unsafe { current().inner.as_ref().parker().park(); } <ins> // No panic occurred, do not abort. forget(guard); </ins> } /// Use [`park_timeout`].


/// ``` #[stable(feature = "park_timeout", since = "1.4.0")] pub fn park_timeout(dur: Duration) { <ins> let guard = PanicGuard; </ins> // SAFETY: park_timeout is called on the parker owned by this thread. unsafe { current().inner.as_ref().parker().park_timeout(dur); } <ins> // No panic occurred, do not abort. forget(guard); </ins> } ////////////////////////////////////////////////////////////////////////////////


span: Span, origin: &hir::OpaqueTyOrigin, ) { <del> let hidden_type = tcx.bound_type_of(def_id.to_def_id()).subst(tcx, substs); </del> let hir_id = tcx.hir().local_def_id_to_hir_id(def_id); let defining_use_anchor = match *origin { hir::OpaqueTyOrigin::FnReturn(did) | hir::OpaqueTyOrigin::AsyncFn(did) => did,


let ocx = ObligationCtxt::new(&infcx); let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs); <ins> // `ReErased` regions appear in the "parent_substs" of closures/generators. // We're ignoring them here and replacing them with fresh region variables. // See tests in ui/type-alias-impl-trait/closure_{parent_substs,wf_outlives}.rs. // // FIXME: Consider wrapping the hidden type in an existential `Binder` and instantiating it // here rather than using ReErased. let hidden_ty = tcx.bound_type_of(def_id.to_def_id()).subst(tcx, substs); let hidden_ty = tcx.fold_regions(hidden_ty, |re, _dbi| match re.kind() { ty::ReErased => infcx.next_region_var(RegionVariableOrigin::MiscVariable(span)), _ => re, }); </ins> let misc_cause = traits::ObligationCause::misc(span, hir_id); <del> match infcx.at(&misc_cause, param_env).eq(opaque_ty, hidden_type) { </del> <ins> match infcx.at(&misc_cause, param_env).eq(opaque_ty, hidden_ty) { </ins> Ok(infer_ok) => ocx.register_infer_ok_obligations(infer_ok), Err(ty_err) => { tcx.sess.delay_span_bug( span, <del> &format!("could not unify `{hidden_type}` with revealed type:n{ty_err}"), </del> <ins> &format!("could not unify `{hidden_ty}` with revealed type:n{ty_err}"), </ins> ); } }


// Defining use functions may have more bounds than the opaque type, which is ok, as long as the // hidden type is well formed even without those bounds. let predicate = <del> ty::Binder::dummy(ty::PredicateKind::WellFormed(hidden_type.into())).to_predicate(tcx); </del> <ins> ty::Binder::dummy(ty::PredicateKind::WellFormed(hidden_ty.into())).to_predicate(tcx); </ins> ocx.register_obligation(Obligation::new(misc_cause, param_env, predicate)); // Check that all obligations are satisfied by the implementation's


<ins> // When WF checking the hidden type in the ParamEnv of the opaque type, // one complication arises when the hidden type is a closure/generator: // the "parent_substs" of the type may reference lifetime parameters // not present in the opaque type. // These region parameters are not really useful in this check. // So here we ignore them and replace them with fresh region variables. // check-pass #![feature(type_alias_impl_trait)] #![allow(dead_code)] // Basic test mod test1 { // Hidden type = Closure['_#0r] type Opaque = impl Sized; fn define<'a: 'a>() -> Opaque { || {} } } // the region vars cannot both be equal to `'static` or `'empty` mod test2 { trait Trait {} // Hidden type = Closure['a, '_#0r, '_#1r] // Constraints = [('_#0r: 'a), ('a: '_#1r)] type Opaque<'a> where &'a (): Trait, = impl Sized + 'a; fn define<'a, 'x, 'y>() -> Opaque<'a> where &'a (): Trait, 'x: 'a, 'a: 'y, { || {} } } // the region var cannot be equal to `'a` or `'b` mod test3 { trait Trait {} // Hidden type = Closure['a, 'b, '_#0r] // Constraints = [('_#0r: 'a), ('_#0r: 'b)] type Opaque<'a, 'b> where (&'a (), &'b ()): Trait, = impl Sized + 'a + 'b; fn define<'a, 'b, 'x>() -> Opaque<'a, 'b> where (&'a (), &'b ()): Trait, 'x: 'a, 'x: 'b, { || {} } } fn main() {} </ins>


<ins> // If the hidden type is a closure, we require the "outlives" bounds that appear on the // defining site to also appear on the opaque type. // // It's not clear if this is the desired behavior but at least // it's consistent and has no back-compat risk. // check-fail #![feature(type_alias_impl_trait)] #![allow(dead_code)] // requires `'a: 'b` bound mod test1 { type Opaque<'a, 'b> = impl Sized + 'a + 'b; //~^ ERROR lifetime bound not satisfied fn define<'a, 'b>() -> Opaque<'a, 'b> where 'a: 'b, { || {} } } // Same as the above but through indirection `'x` mod test2 { type Opaque<'a, 'b> = impl Sized + 'a + 'b; //~^ ERROR cannot infer an appropriate lifetime fn define<'a, 'b, 'x>() -> Opaque<'a, 'b> where 'a: 'x, 'x: 'b, { || {} } } // fixed version of the above mod test2_fixed { type Opaque<'a: 'b, 'b> = impl Sized + 'a + 'b; fn define<'a, 'b, 'x>() -> Opaque<'a, 'b> where 'a: 'x, 'x: 'b, { || {} } } // requires `T: 'static` mod test3 { type Opaque<T> = impl Sized; //~^ ERROR the parameter type `T` may not live long enough fn define<T>() -> Opaque<T> where T: 'static, { || {} } } fn main() {} </ins>


<ins> error[E0478]: lifetime bound not satisfied --> $DIR/closure_wf_outlives.rs:14:27 | LL |     type Opaque<'a, 'b> = impl Sized + 'a + 'b; |                           ^^^^^^^^^^^^^^^^^^^^ | note: lifetime parameter instantiated with the lifetime `'a` as defined here --> $DIR/closure_wf_outlives.rs:14:17 | LL |     type Opaque<'a, 'b> = impl Sized + 'a + 'b; |                 ^^ note: but lifetime parameter must outlive the lifetime `'b` as defined here --> $DIR/closure_wf_outlives.rs:14:21 | LL |     type Opaque<'a, 'b> = impl Sized + 'a + 'b; |                     ^^ error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements --> $DIR/closure_wf_outlives.rs:27:27 | LL |     type Opaque<'a, 'b> = impl Sized + 'a + 'b; |                           ^^^^^^^^^^^^^^^^^^^^ | note: first, the lifetime cannot outlive the lifetime `'a` as defined here... --> $DIR/closure_wf_outlives.rs:27:17 | LL |     type Opaque<'a, 'b> = impl Sized + 'a + 'b; |                 ^^ note: ...so that the declared lifetime parameter bounds are satisfied --> $DIR/closure_wf_outlives.rs:27:27 | LL |     type Opaque<'a, 'b> = impl Sized + 'a + 'b; |                           ^^^^^^^^^^^^^^^^^^^^ note: but, the lifetime must be valid for the lifetime `'b` as defined here... --> $DIR/closure_wf_outlives.rs:27:21 | LL |     type Opaque<'a, 'b> = impl Sized + 'a + 'b; |                     ^^ note: ...so that the declared lifetime parameter bounds are satisfied --> $DIR/closure_wf_outlives.rs:27:27 | LL |     type Opaque<'a, 'b> = impl Sized + 'a + 'b; |                           ^^^^^^^^^^^^^^^^^^^^ error[E0310]: the parameter type `T` may not live long enough --> $DIR/closure_wf_outlives.rs:54:22 | LL |     type Opaque<T> = impl Sized; |                      ^^^^^^^^^^ ...so that the type `T` will meet its required lifetime bounds... | note: ...that is required by this bound --> $DIR/closure_wf_outlives.rs:59:12 | LL |         T: 'static, |            ^^^^^^^ help: consider adding an explicit lifetime bound... | LL |     type Opaque<T: 'static> = impl Sized; |                  +++++++++ error: aborting due to 3 previous errors Some errors have detailed explanations: E0310, E0478, E0495. For more information about an error, try `rustc --explain E0310`. </ins>


let ocx = ObligationCtxt::new(infcx); let norm_cause = ObligationCause::misc(return_span, impl_m_hir_id); <del> let impl_return_ty = ocx.normalize( </del> <ins> let impl_sig = ocx.normalize( </ins> norm_cause.clone(), param_env, <del> infcx .replace_bound_vars_with_fresh_vars( return_span, infer::HigherRankedType, tcx.fn_sig(impl_m.def_id), ) .output(), </del> <ins> infcx.replace_bound_vars_with_fresh_vars( return_span, infer::HigherRankedType, tcx.fn_sig(impl_m.def_id), ), </ins> ); <ins> let impl_return_ty = impl_sig.output(); </ins> let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_hir_id); <del> let unnormalized_trait_return_ty = tcx </del> <ins> let unnormalized_trait_sig = tcx </ins> .liberate_late_bound_regions( impl_m.def_id, tcx.bound_fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs), ) <del> .output() </del> .fold_with(&mut collector); <del> let trait_return_ty = ocx.normalize(norm_cause.clone(), param_env, unnormalized_trait_return_ty); </del> <ins> let trait_sig = ocx.normalize(norm_cause.clone(), param_env, unnormalized_trait_sig); let trait_return_ty = trait_sig.output(); </ins> <del> let wf_tys = FxHashSet::from_iter([unnormalized_trait_return_ty, trait_return_ty]); </del> <ins> let wf_tys = FxHashSet::from_iter( unnormalized_trait_sig.inputs_and_output.iter().chain(trait_sig.inputs_and_output.iter()), ); </ins> match infcx.at(&cause, param_env).eq(trait_return_ty, impl_return_ty) { Ok(infer::InferOk { value: (), obligations }) => {


} } <ins> // Unify the whole function signature. We need to do this to fully infer // the lifetimes of the return type, but do this after unifying just the // return types, since we want to avoid duplicating errors from // `compare_predicate_entailment`. match infcx .at(&cause, param_env) .eq(tcx.mk_fn_ptr(ty::Binder::dummy(trait_sig)), tcx.mk_fn_ptr(ty::Binder::dummy(impl_sig))) { Ok(infer::InferOk { value: (), obligations }) => { ocx.register_obligations(obligations); } Err(terr) => { let guar = tcx.sess.delay_span_bug( return_span, format!("could not unify `{trait_sig}` and `{impl_sig}`: {terr:?}"), ); return Err(guar); } } </ins> // Check that all obligations are satisfied by the implementation's // RPITs. let errors = ocx.select_all_or_error();


let id_substs = InternalSubsts::identity_for_item(tcx, def_id); debug!(?id_substs, ?substs); let map: FxHashMap<ty::GenericArg<'tcx>, ty::GenericArg<'tcx>> = <del> substs.iter().enumerate().map(|(index, arg)| (arg, id_substs[index])).collect(); </del> <ins> std::iter::zip(substs, id_substs).collect(); </ins> debug!(?map); <ins> // NOTE(compiler-errors): RPITITs, like all other RPITs, have early-bound // region substs that are synthesized during AST lowering. These are substs // that are appended to the parent substs (trait and trait method). However, // we're trying to infer the unsubstituted type value of the RPITIT inside // the *impl*, so we can later use the impl's method substs to normalize // an RPITIT to a concrete type (`confirm_impl_trait_in_trait_candidate`). // // Due to the design of RPITITs, during AST lowering, we have no idea that // an impl method corresponds to a trait method with RPITITs in it. Therefore, // we don't have a list of early-bound region substs for the RPITIT in the impl. // Since early region parameters are index-based, we can't just rebase these // (trait method) early-bound region substs onto the impl, and there's no // guarantee that the indices from the trait substs and impl substs line up. // So to fix this, we subtract the number of trait substs and add the number of // impl substs to *renumber* these early-bound regions to their corresponding // indices in the impl's substitutions list. // // Also, we only need to account for a difference in trait and impl substs, // since we previously enforce that the trait method and impl method have the // same generics. let num_trait_substs = trait_to_impl_substs.len(); let num_impl_substs = tcx.generics_of(impl_m.container_id(tcx)).params.len(); </ins> let ty = tcx.fold_regions(ty, |region, _| { <del> if let ty::ReFree(_) = region.kind() { map[&region.into()].expect_region() } else { region } </del> <ins> let ty::ReFree(_) = region.kind() else { return region; }; let ty::ReEarlyBound(e) = map[&region.into()].expect_region().kind() else { bug!("expected ReFree to map to ReEarlyBound"); }; tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: e.def_id, name: e.name, index: (e.index as usize - num_trait_substs + num_impl_substs) as u32, })) </ins> }); debug!(%ty); collected_tys.insert(def_id, ty);


fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { #[cold] #[inline(never)] <del> fn region_param_out_of_range(data: ty::EarlyBoundRegion) -> ! { </del> <ins> fn region_param_out_of_range(data: ty::EarlyBoundRegion, substs: &[GenericArg<'_>]) -> ! { </ins> bug!( <del> "Region parameter out of range when substituting in region {} (index={})", </del> <ins> "Region parameter out of range when substituting in region {} (index={}, substs = {:?})", data.name, data.index, substs, ) } #[cold] #[inline(never)] fn region_param_invalid(data: ty::EarlyBoundRegion, other: GenericArgKind<'_>) -> ! { bug!( "Unexpected parameter {:?} when substituting in region {} (index={})", other, </ins> data.name, data.index )


let rk = self.substs.get(data.index as usize).map(|k| k.unpack()); match rk { Some(GenericArgKind::Lifetime(lt)) => self.shift_region_through_binders(lt), <del> _ => region_param_out_of_range(data), </del> <ins> Some(other) => region_param_invalid(data, other), None => region_param_out_of_range(data, self.substs), </ins> } } _ => r,


} let impl_fn_def_id = leaf_def.item.def_id; <del> let impl_fn_substs = obligation.predicate.substs.rebase_onto(tcx, trait_fn_def_id, data.substs); </del> <ins> // Rebase from {trait}::{fn}::{opaque} to {impl}::{fn}::{opaque}, // since `data.substs` are the impl substs. let impl_fn_substs = obligation.predicate.substs.rebase_onto(tcx, tcx.parent(trait_fn_def_id), data.substs); </ins> let cause = ObligationCause::new( obligation.cause.span,


<ins> // check-pass // edition:2021 #![feature(async_fn_in_trait)] #![allow(incomplete_features)] pub trait SpiDevice { async fn transaction<F, R>(&mut self); } impl SpiDevice for () { async fn transaction<F, R>(&mut self) {} } fn main() {} </ins>


<ins> // check-pass #![feature(return_position_impl_trait_in_trait)] #![allow(incomplete_features)] trait Foo<T> { fn foo<F2: Foo<T>>(self) -> impl Foo<T>; } struct Bar; impl Foo<u8> for Bar { fn foo<F2: Foo<u8>>(self) -> impl Foo<u8> { self } } fn main() {} </ins>


kind: ast::VisibilityKind::Inherited, tokens: None, }, <del> span: ecx.with_def_site_ctxt(sp), </del> <ins> span: sp, </ins> tokens: None, })]) } else {


lint_builtin_export_name_fn = declaration of a function with `export_name` lint_builtin_export_name_method = declaration of a method with `export_name` lint_builtin_export_name_static = declaration of a static with `export_name` <ins> lint_builtin_global_asm = usage of `core::arch::global_asm` lint_builtin_global_macro_unsafety = using this macro is unsafe even though it does not need an `unsafe` block </ins> lint_builtin_impl_unsafe_method = implementation of an `unsafe` method lint_builtin_incomplete_features = the feature `{$name}` is incomplete and may not be safe to use and/or cause compiler crashes


} } <ins> ast::ItemKind::GlobalAsm(..) => { self.report_unsafe(cx, it.span, BuiltinUnsafe::GlobalAsm); } </ins> _ => {} } }


DeclUnsafeMethod, #[diag(lint_builtin_impl_unsafe_method)] ImplUnsafeMethod, <ins> #[diag(lint_builtin_global_asm)] #[note(lint_builtin_global_macro_unsafety)] GlobalAsm, </ins> } #[derive(LintDiagnostic)]


| LL | global_asm!(""); | ^^^^^^^^^^^^^^^ <del> | = note: this error originates in the macro `global_asm` (in Nightly builds, run with -Z macro-backtrace for more info) </del> error: aborting due to 2 previous errors


<ins> //@ needs-asm-support #![deny(unsafe_code)] use std::arch::global_asm; #[allow(unsafe_code)] mod allowed_unsafe { std::arch::global_asm!(""); } macro_rules! unsafe_in_macro { () => { global_asm!(""); //~ ERROR: usage of `core::arch::global_asm` }; } global_asm!(""); //~ ERROR: usage of `core::arch::global_asm` unsafe_in_macro!(); fn main() {} </ins>


<ins> error: usage of `core::arch::global_asm` --> $DIR/lint-global-asm-as-unsafe.rs:17:1 | LL | global_asm!(""); | ^^^^^^^^^^^^^^^ | = note: using this macro is unsafe even though it does not need an `unsafe` block note: the lint level is defined here --> $DIR/lint-global-asm-as-unsafe.rs:2:9 | LL | #![deny(unsafe_code)] |         ^^^^^^^^^^^ error: usage of `core::arch::global_asm` --> $DIR/lint-global-asm-as-unsafe.rs:13:9 | LL |         global_asm!(""); |         ^^^^^^^^^^^^^^^ ... LL | unsafe_in_macro!(); | ------------------ in this macro invocation | = note: using this macro is unsafe even though it does not need an `unsafe` block = note: this error originates in the macro `unsafe_in_macro` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors </ins>


/// Returns a new span representing the next character after the end-point of this span. /// Special cases: /// - if span is a dummy one, returns the same span <del> /// - if next_point reached the end of source, return span with lo = hi </del> <ins> /// - if next_point reached the end of source, return a span exceeding the end of source, ///   which means sm.span_to_snippet(next_point) will get `Err` </ins> /// - respect multi-byte characters pub fn next_point(&self, sp: Span) -> Span { if sp.is_dummy() {


let start_of_next_point = sp.hi().0; let width = self.find_width_of_character_at_span(sp, true); <del> if width == 0 { return Span::new(sp.hi(), sp.hi(), sp.ctxt(), None); } </del> // If the width is 1, then the next span should only contain the next char besides current ending. // However, in the case of a multibyte character, where the width != 1, the next span should // span multiple bytes to include the whole character.


// Ensure indexes are also not malformed. if start_index > end_index || end_index > source_len - 1 { debug!("find_width_of_character_at_span: source indexes are malformed"); <del> return 0; </del> <ins> return 1; </ins> } let src = local_begin.sf.external_src.borrow();


assert_eq!(span.lo().0, 4); assert_eq!(span.hi().0, 5); <del> // A non-empty span at the last byte should advance to create an empty // span pointing at the end of the file. </del> <ins> // Reaching to the end of file, return a span that will get error with `span_to_snippet` </ins> let span = Span::with_root_ctxt(BytePos(4), BytePos(5)); let span = sm.next_point(span); assert_eq!(span.lo().0, 5); <del> assert_eq!(span.hi().0, 5); </del> <ins> assert_eq!(span.hi().0, 6); assert!(sm.span_to_snippet(span).is_err()); </ins> <del> // Empty span pointing just past the last byte. </del> <ins> // Reaching to the end of file, return a span that will get error with `span_to_snippet` </ins> let span = Span::with_root_ctxt(BytePos(5), BytePos(5)); let span = sm.next_point(span); assert_eq!(span.lo().0, 5); <del> assert_eq!(span.hi().0, 5); </del> <ins> assert_eq!(span.hi().0, 6); assert!(sm.span_to_snippet(span).is_err()); </ins> }


<ins> // error-pattern: this file contains an unclosed delimiter // error-pattern: expected value, found struct `R` struct R { } struct S { x: [u8; R </ins>


<ins> error: this file contains an unclosed delimiter --> $DIR/issue-103451.rs:5:15 | LL | struct S { |          - unclosed delimiter LL |     x: [u8; R |        -      ^ |        | |        unclosed delimiter error: this file contains an unclosed delimiter --> $DIR/issue-103451.rs:5:15 | LL | struct S { |          - unclosed delimiter LL |     x: [u8; R |        -      ^ |        | |        unclosed delimiter error[E0423]: expected value, found struct `R` --> $DIR/issue-103451.rs:5:13 | LL | struct R { } | ------------ `R` defined here LL | struct S { LL |     x: [u8; R |             ^ help: use struct literal syntax instead: `R {}` error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0423`. </ins>


} /// Parses the parameter list of a function, including the `(` and `)` delimiters. <del> fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> { </del> <ins> pub(super) fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> { </ins> let mut first_param = true; // Parse the arguments, starting out with `self` being allowed... let (mut params, _) = self.parse_paren_comma_seq(|p| {


has_parens: bool, modifiers: BoundModifiers, ) -> PResult<'a, GenericBound> { <del> let lifetime_defs = self.parse_late_bound_lifetime_defs()?; let path = if self.token.is_keyword(kw::Fn) </del> <ins> let mut lifetime_defs = self.parse_late_bound_lifetime_defs()?; let mut path = if self.token.is_keyword(kw::Fn) </ins> && self.look_ahead(1, |tok| tok.kind == TokenKind::OpenDelim(Delimiter::Parenthesis)) && let Some(path) = self.recover_path_from_fn() {


} else { self.parse_path(PathStyle::Type)? }; <ins> if self.may_recover() && self.token == TokenKind::OpenDelim(Delimiter::Parenthesis) { self.recover_fn_trait_with_lifetime_params(&mut path, &mut lifetime_defs)?; } </ins> if has_parens { if self.token.is_like_plus() { // Someone has written something like `&dyn (Trait + Other)`. The correct code


} } <ins> /// Recover from `Fn`-family traits (Fn, FnMut, FnOnce) with lifetime arguments /// (e.g. `FnOnce<'a>(&'a str) -> bool`). Up to generic arguments have already /// been eaten. fn recover_fn_trait_with_lifetime_params( &mut self, fn_path: &mut ast::Path, lifetime_defs: &mut Vec<GenericParam>, ) -> PResult<'a, ()> { let fn_path_segment = fn_path.segments.last_mut().unwrap(); let generic_args = if let Some(p_args) = &fn_path_segment.args { p_args.clone().into_inner() } else { // Normally it wouldn't come here because the upstream should have parsed // generic parameters (otherwise it's impossible to call this function). return Ok(()); }; let lifetimes = if let ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs { span: _, args }) = &generic_args { args.into_iter() .filter_map(|arg| { if let ast::AngleBracketedArg::Arg(generic_arg) = arg && let ast::GenericArg::Lifetime(lifetime) = generic_arg { Some(lifetime) } else { None } }) .collect() } else { Vec::new() }; // Only try to recover if the trait has lifetime params. if lifetimes.is_empty() { return Ok(()); } // Parse `(T, U) -> R`. let inputs_lo = self.token.span; let inputs: Vec<_> = self.parse_fn_params(|_| false)?.into_iter().map(|input| input.ty).collect(); let inputs_span = inputs_lo.to(self.prev_token.span); let output = self.parse_ret_ty(AllowPlus::No, RecoverQPath::No, RecoverReturnSign::No)?; let args = ast::ParenthesizedArgs { span: fn_path_segment.span().to(self.prev_token.span), inputs, inputs_span, output, } .into(); *fn_path_segment = ast::PathSegment { ident: fn_path_segment.ident, args, id: ast::DUMMY_NODE_ID }; // Convert parsed `<'a>` in `Fn<'a>` into `for<'a>`. let mut generic_params = lifetimes .iter() .map(|lt| GenericParam { id: lt.id, ident: lt.ident, attrs: ast::AttrVec::new(), bounds: Vec::new(), is_placeholder: false, kind: ast::GenericParamKind::Lifetime, colon_span: None, }) .collect::<Vec<GenericParam>>(); lifetime_defs.append(&mut generic_params); let generic_args_span = generic_args.span(); let mut err = self.struct_span_err(generic_args_span, "`Fn` traits cannot take lifetime parameters"); let snippet = format!( "for<{}> ", lifetimes.iter().map(|lt| lt.ident.as_str()).intersperse(", ").collect::<String>(), ); let before_fn_path = fn_path.span.shrink_to_lo(); err.multipart_suggestion( "consider using a higher-ranked trait bound instead", vec![(generic_args_span, "".to_owned()), (before_fn_path, snippet)], Applicability::MaybeIncorrect, ) .emit(); Ok(()) } </ins> pub(super) fn check_lifetime(&mut self) -> bool { self.expected_tokens.push(TokenType::Lifetime); self.token.is_lifetime()


<ins> // Test that Fn-family traits with lifetime parameters shouldn't compile and // we suggest the usage of higher-rank trait bounds instead. fn fa(_: impl Fn<'a>(&'a str) -> bool) {} //~^ ERROR `Fn` traits cannot take lifetime parameters fn fb(_: impl FnMut<'a, 'b>(&'a str, &'b str) -> bool) {} //~^ ERROR `Fn` traits cannot take lifetime parameters fn fc(_: impl std::fmt::Display + FnOnce<'a>(&'a str) -> bool + std::fmt::Debug) {} //~^ ERROR `Fn` traits cannot take lifetime parameters use std::ops::Fn as AliasedFn; fn fd(_: impl AliasedFn<'a>(&'a str) -> bool) {} //~^ ERROR `Fn` traits cannot take lifetime parameters fn fe<F>(_: F) where F: Fn<'a>(&'a str) -> bool {} //~^ ERROR `Fn` traits cannot take lifetime parameters fn main() {} </ins>


<ins> error: `Fn` traits cannot take lifetime parameters --> $DIR/hrtb-malformed-lifetime-generics.rs:4:17 | LL | fn fa(_: impl Fn<'a>(&'a str) -> bool) {} |                 ^^^^ | help: consider using a higher-ranked trait bound instead | LL - fn fa(_: impl Fn<'a>(&'a str) -> bool) {} LL + fn fa(_: impl for<'a> Fn(&'a str) -> bool) {} | error: `Fn` traits cannot take lifetime parameters --> $DIR/hrtb-malformed-lifetime-generics.rs:7:20 | LL | fn fb(_: impl FnMut<'a, 'b>(&'a str, &'b str) -> bool) {} |                    ^^^^^^^^ | help: consider using a higher-ranked trait bound instead | LL - fn fb(_: impl FnMut<'a, 'b>(&'a str, &'b str) -> bool) {} LL + fn fb(_: impl for<'a, 'b> FnMut(&'a str, &'b str) -> bool) {} | error: `Fn` traits cannot take lifetime parameters --> $DIR/hrtb-malformed-lifetime-generics.rs:10:41 | LL | fn fc(_: impl std::fmt::Display + FnOnce<'a>(&'a str) -> bool + std::fmt::Debug) {} |                                         ^^^^ | help: consider using a higher-ranked trait bound instead | LL - fn fc(_: impl std::fmt::Display + FnOnce<'a>(&'a str) -> bool + std::fmt::Debug) {} LL + fn fc(_: impl std::fmt::Display + for<'a> FnOnce(&'a str) -> bool + std::fmt::Debug) {} | error: `Fn` traits cannot take lifetime parameters --> $DIR/hrtb-malformed-lifetime-generics.rs:14:24 | LL | fn fd(_: impl AliasedFn<'a>(&'a str) -> bool) {} |                        ^^^^ | help: consider using a higher-ranked trait bound instead | LL - fn fd(_: impl AliasedFn<'a>(&'a str) -> bool) {} LL + fn fd(_: impl for<'a> AliasedFn(&'a str) -> bool) {} | error: `Fn` traits cannot take lifetime parameters --> $DIR/hrtb-malformed-lifetime-generics.rs:17:27 | LL | fn fe<F>(_: F) where F: Fn<'a>(&'a str) -> bool {} |                           ^^^^ | help: consider using a higher-ranked trait bound instead | LL - fn fe<F>(_: F) where F: Fn<'a>(&'a str) -> bool {} LL + fn fe<F>(_: F) where F: for<'a> Fn(&'a str) -> bool {} | error: aborting due to 5 previous errors </ins>


drain_array_with(self, |iter| try_from_trusted_iterator(iter.map(f))) } <del> /// 'Zips up' two arrays into a single array of pairs. /// /// `zip()` returns a new array where every element is a tuple where the /// first element comes from the first array, and the second element comes /// from the second array. In other words, it zips two arrays together, /// into a single one. /// /// # Examples /// /// ``` /// #![feature(array_zip)] /// let x = [1, 2, 3]; /// let y = [4, 5, 6]; /// let z = x.zip(y); /// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]); /// ``` #[unstable(feature = "array_zip", issue = "80094")] pub fn zip<U>(self, rhs: [U; N]) -> [(T, U); N] { drain_array_with(self, |lhs| { drain_array_with(rhs, |rhs| from_trusted_iterator(crate::iter::zip(lhs, rhs))) }) } </del> /// Returns a slice containing the entire array. Equivalent to `&s[..]`. #[stable(feature = "array_as_slice", since = "1.57.0")] #[rustc_const_stable(feature = "array_as_slice", since = "1.57.0")]


// ignore-debug (the extra assertions get in the way) #![crate_type = "lib"] <del> #![feature(array_zip)] </del> // CHECK-LABEL: @short_integer_map #[no_mangle]


x.map(|x| 2 * x + 1) } <del> // CHECK-LABEL: @short_integer_zip_map #[no_mangle] pub fn short_integer_zip_map(x: [u32; 8], y: [u32; 8]) -> [u32; 8] { // CHECK: %[[A:.+]] = load <8 x i32> // CHECK: %[[B:.+]] = load <8 x i32> // CHECK: sub <8 x i32> %[[B]], %[[A]] // CHECK: store <8 x i32> x.zip(y).map(|(x, y)| x - y) } </del> // This test is checking that LLVM can SRoA away a bunch of the overhead, // like fully moving the iterators to registers.  Notably, previous implementations // of `map` ended up `alloca`ing the whole `array::IntoIterator`, meaning both a


// compile-flags: -C opt-level=3 -Z merge-functions=disabled // only-x86_64 #![crate_type = "lib"] <del> #![feature(array_zip)] </del> // CHECK-LABEL: @auto_vectorize_direct #[no_mangle]


c } <del> // CHECK-LABEL: @auto_vectorize_array_zip_map </del> <ins> // CHECK-LABEL: @auto_vectorize_array_from_fn </ins> #[no_mangle] <del> pub fn auto_vectorize_array_zip_map(a: [f32; 4], b: [f32; 4]) -> [f32; 4] { </del> <ins> pub fn auto_vectorize_array_from_fn(a: [f32; 4], b: [f32; 4]) -> [f32; 4] { </ins> // CHECK: load <4 x float> // CHECK: load <4 x float> // CHECK: fadd <4 x float> // CHECK: store <4 x float> <del> a.zip(b).map(|(a, b)| a + b) </del> <ins> std::array::from_fn(|i| a[i] + b[i]) </ins> }


let my_out = match mode { // This is the intended out directory for compiler documentation. Mode::Rustc | Mode::ToolRustc => self.compiler_doc_out(target), <del> Mode::Std => out_dir.join(target.triple).join("doc"), </del> <ins> Mode::Std => { if self.config.cmd.json() { out_dir.join(target.triple).join("json-doc") } else { out_dir.join(target.triple).join("doc") } } </ins> _ => panic!("doc mode {:?} not expected", mode), }; let rustdoc = self.rustdoc(compiler);


); } let compiler = builder.compiler(stage, builder.config.build); <ins> let target_doc_dir_name = if format == DocumentationFormat::JSON { "json-doc" } else { "doc" }; let target_dir = builder.stage_out(compiler, Mode::Std).join(target.triple).join(target_doc_dir_name); </ins> // This is directory where the compiler will place the output of the command. // We will then copy the files from this directory into the final `out` directory, the specified // as a function parameter. <del> let out_dir = builder.stage_out(compiler, Mode::Std).join(target.triple).join("doc"); // `cargo` uses the same directory for both JSON docs and HTML docs. // This could lead to cross-contamination when copying files into the specified `out` directory. // For example: // ```bash // x doc std // x doc std --json // ``` // could lead to HTML docs being copied into the JSON docs output directory. // To avoid this issue, we clean the doc folder before invoking `cargo`. if out_dir.exists() { builder.remove_dir(&out_dir); } </del> <ins> let out_dir = target_dir.join(target.triple).join("doc"); </ins> let run_cargo_rustdoc_for = |package: &str| { let mut cargo = builder.cargo(compiler, Mode::Std, SourceType::InTree, target, "rustdoc"); compile::std_cargo(builder, target, compiler.stage, &mut cargo); cargo <ins> .arg("--target-dir") .arg(&*target_dir.to_string_lossy()) </ins> .arg("-p") .arg(package) .arg("-Zskip-rustdoc-fingerprint")


<ins> include ../../run-make-fulldeps/tools.mk OUTPUT_DIR := "$(TMPDIR)/rustdoc" TMP_OUTPUT_DIR := "$(TMPDIR)/tmp-rustdoc" all: # Generate html docs $(RUSTDOC) src/lib.rs --crate-name foobar --crate-type lib --out-dir $(OUTPUT_DIR) # Copy first output for to check if it's exactly same after second compilation cp -R $(OUTPUT_DIR) $(TMP_OUTPUT_DIR) # Generate html docs once again on same output $(RUSTDOC) src/lib.rs --crate-name foobar --crate-type lib --out-dir $(OUTPUT_DIR) # Check if everything exactly same $(DIFF) -r -q $(OUTPUT_DIR) $(TMP_OUTPUT_DIR) # Generate json doc on the same output $(RUSTDOC) src/lib.rs --crate-name foobar --crate-type lib --out-dir $(OUTPUT_DIR) -Z unstable-options --output-format json # Check if expected json file is generated [ -e $(OUTPUT_DIR)/foobar.json ] # TODO # We should re-generate json doc once again and compare the diff with previously # generated one. Because layout of json docs changes in each compilation, we can't # do that currently. # # See https://github.com/rust-lang/rust/issues/103785#issuecomment-1307425590 for details. # remove generated json doc rm $(OUTPUT_DIR)/foobar.json # Check if json doc compilation broke any of the html files generated previously $(DIFF) -r -q $(OUTPUT_DIR) $(TMP_OUTPUT_DIR) </ins>


*[other] patterns `{$witness_1}`, `{$witness_2}`, `{$witness_3}` and {$remainder} more } not covered <ins> mir_build_privately_uninhabited = pattern `{$witness_1}` is currently uninhabited, but this variant contains private fields which may become inhabited in the future </ins> mir_build_pattern_not_covered = refutable pattern in {$origin} .pattern_ty = the matched value is of type `{$pattern_ty}`


pub interpreted_as_const: Option<InterpretedAsConst>, #[subdiagnostic] pub adt_defined_here: Option<AdtDefinedHere<'tcx>>, <ins> #[note(mir_build_privately_uninhabited)] pub witness_1_is_privately_uninhabited: Option<()>, </ins> #[note(mir_build_pattern_ty)] pub _p: (), pub pattern_ty: Ty<'tcx>,


AdtDefinedHere { adt_def_span, ty, variants } }; <ins> // Emit an extra note if the first uncovered witness is // visibly uninhabited anywhere in the current crate. let witness_1_is_privately_uninhabited = if cx.tcx.features().exhaustive_patterns && let Some(witness_1) = witnesses.get(0) && let ty::Adt(adt, substs) = witness_1.ty().kind() && adt.is_enum() && let Constructor::Variant(variant_index) = witness_1.ctor() { let variant = adt.variant(*variant_index); let inhabited = variant.inhabited_predicate(cx.tcx, *adt).subst(cx.tcx, substs); assert!(inhabited.apply(cx.tcx, cx.param_env, cx.module)); !inhabited.apply_ignore_module(cx.tcx, cx.param_env) } else { false }; </ins> self.error = Err(self.tcx.sess.emit_err(PatternNotCovered { span: pat.span, origin, uncovered: Uncovered::new(pat.span, &cx, witnesses), inform, interpreted_as_const, <ins> witness_1_is_privately_uninhabited: witness_1_is_privately_uninhabited.then_some(()), </ins> _p: (), pattern_ty, let_suggestion,


LL |     A(A), LL |     B(inner::Wrapper<B>), |     - not covered <ins> = note: pattern `Either::B(_)` is currently uninhabited, but this variant contains private fields which may become inhabited in the future </ins> = note: the matched value is of type `Either<(), !>` help: you might want to use `if let` to ignore the variant that isn't matched |


} enum Foo { <ins> //~^ NOTE `Foo` defined here </ins> A(foo::SecretlyEmpty), <ins> //~^ NOTE not covered </ins> B(foo::NotSoSecretlyEmpty), C(NotSoSecretlyEmpty), D(u32, u32),


let Foo::D(_y, _z) = x; //~^ ERROR refutable pattern in local binding //~| `Foo::A(_)` not covered <ins> //~| NOTE `let` bindings require an "irrefutable pattern" //~| NOTE for more information //~| NOTE pattern `Foo::A(_)` is currently uninhabited //~| NOTE the matched value is of type `Foo` //~| HELP you might want to use `let else` </ins> }


error[E0005]: refutable pattern in local binding <del> --> $DIR/uninhabited-irrefutable.rs:27:9 </del> <ins> --> $DIR/uninhabited-irrefutable.rs:29:9 </ins> | LL |     let Foo::D(_y, _z) = x; |         ^^^^^^^^^^^^^^ pattern `Foo::A(_)` not covered


| LL | enum Foo { |      ^^^ <ins> LL | </ins> LL |     A(foo::SecretlyEmpty), |     - not covered <ins> = note: pattern `Foo::A(_)` is currently uninhabited, but this variant contains private fields which may become inhabited in the future </ins> = note: the matched value is of type `Foo` help: you might want to use `let else` to handle the variant that isn't matched |


let literal = constant.literal; match literal { ConstantKind::Ty(c) => match c.kind() { <del> ConstKind::Param(_) => {} </del> <ins> ConstKind::Param(_) | ConstKind::Error(_) => {} </ins> _ => bug!("only ConstKind::Param should be encountered here, got {:#?}", c), }, ConstantKind::Unevaluated(..) => self.required_consts.push(*constant),


<ins> fn f() -> impl Sized { 2.0E //~^ ERROR expected at least one digit in exponent } fn main() {} </ins>


<ins> error: expected at least one digit in exponent --> $DIR/invalid-const-in-body.rs:2:5 | LL |     2.0E |     ^^^^ error: aborting due to previous error </ins>


font-weight: 600; margin: 0; padding: 0; <del> /* position notable traits in mobile mode within the header */ position: relative; </del> } #crate-search,


// Check the impl items. assert-css: (".impl-items .has-srclink .srclink", {"font-size": "16px", "font-weight": 400}, ALL) assert-css: (".impl-items .has-srclink .code-header", {"font-size": "16px", "font-weight": 600}, ALL) <ins> // Check that we can click on source link store-document-property: (url, "URL") click: ".impl-items .has-srclink .srclink" assert-document-property-false: {"URL": |url|} </ins>


//! //! * Should probably have something like this for strings. //! * Should they implement Closable? Would take extra state. <ins> use cmp::max; </ins> use cmp::min; use prelude::*; use super::*;


} } <ins> // FIXME(#10432) </ins> impl Seek for MemWriter { fn tell(&self) -> u64 { self.pos as u64 } fn seek(&mut self, pos: i64, style: SeekStyle) { <del> match style { SeekSet => { self.pos = pos as uint; } SeekEnd => { self.pos = self.buf.len() + pos as uint; } SeekCur => { self.pos += pos as uint; } } </del> <ins> // compute offset as signed and clamp to prevent overflow let offset = match style { SeekSet => { 0 } SeekEnd => { self.buf.len() } SeekCur => { self.pos } } as i64; self.pos = max(0, offset+pos) as uint; </ins> } }


/// Writes to a fixed-size byte slice <ins> /// /// If a write will not fit in the buffer, it raises the `io_error` /// condition and does not write any data. </ins> pub struct BufWriter<'self> { priv buf: &'self mut [u8], priv pos: uint


} impl<'self> Writer for BufWriter<'self> { <del> fn write(&mut self, _buf: &[u8]) { fail!() } </del> <ins> fn write(&mut self, buf: &[u8]) { // raises a condition if the entire write does not fit in the buffer let max_size = self.buf.len(); if self.pos >= max_size || (self.pos + buf.len()) > max_size { io_error::cond.raise(IoError { kind: OtherIoError, desc: "Trying to write past end of buffer", detail: None }); return; } </ins> <del> fn flush(&mut self) { fail!() } </del> <ins> vec::bytes::copy_memory(self.buf.mut_slice_from(self.pos), buf, buf.len()); self.pos += buf.len(); } </ins> } <ins> // FIXME(#10432) </ins> impl<'self> Seek for BufWriter<'self> { <del> fn tell(&self) -> u64 { fail!() } </del> <ins> fn tell(&self) -> u64 { self.pos as u64 } </ins> <del> fn seek(&mut self, _pos: i64, _style: SeekStyle) { fail!() } </del> <ins> fn seek(&mut self, pos: i64, style: SeekStyle) { // compute offset as signed and clamp to prevent overflow let offset = match style { SeekSet => { 0 } SeekEnd => { self.buf.len() } SeekCur => { self.pos } } as i64; self.pos = max(0, offset+pos) as uint; } </ins> }


} #[test] <ins> fn test_buf_writer() { let mut buf = [0 as u8, ..8]; { let mut writer = BufWriter::new(buf); assert_eq!(writer.tell(), 0); writer.write([0]); assert_eq!(writer.tell(), 1); writer.write([1, 2, 3]); writer.write([4, 5, 6, 7]); assert_eq!(writer.tell(), 8); } assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7]); } #[test] fn test_buf_writer_seek() { let mut buf = [0 as u8, ..8]; { let mut writer = BufWriter::new(buf); assert_eq!(writer.tell(), 0); writer.write([1]); assert_eq!(writer.tell(), 1); writer.seek(2, SeekSet); assert_eq!(writer.tell(), 2); writer.write([2]); assert_eq!(writer.tell(), 3); writer.seek(-2, SeekCur); assert_eq!(writer.tell(), 1); writer.write([3]); assert_eq!(writer.tell(), 2); writer.seek(-1, SeekEnd); assert_eq!(writer.tell(), 7); writer.write([4]); assert_eq!(writer.tell(), 8); } assert_eq!(buf, [1, 3, 2, 0, 0, 0, 0, 4]); } #[test] fn test_buf_writer_error() { let mut buf = [0 as u8, ..2]; let mut writer = BufWriter::new(buf); writer.write([0]); let mut called = false; do io_error::cond.trap(|err| { assert_eq!(err.kind, OtherIoError); called = true; }).inside { writer.write([0, 0]); } assert!(called); } #[test] </ins> fn test_mem_reader() { let mut reader = MemReader::new(~[0, 1, 2, 3, 4, 5, 6, 7]); let mut buf = [];


let tcx = self.infcx.tcx; // Try to find predicates on *generic params* that would allow copying `ty` let infcx = tcx.infer_ctxt().build(); <del> if infcx .type_implements_trait( tcx.lang_items().clone_trait().unwrap(), [tcx.erase_regions(ty)], self.param_env, ) .must_apply_modulo_regions() </del> <ins> if let Some(clone_trait_def) = tcx.lang_items().clone_trait() && infcx .type_implements_trait( clone_trait_def, [tcx.erase_regions(ty)], self.param_env, ) .must_apply_modulo_regions() </ins> { err.span_suggestion_verbose( span.shrink_to_hi(),


<ins> // Avoid panicking if the Clone trait is not found while building error suggestions // See #104870 #![feature(no_core, lang_items)] #![no_core] #[lang = "sized"] trait Sized {} #[lang = "copy"] trait Copy {} fn g<T>(x: T) {} fn f(x: *mut u8) { g(x); g(x); //~ ERROR use of moved value: `x` } fn main() {} </ins>


<ins> error[E0382]: use of moved value: `x` --> $DIR/missing-clone-for-suggestion.rs:17:7 | LL | fn f(x: *mut u8) { |      - move occurs because `x` has type `*mut u8`, which does not implement the `Copy` trait LL |     g(x); |       - value moved here LL |     g(x); |       ^ value used here after move | note: consider changing this parameter type in function `g` to borrow instead if owning the value isn't necessary --> $DIR/missing-clone-for-suggestion.rs:13:12 | LL | fn g<T>(x: T) {} |    -       ^ this parameter takes ownership of the value |    | |    in this function error: aborting due to previous error For more information about this error, try `rustc --explain E0382`. </ins>


)); } <ins> // FIXME: remove the suggestions that are from derive, as the span is not correct suggestions = suggestions .into_iter() .filter(|(span, _, _)| !span.in_derive_expansion()) .collect::<Vec<_>>(); </ins> if suggestions.len() == 1 { let (span, suggestion, msg) = suggestions.pop().unwrap();


<ins> // force-host // no-prefer-dynamic #![crate_type = "proc-macro"] extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro_derive(AddImpl)] pub fn derive(input: TokenStream) -> TokenStream { "use std::cmp::Ordering; impl<T> Ord for PriorityQueue<T> { fn cmp(&self, other: &Self) -> Ordering { self.0.cmp(&self.height) } } " .parse() .unwrap() } </ins>


<ins> // aux-build:issue-104884.rs use std::collections::BinaryHeap; #[macro_use] extern crate issue_104884; #[derive(PartialEq, Eq, PartialOrd, Ord)] struct PriorityQueueEntry<T> { value: T, } #[derive(PartialOrd, AddImpl)] //~^ ERROR can't compare `PriorityQueue<T>` with `PriorityQueue<T>` //~| ERROR the trait bound `PriorityQueue<T>: Eq` is not satisfied //~| ERROR can't compare `T` with `T` struct PriorityQueue<T>(BinaryHeap<PriorityQueueEntry<T>>); fn main() {} </ins>


<ins> error[E0277]: can't compare `PriorityQueue<T>` with `PriorityQueue<T>` --> $DIR/issue-104884-trait-impl-sugg-err.rs:13:10 | LL | #[derive(PartialOrd, AddImpl)] |          ^^^^^^^^^^ no implementation for `PriorityQueue<T> == PriorityQueue<T>` | = help: the trait `PartialEq` is not implemented for `PriorityQueue<T>` note: required by a bound in `PartialOrd` --> $SRC_DIR/core/src/cmp.rs:LL:COL | LL | pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> { |                                           ^^^^^^^^^^^^^^ required by this bound in `PartialOrd` = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `PriorityQueue<T>: Eq` is not satisfied --> $DIR/issue-104884-trait-impl-sugg-err.rs:13:22 | LL | #[derive(PartialOrd, AddImpl)] |                      ^^^^^^^ the trait `Eq` is not implemented for `PriorityQueue<T>` | note: required by a bound in `Ord` --> $SRC_DIR/core/src/cmp.rs:LL:COL | LL | pub trait Ord: Eq + PartialOrd<Self> { |                ^^ required by this bound in `Ord` = note: this error originates in the derive macro `AddImpl` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: can't compare `T` with `T` --> $DIR/issue-104884-trait-impl-sugg-err.rs:13:22 | LL | #[derive(PartialOrd, AddImpl)] |                      ^^^^^^^ no implementation for `T < T` and `T > T` | note: required for `PriorityQueue<T>` to implement `PartialOrd` --> $DIR/issue-104884-trait-impl-sugg-err.rs:13:10 | LL | #[derive(PartialOrd, AddImpl)] |          ^^^^^^^^^^ note: required by a bound in `Ord` --> $SRC_DIR/core/src/cmp.rs:LL:COL | LL | pub trait Ord: Eq + PartialOrd<Self> { |                     ^^^^^^^^^^^^^^^^ required by this bound in `Ord` = note: this error originates in the derive macro `AddImpl` which comes from the expansion of the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0277`. </ins>


//! OS-specific networking functionality. <ins> // See cfg macros in `library/std/src/os/mod.rs` for why these platforms must // be special-cased during rustdoc generation. #[cfg(not(all( doc, any( all(target_arch = "wasm32", not(target_os = "wasi")), all(target_vendor = "fortanix", target_env = "sgx") ) )))] </ins> #[cfg(any(target_os = "linux", target_os = "android", doc))] pub(super) mod linux_ext;


// Use `||` to give these suggestions a precedence let _ = self.suggest_missing_parentheses(err, expr) <ins> || self.suggest_remove_last_method_call(err, expr, expected) </ins> || self.suggest_associated_const(err, expr, expected) || self.suggest_deref_ref_or_into(err, expr, expected, expr_ty, expected_ty_expr) || self.suggest_option_to_bool(err, expr, expr_ty, expected)


} } <ins> pub fn suggest_remove_last_method_call( &self, err: &mut Diagnostic, expr: &hir::Expr<'tcx>, expected: Ty<'tcx>, ) -> bool { if let hir::ExprKind::MethodCall(hir::PathSegment { ident: method, .. }, recv_expr, &[], _) = expr.kind && let Some(recv_ty) = self.typeck_results.borrow().expr_ty_opt(recv_expr) && self.can_coerce(recv_ty, expected) { let span = if let Some(recv_span) = recv_expr.span.find_ancestor_inside(expr.span) { expr.span.with_lo(recv_span.hi()) } else { expr.span.with_lo(method.span.lo() - rustc_span::BytePos(1)) }; err.span_suggestion_verbose( span, "try removing the method call", "", Applicability::MachineApplicable, ); return true; } false } </ins> pub fn suggest_deref_ref_or_into( &self, err: &mut Diagnostic,


<ins> fn test1() { let _v: i32 = (1 as i32).to_string(); //~ ERROR mismatched types // won't suggestion let _v: i32 = (1 as i128).to_string(); //~ ERROR mismatched types let _v: &str = "foo".to_string(); //~ ERROR mismatched types } fn test2() { let mut path: String = "/usr".to_string(); let folder: String = "lib".to_string(); path = format!("{}/{}", path, folder).as_str(); //~ ERROR mismatched types println!("{}", &path); } fn main() { test1(); test2(); } </ins>


<ins> error[E0308]: mismatched types --> $DIR/issue-105494.rs:2:19 | LL |     let _v: i32 = (1 as i32).to_string(); |             ---   ^^^^^^^^^^^^^^^^^^^^^^ expected `i32`, found struct `String` |             | |             expected due to this | help: try removing the method call | LL -     let _v: i32 = (1 as i32).to_string(); LL +     let _v: i32 = (1 as i32); | error[E0308]: mismatched types --> $DIR/issue-105494.rs:5:19 | LL |     let _v: i32 = (1 as i128).to_string(); |             ---   ^^^^^^^^^^^^^^^^^^^^^^^ expected `i32`, found struct `String` |             | |             expected due to this error[E0308]: mismatched types --> $DIR/issue-105494.rs:7:20 | LL |     let _v: &str = "foo".to_string(); |             ----   ^^^^^^^^^^^^^^^^^ expected `&str`, found struct `String` |             | |             expected due to this | help: try removing the method call | LL -     let _v: &str = "foo".to_string(); LL +     let _v: &str = "foo"; | error[E0308]: mismatched types --> $DIR/issue-105494.rs:14:12 | LL |     let mut path: String = "/usr".to_string(); |                   ------ expected due to this type ... LL |     path = format!("{}/{}", path, folder).as_str(); |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `String`, found `&str` | help: try removing the method call | LL -     path = format!("{}/{}", path, folder).as_str(); LL +     path = format!("{}/{}", path, folder); | error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0308`. </ins>


) -> OperandRef<'tcx, Bx::Value> { let tcx = bx.tcx(); <del> let mut span_to_caller_location = |span: Span| { </del> <ins> let mut span_to_caller_location = |mut span: Span| { // Remove `Inlined` marks as they pollute `expansion_cause`. while span.is_inlined() { span.remove_mark(); } </ins> let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span); let caller = tcx.sess.source_map().lookup_char_pos(topmost.lo()); let const_loc = tcx.const_caller_location((


location } <del> pub(crate) fn location_triple_for_span(&self, span: Span) -> (Symbol, u32, u32) { </del> <ins> pub(crate) fn location_triple_for_span(&self, mut span: Span) -> (Symbol, u32, u32) { // Remove `Inlined` marks as they pollute `expansion_cause`. while span.is_inlined() { span.remove_mark(); } </ins> let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span); let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo()); (


pub fn fresh_expansion(self, expn_id: LocalExpnId) -> Span { HygieneData::with(|data| { self.with_ctxt(data.apply_mark( <del> SyntaxContext::root(), </del> <ins> self.ctxt(), </ins> expn_id.to_expn_id(), Transparency::Transparent, ))


// run-pass // revisions: default mir-opt <ins> //[default] compile-flags: -Zinline-mir=no </ins> //[mir-opt] compile-flags: -Zmir-opt-level=4 macro_rules! caller_location_from_macro {


fn main() { let loc = core::panic::Location::caller(); assert_eq!(loc.file(), file!()); <del> assert_eq!(loc.line(), 10); </del> <ins> assert_eq!(loc.line(), 11); </ins> assert_eq!(loc.column(), 15); // `Location::caller()` in a macro should behave similarly to `file!` and `line!`, // i.e. point to where the macro was invoked, instead of the macro itself. let loc2 = caller_location_from_macro!(); assert_eq!(loc2.file(), file!()); <del> assert_eq!(loc2.line(), 17); </del> <ins> assert_eq!(loc2.line(), 18); </ins> assert_eq!(loc2.column(), 16); }


<ins> // run-pass // revisions: default mir-opt //[default] compile-flags: -Zinline-mir=no //[mir-opt] compile-flags: -Zmir-opt-level=4 use std::panic::Location; macro_rules! f { () => { Location::caller() }; } #[inline(always)] fn g() -> &'static Location<'static> { f!() } fn main() { let loc = g(); assert_eq!(loc.line(), 16); assert_eq!(loc.column(), 5); } </ins>


}); } else { debug_assert!(self.tcx.is_trait(trait_def_id)); <ins> if self.tcx.trait_is_auto(trait_def_id) { return; } </ins> for item in self.impl_or_trait_item(trait_def_id) { // Check whether `trait_def_id` defines a method with suitable name. if !self.has_applicable_self(&item) {


_ => false, } }) && (type_is_local || info.def_id.is_local()) <ins> && !self.tcx.trait_is_auto(info.def_id) </ins> && self .associated_value(info.def_id, item_name) .filter(|item| {


trait Bar { fn f(&self) { <del> self.g(); //~ ERROR the method `g` exists for reference `&Self`, but its trait bounds were not satisfied </del> <ins> // issue #105788 self.g(); //~ ERROR no method named `g` found for reference `&Self` in the current scope </ins> } }


LL |     fn g(&self); |     ---^-------- help: remove these associated items <del> error[E0599]: the method `g` exists for reference `&Self`, but its trait bounds were not satisfied --> $DIR/issue-105732.rs:9:14 </del> <ins> error[E0599]: no method named `g` found for reference `&Self` in the current scope --> $DIR/issue-105732.rs:10:14 </ins> | LL |         self.g(); <del> |              ^ | = note: the following trait bounds were not satisfied: `Self: Foo` which is required by `&Self: Foo` `&Self: Foo` = help: items from traits can only be used if the type parameter is bounded by the trait help: the following trait defines an item `g`, perhaps you need to add a supertrait for it: | LL | trait Bar: Foo { |          +++++ </del> <ins> |              ^ help: there is a method with a similar name: `f` </ins> error: aborting due to 2 previous errors


); for virtual_dir in virtual_rust_source_base_dir.iter().flatten() { <del> if let Some(real_dir) = &sess.opts.real_rust_source_base_dir { if let rustc_span::FileName::Real(old_name) = name { if let rustc_span::RealFileName::Remapped { local_path: _, virtual_name } = old_name { if let Ok(rest) = virtual_name.strip_prefix(virtual_dir) { let virtual_name = virtual_name.clone(); // The std library crates are in // `$sysroot/lib/rustlib/src/rust/library`, whereas other crates // may be in `$sysroot/lib/rustlib/src/rust/` directly. So we // detect crates from the std libs and handle them specially. const STD_LIBS: &[&str] = &[ "core", "alloc", "std", "test", "term", "unwind", "proc_macro", "panic_abort", "panic_unwind", "profiler_builtins", "rtstartup", "rustc-std-workspace-core", "rustc-std-workspace-alloc", "rustc-std-workspace-std", "backtrace", ]; let is_std_lib = STD_LIBS.iter().any(|l| rest.starts_with(l)); let new_path = if is_std_lib { real_dir.join("library").join(rest) } else { real_dir.join(rest) }; debug!( "try_to_translate_virtual_to_real: `{}` -> `{}`", virtual_name.display(), new_path.display(), ); let new_name = rustc_span::RealFileName::Remapped { local_path: Some(new_path), virtual_name, }; *old_name = new_name; } </del> <ins> if let Some(real_dir) = &sess.opts.real_rust_source_base_dir && let rustc_span::FileName::Real(old_name) = name && let rustc_span::RealFileName::Remapped { local_path: _, virtual_name } = old_name && let Ok(rest) = virtual_name.strip_prefix(virtual_dir) { // The std library crates are in // `$sysroot/lib/rustlib/src/rust/library`, whereas other crates // may be in `$sysroot/lib/rustlib/src/rust/` directly. So we // detect crates from the std libs and handle them specially. const STD_LIBS: &[&str] = &[ "core", "alloc", "std", "test", "term", "unwind", "proc_macro", "panic_abort", "panic_unwind", "profiler_builtins", "rtstartup", "rustc-std-workspace-core", "rustc-std-workspace-alloc", "rustc-std-workspace-std", "backtrace", ]; let is_std_lib = STD_LIBS.iter().any(|l| rest.starts_with(l)); let new_path = if is_std_lib { real_dir.join("library").join(rest) } else { real_dir.join(rest) }; debug!( "try_to_translate_virtual_to_real: `{}` -> `{}`", virtual_name.display(), new_path.display(), ); // Check if the translated real path is affected by any user-requested // remaps via --remap-path-prefix. Apply them if so. // Note that this is a special case for imported rust-src paths specified by // https://rust-lang.github.io/rfcs/3127-trim-paths.html#handling-sysroot-paths. // Other imported paths are not currently remapped (see #66251). let (user_remapped, applied) = sess.source_map().path_mapping().map_prefix(&new_path); let new_name = if applied { rustc_span::RealFileName::Remapped { local_path: Some(new_path.clone()), virtual_name: user_remapped.to_path_buf(), </ins> } <del> } </del> <ins> } else { rustc_span::RealFileName::LocalPath(new_path) }; *old_name = new_name; </ins> } } };


const CWD: &str = "{{cwd}}"; const SRC_BASE: &str = "{{src-base}}"; const BUILD_BASE: &str = "{{build-base}}"; <ins> const RUST_SRC_BASE: &str = "{{rust-src-base}}"; </ins> const SYSROOT_BASE: &str = "{{sysroot-base}}"; const TARGET_LINKER: &str = "{{target-linker}}"; const TARGET: &str = "{{target}}";


value = value.replace(TARGET, &config.target); } <ins> if value.contains(RUST_SRC_BASE) { let src_base = config.sysroot_base.join("lib/rustlib/src/rust"); src_base.try_exists().expect(&*format!("{} should exists", src_base.display())); let src_base = src_base.read_link().unwrap_or(src_base); value = value.replace(RUST_SRC_BASE, &src_base.to_string_lossy()); } </ins> value }


} let base_dir = Path::new("/rustc/FAKE_PREFIX"); <del> // Paths into the libstd/libcore </del> <ins> // Fake paths into the libstd/libcore </ins> normalize_path(&base_dir.join("library"), "$SRC_DIR"); // `ui-fulldeps` tests can show paths to the compiler source when testing macros from // `rustc_macros` // eg. /home/user/rust/compiler normalize_path(&base_dir.join("compiler"), "$COMPILER_DIR"); <ins> // Real paths into the libstd/libcore let rust_src_dir = &self.config.sysroot_base.join("lib/rustlib/src/rust"); rust_src_dir.try_exists().expect(&*format!("{} should exists", rust_src_dir.display())); let rust_src_dir = rust_src_dir.read_link().unwrap_or(rust_src_dir.to_path_buf()); normalize_path(&rust_src_dir.join("library"), "$SRC_DIR_REAL"); </ins> // Paths into the build directory let test_build_dir = &self.config.build_base; let parent_build_dir = test_build_dir.parent().unwrap().parent().unwrap().parent().unwrap();


// eg. /home/user/rust/build normalize_path(parent_build_dir, "$BUILD_DIR"); <del> // Paths into lib directory. normalize_path(&parent_build_dir.parent().unwrap().join("lib"), "$LIB_DIR"); </del> if json { // escaped newlines in json strings should be readable // in the stderr files. There's no point int being correct,


<ins> //@ revisions: with-remap without-remap //@ compile-flags: -g -Ztranslate-remapped-path-to-local-path=yes //@ [with-remap]compile-flags: --remap-path-prefix={{rust-src-base}}=remapped //@ [with-remap]compile-flags: --remap-path-prefix={{src-base}}=remapped-tests-ui //@ [without-remap]compile-flags: //@ error-pattern: E0507 // The $SRC_DIR*.rs:LL:COL normalisation doesn't kick in automatically // as the remapped revision will not begin with $SRC_DIR_REAL, // so we have to do it ourselves. //@ normalize-stderr-test: ".rs:d+:d+" -> ".rs:LL:COL" use std::thread; struct Worker { thread: thread::JoinHandle<()>, } impl Drop for Worker { fn drop(&mut self) { self.thread.join().unwrap(); } } pub fn main(){} </ins>


<ins> error[E0507]: cannot move out of `self.thread` which is behind a mutable reference --> remapped-tests-ui/errors/remap-path-prefix-sysroot.rs:LL:COL | LL |         self.thread.join().unwrap(); |         ^^^^^^^^^^^ ------ `self.thread` moved due to this method call |         | |         move occurs because `self.thread` has type `JoinHandle<()>`, which does not implement the `Copy` trait | note: `JoinHandle::<T>::join` takes ownership of the receiver `self`, which moves `self.thread` --> remapped/library/std/src/thread/mod.rs:LL:COL | LL |     pub fn join(self) -> Result<T> { |                 ^^^^ error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0507`. </ins>


<ins> error[E0507]: cannot move out of `self.thread` which is behind a mutable reference --> $DIR/remap-path-prefix-sysroot.rs:LL:COL | LL |         self.thread.join().unwrap(); |         ^^^^^^^^^^^ ------ `self.thread` moved due to this method call |         | |         move occurs because `self.thread` has type `JoinHandle<()>`, which does not implement the `Copy` trait | note: `JoinHandle::<T>::join` takes ownership of the receiver `self`, which moves `self.thread` --> $SRC_DIR_REAL/std/src/thread/mod.rs:LL:COL | LL |     pub fn join(self) -> Result<T> { |                 ^^^^ error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0507`. </ins>


|| self.suggest_boxing_when_appropriate(err, expr, expected, expr_ty) || self.suggest_block_to_brackets_peeling_refs(err, expr, expr_ty, expected) || self.suggest_copied_or_cloned(err, expr, expr_ty, expected) <ins> || self.suggest_clone_for_ref(err, expr, expr_ty, expected) </ins> || self.suggest_into(err, expr, expr_ty, expected) || self.suggest_floating_point_literal(err, expr, expected); if !suggested {


} } <ins> pub(crate) fn suggest_clone_for_ref( &self, diag: &mut Diagnostic, expr: &hir::Expr<'_>, expr_ty: Ty<'tcx>, expected_ty: Ty<'tcx>, ) -> bool { if let ty::Ref(_, inner_ty, hir::Mutability::Not) = expr_ty.kind() && let Some(clone_trait_def) = self.tcx.lang_items().clone_trait() && expected_ty == *inner_ty && self .infcx .type_implements_trait( clone_trait_def, [self.tcx.erase_regions(expected_ty)], self.param_env ) .must_apply_modulo_regions() { diag.span_suggestion_verbose( expr.span.shrink_to_hi(), "consider using clone here", ".clone()", Applicability::MachineApplicable, ); return true; } false } </ins> pub(crate) fn suggest_copied_or_cloned( &self, diag: &mut Diagnostic,


); } <ins> if self.suggest_add_clone_to_arg(&obligation, &mut err, trait_predicate) { err.emit(); return; } </ins> if self.suggest_impl_trait(&mut err, span, &obligation, trait_predicate) { err.emit(); return;


use crate::traits::{NormalizeExt, ObligationCtxt}; use hir::def::CtorOf; <del> use hir::HirId; </del> <ins> use hir::{Expr, HirId}; </ins> use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_errors::{


trait_pred: ty::PolyTraitPredicate<'tcx>, ); <ins> fn suggest_add_clone_to_arg( &self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic, trait_pred: ty::PolyTraitPredicate<'tcx>, ) -> bool; </ins> fn suggest_add_reference_to_arg( &self, obligation: &PredicateObligation<'tcx>,


} } <ins> fn suggest_add_clone_to_arg( &self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic, trait_pred: ty::PolyTraitPredicate<'tcx>, ) -> bool { let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty()); let ty = self.tcx.erase_late_bound_regions(self_ty); let owner = self.tcx.hir().get_parent_item(obligation.cause.body_id); let Some(generics) = self.tcx.hir().get_generics(owner.def_id) else { return false }; let ty::Ref(_, inner_ty, hir::Mutability::Not) = ty.kind() else { return false }; let ty::Param(param) = inner_ty.kind() else { return false }; let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = obligation.cause.code() else { return false }; let arg_node = self.tcx.hir().get(*arg_hir_id); let Node::Expr(Expr { kind: hir::ExprKind::Path(_), ..}) = arg_node else { return false }; let clone_trait = self.tcx.require_lang_item(LangItem::Clone, None); let has_clone = |ty| { self.type_implements_trait(clone_trait, [ty], obligation.param_env) .must_apply_modulo_regions() }; let new_obligation = self.mk_trait_obligation_with_new_self_ty( obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, *inner_ty)), ); if self.predicate_may_hold(&new_obligation) && has_clone(ty) { if !has_clone(param.to_ty(self.tcx)) { suggest_constraining_type_param( self.tcx, generics, err, param.name.as_str(), "Clone", Some(clone_trait), ); } err.span_suggestion_verbose( obligation.cause.span.shrink_to_hi(), "consider using clone here", ".clone()".to_string(), Applicability::MaybeIncorrect, ); return true; } false } </ins> fn suggest_add_reference_to_arg( &self, obligation: &PredicateObligation<'tcx>,


<ins> #[derive(Clone)] struct S; // without Clone struct T; fn foo(_: S) {} fn test1() { let s = &S; foo(s); //~ ERROR mismatched types } fn bar(_: T) {} fn test2() { let t = &T; bar(t); //~ ERROR mismatched types } fn main() { test1(); test2(); } </ins>


<ins> error[E0308]: mismatched types --> $DIR/issue-106443-sugg-clone-for-arg.rs:11:9 | LL |     foo(s); |     --- ^ expected struct `S`, found `&S` |     | |     arguments to this function are incorrect | note: function defined here --> $DIR/issue-106443-sugg-clone-for-arg.rs:7:4 | LL | fn foo(_: S) {} |    ^^^ ---- help: consider using clone here | LL |     foo(s.clone()); |          ++++++++ error[E0308]: mismatched types --> $DIR/issue-106443-sugg-clone-for-arg.rs:17:9 | LL |     bar(t); |     --- ^ expected struct `T`, found `&T` |     | |     arguments to this function are incorrect | note: function defined here --> $DIR/issue-106443-sugg-clone-for-arg.rs:14:4 | LL | fn bar(_: T) {} |    ^^^ ---- error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0308`. </ins>


<ins> #[derive(Clone)] struct S; trait X {} impl X for S {} fn foo<T: X>(_: T) {} fn bar<T: X>(s: &T) { foo(s); //~ ERROR the trait bound `&T: X` is not satisfied } fn bar_with_clone<T: X + Clone>(s: &T) { foo(s); //~ ERROR the trait bound `&T: X` is not satisfied } fn main() { let s = &S; bar(s); } </ins>


<ins> error[E0277]: the trait bound `&T: X` is not satisfied --> $DIR/issue-106443-sugg-clone-for-bound.rs:10:9 | LL |     foo(s); |         ^ the trait `X` is not implemented for `&T` | help: consider further restricting this bound | LL | fn bar<T: X + Clone>(s: &T) { |             +++++++ help: consider using clone here | LL |     foo(s.clone()); |          ++++++++ error[E0277]: the trait bound `&T: X` is not satisfied --> $DIR/issue-106443-sugg-clone-for-bound.rs:14:9 | LL |     foo(s); |         ^ the trait `X` is not implemented for `&T` | help: consider using clone here | LL |     foo(s.clone()); |          ++++++++ error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0277`. </ins>


names: FxHashMap<Symbol, usize>, } <del> // FIXME: Rustdoc has trouble proving Send/Sync for this. See #106930. #[cfg(parallel_compiler)] unsafe impl Sync for FormatArguments {} #[cfg(parallel_compiler)] unsafe impl Send for FormatArguments {} </del> impl FormatArguments { pub fn new() -> Self { Self {


cx: &mut DocContext<'_>, item_def_id: DefId, ) -> impl Iterator<Item = Item> { <del> // FIXME: To be removed once `parallel_compiler` bugs are fixed! // More information in <https://github.com/rust-lang/rust/pull/106930>. if cfg!(parallel_compiler) { return vec![].into_iter().chain(vec![].into_iter()); } </del> let auto_impls = cx .sess() .prof


use rustc_middle::ty::TyCtxt; pub fn check_crate(tcx: TyCtxt<'_>) { <del> tcx.dep_graph.assert_ignored(); </del> if tcx.sess.opts.unstable_opts.hir_stats { crate::hir_stats::print_hir_stats(tcx); }


assert_eq!(_green_node_index, DepNodeIndex::SINGLETON_DEPENDENCYLESS_ANON_NODE); // Instantiate a dependy-less red node only once for anonymous queries. <del> let (_red_node_index, _prev_and_index) = current.intern_node( </del> <ins> let (red_node_index, red_node_prev_index_and_color) = current.intern_node( </ins> profiler, &prev_graph, DepNode { kind: DepKind::RED, hash: Fingerprint::ZERO.into() },


None, false, ); <del> assert_eq!(_red_node_index, DepNodeIndex::FOREVER_RED_NODE); assert!(matches!(_prev_and_index, None | Some((_, DepNodeColor::Red)))); </del> <ins> assert_eq!(red_node_index, DepNodeIndex::FOREVER_RED_NODE); match red_node_prev_index_and_color { None => { // This is expected when we have no previous compilation session. assert!(prev_graph_node_count == 0); } Some((prev_red_node_index, DepNodeColor::Red)) => { assert_eq!(prev_red_node_index.as_usize(), red_node_index.as_usize()); colors.insert(prev_red_node_index, DepNodeColor::Red); } Some((_, DepNodeColor::Green(_))) => { // There must be a logic error somewhere if we hit this branch. panic!("DepNodeIndex::FOREVER_RED_NODE evaluated to DepNodeColor::Green") } } </ins> DepGraph { data: Some(Lrc::new(DepGraphData {


})) }; <del> let task_deps_ref = match &task_deps { Some(deps) => TaskDepsRef::Allow(deps), None => TaskDepsRef::Ignore, }; </del> <ins> let task_deps_ref = task_deps.as_ref().map(TaskDepsRef::Allow).unwrap_or(TaskDepsRef::EvalAlways); </ins> let result = K::with_deps(task_deps_ref, || task(cx, arg)); let edges = task_deps.map_or_else(|| smallvec![], |lock| lock.into_inner().reads);


K::read_deps(|task_deps| { let mut task_deps = match task_deps { TaskDepsRef::Allow(deps) => deps.lock(), <ins> TaskDepsRef::EvalAlways => { // We don't need to record dependencies of eval_always // queries. They are re-evaluated unconditionally anyway. return; } </ins> TaskDepsRef::Ignore => return, TaskDepsRef::Forbid => { panic!("Illegal read of: {dep_node_index:?}")


let mut edges = SmallVec::new(); K::read_deps(|task_deps| match task_deps { TaskDepsRef::Allow(deps) => edges.extend(deps.lock().reads.iter().copied()), <del> TaskDepsRef::Ignore => {} // During HIR lowering, we have no dependencies. </del> <ins> TaskDepsRef::EvalAlways => { edges.push(DepNodeIndex::FOREVER_RED_NODE); } TaskDepsRef::Ignore => {} </ins> TaskDepsRef::Forbid => { panic!("Cannot summarize when dependencies are not recorded.") }


/// `TaskDeps`. This is used when executing a 'normal' query /// (no `eval_always` modifier) Allow(&'a Lock<TaskDeps<K>>), <del> /// New dependencies are ignored. This is used when /// executing an `eval_always` query, since there's no </del> <ins> /// This is used when executing an `eval_always` query. We don't </ins> /// need to track dependencies for a query that's always <del> /// re-executed. This is also used for `dep_graph.with_ignore` </del> <ins> /// re-executed -- but we need to know that this is an `eval_always` /// query in order to emit dependencies to `DepNodeIndex::FOREVER_RED_NODE` /// when directly feeding other queries. EvalAlways, /// New dependencies are ignored. This is also used for `dep_graph.with_ignore`. </ins> Ignore, /// Any attempt to add new dependencies will cause a panic. /// This is used when decoding a query result from disk,


<ins> // revisions: cpass1 cpass2 #![crate_type = "rlib"] use std::fmt::Debug; // MCVE kindly provided by Nilstrieb at // https://github.com/rust-lang/rust/issues/108481#issuecomment-1493080185 #[derive(Debug)] pub struct ConstGeneric<const CHUNK_SIZE: usize> { _p: [(); CHUNK_SIZE], } #[cfg(cpass1)] impl<const CHUNK_SIZE: usize> ConstGeneric<CHUNK_SIZE> {} </ins>


self.draw_code_line( &mut buffer, &mut row_num, <del> &Vec::new(), </del> <ins> &[], </ins> p + line_start, l, show_code_change,


self.draw_code_line( &mut buffer, &mut row_num, <del> highlight_parts, </del> <ins> &highlight_parts, </ins> line_pos + line_start, line, show_code_change,


&self, buffer: &mut StyledBuffer, row_num: &mut usize, <del> highlight_parts: &Vec<SubstitutionHighlight>, </del> <ins> highlight_parts: &[SubstitutionHighlight], </ins> line_num: usize, line_to_add: &str, show_code_change: DisplaySuggestion,


}); buf.push_str(&part.snippet); let cur_hi = sm.lookup_char_pos(part.span.hi()); <del> if prev_hi.line == cur_lo.line && cur_hi.line == cur_lo.line { </del> <ins> if cur_hi.line == cur_lo.line { </ins> // Account for the difference between the width of the current code and the // snippet being suggested, so that the *later* suggestions are correctly // aligned on the screen.


<ins> // compile-flags: --error-format=human --color=always // ignore-windows fn short(foo_bar: &Vec<&i32>) -> &i32 { //~ ERROR missing lifetime specifier &12 } fn long( //~ ERROR missing lifetime specifier foo_bar: &Vec<&i32>, something_very_long_so_that_the_line_will_wrap_around__________: i32, ) -> &i32 { &12 } fn long2( //~ ERROR missing lifetime specifier foo_bar: &Vec<&i32>) -> &i32 { &12 } fn main() {} </ins>


<ins> error[E0106]: missing lifetime specifier   --> $DIR/multiline-multipart-suggestion.rs:4:34    | LL | fn short(foo_bar: &Vec<&i32>) -> &i32 {    |                   ----------     ^ expected named lifetime parameter    |    = help: this function's return type contains a borrowed value, but the signature does not say which one of `foo_bar`'s 2 lifetimes it is borrowed from help: consider introducing a named lifetime parameter    | LL | fn short<'a>(foo_bar: &'a Vec<&'a i32>) -> &'a i32 {    |         ++++           ++      ++           ++ error[E0106]: missing lifetime specifier   --> $DIR/multiline-multipart-suggestion.rs:11:6    | LL |     foo_bar: &Vec<&i32>,    |              ---------- LL |     something_very_long_so_that_the_line_will_wrap_around__________: i32, LL | ) -> &i32 {    |      ^ expected named lifetime parameter    |    = help: this function's return type contains a borrowed value, but the signature does not say which one of `foo_bar`'s 2 lifetimes it is borrowed from help: consider introducing a named lifetime parameter    | LL ~ fn long<'a>( LL ~     foo_bar: &'a Vec<&'a i32>, LL |     something_very_long_so_that_the_line_will_wrap_around__________: i32, LL ~ ) -> &'a i32 {    | error[E0106]: missing lifetime specifier   --> $DIR/multiline-multipart-suggestion.rs:16:29    | LL |     foo_bar: &Vec<&i32>) -> &i32 {    |              ----------     ^ expected named lifetime parameter    |    = help: this function's return type contains a borrowed value, but the signature does not say which one of `foo_bar`'s 2 lifetimes it is borrowed from help: consider introducing a named lifetime parameter    | LL ~ fn long2<'a>( LL ~     foo_bar: &'a Vec<&'a i32>) -> &'a i32 {    | error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0106`. </ins>