<ins> // Copyright 2014 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. // Regression test for #3512 - conflicting trait impls in different crates should give a // 'conflicting implementations' error message. // aux-build:trait_impl_conflict.rs extern mod trait_impl_conflict; use trait_impl_conflict::Foo; impl<A> Foo for A { //~^ ERROR conflicting implementations for trait `trait_impl_conflict::Foo` //~^^ ERROR cannot provide an extension implementation where both trait and type are not defined in this crate } fn main() { } </ins>


let &(ref first_arm_pats, _) = &arms[0]; let first_pat = &first_arm_pats[0]; let span = first_pat.span; <del> span_err!(cx.tcx.sess, span, E0165, "irrefutable while-let pattern"); </del> <ins> struct_span_err!(cx.tcx.sess, span, E0165, "irrefutable while-let pattern") .span_label(span, &format!("irrefutable pattern")) .emit(); </ins> }, hir::MatchSource::ForLoopDesugar => {


tcx.sess.add_lint(lint::builtin::MATCH_OF_UNIT_VARIANT_VIA_PAREN_DOTDOT, pat.id, pat.span, msg); } else { <del> span_err!(tcx.sess, pat.span, E0164, "{}", msg); </del> <ins> struct_span_err!(tcx.sess, pat.span, E0164, "{}", msg) .span_label(pat.span, &format!("not a tuple variant or struct")).emit(); </ins> on_error(); } };


.emit(); } Err(CopyImplementationError::HasDestructor) => { <del> span_err!(tcx.sess, span, E0184, </del> <ins> struct_span_err!(tcx.sess, span, E0184, </ins> "the trait `Copy` may not be implemented for this type;  <del> the type has a destructor"); </del> <ins> the type has a destructor") .span_label(span, &format!("Copy not allowed on types with destructors")) .emit(); </ins> } } });


fn bar(foo: Foo) -> u32 { match foo { Foo::B(i) => i, //~ ERROR E0164 <ins> //~| NOTE not a tuple variant or struct </ins> } }


fn main() { let irr = Irrefutable(0); while let Irrefutable(x) = irr { //~ ERROR E0165 <ins> //~| irrefutable pattern </ins> // ... } }


// except according to those terms. #[derive(Copy)] //~ ERROR E0184 <ins> //~| NOTE Copy not allowed on types with destructors //~| NOTE in this expansion of #[derive(Copy)] </ins> struct Foo; impl Drop for Foo {


return Error(span, "missing fragment specifier".to_string()); } } <del> TokenTree::MetaVarDecl(..) => { </del> <ins> TokenTree::MetaVarDecl(_, _, id) => { </ins> // Built-in nonterminals never start with these tokens, // so we can eliminate them from consideration. <del> match *token { token::CloseDelim(_) => {}, _ => bb_eis.push(ei), </del> <ins> if may_begin_with(&*id.name.as_str(), token) { bb_eis.push(ei); </ins> } } seq @ TokenTree::Delimited(..) | seq @ TokenTree::Token(_, DocComment(..)) => {


} } <ins> /// Checks whether a non-terminal may begin with a particular token. /// /// Returning `false` is a *stability guarantee* that such a matcher will *never* begin with that /// token. Be conservative (return true) if not sure. fn may_begin_with(name: &str, token: &Token) -> bool { /// Checks whether the non-terminal may contain a single (non-keyword) identifier. fn may_be_ident(nt: &token::Nonterminal) -> bool { match *nt { token::NtItem(_) | token::NtBlock(_) | token::NtVis(_) => false, _ => true, } } match name { "expr" => token.can_begin_expr(), "ty" => token.can_begin_type(), "ident" => token.is_ident(), "vis" => match *token { // The follow-set of :vis + "priv" keyword + interpolated Token::Comma | Token::Ident(_) | Token::Interpolated(_) => true, _ => token.can_begin_type(), }, "block" => match *token { Token::OpenDelim(token::Brace) => true, Token::Interpolated(ref nt) => match nt.0 { token::NtItem(_) | token::NtPat(_) | token::NtTy(_) | token::NtIdent(_) | token::NtMeta(_) | token::NtPath(_) | token::NtVis(_) => false, // none of these may start with '{'. _ => true, }, _ => false, }, "path" | "meta" => match *token { Token::ModSep | Token::Ident(_) => true, Token::Interpolated(ref nt) => match nt.0 { token::NtPath(_) | token::NtMeta(_) => true, _ => may_be_ident(&nt.0), }, _ => false, }, "pat" => match *token { Token::Ident(_) |               // box, ref, mut, and other identifiers (can stricten) Token::OpenDelim(token::Paren) |    // tuple pattern Token::OpenDelim(token::Bracket) |  // slice pattern Token::BinOp(token::And) |          // reference Token::BinOp(token::Minus) |        // negative literal Token::AndAnd |                     // double reference Token::Literal(..) |                // literal Token::DotDot |                     // range pattern (future compat) Token::DotDotDot |                  // range pattern (future compat) Token::ModSep |                     // path Token::Lt |                         // path (UFCS constant) Token::BinOp(token::Shl) |          // path (double UFCS) Token::Underscore => true,          // placeholder Token::Interpolated(ref nt) => may_be_ident(&nt.0), _ => false, }, _ => match *token { token::CloseDelim(_) => false, _ => true, }, } } </ins> fn parse_nt<'a>(p: &mut Parser<'a>, sp: Span, name: &str) -> Nonterminal { if name == "tt" { return token::NtTT(p.parse_token_tree());


// except according to those terms. fn main() { <del> panic!(@); //~ ERROR expected expression, found `@` </del> <ins> panic!(@); //~ ERROR no rules expected the token `@` </ins> }


// except according to those terms. pub fn main() { <del> vec![,]; //~ ERROR expected expression, found `,` </del> <ins> vec![,]; //~ ERROR no rules expected the token `,` </ins> }


<ins> // Copyright 2017 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. #![feature(macro_vis_matcher)] //{{{ issue 40569 ============================================================== macro_rules! my_struct { ($(#[$meta:meta])* $ident:ident) => { $(#[$meta])* struct $ident; } } my_struct!(#[derive(Debug, PartialEq)] Foo40569); fn test_40569() { assert_eq!(Foo40569, Foo40569); } //}}} //{{{ issue 26444 ============================================================== macro_rules! foo_26444 { ($($beginning:ident),*; $middle:ident; $($end:ident),*) => { stringify!($($beginning,)* $middle $(,$end)*) } } fn test_26444() { assert_eq!("a , b , c , d , e", foo_26444!(a, b; c; d, e)); assert_eq!("f", foo_26444!(; f ;)); } macro_rules! pat_26444 { ($fname:ident $($arg:pat)* =) => {} } pat_26444!(foo 1 2 5...7 =); pat_26444!(bar Some(ref x) Ok(ref mut y) &(w, z) =); //}}} //{{{ issue 40984 ============================================================== macro_rules! thread_local_40984 { () => {}; ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => { thread_local_40984!($($rest)*); }; ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr) => {}; } thread_local_40984! { // no docs #[allow(unused)] static FOO: i32 = 42; /// docs pub static BAR: String = String::from("bar"); // look at these restrictions!! pub(crate) static BAZ: usize = 0; pub(in foo) static QUUX: usize = 0; } //}}} //{{{ issue 35650 ============================================================== macro_rules! size { ($ty:ty) => { std::mem::size_of::<$ty>() }; ($size:tt) => { $size }; } fn test_35650() { assert_eq!(size!(u64), 8); assert_eq!(size!(5), 5); } //}}} //{{{ issue 27832 ============================================================== macro_rules! m { ( $i:ident ) => (); ( $t:tt $j:tt ) => (); } m!(c); m!(t 9); m!(0 9); m!(struct); m!(struct Foo); macro_rules! m2 { ( $b:expr ) => (); ( $t:tt $u:tt ) => (); } m2!(3); m2!(1 2); m2!(_ 1); m2!(enum Foo); //}}} //{{{ issue 39964 ============================================================== macro_rules! foo_39964 { ($a:ident) => {}; (_) => {}; } foo_39964!(_); //}}} //{{{ issue 34030 ============================================================== macro_rules! foo_34030 { ($($t:ident),* /) => {}; } foo_34030!(a, b/); foo_34030!(a/); foo_34030!(/); //}}} //{{{ issue 24189 ============================================================== macro_rules! foo_24189 { ( pub enum $name:ident { $( #[$attr:meta] )* $var:ident } ) => { pub enum $name { $( #[$attr] )* $var } }; } foo_24189! { pub enum Foo24189 { #[doc = "Bar"] Baz } } macro_rules! serializable { ( $(#[$struct_meta:meta])* pub struct $name:ident { $( $(#[$field_meta:meta])* $field:ident: $type_:ty ),* , } ) => { $(#[$struct_meta])* pub struct $name { $( $(#[$field_meta])* $field: $type_ ),* , } } } serializable! { #[allow(dead_code)] /// This is a test pub struct Tester { #[allow(dead_code)] name: String, } } macro_rules! foo_24189_c { ( $( > )* $x:ident ) => { }; } foo_24189_c!( > a ); fn test_24189() { let _ = Foo24189::Baz; let _ = Tester { name: "".to_owned() }; } //}}} //{{{ some more tests ========================================================== macro_rules! test_block { (< $($b:block)* >) => {} } test_block!(<>); test_block!(<{}>); test_block!(<{1}{2}>); macro_rules! test_ty { ($($t:ty),* $(,)*) => {} } test_ty!(); test_ty!(,); test_ty!(u8); test_ty!(u8,); macro_rules! test_path { ($($t:path),* $(,)*) => {} } test_path!(); test_path!(,); test_path!(::std); test_path!(std::u8,); test_path!(any, super, super::super::self::path, X<Y>::Z<'a, T=U>); macro_rules! test_meta_block { ($($m:meta)* $b:block) => {}; } test_meta_block!(windows {}); //}}} fn main() { test_26444(); test_40569(); test_35650(); test_24189(); } </ins>


/// Returns the path to the C++ compiler for the target specified, may panic /// if no C++ compiler was configured for the target. fn cxx(&self, target: &str) -> &Path { <del> self.cxx[target].path() </del> <ins> match self.cxx.get(target) { Some(p) => p.path(), None => panic!("nntarget `{}` is not configured as a host, only as a targetnn", target), } </ins> } /// Returns flags to pass to the compiler to generate code for `target`.


"codegen-units"); suite("check-incremental", "src/test/incremental", "incremental", "incremental"); <del> suite("check-ui", "src/test/ui", "ui", "ui"); </del> } if build.config.build.contains("msvc") {


}); }; <ins> suite("check-ui", "src/test/ui", "ui", "ui"); </ins> suite("check-rpass-full", "src/test/run-pass-fulldeps", "run-pass", "run-pass-fulldeps"); suite("check-rfail-full", "src/test/run-fail-fulldeps",


assert!(plan.iter().any(|s| s.name.contains("-ui"))); assert!(plan.iter().any(|s| s.name.contains("cfail"))); <del> assert!(plan.iter().any(|s| s.name.contains("cfail"))); </del> assert!(plan.iter().any(|s| s.name.contains("cfail-full"))); assert!(plan.iter().any(|s| s.name.contains("codegen-units"))); assert!(plan.iter().any(|s| s.name.contains("debuginfo")));


assert!(plan.iter().all(|s| s.host == "A")); assert!(plan.iter().all(|s| s.target == "C")); <del> assert!(plan.iter().any(|s| s.name.contains("-ui"))); assert!(plan.iter().any(|s| s.name.contains("cfail"))); </del> <ins> assert!(!plan.iter().any(|s| s.name.contains("-ui"))); </ins> assert!(plan.iter().any(|s| s.name.contains("cfail"))); assert!(!plan.iter().any(|s| s.name.contains("cfail-full"))); assert!(plan.iter().any(|s| s.name.contains("codegen-units")));


<ins> // Copyright 2016 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. // no-prefer-dynamic #![crate_type = "proc-macro"] #![feature(proc_macro, proc_macro_lib)] extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro_derive(Foo)] pub fn derive_foo(input: TokenStream) -> TokenStream { input } #[proc_macro_derive(Bar)] pub fn derive_bar(input: TokenStream) -> TokenStream { panic!("lolnope"); } </ins>


<ins> // Copyright 2016 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. // aux-build:plugin.rs #![feature(proc_macro)] #[macro_use] extern crate plugin; #[derive(Foo, Bar)] struct Baz { a: i32, b: i32, } fn main() {} </ins>


<ins> error: custom derive attribute panicked --> $DIR/issue-36935.rs:17:15 | 17 | #[derive(Foo, Bar)] |               ^^^ | = help: message: lolnope </ins>


use schema::{METADATA_HEADER, rustc_version}; use rustc::hir::svh::Svh; <del> use rustc::session::Session; </del> <ins> use rustc::session::{config, Session}; </ins> use rustc::session::filesearch::{FileSearch, FileMatches, FileDoesntMatch}; use rustc::session::search_paths::PathKind; use rustc::util::common;


"can't find crate for `{}`{}", self.ident, add); <ins> if (self.ident == "std" || self.ident == "core") && self.triple != config::host_triple() { err.note(&format!("the `{}` target may not be installed", self.triple)); } </ins> err.span_label(self.span, &format!("can't find crate")); err };


<ins> // Copyright 2012-2014 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. // Tests that compiling for a target which is not installed will result in a helpful // error message. // compile-flags: --target=s390x-unknown-linux-gnu // ignore s390x // error-pattern:target may not be installed fn main() { } </ins>


// FIXME (#9639): This needs to handle non-utf8 paths let mut args = vec![input_file.to_str().unwrap().to_owned(), "-L".to_owned(), <del> self.config.build_base.to_str().unwrap().to_owned(), format!("--target={}", target)]; </del> <ins> self.config.build_base.to_str().unwrap().to_owned()]; // Optionally prevent default --target if specified in test compile-flags. let custom_target = self.props.compile_flags .iter() .fold(false, |acc, ref x| acc || x.starts_with("--target")); if !custom_target { args.extend(vec![ format!("--target={}", target), ]); } </ins> if let Some(revision) = self.revision { args.extend(vec![


use std::str; pub const MAX_BASE: u64 = 64; <ins> pub const ALPHANUMERIC_ONLY: u64 = 62; </ins> const BASE_64: &'static [u8; MAX_BASE as usize] = b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@$";


let mut name = String::with_capacity(prefix.len() + 6); name.push_str(prefix); name.push_str("."); <del> base_n::push_str(idx as u64, base_n::MAX_BASE, &mut name); </del> <ins> base_n::push_str(idx as u64, base_n::ALPHANUMERIC_ONLY, &mut name); </ins> name } }


} } <del> #[derive(Copy, Clone)] </del> <ins> #[derive(Copy, Clone, PartialEq)] </ins> enum PathScope { Global, Lexical,


// // Such behavior is required for backward compatibility. // The same fallback is used when `a` resolves to nothing. <del> _ if self.primitive_type_table.primitive_types.contains_key(&path[0].name) => { </del> <ins> PathResult::Module(..) | PathResult::Failed(..) if scope == PathScope::Lexical && (ns == TypeNS || path.len() > 1) && self.primitive_type_table.primitive_types.contains_key(&path[0].name) => { </ins> PathResolution { base_def: Def::PrimTy(self.primitive_type_table.primitive_types[&path[0].name]), depth: segments.len() - 1,


<ins> // Copyright 2016 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. fn main() { // Make sure primitive type fallback doesn't work in value namespace std::mem::size_of(u16); //~^ ERROR unresolved name `u16` //~| ERROR this function takes 0 parameters but 1 parameter was supplied // Make sure primitive type fallback doesn't work with global paths let _: ::u8; //~^ ERROR type name `u8` is undefined or not in scope } </ins>


impl<'a> Resolver<'a> { fn resolution(&self, module: Module<'a>, ident: Ident, ns: Namespace) -> &'a RefCell<NameResolution<'a>> { <ins> let ident = ident.unhygienize(); </ins> *module.resolutions.borrow_mut().entry((ident, ns)) .or_insert_with(|| self.arenas.alloc_name_resolution()) }


ignore_unresolved_invocations: bool, record_used: Option<Span>) -> Result<&'a NameBinding<'a>, Determinacy> { <del> let ident = ident.unhygienize(); </del> self.populate_module_if_necessary(module); let resolution = self.resolution(module, ident, ns)


ns: Namespace, binding: &'a NameBinding<'a>) -> Result<(), &'a NameBinding<'a>> { <del> let ident = ident.unhygienize(); </del> self.update_resolution(module, ident, ns, |this, resolution| { if let Some(old_binding) = resolution.binding { if binding.is_glob_import() {


view_path.map(|Spanned {node, span}| Spanned { node: match node { ViewPathSimple(ident, path) => { <del> ViewPathSimple(ident, fld.fold_path(path)) </del> <ins> ViewPathSimple(fld.fold_ident(ident), fld.fold_path(path)) </ins> } ViewPathGlob(path) => { ViewPathGlob(fld.fold_path(path)) } ViewPathList(path, path_list_idents) => { <del> ViewPathList(fld.fold_path(path), path_list_idents.move_map(|path_list_ident| { Spanned { node: PathListItem_ { id: fld.new_id(path_list_ident.node.id), rename: path_list_ident.node.rename, name: path_list_ident.node.name, }, span: fld.new_span(path_list_ident.span) } })) </del> <ins> let path = fld.fold_path(path); let path_list_idents = path_list_idents.move_map(|path_list_ident| Spanned { node: PathListItem_ { id: fld.new_id(path_list_ident.node.id), rename: path_list_ident.node.rename.map(|ident| fld.fold_ident(ident)), name: fld.fold_ident(path_list_ident.node.name), }, span: fld.new_span(path_list_ident.span) }); ViewPathList(path, path_list_idents) </ins> } }, span: fld.new_span(span)


pub fn noop_fold_ty_binding<T: Folder>(b: TypeBinding, fld: &mut T) -> TypeBinding { TypeBinding { id: fld.new_id(b.id), <del> ident: b.ident, </del> <ins> ident: fld.fold_ident(b.ident), </ins> ty: fld.fold_ty(b.ty), span: fld.new_span(b.span), }


.collect::<Vec<_>>() .into(), id: fld.new_id(id), <del> ident: ident, </del> <ins> ident: fld.fold_ident(ident), </ins> bounds: fld.fold_bounds(bounds), default: default.map(|x| fld.fold_ty(x)), span: span


let fs = fields.move_map(|f| { Spanned { span: folder.new_span(f.span), node: ast::FieldPat { <del> ident: f.node.ident, </del> <ins> ident: folder.fold_ident(f.node.ident), </ins> pat: folder.fold_pat(f.node.pat), is_shorthand: f.node.is_shorthand, }}


<ins> // Copyright 2016 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. pub struct Foo; macro_rules! reexport { () => { use Foo as Bar; } } reexport!(); fn main() { use Bar; fn f(_: Bar) {} } </ins>


/// Sets the child process's user ID. This translates to a /// `setuid` call in the child process. Failure in the `setuid` /// call will cause the spawn to fail. <ins> /// /// # Notes /// /// This will also trigger a call to `setgroups(0, NULL)` in the child /// process if no groups have been specified. /// This removes supplementary groups that might have given the child /// unwanted permissions. </ins> #[stable(feature = "rust1", since = "1.0.0")] fn uid(&mut self, id: UserId) -> &mut process::Command;


if let Some(u) = self.get_uid() { // When dropping privileges from root, the `setgroups` call // will remove any extraneous groups. We only drop groups <del> // if the current uid is 0 and we weren't given an explicit </del> <ins> // if we have CAP_SETGID and we weren't given an explicit </ins> // set of groups. If we don't call this, then even though our // uid has dropped, we may still have groups that enable us to // do super-user things. //FIXME: Redox kernel does not support setgroups yet #[cfg(not(target_os = "redox"))] <del> if libc::getuid() == 0 && self.get_groups().is_none() { cvt(libc::setgroups(0, crate::ptr::null()))?; </del> <ins> if self.get_groups().is_none() { let res = cvt(libc::setgroups(0, crate::ptr::null())); if let Err(e) = res { // Here we ignore the case of not having CAP_SETGID. // An alternative would be to require CAP_SETGID (in // addition to CAP_SETUID) for setting the UID. if e.raw_os_error() != Some(libc::EPERM) { return Err(e.into()); } } </ins> } cvt(libc::setuid(u as uid_t))?; }


## `Cell<T>` <del> [`Cell<T>`][cell] is a type that provides zero-cost interior mutability, but only for `Copy` types. </del> <ins> [`Cell<T>`][cell] is a type that provides zero-cost interior mutability by moving data in and out of the cell. </ins> Since the compiler knows that all the data owned by the contained value is on the stack, there's no worry of leaking any data behind references (or worse!) by simply replacing the data.


unnecessary. However, this also relaxes the guarantees that the restriction provides; so if your invariants depend on data stored within `Cell`, you should be careful. <del> This is useful for mutating primitives and other `Copy` types when there is no easy way of </del> <ins> This is useful for mutating primitives and other types when there is no easy way of </ins> doing it in line with the static rules of `&` and `&mut`. `Cell` does not let you obtain interior references to the data, which makes it safe to freely


#### Cost <del> There is no runtime cost to using `Cell<T>`, however if you are using it to wrap larger (`Copy`) </del> <ins> There is no runtime cost to using `Cell<T>`, however if you are using it to wrap larger </ins> structs, it might be worthwhile to instead wrap individual fields in `Cell<T>` since each write is otherwise a full copy of the struct. ## `RefCell<T>` <del> [`RefCell<T>`][refcell] also provides interior mutability, but isn't restricted to `Copy` types. </del> <ins> [`RefCell<T>`][refcell] also provides interior mutability, but doesn't move data in and out of the cell. </ins> <del> Instead, it has a runtime cost. `RefCell<T>` enforces the read-write lock pattern at runtime (it's </del> <ins> However, it has a runtime cost. `RefCell<T>` enforces the read-write lock pattern at runtime (it's </ins> like a single-threaded mutex), unlike `&T`/`&mut T` which do so at compile time. This is done by the `borrow()` and `borrow_mut()` functions, which modify an internal reference count and return smart pointers which can be dereferenced immutably and mutably respectively. The refcount is restored when


//! references. We say that `Cell<T>` and `RefCell<T>` provide 'interior mutability', in contrast //! with typical Rust types that exhibit 'inherited mutability'. //! <del> //! Cell types come in two flavors: `Cell<T>` and `RefCell<T>`. `Cell<T>` provides `get` and `set` //! methods that change the interior value with a single method call. `Cell<T>` though is only //! compatible with types that implement `Copy`. For other types, one must use the `RefCell<T>` //! type, acquiring a write lock before mutating. </del> <ins> //! Cell types come in two flavors: `Cell<T>` and `RefCell<T>`. `Cell<T>` implements interior //! mutability by moving values in and out of the `Cell<T>`. To use references instead of values, //! one must use the `RefCell<T>` type, acquiring a write lock before mutating. `Cell<T>` provides //! methods to retrieve and change the current interior value: //! //!  - For types that implement `Copy`, the `get` method retrieves the current interior value. //!  - For types that implement `Default`, the `take` method replaces the current interior value //!    with `Default::default()` and returns the replaced value. //!  - For all types, the `replace` method replaces the current interior value and returns the //!    replaced value and the `into_inner` method consumes the `Cell<T>` and returns the interior //!    value. Additionally, the `set` method replaces the interior value, dropping the replaced //!    value. </ins> //! //! `RefCell<T>` uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can //! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are


use cmp::Ordering; use fmt::{self, Debug, Display}; use marker::Unsize; <ins> use mem; </ins> use ops::{Deref, DerefMut, CoerceUnsized}; <del> /// A mutable memory location that admits only `Copy` data. </del> <ins> /// A mutable memory location. </ins> /// /// See the [module-level documentation](index.html) for more. #[stable(feature = "rust1", since = "1.0.0")]


} impl<T:Copy> Cell<T> { <del> /// Creates a new `Cell` containing the given value. /// /// # Examples /// /// ``` /// use std::cell::Cell; /// /// let c = Cell::new(5); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub const fn new(value: T) -> Cell<T> { Cell { value: UnsafeCell::new(value), } } </del> /// Returns a copy of the contained value. /// /// # Examples


unsafe{ *self.value.get() } } <del> /// Sets the contained value. /// /// # Examples /// /// ``` /// use std::cell::Cell; /// /// let c = Cell::new(5); /// /// c.set(10); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn set(&self, value: T) { unsafe { *self.value.get() = value; } } </del> /// Returns a reference to the underlying `UnsafeCell`. /// /// # Examples


} } <ins> impl<T> Cell<T> { /// Creates a new `Cell` containing the given value. /// /// # Examples /// /// ``` /// use std::cell::Cell; /// /// let c = Cell::new(5); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub const fn new(value: T) -> Cell<T> { Cell { value: UnsafeCell::new(value), } } /// Sets the contained value. /// /// # Examples /// /// ``` /// use std::cell::Cell; /// /// let c = Cell::new(5); /// /// c.set(10); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn set(&self, val: T) { let old = self.replace(val); drop(old); } /// Replaces the contained value. /// /// # Examples /// /// ``` /// #![feature(move_cell)] /// use std::cell::Cell; /// /// let c = Cell::new(5); /// let old = c.replace(10); /// /// assert_eq!(5, old); /// ``` #[unstable(feature = "move_cell", issue = "39264")] pub fn replace(&self, val: T) -> T { mem::replace(unsafe { &mut *self.value.get() }, val) } /// Unwraps the value. /// /// # Examples /// /// ``` /// #![feature(move_cell)] /// use std::cell::Cell; /// /// let c = Cell::new(5); /// let five = c.into_inner(); /// /// assert_eq!(five, 5); /// ``` #[unstable(feature = "move_cell", issue = "39264")] pub fn into_inner(self) -> T { unsafe { self.value.into_inner() } } } impl<T: Default> Cell<T> { /// Takes the value of the cell, leaving `Default::default()` in its place. /// /// # Examples /// /// ``` /// #![feature(move_cell)] /// use std::cell::Cell; /// /// let c = Cell::new(5); /// let five = c.take(); /// /// assert_eq!(five, 5); /// assert_eq!(c.into_inner(), 0); /// ``` #[unstable(feature = "move_cell", issue = "39264")] pub fn take(&self) -> T { self.replace(Default::default()) } } </ins> #[unstable(feature = "coerce_unsized", issue = "27732")] impl<T: CoerceUnsized<U>, U> CoerceUnsized<Cell<U>> for Cell<T> {}


} #[test] <ins> fn cell_set() { let cell = Cell::new(10); cell.set(20); assert_eq!(20, cell.get()); let cell = Cell::new("Hello".to_owned()); cell.set("World".to_owned()); assert_eq!("World".to_owned(), cell.into_inner()); } #[test] fn cell_replace() { let cell = Cell::new(10); assert_eq!(10, cell.replace(20)); assert_eq!(20, cell.get()); let cell = Cell::new("Hello".to_owned()); assert_eq!("Hello".to_owned(), cell.replace("World".to_owned())); assert_eq!("World".to_owned(), cell.into_inner()); } #[test] fn cell_into_inner() { let cell = Cell::new(10); assert_eq!(10, cell.into_inner()); let cell = Cell::new("Hello world".to_owned()); assert_eq!("Hello world".to_owned(), cell.into_inner()); } #[test] </ins> fn refcell_default() { let cell: RefCell<u64> = Default::default(); assert_eq!(0, *cell.borrow());


#![feature(ordering_chaining)] #![feature(result_unwrap_or_default)] #![feature(ptr_unaligned)] <ins> #![feature(move_cell)] </ins> extern crate core; extern crate test;


ostype += 'abi64' elif cputype in {'powerpc', 'ppc', 'ppc64'}: cputype = 'powerpc' <ins> elif cputype == 'sparcv9': pass </ins> elif cputype in {'amd64', 'x86_64', 'x86-64', 'x64'}: cputype = 'x86_64' else:


// compiler-rt's build system already cfg.flag("-fno-builtin"); cfg.flag("-fvisibility=hidden"); <del> cfg.flag("-fomit-frame-pointer"); </del> <ins> // Accepted practice on Solaris is to never omit frame pointer so that // system observability tools work as expected.  In addition, at least // on Solaris, -fomit-frame-pointer on sparcv9 appears to generate // references to data outside of the current stack frame.  A search of // the gcc bug database provides a variety of issues surrounding // -fomit-frame-pointer on non-x86 platforms. if !target.contains("solaris") && !target.contains("sparc") { cfg.flag("-fomit-frame-pointer"); } </ins> cfg.flag("-ffreestanding"); cfg.define("VISIBILITY_HIDDEN", None); }


("armv7s-apple-ios", armv7s_apple_ios), ("x86_64-sun-solaris", x86_64_sun_solaris), <ins> ("sparcv9-sun-solaris", sparcv9_sun_solaris), </ins> ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu), ("i686-pc-windows-gnu", i686_pc_windows_gnu),


<ins> // Copyright 2016 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. use target::{Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::solaris_base::opts(); base.pre_link_args.push("-m64".to_string()); // llvm calls this "v9" base.cpu = "v9".to_string(); base.max_atomic_width = Some(64); Ok(Target { llvm_target: "sparcv9-sun-solaris".to_string(), target_endian: "big".to_string(), target_pointer_width: "64".to_string(), data_layout: "E-m:e-i64:64-n32:64-S128".to_string(), // Use "sparc64" instead of "sparcv9" here, since the former is already // used widely in the source base.  If we ever needed ABI // differentiation from the sparc64, we could, but that would probably // just be confusing. arch: "sparc64".to_string(), target_os: "solaris".to_string(), target_env: "".to_string(), target_vendor: "sun".to_string(), options: base, }) } </ins>


// //   match <sub_expr> { //     <pat> => <body>, <del> //     [_ if <else_opt_if_cond> => <else_opt_if_body>,] </del> //     _ => [<else_opt> | ()] //   }


arms.push(self.arm(hir_vec![pat], body_expr)); } <del> // `[_ if <else_opt_if_cond> => <else_opt_if_body>,]` // `_ => [<else_opt> | ()]` </del> <ins> // _ => [<else_opt>|()] </ins> { <del> let mut current: Option<&Expr> = else_opt.as_ref().map(|p| &**p); let mut else_exprs: Vec<Option<&Expr>> = vec![current]; // First, we traverse the AST and recursively collect all // `else` branches into else_exprs, e.g.: // // if let Some(_) = x { //    ... // } else if ... {  // Expr1 //    ... // } else if ... {  // Expr2 //    ... // } else {         // Expr3 //    ... // } // // ... results in else_exprs = [Some(&Expr1), //                              Some(&Expr2), //                              Some(&Expr3)] // // Because there also the case there is no `else`, these // entries can also be `None`, as in: // // if let Some(_) = x { //    ... // } else if ... {  // Expr1 //    ... // } else if ... {  // Expr2 //    ... // } // // ... results in else_exprs = [Some(&Expr1), //                              Some(&Expr2), //                              None] // // The last entry in this list is always translated into // the final "unguard" wildcard arm of the `match`. In the // case of a `None`, it becomes `_ => ()`. loop { if let Some(e) = current { // There is an else branch at this level if let ExprKind::If(_, _, ref else_opt) = e.node { // The else branch is again an if-expr current = else_opt.as_ref().map(|p| &**p); else_exprs.push(current); } else { // The last item in the list is not an if-expr, // stop here break } } else { // We have no more else branch break } } // Now translate the list of nested else-branches into the // arms of the match statement. for else_expr in else_exprs { if let Some(else_expr) = else_expr { let (guard, body) = if let ExprKind::If(ref cond, ref then, _) = else_expr.node { let then = self.lower_block(then, false); (Some(cond), self.expr_block(then, ThinVec::new())) } else { (None, self.lower_expr(else_expr)) }; arms.push(hir::Arm { attrs: hir_vec![], pats: hir_vec![self.pat_wild(e.span)], guard: guard.map(|e| P(self.lower_expr(e))), body: P(body), }); } else { // There was no else-branch, push a noop let pat_under = self.pat_wild(e.span); let unit = self.expr_tuple(e.span, hir_vec![]); arms.push(self.arm(hir_vec![pat_under], unit)); } } </del> <ins> let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p); let wildcard_pattern = self.pat_wild(e.span); let body = if let Some(else_expr) = wildcard_arm { P(self.lower_expr(else_expr)) } else { self.expr_tuple(e.span, hir_vec![]) }; arms.push(self.arm(hir_vec![wildcard_pattern], body)); </ins> } let contains_else_clause = else_opt.is_some();


<ins> // Copyright 2017 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. struct Foo; impl Foo { fn bar(&mut self) -> bool { true } } fn error(foo: &mut Foo) { if let Some(_) = Some(true) { } else if foo.bar() {} } fn ok(foo: &mut Foo) { if let Some(_) = Some(true) { } else { if foo.bar() {} } } fn main() {} </ins>


# 32/64-bit MinGW builds. # <del> # The MinGW builds unfortunately have to both download a custom toolchain and # avoid the one installed by AppVeyor by default. Interestingly, though, for # different reasons! </del> <ins> # We are using MinGW with posix threads since LLVM does not compile with # the win32 threads version due to missing support for C++'s std::thread. </ins> # <del> # For 32-bit the installed gcc toolchain on AppVeyor uses the pthread # threading model. This is unfortunately not what we want, and if we compile # with it then there's lots of link errors in the standard library (undefined # references to pthread symbols). # # For 64-bit the installed gcc toolchain is currently 5.3.0 which # unfortunately segfaults on Windows with --enable-llvm-assertions (segfaults # in LLVM). See rust-lang/rust#28445 for more information, but to work around # this we go back in time to 4.9.2 specifically. </del> <ins> # Instead of relying on the MinGW version installed on appveryor we download # and install one ourselves so we won't be surprised by changes to appveyor's # build image. </ins> # # Finally, note that the downloads below are all in the `rust-lang-ci` S3 # bucket, but they cleraly didn't originate there! The downloads originally # came from the mingw-w64 SourceForge download site. Unfortunately # SourceForge is notoriously flaky, so we mirror it on our own infrastructure. <del> # # And as a final point of note, the 32-bit MinGW build using the makefiles do # *not* use debug assertions and llvm assertions. This is because they take # too long on appveyor and this is tested by rustbuild below. </del> - MSYS_BITS: 32 RUST_CONFIGURE_ARGS: --build=i686-pc-windows-gnu --enable-ninja SCRIPT: python x.py test MINGW_URL: https://s3.amazonaws.com/rust-lang-ci/rust-ci-mirror <del> MINGW_ARCHIVE: i686-6.2.0-release-win32-dwarf-rt_v5-rev1.7z </del> <ins> MINGW_ARCHIVE: i686-6.2.0-release-posix-dwarf-rt_v5-rev1.7z </ins> MINGW_DIR: mingw32 - MSYS_BITS: 64 SCRIPT: python x.py test RUST_CONFIGURE_ARGS: --build=x86_64-pc-windows-gnu --enable-ninja MINGW_URL: https://s3.amazonaws.com/rust-lang-ci/rust-ci-mirror <del> MINGW_ARCHIVE: x86_64-6.2.0-release-win32-seh-rt_v5-rev1.7z </del> <ins> MINGW_ARCHIVE: x86_64-6.2.0-release-posix-seh-rt_v5-rev1.7z </ins> MINGW_DIR: mingw64 # 32/64 bit MSVC and GNU deployment


RUST_CONFIGURE_ARGS: --build=i686-pc-windows-gnu --enable-extended --enable-ninja SCRIPT: python x.py dist MINGW_URL: https://s3.amazonaws.com/rust-lang-ci/rust-ci-mirror <del> MINGW_ARCHIVE: i686-6.2.0-release-win32-dwarf-rt_v5-rev1.7z </del> <ins> MINGW_ARCHIVE: i686-6.2.0-release-posix-dwarf-rt_v5-rev1.7z </ins> MINGW_DIR: mingw32 DEPLOY: 1 - MSYS_BITS: 64 SCRIPT: python x.py dist RUST_CONFIGURE_ARGS: --build=x86_64-pc-windows-gnu --enable-extended --enable-ninja MINGW_URL: https://s3.amazonaws.com/rust-lang-ci/rust-ci-mirror <del> MINGW_ARCHIVE: x86_64-6.2.0-release-win32-seh-rt_v5-rev1.7z </del> <ins> MINGW_ARCHIVE: x86_64-6.2.0-release-posix-seh-rt_v5-rev1.7z </ins> MINGW_DIR: mingw64 DEPLOY: 1


COPY build-emscripten.sh /tmp/ RUN ./build-emscripten.sh ENV PATH=$PATH:/tmp/emsdk_portable <del> ENV PATH=$PATH:/tmp/emsdk_portable/clang/tag-e1.37.1/build_tag-e1.37.1_32/bin </del> <ins> ENV PATH=$PATH:/tmp/emsdk_portable/clang/tag-e1.37.10/build_tag-e1.37.10_32/bin </ins> ENV PATH=$PATH:/tmp/emsdk_portable/node/4.1.1_32bit/bin <del> ENV PATH=$PATH:/tmp/emsdk_portable/emscripten/tag-1.37.1 ENV EMSCRIPTEN=/tmp/emsdk_portable/emscripten/tag-1.37.1 </del> <ins> ENV PATH=$PATH:/tmp/emsdk_portable/emscripten/tag-1.37.10 ENV EMSCRIPTEN=/tmp/emsdk_portable/emscripten/tag-1.37.10 </ins> ENV RUST_CONFIGURE_ARGS --target=asmjs-unknown-emscripten


source emsdk_portable/emsdk_env.sh hide_output emsdk update <del> hide_output emsdk install --build=Release sdk-tag-1.37.1-32bit hide_output emsdk activate --build=Release sdk-tag-1.37.1-32bit </del> <ins> hide_output emsdk install --build=Release sdk-tag-1.37.10-32bit hide_output emsdk activate --build=Release sdk-tag-1.37.10-32bit </ins>


<del> Subproject commit d30da544a8afc5d78391dee270bdf40e74a215d3 </del> <ins> Subproject commit c8a8767c56ad3d3f4eb45c87b95026936fb9aa35 </ins>


} if target.contains("arm") && !target.contains("ios") { <ins> // (At least) udivsi3.S is broken for Thumb 1 which our gcc uses by // default, we don't want Thumb 2 since it isn't supported on some // devices, so disable thumb entirely. // Upstream bug: https://bugs.llvm.org/show_bug.cgi?id=32492 cfg.define("__ARM_ARCH_ISA_THUMB", Some("0")); </ins> sources.extend(&["arm/aeabi_cdcmp.S", "arm/aeabi_cdcmpeq_check_nan.c", "arm/aeabi_cfcmp.S",


<del> Subproject commit 2e951c3ae354bcbd2e50b30798e232949a926b75 </del> <ins> Subproject commit a884d21cc5f0b23a1693d1e872fd8998a4fdd17f </ins>


// write_volatile causes an LLVM assert with composite types <ins> // ignore-emscripten See #41299: probably a bad optimization </ins> #![feature(volatile)] use std::ptr::{read_volatile, write_volatile};


exit_success_if_unwind::bar(do_panic); } } <del> let s = Command::new(env::args_os().next().unwrap()).arg("foo").status(); </del> <ins> let mut cmd = Command::new(env::args_os().next().unwrap()); cmd.arg("foo"); // ARMv6 hanges while printing the backtrace, see #41004 if cfg!(target_arch = "arm") && cfg!(target_env = "gnu") { cmd.env("RUST_BACKTRACE", "0"); } let s = cmd.status(); </ins> assert!(s.unwrap().code() != Some(0)); }


panic!("try to catch me"); } } <del> let s = Command::new(env::args_os().next().unwrap()).arg("foo").status(); </del> <ins> let mut cmd = Command::new(env::args_os().next().unwrap()); cmd.arg("foo"); // ARMv6 hanges while printing the backtrace, see #41004 if cfg!(target_arch = "arm") && cfg!(target_env = "gnu") { cmd.env("RUST_BACKTRACE", "0"); } let s = cmd.status(); </ins> assert!(s.unwrap().code() != Some(0)); }


// So peel off one-level, turning the &T into T. match base_ty.builtin_deref(false, ty::NoPreference) { Some(t) => t.ty, <del> None => { return Err(()); } </del> <ins> None => { debug!("By-ref binding of non-derefable type {:?}", base_ty); return Err(()); } </ins> } } _ => base_ty,


match base_cmt.ty.builtin_index() { Some(ty) => (ty, ElementKind::VecElement), None => { <ins> debug!("Explicit index of non-indexable type {:?}", base_cmt); </ins> return Err(()); } }


PatKind::TupleStruct(hir::QPath::Resolved(_, ref path), ..) | PatKind::Struct(hir::QPath::Resolved(_, ref path), ..) => { match path.def { <del> Def::Err => return Err(()), </del> <ins> Def::Err => { debug!("access to unresolvable pattern {:?}", pat); return Err(()) } </ins> Def::Variant(variant_did) | Def::VariantCtor(variant_did, ..) => { // univariant enums do not need downcasts


panic!(ExplicitBug); } pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) { <ins> if self.treat_err_as_bug { self.span_bug(sp, msg); } </ins> let mut delayed = self.delayed_span_bug.borrow_mut(); *delayed = Some((sp.into(), msg.to_string())); }


}; let index_expr_ty = self.node_ty(index_expr.id); <ins> let adjusted_base_ty = self.resolve_type_vars_if_possible(&adjusted_base_ty); let index_expr_ty = self.resolve_type_vars_if_possible(&index_expr_ty); </ins> let result = self.try_index_step(ty::MethodCall::expr(expr.id), expr,


let expr_ty = self.node_ty(expr.id); self.demand_suptype(expr.span, expr_ty, return_ty); <ins> } else { // We could not perform a mutable index. Re-apply the // immutable index adjustments - borrowck will detect // this as an error. if let Some(adjustment) = adjustment { self.apply_adjustment(expr.id, adjustment); } self.tcx.sess.delay_span_bug( expr.span, "convert_lvalue_derefs_to_mutable failed"); </ins> } } hir::ExprUnary(hir::UnDeref, ref base_expr) => {


<ins> // Copyright 2017 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. // regression test for issue #41498. struct S; impl S { fn mutate(&mut self) {} } fn call_and_ref<T, F: FnOnce() -> T>(x: &mut Option<T>, f: F) -> &mut T { *x = Some(f()); x.as_mut().unwrap() } fn main() { let mut n = None; call_and_ref(&mut n, || [S])[0].mutate(); } </ins>


use rustc::mir::*; use rustc::mir::transform::{MirSuite, MirPassIndex, MirSource}; use rustc::ty::TyCtxt; <ins> use rustc::ty::item_path; </ins> use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::indexed_vec::{Idx}; use std::fmt::Display;


return; } <del> let node_path = tcx.item_path_str(tcx.hir.local_def_id(source.item_id())); </del> <ins> let node_path = item_path::with_forced_impl_filename_line(|| { // see notes on #41697 below tcx.item_path_str(tcx.hir.local_def_id(source.item_id())) }); </ins> dump_matched_mir_node(tcx, pass_num, pass_name, &node_path, disambiguator, source, mir); for (index, promoted_mir) in mir.promoted.iter_enumerated() {


Some(ref filters) => filters, }; let node_id = source.item_id(); <del> let node_path = tcx.item_path_str(tcx.hir.local_def_id(node_id)); </del> <ins> let node_path = item_path::with_forced_impl_filename_line(|| { // see notes on #41697 below tcx.item_path_str(tcx.hir.local_def_id(node_id)) }); </ins> filters.split("&") .any(|filter| { filter == "all" ||


}) } <ins> // #41697 -- we use `with_forced_impl_filename_line()` because // `item_path_str()` would otherwise trigger `type_of`, and this can // run while we are already attempting to evaluate `type_of`. </ins> fn dump_matched_mir_node<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, pass_num: Option<(MirSuite, MirPassIndex)>, pass_name: &str,


<ins> // Copyright 2016 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. // compile-flags:-Zdump-mir=NEVER_MATCHED // Regression test for #41697. Using dump-mir was triggering // artificial cycles: during type-checking, we had to get the MIR for // the constant expressions in `[u8; 2]`, which in turn would trigger // an attempt to get the item-path, which in turn would request the // types of the impl, which would trigger a cycle. We supressed this // cycle now by forcing mir-dump to avoid asking for types of an impl. #![feature(rustc_attrs)] use std::sync::Arc; trait Foo { fn get(&self) -> [u8; 2]; } impl Foo for [u8; 2] { fn get(&self) -> [u8; 2] { *self } } struct Bar<T: ?Sized>(T); fn unsize_fat_ptr<'a>(x: &'a Bar<Foo + Send + 'a>) -> &'a Bar<Foo + 'a> { x } fn unsize_nested_fat_ptr(x: Arc<Foo + Send>) -> Arc<Foo> { x } fn main() { let x: Box<Bar<Foo + Send>> = Box::new(Bar([1,2])); assert_eq!(unsize_fat_ptr(&*x).0.get(), [1, 2]); let x: Arc<Foo + Send> = Arc::new([3, 4]); assert_eq!(unsize_nested_fat_ptr(x).get(), [3, 4]); } </ins>


output: $output:tt) => { define_map_struct! { tcx: $tcx, <del> ready: ([pub] $attrs $name), </del> <ins> ready: ([] $attrs $name), </ins> input: ($($input)*), output: $output }


MirSource::Promoted(_, i) => write!(w, "{:?} in", i)? } <del> write!(w, " {}", tcx.node_path_str(src.item_id()))?; </del> <ins> item_path::with_forced_impl_filename_line(|| { // see notes on #41697 elsewhere write!(w, " {}", tcx.node_path_str(src.item_id())) })?; </ins> if let MirSource::Fn(_) = src { write!(w, "(")?;


<ins> // Copyright 2016 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. // Regression test for #41697. Using dump-mir was triggering // artificial cycles: during type-checking, we had to get the MIR for // the constant expressions in `[u8; 2]`, which in turn would trigger // an attempt to get the item-path, which in turn would request the // types of the impl, which would trigger a cycle. We supressed this // cycle now by forcing mir-dump to avoid asking for types of an impl. #![feature(rustc_attrs)] use std::sync::Arc; trait Foo { fn get(&self) -> [u8; 2]; } impl Foo for [u8; 2] { fn get(&self) -> [u8; 2] { *self } } struct Bar<T: ?Sized>(T); fn unsize_fat_ptr<'a>(x: &'a Bar<Foo + Send + 'a>) -> &'a Bar<Foo + 'a> { x } fn unsize_nested_fat_ptr(x: Arc<Foo + Send>) -> Arc<Foo> { x } fn main() { let x: Box<Bar<Foo + Send>> = Box::new(Bar([1,2])); assert_eq!(unsize_fat_ptr(&*x).0.get(), [1, 2]); let x: Arc<Foo + Send> = Arc::new([3, 4]); assert_eq!(unsize_nested_fat_ptr(x).get(), [3, 4]); } </ins>


<del> // Copyright 2016 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. // compile-flags:-Zdump-mir=NEVER_MATCHED // Regression test for #41697. Using dump-mir was triggering // artificial cycles: during type-checking, we had to get the MIR for // the constant expressions in `[u8; 2]`, which in turn would trigger // an attempt to get the item-path, which in turn would request the // types of the impl, which would trigger a cycle. We supressed this // cycle now by forcing mir-dump to avoid asking for types of an impl. #![feature(rustc_attrs)] use std::sync::Arc; trait Foo { fn get(&self) -> [u8; 2]; } impl Foo for [u8; 2] { fn get(&self) -> [u8; 2] { *self } } struct Bar<T: ?Sized>(T); fn unsize_fat_ptr<'a>(x: &'a Bar<Foo + Send + 'a>) -> &'a Bar<Foo + 'a> { x } fn unsize_nested_fat_ptr(x: Arc<Foo + Send>) -> Arc<Foo> { x } fn main() { let x: Box<Bar<Foo + Send>> = Box::new(Bar([1,2])); assert_eq!(unsize_fat_ptr(&*x).0.get(), [1, 2]); let x: Arc<Foo + Send> = Arc::new([3, 4]); assert_eq!(unsize_nested_fat_ptr(x).get(), [3, 4]); } </del>


let path = @{span: span, global: false, idents: ~[nm], rp: None, types: ~[]}; @{id: self.next_id(), <del> node: ast::pat_ident(ast::bind_by_implicit_ref, </del> <ins> node: ast::pat_ident(ast::bind_by_ref(ast::m_imm), </ins> path, None), span: span}


let pat_node = if pats.is_empty() { ast::pat_ident( <del> ast::bind_by_implicit_ref, </del> <ins> ast::bind_by_ref(ast::m_imm), </ins> cx.path(span, ~[v_name]), None )


<ins> #[forbid(deprecated_pattern)]; </ins> extern mod std; // These tests used to be separate files, but I wanted to refactor all


let ebml_w = &EBWriter::Serializer(wr); a1.serialize(ebml_w) }; <del> let d = EBReader::Doc(@bytes); </del> <ins> let d = EBReader::Doc(@move bytes); </ins> let a2: A = deserialize(&EBReader::Deserializer(d)); assert *a1 == a2; }


#![feature(core_intrinsics)] #![feature(dropck_eyepatch)] #![feature(generic_param_attrs)] <del> #![feature(needs_drop)] </del> #![cfg_attr(test, feature(test))] #![allow(deprecated)]


/// Here's an example of how a collection might make use of needs_drop: /// /// ``` <del> /// #![feature(needs_drop)] </del> /// use std::{mem, ptr}; /// /// pub struct MyCollection<T> {


/// } /// ``` #[inline] <del> #[unstable(feature = "needs_drop", issue = "41890")] </del> <ins> #[stable(feature = "needs_drop", since = "1.22.0")] </ins> pub fn needs_drop<T>() -> bool { unsafe { intrinsics::needs_drop::<T>() } }


#![feature(macro_reexport)] #![feature(macro_vis_matcher)] #![feature(needs_panic_runtime)] <del> #![feature(needs_drop)] </del> #![feature(never_type)] #![feature(num_bits_bytes)] #![feature(old_wrapping)]


TokenTree::Sequence(span, ref seq) => { if seq.separator.is_none() && seq.tts.iter().all(|seq_tt| { match *seq_tt { <ins> TokenTree::MetaVarDecl(_, _, id) => id.name == "vis", </ins> TokenTree::Sequence(_, ref sub_seq) => sub_seq.op == quoted::KleeneOp::ZeroOrMore, _ => false,


<ins> // Copyright 2017 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. #![feature(macro_vis_matcher)] macro_rules! foo { ($($p:vis)*) => {} //~ ERROR repetition matches empty token tree } foo!(a); </ins>


// #[repr(simd)], even if we don't actually use this struct directly. // // FIXME repr(simd) broken on emscripten and redox <del> // It's also broken on big-endian powerpc64 and s390x.  #42778 #[cfg_attr(not(any(target_os = "emscripten", target_os = "redox", target_endian = "big")), repr(simd))] </del> <ins> #[cfg_attr(not(any(target_os = "emscripten", target_os = "redox")), repr(simd))] </ins> struct Block(u64, u64, u64, u64); struct UnalignedBlock(u64, u64, u64, u64);


trait_obj.method_two(); ``` <del> You can read more about trait objects in the Trait Object section of the Reference: </del> <ins> You can read more about trait objects in the [Trait Objects] section of the Reference. </ins> <del> https://doc.rust-lang.org/reference.html#trait-objects </del> <ins> [Trait Objects]: https://doc.rust-lang.org/reference/types.html#trait-objects </ins> "##, E0034: r##"


optional namespacing), a dereference, an indexing expression or a field reference. <del> More details can be found here: https://doc.rust-lang.org/reference.html#lvalues-rvalues-and-temporaries </del> <ins> More details can be found in the [Expressions] section of the Reference. [Expressions]: https://doc.rust-lang.org/reference/expressions.html#lvalues-rvalues-and-temporaries </ins> Now, we can go further. Here are some erroneous code examples:


} ``` <del> PhantomData can also be used to express information about unused type parameters. You can read more about it in the API documentation: </del> <ins> [PhantomData] can also be used to express information about unused type parameters. </ins> <del> https://doc.rust-lang.org/std/marker/struct.PhantomData.html </del> <ins> [PhantomData]: https://doc.rust-lang.org/std/marker/struct.PhantomData.html </ins> "##, E0393: r##"


println!("x: {}, y: {}", variable.x, variable.y); ``` <del> For more information see The Rust Book: https://doc.rust-lang.org/book/ </del> <ins> For more information about primitives and structs, take a look at The Book: https://doc.rust-lang.org/book/first-edition/primitive-types.html https://doc.rust-lang.org/book/first-edition/structs.html </ins> "##, E0611: r##"


} ``` <del> To fix this error, you need to pass variables corresponding to C types as much as possible. For better explanations, see The Rust Book: https://doc.rust-lang.org/book/ </del> <ins> Certain Rust types must be cast before passing them to a variadic function, because of arcane ABI rules dictated by the C standard. To fix the error, cast the value to the type specified by the error message (which you may need to import from `std::os::raw`). </ins> "##, E0618: r##"


- [Command-line arguments](command-line-arguments.md) - [The `#[doc]` attribute](the-doc-attribute.md) - [Documentation tests](documentation-tests.md) <ins> - [Linking to items by name](linking-to-items-by-name.md) </ins> - [Lints](lints.md) - [Passes](passes.md) - [Advanced Features](advanced-features.md)


<ins> # Linking to items by name Rustdoc is capable of directly linking to other rustdoc pages in Markdown documentation using the path of item as a link. For example, in the following code all of the links will link to the rustdoc page for `Bar`: ```rust /// This struct is not [Bar] pub struct Foo1; /// This struct is also not [bar](Bar) pub struct Foo2; /// This struct is also not [bar][b] /// /// [b]: Bar pub struct Foo3; /// This struct is also not [`Bar`] pub struct Foo4; pub struct Bar; ``` You can refer to anything in scope, and use paths, including `Self`, `self`, `super`, and `crate`. You may also use `foo()` and `foo!()` to refer to methods/functions and macros respectively. Backticks around the link will be stripped. ```rust,edition2018 use std::sync::mpsc::Receiver; /// This is an version of [`Receiver`], with support for [`std::future`]. /// /// You can obtain a [`std::future::Future`] by calling [`Self::recv()`]. pub struct AsyncReceiver<T> { sender: Receiver<T> } impl<T> AsyncReceiver<T> { pub async fn recv() -> T { unimplemented!() } } ``` You can also link to sections using URL fragment specifiers: ```rust /// This is a special implementation of [positional parameters] /// /// [positional parameters]: std::fmt#formatting-parameters struct MySpecialFormatter; ``` Paths in Rust have three namespaces: type, value, and macro. Items from these namespaces are allowed to overlap. In case of ambiguity, rustdoc will warn about the ambiguity and ask you to disambiguate, which can be done by using a prefix like  `struct@`, `enum@`, `type@`, `trait@`, `union@`, `const@`, `static@`, `value@`, `function@`, `mod@`, `fn@`, `module@`, `method@`, `prim@`, `primitive@`, `macro@`, or `derive@`:: ```rust /// See also: [`Foo`](struct@Foo) struct Bar; /// This is different from [`Foo`](fn@Foo) struct Foo {} fn Foo() {} ``` Note: Because of how `macro_rules` macros are scoped in Rust, the intra-doc links of a `macro_rules` macro will be resolved relative to the crate root, as opposed to the module it is defined in. </ins>


## broken_intra_doc_links <del> This lint **warns by default** and is **nightly-only**. This lint detects when an intra-doc link fails to get resolved. For example: </del> <ins> This lint **warns by default**. This lint detects when an [intra-doc link] fails to get resolved. For example: [intra-doc link]: linking-to-items-by-name.html </ins> ```rust <del> /// I want to link to [`Inexistent`] but it doesn't exist! </del> <ins> /// I want to link to [`Nonexistent`] but it doesn't exist! </ins> pub fn foo() {} ``` You'll get a warning saying: ```text <del> error: `[`Inexistent`]` cannot be resolved, ignoring it... </del> <ins> warning: unresolved link to `Nonexistent` --> test.rs:1:24 | 1 | /// I want to link to [`Nonexistent`] but it doesn't exist! |                        ^^^^^^^^^^^^^ no item named `Nonexistent` in `test` ``` It will also warn when there is an ambiguity and suggest how to disambiguate: ```rust /// [`Foo`] pub fn function() {} pub enum Foo {} pub fn Foo(){} ``` ```text warning: `Foo` is both an enum and a function --> test.rs:1:6 | 1 | /// [`Foo`] |      ^^^^^ ambiguous link | = note: `#[warn(broken_intra_doc_links)]` on by default help: to link to the enum, prefix with the item type | 1 | /// [`enum@Foo`] |      ^^^^^^^^^^ help: to link to the function, add parentheses | 1 | /// [`Foo()`] |      ^^^^^^^ </ins> ``` ## missing_docs


Attempting to use these error numbers on stable will result in the code sample being interpreted as plain text. <del> ### Linking to items by name Rustdoc is capable of directly linking to other rustdoc pages in Markdown documentation using the path of item as a link. For example, in the following code all of the links will link to the rustdoc page for `Bar`: ```rust /// This struct is not [Bar] pub struct Foo1; /// This struct is also not [bar](Bar) pub struct Foo2; /// This struct is also not [bar][b] /// /// [b]: Bar pub struct Foo3; /// This struct is also not [`Bar`] pub struct Foo4; pub struct Bar; ``` You can refer to anything in scope, and use paths, including `Self`. You may also use `foo()` and `foo!()` to refer to methods/functions and macros respectively. ```rust,edition2018 use std::sync::mpsc::Receiver; /// This is an version of [`Receiver`], with support for [`std::future`]. /// /// You can obtain a [`std::future::Future`] by calling [`Self::recv()`]. pub struct AsyncReceiver<T> { sender: Receiver<T> } impl<T> AsyncReceiver<T> { pub async fn recv() -> T { unimplemented!() } } ``` Paths in Rust have three namespaces: type, value, and macro. Items from these namespaces are allowed to overlap. In case of ambiguity, rustdoc will warn about the ambiguity and ask you to disambiguate, which can be done by using a prefix like `struct@`, `enum@`, `type@`, `trait@`, `union@`, `const@`, `static@`, `value@`, `function@`, `mod@`, `fn@`, `module@`, `method@`, `prim@`, `primitive@`, `macro@`, or `derive@`: ```rust /// See also: [`Foo`](struct@Foo) struct Bar; /// This is different from [`Foo`](fn@Foo) struct Foo {} fn Foo() {} ``` Note: Because of how `macro_rules` macros are scoped in Rust, the intra-doc links of a `macro_rules` macro will be resolved relative to the crate root, as opposed to the module it is defined in. </del> ## Extensions to the `#[doc]` attribute These features operate by extending the `#[doc]` attribute, and thus can be caught by the compiler


use rustc_data_structures::stable_set::FxHashSet; use rustc_errors::{Applicability, DiagnosticBuilder}; use rustc_expand::base::SyntaxExtensionKind; <del> use rustc_feature::UnstableFeatures; </del> use rustc_hir as hir; use rustc_hir::def::{ DefKind,


}; pub fn collect_intra_doc_links(krate: Crate, cx: &DocContext<'_>) -> Crate { <del> if !UnstableFeatures::from_environment().is_nightly_build() { krate } else { let mut coll = LinkCollector::new(cx); coll.fold_crate(krate) } </del> <ins> let mut coll = LinkCollector::new(cx); coll.fold_crate(krate) </ins> } enum ErrorKind<'a> {


/// println!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() }); /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] <del> #[inline] </del> pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> { builders::debug_struct_new(self, name) }


/// println!("{:?}", Foo(10, "Hello World".to_string())); /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] <del> #[inline] </del> pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> { builders::debug_tuple_new(self, name) }


/// println!("{:?}", Foo(vec![10, 11])); /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] <del> #[inline] </del> pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> { builders::debug_list_new(self) }


/// println!("{:?}", Foo(vec![10, 11])); /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] <del> #[inline] </del> pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> { builders::debug_set_new(self) }


/// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])); /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] <del> #[inline] </del> pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> { builders::debug_map_new(self) }


declare_lint! { pub UNUSED_EXTERN_CRATES, <del> Warn, </del> <ins> Allow, </ins> "extern crates that are never used" }


<del> Subproject commit d9e7d2696e41983b6b5a0b4fac604b4e548a84d3 </del> <ins> Subproject commit c7a16bd57c2a9c643a52f0cebecdaf0b6a996da1 </ins>


unsafe { ::sys::abort_internal() }; } <ins> /// Returns the OS-assigned process identifier associated with this process. /// /// # Examples /// /// Basic usage: /// /// ```no_run /// #![feature(getpid)] /// use std::process; /// /// println!("My pid is {}", process::id()); /// ``` /// /// #[unstable(feature = "getpid", issue = "44971", reason = "recently added")] pub fn id() -> u32 { ::sys::os::getpid() } </ins> #[cfg(all(test, not(target_os = "emscripten")))] mod tests { use io::prelude::*;


let _ = syscall::exit(code as usize); unreachable!(); } <ins> pub fn getpid() -> u32 { syscall::getpid().unwrap() as u32 } </ins>


pub fn exit(code: i32) -> ! { unsafe { libc::exit(code as c_int) } } <ins> pub fn getpid() -> u32 { unsafe { libc::getpid() as u32 } } </ins>


unsafe { c::ExitProcess(code as c::UINT) } } <ins> pub fn getpid() -> u32 { unsafe { c::GetCurrentProcessId() as u32 } } </ins> #[cfg(test)] mod tests { use io::Error;


struct Void { _priv: (), <ins> /// Erases all oibits, because `Void` erases the type of the object that /// will be used to produce formatted output. Since we do not know what /// oibits the real types have (and they can have any or none), we need to /// take the most conservative approach and forbid all oibits. /// /// It was added after #45197 showed that one could share a `!Sync` /// object across threads by passing it into `format_args!`. _oibit_remover: PhantomData<*mut Fn()>, </ins> } /// This struct represents the generic "argument" which is taken by the Xprintf


<ins> // Copyright 2017 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. fn send<T: Send>(_: T) {} fn sync<T: Sync>(_: T) {} fn main() { // `Cell` is not `Sync`, so `&Cell` is neither `Sync` nor `Send`, // `std::fmt::Arguments` used to forget this... let c = std::cell::Cell::new(42); send(format_args!("{:?}", c)); sync(format_args!("{:?}", c)); } </ins>


<ins> error[E0277]: the trait bound `*mut std::ops::Fn() + 'static: std::marker::Sync` is not satisfied in `[std::fmt::ArgumentV1<'_>]` --> $DIR/send-sync.rs:18:5 | 18 |     send(format_args!("{:?}", c)); |     ^^^^ `*mut std::ops::Fn() + 'static` cannot be shared between threads safely | = help: within `[std::fmt::ArgumentV1<'_>]`, the trait `std::marker::Sync` is not implemented for `*mut std::ops::Fn() + 'static` = note: required because it appears within the type `std::marker::PhantomData<*mut std::ops::Fn() + 'static>` = note: required because it appears within the type `core::fmt::Void` = note: required because it appears within the type `&core::fmt::Void` = note: required because it appears within the type `std::fmt::ArgumentV1<'_>` = note: required because it appears within the type `[std::fmt::ArgumentV1<'_>]` = note: required because of the requirements on the impl of `std::marker::Send` for `&[std::fmt::ArgumentV1<'_>]` = note: required because it appears within the type `std::fmt::Arguments<'_>` = note: required by `send` error[E0277]: the trait bound `*mut std::ops::Fn() + 'static: std::marker::Sync` is not satisfied in `std::fmt::Arguments<'_>` --> $DIR/send-sync.rs:19:5 | 19 |     sync(format_args!("{:?}", c)); |     ^^^^ `*mut std::ops::Fn() + 'static` cannot be shared between threads safely | = help: within `std::fmt::Arguments<'_>`, the trait `std::marker::Sync` is not implemented for `*mut std::ops::Fn() + 'static` = note: required because it appears within the type `std::marker::PhantomData<*mut std::ops::Fn() + 'static>` = note: required because it appears within the type `core::fmt::Void` = note: required because it appears within the type `&core::fmt::Void` = note: required because it appears within the type `std::fmt::ArgumentV1<'_>` = note: required because it appears within the type `[std::fmt::ArgumentV1<'_>]` = note: required because it appears within the type `&[std::fmt::ArgumentV1<'_>]` = note: required because it appears within the type `std::fmt::Arguments<'_>` = note: required by `sync` error: aborting due to 2 previous errors </ins>


#[stable(feature = "rust1", since = "1.0.0")] #[macro_export] #[cfg(dox)] <del> macro_rules! format_args { ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ }) } </del> <ins> macro_rules! format_args { ($fmt:expr) => ({ /* compiler built-in */ }); ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ }); } </ins> /// Inspect an environment variable at compile time. ///


#[stable(feature = "rust1", since = "1.0.0")] #[macro_export] #[cfg(dox)] <del> macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) } </del> <ins> macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }); ($name:expr,) => ({ /* compiler built-in */ }); } </ins> /// Optionally inspect an environment variable at compile time. ///


#[macro_export] #[cfg(dox)] macro_rules! concat_idents { <del> ($($e:ident),*) => ({ /* compiler built-in */ }) </del> <ins> ($($e:ident),*) => ({ /* compiler built-in */ }); ($($e:ident,)*) => ({ /* compiler built-in */ }); </ins> } /// Concatenates literals into a static string slice.


#[stable(feature = "rust1", since = "1.0.0")] #[macro_export] #[cfg(dox)] <del> macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) } </del> <ins> macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }); ($($e:expr,)*) => ({ /* compiler built-in */ }); } </ins> /// A macro which expands to the line number on which it was invoked. ///


/// ``` #[stable(feature = "rust1", since = "1.0.0")] #[macro_export] <del> macro_rules! format_args { ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ }) } </del> <ins> macro_rules! format_args { ($fmt:expr) => ({ /* compiler built-in */ }); ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ }); } </ins> /// Inspect an environment variable at compile time. ///


/// ``` #[stable(feature = "rust1", since = "1.0.0")] #[macro_export] <del> macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) } </del> <ins> macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }); ($name:expr,) => ({ /* compiler built-in */ }); } </ins> /// Optionally inspect an environment variable at compile time. ///


#[unstable(feature = "concat_idents_macro", issue = "29599")] #[macro_export] macro_rules! concat_idents { <del> ($($e:ident),*) => ({ /* compiler built-in */ }) </del> <ins> ($($e:ident),*) => ({ /* compiler built-in */ }); ($($e:ident,)*) => ({ /* compiler built-in */ }); </ins> } /// Concatenates literals into a static string slice.


/// ``` #[stable(feature = "rust1", since = "1.0.0")] #[macro_export] <del> macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) } </del> <ins> macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }); ($($e:expr,)*) => ({ /* compiler built-in */ }); } </ins> /// A macro which expands to the line number on which it was invoked. ///


self.search_mut(k).into_occupied_bucket().map(|bucket| pop_internal(bucket).1) } <ins> /// Removes a key from the map, returning the stored key and value if the /// key was previously in the map. /// /// The key may be any borrowed form of the map's key type, but /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for /// the key type. /// /// [`Eq`]: ../../std/cmp/trait.Eq.html /// [`Hash`]: ../../std/hash/trait.Hash.html /// /// # Examples /// /// ``` /// #![feature(hash_map_remove_entry)] /// use std::collections::HashMap; /// /// # fn main() { /// let mut map = HashMap::new(); /// map.insert(1, "a"); /// assert_eq!(map.remove_entry(&1), Some((1, "a"))); /// assert_eq!(map.remove(&1), None); /// # } /// ``` #[unstable(feature = "hash_map_remove_entry", issue = "46344")] pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)> where K: Borrow<Q>, Q: Hash + Eq { if self.table.size() == 0 { return None; } self.search_mut(k) .into_occupied_bucket() .map(|bucket| { let (k, v, _) = pop_internal(bucket); (k, v) }) } </ins> /// Retains only the elements specified by the predicate. /// /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.


} #[test] <del> fn test_pop() { </del> <ins> fn test_remove() { </ins> let mut m = HashMap::new(); m.insert(1, 2); assert_eq!(m.remove(&1), Some(2));


} #[test] <ins> fn test_remove_entry() { let mut m = HashMap::new(); m.insert(1, 2); assert_eq!(m.remove_entry(&1), Some((1, 2))); assert_eq!(m.remove(&1), None); } #[test] </ins> fn test_iterate() { let mut m = HashMap::with_capacity(4); for i in 0..32 {


unsafe { let g = get_static(cx, def_id); <del> let v = match ::mir::codegen_static_initializer(cx, def_id) { </del> <ins> let (v, alloc) = match ::mir::codegen_static_initializer(cx, def_id) { </ins> Ok(v) => v, // Error has already been reported Err(_) => return,


if attr::contains_name(attrs, "thread_local") { llvm::set_thread_local_mode(g, cx.tls_model); <ins> // Do not allow LLVM to change the alignment of a TLS on macOS. // // By default a global's alignment can be freely increased. // This allows LLVM to generate more performant instructions // e.g. using load-aligned into a SIMD register. // // However, on macOS 10.10 or below, the dynamic linker does not // respect any alignment given on the TLS (radar 24221680). // This will violate the alignment assumption, and causing segfault at runtime. // // This bug is very easy to trigger. In `println!` and `panic!`, // the `LOCAL_STDOUT`/`LOCAL_STDERR` handles are stored in a TLS, // which the values would be `mem::replace`d on initialization. // The implementation of `mem::replace` will use SIMD // whenever the size is 32 bytes or higher. LLVM notices SIMD is used // and tries to align `LOCAL_STDOUT`/`LOCAL_STDERR` to a 32-byte boundary, // which macOS's dyld disregarded and causing crashes // (see issues #51794, #51758, #50867, #48866 and #44056). // // To workaround the bug, we trick LLVM into not increasing // the global's alignment by explicitly assigning a section to it // (equivalent to automatically generating a `#[link_section]` attribute). // See the comment in the `GlobalValue::canIncreaseAlignment()` function // of `lib/IR/Globals.cpp` for why this works. // // When the alignment is not increased, the optimized `mem::replace` // will use load-unaligned instructions instead, and thus avoiding the crash. // // We could remove this hack whenever we decide to drop macOS 10.10 support. if cx.tcx.sess.target.target.options.is_like_osx { let sect_name = if alloc.bytes.iter().all(|b| *b == 0) { CStr::from_bytes_with_nul_unchecked(b"__DATA,__thread_bss0") } else { CStr::from_bytes_with_nul_unchecked(b"__DATA,__thread_data0") }; llvm::LLVMSetSection(g, sect_name.as_ptr()); } </ins> } base::set_link_section(cx, g, attrs);


pub fn codegen_static_initializer<'a, 'tcx>( cx: &CodegenCx<'a, 'tcx>, def_id: DefId) <del> -> Result<ValueRef, Lrc<ConstEvalErr<'tcx>>> </del> <ins> -> Result<(ValueRef, &'tcx Allocation), Lrc<ConstEvalErr<'tcx>>> </ins> { let instance = ty::Instance::mono(cx.tcx, def_id); let cid = GlobalId {


ConstValue::ByRef(alloc, n) if n.bytes() == 0 => alloc, _ => bug!("static const eval returned {:#?}", static_), }; <del> Ok(const_alloc_to_llvm(cx, alloc)) </del> <ins> Ok((const_alloc_to_llvm(cx, alloc), alloc)) </ins> } impl<'a, 'tcx> FunctionCx<'a, 'tcx> {


<ins> // Copyright 2018 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. // ignore-tidy-linelength // only-macos // no-system-llvm // min-llvm-version 6.0 // compile-flags: -O #![crate_type = "rlib"] #![feature(thread_local)] // CHECK: @STATIC_VAR_1 = internal thread_local unnamed_addr global <{ [32 x i8] }> zeroinitializer, section "__DATA,__thread_bss", align 4 #[no_mangle] #[allow(private_no_mangle_statics)] #[thread_local] static mut STATIC_VAR_1: [u32; 8] = [0; 8]; // CHECK: @STATIC_VAR_2 = internal thread_local unnamed_addr global <{ [32 x i8] }> <{{[^>]*}}>, section "__DATA,__thread_data", align 4 #[no_mangle] #[allow(private_no_mangle_statics)] #[thread_local] static mut STATIC_VAR_2: [u32; 8] = [4; 8]; #[no_mangle] pub unsafe fn f(x: &mut [u32; 8]) { std::mem::swap(x, &mut STATIC_VAR_1) } #[no_mangle] pub unsafe fn g(x: &mut [u32; 8]) { std::mem::swap(x, &mut STATIC_VAR_2) } </ins>


<ins> // Copyright 2018 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. // only-x86_64 // no-prefer-dynamic // compile-flags: -Ctarget-feature=+avx -Clto fn main() {} </ins>


self.cx } <del> fn do_not_inline(&mut self, _llret: RValue<'gcc>) { </del> <ins> fn apply_attrs_to_cleanup_callsite(&mut self, _llret: RValue<'gcc>) { </ins> unimplemented!(); }


unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED) } } <del> fn do_not_inline(&mut self, llret: &'ll Value) { llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret); </del> <ins> fn apply_attrs_to_cleanup_callsite(&mut self, llret: &'ll Value) { // Cleanup is always the cold path. llvm::Attribute::Cold.apply_callsite(llvm::AttributePlace::Function, llret); // In LLVM versions with deferred inlining (currently, system LLVM < 14), // inlining drop glue can lead to exponential size blowup, see #41696 and #92110. if !llvm_util::is_rust_llvm() && llvm_util::get_version() < (14, 0, 0) { llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret); } </ins> } }


pub fn LLVMRustVersionMinor() -> u32; pub fn LLVMRustVersionPatch() -> u32; <ins> pub fn LLVMRustIsRustLLVM() -> bool; </ins> pub fn LLVMRustAddModuleFlag(M: &Module, name: *const c_char, value: u32); pub fn LLVMRustMetadataAsValue<'a>(C: &'a Context, MD: &'a Metadata) -> &'a Value;


} } <ins> /// Returns `true` if this LLVM is Rust's bundled LLVM (and not system LLVM). pub fn is_rust_llvm() -> bool { // Can be called without initializing LLVM unsafe { llvm::LLVMRustIsRustLLVM() } } </ins> pub fn print_passes() { // Can be called without initializing LLVM unsafe {


let llret = bx.call(fn_ty, fn_ptr, &llargs, self.funclet(fx)); bx.apply_attrs_callsite(&fn_abi, llret); if fx.mir[self.bb].is_cleanup { <del> // Cleanup is always the cold path. Don't inline // drop glue. Also, when there is a deeply-nested // struct, there are "symmetry" issues that cause // exponential inlining - see issue #41696. bx.do_not_inline(llret); </del> <ins> bx.apply_attrs_to_cleanup_callsite(llret); </ins> } if let Some((ret_dest, target)) = destination {


) -> Self::Value; fn zext(&mut self, val: Self::Value, dest_ty: Self::Type) -> Self::Value; <del> fn do_not_inline(&mut self, llret: Self::Value); </del> <ins> fn apply_attrs_to_cleanup_callsite(&mut self, llret: Self::Value); </ins> }


extern "C" uint32_t LLVMRustVersionMajor() { return LLVM_VERSION_MAJOR; } <ins> extern "C" bool LLVMRustIsRustLLVM() { #ifdef LLVM_RUSTLLVM return true; #else return false; #endif } </ins> extern "C" void LLVMRustAddModuleFlag(LLVMModuleRef M, const char *Name, uint32_t Value) { unwrap(M)->addModuleFlag(Module::Warning, Name, Value);


<ins> // no-system-llvm: needs #92110 // compile-flags: -Cno-prepopulate-passes #![crate_type = "lib"] // This test checks that drop calls in unwind landing pads // get the `cold` attribute. // CHECK-LABEL: @check_cold // CHECK: call void {{.+}}drop_in_place{{.+}} [[ATTRIBUTES:#[0-9]+]] // CHECK: attributes [[ATTRIBUTES]] = { cold } #[no_mangle] pub fn check_cold(f: fn(), x: Box<u32>) { // this may unwind f(); } </ins>


<ins> // no-system-llvm: needs #92110 + patch for Rust alloc/dealloc functions // compile-flags: -Copt-level=3 #![crate_type = "lib"] // This test checks that we can inline drop_in_place in // unwind landing pads. // Without inlining, the box pointers escape via the call to drop_in_place, // and LLVM will not optimize out the pointer comparison. // With inlining, everything should be optimized out. // See https://github.com/rust-lang/rust/issues/46515 // CHECK-LABEL: @check_no_escape_in_landingpad // CHECK: start: // CHECK-NEXT: ret void #[no_mangle] pub fn check_no_escape_in_landingpad(f: fn()) { let x = &*Box::new(0); let y = &*Box::new(0); if x as *const _ == y as *const _ { f(); } } // Without inlining, the compiler can't tell that // dropping an empty string (in a landing pad) does nothing. // With inlining, the landing pad should be optimized out. // See https://github.com/rust-lang/rust/issues/87055 // CHECK-LABEL: @check_eliminate_noop_drop // CHECK: start: // CHECK-NEXT: call void %g() // CHECK-NEXT: ret void #[no_mangle] pub fn check_eliminate_noop_drop(g: fn()) { let _var = String::new(); g(); } </ins>


pub fn span_err(&self, sp: Span, m: &str) { self.sess.span_diagnostic.span_err(sp, m) } <ins> pub fn struct_span_err(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> { self.sess.span_diagnostic.struct_span_err(sp, m) } </ins> pub fn span_err_help(&self, sp: Span, m: &str, h: &str) { let mut err = self.sess.span_diagnostic.mut_span_err(sp, m); err.help(h);


let lo = self.span; let hi; <del> if self.check(&token::DotDot) { </del> <ins> if self.check(&token::DotDot) || self.token == token::DotDotDot { if self.token == token::DotDotDot { // Issue #46718 let mut err = self.struct_span_err(self.span, "expected field pattern, found `...`"); err.span_suggestion(self.span, "to omit remaining fields, use one fewer `.`", "..".to_owned()); err.emit(); } </ins> self.bump(); if self.token != token::CloseDelim(token::Brace) { let token_str = self.this_token_to_string();


<ins> // Copyright 2017 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. #![allow(unused)] struct PersonalityInventory { expressivity: f32, instrumentality: f32 } impl PersonalityInventory { fn expressivity(&self) -> f32 { match *self { PersonalityInventory { expressivity: exp, ... } => exp //~^ ERROR expected field pattern, found `...` } } } fn main() {} </ins>


<ins> error: expected field pattern, found `...` --> $DIR/issue-46718-struct-pattern-dotdotdot.rs:21:55 | 21 |             PersonalityInventory { expressivity: exp, ... } => exp |                                                       ^^^ help: to omit remaining fields, use one fewer `.`: `..` error: aborting due to previous error </ins>


} #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")] <ins> #[cfg(bootstrap)] </ins> impl<B, C> ops::TryV1 for ControlFlow<B, C> { type Output = C; type Error = B;


mod generator; mod index; mod range; <ins> #[cfg(bootstrap)] </ins> mod r#try; mod try_trait; mod unsize;


pub use self::r#try::Try; #[unstable(feature = "try_trait_transition", reason = "for bootstrap", issue = "none")] <ins> #[cfg(bootstrap)] </ins> pub(crate) use self::r#try::Try as TryV1; #[unstable(feature = "try_trait_v2", issue = "84277")]


#[rustc_diagnostic_item = "none_error"] #[unstable(feature = "try_trait", issue = "42327")] #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] <ins> #[cfg(bootstrap)] </ins> pub struct NoneError; #[unstable(feature = "try_trait", issue = "42327")] <ins> #[cfg(bootstrap)] </ins> impl<T> ops::TryV1 for Option<T> { type Output = T; type Error = NoneError;


} #[unstable(feature = "try_trait", issue = "42327")] <ins> #[cfg(bootstrap)] </ins> impl<T, E> ops::TryV1 for Result<T, E> { type Output = T; type Error = E;


} #[stable(feature = "futures_api", since = "1.36.0")] <ins> #[cfg(bootstrap)] </ins> impl<T, E> ops::TryV1 for Poll<Result<T, E>> { type Output = Poll<T>; type Error = E;


} #[stable(feature = "futures_api", since = "1.36.0")] <ins> #[cfg(bootstrap)] </ins> impl<T, E> ops::TryV1 for Poll<Option<Result<T, E>>> { type Output = Poll<Option<T>>; type Error = E;


#![feature(str_internals)] #![feature(test)] #![feature(trusted_len)] <del> #![feature(try_trait)] </del> #![feature(try_trait_v2)] #![feature(slice_internals)] #![feature(slice_partition_dedup)]


/// types inside a `Vec`, it will not allocate space for them. *Note that in this case /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only /// if [`mem::size_of::<T>`]`() * capacity() > 0`. In general, `Vec`'s allocation <del> /// details are subtle enough that it is strongly recommended that you only /// free memory allocated by a `Vec` by creating a new `Vec` and dropping it. </del> <ins> /// details are very subtle — if you intend to allocate memory using a `Vec` /// and use it for something else (either to pass to unsafe code, or to build your /// own memory-backed collection), be sure to deallocate this memory by using /// `from_raw_parts` to recover the `Vec` and then dropping it. </ins> /// /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap /// (as defined by the allocator Rust is configured to use by default), and its


res.recv(); } <del> #[test] #[should_fail] #[ignore(cfg(windows))] </del> <ins> #[test] #[should_fail] #[ignore(reason = "random red")] </ins> pub fn exclusive_unwrap_conflict() { let x = exclusive(~~"hello"); let x2 = ~mut Some(x.clone());


#[cfg(not(test))] pub fn init() { <ins> // The standard streams might be closed on application startup. To prevent // std::io::{stdin, stdout,stderr} objects from using other unrelated file // resources opened later, we reopen standards streams when they are closed. unsafe { sanitize_standard_fds(); } </ins> // By default, some platforms will send a *signal* when an EPIPE error // would otherwise be delivered. This runtime doesn't install a SIGPIPE // handler, causing it to kill the program, which isn't exactly what we


reset_sigpipe(); } <ins> // In the case when all file descriptors are open, the poll has been // observed to perform better than fcntl (on GNU/Linux). #[cfg(not(any( miri, target_os = "emscripten", target_os = "fuchsia", // The poll on Darwin doesn't set POLLNVAL for closed fds. target_os = "macos", target_os = "ios", target_os = "redox", )))] unsafe fn sanitize_standard_fds() { use crate::sys::os::errno; let pfds: &mut [_] = &mut [ libc::pollfd { fd: 0, events: 0, revents: 0 }, libc::pollfd { fd: 1, events: 0, revents: 0 }, libc::pollfd { fd: 2, events: 0, revents: 0 }, ]; while libc::poll(pfds.as_mut_ptr(), 3, 0) == -1 { if errno() == libc::EINTR { continue; } libc::abort(); } for pfd in pfds { if pfd.revents & libc::POLLNVAL == 0 { continue; } if libc::open("/dev/null0".as_ptr().cast(), libc::O_RDWR, 0) == -1 { // If the stream is closed but we failed to reopen it, abort the // process. Otherwise we wouldn't preserve the safety of // operations on the corresponding Rust object Stdin, Stdout, or // Stderr. libc::abort(); } } } #[cfg(any(target_os = "macos", target_os = "ios", target_os = "redox"))] unsafe fn sanitize_standard_fds() { use crate::sys::os::errno; for fd in 0..3 { if libc::fcntl(fd, libc::F_GETFD) == -1 && errno() == libc::EBADF { if libc::open("/dev/null0".as_ptr().cast(), libc::O_RDWR, 0) == -1 { libc::abort(); } } } } #[cfg(any( // The standard fds are always available in Miri. miri, target_os = "emscripten", target_os = "fuchsia"))] unsafe fn sanitize_standard_fds() {} </ins> #[cfg(not(any(target_os = "emscripten", target_os = "fuchsia")))] unsafe fn reset_sigpipe() { assert!(signal(libc::SIGPIPE, libc::SIG_IGN) != libc::SIG_ERR);


return r } <ins> #[cfg(unix)] fn assert_fd_is_valid(fd: libc::c_int) { if unsafe { libc::fcntl(fd, libc::F_GETFD) == -1 } { panic!("file descriptor {} is not valid: {}", fd, io::Error::last_os_error()); } } #[cfg(windows)] fn assert_fd_is_valid(_fd: libc::c_int) {} </ins> #[cfg(windows)] unsafe fn without_stdio<R, F: FnOnce() -> R>(f: F) -> R { type DWORD = u32;


fn main() { if env::args().len() > 1 { <ins> // Writing to stdout & stderr should not panic. </ins> println!("test"); assert!(io::stdout().write(b"testn").is_ok()); assert!(io::stderr().write(b"testn").is_ok()); <ins> // Stdin should be at EOF. </ins> assert_eq!(io::stdin().read(&mut [0; 10]).unwrap(), 0); <ins> // Standard file descriptors should be valid on UNIX: assert_fd_is_valid(0); assert_fd_is_valid(1); assert_fd_is_valid(2); </ins> return }


.stdout(Stdio::null()) .stderr(Stdio::null()) .status().unwrap(); <del> assert!(status.success(), "{:?} isn't a success", status); </del> <ins> assert!(status.success(), "{} isn't a success", status); </ins> // Finally, close everything then spawn a child to make sure everything is // *still* ok. let status = unsafe { without_stdio(|| Command::new(&me).arg("next").status()) }.unwrap(); <del> assert!(status.success(), "{:?} isn't a success", status); </del> <ins> assert!(status.success(), "{} isn't a success", status); </ins> }


end: RangeEnd, }, <del> /// matches against a slice, checking the length and extracting elements </del> <ins> /// matches against a slice, checking the length and extracting elements. /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty. /// e.g. `&[ref xs..]`. </ins> Slice { prefix: Vec<Pattern<'tcx>>, slice: Option<Pattern<'tcx>>,


Err(match_pair) } <del> PatternKind::Range { .. } | PatternKind::Slice { .. } => { </del> <ins> PatternKind::Range { .. } => { </ins> Err(match_pair) } <ins> PatternKind::Slice { ref prefix, ref slice, ref suffix } => { if prefix.is_empty() && slice.is_some() && suffix.is_empty() { // irrefutable self.prefix_slice_suffix(&mut candidate.match_pairs, &match_pair.place, prefix, slice.as_ref(), suffix); Ok(()) } else { Err(match_pair) } } </ins> PatternKind::Variant { adt_def, substs, variant_index, ref subpatterns } => { let irrefutable = adt_def.variants.iter().enumerate().all(|(i, v)| { i == variant_index || {


<ins> // Copyright 2018 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. // #47096 #![feature(slice_patterns)] fn foo(s: &[i32]) -> &[i32] { let &[ref xs..] = s; xs } fn main() { let x = [1, 2, 3]; let y = foo(&x); assert_eq!(x, y); } </ins>


#[test] #[should_fail] fn test_ascii_fail_char_slice() { 'λ'.to_ascii(); } <ins> #[test] </ins> fn test_opt() { assert_eq!(65u8.to_ascii_opt(), Some(Ascii { chr: 65u8 })); assert_eq!(255u8.to_ascii_opt(), None);


#[cfg(test)] mod test { use super::*; <del> use io::net::ip::{Ipv4Addr, SocketAddr}; </del> <ins> use io::net::ip::{SocketAddr}; </ins> use io::*; <del> use io::test::*; </del> use prelude::*; iotest!(fn bind_error() {


use unstable::run_in_bare_thread; use super::*; use rt::task::Task; <del> use rt::local_ptr; </del> #[test] fn thread_local_task_smoke_test() {


fn visit_estr_uniq(&mut self) -> bool { true } fn visit_estr_slice(&mut self) -> bool { true } fn visit_estr_fixed(&mut self, <del> _sz: uint, _sz: uint, </del> <ins> _sz: uint, _sz2: uint, </ins> _align: uint) -> bool { true } fn visit_box(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { true }


&substs[..] )); } <del> DefiningTy::Const(ty) => { </del> <ins> DefiningTy::Const(def_id, substs) => { </ins> err.note(&format!( <del> "defining type: {:?}", ty </del> <ins> "defining constant type: {:?} with substs {:#?}", def_id, &substs[..] </ins> )); } }


/// The MIR represents some form of constant. The signature then /// is that it has no inputs and a single return value, which is /// the value of the constant. <del> Const(Ty<'tcx>), </del> <ins> Const(DefId, &'tcx Substs<'tcx>), </ins> } #[derive(Debug)]


/// see `DefiningTy` for details. fn defining_ty(&self) -> DefiningTy<'tcx> { let tcx = self.infcx.tcx; let closure_base_def_id = tcx.closure_base_def_id(self.mir_def_id); <del> let defining_ty = if self.mir_def_id == closure_base_def_id { tcx.type_of(closure_base_def_id) } else { let tables = tcx.typeck_tables_of(self.mir_def_id); tables.node_id_to_type(self.mir_hir_id) }; let defining_ty = self.infcx .replace_free_regions_with_nll_infer_vars(FR, &defining_ty); </del> match tcx.hir.body_owner_kind(self.mir_node_id) { <del> BodyOwnerKind::Fn => match defining_ty.sty { ty::TyClosure(def_id, substs) => DefiningTy::Closure(def_id, substs), ty::TyGenerator(def_id, substs, interior) => { DefiningTy::Generator(def_id, substs, interior) </del> <ins> BodyOwnerKind::Fn => { let defining_ty = if self.mir_def_id == closure_base_def_id { tcx.type_of(closure_base_def_id) } else { let tables = tcx.typeck_tables_of(self.mir_def_id); tables.node_id_to_type(self.mir_hir_id) }; let defining_ty = self.infcx .replace_free_regions_with_nll_infer_vars(FR, &defining_ty); match defining_ty.sty  { ty::TyClosure(def_id, substs) => DefiningTy::Closure(def_id, substs), ty::TyGenerator(def_id, substs, interior) => { DefiningTy::Generator(def_id, substs, interior) } ty::TyFnDef(def_id, substs) => DefiningTy::FnDef(def_id, substs), _ => span_bug!( tcx.def_span(self.mir_def_id), "expected defining type for `{:?}`: `{:?}`", self.mir_def_id, defining_ty ), </ins> } <del> ty::TyFnDef(def_id, substs) => DefiningTy::FnDef(def_id, substs), _ => span_bug!( tcx.def_span(self.mir_def_id), "expected defining type for `{:?}`: `{:?}`", self.mir_def_id, defining_ty ), }, BodyOwnerKind::Const | BodyOwnerKind::Static(..) => DefiningTy::Const(defining_ty), </del> <ins> } BodyOwnerKind::Const | BodyOwnerKind::Static(..) => { assert_eq!(closure_base_def_id, self.mir_def_id); let identity_substs = Substs::identity_for_item(tcx, closure_base_def_id); let substs = self.infcx .replace_free_regions_with_nll_infer_vars(FR, &identity_substs); DefiningTy::Const(self.mir_def_id, substs) } </ins> } }


substs.substs } <del> DefiningTy::FnDef(_, substs) => substs, // When we encounter a constant body, just return whatever // substitutions are in scope for that constant. DefiningTy::Const(_) => { identity_substs } </del> <ins> DefiningTy::FnDef(_, substs) | DefiningTy::Const(_, substs) => substs, </ins> }; let global_mapping = iter::once((gcx.types.re_static, fr_static));


sig.inputs_and_output() } <del> // For a constant body, there are no inputs, and one // "output" (the type of the constant). DefiningTy::Const(ty) => ty::Binder::dummy(tcx.mk_type_list(iter::once(ty))), </del> <ins> DefiningTy::Const(def_id, _) => { // For a constant body, there are no inputs, and one // "output" (the type of the constant). assert_eq!(self.mir_def_id, def_id); let ty = tcx.type_of(def_id); let ty = indices.fold_to_region_vids(tcx, &ty); ty::Binder::dummy(tcx.mk_type_list(iter::once(ty))) } </ins> } }


<ins> // Copyright 2018 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. // Test cases where we put various lifetime constraints on trait // associated constants. #![feature(rustc_attrs)] use std::option::Option; trait Anything<'a: 'b, 'b> { const AC: Option<&'b str>; } struct OKStruct { } impl<'a: 'b, 'b> Anything<'a, 'b> for OKStruct { const AC: Option<&'b str> = None; } struct FailStruct1 { } impl<'a: 'b, 'b, 'c> Anything<'a, 'b> for FailStruct1 { const AC: Option<&'c str> = None; //~^ ERROR: mismatched types } struct FailStruct2 { } impl<'a: 'b, 'b> Anything<'a, 'b> for FailStruct2 { const AC: Option<&'a str> = None; //~^ ERROR: mismatched types } fn main() {} </ins>


<ins> error[E0308]: mismatched types --> $DIR/trait-associated-constant.rs:31:5 | 31 |     const AC: Option<&'c str> = None; |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetime mismatch | = note: expected type `std::option::Option<&'b str>` found type `std::option::Option<&'c str>` note: the lifetime 'c as defined on the impl at 30:1... --> $DIR/trait-associated-constant.rs:30:1 | 30 | impl<'a: 'b, 'b, 'c> Anything<'a, 'b> for FailStruct1 { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note: ...does not necessarily outlive the lifetime 'b as defined on the impl at 30:1 --> $DIR/trait-associated-constant.rs:30:1 | 30 | impl<'a: 'b, 'b, 'c> Anything<'a, 'b> for FailStruct1 { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0308]: mismatched types --> $DIR/trait-associated-constant.rs:38:5 | 38 |     const AC: Option<&'a str> = None; |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetime mismatch | = note: expected type `std::option::Option<&'b str>` found type `std::option::Option<&'a str>` note: the lifetime 'a as defined on the impl at 37:1... --> $DIR/trait-associated-constant.rs:37:1 | 37 | impl<'a: 'b, 'b> Anything<'a, 'b> for FailStruct2 { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note: ...does not necessarily outlive the lifetime 'b as defined on the impl at 37:1 --> $DIR/trait-associated-constant.rs:37:1 | 37 | impl<'a: 'b, 'b> Anything<'a, 'b> for FailStruct2 { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 2 previous errors </ins>


} OptLevel::Default } else { <del> match ( cg.opt_level.as_ref().map(String::as_ref), nightly_options::is_nightly_build(), ) { (None, _) => OptLevel::No, (Some("0"), _) => OptLevel::No, (Some("1"), _) => OptLevel::Less, (Some("2"), _) => OptLevel::Default, (Some("3"), _) => OptLevel::Aggressive, (Some("s"), true) => OptLevel::Size, (Some("z"), true) => OptLevel::SizeMin, (Some("s"), false) | (Some("z"), false) => { early_error( error_format, &format!( "the optimizations s or z are only  accepted on the nightly compiler" ), ); } (Some(arg), _) => { </del> <ins> match cg.opt_level.as_ref().map(String::as_ref) { None => OptLevel::No, Some("0") => OptLevel::No, Some("1") => OptLevel::Less, Some("2") => OptLevel::Default, Some("3") => OptLevel::Aggressive, Some("s") => OptLevel::Size, Some("z") => OptLevel::SizeMin, Some(arg) => { </ins> early_error( error_format, &format!(


pub use run::{cmd, run, run_fail, run_with_args}; /// Helpers for checking target information. <del> pub use targets::{is_darwin, is_msvc, is_windows, llvm_components_contain, target, uname}; </del> <ins> pub use targets::{is_darwin, is_msvc, is_windows, llvm_components_contain, target, uname, apple_os}; </ins> /// Helpers for building names of output artifacts that are potentially target-specific. pub use artifact_names::{


target().contains("darwin") } <ins> /// Get the target OS on Apple operating systems. #[must_use] pub fn apple_os() -> &'static str { if target().contains("darwin") { "macos" } else if target().contains("ios") { "ios" } else if target().contains("tvos") { "tvos" } else if target().contains("watchos") { "watchos" } else if target().contains("visionos") { "visionos" } else { panic!("not an Apple OS") } } </ins> /// Check if `component` is within `LLVM_COMPONENTS` #[must_use] pub fn llvm_components_contain(component: &str) -> bool {


run-make/issue-84395-lto-embed-bitcode/Makefile run-make/jobserver-error/Makefile run-make/libs-through-symlinks/Makefile <del> run-make/macos-deployment-target/Makefile </del> run-make/split-debuginfo/Makefile run-make/symbol-mangling-hashed/Makefile run-make/translation/Makefile