) -> Result<&'tcx Layout, LayoutError<'tcx>> { use SavedLocalEligibility::*; let tcx = self.tcx; let subst_field = |ty: Ty<'tcx>| ty.subst(tcx, substs); <del> let info = tcx.generator_layout(def_id); </del> <ins> let info = match tcx.generator_layout(def_id) { None => return Err(LayoutError::Unknown(ty)), Some(info) => info, }; </ins> let (ineligible_locals, assignments) = self.generator_saved_local_eligibility(&info); // Build a prefix layout, including "promoting" all ineligible


self.trait_def(trait_def_id).has_auto_impl } <del> pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> { self.optimized_mir(def_id).generator_layout.as_ref().unwrap() </del> <ins> /// Returns layout of a generator. Layout might be unavailable if the /// generator is tainted by errors. pub fn generator_layout(self, def_id: DefId) -> Option<&'tcx GeneratorLayout<'tcx>> { self.optimized_mir(def_id).generator_layout.as_ref() </ins> } /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.


#[inline] pub fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range<VariantIdx> { // FIXME requires optimized MIR <del> let num_variants = tcx.generator_layout(def_id).variant_fields.len(); </del> <ins> let num_variants = tcx.generator_layout(def_id).unwrap().variant_fields.len(); </ins> VariantIdx::new(0)..VariantIdx::new(num_variants) }


def_id: DefId, tcx: TyCtxt<'tcx>, ) -> impl Iterator<Item = impl Iterator<Item = Ty<'tcx>> + Captures<'tcx>> { <del> let layout = tcx.generator_layout(def_id); </del> <ins> let layout = tcx.generator_layout(def_id).unwrap(); </ins> layout.variant_fields.iter().map(move |variant| { variant.iter().map(move |field| layout.field_tys[*field].subst(tcx, self.substs)) })


<ins> // Verifies that computing a layout of a generator tainted by type errors // doesn't ICE. Regression test for #80998. // // edition:2018 #![feature(type_alias_impl_trait)] use std::future::Future; pub struct Task<F: Future>(F); impl<F: Future> Task<F> { fn new() -> Self { todo!() } fn spawn(&self, _: impl FnOnce() -> F) { todo!() } } fn main() { async fn cb() { let a = Foo; //~ ERROR cannot find value `Foo` in this scope } type F = impl Future; // Check that statics are inhabited computes they layout. static POOL: Task<F> = Task::new(); Task::spawn(&POOL, || cb()); } </ins>


<ins> error[E0425]: cannot find value `Foo` in this scope --> $DIR/layout-error.rs:21:17 | LL |         let a = Foo; |                 ^^^ not found in this scope error: aborting due to previous error For more information about this error, try `rustc --explain E0425`. </ins>


debug!("exp_found {:?} terr {:?}", exp_found, terr); if let Some(exp_found) = exp_found { self.suggest_as_ref_where_appropriate(span, &exp_found, diag); <ins> self.suggest_accessing_field_where_appropriate(cause, &exp_found, diag); </ins> self.suggest_await_on_expect_found(cause, span, &exp_found, diag); }


} } <ins> fn suggest_accessing_field_where_appropriate( &self, cause: &ObligationCause<'tcx>, exp_found: &ty::error::ExpectedFound<Ty<'tcx>>, diag: &mut DiagnosticBuilder<'tcx>, ) { debug!( "suggest_accessing_field_where_appropriate(cause={:?}, exp_found={:?})", cause, exp_found ); if let ty::Adt(expected_def, expected_substs) = exp_found.expected.kind() { if expected_def.is_enum() { return; } if let Some((name, ty)) = expected_def .non_enum_variant() .fields .iter() .filter(|field| field.vis.is_accessible_from(field.did, self.tcx)) .map(|field| (field.ident.name, field.ty(self.tcx, expected_substs))) .find(|(_, ty)| ty::TyS::same_type(ty, exp_found.found)) { if let ObligationCauseCode::Pattern { span: Some(span), .. } = cause.code { if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) { let suggestion = if expected_def.is_struct() { format!("{}.{}", snippet, name) } else if expected_def.is_union() { format!("unsafe {{ {}.{} }}", snippet, name) } else { return; }; diag.span_suggestion( span, &format!( "you might have meant to use field `{}` of type `{}`", name, ty ), suggestion, Applicability::MaybeIncorrect, ); } } } } } </ins> /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate, /// suggests it. fn suggest_as_ref_where_appropriate(


<ins> // run-rustfix #![allow(dead_code)] struct A { b: B, } enum B { Fst, Snd, } union Foo { bar: u32, qux: f32, } fn main() { let a = A { b: B::Fst }; if let B::Fst = a.b {}; //~ ERROR mismatched types [E0308] //~^ HELP you might have meant to use field `b` of type `B` match a.b { //~^ HELP you might have meant to use field `b` of type `B` //~| HELP you might have meant to use field `b` of type `B` B::Fst => (), //~ ERROR mismatched types [E0308] B::Snd => (), //~ ERROR mismatched types [E0308] } let foo = Foo { bar: 42 }; match unsafe { foo.bar } { //~^ HELP you might have meant to use field `bar` of type `u32` 1u32 => (), //~ ERROR mismatched types [E0308] _ => (), } } </ins>


<ins> // run-rustfix #![allow(dead_code)] struct A { b: B, } enum B { Fst, Snd, } union Foo { bar: u32, qux: f32, } fn main() { let a = A { b: B::Fst }; if let B::Fst = a {}; //~ ERROR mismatched types [E0308] //~^ HELP you might have meant to use field `b` of type `B` match a { //~^ HELP you might have meant to use field `b` of type `B` //~| HELP you might have meant to use field `b` of type `B` B::Fst => (), //~ ERROR mismatched types [E0308] B::Snd => (), //~ ERROR mismatched types [E0308] } let foo = Foo { bar: 42 }; match foo { //~^ HELP you might have meant to use field `bar` of type `u32` 1u32 => (), //~ ERROR mismatched types [E0308] _ => (), } } </ins>


<ins> error[E0308]: mismatched types --> $DIR/field-access.rs:20:12 | LL |     Fst, |     --- unit variant defined here ... LL |     if let B::Fst = a {}; |            ^^^^^^   - this expression has type `A` |            | |            expected struct `A`, found enum `B` | help: you might have meant to use field `b` of type `B` | LL |     if let B::Fst = a.b {}; |                     ^^^ error[E0308]: mismatched types --> $DIR/field-access.rs:25:9 | LL |     Fst, |     --- unit variant defined here ... LL |     match a { |           - this expression has type `A` ... LL |         B::Fst => (), |         ^^^^^^ expected struct `A`, found enum `B` | help: you might have meant to use field `b` of type `B` | LL |     match a.b { |           ^^^ error[E0308]: mismatched types --> $DIR/field-access.rs:26:9 | LL |     Snd, |     --- unit variant defined here ... LL |     match a { |           - this expression has type `A` ... LL |         B::Snd => (), |         ^^^^^^ expected struct `A`, found enum `B` | help: you might have meant to use field `b` of type `B` | LL |     match a.b { |           ^^^ error[E0308]: mismatched types --> $DIR/field-access.rs:32:9 | LL |     match foo { |           --- this expression has type `Foo` LL | LL |         1u32 => (), |         ^^^^ expected union `Foo`, found `u32` | help: you might have meant to use field `bar` of type `u32` | LL |     match unsafe { foo.bar } { |           ^^^^^^^^^^^^^^^^^^ error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0308`. </ins>


FakeReadCause, Local, LocalDecl, LocalInfo, LocalKind, Location, Operand, Place, PlaceRef, ProjectionElem, Rvalue, Statement, StatementKind, Terminator, TerminatorKind, VarBindingForm, }; <del> use rustc_middle::ty::{self, suggest_constraining_type_param, Instance, Ty}; use rustc_span::{source_map::DesugaringKind, symbol::sym, Span}; </del> <ins> use rustc_middle::ty::{self, suggest_constraining_type_param, Ty, TypeFoldable}; use rustc_span::source_map::DesugaringKind; use rustc_span::symbol::sym; use rustc_span::Span; </ins> use crate::dataflow::drop_flag_effects; use crate::dataflow::indexes::{MoveOutIndex, MovePathIndex}; use crate::util::borrowck_errors; use crate::borrow_check::{ <del> borrow_set::BorrowData, prefixes::IsPrefixOf, InitializationRequiringAction, MirBorrowckCtxt, PrefixSet, WriteKind, </del> <ins> borrow_set::BorrowData, diagnostics::Instance, prefixes::IsPrefixOf, InitializationRequiringAction, MirBorrowckCtxt, PrefixSet, WriteKind, </ins> }; use super::{


if return_span != borrow_span { err.span_label(borrow_span, note); <ins> let tcx = self.infcx.tcx; let ty_params = ty::List::empty(); let return_ty = self.regioncx.universal_regions().unnormalized_output_ty; let return_ty = tcx.erase_regions(return_ty); // to avoid panics if !return_ty.has_infer_types() { if let Some(iter_trait) = tcx.get_diagnostic_item(sym::Iterator) { if tcx.type_implements_trait((iter_trait, return_ty, ty_params, self.param_env)) { if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(return_span) { err.span_suggestion_hidden( return_span, "use `.collect()` to allocate the iterator", format!("{}{}", snippet, ".collect::<Vec<_>>()"), Applicability::MaybeIncorrect, ); } } } } </ins> } Some(err)


message = "`{Self}` is not an iterator" )] #[doc(spotlight)] <ins> #[rustc_diagnostic_item = "Iterator"] </ins> #[must_use = "iterators are lazy and do nothing unless consumed"] pub trait Iterator { /// The type of the elements being iterated over.


<ins> // run-rustfix fn main() { let _ = vec![vec![0, 1], vec![2]] .into_iter() .map(|y| y.iter().map(|x| x + 1).collect::<Vec<_>>()) //~^ ERROR cannot return value referencing function parameter `y` .collect::<Vec<_>>(); } </ins>


<ins> // run-rustfix fn main() { let _ = vec![vec![0, 1], vec![2]] .into_iter() .map(|y| y.iter().map(|x| x + 1)) //~^ ERROR cannot return value referencing function parameter `y` .collect::<Vec<_>>(); } </ins>


<ins> error[E0515]: cannot return value referencing function parameter `y` --> $DIR/issue-81584.rs:5:22 | LL |             .map(|y| y.iter().map(|x| x + 1)) |                      -^^^^^^^^^^^^^^^^^^^^^^ |                      | |                      returns a value referencing data owned by the current function |                      `y` is borrowed here | = help: use `.collect()` to allocate the iterator error: aborting due to previous error For more information about this error, try `rustc --explain E0515`. </ins>


| |                   ------------------------------ temporary value created here LL | |     } | |_____^ returns a value referencing data owned by the current function <ins> | = help: use `.collect()` to allocate the iterator </ins> error: aborting due to 4 previous errors


ctrl = table.GetChildMemberWithName("ctrl").GetChildAtIndex(0) self.size = table.GetChildMemberWithName("items").GetValueAsUnsigned() <del> self.pair_type = table.type.template_args[0].GetTypedefedType() </del> <ins> self.pair_type = table.type.template_args[0] if self.pair_type.IsTypedefType(): self.pair_type = self.pair_type.GetTypedefedType() </ins> self.pair_type_size = self.pair_type.GetByteSize() self.new_layout = not table.GetChildMemberWithName("data").IsValid()


} let mut completed_test = res.unwrap(); <del> let running_test = running_tests.remove(&completed_test.desc).unwrap(); if let Some(join_handle) = running_test.join_handle { if let Err(_) = join_handle.join() { if let TrOk = completed_test.result { completed_test.result = TrFailedMsg("panicked after reporting success".to_string()); </del> <ins> if let Some(running_test) = running_tests.remove(&completed_test.desc) { if let Some(join_handle) = running_test.join_handle { if let Err(_) = join_handle.join() { if let TrOk = completed_test.result { completed_test.result = TrFailedMsg("panicked after reporting success".to_string()); } </ins> } } }


| GenericArgKind::Const(_), _, ) => { <del> // I *think* that HIR lowering should ensure this // doesn't happen, even in erroneous // programs. Else we should use delay-span-bug. span_bug!( </del> <ins> // HIR lowering sometimes doesn't catch this in erroneous // programs, so we need to use delay_span_bug here. See #82126. self.infcx.tcx.sess.delay_span_bug( </ins> hir_arg.span(), <del> "unmatched subst and hir arg: found {:?} vs {:?}", kind, hir_arg, </del> <ins> &format!("unmatched subst and hir arg: found {:?} vs {:?}", kind, hir_arg), </ins> ); } }


<ins> // Regression test for #82126. Checks that mismatched lifetimes and types are // properly handled. // edition:2018 use std::sync::Mutex; struct MarketMultiplier {} impl MarketMultiplier { fn buy(&mut self) -> &mut usize { todo!() } } async fn buy_lock(generator: &Mutex<MarketMultiplier>) -> LockedMarket<'_> { //~^ ERROR this struct takes 0 lifetime arguments but 1 lifetime argument was supplied //~^^ ERROR this struct takes 1 type argument but 0 type arguments were supplied LockedMarket(generator.lock().unwrap().buy()) //~^ ERROR cannot return value referencing temporary value } struct LockedMarket<T>(T); fn main() {} </ins>


<ins> error[E0107]: this struct takes 0 lifetime arguments but 1 lifetime argument was supplied --> $DIR/issue-82126-mismatched-subst-and-hir.rs:16:59 | LL | async fn buy_lock(generator: &Mutex<MarketMultiplier>) -> LockedMarket<'_> { |                                                           ^^^^^^^^^^^^---- help: remove these generics |                                                           | |                                                           expected 0 lifetime arguments | note: struct defined here, with 0 lifetime parameters --> $DIR/issue-82126-mismatched-subst-and-hir.rs:23:8 | LL | struct LockedMarket<T>(T); |        ^^^^^^^^^^^^ error[E0107]: this struct takes 1 type argument but 0 type arguments were supplied --> $DIR/issue-82126-mismatched-subst-and-hir.rs:16:59 | LL | async fn buy_lock(generator: &Mutex<MarketMultiplier>) -> LockedMarket<'_> { |                                                           ^^^^^^^^^^^^ expected 1 type argument | note: struct defined here, with 1 type parameter: `T` --> $DIR/issue-82126-mismatched-subst-and-hir.rs:23:8 | LL | struct LockedMarket<T>(T); |        ^^^^^^^^^^^^ - help: add missing type argument | LL | async fn buy_lock(generator: &Mutex<MarketMultiplier>) -> LockedMarket<'_, T> { |                                                                          ^^^ error[E0515]: cannot return value referencing temporary value --> $DIR/issue-82126-mismatched-subst-and-hir.rs:19:5 | LL |     LockedMarket(generator.lock().unwrap().buy()) |     ^^^^^^^^^^^^^-------------------------^^^^^^^ |     |            | |     |            temporary value created here |     returns a value referencing data owned by the current function error: aborting due to 3 previous errors Some errors have detailed explanations: E0107, E0515. For more information about an error, try `rustc --explain E0107`. </ins>


fn run(self, builder: &Builder<'_>) -> Option<PathBuf> { let compiler = self.compiler; let target = self.target; <del> let tool = self.tool; </del> <ins> let mut tool = self.tool; </ins> let path = self.path; let is_optional_tool = self.is_optional_tool;


None } } else { <ins> // HACK(#82501): on Windows, the tools directory gets added to PATH when running tests, and // compiletest confuses HTML tidy with the in-tree tidy. Name the in-tree tidy something // different so the problem doesn't come up. if tool == "tidy" { tool = "rust-tidy"; } </ins> let cargo_out = builder.cargo_out(compiler, self.mode, target).join(exe(tool, compiler.host)); let bin = builder.tools_dir(compiler).join(exe(tool, compiler.host));


version = "0.1.0" authors = ["Alex Crichton <alex@alexcrichton.com>"] edition = "2018" <ins> autobins = false </ins> [dependencies] cargo_metadata = "0.11" regex = "1" lazy_static = "1" walkdir = "2" <ins> [[bin]] name = "rust-tidy" path = "src/main.rs" </ins>


use rustc_hir::{ExprKind, ItemKind, Node}; use rustc_infer::infer; use rustc_middle::lint::in_external_macro; <del> use rustc_middle::ty::{self, Ty}; </del> <ins> use rustc_middle::ty::{self, Binder, Ty}; </ins> use rustc_span::symbol::kw; use std::iter;


let found = self.resolve_vars_with_obligations(found); if let hir::FnRetTy::Return(ty) = fn_decl.output { let ty = AstConv::ast_ty_to_ty(self, ty); <ins> let ty = self.tcx.erase_late_bound_regions(Binder::bind(ty)); </ins> let ty = self.normalize_associated_types_in(expr.span, ty); if self.can_coerce(found, ty) { err.multipart_suggestion(


<ins> // Regression test for #82612. use std::marker::PhantomData; pub trait SparseSetIndex { fn sparse_set_index(&self) -> usize; } pub struct SparseArray<I, V = I> { values: Vec<Option<V>>, marker: PhantomData<I>, } impl<I: SparseSetIndex, V> SparseArray<I, V> { pub fn get_or_insert_with(&mut self, index: I, func: impl FnOnce() -> V) -> &mut V { let index = index.sparse_set_index(); if index < self.values.len() { let value = unsafe { self.values.get_unchecked_mut(index) }; value.get_or_insert_with(func) //~ ERROR mismatched types } unsafe { self.values.get_unchecked_mut(index).as_mut().unwrap() } } } fn main() {} </ins>


<ins> error[E0308]: mismatched types --> $DIR/issue-82612-return-mutable-reference.rs:18:13 | LL | /         if index < self.values.len() { LL | |             let value = unsafe { self.values.get_unchecked_mut(index) }; LL | |             value.get_or_insert_with(func) | |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found `&mut V` LL | |         } | |_________- expected this to be `()` | = note:      expected unit type `()` found mutable reference `&mut V` help: consider using a semicolon here | LL |             value.get_or_insert_with(func); |                                           ^ help: consider using a semicolon here | LL |         }; |          ^ help: you might have meant to return this value | LL |             return value.get_or_insert_with(func); |             ^^^^^^                               ^ error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. </ins>


- [Documentation tests](documentation-tests.md) - [Linking to items by name](linking-to-items-by-name.md) - [Lints](lints.md) <del> - [Passes](passes.md) </del> - [Advanced features](advanced-features.md) - [Unstable features](unstable-features.md) <ins> - [Passes](passes.md) </ins> - [References](references.md)


LLVM version: 3.9 ``` <del> ## `-r`/`--input-format`: input format This flag is currently ignored; the idea is that `rustdoc` would support various input formats, and you could specify them via this flag. Rustdoc only supports Rust source code and Markdown input formats. If the file ends in `.md` or `.markdown`, `rustdoc` treats it as a Markdown file. Otherwise, it assumes that the input file is Rust. ## `-w`/`--output-format`: output format This flag is currently ignored; the idea is that `rustdoc` would support various output formats, and you could specify them via this flag. Rustdoc only supports HTML output, and so this flag is redundant today. </del> ## `-o`/`--output`: output path Using this flag looks like this:


as the `.rs` file. `--crate-name` lets you override this assumption with whatever name you choose. <ins> ## `--document-private-items`: Show items that are not public Using this flag looks like this: ```bash $ rustdoc src/lib.rs --document-private-items ``` By default, `rustdoc` only documents items that are publicly reachable. ```rust pub fn public() {} // this item is public and will documented mod private { // this item is private and will not be documented pub fn unreachable() {} // this item is public, but unreachable, so it will not be documented } ``` `--document-private-items` documents all items, even if they're not public. </ins> ## `-L`/`--library-path`: where to look for dependencies Using this flag looks like this:


The arguments to this flag are the same as those for the `-C` flag on rustc. Run `rustc -C help` to get the full list. <del> ## `--passes`: add more rustdoc passes Using this flag looks like this: ```bash $ rustdoc --passes list $ rustdoc src/lib.rs --passes strip-priv-imports ``` An argument of "list" will print a list of possible "rustdoc passes", and other arguments will be the name of which passes to run in addition to the defaults. For more details on passes, see [the chapter on them](passes.md). See also `--no-defaults`. ## `--no-defaults`: don't run default passes Using this flag looks like this: ```bash $ rustdoc src/lib.rs --no-defaults ``` By default, `rustdoc` will run several passes over your code. This removes those defaults, allowing you to use `--passes` to specify exactly which passes you want. For more details on passes, see [the chapter on them](passes.md). See also `--passes`. </del> ## `--test`: run code examples as tests Using this flag looks like this:


command line options from it. These options are one per line; a blank line indicates an empty option. The file can use Unix or Windows style line endings, and must be encoded as UTF-8. <ins> ## `--passes`: add more rustdoc passes This flag is **deprecated**. For more details on passes, see [the chapter on them](passes.md). ## `--no-defaults`: don't run default passes This flag is **deprecated**. For more details on passes, see [the chapter on them](passes.md). ## `-r`/`--input-format`: input format This flag is **deprecated** and **has no effect**. Rustdoc only supports Rust source code and Markdown input formats. If the file ends in `.md` or `.markdown`, `rustdoc` treats it as a Markdown file. Otherwise, it assumes that the input file is Rust. </ins>


Rustdoc has a concept called "passes". These are transformations that `rustdoc` runs on your documentation before producing its final output. <del> In addition to the passes below, check out the docs for these flags: </del> <ins> Customizing passes is **deprecated**. The available passes are not considered stable and may change in any release. </ins> <del> * [`--passes`](command-line-arguments.md#--passes-add-more-rustdoc-passes) * [`--no-defaults`](command-line-arguments.md#--no-defaults-dont-run-default-passes) ## Default passes By default, rustdoc will run some passes, namely: * `strip-hidden` * `strip-private` * `collapse-docs` * `unindent-comments` However, `strip-private` implies `strip-priv-imports`, and so effectively, all passes are run by default. ## `strip-hidden` This pass implements the `#[doc(hidden)]` attribute. When this pass runs, it checks each item, and if it is annotated with this attribute, it removes it from `rustdoc`'s output. Without this pass, these items will remain in the output. ## `unindent-comments` When you write a doc comment like this: ```rust,no_run /// This is a documentation comment. # fn f() {} ``` There's a space between the `///` and that `T`. That spacing isn't intended to be a part of the output; it's there for humans, to help separate the doc comment syntax from the text of the comment. This pass is what removes that space. The exact rules are left under-specified so that we can fix issues that we find. Without this pass, the exact number of spaces is preserved. ## `collapse-docs` With this pass, multiple `#[doc]` attributes are converted into one single documentation string. For example: ```rust,no_run #[doc = "This is the first line."] #[doc = "This is the second line."] # fn f() {} ``` Gets collapsed into a single doc string of ```text This is the first line. This is the second line. ``` ## `strip-private` This removes documentation for any non-public items, so for example: ```rust,no_run /// These are private docs. struct Private; /// These are public docs. pub struct Public; ``` This pass removes the docs for `Private`, since they're not public. This pass implies `strip-priv-imports`. ## `strip-priv-imports` This is the same as `strip-private`, but for `extern crate` and `use` statements instead of items. </del> <ins> In the past the most common use case for customizing passes was to omit the `strip-private` pass. You can do this more easily, and without risk of the pass being changed, by passing [`--document-private-items`](./unstable-features.md#--document-private-items). </ins>


Public items that are not documented can be seen with the built-in `missing_docs` lint. Private items that are not documented can be seen with Clippy's `missing_docs_in_private_items` lint. <ins> ## `-w`/`--output-format`: output format When using [`--show-coverage`](https://doc.rust-lang.org/nightly/rustdoc/unstable-features.html#--show-coverage-get-statistics-about-code-documentation-coverage), passing `--output-format json` will display the coverage information in JSON format. For example, here is the JSON for a file with one documented item and one undocumented item: ```rust /// This item has documentation pub fn foo() {} pub fn no_documentation() {} ``` ```json {"no_std.rs":{"total":3,"with_docs":1,"total_examples":3,"with_examples":0}} ``` Note that the third item is the crate root, which in this case is undocumented. When not using `--show-coverage`, `--output-format json` emits documentation in the experimental [JSON format](https://github.com/rust-lang/rfcs/pull/2963). `--output-format html` has no effect, and is also accepted on stable toolchains. </ins> ### `--enable-per-target-ignores`: allow `ignore-foo` style filters for doctests Using this flag looks like this:


} impl Attribute { <ins> #[inline] </ins> pub fn has_name(&self, name: Symbol) -> bool { match self.kind { AttrKind::Normal(ref item, _) => item.path == name,


use rustc_middle::ty::query::Providers; use rustc_middle::ty::TyCtxt; <del> use rustc_ast::{Attribute, LitKind, NestedMetaItem}; </del> <ins> use rustc_ast::{Attribute, Lit, LitKind, NestedMetaItem}; </ins> use rustc_errors::{pluralize, struct_span_err}; use rustc_hir as hir; use rustc_hir::def_id::LocalDefId;


self.check_export_name(hir_id, &attr, span, target) } else if self.tcx.sess.check_name(attr, sym::rustc_args_required_const) { self.check_rustc_args_required_const(&attr, span, target, item) <ins> } else if self.tcx.sess.check_name(attr, sym::rustc_layout_scalar_valid_range_start) { self.check_rustc_layout_scalar_valid_range(&attr, span, target) } else if self.tcx.sess.check_name(attr, sym::rustc_layout_scalar_valid_range_end) { self.check_rustc_layout_scalar_valid_range(&attr, span, target) </ins> } else if self.tcx.sess.check_name(attr, sym::allow_internal_unstable) { self.check_allow_internal_unstable(hir_id, &attr, span, target, &attrs) } else if self.tcx.sess.check_name(attr, sym::rustc_allow_const_fn_unstable) {


} } <ins> fn check_rustc_layout_scalar_valid_range( &self, attr: &Attribute, span: &Span, target: Target, ) -> bool { if target != Target::Struct { self.tcx .sess .struct_span_err(attr.span, "attribute should be applied to a struct") .span_label(*span, "not a struct") .emit(); return false; } let list = match attr.meta_item_list() { None => return false, Some(it) => it, }; if matches!(&list[..], &[NestedMetaItem::Literal(Lit { kind: LitKind::Int(..), .. })]) { true } else { self.tcx .sess .struct_span_err(attr.span, "expected exactly one integer literal argument") .emit(); false } } </ins> /// Checks if `#[rustc_legacy_const_generics]` is applied to a function and has a valid argument. fn check_rustc_legacy_const_generics( &self,


<ins> #![feature(rustc_attrs)] #[rustc_layout_scalar_valid_range_start(u32::MAX)] //~ ERROR pub struct A(u32); #[rustc_layout_scalar_valid_range_end(1, 2)] //~ ERROR pub struct B(u8); #[rustc_layout_scalar_valid_range_end(a = "a")] //~ ERROR pub struct C(i32); #[rustc_layout_scalar_valid_range_end(1)] //~ ERROR enum E { X = 1, Y = 14, } fn main() { let _ = A(0); let _ = B(0); let _ = C(0); let _ = E::X; } </ins>


<ins> error: expected exactly one integer literal argument --> $DIR/invalid_rustc_layout_scalar_valid_range.rs:3:1 | LL | #[rustc_layout_scalar_valid_range_start(u32::MAX)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: expected exactly one integer literal argument --> $DIR/invalid_rustc_layout_scalar_valid_range.rs:6:1 | LL | #[rustc_layout_scalar_valid_range_end(1, 2)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: expected exactly one integer literal argument --> $DIR/invalid_rustc_layout_scalar_valid_range.rs:9:1 | LL | #[rustc_layout_scalar_valid_range_end(a = "a")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: attribute should be applied to a struct --> $DIR/invalid_rustc_layout_scalar_valid_range.rs:12:1 | LL |   #[rustc_layout_scalar_valid_range_end(1)] |   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ LL | / enum E { LL | |     X = 1, LL | |     Y = 14, LL | | } | |_- not a struct error: aborting due to 4 previous errors </ins>


cx.generated_synthetics.insert((ty, trait_def_id)); <ins> let hir_imp = impl_def_id.as_local() .map(|local| cx.tcx.hir().expect_item(local)) .and_then(|item| if let hir::ItemKind::Impl(i) = &item.kind { Some(i) } else { None }); let items = match hir_imp { Some(imp) => imp .items .iter() .map(|ii| cx.tcx.hir().impl_item(ii.id).clean(cx)) .collect::<Vec<_>>(), None => cx.tcx .associated_items(impl_def_id) .in_definition_order() .map(|x| x.clean(cx)) .collect::<Vec<_>>(), }; </ins> impls.push(Item { name: None, attrs: Default::default(),


// the post-inference `trait_ref`, as it's more accurate. trait_: Some(trait_ref.clean(cx)), for_: ty.clean(cx), <del> items: cx .tcx .associated_items(impl_def_id) .in_definition_order() .map(|x| x.clean(cx)) .collect::<Vec<_>>(), </del> <ins> items, </ins> polarity: ty::ImplPolarity::Positive, kind: ImplKind::Blanket(box trait_ref.self_ty().clean(cx)), }),


/// the hashmap because certain items (traits and types) need to have their mappings for trait /// implementations filled out before they're inserted. fn item(&mut self, item: clean::Item) -> Result<(), Error> { <del> let local_blanket_impl = match item.def_id { clean::ItemId::Blanket { impl_id, .. } => impl_id.is_local(), clean::ItemId::Auto { .. } | clean::ItemId::DefId(_) | clean::ItemId::Primitive(_, _) => false, }; </del> // Flatten items that recursively store other items <del> // FIXME(CraftSpider): We skip children of local blanket implementations, as we'll have //     already seen the actual generic impl, and the generated ones don't need documenting. //     This is necessary due to the visibility, return type, and self arg of the generated //     impls not quite matching, and will no longer be necessary when the mismatch is fixed. if !local_blanket_impl { item.kind.inner_items().for_each(|i| self.item(i.clone()).unwrap()); } </del> <ins> item.kind.inner_items().for_each(|i| self.item(i.clone()).unwrap()); </ins> let id = item.def_id; if let Some(mut new_item) = self.convert_item(item) {


// @has blanket_with_local.json "$.index[*][?(@.name=='Load')]" pub trait Load { <ins> // @has - "$.index[*][?(@.name=='load')]" </ins> fn load() {} <ins> // @has - "$.index[*][?(@.name=='write')]" fn write(self) {} </ins> } impl<P> Load for P { fn load() {} <ins> fn write(self) {} </ins> } // @has - "$.index[*][?(@.name=='Wrapper')]"


use option::{Option,Some,None}; use libc::c_void; use ops::Drop; <ins> use util::NonCopyable; </ins> /** * A simple atomic flag, that can be set and cleared. The most basic atomic type. */ pub struct AtomicFlag { <del> priv v: int </del> <ins> priv v: int, priv nocopy: NonCopyable </ins> } /** * An atomic boolean type. */ pub struct AtomicBool { <del> priv v: uint </del> <ins> priv v: uint, priv nocopy: NonCopyable </ins> } /** * A signed atomic integer type, supporting basic atomic arithmetic operations */ pub struct AtomicInt { <del> priv v: int </del> <ins> priv v: int, priv nocopy: NonCopyable </ins> } /** * An unsigned atomic integer type, supporting basic atomic arithmetic operations */ pub struct AtomicUint { <del> priv v: uint </del> <ins> priv v: uint, priv nocopy: NonCopyable </ins> } /** * An unsafe atomic pointer. Only supports basic atomic operations */ pub struct AtomicPtr<T> { <del> priv p: *mut T </del> <ins> priv p: *mut T, priv nocopy: NonCopyable </ins> } /**


SeqCst } <del> pub static INIT_ATOMIC_FLAG : AtomicFlag = AtomicFlag { v: 0 }; pub static INIT_ATOMIC_BOOL : AtomicBool = AtomicBool { v: 0 }; pub static INIT_ATOMIC_INT  : AtomicInt  = AtomicInt  { v: 0 }; pub static INIT_ATOMIC_UINT : AtomicUint = AtomicUint { v: 0 }; </del> <ins> pub static INIT_ATOMIC_FLAG : AtomicFlag = AtomicFlag { v: 0, nocopy: NonCopyable }; pub static INIT_ATOMIC_BOOL : AtomicBool = AtomicBool { v: 0, nocopy: NonCopyable }; pub static INIT_ATOMIC_INT  : AtomicInt  = AtomicInt  { v: 0, nocopy: NonCopyable }; pub static INIT_ATOMIC_UINT : AtomicUint = AtomicUint { v: 0, nocopy: NonCopyable }; </ins> impl AtomicFlag { pub fn new() -> AtomicFlag { <del> AtomicFlag { v: 0 } </del> <ins> AtomicFlag { v: 0, nocopy: NonCopyable } </ins> } /**


impl AtomicBool { pub fn new(v: bool) -> AtomicBool { <del> AtomicBool { v: if v { 1 } else { 0 } } </del> <ins> AtomicBool { v: if v { 1 } else { 0 }, nocopy: NonCopyable } </ins> } #[inline]


impl AtomicInt { pub fn new(v: int) -> AtomicInt { <del> AtomicInt { v:v } </del> <ins> AtomicInt { v:v, nocopy: NonCopyable } </ins> } #[inline]


impl AtomicUint { pub fn new(v: uint) -> AtomicUint { <del> AtomicUint { v:v } </del> <ins> AtomicUint { v:v, nocopy: NonCopyable } </ins> } #[inline]


impl<T> AtomicPtr<T> { pub fn new(p: *mut T) -> AtomicPtr<T> { <del> AtomicPtr { p:p } </del> <ins> AtomicPtr { p:p, nocopy: NonCopyable } </ins> } #[inline]


<ins> // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Issue #8380 #[feature(globs)]; use std::unstable::atomics::*; use std::ptr; fn main() { let x = INIT_ATOMIC_FLAG; let x = *&x; //~ ERROR: cannot move out of dereference let x = INIT_ATOMIC_BOOL; let x = *&x; //~ ERROR: cannot move out of dereference let x = INIT_ATOMIC_INT; let x = *&x; //~ ERROR: cannot move out of dereference let x = INIT_ATOMIC_UINT; let x = *&x; //~ ERROR: cannot move out of dereference let x: AtomicPtr<uint> = AtomicPtr::new(ptr::mut_null()); let x = *&x; //~ ERROR: cannot move out of dereference let x: AtomicOption<uint> = AtomicOption::empty(); let x = *&x; //~ ERROR: cannot move out of dereference } </ins>


debug!("QueryNormalizer: result = {:#?}", result); debug!("QueryNormalizer: obligations = {:#?}", obligations); self.obligations.extend(obligations); <del> Ok(result.normalized_ty) </del> <ins> let res = result.normalized_ty; // `tcx.normalize_projection_ty` may normalize to a type that still has // unevaluated consts, so keep normalizing here if that's the case. if res != ty && res.has_type_flags(ty::TypeFlags::HAS_CT_PROJECTION) { Ok(res.try_super_fold_with(self)?) } else { Ok(res) } </ins> } ty::Projection(data) => {


debug!("QueryNormalizer: result = {:#?}", result); debug!("QueryNormalizer: obligations = {:#?}", obligations); self.obligations.extend(obligations); <del> Ok(crate::traits::project::PlaceholderReplacer::replace_placeholders( </del> <ins> let res = crate::traits::project::PlaceholderReplacer::replace_placeholders( </ins> infcx, mapped_regions, mapped_types, mapped_consts, &self.universes, result.normalized_ty, <del> )) </del> <ins> ); // `tcx.normalize_projection_ty` may normalize to a type that still has // unevaluated consts, so keep normalizing here if that's the case. if res != ty && res.has_type_flags(ty::TypeFlags::HAS_CT_PROJECTION) { Ok(res.try_super_fold_with(self)?) } else { Ok(res) } </ins> } _ => ty.try_super_fold_with(self), })()?; self.cache.insert(ty, res); Ok(res) }


<ins> // build-pass #![allow(incomplete_features)] #![feature(generic_const_exprs)] trait TraitOne { const MY_NUM: usize; type MyErr: std::fmt::Debug; fn do_one_stuff(arr: [u8; Self::MY_NUM]) -> Result<(), Self::MyErr>; } trait TraitTwo { fn do_two_stuff(); } impl<O: TraitOne> TraitTwo for O where [(); Self::MY_NUM]:, { fn do_two_stuff() { O::do_one_stuff([5; Self::MY_NUM]).unwrap() } } struct Blargotron; #[derive(Debug)] struct ErrTy<const N: usize>([(); N]); impl TraitOne for Blargotron { const MY_NUM: usize = 3; type MyErr = ErrTy<{ Self::MY_NUM }>; fn do_one_stuff(_arr: [u8; Self::MY_NUM]) -> Result<(), Self::MyErr> { Ok(()) } } fn main() { Blargotron::do_two_stuff(); } </ins>


<ins> // build-pass #![allow(incomplete_features)] #![feature(generic_const_exprs)] use std::convert::AsMut; use std::default::Default; trait Foo: Sized { type Baz: Default + AsMut<[u8]>; fn bar() { Self::Baz::default().as_mut(); } } impl Foo for () { type Baz = [u8; 1 * 1]; //type Baz = [u8; 1]; } fn main() { <() as Foo>::bar(); } </ins>


<ins> // build-pass #![allow(incomplete_features)] #![feature(generic_const_exprs)] trait Collate<Op> { type Pass; type Fail; fn collate(self) -> (Self::Pass, Self::Fail); } impl<Op> Collate<Op> for () { type Pass = (); type Fail = (); fn collate(self) -> ((), ()) { ((), ()) } } trait CollateStep<X, Prev> { type Pass; type Fail; fn collate_step(x: X, prev: Prev) -> (Self::Pass, Self::Fail); } impl<X, P, F> CollateStep<X, (P, F)> for () { type Pass = (X, P); type Fail = F; fn collate_step(x: X, (p, f): (P, F)) -> ((X, P), F) { ((x, p), f) } } struct CollateOpImpl<const MASK: u32>; trait CollateOpStep { type NextOp; type Apply; } impl<const MASK: u32> CollateOpStep for CollateOpImpl<MASK> where CollateOpImpl<{ MASK >> 1 }>: Sized, { type NextOp = CollateOpImpl<{ MASK >> 1 }>; type Apply = (); } impl<H, T, Op: CollateOpStep> Collate<Op> for (H, T) where T: Collate<Op::NextOp>, Op::Apply: CollateStep<H, (T::Pass, T::Fail)>, { type Pass = <Op::Apply as CollateStep<H, (T::Pass, T::Fail)>>::Pass; type Fail = <Op::Apply as CollateStep<H, (T::Pass, T::Fail)>>::Fail; fn collate(self) -> (Self::Pass, Self::Fail) { <Op::Apply as CollateStep<H, (T::Pass, T::Fail)>>::collate_step(self.0, self.1.collate()) } } fn collate<X, const MASK: u32>(x: X) -> (X::Pass, X::Fail) where X: Collate<CollateOpImpl<MASK>>, { x.collate() } fn main() { dbg!(collate::<_, 5>(("Hello", (42, ('!', ()))))); } </ins>


<ins> // build-pass #![allow(incomplete_features)] #![feature(generic_const_exprs)] pub trait Foo { fn foo(&self); } pub struct FooImpl<const N: usize>; impl<const N: usize> Foo for FooImpl<N> { fn foo(&self) {} } pub trait Bar: 'static { type Foo: Foo; fn get() -> &'static Self::Foo; } struct BarImpl; impl Bar for BarImpl { type Foo = FooImpl< { { 4 } }, >; fn get() -> &'static Self::Foo { &FooImpl } } pub fn boom<B: Bar>() { B::get().foo(); } fn main() { boom::<BarImpl>(); } </ins>


<ins> // build-pass #![feature(generic_const_exprs)] #![allow(incomplete_features)] trait Foo { type Output; fn foo() -> Self::Output; } impl Foo for [u8; 3] { type Output = [u8; 1 + 2]; fn foo() -> [u8; 3] { [1u8; 3] } } fn bug<const N: usize>() where [u8; N]: Foo, <[u8; N] as Foo>::Output: AsRef<[u8]>, { <[u8; N]>::foo().as_ref(); } fn main() { bug::<3>(); } </ins>


<ins> // build-pass #![allow(incomplete_features)] #![feature(generic_const_exprs)] use std::marker::PhantomData; fn main() { let x = FooImpl::<BarImpl<1>> { phantom: PhantomData }; let _ = x.foo::<BarImpl<1>>(); } trait Foo<T> where T: Bar, { fn foo<U>(&self) where T: Operation<U>, <T as Operation<U>>::Output: Bar; } struct FooImpl<T> where T: Bar, { phantom: PhantomData<T>, } impl<T> Foo<T> for FooImpl<T> where T: Bar, { fn foo<U>(&self) where T: Operation<U>, <T as Operation<U>>::Output: Bar, { <<T as Operation<U>>::Output as Bar>::error_occurs_here(); } } trait Bar { fn error_occurs_here(); } struct BarImpl<const N: usize>; impl<const N: usize> Bar for BarImpl<N> { fn error_occurs_here() {} } trait Operation<Rhs> { type Output; } //// Part-A: This causes error. impl<const M: usize, const N: usize> Operation<BarImpl<M>> for BarImpl<N> where BarImpl<{ N + M }>: Sized, { type Output = BarImpl<{ N + M }>; } //// Part-B: This doesn't cause error. // impl<const M: usize, const N: usize> Operation<BarImpl<M>> for BarImpl<N> { //     type Output = BarImpl<M>; // } //// Part-C: This also doesn't cause error. // impl<const M: usize, const N: usize> Operation<BarImpl<M>> for BarImpl<N> { //     type Output = BarImpl<{ M }>; // } </ins>


Res::Def(DefKind::Ctor(..), def_id) => { tcx.generics_of(tcx.parent(def_id).unwrap()) } <del> Res::Def(_, def_id) => tcx.generics_of(def_id), </del> <ins> // Other `DefKind`s don't have generics and would ICE when calling // `generics_of`. Res::Def( DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::Variant | DefKind::Trait | DefKind::OpaqueTy | DefKind::TyAlias | DefKind::ForeignTy | DefKind::TraitAlias | DefKind::AssocTy | DefKind::Fn | DefKind::AssocFn | DefKind::AssocConst | DefKind::Impl, def_id, ) => tcx.generics_of(def_id), </ins> Res::Err => { tcx.sess.delay_span_bug(tcx.def_span(def_id), "anon const with Res::Err"); return None;


<ins> fn f() { std::<0>; //~ ERROR expected value } fn j() { std::<_ as _>; //~ ERROR expected value //~^ ERROR expected one of `,` or `>`, found keyword `as` } fn main () {} </ins>


<ins> error: expected one of `,` or `>`, found keyword `as` --> $DIR/issue-84831.rs:5:13 | LL |     std::<_ as _>; |             ^^ expected one of `,` or `>` | help: expressions must be enclosed in braces to be used as const generic arguments | LL |     std::<{ _ as _ }>; |           ^        ^ error[E0423]: expected value, found crate `std` --> $DIR/issue-84831.rs:2:5 | LL |     std::<0>; |     ^^^^^^^^ not a value error[E0423]: expected value, found crate `std` --> $DIR/issue-84831.rs:5:5 | LL |     std::<_ as _>; |     ^^^^^^^^^^^^^ not a value error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0423`. </ins>


E0782: include_str!("./error_codes/E0782.md"), E0783: include_str!("./error_codes/E0783.md"), E0784: include_str!("./error_codes/E0784.md"), <ins> E0785: include_str!("./error_codes/E0785.md"), </ins> ; //  E0006, // merged with E0005 //  E0008, // cannot bind by-move into a pattern guard


<ins> An inherent `impl` was written on a dyn auto trait. Erroneous code example: ```compile_fail,E0785 #![feature(auto_traits)] auto trait AutoTrait {} impl dyn AutoTrait {} ``` Dyn objects allow any number of auto traits, plus at most one non-auto trait. The non-auto trait becomes the "principal trait". When checking if an impl on a dyn trait is coherent, the principal trait is normally the only one considered. Since the erroneous code has no principal trait, it cannot be implemented at all. Working example: ``` #![feature(auto_traits)] trait PrincipalTrait {} auto trait AutoTrait {} impl dyn PrincipalTrait + AutoTrait + Send {} ``` </ins>


ty::Dynamic(ref data, ..) if data.principal_def_id().is_some() => { self.check_def_id(item, data.principal_def_id().unwrap()); } <ins> ty::Dynamic(..) => { struct_span_err!( self.tcx.sess, ty.span, E0785, "cannot define inherent `impl` for a dyn auto trait" ) .span_label(ty.span, "impl requires at least one non-auto trait") .note("define and implement a new trait or type instead") .emit(); } </ins> ty::Bool => { self.check_primitive_impl( item.def_id,


<ins> #![feature(auto_traits)] auto trait AutoTrait {} // You cannot impl your own `dyn AutoTrait`. impl dyn AutoTrait {} //~ERROR E0785 // You cannot impl someone else's `dyn AutoTrait` impl dyn Unpin {} //~ERROR E0785 fn main() {} </ins>


<ins> error[E0785]: cannot define inherent `impl` for a dyn auto trait --> $DIR/issue-85026.rs:5:6 | LL | impl dyn AutoTrait {} |      ^^^^^^^^^^^^^ impl requires at least one non-auto trait | = note: define and implement a new trait or type instead error[E0785]: cannot define inherent `impl` for a dyn auto trait --> $DIR/issue-85026.rs:8:6 | LL | impl dyn Unpin {} |      ^^^^^^^^^ impl requires at least one non-auto trait | = note: define and implement a new trait or type instead error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0785`. </ins>


from rust_types import * <del> rust_enabled = 'set language rust' in gdb.execute('complete set language ru', to_string=True) </del> _gdb_version_matched = re.search('([0-9]+).([0-9]+)', gdb.VERSION) gdb_version = [int(num) for num in _gdb_version_matched.groups()] if _gdb_version_matched else []


return StdStringProvider(valobj) if rust_type == RustType.STD_OS_STRING: return StdOsStringProvider(valobj) <del> if rust_type == RustType.STD_STR and not rust_enabled: </del> <ins> if rust_type == RustType.STD_STR: </ins> return StdStrProvider(valobj) <ins> if rust_type == RustType.STD_SLICE: return StdSliceProvider(valobj) </ins> if rust_type == RustType.STD_VEC: return StdVecProvider(valobj) if rust_type == RustType.STD_VEC_DEQUE:


def display_hint(): return "string" <ins> def _enumerate_array_elements(element_ptrs): for (i, element_ptr) in enumerate(element_ptrs): key = "[{}]".format(i) element = element_ptr.dereference() try: # rust-lang/rust#64343: passing deref expr to `str` allows # catching exception on garbage pointer str(element) except RuntimeError: yield key, "inaccessible" break yield key, element class StdSliceProvider: def __init__(self, valobj): self.valobj = valobj self.length = int(valobj["length"]) self.data_ptr = valobj["data_ptr"] def to_string(self): return "{}(size={})".format(self.valobj.type, self.length) def children(self): return _enumerate_array_elements( self.data_ptr + index for index in xrange(self.length) ) @staticmethod def display_hint(): return "array" </ins> class StdVecProvider: def __init__(self, valobj):


return "Vec(size={})".format(self.length) def children(self): <del> saw_inaccessible = False for index in xrange(self.length): element_ptr = self.data_ptr + index if saw_inaccessible: return try: # rust-lang/rust#64343: passing deref expr to `str` allows # catching exception on garbage pointer str(element_ptr.dereference()) yield "[{}]".format(index), element_ptr.dereference() except RuntimeError: saw_inaccessible = True yield str(index), "inaccessible" </del> <ins> return _enumerate_array_elements( self.data_ptr + index for index in xrange(self.length) ) </ins> @staticmethod def display_hint():


return "VecDeque(size={})".format(self.size) def children(self): <del> for index in xrange(0, self.size): value = (self.data_ptr + ((self.tail + index) % self.cap)).dereference() yield "[{}]".format(index), value </del> <ins> return _enumerate_array_elements( (self.data_ptr + ((self.tail + index) % self.cap)) for index in xrange(self.size) ) </ins> @staticmethod def display_hint():


type synthetic add -l lldb_lookup.synthetic_lookup -x ".*" --category Rust type summary add -F lldb_lookup.summary_lookup  -e -x -h "^(alloc::([a-z_]+::)+)String$" --category Rust <del> type summary add -F lldb_lookup.summary_lookup  -e -x -h "^&str$" --category Rust type summary add -F lldb_lookup.summary_lookup  -e -x -h "^&[.+]$" --category Rust </del> <ins> type summary add -F lldb_lookup.summary_lookup  -e -x -h "^&(mut )?str$" --category Rust type summary add -F lldb_lookup.summary_lookup  -e -x -h "^&(mut )?[.+]$" --category Rust </ins> type summary add -F lldb_lookup.summary_lookup  -e -x -h "^(std::ffi::([a-z_]+::)+)OsString$" --category Rust type summary add -F lldb_lookup.summary_lookup  -e -x -h "^(alloc::([a-z_]+::)+)Vec<.+>$" --category Rust type summary add -F lldb_lookup.summary_lookup  -e -x -h "^(alloc::([a-z_]+::)+)VecDeque<.+>$" --category Rust


STD_STRING_REGEX = re.compile(r"^(alloc::(w+::)+)String$") <del> STD_STR_REGEX = re.compile(r"^&str$") STD_SLICE_REGEX = re.compile(r"^&[.+]$") </del> <ins> STD_STR_REGEX = re.compile(r"^&(mut )?str$") STD_SLICE_REGEX = re.compile(r"^&(mut )?[.+]$") </ins> STD_OS_STRING_REGEX = re.compile(r"^(std::ffi::(w+::)+)OsString$") STD_VEC_REGEX = re.compile(r"^(alloc::(w+::)+)Vec<.+>$") STD_VEC_DEQUE_REGEX = re.compile(r"^(alloc::(w+::)+)VecDeque<.+>$")


// gdb-check:$1 = Vec(size=1000000000) = {[...]...} // gdb-command: print slice <del> // gdb-check:$2 = &[u8] {data_ptr: [...], length: 1000000000} </del> <ins> // gdb-check:$2 = &[u8](size=1000000000) = {[...]...} </ins> #![allow(unused_variables)]


<ins> // ignore-android: FIXME(#10381) // ignore-windows // compile-flags:-g // gdb-command: run // gdb-command: print slice // gdbg-check: $1 = struct &[i32](size=3) = {0, 1, 2} // gdbr-check: $1 = &[i32](size=3) = {0, 1, 2} // gdb-command: print mut_slice // gdbg-check: $2 = struct &mut [i32](size=4) = {2, 3, 5, 7} // gdbr-check: $2 = &mut [i32](size=4) = {2, 3, 5, 7} // gdb-command: print str_slice // gdb-check: $3 = "string slice" // gdb-command: print mut_str_slice // gdb-check: $4 = "mutable string slice" // lldb-command: run // lldb-command: print slice // lldb-check: (&[i32]) $0 = size=3 { [0] = 0 [1] = 1 [2] = 2 } // lldb-command: print mut_slice // lldb-check: (&mut [i32]) $1 = size=4 { [0] = 2 [1] = 3 [2] = 5 [3] = 7 } // lldb-command: print str_slice // lldb-check: (&str) $2 = "string slice" { data_ptr = [...] length = 12 } // lldb-command: print mut_str_slice // lldb-check: (&mut str) $3 = "mutable string slice" { data_ptr = [...] length = 20 } fn b() {} fn main() { let slice: &[i32] = &[0, 1, 2]; let mut_slice: &mut [i32] = &mut [2, 3, 5, 7]; let str_slice: &str = "string slice"; let mut mut_str_slice_buffer = String::from("mutable string slice"); let mut_str_slice: &mut str = mut_str_slice_buffer.as_mut_str(); b(); // #break } </ins>


let rust_type_regexes = vec![ "^(alloc::([a-z_]+::)+)String$", <del> "^&str$", "^&[.+]$", </del> <ins> "^&(mut )?str$", "^&(mut )?[.+]$", </ins> "^(std::ffi::([a-z_]+::)+)OsString$", "^(alloc::([a-z_]+::)+)Vec<.+>$", "^(alloc::([a-z_]+::)+)VecDeque<.+>$",


<ins> Version 1.54.0 (2021-07-29) ============================ Language ----------------------- - [You can now use macros for values in built-in attribute macros.][83366] While a seemingly minor addition on its own, this enables a lot of powerful functionality when combined correctly. Most notably you can now include external documentation in your crate by writing the following. ```rust #![doc = include_str!("README.md")] ``` You can also use this to include auto-generated modules: ```rust #[path = concat!(env!("OUT_DIR"), "/generated.rs")] mod generated; ``` - [You can now cast between unsized slice types (and types which contain unsized slices) in `const fn`.][85078] - [You can now use multiple generic lifetimes with `impl Trait` where the lifetimes don't explicitly outlive another.][84701] In code this means that you can now have `impl Trait<'a, 'b>` where as before you could only have `impl Trait<'a, 'b> where 'b: 'a`. Compiler ----------------------- - [Rustc will now search for custom JSON targets in `/lib/rustlib/<target-triple>/target.json` where `/` is the "sysroot" directory.][83800] You can find your sysroot directory by running `rustc --print sysroot`. - [Added `wasm` as a `target_family` for WebAssembly platforms.][84072] - [You can now use `#[target_feature]` on safe functions when targeting WebAssembly platforms.][84988] - [Improved debugger output for enums on Windows MSVC platforms.][85292] - [Added tier 3* support for `bpfel-unknown-none` and `bpfeb-unknown-none`.][79608] * Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries ----------------------- - [`panic::panic_any` will now `#[track_caller]`.][85745] - [Added `OutOfMemory` as a variant of `io::ErrorKind`.][84744] - [ `proc_macro::Literal` now implements `FromStr`.][84717] - [The implementations of vendor intrinsics in core::arch have been significantly refactored.][83278] The main user-visible changes are a 50% reduction in the size of libcore.rlib and stricter validation of constant operands passed to intrinsics. The latter is technically a breaking change, but allows Rust to more closely match the C vendor intrinsics API. Stabilized APIs --------------- - [`BTreeMap::into_keys`] - [`BTreeMap::into_values`] - [`HashMap::into_keys`] - [`HashMap::into_values`] - [`arch::wasm32`] - [`VecDeque::binary_search`] - [`VecDeque::binary_search_by`] - [`VecDeque::binary_search_by_key`] - [`VecDeque::partition_point`] Cargo ----------------------- - [Added the `--prune <spec>` option to `cargo-tree` to remove a package from the dependency graph.][cargo/9520] - [Added the `--depth` option to `cargo-tree` to print only to a certain depth in the tree ][cargo/9499] - [Added the `no-proc-macro` value to `cargo-tree --edges` to hide procedural macro dependencies.][cargo/9488] - [A new environment variable named `CARGO_TARGET_TMPDIR` is available.][cargo/9375] This variable points to a directory that integration tests and benches can use as a "scratchpad" for testing filesystem operations. [79608]: https://github.com/rust-lang/rust/pull/79608 [84988]: https://github.com/rust-lang/rust/pull/84988 [84701]: https://github.com/rust-lang/rust/pull/84701 [84072]: https://github.com/rust-lang/rust/pull/84072 [85745]: https://github.com/rust-lang/rust/pull/85745 [84744]: https://github.com/rust-lang/rust/pull/84744 [85078]: https://github.com/rust-lang/rust/pull/85078 [84717]: https://github.com/rust-lang/rust/pull/84717 [83800]: https://github.com/rust-lang/rust/pull/83800 [83366]: https://github.com/rust-lang/rust/pull/83366 [83278]: https://github.com/rust-lang/rust/pull/83278 [85292]: https://github.com/rust-lang/rust/pull/85292 [cargo/9520]: https://github.com/rust-lang/cargo/pull/9520 [cargo/9499]: https://github.com/rust-lang/cargo/pull/9499 [cargo/9488]: https://github.com/rust-lang/cargo/pull/9488 [cargo/9375]: https://github.com/rust-lang/cargo/pull/9375 [`BTreeMap::into_keys`]: https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.into_keys [`BTreeMap::into_values`]: https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.into_values [`HashMap::into_keys`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.into_keys [`HashMap::into_values`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.into_values [`arch::wasm32`]: https://doc.rust-lang.org/core/arch/wasm32/index.html [`VecDeque::binary_search`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.binary_search [`VecDeque::binary_search_by`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.binary_search_by [`VecDeque::binary_search_by_key`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.binary_search_by_key [`VecDeque::partition_point`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.partition_point </ins> Version 1.53.0 (2021-06-17) ============================


- [You can now use `#[repr(transparent)]` on univariant `enum`s.][68122] Meaning that you can create an enum that has the exact layout and ABI of the type it contains. <del> - [You can now use outer attribute procedural macros on inline modules.][64273] </del> <ins> - [You can now use outer attribute procedural macros on inline modules.][64273] </ins> - [There are some *syntax-only* changes:][67131] - `default` is syntactically allowed before items in `trait` definitions. - Items in `impl`s (i.e. `const`s, `type`s, and `fn`s) may syntactically


ty = it.type_(), path = relpath ); if parentlen == 0 { <del> // There is no sidebar-items.js beyond the crate root path // FIXME maybe dynamic crate loading can be merged here </del> <ins> write!( buffer, "<script defer src="{}sidebar-items{}.js"></script>", relpath, cx.shared.resource_suffix ); </ins> } else { <del> write!(buffer, "<script defer src="{path}sidebar-items.js"></script>", path = relpath); </del> <ins> write!(buffer, "<script defer src="{}sidebar-items.js"></script>", relpath); </ins> } // Closes sidebar-elems div. buffer.write_str("</div>"); }


)?; write_minify("search.js", static_files::SEARCH_JS)?; write_minify("settings.js", static_files::SETTINGS_JS)?; <ins> write_minify("sidebar-items.js", static_files::sidebar::ITEMS)?; </ins> if cx.shared.include_sources { write_minify("source-script.js", static_files::sidebar::SOURCE_SCRIPT)?; }


crate mod sidebar { /// File script to handle sidebar. crate static SOURCE_SCRIPT: &str = include_str!("static/source-script.js"); <ins> /// Top Level sidebar items script which will load a sidebar without items. crate static ITEMS: &str = include_str!("static/sidebar-items.js"); </ins> }


.define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap()) .define("LLVM_DEFAULT_TARGET_TRIPLE", target_native); <del> if target != "aarch64-apple-darwin" { </del> <ins> if target != "aarch64-apple-darwin" && !target.contains("windows") { </ins> cfg.define("LLVM_ENABLE_ZLIB", "ON"); } else { cfg.define("LLVM_ENABLE_ZLIB", "OFF");


use crate::cell::UnsafeCell; <del> use crate::mem::MaybeUninit; </del> <ins> use crate::mem::{forget, MaybeUninit}; </ins> use crate::sys::cvt_nz; use crate::sys_common::lazy_box::{LazyBox, LazyInit};


unsafe { mutex.init() }; mutex } <ins> fn destroy(mutex: Box<Self>) { // We're not allowed to pthread_mutex_destroy a locked mutex, // so check first if it's unlocked. if unsafe { mutex.try_lock() } { unsafe { mutex.unlock() }; drop(mutex); } else { // The mutex is locked. This happens if a MutexGuard is leaked. // In this case, we just leak the Mutex too. forget(mutex); } } fn cancel_init(_: Box<Self>) { // In this case, we can just drop it without any checks, // since it cannot have been locked yet. } </ins> } impl Mutex {


use crate::cell::UnsafeCell; <ins> use crate::mem::forget; </ins> use crate::sync::atomic::{AtomicUsize, Ordering}; use crate::sys_common::lazy_box::{LazyBox, LazyInit};


fn init() -> Box<Self> { Box::new(Self::new()) } <ins> fn destroy(mut rwlock: Box<Self>) { // We're not allowed to pthread_rwlock_destroy a locked rwlock, // so check first if it's unlocked. if *rwlock.write_locked.get_mut() || *rwlock.num_readers.get_mut() != 0 { // The rwlock is locked. This happens if a RwLock{Read,Write}Guard is leaked. // In this case, we just leak the RwLock too. forget(rwlock); } } fn cancel_init(_: Box<Self>) { // In this case, we can just drop it without any checks, // since it cannot have been locked yet. } </ins> } impl RwLock {


/// /// It might be called more than once per LazyBox, as multiple threads /// might race to initialize it concurrently, each constructing and initializing <del> /// their own box. (All but one of them will be destroyed right after.) </del> <ins> /// their own box. All but one of them will be passed to `cancel_init` right after. </ins> fn init() -> Box<Self>; <ins> /// Any surplus boxes from `init()` that lost the initialization race /// are passed to this function for disposal. /// /// The default implementation calls destroy(). fn cancel_init(x: Box<Self>) { Self::destroy(x); } /// This is called to destroy a used box. /// /// The default implementation just drops it. fn destroy(_: Box<Self>) {} </ins> } impl<T: LazyInit> LazyBox<T> {


Err(ptr) => { // Lost the race to another thread. // Drop the box we created, and use the one from the other thread instead. <del> drop(unsafe { Box::from_raw(new_ptr) }); </del> <ins> T::cancel_init(unsafe { Box::from_raw(new_ptr) }); </ins> ptr } }


fn drop(&mut self) { let ptr = *self.ptr.get_mut(); if !ptr.is_null() { <del> drop(unsafe { Box::from_raw(ptr) }); </del> <ins> T::destroy(unsafe { Box::from_raw(ptr) }); </ins> } } }


let prev_ptr = ptr.add(gap.write.wrapping_sub(1)); if same_bucket(&mut *read_ptr, &mut *prev_ptr) { <ins> // Increase `gap.read` now since the drop may panic. gap.read += 1; </ins> /* We have found duplicate, drop it in-place */ ptr::drop_in_place(read_ptr); } else {


/* We have filled that place, so go further */ gap.write += 1; <ins> gap.read += 1; </ins> } <del> gap.read += 1; </del> } /* Technically we could let `gap` clean up with its Drop, but


#[test] fn test_vec_dedup_panicking() { #[derive(Debug)] <del> struct Panic { drop_counter: &'static AtomicU32, </del> <ins> struct Panic<'a> { drop_counter: &'a Cell<u32>, </ins> value: bool, index: usize, } <del> impl PartialEq for Panic { </del> <ins> impl<'a> PartialEq for Panic<'a> { </ins> fn eq(&self, other: &Self) -> bool { self.value == other.value } } <del> impl Drop for Panic { </del> <ins> impl<'a> Drop for Panic<'a> { </ins> fn drop(&mut self) { <del> let x = self.drop_counter.fetch_add(1, Ordering::SeqCst); assert!(x != 4); </del> <ins> self.drop_counter.set(self.drop_counter.get() + 1); if !std::thread::panicking() { assert!(self.index != 4); } </ins> } } <del> static DROP_COUNTER: AtomicU32 = AtomicU32::new(0); </del> <ins> let drop_counter = &Cell::new(0); </ins> let expected = [ <del> Panic { drop_counter: &DROP_COUNTER, value: false, index: 0 }, Panic { drop_counter: &DROP_COUNTER, value: false, index: 5 }, Panic { drop_counter: &DROP_COUNTER, value: true, index: 6 }, Panic { drop_counter: &DROP_COUNTER, value: true, index: 7 }, </del> <ins> Panic { drop_counter, value: false, index: 0 }, Panic { drop_counter, value: false, index: 5 }, Panic { drop_counter, value: true, index: 6 }, Panic { drop_counter, value: true, index: 7 }, </ins> ]; let mut vec = vec![ <del> Panic { drop_counter: &DROP_COUNTER, value: false, index: 0 }, </del> <ins> Panic { drop_counter, value: false, index: 0 }, </ins> // these elements get deduplicated <del> Panic { drop_counter: &DROP_COUNTER, value: false, index: 1 }, Panic { drop_counter: &DROP_COUNTER, value: false, index: 2 }, Panic { drop_counter: &DROP_COUNTER, value: false, index: 3 }, Panic { drop_counter: &DROP_COUNTER, value: false, index: 4 }, // here it panics Panic { drop_counter: &DROP_COUNTER, value: false, index: 5 }, Panic { drop_counter: &DROP_COUNTER, value: true, index: 6 }, Panic { drop_counter: &DROP_COUNTER, value: true, index: 7 }, </del> <ins> Panic { drop_counter, value: false, index: 1 }, Panic { drop_counter, value: false, index: 2 }, Panic { drop_counter, value: false, index: 3 }, Panic { drop_counter, value: false, index: 4 }, // here it panics while dropping the item with index==4 Panic { drop_counter, value: false, index: 5 }, Panic { drop_counter, value: true, index: 6 }, Panic { drop_counter, value: true, index: 7 }, </ins> ]; <del> let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { vec.dedup(); })); </del> <ins> let _ = catch_unwind(AssertUnwindSafe(|| vec.dedup())).unwrap_err(); assert_eq!(drop_counter.get(), 4); </ins> let ok = vec.iter().zip(expected.iter()).all(|(x, y)| x.index == y.index);


<del> Subproject commit 62046bf8b4eadd4fb398d59f1eebcc140506bf85 </del> <ins> Subproject commit 4fa9363ebba236f7c29ae11180db6051d7d2ce3b </ins>


} } <ins> // This is required by the compiler to exist (e.g., it's a lang item), but it's // never actually called by the compiler.  Emscripten EH doesn't use a // personality function at all, it instead uses __cxa_find_matching_catch. // Wasm error handling would use __gxx_personality_wasm0. </ins> #[lang = "eh_personality"] unsafe extern "C" fn rust_eh_personality( <del> version: c_int, actions: uw::_Unwind_Action, exception_class: uw::_Unwind_Exception_Class, exception_object: *mut uw::_Unwind_Exception, context: *mut uw::_Unwind_Context, </del> <ins> _version: c_int, _actions: uw::_Unwind_Action, _exception_class: uw::_Unwind_Exception_Class, _exception_object: *mut uw::_Unwind_Exception, _context: *mut uw::_Unwind_Context, </ins> ) -> uw::_Unwind_Reason_Code { <del> __gxx_personality_v0(version, actions, exception_class, exception_object, context) </del> <ins> core::intrinsics::abort() </ins> } extern "C" {


tinfo: *const TypeInfo, dest: extern "C" fn(*mut libc::c_void) -> *mut libc::c_void, ) -> !; <del> fn __gxx_personality_v0( version: c_int, actions: uw::_Unwind_Action, exception_class: uw::_Unwind_Exception_Class, exception_object: *mut uw::_Unwind_Exception, context: *mut uw::_Unwind_Context, ) -> uw::_Unwind_Reason_Code; </del> }


<del> Subproject commit 453affaaa1762a065d2857970b8333017211208c </del> <ins> Subproject commit 5dde0fe6de2941c9ef16bc1e9d91ecf20ac5ee8b </ins>


use crate::cmp; <del> use crate::iter::{ adapters::zip::try_get_unchecked, adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedLen, TrustedRandomAccess, }; </del> <ins> use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedLen}; </ins> use crate::ops::{ControlFlow, Try}; /// An iterator that only iterates over the first `n` iterations of `iter`.


self.try_fold(init, ok(fold)).unwrap() } <del> unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> <I as Iterator>::Item where Self: TrustedRandomAccess, { // SAFETY: the caller must uphold the contract for // `Iterator::__iterator_get_unchecked`. unsafe { try_get_unchecked(&mut self.iter, idx) } } </del> } #[unstable(issue = "none", feature = "inplace_iteration")]


#[unstable(feature = "trusted_len", issue = "37572")] unsafe impl<I: TrustedLen> TrustedLen for Take<I> {} <del> #[doc(hidden)] #[unstable(feature = "trusted_random_access", issue = "none")] unsafe impl<I> TrustedRandomAccess for Take<I> where I: TrustedRandomAccess, { const MAY_HAVE_SIDE_EFFECT: bool = I::MAY_HAVE_SIDE_EFFECT; } </del>


#[test] fn smoke() { <ins> #[derive(Clone)] </ins> struct TypeWithDrop; impl Drop for TypeWithDrop { fn drop(&mut self) {


let x: Box<ManuallyDrop<[TypeWithDrop]>> = Box::new(ManuallyDrop::new([TypeWithDrop, TypeWithDrop])); drop(x); <ins> // test clone and clone_from implementations let mut x = ManuallyDrop::new(TypeWithDrop); let y = x.clone(); x.clone_from(&y); drop(x); drop(y); </ins> }


if let LinkerFlavor::Gcc = flavor { match ld_impl { LdImpl::Lld => { <del> let tools_path = sess.host_filesearch(PathKind::All).get_tools_search_paths(false); let lld_path = tools_path .into_iter() .map(|p| p.join("gcc-ld")) .find(|p| { p.join(if sess.host.is_like_windows { "ld.exe" } else { "ld" }).exists() }) .unwrap_or_else(|| sess.fatal("rust-lld (as ld) not found")); cmd.cmd().arg({ let mut arg = OsString::from("-B"); arg.push(lld_path); arg }); </del> <ins> if sess.target.lld_flavor == LldFlavor::Ld64 { let tools_path = sess.host_filesearch(PathKind::All).get_tools_search_paths(false); let ld64_exe = tools_path .into_iter() .map(|p| p.join("gcc-ld")) .map(|p| { p.join(if sess.host.is_like_windows { "ld64.exe" } else { "ld64" }) }) .find(|p| p.exists()) .unwrap_or_else(|| sess.fatal("rust-lld (as ld64) not found")); cmd.cmd().arg({ let mut arg = OsString::from("-fuse-ld="); arg.push(ld64_exe); arg }); } else { let tools_path = sess.host_filesearch(PathKind::All).get_tools_search_paths(false); let lld_path = tools_path .into_iter() .map(|p| p.join("gcc-ld")) .find(|p| { p.join(if sess.host.is_like_windows { "ld.exe" } else { "ld" }) .exists() }) .unwrap_or_else(|| sess.fatal("rust-lld (as ld) not found")); cmd.cmd().arg({ let mut arg = OsString::from("-B"); arg.push(lld_path); arg }); } </ins> } } } else {


use std::env; <del> use crate::spec::{FramePointer, SplitDebuginfo, TargetOptions}; </del> <ins> use crate::spec::{FramePointer, LldFlavor, SplitDebuginfo, TargetOptions}; </ins> pub fn opts(os: &str) -> TargetOptions { // ELF TLS is only available in macOS 10.7+. If you try to compile for 10.6


abi_return_struct_as_int: true, emit_debug_gdb_scripts: false, eh_frame_header: false, <ins> lld_flavor: LldFlavor::Ld64, </ins> // The historical default for macOS targets is to run `dsymutil` which // generates a packed version of debuginfo split from the main file.


&lld_install.join("bin").join(&src_exe), &gcc_ld_dir.join(exe("ld", target_compiler.host)), ); <ins> builder.copy( &lld_install.join("bin").join(&src_exe), &gcc_ld_dir.join(exe("ld64", target_compiler.host)), ); </ins> } // Similarly, copy `llvm-dwp` into libdir for Split DWARF. Only copy it when the LLVM


let gcc_lld_dir = dst_dir.join("gcc-ld"); t!(fs::create_dir(&gcc_lld_dir)); builder.copy(&src_dir.join(&rust_lld), &gcc_lld_dir.join(exe("ld", compiler.host))); <ins> builder .copy(&src_dir.join(&rust_lld), &gcc_lld_dir.join(exe("ld64", compiler.host))); </ins> } // Copy over llvm-dwp if it's there


padding: 0 20px 20px 17px;; } <ins> .item-info .stab { display: table; } </ins> .stab { border-width: 1px; border-style: solid;


<ins> // This test ensures that the item information don't take 100% of the width if unnecessary. goto: file://|DOC_PATH|/lib2/struct.Foo.html // We set a fixed size so there is no chance of "random" resize. size: (1100, 800) // We check that ".item-info" is bigger than its content. assert-css: (".item-info", {"width": "807px"}) assert-css: (".item-info .stab", {"width": "343px"}) </ins>


// ignore-tidy-linelength <ins> #![feature(doc_cfg)] </ins> pub mod module { pub mod sub_module { pub mod sub_sub_module {


pub type Alias = u32; <ins> #[doc(cfg(feature = "foo-method"))] </ins> pub struct Foo { pub x: Alias, }


} } } <del> PatKind::Lit(_) => { // If the PatKind is a Lit then we want </del> <ins> PatKind::Lit(_) | PatKind::Range(..) => { // If the PatKind is a Lit or a Range then we want </ins> // to borrow discr. needs_to_be_read = true; } <del> _ => {} </del> <ins> PatKind::Or(_) | PatKind::Box(_) | PatKind::Slice(..) | PatKind::Ref(..) | PatKind::Wild => { // If the PatKind is Or, Box, Slice or Ref, the decision is made later // as these patterns contains subpatterns // If the PatKind is Wild, the decision is made based on the other patterns being // examined } </ins> } })); }


<ins> // run-pass // edition:2021 pub fn foo() { let ref_x_ck = 123; let _y = || match ref_x_ck { 2_000_000..=3_999_999 => { println!("A")} _ => { println!("B")} }; } fn main() { foo(); } </ins>


let mut err = match *error { SelectionError::Unimplemented => { <del> // If this obligation was generated as a result of well-formed checking, see if we // can get a better error message by performing HIR-based well formed checking. </del> <ins> // If this obligation was generated as a result of well-formedness checking, see if we // can get a better error message by performing HIR-based well-formedness checking. </ins> if let ObligationCauseCode::WellFormed(Some(wf_loc)) = root_obligation.cause.code.peel_derives() {


// given the type `Option<MyStruct<u8>>`, we will check // `Option<MyStruct<u8>>`, `MyStruct<u8>`, and `u8`. // For each type, we perform a well-formed check, and see if we get <del> // an erorr that matches our expected predicate. We keep save </del> <ins> // an error that matches our expected predicate. We save </ins> // the `ObligationCause` corresponding to the *innermost* type, // which is the most specific type that we can point to. // In general, the different components of an `hir::Ty` may have <del> // completely differentr spans due to macro invocations. Pointing </del> <ins> // completely different spans due to macro invocations. Pointing </ins> // to the most accurate part of the type can be the difference // between a useless span (e.g. the macro invocation site) <del> // and a useful span (e.g. a user-provided type passed in to the macro). </del> <ins> // and a useful span (e.g. a user-provided type passed into the macro). </ins> // // This approach is quite inefficient - we redo a lot of work done // by the normal WF checker. However, this code is run at most once // per reported error - it will have no impact when compilation succeeds, <del> // and should only have an impact if a very large number of errors are // displaydd to the user. </del> <ins> // and should only have an impact if a very large number of errors is // displayed to the user. </ins> struct HirWfCheck<'tcx> { tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tcx>,


WellFormedLoc::Ty(_) => match hir.get(hir_id) { hir::Node::ImplItem(item) => match item.kind { hir::ImplItemKind::TyAlias(ty) => Some(ty), <ins> hir::ImplItemKind::Const(ty, _) => Some(ty), </ins> ref item => bug!("Unexpected ImplItem {:?}", item), }, hir::Node::TraitItem(item) => match item.kind { hir::TraitItemKind::Type(_, ty) => ty, <ins> hir::TraitItemKind::Const(ty, _) => Some(ty), </ins> ref item => bug!("Unexpected TraitItem {:?}", item), }, hir::Node::Item(item) => match item.kind {


<ins> // Regression test for the ICE described in #87495. trait T { const CONST: (bool, dyn T); //~^ ERROR: the trait `T` cannot be made into an object [E0038] } fn main() {} </ins>


<ins> error[E0038]: the trait `T` cannot be made into an object --> $DIR/issue-87495.rs:4:25 | LL |     const CONST: (bool, dyn T); |                         ^^^^^ `T` cannot be made into an object | = help: consider moving `CONST` to another trait note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety> --> $DIR/issue-87495.rs:4:11 | LL | trait T { |       - this trait cannot be made into an object... LL |     const CONST: (bool, dyn T); |           ^^^^^ ...because it contains this associated `const` error: aborting due to previous error For more information about this error, try `rustc --explain E0038`. </ins>


if let ObligationCauseCode::WellFormed(Some(wf_loc)) = root_obligation.cause.code.peel_derives() { <del> if let Some(cause) = self.tcx.diagnostic_hir_wf_check((obligation.predicate, wf_loc.clone())) { </del> <ins> if let Some(cause) = self.tcx.diagnostic_hir_wf_check(( tcx.erase_regions(obligation.predicate), wf_loc.clone(), )) { </ins> obligation.cause = cause; span = obligation.cause.span; }


<ins> // Regression test for #87549. // compile-flags: -C incremental=tmp/wf/hir-wf-check-erase-regions pub struct Table<T, const N: usize>([Option<T>; N]); impl<'a, T, const N: usize> IntoIterator for &'a Table<T, N> { type IntoIter = std::iter::Flatten<std::slice::Iter<'a, T>>; //~ ERROR `&T` is not an iterator type Item = &'a T; fn into_iter(self) -> Self::IntoIter { //~ ERROR `&T` is not an iterator unimplemented!() } } fn main() {} </ins>


<ins> error[E0277]: `&T` is not an iterator --> $DIR/hir-wf-check-erase-regions.rs:7:5 | LL |     type IntoIter = std::iter::Flatten<std::slice::Iter<'a, T>>; |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `&T` is not an iterator | ::: $SRC_DIR/core/src/iter/adapters/flatten.rs:LL:COL | LL | pub struct Flatten<I: Iterator<Item: IntoIterator>> { |                                      ------------ required by this bound in `Flatten` | = help: the trait `Iterator` is not implemented for `&T` = note: required because of the requirements on the impl of `IntoIterator` for `&T` error[E0277]: `&T` is not an iterator --> $DIR/hir-wf-check-erase-regions.rs:10:27 | LL |     fn into_iter(self) -> Self::IntoIter { |                           ^^^^^^^^^^^^^^ `&T` is not an iterator | ::: $SRC_DIR/core/src/iter/adapters/flatten.rs:LL:COL | LL | pub struct Flatten<I: Iterator<Item: IntoIterator>> { |                                      ------------ required by this bound in `Flatten` | = help: the trait `Iterator` is not implemented for `&T` = note: required because of the requirements on the impl of `IntoIterator` for `&T` error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0277`. </ins>


if def.variants.len() > 1 { needs_to_be_read = true; } <ins> } else { // If it is not ty::Adt, then it should be read needs_to_be_read = true; </ins> } } PatKind::Lit(_) | PatKind::Range(..) => {


<ins> // run-pass // edition:2021 const LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED: i32 = 0x01; const LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT: i32 = 0x02; pub fn hotplug_callback(event: i32) { let _ = || { match event { LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED => (), LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT => (), _ => (), }; }; } fn main() { hotplug_callback(1); } </ins>


<ins> // run-pass // edition:2021 const PATTERN_REF: &str = "Hello World"; const NUMBER: i32 = 30; const NUMBER_POINTER: *const i32 = &NUMBER; pub fn edge_case_ref(event: &str) { let _ = || { match event { PATTERN_REF => (), _ => (), }; }; } pub fn edge_case_str(event: String) { let _ = || { match event.as_str() { "hello" => (), _ => (), }; }; } pub fn edge_case_raw_ptr(event: *const i32) { let _ = || { match event { NUMBER_POINTER => (), _ => (), }; }; } pub fn edge_case_char(event: char) { let _ = || { match event { 'a' => (), _ => (), }; }; } fn main() {} </ins>


impl AddCallGuards { pub fn add_call_guards(&self, body: &mut Body<'_>) { <del> let pred_count: IndexVec<_, _> = body.predecessors().iter().map(|ps| ps.len()).collect(); </del> <ins> let mut pred_count: IndexVec<_, _> = body.predecessors().iter().map(|ps| ps.len()).collect(); pred_count[START_BLOCK] += 1; </ins> // We need a place to store the new blocks generated let mut new_blocks = Vec::new();


// CHECK-LABEL: @main fn main() { take_until(|| true); <ins> f(None); </ins> } <ins> fn f(_a: Option<String>) -> Option<u32> { loop { g(); () } } fn g() -> Option<u32> { None } </ins>


if let Some(hir::Guard::If(ref e)) = arm.guard { self.consume_expr(e) <ins> } else if let Some(hir::Guard::IfLet(_, ref e)) = arm.guard { self.consume_expr(e) </ins> } self.consume_expr(&arm.body);


<ins> // edition:2021 // run-pass #![feature(if_let_guard)] #[allow(unused_must_use)] #[allow(dead_code)] fn print_error_count(registry: &Registry) { |x: &Registry| { match &x { Registry if let _ = registry.try_find_description() => { } //~^ WARNING: irrefutable `if let` guard pattern _ => {} } }; } struct Registry; impl Registry { pub fn try_find_description(&self) { unimplemented!() } } fn main() {} </ins>


<ins> warning: irrefutable `if let` guard pattern --> $DIR/issue-88118-2.rs:10:29 | LL |             Registry if let _ = registry.try_find_description() => { } |                             ^ | = note: `#[warn(irrefutable_let_patterns)]` on by default = note: this pattern will always match, so the guard is useless = help: consider removing the guard and adding a `let` inside the match arm warning: 1 warning emitted </ins>


} fn check_fn_decl(&self, fn_decl: &FnDecl, self_semantic: SelfSemantic) { <ins> self.check_decl_num_args(fn_decl); </ins> self.check_decl_cvaradic_pos(fn_decl); self.check_decl_attrs(fn_decl); self.check_decl_self_param(fn_decl, self_semantic); } <ins> /// Emits fatal error if function declaration has more than `u16::MAX` arguments /// Error is fatal to prevent errors during typechecking fn check_decl_num_args(&self, fn_decl: &FnDecl) { let max_num_args: usize = u16::MAX.into(); if fn_decl.inputs.len() > max_num_args { let Param { span, .. } = fn_decl.inputs[0]; self.err_handler().span_fatal( span, &format!("function can not have more than {} arguments", max_num_args), ); } } </ins> fn check_decl_cvaradic_pos(&self, fn_decl: &FnDecl) { match &*fn_decl.inputs { [Param { ty, span, .. }] => {


<ins> macro_rules! many_args { ([$($t:tt)*]#$($h:tt)*) => { many_args!{[$($t)*$($t)*]$($h)*} }; ([$($t:tt)*]) => { fn _f($($t: ()),*) {} //~ ERROR function can not have more than 65535 arguments } } many_args!{[_]########## ######} fn main() {} </ins>


<ins> error: function can not have more than 65535 arguments --> $DIR/issue-88577-check-fn-with-more-than-65535-arguments.rs:6:24 | LL |           fn _f($($t: ()),*) {} |  ________________________^ LL | |     } LL | | } LL | | LL | | many_args!{[_]########## ######} | |____________^ error: aborting due to previous error </ins>


struct_span_err!(sess, sp, E0004, "{}", &error_message) } <ins> #[derive(PartialEq)] enum RefutableFlag { Irrefutable, Refutable, } use RefutableFlag::*; </ins> struct MatchVisitor<'a, 'p, 'tcx> { tcx: TyCtxt<'tcx>, typeck_results: &'a ty::TypeckResults<'tcx>,


hir::LocalSource::AssignDesugar(_) => ("destructuring assignment binding", None), }; self.check_irrefutable(&loc.pat, msg, sp); <del> self.check_patterns(&loc.pat); </del> <ins> self.check_patterns(&loc.pat, Irrefutable); </ins> } fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) { intravisit::walk_param(self, param); self.check_irrefutable(&param.pat, "function argument", None); <del> self.check_patterns(&param.pat); </del> <ins> self.check_patterns(&param.pat, Irrefutable); </ins> } }


} impl<'p, 'tcx> MatchVisitor<'_, 'p, 'tcx> { <del> fn check_patterns(&self, pat: &Pat<'_>) { </del> <ins> fn check_patterns(&self, pat: &Pat<'_>, rf: RefutableFlag) { </ins> pat.walk_always(|pat| check_borrow_conflicts_in_at_patterns(self, pat)); <del> check_for_bindings_named_same_as_variants(self, pat); </del> <ins> check_for_bindings_named_same_as_variants(self, pat, rf); </ins> } fn lower_pattern(


} fn check_let(&mut self, pat: &'tcx hir::Pat<'tcx>, expr: &hir::Expr<'_>, span: Span) { <del> self.check_patterns(pat); </del> <ins> self.check_patterns(pat, Refutable); </ins> let mut cx = self.new_cx(expr.hir_id); let tpat = self.lower_pattern(&mut cx, pat, &mut false); check_let_reachability(&mut cx, pat.hir_id, tpat, span);


for arm in arms { // Check the arm for some things unrelated to exhaustiveness. <del> self.check_patterns(&arm.pat); </del> <ins> self.check_patterns(&arm.pat, Refutable); </ins> if let Some(hir::Guard::IfLet(ref pat, _)) = arm.guard { <del> self.check_patterns(pat); </del> <ins> self.check_patterns(pat, Refutable); </ins> let tpat = self.lower_pattern(&mut cx, pat, &mut false); check_let_reachability(&mut cx, pat.hir_id, tpat, tpat.span()); }


} } <del> fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor<'_, '_, '_>, pat: &Pat<'_>) { </del> <ins> fn check_for_bindings_named_same_as_variants( cx: &MatchVisitor<'_, '_, '_>, pat: &Pat<'_>, rf: RefutableFlag, ) { </ins> pat.walk_always(|p| { if let hir::PatKind::Binding(_, _, ident, None) = p.kind { if let Some(ty::BindByValue(hir::Mutability::Not)) =


variant.ident == ident && variant.ctor_kind == CtorKind::Const }) { <ins> let variant_count = edef.variants.len(); </ins> cx.tcx.struct_span_lint_hir( BINDINGS_WITH_VARIANT_NAME, p.hir_id, p.span, |lint| { let ty_path = cx.tcx.def_path_str(edef.did); <del> lint.build(&format!( </del> <ins> let mut err = lint.build(&format!( </ins> "pattern binding `{}` is named the same as one  <del> of the variants of the type `{}`", </del> <ins> of the variants of the type `{}`", </ins> ident, ty_path <del> )) .code(error_code!(E0170)) .span_suggestion( p.span, "to match on the variant, qualify the path", format!("{}::{}", ty_path, ident), Applicability::MachineApplicable, ) .emit(); </del> <ins> )); err.code(error_code!(E0170)); // If this is an irrefutable pattern, and there's > 1 variant, // then we can't actually match on this. Applying the below // suggestion would produce code that breaks on `check_irrefutable`. if rf == Refutable || variant_count == 1 { err.span_suggestion( p.span, "to match on the variant, qualify the path", format!("{}::{}", ty_path, ident), Applicability::MachineApplicable, ); } err.emit(); </ins> }, ) }


<ins> #![allow(unused, nonstandard_style)] #![deny(bindings_with_variant_name)] // If an enum has two different variants, // then it cannot be matched upon in a function argument. // It still gets a warning, but no suggestions. enum Foo { C, D, } fn foo(C: Foo) {} //~ERROR fn main() { let C = Foo::D; //~ERROR } </ins>


<ins> error[E0170]: pattern binding `C` is named the same as one of the variants of the type `Foo` --> $DIR/issue-88730.rs:12:8 | LL | fn foo(C: Foo) {} |        ^ | note: the lint level is defined here --> $DIR/issue-88730.rs:2:9 | LL | #![deny(bindings_with_variant_name)] |         ^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0170]: pattern binding `C` is named the same as one of the variants of the type `Foo` --> $DIR/issue-88730.rs:15:9 | LL |     let C = Foo::D; |         ^ error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0170`. </ins>


if self.not_enough_args_provided() { self.suggest_adding_args(err); } else if self.too_many_args_provided() { <ins> self.suggest_moving_args_from_assoc_fn_to_trait(err); </ins> self.suggest_removing_args_or_generics(err); } else { unreachable!();


} } <ins> /// Suggests moving redundant argument(s) of an associate function to the /// trait it belongs to. /// /// ```compile_fail /// Into::into::<Option<_>>(42) // suggests considering `Into::<Option<_>>::into(42)` /// ``` fn suggest_moving_args_from_assoc_fn_to_trait(&self, err: &mut Diagnostic) { let trait_ = match self.tcx.trait_of_item(self.def_id) { Some(def_id) => def_id, None => return, }; // Skip suggestion when the associated function is itself generic, it is unclear // how to split the provided parameters between those to suggest to the trait and // those to remain on the associated type. let num_assoc_fn_expected_args = self.num_expected_type_or_const_args() + self.num_expected_lifetime_args(); if num_assoc_fn_expected_args > 0 { return; } let num_assoc_fn_excess_args = self.num_excess_type_or_const_args() + self.num_excess_lifetime_args(); let trait_generics = self.tcx.generics_of(trait_); let num_trait_generics_except_self = trait_generics.count() - if trait_generics.has_self { 1 } else { 0 }; let msg = format!( "consider moving {these} generic argument{s} to the `{name}` trait, which takes up to {num} argument{s}", these = pluralize!("this", num_assoc_fn_excess_args), s = pluralize!(num_assoc_fn_excess_args), name = self.tcx.item_name(trait_), num = num_trait_generics_except_self, ); if let Some(hir_id) = self.path_segment.hir_id && let Some(parent_node) = self.tcx.hir().find_parent_node(hir_id) && let Some(parent_node) = self.tcx.hir().find(parent_node) && let hir::Node::Expr(expr) = parent_node { match expr.kind { hir::ExprKind::Path(ref qpath) => { self.suggest_moving_args_from_assoc_fn_to_trait_for_qualified_path( err, qpath, msg, num_assoc_fn_excess_args, num_trait_generics_except_self ) }, hir::ExprKind::MethodCall(..) => { self.suggest_moving_args_from_assoc_fn_to_trait_for_method_call( err, trait_, expr, msg, num_assoc_fn_excess_args, num_trait_generics_except_self ) }, _ => return, } } } fn suggest_moving_args_from_assoc_fn_to_trait_for_qualified_path( &self, err: &mut Diagnostic, qpath: &'tcx hir::QPath<'tcx>, msg: String, num_assoc_fn_excess_args: usize, num_trait_generics_except_self: usize, ) { if let hir::QPath::Resolved(_, path) = qpath && let Some(trait_path_segment) = path.segments.get(0) { let num_generic_args_supplied_to_trait = trait_path_segment.args().num_generic_params(); if num_assoc_fn_excess_args == num_trait_generics_except_self - num_generic_args_supplied_to_trait { if let Some(span) = self.gen_args.span_ext() && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) { let sugg = vec![ (self.path_segment.ident.span, format!("{}::{}", snippet, self.path_segment.ident)), (span.with_lo(self.path_segment.ident.span.hi()), "".to_owned()) ]; err.multipart_suggestion( msg, sugg, Applicability::MaybeIncorrect ); } } } } fn suggest_moving_args_from_assoc_fn_to_trait_for_method_call( &self, err: &mut Diagnostic, trait_: DefId, expr: &'tcx hir::Expr<'tcx>, msg: String, num_assoc_fn_excess_args: usize, num_trait_generics_except_self: usize, ) { if let hir::ExprKind::MethodCall(_, args, _) = expr.kind { assert_eq!(args.len(), 1); if num_assoc_fn_excess_args == num_trait_generics_except_self { if let Some(gen_args) = self.gen_args.span_ext() && let Ok(gen_args) = self.tcx.sess.source_map().span_to_snippet(gen_args) && let Ok(args) = self.tcx.sess.source_map().span_to_snippet(args[0].span) { let sugg = format!("{}::{}::{}({})", self.tcx.item_name(trait_), gen_args, self.tcx.item_name(self.def_id), args); err.span_suggestion(expr.span, msg, sugg, Applicability::MaybeIncorrect); } } } } </ins> /// Suggests to remove redundant argument(s): /// /// ```text


--> $DIR/invalid-const-arg-for-type-param.rs:6:23 | LL |     let _: u32 = 5i32.try_into::<32>().unwrap(); <del> |                       ^^^^^^^^------ help: remove these generics |                       | |                       expected 0 generic arguments </del> <ins> |                       ^^^^^^^^ expected 0 generic arguments </ins> | note: associated function defined here, with 0 generic parameters --> $SRC_DIR/core/src/convert/mod.rs:LL:COL | LL |     fn try_into(self) -> Result<T, Self::Error>; |        ^^^^^^^^ <ins> help: consider moving this generic argument to the `TryInto` trait, which takes up to 1 argument | LL |     let _: u32 = TryInto::<32>::try_into(5i32).unwrap(); |                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ help: remove these generics | LL -     let _: u32 = 5i32.try_into::<32>().unwrap(); LL +     let _: u32 = 5i32.try_into().unwrap(); | </ins> error[E0599]: no method named `f` found for struct `S` in the current scope --> $DIR/invalid-const-arg-for-type-param.rs:9:7


<ins> use std::convert::TryInto; trait A<T> { fn foo() {} } trait B<T, U> { fn bar() {} } struct S; impl<T> A<T> for S {} impl<T, U> B<T, U> for S {} fn main() { let _ = A::foo::<S>(); //~^ ERROR //~| HELP remove these generics //~| HELP consider moving this generic argument let _ = B::bar::<S, S>(); //~^ ERROR //~| HELP remove these generics //~| HELP consider moving these generic arguments let _ = A::<S>::foo::<S>(); //~^ ERROR //~| HELP remove these generics let _ = 42.into::<Option<_>>(); //~^ ERROR //~| HELP remove these generics //~| HELP consider moving this generic argument } </ins>


<ins> error[E0107]: this associated function takes 0 generic arguments but 1 generic argument was supplied --> $DIR/issue-89064.rs:17:16 | LL |     let _ = A::foo::<S>(); |                ^^^ expected 0 generic arguments | note: associated function defined here, with 0 generic parameters --> $DIR/issue-89064.rs:4:8 | LL |     fn foo() {} |        ^^^ help: consider moving this generic argument to the `A` trait, which takes up to 1 argument | LL -     let _ = A::foo::<S>(); LL +     let _ = A::<S>::foo(); | help: remove these generics | LL -     let _ = A::foo::<S>(); LL +     let _ = A::foo(); | error[E0107]: this associated function takes 0 generic arguments but 2 generic arguments were supplied --> $DIR/issue-89064.rs:22:16 | LL |     let _ = B::bar::<S, S>(); |                ^^^ expected 0 generic arguments | note: associated function defined here, with 0 generic parameters --> $DIR/issue-89064.rs:8:8 | LL |     fn bar() {} |        ^^^ help: consider moving these generic arguments to the `B` trait, which takes up to 2 arguments | LL -     let _ = B::bar::<S, S>(); LL +     let _ = B::<S, S>::bar(); | help: remove these generics | LL -     let _ = B::bar::<S, S>(); LL +     let _ = B::bar(); | error[E0107]: this associated function takes 0 generic arguments but 1 generic argument was supplied --> $DIR/issue-89064.rs:27:21 | LL |     let _ = A::<S>::foo::<S>(); |                     ^^^----- help: remove these generics |                     | |                     expected 0 generic arguments | note: associated function defined here, with 0 generic parameters --> $DIR/issue-89064.rs:4:8 | LL |     fn foo() {} |        ^^^ error[E0107]: this associated function takes 0 generic arguments but 1 generic argument was supplied --> $DIR/issue-89064.rs:31:16 | LL |     let _ = 42.into::<Option<_>>(); |                ^^^^ expected 0 generic arguments | note: associated function defined here, with 0 generic parameters --> $SRC_DIR/core/src/convert/mod.rs:LL:COL | LL |     fn into(self) -> T; |        ^^^^ help: consider moving this generic argument to the `Into` trait, which takes up to 1 argument | LL |     let _ = Into::<Option<_>>::into(42); |             ~~~~~~~~~~~~~~~~~~~~~~~~~~~ help: remove these generics | LL -     let _ = 42.into::<Option<_>>(); LL +     let _ = 42.into(); | error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0107`. </ins>


} impl<'tcx> FieldDef { <del> /// Returns the type of this field. The `subst` is typically obtained /// via the second field of `TyKind::AdtDef`. </del> <ins> /// Returns the type of this field. The resulting type is not normalized. The `subst` is /// typically obtained via the second field of `TyKind::AdtDef`. </ins> pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> { tcx.type_of(self.did).subst(tcx, subst) }


variant.fields.iter().enumerate().filter_map(move |(i, field)| { let ty = field.ty(cx.tcx, substs); <ins> // `field.ty()` doesn't normalize after substituting. let ty = cx.tcx.normalize_erasing_regions(cx.param_env, ty); </ins> let is_visible = adt.is_enum() || field.vis.is_accessible_from(cx.module, cx.tcx); let is_uninhabited = cx.is_uninhabited(ty);


write!(f, "{}", hi) } IntRange(range) => write!(f, "{:?}", range), // Best-effort, will render e.g. `false` as `0..=0` <del> Wildcard | Missing { .. } | NonExhaustive => write!(f, "_"), </del> <ins> Wildcard | Missing { .. } | NonExhaustive => write!(f, "_ : {:?}", self.ty), </ins> Or => { for pat in self.iter_fields() { write!(f, "{}{:?}", start_or_continue(" | "), pat)?;


assert!(rows.iter().all(|r| r.len() == v.len())); <del> // FIXME(Nadrieril): Hack to work around type normalization issues (see #72476). let ty = matrix.heads().next().map_or(v.head().ty(), |r| r.ty()); </del> <ins> let ty = v.head().ty(); </ins> let is_non_exhaustive = cx.is_foreign_non_exhaustive_enum(ty); let pcx = PatCtxt { cx, ty, span: v.head().span(), is_top_level, is_non_exhaustive };


<ins> // check-pass // From https://github.com/rust-lang/rust/issues/72476 // and https://github.com/rust-lang/rust/issues/89393 trait Trait { type Projection; } struct A; impl Trait for A { type Projection = bool; } struct B; impl Trait for B { type Projection = (u32, u32); } struct Next<T: Trait>(T::Projection); fn foo1(item: Next<A>) { match item { Next(true) => {} Next(false) => {} } } fn foo2(x: <A as Trait>::Projection) { match x { true => {} false => {} } } fn foo3(x: Next<B>) { let Next((_, _)) = x; match x { Next((_, _)) => {} } } fn foo4(x: <B as Trait>::Projection) { let (_, _) = x; match x { (_, _) => {} } } fn foo5<T: Trait>(x: <T as Trait>::Projection) { match x { _ => {} } } fn main() {} </ins>


<del> // check-pass // From https://github.com/rust-lang/rust/issues/72476 trait A { type Projection; } impl A for () { type Projection = bool; } struct Next<T: A>(T::Projection); fn f(item: Next<()>) { match item { Next(true) => {} Next(false) => {} } } fn main() {} </del>


<del> Subproject commit 18667a856596713fc4479f99b96afc7f03aa995c </del> <ins> Subproject commit fa91a89193d26e6a86e2eee1cbaa38cb28ccebe1 </ins>


fn universe_for(&mut self, debruijn: ty::DebruijnIndex) -> ty::UniverseIndex { let infcx = self.infcx; let index = <del> self.universe_indices.len() - debruijn.as_usize() + self.current_index.as_usize() - 1; </del> <ins> self.universe_indices.len() + self.current_index.as_usize() - debruijn.as_usize() - 1; </ins> let universe = self.universe_indices[index].unwrap_or_else(|| { for i in self.universe_indices.iter_mut().take(index + 1) { *i = i.or_else(|| Some(infcx.create_next_universe()))


!ptr.is_null() && ptr as usize % mem::align_of::<T>() == 0 } <ins> /// Checks whether the regions of memory starting at `src` and `dst` of size /// `count * size_of::<T>()` do *not* overlap. #[cfg(debug_assertions)] pub(crate) fn is_nonoverlapping<T>(src: *const T, dst: *const T, count: usize) -> bool { let src_usize = src as usize; let dst_usize = dst as usize; let size = mem::size_of::<T>().checked_mul(count).unwrap(); let diff = if src_usize > dst_usize { src_usize - dst_usize } else { dst_usize - src_usize }; // If the absolute distance between the ptrs is at least as big as the size of the buffer, // they do not overlap. diff >= size } </ins> /// Copies `count * size_of::<T>()` bytes from `src` to `dst`. The source /// and destination must *not* overlap. ///


pub fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize); } <del> // FIXME: Perform these checks only at run time /*if cfg!(debug_assertions) && !(is_aligned_and_not_null(src) && is_aligned_and_not_null(dst) && is_nonoverlapping(src, dst, count)) { // Not panicking to keep codegen impact smaller. abort(); }*/ </del> <ins> #[cfg(debug_assertions)] fn runtime_check<T>(src: *const T, dst: *mut T, count: usize) { if !is_aligned_and_not_null(src) || !is_aligned_and_not_null(dst) || !is_nonoverlapping(src, dst, count) { // Not panicking to keep codegen impact smaller. abort(); } } #[cfg(debug_assertions)] const fn compiletime_check<T>(_src: *const T, _dst: *mut T, _count: usize) {} #[cfg(debug_assertions)] // SAFETY: runtime debug-assertions are a best-effort basis; it's fine to // not do them during compile time unsafe { const_eval_select((src, dst, count), compiletime_check, runtime_check); } </ins> // SAFETY: the safety contract for `copy_nonoverlapping` must be // upheld by the caller.


fn copy<T>(src: *const T, dst: *mut T, count: usize); } <del> // FIXME: Perform these checks only at run time /*if cfg!(debug_assertions) && !(is_aligned_and_not_null(src) && is_aligned_and_not_null(dst)) { // Not panicking to keep codegen impact smaller. abort(); }*/ </del> <ins> #[cfg(debug_assertions)] fn runtime_check<T>(src: *const T, dst: *mut T) { if !is_aligned_and_not_null(src) || !is_aligned_and_not_null(dst) { // Not panicking to keep codegen impact smaller. abort(); } } #[cfg(debug_assertions)] const fn compiletime_check<T>(_src: *const T, _dst: *mut T) {} #[cfg(debug_assertions)] // SAFETY: runtime debug-assertions are a best-effort basis; it's fine to // not do them during compile time unsafe { const_eval_select((src, dst), compiletime_check, runtime_check); } </ins> // SAFETY: the safety contract for `copy` must be upheld by the caller. unsafe { copy(src, dst, count) }


#![feature(const_caller_location)] #![feature(const_cell_into_inner)] #![feature(const_discriminant)] <del> #![cfg_attr(not(bootstrap), feature(const_eval_select))] </del> <ins> #![feature(const_eval_select)] </ins> #![feature(const_float_bits_conv)] #![feature(const_float_classify)] #![feature(const_fmt_arguments_new)]


// Save the index of all fields regardless of their visibility in case // of error recovery. self.write_field_index(expr.hir_id, index); <ins> let adjustments = self.adjust_steps(&autoderef); </ins> if field.vis.is_accessible_from(def_scope, self.tcx) { <del> let adjustments = self.adjust_steps(&autoderef); </del> self.apply_adjustments(base, adjustments); self.register_predicates(autoderef.into_obligations()); self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None); return field_ty; } <del> private_candidate = Some((base_def.did, field_ty)); </del> <ins> private_candidate = Some((adjustments, base_def.did, field_ty)); </ins> } } ty::Tuple(tys) => {


} self.structurally_resolved_type(autoderef.span(), autoderef.final_ty(false)); <del> if let Some((did, field_ty)) = private_candidate { </del> <ins> if let Some((adjustments, did, field_ty)) = private_candidate { // (#90483) apply adjustments to avoid ExprUseVisitor from // creating erroneous projection. self.apply_adjustments(base, adjustments); </ins> self.ban_private_field_access(expr, expr_t, field, did); return field_ty; }


<ins> // edition:2021 mod m { pub struct S { foo: i32 } impl S { pub fn foo(&self) -> i32 { 42 } } } fn bar(s: &m::S) { || s.foo() + s.foo; //~ ERROR E0616 } fn main() {} </ins>


<ins> error[E0616]: field `foo` of struct `S` is private --> $DIR/issue-90483-inaccessible-field-adjustment.rs:11:18 | LL |   || s.foo() + s.foo; |                  ^^^ private field | help: a method `foo` also exists, call it with parentheses | LL |   || s.foo() + s.foo(); |                     ++ error: aborting due to previous error For more information about this error, try `rustc --explain E0616`. </ins>


<del> Subproject commit 01c8b654f9a01371414d1fd69cba38b289510a9e </del> <ins> Subproject commit 2b9078f4afae82f60c5ac0fdb4af42d269e2f2f3 </ins>