diff --git a/.gitmodules b/.gitmodules index 40e6fc2c19db0..984113151de4d 100644 --- a/.gitmodules +++ b/.gitmodules @@ -37,7 +37,7 @@ [submodule "src/llvm-project"] path = src/llvm-project url = https://github.com/rust-lang/llvm-project.git - branch = rustc/11.0-2021-01-05 + branch = rustc/11.0-2020-10-12 [submodule "src/doc/embedded-book"] path = src/doc/embedded-book url = https://github.com/rust-embedded/book.git diff --git a/Cargo.lock b/Cargo.lock index b2ae22b6abd9b..ab452c97e7b37 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -101,12 +101,6 @@ version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4d25d88fd6b8041580a654f9d0c581a047baee2b3efee13275f2fc392fc75034" -[[package]] -name = "array_tool" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f8cb5d814eb646a863c4f24978cff2880c4be96ad8cde2c0f0678732902e271" - [[package]] name = "arrayref" version = "0.3.6" @@ -1636,32 +1630,6 @@ version = "0.11.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92c245af8786f6ac35f95ca14feca9119e71339aaab41e878e7cdd655c97e9e5" -[[package]] -name = "jsondocck" -version = "0.1.0" -dependencies = [ - "getopts", - "jsonpath_lib", - "lazy_static", - "regex", - "serde", - "serde_json", - "shlex", -] - -[[package]] -name = "jsonpath_lib" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61352ec23883402b7d30b3313c16cbabefb8907361c4eb669d990cbb87ceee5a" -dependencies = [ - "array_tool", - "env_logger 0.7.1", - "log", - "serde", - "serde_json", -] - [[package]] name = "jsonrpc-client-transports" version = "14.2.1" @@ -2005,9 +1973,9 @@ dependencies = [ [[package]] name = "mdbook" -version = "0.4.6" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3d948b64449003363127ed6c6139f03273982c3fe97da4cb3dee933e38ce38f" +checksum = "21251d3eb9ca5e8ac5b73384ddaa483a9bbc7d7dcd656b1fa8f266634810334a" dependencies = [ "ammonia", "anyhow", @@ -2752,9 +2720,9 @@ dependencies = [ [[package]] name = "racer" -version = "2.1.42" +version = "2.1.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4463624cd50208e86382c13a84561fcd1d3e9d8ff4d97e8ef0c5e304df8d2b9" +checksum = "a2f1a4baaaf5c4a9aa30c708c339ae293d02976d2b7f1575a59f44558d25bfea" dependencies = [ "bitflags", "clap", @@ -2886,9 +2854,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.4.3" +version = "1.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9251239e129e16308e70d853559389de218ac275b515068abc96829d05b948a" +checksum = "9c3780fcf44b193bc4d09f36d2a3c87b251da4a046c87795a0d35f4f927ad8e6" dependencies = [ "aho-corasick", "memchr", @@ -2908,9 +2876,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.6.22" +version = "0.6.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5eb417147ba9860a96cfe72a0b93bf88fee1744b5636ec99ab20c1aa9376581" +checksum = "26412eb97c6b088a6997e05f69403a802a92d520de2f8e63c2b65f9e0f47c4e8" [[package]] name = "remote-test-client" @@ -2996,9 +2964,9 @@ dependencies = [ [[package]] name = "rls-data" -version = "0.19.1" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a58135eb039f3a3279a33779192f0ee78b56f57ae636e25cec83530e41debb99" +checksum = "76c72ea97e045be5f6290bb157ebdc5ee9f2b093831ff72adfaf59025cf5c491" dependencies = [ "rls-span", "serde", @@ -3033,9 +3001,9 @@ dependencies = [ [[package]] name = "rls-span" -version = "0.5.3" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0eea58478fc06e15f71b03236612173a1b81e9770314edecfa664375e3e4c86" +checksum = "f2e9bed56f6272bd85d9d06d1aaeef80c5fddc78a82199eb36dceb5f94e7d934" dependencies = [ "serde", ] @@ -3081,18 +3049,18 @@ dependencies = [ [[package]] name = "rustc-ap-rustc_arena" -version = "697.0.0" +version = "691.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb953bea2006184c8f01a6fd3ed51658c73380992a9aefc113e8d32ece6b7516" +checksum = "81f7b9bc5a6f79b1f230833cb4c8f8928d48c129b21df5b372c202fb826c0b5e" dependencies = [ "smallvec 1.4.2", ] [[package]] name = "rustc-ap-rustc_ast" -version = "697.0.0" +version = "691.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94da60fa49b2f60d2539e8823cf2b4d4e61583ba4ee796b8289e12f017d3dc5b" +checksum = "3d77f313e9f30af93f2737f1a99d6552e26b702c5cef3bb65e35f5b4fe5191f1" dependencies = [ "bitflags", "rustc-ap-rustc_data_structures", @@ -3107,9 +3075,9 @@ dependencies = [ [[package]] name = "rustc-ap-rustc_ast_passes" -version = "697.0.0" +version = "691.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e9f9eaaee223832187a398abe0f9cb8bc4e5cd538322d8f3864aea65239c79e" +checksum = "30408fbf42fa6fbeb383d3fce0f24d2490c3d12527beb2f48e6e728765bc8695" dependencies = [ "itertools 0.9.0", "rustc-ap-rustc_ast", @@ -3126,9 +3094,9 @@ dependencies = [ [[package]] name = "rustc-ap-rustc_ast_pretty" -version = "697.0.0" +version = "691.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "302b43429c62efc43b159b1f8ab94c8b517fb553cbae854c3fcf34e01c36accb" +checksum = "d47b8a3adcccc204578b0ee9cd2f9952921fa43977f58343913cca04cce87043" dependencies = [ "rustc-ap-rustc_ast", "rustc-ap-rustc_span", @@ -3138,9 +3106,9 @@ dependencies = [ [[package]] name = "rustc-ap-rustc_attr" -version = "697.0.0" +version = "691.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cbd78cb6f7ca0991478d7f1bc5646b6eca58c37ccbdf70b5d83c490a7c47be7" +checksum = "66f5f53ecdbf7d8b47905936f93eb1fdae496137e94b7e4023a0b866b0e1a92d" dependencies = [ "rustc-ap-rustc_ast", "rustc-ap-rustc_ast_pretty", @@ -3157,9 +3125,9 @@ dependencies = [ [[package]] name = "rustc-ap-rustc_data_structures" -version = "697.0.0" +version = "691.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b9ebd359b0f21086a88595a25d92dc7e8e5f7b111e41c52bb6c97e2d95fd0bb" +checksum = "3aa913fa40b90157067b17dd7ddfd5df0d8566e339ffa8351a638bdf3fc7ee81" dependencies = [ "arrayvec", "bitflags", @@ -3188,9 +3156,9 @@ dependencies = [ [[package]] name = "rustc-ap-rustc_errors" -version = "697.0.0" +version = "691.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b810fcac4d738c47d7793afe3e0f2e03d5193c36c698b0fbcebfb64e468c06b" +checksum = "5d4b4956287d7c4996409b8362aa69c0c9a6853751ff00ee0a6f78223c5ef3ad" dependencies = [ "annotate-snippets 0.8.0", "atty", @@ -3208,9 +3176,9 @@ dependencies = [ [[package]] name = "rustc-ap-rustc_expand" -version = "697.0.0" +version = "691.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5b44aadd09c05a42a21a063e9f2241fd3d9c00c3dd6e474e22c3a3e8274c959" +checksum = "3fa908bb1b67230dd4309e93edefc6a6c2f3d8b6a195f77c47743c882114a22e" dependencies = [ "rustc-ap-rustc_ast", "rustc-ap-rustc_ast_passes", @@ -3231,9 +3199,9 @@ dependencies = [ [[package]] name = "rustc-ap-rustc_feature" -version = "697.0.0" +version = "691.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2f4121cb9718c8c1c6350a3aaea619fbbae38fb1aadd3d7305586460babb531" +checksum = "d9b7a1db115893ed7ed0db80f70d2246c1709de7854238acde76471495930f2a" dependencies = [ "rustc-ap-rustc_data_structures", "rustc-ap-rustc_span", @@ -3241,21 +3209,21 @@ dependencies = [ [[package]] name = "rustc-ap-rustc_fs_util" -version = "697.0.0" +version = "691.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdb0f36e34fafb725795bef3ec6f414cac34e7ca98e6d25927be36d95ae1c6ac" +checksum = "55937887cb606cc72193ea3c5feb8bbbb810d812aa233b9a1e7749155c4a3501" [[package]] name = "rustc-ap-rustc_graphviz" -version = "697.0.0" +version = "691.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a98402e20e2913016ed54f12aead5c987fe227a0fb31cc720e17ff51c6f32466" +checksum = "e39e179e616356927f0c4eda43e3a35d88476f91e1ac8e4a0a09661dbab44a6e" [[package]] name = "rustc-ap-rustc_index" -version = "697.0.0" +version = "691.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec91408d727f73f682cd8ae836d762c8dab0ed4e81994ced03aa1edcee3b99a4" +checksum = "572d3962d6999f3b1a71d335308e939e204339d4ad36e6ebe7a591c9d4329f5d" dependencies = [ "arrayvec", "rustc-ap-rustc_macros", @@ -3264,18 +3232,18 @@ dependencies = [ [[package]] name = "rustc-ap-rustc_lexer" -version = "697.0.0" +version = "691.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67adbe260a0a11910624d6d28c0304fcf7b063e666682111005c83b09f73429d" +checksum = "44bc89d9ca7a78fb82e103b389362c55f03800745f8ba14e068b805cfaf783ec" dependencies = [ "unicode-xid", ] [[package]] name = "rustc-ap-rustc_lint_defs" -version = "697.0.0" +version = "691.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bf11d0646da7bd136fbca53834afcc3760fbfc20fa4875e139b3ada41ec53a5" +checksum = "7d39bda92aabd77e49ac8ad5e24fccf9d7245b8ff2bf1249ab98733e2e5a2863" dependencies = [ "rustc-ap-rustc_ast", "rustc-ap-rustc_data_structures", @@ -3287,9 +3255,9 @@ dependencies = [ [[package]] name = "rustc-ap-rustc_macros" -version = "697.0.0" +version = "691.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c454b10b66750ffd9bfd7d53b0f30eaba1462356e9ac91f0d037cb0556dc7681" +checksum = "a3295fbc9625197494e356e92d8ac08370eddafa60189861c7b2f084b3b5a6b8" dependencies = [ "proc-macro2", "quote", @@ -3299,9 +3267,9 @@ dependencies = [ [[package]] name = "rustc-ap-rustc_parse" -version = "697.0.0" +version = "691.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d03f423948137a8370a88447382a18015d47a273268e3ead2d0a987c3b14070" +checksum = "9ff5d0094396844efead43303a6eb25b8a4962e2c80fb0ea4a86e4101fbfd404" dependencies = [ "bitflags", "rustc-ap-rustc_ast", @@ -3319,9 +3287,9 @@ dependencies = [ [[package]] name = "rustc-ap-rustc_serialize" -version = "697.0.0" +version = "691.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7ed5df71bd37d1e179b4bbedf77db76c9e0eb2e03159c58a691adbf29f74682" +checksum = "2d5cff6709a8b51a3730288a9ead17cabe8146b1c787db52298447ef7890140a" dependencies = [ "indexmap", "smallvec 1.4.2", @@ -3329,9 +3297,9 @@ dependencies = [ [[package]] name = "rustc-ap-rustc_session" -version = "697.0.0" +version = "691.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e3b92b51fad25a897b23ec98961126aea038abeab8d47989f774f7727016b5e" +checksum = "36bb15ef12174b5ed6419a7e4260a899ce8927e8c8fd1f0cddf178818737dcdf" dependencies = [ "bitflags", "getopts", @@ -3351,9 +3319,9 @@ dependencies = [ [[package]] name = "rustc-ap-rustc_span" -version = "697.0.0" +version = "691.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d98273206d8a571c780f233f3391ea30e29c5e75ecdc60335ccef346046e1953" +checksum = "104d349a32be9cfd3d39a5a70ad6c5e682ce262fc5cc8717d35a01e980c0d8b2" dependencies = [ "cfg-if 0.1.10", "md-5", @@ -3371,9 +3339,9 @@ dependencies = [ [[package]] name = "rustc-ap-rustc_target" -version = "697.0.0" +version = "691.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08ce81fe0130e61112db5f3b2db6b21d407e4b14ae467ab9637f4696cc340ad1" +checksum = "9d7ac4ded9a6aecb534744c836a160497985f0d53b272581e95e7890d31b9e17" dependencies = [ "bitflags", "rustc-ap-rustc_data_structures", @@ -3928,7 +3896,6 @@ dependencies = [ "rustc_macros", "rustc_serialize", "rustc_span", - "rustc_target", "tracing", ] @@ -4432,7 +4399,7 @@ dependencies = [ [[package]] name = "rustfmt-nightly" -version = "1.4.32" +version = "1.4.30" dependencies = [ "annotate-snippets 0.6.1", "anyhow", @@ -4610,7 +4577,6 @@ version = "1.0.59" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dcac07dbffa1c65e7f816ab9eba78eb142c6d44410f4eeba1e26e4f5dfa56b95" dependencies = [ - "indexmap", "itoa", "ryu", "serde", diff --git a/Cargo.toml b/Cargo.toml index 5bd1147cad554..204c92045b110 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,7 +31,6 @@ members = [ "src/tools/rustdoc-themes", "src/tools/unicode-table-generator", "src/tools/expand-yaml-anchors", - "src/tools/jsondocck", ] exclude = [ diff --git a/README.md b/README.md index 6ab11e7e2be6d..07c0960466400 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ -# The Rust Programming Language + +The Rust Programming Language + This is the main source code repository for [Rust]. It contains the compiler, standard library, and documentation. diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index ff89982a4efd8..8601da6fa0650 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -242,21 +242,12 @@ impl Into>> for ParenthesizedArgs { /// A path like `Foo(A, B) -> C`. #[derive(Clone, Encodable, Decodable, Debug)] pub struct ParenthesizedArgs { - /// ```text - /// Foo(A, B) -> C - /// ^^^^^^^^^^^^^^ - /// ``` + /// Overall span pub span: Span, /// `(A, B)` pub inputs: Vec>, - /// ```text - /// Foo(A, B) -> C - /// ^^^^^^ - /// ``` - pub inputs_span: Span, - /// `C` pub output: FnRetTy, } @@ -925,6 +916,16 @@ impl Stmt { } } + pub fn set_tokens(&mut self, tokens: Option) { + match self.kind { + StmtKind::Local(ref mut local) => local.tokens = tokens, + StmtKind::Item(ref mut item) => item.tokens = tokens, + StmtKind::Expr(ref mut expr) | StmtKind::Semi(ref mut expr) => expr.tokens = tokens, + StmtKind::Empty => {} + StmtKind::MacCall(ref mut mac) => mac.tokens = tokens, + } + } + pub fn has_trailing_semicolon(&self) -> bool { match &self.kind { StmtKind::Semi(_) => true, @@ -2880,69 +2881,3 @@ impl TryFrom for ForeignItemKind { } pub type ForeignItem = Item; - -pub trait HasTokens { - /// Called by `Parser::collect_tokens` to store the collected - /// tokens inside an AST node - fn finalize_tokens(&mut self, tokens: LazyTokenStream); -} - -impl HasTokens for P { - fn finalize_tokens(&mut self, tokens: LazyTokenStream) { - (**self).finalize_tokens(tokens); - } -} - -impl HasTokens for Option { - fn finalize_tokens(&mut self, tokens: LazyTokenStream) { - if let Some(inner) = self { - inner.finalize_tokens(tokens); - } - } -} - -impl HasTokens for Attribute { - fn finalize_tokens(&mut self, tokens: LazyTokenStream) { - match &mut self.kind { - AttrKind::Normal(_, attr_tokens) => { - if attr_tokens.is_none() { - *attr_tokens = Some(tokens); - } - } - AttrKind::DocComment(..) => { - panic!("Called finalize_tokens on doc comment attr {:?}", self) - } - } - } -} - -impl HasTokens for Stmt { - fn finalize_tokens(&mut self, tokens: LazyTokenStream) { - let stmt_tokens = match self.kind { - StmtKind::Local(ref mut local) => &mut local.tokens, - StmtKind::Item(ref mut item) => &mut item.tokens, - StmtKind::Expr(ref mut expr) | StmtKind::Semi(ref mut expr) => &mut expr.tokens, - StmtKind::Empty => return, - StmtKind::MacCall(ref mut mac) => &mut mac.tokens, - }; - if stmt_tokens.is_none() { - *stmt_tokens = Some(tokens); - } - } -} - -macro_rules! derive_has_tokens { - ($($ty:path),*) => { $( - impl HasTokens for $ty { - fn finalize_tokens(&mut self, tokens: LazyTokenStream) { - if self.tokens.is_none() { - self.tokens = Some(tokens); - } - } - } - )* } -} - -derive_has_tokens! { - Item, Expr, Ty, AttrItem, Visibility, Path, Block, Pat -} diff --git a/compiler/rustc_ast/src/attr/mod.rs b/compiler/rustc_ast/src/attr/mod.rs index 4dcbe4831be27..6a54cb4766b24 100644 --- a/compiler/rustc_ast/src/attr/mod.rs +++ b/compiler/rustc_ast/src/attr/mod.rs @@ -526,7 +526,7 @@ impl MetaItemKind { fn list_from_tokens(tokens: TokenStream) -> Option { let mut tokens = tokens.into_trees().peekable(); let mut result = Vec::new(); - while tokens.peek().is_some() { + while let Some(..) = tokens.peek() { let item = NestedMetaItem::from_tokens(&mut tokens)?; result.push(item); match tokens.next() { diff --git a/compiler/rustc_ast/src/lib.rs b/compiler/rustc_ast/src/lib.rs index 08695491de756..8a20dd7968590 100644 --- a/compiler/rustc_ast/src/lib.rs +++ b/compiler/rustc_ast/src/lib.rs @@ -13,7 +13,6 @@ #![feature(const_fn_transmute)] #![feature(const_panic)] #![feature(crate_visibility_modifier)] -#![feature(iterator_fold_self)] #![feature(label_break_value)] #![feature(nll)] #![feature(or_patterns)] diff --git a/compiler/rustc_ast/src/mut_visit.rs b/compiler/rustc_ast/src/mut_visit.rs index 35de744d274c9..575552c4dcee6 100644 --- a/compiler/rustc_ast/src/mut_visit.rs +++ b/compiler/rustc_ast/src/mut_visit.rs @@ -565,7 +565,7 @@ pub fn noop_visit_parenthesized_parameter_data( args: &mut ParenthesizedArgs, vis: &mut T, ) { - let ParenthesizedArgs { inputs, output, span, .. } = args; + let ParenthesizedArgs { inputs, output, span } = args; visit_vec(inputs, |input| vis.visit_ty(input)); noop_visit_fn_ret_ty(output, vis); vis.visit_span(span); diff --git a/compiler/rustc_ast/src/util/literal.rs b/compiler/rustc_ast/src/util/literal.rs index 2124f1efb990c..106ffb2a0fdfb 100644 --- a/compiler/rustc_ast/src/util/literal.rs +++ b/compiler/rustc_ast/src/util/literal.rs @@ -87,6 +87,7 @@ impl LitKind { } }); error?; + buf.shrink_to_fit(); Symbol::intern(&buf) } else { symbol @@ -104,6 +105,7 @@ impl LitKind { } }); error?; + buf.shrink_to_fit(); LitKind::ByteStr(buf.into()) } token::ByteStrRaw(_) => { @@ -118,6 +120,7 @@ impl LitKind { } }); error?; + buf.shrink_to_fit(); buf } else { symbol.to_string().into_bytes() diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 1b9ccbd850bee..9b1642df11401 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -87,12 +87,9 @@ impl<'hir> LoweringContext<'_, 'hir> { ExprKind::Let(ref pat, ref scrutinee) => { self.lower_expr_let(e.span, pat, scrutinee) } - ExprKind::If(ref cond, ref then, ref else_opt) => match cond.kind { - ExprKind::Let(ref pat, ref scrutinee) => { - self.lower_expr_if_let(e.span, pat, scrutinee, then, else_opt.as_deref()) - } - _ => self.lower_expr_if(cond, then, else_opt.as_deref()), - }, + ExprKind::If(ref cond, ref then, ref else_opt) => { + self.lower_expr_if(e.span, cond, then, else_opt.as_deref()) + } ExprKind::While(ref cond, ref body, opt_label) => self .with_loop_scope(e.id, |this| { this.lower_expr_while_in_loop_scope(e.span, cond, body, opt_label) @@ -339,29 +336,9 @@ impl<'hir> LoweringContext<'_, 'hir> { } fn lower_expr_if( - &mut self, - cond: &Expr, - then: &Block, - else_opt: Option<&Expr>, - ) -> hir::ExprKind<'hir> { - macro_rules! make_if { - ($opt:expr) => {{ - let then_expr = self.lower_block_expr(then); - hir::ExprKind::If(self.lower_expr(cond), self.arena.alloc(then_expr), $opt) - }}; - } - if let Some(rslt) = else_opt { - make_if!(Some(self.lower_expr(rslt))) - } else { - make_if!(None) - } - } - - fn lower_expr_if_let( &mut self, span: Span, - pat: &Pat, - scrutinee: &Expr, + cond: &Expr, then: &Block, else_opt: Option<&Expr>, ) -> hir::ExprKind<'hir> { @@ -376,13 +353,30 @@ impl<'hir> LoweringContext<'_, 'hir> { let else_arm = self.arm(else_pat, else_expr); // Handle then + scrutinee: - let scrutinee = self.lower_expr(scrutinee); - let then_pat = self.lower_pat(pat); - + let (then_pat, scrutinee, desugar) = match cond.kind { + // ` => `: + ExprKind::Let(ref pat, ref scrutinee) => { + let scrutinee = self.lower_expr(scrutinee); + let pat = self.lower_pat(pat); + (pat, scrutinee, hir::MatchSource::IfLetDesugar { contains_else_clause }) + } + // `true => `: + _ => { + // Lower condition: + let cond = self.lower_expr(cond); + let span_block = + self.mark_span_with_reason(DesugaringKind::CondTemporary, cond.span, None); + // Wrap in a construct equivalent to `{ let _t = $cond; _t }` + // to preserve drop semantics since `if cond { ... }` does not + // let temporaries live outside of `cond`. + let cond = self.expr_drop_temps(span_block, cond, ThinVec::new()); + let pat = self.pat_bool(span, true); + (pat, cond, hir::MatchSource::IfDesugar { contains_else_clause }) + } + }; let then_expr = self.lower_block_expr(then); let then_arm = self.arm(then_pat, self.arena.alloc(then_expr)); - let desugar = hir::MatchSource::IfLetDesugar { contains_else_clause }; hir::ExprKind::Match(scrutinee, arena_vec![self; then_arm, else_arm], desugar) } diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 69257ce1c19e9..eef6d38aa0584 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -134,7 +134,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let old_len = self.in_scope_lifetimes.len(); let parent_generics = match self.items.get(&parent_hir_id).unwrap().kind { - hir::ItemKind::Impl(hir::Impl { ref generics, .. }) + hir::ItemKind::Impl { ref generics, .. } | hir::ItemKind::Trait(_, _, ref generics, ..) => &generics.params[..], _ => &[], }; @@ -310,24 +310,19 @@ impl<'hir> LoweringContext<'_, 'hir> { ); let sig = hir::FnSig { decl, - header: this.lower_fn_header(header, fn_sig_span, id), + header: this.lower_fn_header(header), span: fn_sig_span, }; hir::ItemKind::Fn(sig, generics, body_id) }) } ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)), - ItemKind::ForeignMod(ref fm) => { - if fm.abi.is_none() { - self.maybe_lint_missing_abi(span, id, abi::Abi::C); - } - hir::ItemKind::ForeignMod { - abi: fm.abi.map_or(abi::Abi::C, |abi| self.lower_abi(abi)), - items: self - .arena - .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))), - } - } + ItemKind::ForeignMod(ref fm) => hir::ItemKind::ForeignMod { + abi: fm.abi.map_or(abi::Abi::C, |abi| self.lower_abi(abi)), + items: self + .arena + .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))), + }, ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)), ItemKind::TyAlias(_, ref gen, _, Some(ref ty)) => { // We lower @@ -436,7 +431,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // to not cause an assertion failure inside the `lower_defaultness` function. let has_val = true; let (defaultness, defaultness_span) = self.lower_defaultness(defaultness, has_val); - hir::ItemKind::Impl(hir::Impl { + hir::ItemKind::Impl { unsafety: self.lower_unsafety(unsafety), polarity, defaultness, @@ -446,7 +441,7 @@ impl<'hir> LoweringContext<'_, 'hir> { of_trait: trait_ref, self_ty: lowered_ty, items: new_impl_items, - }) + } } ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => { let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed()); @@ -806,13 +801,13 @@ impl<'hir> LoweringContext<'_, 'hir> { AssocItemKind::Fn(_, ref sig, ref generics, None) => { let names = self.lower_fn_params_to_names(&sig.decl); let (generics, sig) = - self.lower_method_sig(generics, sig, trait_item_def_id, false, None, i.id); + self.lower_method_sig(generics, sig, trait_item_def_id, false, None); (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names))) } AssocItemKind::Fn(_, ref sig, ref generics, Some(ref body)) => { let body_id = self.lower_fn_body_block(i.span, &sig.decl, Some(body)); let (generics, sig) = - self.lower_method_sig(generics, sig, trait_item_def_id, false, None, i.id); + self.lower_method_sig(generics, sig, trait_item_def_id, false, None); (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id))) } AssocItemKind::TyAlias(_, ref generics, ref bounds, ref default) => { @@ -882,7 +877,6 @@ impl<'hir> LoweringContext<'_, 'hir> { impl_item_def_id, impl_trait_return_allow, asyncness.opt_return_id(), - i.id, ); (generics, hir::ImplItemKind::Fn(sig, body_id)) @@ -1276,9 +1270,8 @@ impl<'hir> LoweringContext<'_, 'hir> { fn_def_id: LocalDefId, impl_trait_return_allow: bool, is_async: Option, - id: NodeId, ) -> (hir::Generics<'hir>, hir::FnSig<'hir>) { - let header = self.lower_fn_header(sig.header, sig.span, id); + let header = self.lower_fn_header(sig.header); let (generics, decl) = self.add_in_band_defs( generics, fn_def_id, @@ -1295,12 +1288,12 @@ impl<'hir> LoweringContext<'_, 'hir> { (generics, hir::FnSig { header, decl, span: sig.span }) } - fn lower_fn_header(&mut self, h: FnHeader, span: Span, id: NodeId) -> hir::FnHeader { + fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader { hir::FnHeader { unsafety: self.lower_unsafety(h.unsafety), asyncness: self.lower_asyncness(h.asyncness), constness: self.lower_constness(h.constness), - abi: self.lower_extern(h.ext, span, id), + abi: self.lower_extern(h.ext), } } @@ -1311,13 +1304,10 @@ impl<'hir> LoweringContext<'_, 'hir> { }) } - pub(super) fn lower_extern(&mut self, ext: Extern, span: Span, id: NodeId) -> abi::Abi { + pub(super) fn lower_extern(&mut self, ext: Extern) -> abi::Abi { match ext { Extern::None => abi::Abi::Rust, - Extern::Implicit => { - self.maybe_lint_missing_abi(span, id, abi::Abi::C); - abi::Abi::C - } + Extern::Implicit => abi::Abi::C, Extern::Explicit(abi) => self.lower_abi(abi), } } diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 6d95da02151a8..89557c29dd166 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -53,15 +53,13 @@ use rustc_hir::definitions::{DefKey, DefPathData, Definitions}; use rustc_hir::intravisit; use rustc_hir::{ConstArg, GenericArg, ParamName}; use rustc_index::vec::{Idx, IndexVec}; -use rustc_session::lint::builtin::{BARE_TRAIT_OBJECTS, MISSING_ABI}; -use rustc_session::lint::{BuiltinLintDiagnostics, LintBuffer}; +use rustc_session::lint::{builtin::BARE_TRAIT_OBJECTS, BuiltinLintDiagnostics, LintBuffer}; use rustc_session::parse::ParseSess; use rustc_session::Session; use rustc_span::hygiene::ExpnId; use rustc_span::source_map::{respan, DesugaringKind}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::Span; -use rustc_target::spec::abi::Abi; use smallvec::{smallvec, SmallVec}; use std::collections::BTreeMap; @@ -1290,7 +1288,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(&f.generic_params, |this| { this.with_anonymous_lifetime_mode(AnonymousLifetimeMode::PassThrough, |this| { - let span = this.sess.source_map().next_point(t.span.shrink_to_lo()); hir::TyKind::BareFn(this.arena.alloc(hir::BareFnTy { generic_params: this.lower_generic_params( &f.generic_params, @@ -1298,7 +1295,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ImplTraitContext::disallowed(), ), unsafety: this.lower_unsafety(f.unsafety), - abi: this.lower_extern(f.ext, span, t.id), + abi: this.lower_extern(f.ext), decl: this.lower_fn_decl(&f.decl, None, false, None), param_names: this.lower_fn_params_to_names(&f.decl), })) @@ -2780,26 +2777,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ) } } - - fn maybe_lint_missing_abi(&mut self, span: Span, id: NodeId, default: Abi) { - // FIXME(davidtwco): This is a hack to detect macros which produce spans of the - // call site which do not have a macro backtrace. See #61963. - let is_macro_callsite = self - .sess - .source_map() - .span_to_snippet(span) - .map(|snippet| snippet.starts_with("#[")) - .unwrap_or(true); - if !is_macro_callsite { - self.resolver.lint_buffer().buffer_lint_with_diagnostic( - MISSING_ABI, - id, - span, - "extern declarations without an explicit ABI are deprecated", - BuiltinLintDiagnostics::MissingAbi(span, default), - ) - } - } } fn body_ids(bodies: &BTreeMap>) -> Vec { diff --git a/compiler/rustc_ast_lowering/src/path.rs b/compiler/rustc_ast_lowering/src/path.rs index 9079e26eb509e..6afed355dc338 100644 --- a/compiler/rustc_ast_lowering/src/path.rs +++ b/compiler/rustc_ast_lowering/src/path.rs @@ -273,7 +273,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { if !generic_args.parenthesized && !has_lifetimes { generic_args.args = self .elided_path_lifetimes( - first_generic_span.map_or(segment.ident.span, |s| s.shrink_to_lo()), + first_generic_span.map(|s| s.shrink_to_lo()).unwrap_or(segment.ident.span), expected_lifetimes, ) .map(GenericArg::Lifetime) @@ -401,15 +401,15 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // compatibility, even in contexts like an impl header where // we generally don't permit such things (see #51008). self.with_anonymous_lifetime_mode(AnonymousLifetimeMode::PassThrough, |this| { - let ParenthesizedArgs { span, inputs, inputs_span, output } = data; + let &ParenthesizedArgs { ref inputs, ref output, span } = data; let inputs = this.arena.alloc_from_iter( inputs.iter().map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed())), ); let output_ty = match output { FnRetTy::Ty(ty) => this.lower_ty(&ty, ImplTraitContext::disallowed()), - FnRetTy::Default(_) => this.arena.alloc(this.ty_tup(*span, &[])), + FnRetTy::Default(_) => this.arena.alloc(this.ty_tup(span, &[])), }; - let args = smallvec![GenericArg::Type(this.ty_tup(*inputs_span, inputs))]; + let args = smallvec![GenericArg::Type(this.ty_tup(span, inputs))]; let binding = this.output_ty_binding(output_ty.span, output_ty); ( GenericArgsCtor { args, bindings: arena_vec![this; binding], parenthesized: true }, diff --git a/compiler/rustc_ast_passes/src/feature_gate.rs b/compiler/rustc_ast_passes/src/feature_gate.rs index 7bd805f91c857..d65bc820f8fb1 100644 --- a/compiler/rustc_ast_passes/src/feature_gate.rs +++ b/compiler/rustc_ast_passes/src/feature_gate.rs @@ -370,7 +370,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { gate_feature_post!( &self, negative_impls, - span.to(of_trait.as_ref().map_or(span, |t| t.path.span)), + span.to(of_trait.as_ref().map(|t| t.path.span).unwrap_or(span)), "negative trait bounds are not yet fully implemented; \ use marker types for now" ); diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs index 8946ac43bc65a..be5b247bb9f0b 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs @@ -824,7 +824,7 @@ pub(crate) fn codegen_intrinsic_call<'tcx>( } ty => unreachable!("bswap {}", ty), } - } + }; let res = CValue::by_val(swap(&mut fx.bcx, arg), fx.layout_of(T)); ret.write_cvalue(fx, res); }; diff --git a/compiler/rustc_codegen_llvm/src/attributes.rs b/compiler/rustc_codegen_llvm/src/attributes.rs index 700f32e15b952..97c38e04bc182 100644 --- a/compiler/rustc_codegen_llvm/src/attributes.rs +++ b/compiler/rustc_codegen_llvm/src/attributes.rs @@ -127,18 +127,13 @@ fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) { return; } + // Flag our internal `__rust_probestack` function as the stack probe symbol. + // This is defined in the `compiler-builtins` crate for each architecture. llvm::AddFunctionAttrStringValue( llfn, llvm::AttributePlace::Function, const_cstr!("probe-stack"), - if llvm_util::get_version() < (11, 0, 1) { - // Flag our internal `__rust_probestack` function as the stack probe symbol. - // This is defined in the `compiler-builtins` crate for each architecture. - const_cstr!("__rust_probestack") - } else { - // On LLVM 11+, emit inline asm for stack probes instead of a function call. - const_cstr!("inline-asm") - }, + const_cstr!("__rust_probestack"), ); } diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index e225730dce061..68f319ade1e79 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -1002,7 +1002,8 @@ pub unsafe fn with_llvm_pmb( // reasonable defaults and prepare it to actually populate the pass // manager. let builder = llvm::LLVMPassManagerBuilderCreate(); - let opt_size = config.opt_size.map_or(llvm::CodeGenOptSizeNone, |x| to_llvm_opt_settings(x).1); + let opt_size = + config.opt_size.map(|x| to_llvm_opt_settings(x).1).unwrap_or(llvm::CodeGenOptSizeNone); let inline_threshold = config.inline_threshold; let pgo_gen_path = get_pgo_gen_path(config); let pgo_use_path = get_pgo_use_path(config); diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index 6acd26bd415dc..8dd40308075ed 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -114,7 +114,7 @@ pub unsafe fn create_module( let llmod = llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx); let mut target_data_layout = sess.target.data_layout.clone(); - if llvm_util::get_version() < (10, 0, 0) + if llvm_util::get_major_version() < 10 && (sess.target.arch == "x86" || sess.target.arch == "x86_64") { target_data_layout = strip_x86_address_spaces(target_data_layout); diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index b9ae796325023..36a21b38c035d 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -1832,9 +1832,8 @@ impl<'tcx> VariantInfo<'_, 'tcx> { fn source_info(&self, cx: &CodegenCx<'ll, 'tcx>) -> Option> { match self { VariantInfo::Generator { def_id, variant_index, .. } => { - let span = cx.tcx.generator_layout(*def_id).unwrap().variant_source_info - [*variant_index] - .span; + let span = + cx.tcx.generator_layout(*def_id).variant_source_info[*variant_index].span; if !span.is_dummy() { let loc = cx.lookup_debug_loc(span.lo()); return Some(SourceInfo { diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs index 955e739b2c126..ccbe7325cc6c2 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs @@ -552,6 +552,7 @@ impl DebugInfoMethods<'tcx> for CodegenCx<'ll, 'tcx> { unsafe { llvm::LLVMRustDIBuilderCreateDebugLocation( + utils::debug_context(self).llcontext, line.unwrap_or(UNKNOWN_LINE_NUMBER), col.unwrap_or(UNKNOWN_COLUMN_NUMBER), scope, diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs index d9f42efebab47..e359d9f8c9c77 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -1811,7 +1811,6 @@ extern "C" { pub fn LLVMRustDebugMetadataVersion() -> u32; pub fn LLVMRustVersionMajor() -> u32; pub fn LLVMRustVersionMinor() -> u32; - pub fn LLVMRustVersionPatch() -> u32; pub fn LLVMRustAddModuleFlag(M: &Module, name: *const c_char, value: u32); @@ -2103,6 +2102,7 @@ extern "C" { ); pub fn LLVMRustDIBuilderCreateDebugLocation( + Context: &'a Context, Line: c_uint, Column: c_uint, Scope: &'a DIScope, diff --git a/compiler/rustc_codegen_llvm/src/llvm_util.rs b/compiler/rustc_codegen_llvm/src/llvm_util.rs index 544ef38c12c6d..a9d57ea8b8aa4 100644 --- a/compiler/rustc_codegen_llvm/src/llvm_util.rs +++ b/compiler/rustc_codegen_llvm/src/llvm_util.rs @@ -171,17 +171,16 @@ pub fn target_features(sess: &Session) -> Vec { } pub fn print_version() { - let (major, minor, patch) = get_version(); - println!("LLVM version: {}.{}.{}", major, minor, patch); -} - -pub fn get_version() -> (u32, u32, u32) { // Can be called without initializing LLVM unsafe { - (llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor(), llvm::LLVMRustVersionPatch()) + println!("LLVM version: {}.{}", llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor()); } } +pub fn get_major_version() -> u32 { + unsafe { llvm::LLVMRustVersionMajor() } +} + pub fn print_passes() { // Can be called without initializing LLVM unsafe { @@ -214,7 +213,11 @@ fn handle_native(name: &str) -> &str { } pub fn target_cpu(sess: &Session) -> &str { - let name = sess.opts.cg.target_cpu.as_ref().unwrap_or(&sess.target.cpu); + let name = match sess.opts.cg.target_cpu { + Some(ref s) => &**s, + None => &*sess.target.cpu, + }; + handle_native(name) } @@ -250,6 +253,8 @@ pub fn handle_native_features(sess: &Session) -> Vec { } pub fn tune_cpu(sess: &Session) -> Option<&str> { - let name = sess.opts.debugging_opts.tune_cpu.as_ref()?; - Some(handle_native(name)) + match sess.opts.debugging_opts.tune_cpu { + Some(ref s) => Some(handle_native(&**s)), + None => None, + } } diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index e51904f308dd4..728795cf50b85 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -74,7 +74,7 @@ pub fn link_binary<'a, B: ArchiveBuilder<'a>>( } }); - if outputs.outputs.should_link() { + if outputs.outputs.should_codegen() { let tmpdir = TempFileBuilder::new() .prefix("rustc") .tempdir() @@ -123,7 +123,9 @@ pub fn link_binary<'a, B: ArchiveBuilder<'a>>( } }; - if sess.opts.output_types.should_link() && !preserve_objects_for_their_debuginfo(sess) { + if sess.opts.output_types.should_codegen() + && !preserve_objects_for_their_debuginfo(sess) + { for module in &codegen_results.modules { remove_temps_from_module(module); } @@ -164,7 +166,7 @@ fn get_linker( _ => match flavor { LinkerFlavor::Lld(f) => Command::lld(linker, f), LinkerFlavor::Msvc if sess.opts.cg.linker.is_none() && sess.target.linker.is_none() => { - Command::new(msvc_tool.as_ref().map_or(linker, |t| t.path())) + Command::new(msvc_tool.as_ref().map(|t| t.path()).unwrap_or(linker)) } _ => Command::new(linker), }, diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index 2ce5fe5ad504b..f47d2ada61a14 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -29,6 +29,7 @@ use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; use rustc_session::cgu_reuse_tracker::CguReuse; use rustc_session::config::{self, EntryFnType}; +use rustc_session::utils::NativeLibKind; use rustc_session::Session; use rustc_target::abi::{Align, LayoutOf, VariantIdx}; @@ -816,6 +817,32 @@ pub fn provide_both(providers: &mut Providers) { } tcx.sess.opts.optimize }; + + providers.dllimport_foreign_items = |tcx, krate| { + let module_map = tcx.foreign_modules(krate); + + let dllimports = tcx + .native_libraries(krate) + .iter() + .filter(|lib| { + if !matches!(lib.kind, NativeLibKind::Dylib | NativeLibKind::Unspecified) { + return false; + } + let cfg = match lib.cfg { + Some(ref cfg) => cfg, + None => return true, + }; + attr::cfg_matches(cfg, &tcx.sess.parse_sess, None) + }) + .filter_map(|lib| lib.foreign_module) + .map(|id| &module_map[&id]) + .flat_map(|module| module.foreign_items.iter().cloned()) + .collect(); + dllimports + }; + + providers.is_dllimport_foreign_item = + |tcx, def_id| tcx.dllimport_foreign_items(def_id.krate).contains(&def_id); } fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse { diff --git a/compiler/rustc_data_structures/src/profiling.rs b/compiler/rustc_data_structures/src/profiling.rs index b16d5a9e2b421..5d13b7f27c704 100644 --- a/compiler/rustc_data_structures/src/profiling.rs +++ b/compiler/rustc_data_structures/src/profiling.rs @@ -166,7 +166,7 @@ impl SelfProfilerRef { // If there is no SelfProfiler then the filter mask is set to NONE, // ensuring that nothing ever tries to actually access it. let event_filter_mask = - profiler.as_ref().map_or(EventFilter::empty(), |p| p.event_filter_mask); + profiler.as_ref().map(|p| p.event_filter_mask).unwrap_or(EventFilter::empty()); SelfProfilerRef { profiler, diff --git a/compiler/rustc_data_structures/src/steal.rs b/compiler/rustc_data_structures/src/steal.rs index 7f9e4160fcdde..e532a84cea3f2 100644 --- a/compiler/rustc_data_structures/src/steal.rs +++ b/compiler/rustc_data_structures/src/steal.rs @@ -30,7 +30,6 @@ impl Steal { Steal { value: RwLock::new(Some(value)) } } - #[track_caller] pub fn borrow(&self) -> MappedReadGuard<'_, T> { ReadGuard::map(self.value.borrow(), |opt| match *opt { None => panic!("attempted to read from stolen value"), @@ -38,11 +37,10 @@ impl Steal { }) } - #[track_caller] pub fn steal(&self) -> T { let value_ref = &mut *self.value.try_write().expect("stealing value which is locked"); let value = value_ref.take(); - value.expect("attempt to steal from stolen value") + value.expect("attempt to read from stolen value") } } diff --git a/compiler/rustc_driver/src/lib.rs b/compiler/rustc_driver/src/lib.rs index 15b984acac590..509f81e16536b 100644 --- a/compiler/rustc_driver/src/lib.rs +++ b/compiler/rustc_driver/src/lib.rs @@ -798,7 +798,7 @@ pub fn version(binary: &str, matches: &getopts::Matches) { println!("commit-date: {}", unw(util::commit_date_str())); println!("host: {}", config::host_triple()); println!("release: {}", unw(util::release_str())); - if cfg!(feature = "llvm") { + if cfg!(llvm) { get_builtin_codegen_backend("llvm")().print_version(); } } @@ -1087,7 +1087,7 @@ pub fn handle_options(args: &[String]) -> Option { } if cg_flags.iter().any(|x| *x == "passes=list") { - if cfg!(feature = "llvm") { + if cfg!(llvm) { get_builtin_codegen_backend("llvm")().print_passes(); } return None; @@ -1236,7 +1236,7 @@ pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) { } // If backtraces are enabled, also print the query stack - let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0"); + let backtrace = env::var_os("RUST_BACKTRACE").map(|x| &x != "0").unwrap_or(false); let num_frames = if backtrace { None } else { Some(2) }; diff --git a/compiler/rustc_driver/src/pretty.rs b/compiler/rustc_driver/src/pretty.rs index b7edc24bc4a1a..305fa838afad2 100644 --- a/compiler/rustc_driver/src/pretty.rs +++ b/compiler/rustc_driver/src/pretty.rs @@ -363,15 +363,8 @@ impl<'tcx> pprust_hir::PpAnn for TypedAnnotation<'tcx> { fn get_source(input: &Input, sess: &Session) -> (String, FileName) { let src_name = input.source_name(); - let src = String::clone( - &sess - .source_map() - .get_source_file(&src_name) - .expect("get_source_file") - .src - .as_ref() - .expect("src"), - ); + let src = + String::clone(&sess.source_map().get_source_file(&src_name).unwrap().src.as_ref().unwrap()); (src, src_name) } diff --git a/compiler/rustc_error_codes/src/error_codes/E0044.md b/compiler/rustc_error_codes/src/error_codes/E0044.md index ed7daf8ddd9c7..635ff95329013 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0044.md +++ b/compiler/rustc_error_codes/src/error_codes/E0044.md @@ -3,13 +3,13 @@ You cannot use type or const parameters on foreign items. Example of erroneous code: ```compile_fail,E0044 -extern "C" { fn some_func(x: T); } +extern { fn some_func(x: T); } ``` To fix this, replace the generic parameter with the specializations that you need: ``` -extern "C" { fn some_func_i32(x: i32); } -extern "C" { fn some_func_i64(x: i64); } +extern { fn some_func_i32(x: i32); } +extern { fn some_func_i64(x: i64); } ``` diff --git a/compiler/rustc_error_codes/src/error_codes/E0130.md b/compiler/rustc_error_codes/src/error_codes/E0130.md index 2cd27b5ec0523..a270feaf58c17 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0130.md +++ b/compiler/rustc_error_codes/src/error_codes/E0130.md @@ -3,7 +3,7 @@ A pattern was declared as an argument in a foreign function declaration. Erroneous code example: ```compile_fail,E0130 -extern "C" { +extern { fn foo((a, b): (u32, u32)); // error: patterns aren't allowed in foreign // function declarations } @@ -17,7 +17,7 @@ struct SomeStruct { b: u32, } -extern "C" { +extern { fn foo(s: SomeStruct); // ok! } ``` @@ -25,7 +25,7 @@ extern "C" { Or: ``` -extern "C" { +extern { fn foo(a: (u32, u32)); // ok! } ``` diff --git a/compiler/rustc_error_codes/src/error_codes/E0373.md b/compiler/rustc_error_codes/src/error_codes/E0373.md index effa597aad918..fd96987793115 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0373.md +++ b/compiler/rustc_error_codes/src/error_codes/E0373.md @@ -50,24 +50,3 @@ fn foo() -> Box u32> { Now that the closure has its own copy of the data, there's no need to worry about safety. - -This error may also be encountered while using `async` blocks: - -```compile_fail,E0373,edition2018 -use std::future::Future; - -async fn f() { - let v = vec![1, 2, 3i32]; - spawn(async { //~ ERROR E0373 - println!("{:?}", v) - }); -} - -fn spawn(future: F) { - unimplemented!() -} -``` - -Similarly to closures, `async` blocks are not executed immediately and may -capture closed-over data by reference. For more information, see -https://rust-lang.github.io/async-book/03_async_await/01_chapter.html. diff --git a/compiler/rustc_error_codes/src/error_codes/E0454.md b/compiler/rustc_error_codes/src/error_codes/E0454.md index 95a22b92e36ee..23ca6c7824df1 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0454.md +++ b/compiler/rustc_error_codes/src/error_codes/E0454.md @@ -3,7 +3,7 @@ A link name was given with an empty name. Erroneous code example: ```compile_fail,E0454 -#[link(name = "")] extern "C" {} +#[link(name = "")] extern {} // error: `#[link(name = "")]` given with empty name ``` @@ -11,5 +11,5 @@ The rust compiler cannot link to an external library if you don't give it its name. Example: ```no_run -#[link(name = "some_lib")] extern "C" {} // ok! +#[link(name = "some_lib")] extern {} // ok! ``` diff --git a/compiler/rustc_error_codes/src/error_codes/E0455.md b/compiler/rustc_error_codes/src/error_codes/E0455.md index 84689b3ece610..2f80c34b88971 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0455.md +++ b/compiler/rustc_error_codes/src/error_codes/E0455.md @@ -4,7 +4,7 @@ as frameworks are specific to that operating system. Erroneous code example: ```ignore (should-compile_fail-but-cannot-doctest-conditionally-without-macos) -#[link(name = "FooCoreServices", kind = "framework")] extern "C" {} +#[link(name = "FooCoreServices", kind = "framework")] extern {} // OS used to compile is Linux for example ``` @@ -12,7 +12,7 @@ To solve this error you can use conditional compilation: ``` #[cfg_attr(target="macos", link(name = "FooCoreServices", kind = "framework"))] -extern "C" {} +extern {} ``` Learn more in the [Conditional Compilation][conditional-compilation] section diff --git a/compiler/rustc_error_codes/src/error_codes/E0458.md b/compiler/rustc_error_codes/src/error_codes/E0458.md index 359aeb6fd9a0a..075226ac98b9d 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0458.md +++ b/compiler/rustc_error_codes/src/error_codes/E0458.md @@ -3,7 +3,7 @@ An unknown "kind" was specified for a link attribute. Erroneous code example: ```compile_fail,E0458 -#[link(kind = "wonderful_unicorn")] extern "C" {} +#[link(kind = "wonderful_unicorn")] extern {} // error: unknown kind: `wonderful_unicorn` ``` diff --git a/compiler/rustc_error_codes/src/error_codes/E0459.md b/compiler/rustc_error_codes/src/error_codes/E0459.md index 4a49a76544520..6f75f2a99a563 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0459.md +++ b/compiler/rustc_error_codes/src/error_codes/E0459.md @@ -3,7 +3,7 @@ A link was used without a name parameter. Erroneous code example: ```compile_fail,E0459 -#[link(kind = "dylib")] extern "C" {} +#[link(kind = "dylib")] extern {} // error: `#[link(...)]` specified without `name = "foo"` ``` @@ -11,5 +11,5 @@ Please add the name parameter to allow the rust compiler to find the library you want. Example: ```no_run -#[link(kind = "dylib", name = "some_lib")] extern "C" {} // ok! +#[link(kind = "dylib", name = "some_lib")] extern {} // ok! ``` diff --git a/compiler/rustc_error_codes/src/error_codes/E0617.md b/compiler/rustc_error_codes/src/error_codes/E0617.md index 1c5d1f87b912b..61b56766c26e2 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0617.md +++ b/compiler/rustc_error_codes/src/error_codes/E0617.md @@ -3,7 +3,7 @@ Attempted to pass an invalid type of variable into a variadic function. Erroneous code example: ```compile_fail,E0617 -extern "C" { +extern { fn printf(c: *const i8, ...); } @@ -21,7 +21,7 @@ to import from `std::os::raw`). In this case, `c_double` has the same size as `f64` so we can use it directly: ```no_run -# extern "C" { +# extern { # fn printf(c: *const i8, ...); # } unsafe { diff --git a/compiler/rustc_error_codes/src/error_codes/E0633.md b/compiler/rustc_error_codes/src/error_codes/E0633.md index 4d1f0c47829c9..7f488cde664d9 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0633.md +++ b/compiler/rustc_error_codes/src/error_codes/E0633.md @@ -6,7 +6,7 @@ Erroneous code example: #![feature(unwind_attributes)] #[unwind()] // error: expected one argument -pub extern "C" fn something() {} +pub extern fn something() {} fn main() {} ``` diff --git a/compiler/rustc_error_codes/src/error_codes/E0724.md b/compiler/rustc_error_codes/src/error_codes/E0724.md index 70578acbe0d5f..e8f84d0fc7d50 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0724.md +++ b/compiler/rustc_error_codes/src/error_codes/E0724.md @@ -18,7 +18,7 @@ the function inside of an `extern` block. ``` #![feature(ffi_returns_twice)] -extern "C" { +extern { #[ffi_returns_twice] // ok! pub fn foo(); } diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index e184e929b0745..593e0d92031ff 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -804,7 +804,7 @@ impl HandlerInner { } fn treat_err_as_bug(&self) -> bool { - self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() >= c) + self.flags.treat_err_as_bug.map(|c| self.err_count() >= c).unwrap_or(false) } fn print_error_count(&mut self, registry: &Registry) { @@ -913,7 +913,7 @@ impl HandlerInner { // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before // incrementing `err_count` by one, so we need to +1 the comparing. // FIXME: Would be nice to increment err_count in a more coherent way. - if self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() + 1 >= c) { + if self.flags.treat_err_as_bug.map(|c| self.err_count() + 1 >= c).unwrap_or(false) { // FIXME: don't abort here if report_delayed_bugs is off self.span_bug(sp, msg); } diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index b07bce94870c1..1193f66651ce9 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -423,7 +423,7 @@ impl<'a> StripUnconfigured<'a> { /// If attributes are not allowed on expressions, emit an error for `attr` pub fn maybe_emit_expr_attr_err(&self, attr: &Attribute) { - if !self.features.map_or(true, |features| features.stmt_expr_attributes) { + if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) { let mut err = feature_err( &self.sess.parse_sess, sym::stmt_expr_attributes, diff --git a/compiler/rustc_expand/src/mbe/macro_parser.rs b/compiler/rustc_expand/src/mbe/macro_parser.rs index 1aed42a24e2b3..e76cc6f1fed7b 100644 --- a/compiler/rustc_expand/src/mbe/macro_parser.rs +++ b/compiler/rustc_expand/src/mbe/macro_parser.rs @@ -500,7 +500,7 @@ fn inner_parse_loop<'root, 'tt>( if idx == len && item.sep.is_some() { // We have a separator, and it is the current token. We can advance past the // separator token. - if item.sep.as_ref().map_or(false, |sep| token_name_eq(token, sep)) { + if item.sep.as_ref().map(|sep| token_name_eq(token, sep)).unwrap_or(false) { item.idx += 1; next_items.push(item); } diff --git a/compiler/rustc_expand/src/mbe/macro_rules.rs b/compiler/rustc_expand/src/mbe/macro_rules.rs index e8c711cae64ef..3d126749d541d 100644 --- a/compiler/rustc_expand/src/mbe/macro_rules.rs +++ b/compiler/rustc_expand/src/mbe/macro_rules.rs @@ -56,11 +56,36 @@ crate fn annotate_err_with_kind( }; } +/// Instead of e.g. `vec![a, b, c]` in a pattern context, suggest `[a, b, c]`. +fn suggest_slice_pat(e: &mut DiagnosticBuilder<'_>, site_span: Span, parser: &Parser<'_>) { + let mut suggestion = None; + if let Ok(code) = parser.sess.source_map().span_to_snippet(site_span) { + if let Some(bang) = code.find('!') { + suggestion = Some(code[bang + 1..].to_string()); + } + } + if let Some(suggestion) = suggestion { + e.span_suggestion( + site_span, + "use a slice pattern here instead", + suggestion, + Applicability::MachineApplicable, + ); + } else { + e.span_label(site_span, "use a slice pattern here instead"); + } + e.help( + "for more information, see https://doc.rust-lang.org/edition-guide/\ + rust-2018/slice-patterns.html", + ); +} + fn emit_frag_parse_err( mut e: DiagnosticBuilder<'_>, parser: &Parser<'_>, orig_parser: &mut Parser<'_>, site_span: Span, + macro_ident: Ident, arm_span: Span, kind: AstFragmentKind, ) { @@ -88,6 +113,9 @@ fn emit_frag_parse_err( e.span_label(site_span, "in this macro invocation"); } match kind { + AstFragmentKind::Pat if macro_ident.name == sym::vec => { + suggest_slice_pat(&mut e, site_span, parser); + } // Try a statement if an expression is wanted but failed and suggest adding `;` to call. AstFragmentKind::Expr => match parse_ast_fragment(orig_parser, AstFragmentKind::Stmts) { Err(mut err) => err.cancel(), @@ -115,7 +143,7 @@ impl<'a> ParserAnyMacro<'a> { let fragment = match parse_ast_fragment(parser, kind) { Ok(f) => f, Err(err) => { - emit_frag_parse_err(err, parser, snapshot, site_span, arm_span, kind); + emit_frag_parse_err(err, parser, snapshot, site_span, macro_ident, arm_span, kind); return kind.dummy(site_span); } }; @@ -175,7 +203,7 @@ fn macro_rules_dummy_expander<'cx>( } fn trace_macros_note(cx_expansions: &mut FxHashMap>, sp: Span, message: String) { - let sp = sp.macro_backtrace().last().map_or(sp, |trace| trace.call_site); + let sp = sp.macro_backtrace().last().map(|trace| trace.call_site).unwrap_or(sp); cx_expansions.entry(sp).or_default().push(message); } diff --git a/compiler/rustc_expand/src/mbe/quoted.rs b/compiler/rustc_expand/src/mbe/quoted.rs index c8049495d223c..a4b44931fc1ae 100644 --- a/compiler/rustc_expand/src/mbe/quoted.rs +++ b/compiler/rustc_expand/src/mbe/quoted.rs @@ -99,10 +99,10 @@ pub(super) fn parse( } _ => token.span, }, - tree => tree.as_ref().map_or(span, tokenstream::TokenTree::span), + tree => tree.as_ref().map(tokenstream::TokenTree::span).unwrap_or(span), } } - tree => tree.as_ref().map_or(start_sp, tokenstream::TokenTree::span), + tree => tree.as_ref().map(tokenstream::TokenTree::span).unwrap_or(start_sp), }; if node_id != DUMMY_NODE_ID { // Macros loaded from other crates have dummy node ids. @@ -250,7 +250,7 @@ fn parse_kleene_op( Some(op) => Ok(Ok((op, token.span))), None => Ok(Err(token)), }, - tree => Err(tree.as_ref().map_or(span, tokenstream::TokenTree::span)), + tree => Err(tree.as_ref().map(tokenstream::TokenTree::span).unwrap_or(span)), } } diff --git a/compiler/rustc_feature/src/active.rs b/compiler/rustc_feature/src/active.rs index b9d1597c4c65f..3b54ffbc3f08d 100644 --- a/compiler/rustc_feature/src/active.rs +++ b/compiler/rustc_feature/src/active.rs @@ -629,8 +629,6 @@ declare_features! ( /// Allows references to types with interior mutability within constants (active, const_refs_to_cell, "1.51.0", Some(80384), None), - /// Allows using `pointer` and `reference` in intra-doc links - (active, intra_doc_pointers, "1.51.0", Some(80896), None), // ------------------------------------------------------------------------- // feature-group-end: actual feature gates // ------------------------------------------------------------------------- diff --git a/compiler/rustc_hir/src/def.rs b/compiler/rustc_hir/src/def.rs index a81eb747a335a..4ede9d67b741f 100644 --- a/compiler/rustc_hir/src/def.rs +++ b/compiler/rustc_hir/src/def.rs @@ -5,7 +5,6 @@ use rustc_ast as ast; use rustc_ast::NodeId; use rustc_macros::HashStable_Generic; use rustc_span::hygiene::MacroKind; -use rustc_span::Symbol; use std::array::IntoIter; use std::fmt::Debug; @@ -35,7 +34,7 @@ pub enum CtorKind { #[derive(HashStable_Generic)] pub enum NonMacroAttrKind { /// Single-segment attribute defined by the language (`#[inline]`) - Builtin(Symbol), + Builtin, /// Multi-segment custom attribute living in a "tool module" (`#[rustfmt::skip]`). Tool, /// Single-segment custom attribute registered by a derive macro (`#[serde(default)]`). @@ -372,7 +371,7 @@ impl CtorKind { impl NonMacroAttrKind { pub fn descr(self) -> &'static str { match self { - NonMacroAttrKind::Builtin(..) => "built-in attribute", + NonMacroAttrKind::Builtin => "built-in attribute", NonMacroAttrKind::Tool => "tool attribute", NonMacroAttrKind::DeriveHelper | NonMacroAttrKind::DeriveHelperCompat => { "derive helper attribute" @@ -394,7 +393,7 @@ impl NonMacroAttrKind { NonMacroAttrKind::Tool | NonMacroAttrKind::DeriveHelper | NonMacroAttrKind::DeriveHelperCompat => true, - NonMacroAttrKind::Builtin(..) | NonMacroAttrKind::Registered => false, + NonMacroAttrKind::Builtin | NonMacroAttrKind::Registered => false, } } } diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 3673e5c8bf3a5..acd254ae85cb1 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -11,9 +11,9 @@ pub use rustc_ast::{CaptureBy, Movability, Mutability}; use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; use rustc_data_structures::sync::{par_for_each_in, Send, Sync}; use rustc_macros::HashStable_Generic; -use rustc_span::source_map::{SourceMap, Spanned}; +use rustc_span::def_id::LocalDefId; +use rustc_span::source_map::Spanned; use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::{def_id::LocalDefId, BytePos}; use rustc_span::{MultiSpan, Span, DUMMY_SP}; use rustc_target::asm::InlineAsmRegOrRegClass; use rustc_target::spec::abi::Abi; @@ -231,11 +231,7 @@ impl<'hir> PathSegment<'hir> { PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None } } - pub fn invalid() -> Self { - Self::from_ident(Ident::invalid()) - } - - pub fn args(&self) -> &GenericArgs<'hir> { + pub fn generic_args(&self) -> &GenericArgs<'hir> { if let Some(ref args) = self.args { args } else { @@ -279,10 +275,6 @@ impl GenericArg<'_> { matches!(self, GenericArg::Const(_)) } - pub fn is_synthetic(&self) -> bool { - matches!(self, GenericArg::Lifetime(lifetime) if lifetime.name.ident() == Ident::invalid()) - } - pub fn descr(&self) -> &'static str { match self { GenericArg::Lifetime(_) => "lifetime", @@ -291,6 +283,14 @@ impl GenericArg<'_> { } } + pub fn short_descr(&self) -> &'static str { + match self { + GenericArg::Lifetime(_) => "lifetime", + GenericArg::Type(_) => "type", + GenericArg::Const(_) => "const", + } + } + pub fn to_ord(&self, feats: &rustc_feature::Features) -> ast::ParamKindOrd { match self { GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime, @@ -352,39 +352,6 @@ impl GenericArgs<'_> { own_counts } - - pub fn span(&self) -> Option { - self.args - .iter() - .filter(|arg| !arg.is_synthetic()) - .map(|arg| arg.span()) - .fold_first(|span1, span2| span1.to(span2)) - } - - /// Returns span encompassing arguments and their surrounding `<>` or `()` - pub fn span_ext(&self, sm: &SourceMap) -> Option { - let mut span = self.span()?; - - let (o, c) = if self.parenthesized { ('(', ')') } else { ('<', '>') }; - - if let Ok(snippet) = sm.span_to_snippet(span) { - let snippet = snippet.as_bytes(); - - if snippet[0] != (o as u8) || snippet[snippet.len() - 1] != (c as u8) { - span = sm.span_extend_to_prev_char(span, o, true); - span = span.with_lo(span.lo() - BytePos(1)); - - span = sm.span_extend_to_next_char(span, c, true); - span = span.with_hi(span.hi() + BytePos(1)); - } - } - - Some(span) - } - - pub fn is_empty(&self) -> bool { - self.args.is_empty() - } } /// A modifier on a bound, currently this is only used for `?Sized`, where the @@ -561,7 +528,7 @@ impl WhereClause<'_> { /// in `fn foo(t: T) where T: Foo,` so we don't suggest two trailing commas. pub fn tail_span_for_suggestion(&self) -> Span { let end = self.span_for_predicates_or_empty_place().shrink_to_hi(); - self.predicates.last().map_or(end, |p| p.span()).shrink_to_hi().to(end) + self.predicates.last().map(|p| p.span()).unwrap_or(end).shrink_to_hi().to(end) } } @@ -1431,7 +1398,6 @@ impl Expr<'_> { ExprKind::Lit(_) => ExprPrecedence::Lit, ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast, ExprKind::DropTemps(ref expr, ..) => expr.precedence(), - ExprKind::If(..) => ExprPrecedence::If, ExprKind::Loop(..) => ExprPrecedence::Loop, ExprKind::Match(..) => ExprPrecedence::Match, ExprKind::Closure(..) => ExprPrecedence::Closure, @@ -1493,7 +1459,6 @@ impl Expr<'_> { | ExprKind::MethodCall(..) | ExprKind::Struct(..) | ExprKind::Tup(..) - | ExprKind::If(..) | ExprKind::Match(..) | ExprKind::Closure(..) | ExprKind::Block(..) @@ -1610,10 +1575,6 @@ pub enum ExprKind<'hir> { /// This construct only exists to tweak the drop order in HIR lowering. /// An example of that is the desugaring of `for` loops. DropTemps(&'hir Expr<'hir>), - /// An `if` block, with an optional else block. - /// - /// I.e., `if { } else { }`. - If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>), /// A conditionless loop (can be exited with `break`, `continue`, or `return`). /// /// I.e., `'label: loop { }`. @@ -1767,6 +1728,8 @@ pub enum LocalSource { pub enum MatchSource { /// A `match _ { .. }`. Normal, + /// An `if _ { .. }` (optionally with `else { .. }`). + IfDesugar { contains_else_clause: bool }, /// An `if let _ = _ { .. }` (optionally with `else { .. }`). IfLetDesugar { contains_else_clause: bool }, /// An `if let _ = _ => { .. }` match guard. @@ -1789,7 +1752,7 @@ impl MatchSource { use MatchSource::*; match self { Normal => "match", - IfLetDesugar { .. } | IfLetGuardDesugar => "if", + IfDesugar { .. } | IfLetDesugar { .. } | IfLetGuardDesugar => "if", WhileDesugar | WhileLetDesugar => "while", ForLoopDesugar => "for", TryDesugar => "?", @@ -2599,25 +2562,22 @@ pub enum ItemKind<'hir> { TraitAlias(Generics<'hir>, GenericBounds<'hir>), /// An implementation, e.g., `impl Trait for Foo { .. }`. - Impl(Impl<'hir>), -} - -#[derive(Debug, HashStable_Generic)] -pub struct Impl<'hir> { - pub unsafety: Unsafety, - pub polarity: ImplPolarity, - pub defaultness: Defaultness, - // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata - // decoding as `Span`s cannot be decoded when a `Session` is not available. - pub defaultness_span: Option, - pub constness: Constness, - pub generics: Generics<'hir>, - - /// The trait being implemented, if any. - pub of_trait: Option>, - - pub self_ty: &'hir Ty<'hir>, - pub items: &'hir [ImplItemRef<'hir>], + Impl { + unsafety: Unsafety, + polarity: ImplPolarity, + defaultness: Defaultness, + // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata + // decoding as `Span`s cannot be decoded when a `Session` is not available. + defaultness_span: Option, + constness: Constness, + generics: Generics<'hir>, + + /// The trait being implemented, if any. + of_trait: Option>, + + self_ty: &'hir Ty<'hir>, + items: &'hir [ImplItemRef<'hir>], + }, } impl ItemKind<'_> { @@ -2630,7 +2590,7 @@ impl ItemKind<'_> { | ItemKind::Struct(_, ref generics) | ItemKind::Union(_, ref generics) | ItemKind::Trait(_, _, ref generics, _, _) - | ItemKind::Impl(Impl { ref generics, .. }) => generics, + | ItemKind::Impl { ref generics, .. } => generics, _ => return None, }) } diff --git a/compiler/rustc_hir/src/intravisit.rs b/compiler/rustc_hir/src/intravisit.rs index 8707a84a98fcc..b0e82214cf95f 100644 --- a/compiler/rustc_hir/src/intravisit.rs +++ b/compiler/rustc_hir/src/intravisit.rs @@ -611,7 +611,7 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item<'v>) { // `visit_enum_def()` takes care of visiting the `Item`'s `HirId`. visitor.visit_enum_def(enum_definition, generics, item.hir_id, item.span) } - ItemKind::Impl(Impl { + ItemKind::Impl { unsafety: _, defaultness: _, polarity: _, @@ -621,7 +621,7 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item<'v>) { ref of_trait, ref self_ty, items, - }) => { + } => { visitor.visit_id(item.hir_id); visitor.visit_generics(generics); walk_list!(visitor, visit_trait_ref, of_trait); @@ -1146,11 +1146,6 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr<'v>) ExprKind::DropTemps(ref subexpression) => { visitor.visit_expr(subexpression); } - ExprKind::If(ref cond, ref then, ref else_opt) => { - visitor.visit_expr(cond); - visitor.visit_expr(then); - walk_list!(visitor, visit_expr, else_opt); - } ExprKind::Loop(ref block, ref opt_label, _) => { walk_list!(visitor, visit_label, opt_label); visitor.visit_block(block); diff --git a/compiler/rustc_hir/src/lang_items.rs b/compiler/rustc_hir/src/lang_items.rs index e82ea310b8cc5..3e4eb9eafd7f9 100644 --- a/compiler/rustc_hir/src/lang_items.rs +++ b/compiler/rustc_hir/src/lang_items.rs @@ -157,7 +157,7 @@ where } language_item_table! { -// Variant name, Name, Method name, Target; +// Variant name, Name, Method name, Target; Bool, sym::bool, bool_impl, Target::Impl; Char, sym::char, char_impl, Target::Impl; Str, sym::str, str_impl, Target::Impl; diff --git a/compiler/rustc_hir/src/lib.rs b/compiler/rustc_hir/src/lib.rs index 8b55ec6c70591..9d931b3a9e1e5 100644 --- a/compiler/rustc_hir/src/lib.rs +++ b/compiler/rustc_hir/src/lib.rs @@ -7,7 +7,6 @@ #![feature(const_fn)] // For the unsizing cast on `&[]` #![feature(const_panic)] #![feature(in_band_lifetimes)] -#![feature(iterator_fold_self)] #![feature(once_cell)] #![feature(or_patterns)] #![recursion_limit = "256"] diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index a3ab1d96e1dfe..a9aa192bbcc3b 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -684,7 +684,7 @@ impl<'a> State<'a> { self.head(visibility_qualified(&item.vis, "union")); self.print_struct(struct_def, generics, item.ident.name, item.span, true); } - hir::ItemKind::Impl(hir::Impl { + hir::ItemKind::Impl { unsafety, polarity, defaultness, @@ -694,7 +694,7 @@ impl<'a> State<'a> { ref of_trait, ref self_ty, items, - }) => { + } => { self.head(""); self.print_visibility(&item.vis); self.print_defaultness(defaultness); @@ -1080,50 +1080,6 @@ impl<'a> State<'a> { self.ann.post(self, AnnNode::Block(blk)) } - fn print_else(&mut self, els: Option<&hir::Expr<'_>>) { - match els { - Some(_else) => { - match _else.kind { - // "another else-if" - hir::ExprKind::If(ref i, ref then, ref e) => { - self.cbox(INDENT_UNIT - 1); - self.ibox(0); - self.s.word(" else if "); - self.print_expr_as_cond(&i); - self.s.space(); - self.print_expr(&then); - self.print_else(e.as_ref().map(|e| &**e)) - } - // "final else" - hir::ExprKind::Block(ref b, _) => { - self.cbox(INDENT_UNIT - 1); - self.ibox(0); - self.s.word(" else "); - self.print_block(&b) - } - // BLEAH, constraints would be great here - _ => { - panic!("print_if saw if with weird alternative"); - } - } - } - _ => {} - } - } - - pub fn print_if( - &mut self, - test: &hir::Expr<'_>, - blk: &hir::Expr<'_>, - elseopt: Option<&hir::Expr<'_>>, - ) { - self.head("if"); - self.print_expr_as_cond(test); - self.s.space(); - self.print_expr(blk); - self.print_else(elseopt) - } - pub fn print_anon_const(&mut self, constant: &hir::AnonConst) { self.ann.nested(self, Nested::Body(constant.body)) } @@ -1257,7 +1213,7 @@ impl<'a> State<'a> { self.s.word("."); self.print_ident(segment.ident); - let generic_args = segment.args(); + let generic_args = segment.generic_args(); if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() { self.print_generic_args(generic_args, segment.infer_args, true); } @@ -1393,9 +1349,6 @@ impl<'a> State<'a> { // Print `}`: self.bclose_maybe_open(expr.span, true); } - hir::ExprKind::If(ref test, ref blk, ref elseopt) => { - self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e)); - } hir::ExprKind::Loop(ref blk, opt_label, _) => { if let Some(label) = opt_label { self.print_ident(label.ident); @@ -1708,7 +1661,11 @@ impl<'a> State<'a> { } if segment.ident.name != kw::PathRoot { self.print_ident(segment.ident); - self.print_generic_args(segment.args(), segment.infer_args, colons_before_params); + self.print_generic_args( + segment.generic_args(), + segment.infer_args, + colons_before_params, + ); } } } @@ -1716,7 +1673,7 @@ impl<'a> State<'a> { pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) { if segment.ident.name != kw::PathRoot { self.print_ident(segment.ident); - self.print_generic_args(segment.args(), segment.infer_args, false); + self.print_generic_args(segment.generic_args(), segment.infer_args, false); } } @@ -1736,7 +1693,7 @@ impl<'a> State<'a> { if segment.ident.name != kw::PathRoot { self.print_ident(segment.ident); self.print_generic_args( - segment.args(), + segment.generic_args(), segment.infer_args, colons_before_params, ); @@ -1748,7 +1705,7 @@ impl<'a> State<'a> { let item_segment = path.segments.last().unwrap(); self.print_ident(item_segment.ident); self.print_generic_args( - item_segment.args(), + item_segment.generic_args(), item_segment.infer_args, colons_before_params, ) @@ -1768,7 +1725,7 @@ impl<'a> State<'a> { self.s.word("::"); self.print_ident(item_segment.ident); self.print_generic_args( - item_segment.args(), + item_segment.generic_args(), item_segment.infer_args, colons_before_params, ) @@ -2476,13 +2433,7 @@ impl<'a> State<'a> { // // Duplicated from `parse::classify`, but adapted for the HIR. fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool { - !matches!( - e.kind, - hir::ExprKind::If(..) - | hir::ExprKind::Match(..) - | hir::ExprKind::Block(..) - | hir::ExprKind::Loop(..) - ) + !matches!(e.kind, hir::ExprKind::Match(..) | hir::ExprKind::Block(..) | hir::ExprKind::Loop(..)) } /// This statement requires a semicolon after it. diff --git a/compiler/rustc_incremental/src/lib.rs b/compiler/rustc_incremental/src/lib.rs index 95456c07b10aa..a80c4be3e9335 100644 --- a/compiler/rustc_incremental/src/lib.rs +++ b/compiler/rustc_incremental/src/lib.rs @@ -17,6 +17,7 @@ mod persist; pub use assert_dep_graph::assert_dep_graph; pub use persist::copy_cgu_workproduct_to_incr_comp_cache_dir; pub use persist::delete_workproduct_files; +pub use persist::dep_graph_tcx_init; pub use persist::finalize_session_directory; pub use persist::garbage_collect_session_directories; pub use persist::in_incr_comp_dir; diff --git a/compiler/rustc_incremental/src/persist/load.rs b/compiler/rustc_incremental/src/persist/load.rs index 0add0c5aa268e..35428dc8d84e5 100644 --- a/compiler/rustc_incremental/src/persist/load.rs +++ b/compiler/rustc_incremental/src/persist/load.rs @@ -4,6 +4,7 @@ use rustc_data_structures::fx::FxHashMap; use rustc_hir::definitions::Definitions; use rustc_middle::dep_graph::{PreviousDepGraph, SerializedDepGraph, WorkProduct, WorkProductId}; use rustc_middle::ty::query::OnDiskCache; +use rustc_middle::ty::TyCtxt; use rustc_serialize::opaque::Decoder; use rustc_serialize::Decodable as RustcDecodable; use rustc_session::Session; @@ -14,6 +15,14 @@ use super::file_format; use super::fs::*; use super::work_product; +pub fn dep_graph_tcx_init(tcx: TyCtxt<'_>) { + if !tcx.dep_graph.is_fully_enabled() { + return; + } + + tcx.allocate_metadata_dep_nodes(); +} + type WorkProductMap = FxHashMap; pub enum LoadResult { diff --git a/compiler/rustc_incremental/src/persist/mod.rs b/compiler/rustc_incremental/src/persist/mod.rs index 8821b34b50212..7bc3b47e15adf 100644 --- a/compiler/rustc_incremental/src/persist/mod.rs +++ b/compiler/rustc_incremental/src/persist/mod.rs @@ -15,6 +15,7 @@ pub use fs::garbage_collect_session_directories; pub use fs::in_incr_comp_dir; pub use fs::in_incr_comp_dir_sess; pub use fs::prepare_session_directory; +pub use load::dep_graph_tcx_init; pub use load::load_query_result_cache; pub use load::LoadResult; pub use load::{load_dep_graph, DepGraphFuture}; diff --git a/compiler/rustc_incremental/src/persist/save.rs b/compiler/rustc_incremental/src/persist/save.rs index 45d474b89b8df..f63cdfc56945e 100644 --- a/compiler/rustc_incremental/src/persist/save.rs +++ b/compiler/rustc_incremental/src/persist/save.rs @@ -1,6 +1,6 @@ use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sync::join; -use rustc_middle::dep_graph::{DepGraph, WorkProduct, WorkProductId}; +use rustc_middle::dep_graph::{DepGraph, DepKind, WorkProduct, WorkProductId}; use rustc_middle::ty::TyCtxt; use rustc_serialize::opaque::{FileEncodeResult, FileEncoder}; use rustc_serialize::Encodable as RustcEncodable; @@ -148,15 +148,83 @@ fn encode_dep_graph(tcx: TyCtxt<'_>, encoder: &mut FileEncoder) -> FileEncodeRes // First encode the commandline arguments hash tcx.sess.opts.dep_tracking_hash().encode(encoder)?; + // Encode the graph data. + let serialized_graph = + tcx.sess.time("incr_comp_serialize_dep_graph", || tcx.dep_graph.serialize()); + if tcx.sess.opts.debugging_opts.incremental_info { - tcx.dep_graph.print_incremental_info(); - } + #[derive(Clone)] + struct Stat { + kind: DepKind, + node_counter: u64, + edge_counter: u64, + } + + let total_node_count = serialized_graph.nodes.len(); + let total_edge_count = serialized_graph.edge_list_data.len(); + + let mut counts: FxHashMap<_, Stat> = + FxHashMap::with_capacity_and_hasher(total_node_count, Default::default()); + + for (i, &node) in serialized_graph.nodes.iter_enumerated() { + let stat = counts.entry(node.kind).or_insert(Stat { + kind: node.kind, + node_counter: 0, + edge_counter: 0, + }); + + stat.node_counter += 1; + let (edge_start, edge_end) = serialized_graph.edge_list_indices[i]; + stat.edge_counter += (edge_end - edge_start) as u64; + } - // There is a tiny window between printing the incremental info above and encoding the dep - // graph below in which the dep graph could change, thus making the printed incremental info - // slightly out of date. If this matters to you, please feel free to submit a patch. :) + let mut counts: Vec<_> = counts.values().cloned().collect(); + counts.sort_by_key(|s| -(s.node_counter as i64)); + + println!("[incremental]"); + println!("[incremental] DepGraph Statistics"); + + const SEPARATOR: &str = "[incremental] --------------------------------\ + ----------------------------------------------\ + ------------"; + + println!("{}", SEPARATOR); + println!("[incremental]"); + println!("[incremental] Total Node Count: {}", total_node_count); + println!("[incremental] Total Edge Count: {}", total_edge_count); + if let Some((total_edge_reads, total_duplicate_edge_reads)) = + tcx.dep_graph.edge_deduplication_data() + { + println!("[incremental] Total Edge Reads: {}", total_edge_reads); + println!("[incremental] Total Duplicate Edge Reads: {}", total_duplicate_edge_reads); + } + println!("[incremental]"); + println!( + "[incremental] {:<36}| {:<17}| {:<12}| {:<17}|", + "Node Kind", "Node Frequency", "Node Count", "Avg. Edge Count" + ); + println!( + "[incremental] -------------------------------------\ + |------------------\ + |-------------\ + |------------------|" + ); + + for stat in counts.iter() { + println!( + "[incremental] {:<36}|{:>16.1}% |{:>12} |{:>17.1} |", + format!("{:?}", stat.kind), + (100.0 * (stat.node_counter as f64)) / (total_node_count as f64), // percentage of all nodes + stat.node_counter, + (stat.edge_counter as f64) / (stat.node_counter as f64), // average edges per kind + ); + } + + println!("{}", SEPARATOR); + println!("[incremental]"); + } - tcx.sess.time("incr_comp_encode_serialized_dep_graph", || tcx.dep_graph.encode(encoder)) + tcx.sess.time("incr_comp_encode_serialized_dep_graph", || serialized_graph.encode(encoder)) } fn encode_work_product_index( diff --git a/compiler/rustc_infer/src/infer/canonical/query_response.rs b/compiler/rustc_infer/src/infer/canonical/query_response.rs index 4357eb34add23..71ce50f745372 100644 --- a/compiler/rustc_infer/src/infer/canonical/query_response.rs +++ b/compiler/rustc_infer/src/infer/canonical/query_response.rs @@ -530,10 +530,10 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> { let atom = match k1.unpack() { GenericArgKind::Lifetime(r1) => { - ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(r1, r2)) + ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate(r1, r2)) } GenericArgKind::Type(t1) => { - ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(t1, r2)) + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(t1, r2)) } GenericArgKind::Const(..) => { // Consts cannot outlive one another, so we don't expect to @@ -541,7 +541,8 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> { span_bug!(cause.span, "unexpected const outlives {:?}", constraint); } }; - let predicate = predicate.rebind(atom).to_predicate(self.tcx); + let predicate = + predicate.rebind(atom).potentially_quantified(self.tcx, ty::PredicateKind::ForAll); Obligation::new(cause.clone(), param_env, predicate) }) @@ -663,7 +664,7 @@ impl<'tcx> TypeRelatingDelegate<'tcx> for QueryTypeRelatingDelegate<'_, 'tcx> { self.obligations.push(Obligation { cause: self.cause.clone(), param_env: self.param_env, - predicate: ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(sup, sub)) + predicate: ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate(sup, sub)) .to_predicate(self.infcx.tcx), recursion_depth: 0, }); diff --git a/compiler/rustc_infer/src/infer/combine.rs b/compiler/rustc_infer/src/infer/combine.rs index b344086e95e77..e38eebe23b1e1 100644 --- a/compiler/rustc_infer/src/infer/combine.rs +++ b/compiler/rustc_infer/src/infer/combine.rs @@ -358,7 +358,7 @@ impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> { self.obligations.push(Obligation::new( self.trace.cause.clone(), self.param_env, - ty::PredicateKind::WellFormed(b_ty.into()).to_predicate(self.infcx.tcx), + ty::PredicateAtom::WellFormed(b_ty.into()).to_predicate(self.infcx.tcx), )); } @@ -451,9 +451,9 @@ impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> { b: &'tcx ty::Const<'tcx>, ) { let predicate = if a_is_expected { - ty::PredicateKind::ConstEquate(a, b) + ty::PredicateAtom::ConstEquate(a, b) } else { - ty::PredicateKind::ConstEquate(b, a) + ty::PredicateAtom::ConstEquate(b, a) }; self.obligations.push(Obligation::new( self.trace.cause.clone(), diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index c39daea0811e0..7b0a91986b3a3 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -98,7 +98,7 @@ pub(super) fn note_and_explain_region( // uh oh, hope no user ever sees THIS ty::ReEmpty(ui) => (format!("the empty lifetime in universe {:?}", ui), None), - ty::RePlaceholder(_) => return, + ty::RePlaceholder(_) => ("any other region".to_string(), None), // FIXME(#13998) RePlaceholder should probably print like // ReFree rather than dumping Debug output on the user. @@ -1675,16 +1675,6 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { self.check_and_note_conflicting_crates(diag, terr); self.tcx.note_and_explain_type_err(diag, terr, cause, span, body_owner_def_id.to_def_id()); - if let Some(ValuePairs::PolyTraitRefs(exp_found)) = values { - if let ty::Closure(def_id, _) = exp_found.expected.skip_binder().self_ty().kind() { - if let Some(def_id) = def_id.as_local() { - let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id); - let span = self.tcx.hir().span(hir_id); - diag.span_note(span, "this closure does not fulfill the lifetime requirements"); - } - } - } - // It reads better to have the error origin as the final // thing. self.note_error_origin(diag, cause, exp_found); @@ -1706,8 +1696,8 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { for (predicate, _) in bounds { let predicate = predicate.subst(self.tcx, substs); - if let ty::PredicateKind::Projection(projection_predicate) = - predicate.kind().skip_binder() + if let ty::PredicateAtom::Projection(projection_predicate) = + predicate.skip_binders() { if projection_predicate.projection_ty.item_def_id == item_def_id { // We don't account for multiple `Future::Output = Ty` contraints. @@ -2118,7 +2108,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { let consider = format!( "{} {}...", msg, - if type_param_span.map_or(false, |(_, _, is_impl_trait)| is_impl_trait) { + if type_param_span.map(|(_, _, is_impl_trait)| is_impl_trait).unwrap_or(false) { format!(" `{}` to `{}`", sub, bound_kind) } else { format!("`{}: {}`", bound_kind, sub) diff --git a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs index bd43d3c01e218..aaab89ace0ad9 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs @@ -429,7 +429,6 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { body_id: Option, span: Span, arg: GenericArg<'tcx>, - impl_candidates: Vec>, error_code: TypeAnnotationNeeded, ) -> DiagnosticBuilder<'tcx> { let arg = self.resolve_vars_if_possible(arg); @@ -654,44 +653,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { }; err.span_label(pattern.span, msg); } else if let Some(e) = local_visitor.found_method_call { - if let ExprKind::MethodCall(segment, _, exprs, _) = &e.kind { - // Suggest impl candidates: - // - // error[E0283]: type annotations needed - // --> $DIR/E0283.rs:35:24 - // | - // LL | let bar = foo_impl.into() * 1u32; - // | ---------^^^^-- - // | | | - // | | cannot infer type for type parameter `T` declared on the trait `Into` - // | this method call resolves to `T` - // | help: specify type like: `>::into(foo_impl)` - // | - // = note: cannot satisfy `Impl: Into<_>` - if !impl_candidates.is_empty() && e.span.contains(span) { - if let Some(expr) = exprs.first() { - if let ExprKind::Path(hir::QPath::Resolved(_, path)) = expr.kind { - if let [path_segment] = &path.segments[..] { - let candidate_len = impl_candidates.len(); - let suggestions = impl_candidates.iter().map(|candidate| { - format!( - "{}::{}({})", - candidate, segment.ident, path_segment.ident - ) - }); - err.span_suggestions( - e.span, - &format!( - "use the fully qualified path for the potential candidate{}", - pluralize!(candidate_len), - ), - suggestions, - Applicability::MaybeIncorrect, - ); - } - } - }; - } + if let ExprKind::MethodCall(segment, ..) = &e.kind { // Suggest specifying type params or point out the return type of the call: // // error[E0282]: type annotations needed diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs index c6ae71ba33019..5264854d8ebc8 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs @@ -345,10 +345,9 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { match tcx.hir().get_if_local(def_id) { Some(Node::ImplItem(ImplItem { ident, hir_id, .. })) => { match tcx.hir().find(tcx.hir().get_parent_item(*hir_id)) { - Some(Node::Item(Item { - kind: ItemKind::Impl(hir::Impl { self_ty, .. }), - .. - })) => Some((*ident, self_ty)), + Some(Node::Item(Item { kind: ItemKind::Impl { self_ty, .. }, .. })) => { + Some((*ident, self_ty)) + } _ => None, } } @@ -368,7 +367,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { let impl_did = tcx.hir().local_def_id(*impl_node); match tcx.hir().get_if_local(impl_did.to_def_id()) { Some(Node::Item(Item { - kind: ItemKind::Impl(hir::Impl { self_ty, .. }), + kind: ItemKind::Impl { self_ty, .. }, .. })) if trait_objects.iter().all(|did| { // FIXME: we should check `self_ty` against the receiver diff --git a/compiler/rustc_infer/src/infer/error_reporting/note.rs b/compiler/rustc_infer/src/infer/error_reporting/note.rs index c88869abc29e4..7fb94332cad5c 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/note.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/note.rs @@ -1,7 +1,6 @@ use crate::infer::error_reporting::{note_and_explain_region, ObligationCauseExt}; use crate::infer::{self, InferCtxt, SubregionOrigin}; use rustc_errors::{struct_span_err, DiagnosticBuilder}; -use rustc_middle::traits::ObligationCauseCode; use rustc_middle::ty::error::TypeError; use rustc_middle::ty::{self, Region}; @@ -108,37 +107,14 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { infer::Subtype(box trace) => { let terr = TypeError::RegionsDoesNotOutlive(sup, sub); let mut err = self.report_and_explain_type_error(trace, &terr); - match (sub, sup) { - (ty::RePlaceholder(_), ty::RePlaceholder(_)) => {} - (ty::RePlaceholder(_), _) => { - note_and_explain_region( - self.tcx, - &mut err, - "", - sup, - " doesn't meet the lifetime requirements", - ); - } - (_, ty::RePlaceholder(_)) => { - note_and_explain_region( - self.tcx, - &mut err, - "the required lifetime does not necessarily outlive ", - sub, - "", - ); - } - _ => { - note_and_explain_region(self.tcx, &mut err, "", sup, "..."); - note_and_explain_region( - self.tcx, - &mut err, - "...does not necessarily outlive ", - sub, - "", - ); - } - } + note_and_explain_region(self.tcx, &mut err, "", sup, "..."); + note_and_explain_region( + self.tcx, + &mut err, + "...does not necessarily outlive ", + sub, + "", + ); err } infer::Reborrow(span) => { @@ -310,31 +286,13 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { sup: Region<'tcx>, ) -> DiagnosticBuilder<'tcx> { // I can't think how to do better than this right now. -nikomatsakis - debug!(?placeholder_origin, ?sub, ?sup, "report_placeholder_failure"); match placeholder_origin { - infer::Subtype(box ref trace) - if matches!( - &trace.cause.code.peel_derives(), - ObligationCauseCode::BindingObligation(..) - ) => - { - // Hack to get around the borrow checker because trace.cause has an `Rc`. - if let ObligationCauseCode::BindingObligation(_, span) = - &trace.cause.code.peel_derives() - { - let span = *span; - let mut err = self.report_concrete_failure(placeholder_origin, sub, sup); - err.span_note(span, "the lifetime requirement is introduced here"); - err - } else { - unreachable!() - } - } infer::Subtype(box trace) => { let terr = TypeError::RegionsPlaceholderMismatch; - return self.report_and_explain_type_error(trace, &terr); + self.report_and_explain_type_error(trace, &terr) } - _ => return self.report_concrete_failure(placeholder_origin, sub, sup), + + _ => self.report_concrete_failure(placeholder_origin, sub, sup), } } } diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index 27545c126857b..56d9634213ae5 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -1533,7 +1533,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { // Note: if these two lines are combined into one we get // dynamic borrow errors on `self.inner`. let known = self.inner.borrow_mut().type_variables().probe(v).known(); - known.map_or(typ, |t| self.shallow_resolve_ty(t)) + known.map(|t| self.shallow_resolve_ty(t)).unwrap_or(typ) } ty::Infer(ty::IntVar(v)) => self diff --git a/compiler/rustc_infer/src/infer/outlives/mod.rs b/compiler/rustc_infer/src/infer/outlives/mod.rs index 07c75d50d91da..de98cccf25689 100644 --- a/compiler/rustc_infer/src/infer/outlives/mod.rs +++ b/compiler/rustc_infer/src/infer/outlives/mod.rs @@ -6,6 +6,7 @@ pub mod verify; use rustc_middle::traits::query::OutlivesBound; use rustc_middle::ty; +use rustc_middle::ty::fold::TypeFoldable; pub fn explicit_outlives_bounds<'tcx>( param_env: ty::ParamEnv<'tcx>, @@ -14,20 +15,20 @@ pub fn explicit_outlives_bounds<'tcx>( param_env .caller_bounds() .into_iter() - .map(ty::Predicate::kind) - .filter_map(ty::Binder::no_bound_vars) - .filter_map(move |kind| match kind { - ty::PredicateKind::Projection(..) - | ty::PredicateKind::Trait(..) - | ty::PredicateKind::Subtype(..) - | ty::PredicateKind::WellFormed(..) - | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::TypeOutlives(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) - | ty::PredicateKind::TypeWellFormedFromEnv(..) => None, - ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(r_a, r_b)) => { + .map(ty::Predicate::skip_binders) + .filter(|atom| !atom.has_escaping_bound_vars()) + .filter_map(move |atom| match atom { + ty::PredicateAtom::Projection(..) + | ty::PredicateAtom::Trait(..) + | ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::WellFormed(..) + | ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::TypeOutlives(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) + | ty::PredicateAtom::TypeWellFormedFromEnv(..) => None, + ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate(r_a, r_b)) => { Some(OutlivesBound::RegionSubRegion(r_b, r_a)) } }) diff --git a/compiler/rustc_infer/src/infer/sub.rs b/compiler/rustc_infer/src/infer/sub.rs index 668719851583c..a676c5e65a73b 100644 --- a/compiler/rustc_infer/src/infer/sub.rs +++ b/compiler/rustc_infer/src/infer/sub.rs @@ -100,7 +100,7 @@ impl TypeRelation<'tcx> for Sub<'combine, 'infcx, 'tcx> { self.fields.obligations.push(Obligation::new( self.fields.trace.cause.clone(), self.fields.param_env, - ty::PredicateKind::Subtype(ty::SubtypePredicate { + ty::PredicateAtom::Subtype(ty::SubtypePredicate { a_is_expected: self.a_is_expected, a, b, diff --git a/compiler/rustc_infer/src/traits/util.rs b/compiler/rustc_infer/src/traits/util.rs index 13cf1e1083f7f..8273c2d291d09 100644 --- a/compiler/rustc_infer/src/traits/util.rs +++ b/compiler/rustc_infer/src/traits/util.rs @@ -9,8 +9,13 @@ pub fn anonymize_predicate<'tcx>( tcx: TyCtxt<'tcx>, pred: ty::Predicate<'tcx>, ) -> ty::Predicate<'tcx> { - let new = tcx.anonymize_late_bound_regions(pred.kind()); - tcx.reuse_or_mk_predicate(pred, new) + match *pred.kind() { + ty::PredicateKind::ForAll(binder) => { + let new = ty::PredicateKind::ForAll(tcx.anonymize_late_bound_regions(binder)); + tcx.reuse_or_mk_predicate(pred, new) + } + ty::PredicateKind::Atom(_) => pred, + } } struct PredicateSet<'tcx> { @@ -121,9 +126,9 @@ impl Elaborator<'tcx> { fn elaborate(&mut self, obligation: &PredicateObligation<'tcx>) { let tcx = self.visited.tcx; - let bound_predicate = obligation.predicate.kind(); + let bound_predicate = obligation.predicate.bound_atom(); match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(data, _) => { + ty::PredicateAtom::Trait(data, _) => { // Get predicates declared on the trait. let predicates = tcx.super_predicates_of(data.def_id()); @@ -145,36 +150,36 @@ impl Elaborator<'tcx> { self.stack.extend(obligations); } - ty::PredicateKind::WellFormed(..) => { + ty::PredicateAtom::WellFormed(..) => { // Currently, we do not elaborate WF predicates, // although we easily could. } - ty::PredicateKind::ObjectSafe(..) => { + ty::PredicateAtom::ObjectSafe(..) => { // Currently, we do not elaborate object-safe // predicates. } - ty::PredicateKind::Subtype(..) => { + ty::PredicateAtom::Subtype(..) => { // Currently, we do not "elaborate" predicates like `X <: Y`, // though conceivably we might. } - ty::PredicateKind::Projection(..) => { + ty::PredicateAtom::Projection(..) => { // Nothing to elaborate in a projection predicate. } - ty::PredicateKind::ClosureKind(..) => { + ty::PredicateAtom::ClosureKind(..) => { // Nothing to elaborate when waiting for a closure's kind to be inferred. } - ty::PredicateKind::ConstEvaluatable(..) => { + ty::PredicateAtom::ConstEvaluatable(..) => { // Currently, we do not elaborate const-evaluatable // predicates. } - ty::PredicateKind::ConstEquate(..) => { + ty::PredicateAtom::ConstEquate(..) => { // Currently, we do not elaborate const-equate // predicates. } - ty::PredicateKind::RegionOutlives(..) => { + ty::PredicateAtom::RegionOutlives(..) => { // Nothing to elaborate from `'a: 'b`. } - ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty_max, r_min)) => { + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty_max, r_min)) => { // We know that `T: 'a` for some type `T`. We can // often elaborate this. For example, if we know that // `[U]: 'a`, that implies that `U: 'a`. Similarly, if @@ -204,7 +209,7 @@ impl Elaborator<'tcx> { if r.is_late_bound() { None } else { - Some(ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate( + Some(ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate( r, r_min, ))) } @@ -212,7 +217,7 @@ impl Elaborator<'tcx> { Component::Param(p) => { let ty = tcx.mk_ty_param(p.index, p.name); - Some(ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate( + Some(ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate( ty, r_min, ))) } @@ -237,7 +242,7 @@ impl Elaborator<'tcx> { }), ); } - ty::PredicateKind::TypeWellFormedFromEnv(..) => { + ty::PredicateAtom::TypeWellFormedFromEnv(..) => { // Nothing to elaborate } } diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index ead2512d3b2a5..b67704119bccc 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -797,6 +797,12 @@ pub fn create_global_ctxt<'tcx>( }) }); + // Do some initialization of the DepGraph that can only be done with the tcx available. + let icx = ty::tls::ImplicitCtxt::new(&gcx); + ty::tls::enter_context(&icx, |_| { + icx.tcx.sess.time("dep_graph_tcx_init", || rustc_incremental::dep_graph_tcx_init(icx.tcx)); + }); + QueryContext(gcx) } diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 8cdb33ea3175f..20e476b38ccac 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -542,7 +542,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { return; } } - hir::ItemKind::Impl(hir::Impl { of_trait: Some(ref trait_ref), items, .. }) => { + hir::ItemKind::Impl { of_trait: Some(ref trait_ref), items, .. } => { // If the trait is private, add the impl items to `private_traits` so they don't get // reported for missing docs. let real_trait = trait_ref.path.res.def_id(); @@ -1550,13 +1550,13 @@ declare_lint_pass!( impl<'tcx> LateLintPass<'tcx> for TrivialConstraints { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) { use rustc_middle::ty::fold::TypeFoldable; - use rustc_middle::ty::PredicateKind::*; + use rustc_middle::ty::PredicateAtom::*; if cx.tcx.features().trivial_bounds { let def_id = cx.tcx.hir().local_def_id(item.hir_id); let predicates = cx.tcx.predicates_of(def_id); for &(predicate, span) in predicates.predicates { - let predicate_kind_name = match predicate.kind().skip_binder() { + let predicate_kind_name = match predicate.skip_binders() { Trait(..) => "Trait", TypeOutlives(..) | RegionOutlives(..) => "Lifetime", @@ -1936,8 +1936,8 @@ impl ExplicitOutlivesRequirements { ) -> Vec> { inferred_outlives .iter() - .filter_map(|(pred, _)| match pred.kind().skip_binder() { - ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => match a { + .filter_map(|(pred, _)| match pred.skip_binders() { + ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate(a, b)) => match a { ty::ReEarlyBound(ebr) if ebr.index == index => Some(b), _ => None, }, @@ -1952,8 +1952,8 @@ impl ExplicitOutlivesRequirements { ) -> Vec> { inferred_outlives .iter() - .filter_map(|(pred, _)| match pred.kind().skip_binder() { - ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(a, b)) => { + .filter_map(|(pred, _)| match pred.skip_binders() { + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(a, b)) => { a.is_param(index).then_some(b) } _ => None, diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index 3971a3099823f..f4740be34cb08 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -354,23 +354,10 @@ impl LintStore { lint_name.to_string() }; // If the lint was scoped with `tool::` check if the tool lint exists - if let Some(tool_name) = tool_name { + if tool_name.is_some() { match self.by_name.get(&complete_name) { None => match self.lint_groups.get(&*complete_name) { - // If the lint isn't registered, there are two possibilities: - None => { - // 1. The tool is currently running, so this lint really doesn't exist. - // FIXME: should this handle tools that never register a lint, like rustfmt? - tracing::debug!("lints={:?}", self.by_name.keys().collect::>()); - let tool_prefix = format!("{}::", tool_name); - return if self.by_name.keys().any(|lint| lint.starts_with(&tool_prefix)) { - self.no_lint_suggestion(&complete_name) - } else { - // 2. The tool isn't currently running, so no lints will be registered. - // To avoid giving a false positive, ignore all unknown lints. - CheckLintNameResult::Tool(Err((None, String::new()))) - }; - } + None => return CheckLintNameResult::Tool(Err((None, String::new()))), Some(LintGroup { lint_ids, .. }) => { return CheckLintNameResult::Tool(Ok(&lint_ids)); } @@ -411,21 +398,6 @@ impl LintStore { } } - fn no_lint_suggestion(&self, lint_name: &str) -> CheckLintNameResult<'_> { - let name_lower = lint_name.to_lowercase(); - let symbols = - self.get_lints().iter().map(|l| Symbol::intern(&l.name_lower())).collect::>(); - - if lint_name.chars().any(char::is_uppercase) && self.find_lints(&name_lower).is_ok() { - // First check if the lint name is (partly) in upper case instead of lower case... - CheckLintNameResult::NoLint(Some(Symbol::intern(&name_lower))) - } else { - // ...if not, search for lints with a similar name - let suggestion = find_best_match_for_name(&symbols, Symbol::intern(&name_lower), None); - CheckLintNameResult::NoLint(suggestion) - } - } - fn check_tool_name_for_backwards_compat( &self, lint_name: &str, @@ -435,7 +407,18 @@ impl LintStore { match self.by_name.get(&complete_name) { None => match self.lint_groups.get(&*complete_name) { // Now we are sure, that this lint exists nowhere - None => self.no_lint_suggestion(lint_name), + None => { + let symbols = + self.by_name.keys().map(|name| Symbol::intern(&name)).collect::>(); + + let suggestion = find_best_match_for_name( + &symbols, + Symbol::intern(&lint_name.to_lowercase()), + None, + ); + + CheckLintNameResult::NoLint(suggestion) + } Some(LintGroup { lint_ids, depr, .. }) => { // Reaching this would be weird, but let's cover this case anyway if let Some(LintAlias { name, silent }) = depr { @@ -617,10 +600,6 @@ pub trait LintContext: Sized { BuiltinLintDiagnostics::PatternsInFnsWithoutBody(span, ident) => { db.span_suggestion(span, "remove `mut` from the parameter", ident.to_string(), Applicability::MachineApplicable); } - BuiltinLintDiagnostics::MissingAbi(span, default_abi) => { - db.span_label(span, "ABI should be specified here"); - db.help(&format!("the default ABI is {}", default_abi.name())); - } } // Rewrap `db`, and pass control to the user. decorate(LintDiagnosticBuilder::new(db)); diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index fc8f84461f991..5cece569903c7 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -10,7 +10,7 @@ use rustc_hir as hir; use rustc_hir::def_id::{CrateNum, LOCAL_CRATE}; use rustc_hir::{intravisit, HirId}; use rustc_middle::hir::map::Map; -use rustc_middle::lint::LevelAndSource; +use rustc_middle::lint::LevelSource; use rustc_middle::lint::LintDiagnosticBuilder; use rustc_middle::lint::{ struct_lint_level, LintLevelMap, LintLevelSets, LintLevelSource, LintSet, @@ -106,9 +106,9 @@ impl<'s> LintLevelsBuilder<'s> { /// diagnostic with no change to `specs`. fn insert_spec( &mut self, - specs: &mut FxHashMap, + specs: &mut FxHashMap, id: LintId, - (level, src): LevelAndSource, + (level, src): LevelSource, ) { // Setting to a non-forbid level is an error if the lint previously had // a forbid level. Note that this is not necessarily true even with a @@ -381,11 +381,6 @@ impl<'s> LintLevelsBuilder<'s> { src, Some(li.span().into()), |lint| { - let name = if let Some(tool_name) = tool_name { - format!("{}::{}", tool_name, name) - } else { - name.to_string() - }; let mut db = lint.build(&format!("unknown lint: `{}`", name)); if let Some(suggestion) = suggestion { db.span_suggestion( diff --git a/compiler/rustc_lint/src/traits.rs b/compiler/rustc_lint/src/traits.rs index b031c1108c66f..d4f79036e5a18 100644 --- a/compiler/rustc_lint/src/traits.rs +++ b/compiler/rustc_lint/src/traits.rs @@ -45,12 +45,12 @@ declare_lint_pass!( impl<'tcx> LateLintPass<'tcx> for DropTraitConstraints { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) { - use rustc_middle::ty::PredicateKind::*; + use rustc_middle::ty::PredicateAtom::*; let def_id = cx.tcx.hir().local_def_id(item.hir_id); let predicates = cx.tcx.explicit_predicates_of(def_id); for &(predicate, span) in predicates.predicates { - let trait_predicate = match predicate.kind().skip_binder() { + let trait_predicate = match predicate.skip_binders() { Trait(trait_predicate, _constness) => trait_predicate, _ => continue, }; diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 424f91b3f883e..9ad9d53cd0db3 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -647,7 +647,8 @@ pub fn transparent_newtype_field<'a, 'tcx>( let param_env = tcx.param_env(variant.def_id); for field in &variant.fields { let field_ty = tcx.type_of(field.did); - let is_zst = tcx.layout_of(param_env.and(field_ty)).map_or(false, |layout| layout.is_zst()); + let is_zst = + tcx.layout_of(param_env.and(field_ty)).map(|layout| layout.is_zst()).unwrap_or(false); if !is_zst { return Some(field); diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index c1a3eecbbc7ef..35915dc7a9753 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -202,8 +202,8 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { let mut has_emitted = false; for &(predicate, _) in cx.tcx.explicit_item_bounds(def) { // We only look at the `DefId`, so it is safe to skip the binder here. - if let ty::PredicateKind::Trait(ref poly_trait_predicate, _) = - predicate.kind().skip_binder() + if let ty::PredicateAtom::Trait(ref poly_trait_predicate, _) = + predicate.skip_binders() { let def_id = poly_trait_predicate.trait_ref.def_id; let descr_pre = @@ -529,8 +529,8 @@ trait UnusedDelimLint { pprust::expr_to_string(value) }; let keep_space = ( - left_pos.map_or(false, |s| s >= value.span.lo()), - right_pos.map_or(false, |s| s <= value.span.hi()), + left_pos.map(|s| s >= value.span.lo()).unwrap_or(false), + right_pos.map(|s| s <= value.span.hi()).unwrap_or(false), ); self.emit_unused_delims(cx, value.span, &expr_text, ctx.into(), keep_space); } diff --git a/compiler/rustc_lint_defs/Cargo.toml b/compiler/rustc_lint_defs/Cargo.toml index f909f159784cb..7f908088cf5b0 100644 --- a/compiler/rustc_lint_defs/Cargo.toml +++ b/compiler/rustc_lint_defs/Cargo.toml @@ -11,4 +11,3 @@ rustc_data_structures = { path = "../rustc_data_structures" } rustc_span = { path = "../rustc_span" } rustc_serialize = { path = "../rustc_serialize" } rustc_macros = { path = "../rustc_macros" } -rustc_target = { path = "../rustc_target" } diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index 20052ad9bfcbd..f90fc7fc9ab3c 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -4,7 +4,7 @@ //! compiler code, rather than using their own custom pass. Those //! lints are all available in `rustc_lint::builtin`. -use crate::{declare_lint, declare_lint_pass}; +use crate::{declare_lint, declare_lint_pass, declare_tool_lint}; use rustc_span::edition::Edition; use rustc_span::symbol::sym; @@ -2825,29 +2825,8 @@ declare_lint! { }; } -declare_lint! { - /// The `ineffective_unstable_trait_impl` lint detects `#[unstable]` attributes which are not used. - /// - /// ### Example - /// - /// ```compile_fail - /// #![feature(staged_api)] - /// - /// #[derive(Clone)] - /// #[stable(feature = "x", since = "1")] - /// struct S {} - /// - /// #[unstable(feature = "y", issue = "none")] - /// impl Copy for S {} - /// ``` - /// - /// {{produces}} - /// - /// ### Explanation - /// - /// `staged_api` does not currently support using a stability attribute on `impl` blocks. - /// `impl`s are always stable if both the type and trait are stable, and always unstable otherwise. - pub INEFFECTIVE_UNSTABLE_TRAIT_IMPL, +declare_tool_lint! { + pub rustc::INEFFECTIVE_UNSTABLE_TRAIT_IMPL, Deny, "detects `#[unstable]` on stable trait implementations for stable types" } @@ -2938,7 +2917,6 @@ declare_lint_pass! { FUNCTION_ITEM_REFERENCES, USELESS_DEPRECATED, UNSUPPORTED_NAKED_FUNCTIONS, - MISSING_ABI, ] } @@ -2966,28 +2944,3 @@ declare_lint! { } declare_lint_pass!(UnusedDocComment => [UNUSED_DOC_COMMENTS]); - -declare_lint! { - /// The `missing_abi` lint detects cases where the ABI is omitted from - /// extern declarations. - /// - /// ### Example - /// - /// ```rust,compile_fail - /// #![deny(missing_abi)] - /// - /// extern fn foo() {} - /// ``` - /// - /// {{produces}} - /// - /// ### Explanation - /// - /// Historically, Rust implicitly selected C as the ABI for extern - /// declarations. We expect to add new ABIs, like `C-unwind`, in the future, - /// though this has not yet happened, and especially with their addition - /// seeing the ABI easily will make code review easier. - pub MISSING_ABI, - Allow, - "No declared ABI for extern declaration" -} diff --git a/compiler/rustc_lint_defs/src/lib.rs b/compiler/rustc_lint_defs/src/lib.rs index 9d60a51a0afb3..2bfc6a8557691 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -6,7 +6,6 @@ use rustc_ast::node_id::{NodeId, NodeMap}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey}; use rustc_span::edition::Edition; use rustc_span::{sym, symbol::Ident, MultiSpan, Span, Symbol}; -use rustc_target::spec::abi::Abi; pub mod builtin; @@ -253,7 +252,6 @@ pub enum BuiltinLintDiagnostics { UnusedImports(String, Vec<(Span, String)>), RedundantImport(Vec<(Span, bool)>, Ident), DeprecatedMacro(Option, Span), - MissingAbi(Span, Abi), UnusedDocComment(Span), PatternsInFnsWithoutBody(Span, Ident), } diff --git a/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp index 1d89fc8049660..c0ff62c17beb5 100644 --- a/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp @@ -660,8 +660,6 @@ extern "C" uint32_t LLVMRustDebugMetadataVersion() { return DEBUG_METADATA_VERSION; } -extern "C" uint32_t LLVMRustVersionPatch() { return LLVM_VERSION_PATCH; } - extern "C" uint32_t LLVMRustVersionMinor() { return LLVM_VERSION_MINOR; } extern "C" uint32_t LLVMRustVersionMajor() { return LLVM_VERSION_MAJOR; } @@ -996,9 +994,11 @@ LLVMRustDICompositeTypeReplaceArrays(LLVMRustDIBuilderRef Builder, } extern "C" LLVMMetadataRef -LLVMRustDIBuilderCreateDebugLocation(unsigned Line, unsigned Column, - LLVMMetadataRef Scope, +LLVMRustDIBuilderCreateDebugLocation(LLVMContextRef ContextRef, unsigned Line, + unsigned Column, LLVMMetadataRef Scope, LLVMMetadataRef InlinedAt) { + LLVMContext &Context = *unwrap(ContextRef); + DebugLoc debug_loc = DebugLoc::get(Line, Column, unwrapDIPtr(Scope), unwrapDIPtr(InlinedAt)); diff --git a/compiler/rustc_llvm/src/lib.rs b/compiler/rustc_llvm/src/lib.rs index 592010d78cf87..b2ffa271f62e2 100644 --- a/compiler/rustc_llvm/src/lib.rs +++ b/compiler/rustc_llvm/src/lib.rs @@ -38,7 +38,7 @@ pub fn initialize_available_targets() { ($cfg:meta, $($method:ident),*) => { { #[cfg($cfg)] fn init() { - extern "C" { + extern { $(fn $method();)* } unsafe { diff --git a/compiler/rustc_macros/src/query.rs b/compiler/rustc_macros/src/query.rs index d264462bf0895..6d876784be653 100644 --- a/compiler/rustc_macros/src/query.rs +++ b/compiler/rustc_macros/src/query.rs @@ -429,7 +429,7 @@ fn add_query_description_impl( }; let (tcx, desc) = modifiers.desc; - let tcx = tcx.as_ref().map_or(quote! { _ }, |t| quote! { #t }); + let tcx = tcx.as_ref().map(|t| quote! { #t }).unwrap_or(quote! { _ }); let desc = quote! { #[allow(unused_variables)] diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index a7bf79d7e6743..019ca5174a223 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -326,7 +326,7 @@ impl<'a> CrateLoader<'a> { self.verify_no_symbol_conflicts(&crate_root)?; let private_dep = - self.sess.opts.externs.get(&name.as_str()).map_or(false, |e| e.is_private_dep); + self.sess.opts.externs.get(&name.as_str()).map(|e| e.is_private_dep).unwrap_or(false); // Claim this crate number and cache it let cnum = self.cstore.alloc_new_crate_num(); diff --git a/compiler/rustc_metadata/src/native_libs.rs b/compiler/rustc_metadata/src/native_libs.rs index 8d0994320e383..5b33678b25ae2 100644 --- a/compiler/rustc_metadata/src/native_libs.rs +++ b/compiler/rustc_metadata/src/native_libs.rs @@ -132,7 +132,7 @@ impl ItemLikeVisitor<'tcx> for Collector<'tcx> { impl Collector<'tcx> { fn register_native_lib(&mut self, span: Option, lib: NativeLib) { - if lib.name.as_ref().map_or(false, |&s| s == kw::Empty) { + if lib.name.as_ref().map(|&s| s == kw::Empty).unwrap_or(false) { match span { Some(span) => { struct_span_err!( diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index 115569fc60d9f..eace17475771d 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -10,7 +10,7 @@ use rustc_data_structures::captures::Captures; use rustc_data_structures::fingerprint::{Fingerprint, FingerprintDecoder}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::svh::Svh; -use rustc_data_structures::sync::{Lock, LockGuard, Lrc, OnceCell}; +use rustc_data_structures::sync::{AtomicCell, Lock, LockGuard, Lrc, OnceCell}; use rustc_data_structures::unhash::UnhashMap; use rustc_errors::ErrorReported; use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind}; @@ -21,6 +21,7 @@ use rustc_hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE} use rustc_hir::definitions::{DefKey, DefPath, DefPathData, DefPathHash}; use rustc_hir::lang_items; use rustc_index::vec::{Idx, IndexVec}; +use rustc_middle::dep_graph::{self, DepNode, DepNodeExt, DepNodeIndex}; use rustc_middle::hir::exports::Export; use rustc_middle::middle::cstore::{CrateSource, ExternCrate}; use rustc_middle::middle::cstore::{ForeignModule, LinkagePreference, NativeLib}; @@ -83,6 +84,11 @@ crate struct CrateMetadata { def_path_hash_map: OnceCell>, /// Used for decoding interpret::AllocIds in a cached & thread-safe manner. alloc_decoding_state: AllocDecodingState, + /// The `DepNodeIndex` of the `DepNode` representing this upstream crate. + /// It is initialized on the first access in `get_crate_dep_node_index()`. + /// Do not access the value directly, as it might not have been initialized yet. + /// The field must always be initialized to `DepNodeIndex::INVALID`. + dep_node_index: AtomicCell, /// Caches decoded `DefKey`s. def_key_cache: Lock>, /// Caches decoded `DefPathHash`es. @@ -715,25 +721,21 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { &self.raw_proc_macros.unwrap()[pos] } - fn try_item_ident(&self, item_index: DefIndex, sess: &Session) -> Result { + fn item_ident(&self, item_index: DefIndex, sess: &Session) -> Ident { let name = self .def_key(item_index) .disambiguated_data .data .get_opt_name() - .ok_or_else(|| format!("Missing opt name for {:?}", item_index))?; + .expect("no name in item_ident"); let span = self .root .tables .ident_span .get(self, item_index) - .ok_or_else(|| format!("Missing ident span for {:?} ({:?})", name, item_index))? - .decode((self, sess)); - Ok(Ident::new(name, span)) - } - - fn item_ident(&self, item_index: DefIndex, sess: &Session) -> Ident { - self.try_item_ident(item_index, sess).unwrap() + .map(|data| data.decode((self, sess))) + .unwrap_or_else(|| panic!("Missing ident span for {:?} ({:?})", name, item_index)); + Ident::new(name, span) } fn def_kind(&self, index: DefIndex) -> DefKind { @@ -1605,6 +1607,31 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { self.def_path_hash_unlocked(index, &mut def_path_hashes) } + /// Get the `DepNodeIndex` corresponding this crate. The result of this + /// method is cached in the `dep_node_index` field. + fn get_crate_dep_node_index(&self, tcx: TyCtxt<'tcx>) -> DepNodeIndex { + let mut dep_node_index = self.dep_node_index.load(); + + if unlikely!(dep_node_index == DepNodeIndex::INVALID) { + // We have not cached the DepNodeIndex for this upstream crate yet, + // so use the dep-graph to find it out and cache it. + // Note that multiple threads can enter this block concurrently. + // That is fine because the DepNodeIndex remains constant + // throughout the whole compilation session, and multiple stores + // would always write the same value. + + let def_path_hash = self.def_path_hash(CRATE_DEF_INDEX); + let dep_node = + DepNode::from_def_path_hash(def_path_hash, dep_graph::DepKind::CrateMetadata); + + dep_node_index = tcx.dep_graph.dep_node_index_of(&dep_node); + assert!(dep_node_index != DepNodeIndex::INVALID); + self.dep_node_index.store(dep_node_index); + } + + dep_node_index + } + /// Imports the source_map from an external crate into the source_map of the crate /// currently being compiled (the "local crate"). /// @@ -1821,6 +1848,7 @@ impl CrateMetadata { source_map_import_info: OnceCell::new(), def_path_hash_map: Default::default(), alloc_decoding_state, + dep_node_index: AtomicCell::new(DepNodeIndex::INVALID), cnum, cnum_map, dependencies, diff --git a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs index 17ce4a5f9520e..96db0157422a7 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs @@ -44,16 +44,13 @@ macro_rules! provide { let ($def_id, $other) = def_id_arg.into_args(); assert!(!$def_id.is_local()); - // External query providers call `crate_hash` in order to register a dependency - // on the crate metadata. The exception is `crate_hash` itself, which obviously - // doesn't need to do this (and can't, as it would cause a query cycle). - use rustc_middle::dep_graph::DepKind; - if DepKind::$name != DepKind::crate_hash && $tcx.dep_graph.is_fully_enabled() { - $tcx.ensure().crate_hash($def_id.krate); - } - let $cdata = CStore::from_tcx($tcx).get_crate_data($def_id.krate); + if $tcx.dep_graph.is_fully_enabled() { + let crate_dep_node_index = $cdata.get_crate_dep_node_index($tcx); + $tcx.dep_graph.read_index(crate_dep_node_index); + } + $compute })* @@ -132,9 +129,6 @@ provide! { <'tcx> tcx, def_id, other, cdata, generator_kind => { cdata.generator_kind(def_id.index) } def_kind => { cdata.def_kind(def_id.index) } def_span => { cdata.get_span(def_id.index, &tcx.sess) } - def_ident_span => { - cdata.try_item_ident(def_id.index, &tcx.sess).ok().map(|ident| ident.span) - } lookup_stability => { cdata.get_stability(def_id.index).map(|s| tcx.intern_stability(s)) } diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 5e2674254b295..ccaee8608b618 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -46,7 +46,7 @@ pub(super) struct EncodeContext<'a, 'tcx> { lazy_state: LazyState, type_shorthands: FxHashMap, usize>, - predicate_shorthands: FxHashMap, usize>, + predicate_shorthands: FxHashMap, usize>, interpret_allocs: FxIndexSet, @@ -66,11 +66,6 @@ pub(super) struct EncodeContext<'a, 'tcx> { required_source_files: Option>, is_proc_macro: bool, hygiene_ctxt: &'a HygieneEncodeContext, - - // Determines if MIR used for code generation will be included in the crate - // metadata. When emitting only metadata (e.g., cargo check), we can avoid - // generating optimized MIR altogether. - emit_codegen_mir: bool, } /// If the current crate is a proc-macro, returns early with `Lazy:empty()`. @@ -328,7 +323,7 @@ impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> { &mut self.type_shorthands } - fn predicate_shorthands(&mut self) -> &mut FxHashMap, usize> { + fn predicate_shorthands(&mut self) -> &mut FxHashMap, usize> { &mut self.predicate_shorthands } @@ -792,11 +787,9 @@ impl EncodeContext<'a, 'tcx> { self.encode_generics(def_id); self.encode_explicit_predicates(def_id); self.encode_inferred_outlives(def_id); - let opt_mir = tcx.sess.opts.debugging_opts.always_encode_mir || self.emit_codegen_mir; - if opt_mir { - self.encode_optimized_mir(def_id.expect_local()); - } self.encode_mir_for_ctfe(def_id.expect_local()); + self.encode_optimized_mir(def_id.expect_local()); + self.encode_promoted_mir(def_id.expect_local()); } fn encode_info_for_mod(&mut self, id: hir::HirId, md: &hir::Mod<'_>, attrs: &[ast::Attribute]) { @@ -902,11 +895,9 @@ impl EncodeContext<'a, 'tcx> { self.encode_generics(def_id); self.encode_explicit_predicates(def_id); self.encode_inferred_outlives(def_id); - let opt_mir = tcx.sess.opts.debugging_opts.always_encode_mir || self.emit_codegen_mir; - if opt_mir { - self.encode_optimized_mir(def_id.expect_local()); - } + self.encode_optimized_mir(def_id.expect_local()); self.encode_mir_for_ctfe(def_id.expect_local()); + self.encode_promoted_mir(def_id.expect_local()); } fn encode_generics(&mut self, def_id: DefId) { @@ -1033,23 +1024,17 @@ impl EncodeContext<'a, 'tcx> { } } ty::AssocKind::Fn => { - let opt_mir = - tcx.sess.opts.debugging_opts.always_encode_mir || self.emit_codegen_mir; - if opt_mir { - if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id.expect_local()) { - self.encode_optimized_mir(def_id.expect_local()); - self.encode_promoted_mir(def_id.expect_local()); - } + if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id.expect_local()) { + self.encode_optimized_mir(def_id.expect_local()); + self.encode_promoted_mir(def_id.expect_local()); } } } } - fn should_encode_fn_opt_mir(&self, def_id: DefId) -> bool { - self.tcx.sess.opts.debugging_opts.always_encode_mir - || (self.emit_codegen_mir - && (self.tcx.generics_of(def_id).requires_monomorphization(self.tcx) - || self.tcx.codegen_fn_attrs(def_id).requests_inline())) + fn metadata_output_only(&self) -> bool { + // MIR optimisation can be skipped when we're just interested in the metadata. + !self.tcx.sess.opts.output_types.should_codegen() } fn encode_info_for_impl_item(&mut self, def_id: DefId) { @@ -1120,9 +1105,13 @@ impl EncodeContext<'a, 'tcx> { let (mir, mir_const) = match ast_item.kind { hir::ImplItemKind::Const(..) => (false, true), hir::ImplItemKind::Fn(ref sig, _) => { - let opt_mir = self.should_encode_fn_opt_mir(def_id); + let generics = self.tcx.generics_of(def_id); + let needs_inline = (generics.requires_monomorphization(self.tcx) + || tcx.codegen_fn_attrs(def_id).requests_inline()) + && !self.metadata_output_only(); let is_const_fn = sig.header.constness == hir::Constness::Const; - (opt_mir, is_const_fn) + let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir; + (needs_inline || always_encode_mir, is_const_fn) } hir::ImplItemKind::TyAlias(..) => (false, false), }; @@ -1294,7 +1283,7 @@ impl EncodeContext<'a, 'tcx> { is_non_exhaustive: variant.is_field_list_non_exhaustive(), }), adt_def.repr) } - hir::ItemKind::Impl(hir::Impl { defaultness, .. }) => { + hir::ItemKind::Impl { defaultness, .. } => { let trait_ref = self.tcx.impl_trait_ref(def_id); let polarity = self.tcx.impl_polarity(def_id); let parent = if let Some(trait_ref) = trait_ref { @@ -1444,10 +1433,16 @@ impl EncodeContext<'a, 'tcx> { let (mir, const_mir) = match item.kind { hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => (false, true), hir::ItemKind::Fn(ref sig, ..) => { - let opt_mir = self.should_encode_fn_opt_mir(def_id); + let generics = tcx.generics_of(def_id); + let needs_inline = (generics.requires_monomorphization(tcx) + || tcx.codegen_fn_attrs(def_id).requests_inline()) + && !self.metadata_output_only(); + let is_const_fn = sig.header.constness == hir::Constness::Const; + let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir; + let mir = needs_inline || always_encode_mir; // We don't need the optimized MIR for const fns. - (opt_mir, is_const_fn) + (mir, is_const_fn) } _ => (false, false), }; @@ -1507,14 +1502,8 @@ impl EncodeContext<'a, 'tcx> { record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig()); } self.encode_generics(def_id.to_def_id()); - let opt_mir = // FIXME: Optimized MIR is necessary to determine the layout of generators. - matches!(ty.kind(), ty::Generator(..)) - || self.tcx.sess.opts.debugging_opts.always_encode_mir - || self.emit_codegen_mir; - if opt_mir { - self.encode_optimized_mir(def_id); - self.encode_promoted_mir(def_id); - } + self.encode_optimized_mir(def_id); + self.encode_promoted_mir(def_id); } fn encode_info_for_anon_const(&mut self, def_id: LocalDefId) { @@ -2019,9 +2008,10 @@ impl<'tcx, 'v> ParItemLikeVisitor<'v> for PrefetchVisitor<'tcx> { } hir::ItemKind::Fn(ref sig, ..) => { let def_id = tcx.hir().local_def_id(item.hir_id); - let opt_mir = tcx.generics_of(def_id.to_def_id()).requires_monomorphization(tcx) + let generics = tcx.generics_of(def_id.to_def_id()); + let needs_inline = generics.requires_monomorphization(tcx) || tcx.codegen_fn_attrs(def_id.to_def_id()).requests_inline(); - if opt_mir { + if needs_inline { self.prefetch_mir(def_id) } if sig.header.constness == hir::Constness::Const { @@ -2055,10 +2045,11 @@ impl<'tcx, 'v> ParItemLikeVisitor<'v> for PrefetchVisitor<'tcx> { } hir::ImplItemKind::Fn(ref sig, _) => { let def_id = tcx.hir().local_def_id(impl_item.hir_id); - let opt_mir = tcx.generics_of(def_id.to_def_id()).requires_monomorphization(tcx) + let generics = tcx.generics_of(def_id.to_def_id()); + let needs_inline = generics.requires_monomorphization(tcx) || tcx.codegen_fn_attrs(def_id.to_def_id()).requests_inline(); let is_const_fn = sig.header.constness == hir::Constness::Const; - if opt_mir { + if needs_inline { self.prefetch_mir(def_id) } if is_const_fn { @@ -2157,7 +2148,6 @@ fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata { required_source_files, is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro), hygiene_ctxt: &hygiene_ctxt, - emit_codegen_mir: tcx.sess.opts.output_types.should_codegen(), }; // Encode the rustc version string in a predictable location. diff --git a/compiler/rustc_middle/src/dep_graph/dep_node.rs b/compiler/rustc_middle/src/dep_graph/dep_node.rs index 62f2874af0493..b775846bba452 100644 --- a/compiler/rustc_middle/src/dep_graph/dep_node.rs +++ b/compiler/rustc_middle/src/dep_graph/dep_node.rs @@ -29,10 +29,9 @@ //! contained no `DefId` for thing that had been removed. //! //! `DepNode` definition happens in the `define_dep_nodes!()` macro. This macro -//! defines the `DepKind` enum. Each `DepKind` has its own parameters that are -//! needed at runtime in order to construct a valid `DepNode` fingerprint. -//! However, only `CompileCodegenUnit` is constructed explicitly (with -//! `make_compile_codegen_unit`). +//! defines the `DepKind` enum and a corresponding `dep_constructor` module. The +//! `dep_constructor` module links a `DepKind` to the parameters that are needed at +//! runtime in order to construct a valid `DepNode` fingerprint. //! //! Because the macro sees what parameters a given `DepKind` requires, it can //! "infer" some properties for each kind of `DepNode`: @@ -45,14 +44,22 @@ //! `DefId` it was computed from. In other cases, too much information gets //! lost during fingerprint computation. //! -//! `make_compile_codegen_unit`, together with `DepNode::new()`, ensures that only +//! The `dep_constructor` module, together with `DepNode::new()`, ensures that only //! valid `DepNode` instances can be constructed. For example, the API does not //! allow for constructing parameterless `DepNode`s with anything other //! than a zeroed out fingerprint. More generally speaking, it relieves the //! user of the `DepNode` API of having to know how to compute the expected //! fingerprint for a given set of node parameters. -use crate::ty::TyCtxt; +use crate::mir::interpret::{GlobalId, LitToConstInput}; +use crate::traits; +use crate::traits::query::{ + CanonicalPredicateGoal, CanonicalProjectionGoal, CanonicalTyGoal, + CanonicalTypeOpAscribeUserTypeGoal, CanonicalTypeOpEqGoal, CanonicalTypeOpNormalizeGoal, + CanonicalTypeOpProvePredicateGoal, CanonicalTypeOpSubtypeGoal, +}; +use crate::ty::subst::{GenericArg, SubstsRef}; +use crate::ty::{self, ParamEnvAnd, Ty, TyCtxt}; use rustc_data_structures::fingerprint::Fingerprint; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_INDEX}; @@ -207,6 +214,17 @@ pub mod dep_kind { try_load_from_on_disk_cache: |_, _| {}, }; + // Represents metadata from an extern crate. + pub const CrateMetadata: DepKindStruct = DepKindStruct { + has_params: true, + is_anon: false, + is_eval_always: true, + + can_reconstruct_query_key: || true, + force_from_dep_node: |_, dep_node| bug!("force_from_dep_node: encountered {:?}", dep_node), + try_load_from_on_disk_cache: |_, _| {}, + }; + pub const TraitSelect: DepKindStruct = DepKindStruct { has_params: false, is_anon: true, @@ -320,6 +338,25 @@ macro_rules! define_dep_nodes { $($variant),* } + #[allow(non_camel_case_types)] + pub mod dep_constructor { + use super::*; + + $( + #[inline(always)] + #[allow(unreachable_code, non_snake_case)] + pub fn $variant(_tcx: TyCtxt<'_>, $(arg: $tuple_arg_ty)*) -> DepNode { + // tuple args + $({ + erase!($tuple_arg_ty); + return DepNode::construct(_tcx, DepKind::$variant, &arg) + })* + + return DepNode::construct(_tcx, DepKind::$variant, &()) + } + )* + } + fn dep_kind_from_label_string(label: &str) -> Result { match label { $(stringify!($variant) => Ok(DepKind::$variant),)* @@ -342,18 +379,14 @@ rustc_dep_node_append!([define_dep_nodes!][ <'tcx> // We use this for most things when incr. comp. is turned off. [] Null, + // Represents metadata from an extern crate. + [eval_always] CrateMetadata(CrateNum), + [anon] TraitSelect, - // WARNING: if `Symbol` is changed, make sure you update `make_compile_codegen_unit` below. [] CompileCodegenUnit(Symbol), ]); -// WARNING: `construct` is generic and does not know that `CompileCodegenUnit` takes `Symbol`s as keys. -// Be very careful changing this type signature! -crate fn make_compile_codegen_unit(tcx: TyCtxt<'_>, name: Symbol) -> DepNode { - DepNode::construct(tcx, DepKind::CompileCodegenUnit, &name) -} - pub type DepNode = rustc_query_system::dep_graph::DepNode; // We keep a lot of `DepNode`s in memory during compilation. It's not diff --git a/compiler/rustc_middle/src/dep_graph/mod.rs b/compiler/rustc_middle/src/dep_graph/mod.rs index b88ffa2bb7347..22e9cc1cd3ee4 100644 --- a/compiler/rustc_middle/src/dep_graph/mod.rs +++ b/compiler/rustc_middle/src/dep_graph/mod.rs @@ -13,8 +13,7 @@ pub use rustc_query_system::dep_graph::{ WorkProduct, WorkProductId, }; -crate use dep_node::make_compile_codegen_unit; -pub use dep_node::{label_strs, DepKind, DepNode, DepNodeExt}; +pub use dep_node::{dep_constructor, label_strs, DepKind, DepNode, DepNodeExt}; pub type DepGraph = rustc_query_system::dep_graph::DepGraph; pub type TaskDeps = rustc_query_system::dep_graph::TaskDeps; @@ -116,9 +115,20 @@ impl<'tcx> DepContext for TyCtxt<'tcx> { // be removed. https://github.com/rust-lang/rust/issues/62649 is one such // bug that must be fixed before removing this. match dep_node.kind { - DepKind::hir_owner | DepKind::hir_owner_nodes => { + DepKind::hir_owner | DepKind::hir_owner_nodes | DepKind::CrateMetadata => { if let Some(def_id) = dep_node.extract_def_id(*self) { - if !def_id_corresponds_to_hir_dep_node(*self, def_id.expect_local()) { + if def_id_corresponds_to_hir_dep_node(*self, def_id.expect_local()) { + if dep_node.kind == DepKind::CrateMetadata { + // The `DefPath` has corresponding node, + // and that node should have been marked + // either red or green in `data.colors`. + bug!( + "DepNode {:?} should have been \ + pre-marked as red or green but wasn't.", + dep_node + ); + } + } else { // This `DefPath` does not have a // corresponding `DepNode` (e.g. a // struct field), and the ` DefPath` diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index 06bb1347dc1de..eb6aded9cb3bd 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -505,7 +505,7 @@ impl<'hir> Map<'hir> { | ItemKind::Union(_, generics) | ItemKind::Trait(_, _, generics, ..) | ItemKind::TraitAlias(generics, _) - | ItemKind::Impl(Impl { generics, .. }), + | ItemKind::Impl { generics, .. }, .. }) => Some(generics), _ => None, @@ -658,12 +658,12 @@ impl<'hir> Map<'hir> { CRATE_HIR_ID } - /// When on an if expression, a match arm tail expression or a match arm, give back - /// the enclosing `if` or `match` expression. + /// When on a match arm tail expression or on a match arm, give back the enclosing `match` + /// expression. /// - /// Used by error reporting when there's a type error in an if or match arm caused by the + /// Used by error reporting when there's a type error in a match arm caused by the `match` /// expression needing to be unit. - pub fn get_if_cause(&self, hir_id: HirId) -> Option<&'hir Expr<'hir>> { + pub fn get_match_if_cause(&self, hir_id: HirId) -> Option<&'hir Expr<'hir>> { for (_, node) in self.parent_iter(hir_id) { match node { Node::Item(_) @@ -671,9 +671,7 @@ impl<'hir> Map<'hir> { | Node::TraitItem(_) | Node::ImplItem(_) | Node::Stmt(Stmt { kind: StmtKind::Local(_), .. }) => break, - Node::Expr(expr @ Expr { kind: ExprKind::If(..) | ExprKind::Match(..), .. }) => { - return Some(expr); - } + Node::Expr(expr @ Expr { kind: ExprKind::Match(..), .. }) => return Some(expr), _ => {} } } @@ -815,7 +813,7 @@ impl<'hir> Map<'hir> { /// Given a node ID, gets a list of attributes associated with the AST /// corresponding to the node-ID. pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] { - self.find_entry(id).map_or(&[], |entry| match entry.node { + let attrs = self.find_entry(id).map(|entry| match entry.node { Node::Param(a) => &a.attrs[..], Node::Local(l) => &l.attrs[..], Node::Item(i) => &i.attrs[..], @@ -842,7 +840,8 @@ impl<'hir> Map<'hir> { | Node::Block(..) | Node::Lifetime(..) | Node::Visibility(..) => &[], - }) + }); + attrs.unwrap_or(&[]) } /// Gets the span of the definition of the specified HIR node. diff --git a/compiler/rustc_middle/src/lint.rs b/compiler/rustc_middle/src/lint.rs index 80c87dddd5614..64d850192f449 100644 --- a/compiler/rustc_middle/src/lint.rs +++ b/compiler/rustc_middle/src/lint.rs @@ -46,7 +46,7 @@ impl LintLevelSource { } /// A tuple of a lint level and its source. -pub type LevelAndSource = (Level, LintLevelSource); +pub type LevelSource = (Level, LintLevelSource); pub struct LintLevelSets { pub list: Vec, @@ -57,11 +57,11 @@ pub enum LintSet { CommandLine { // -A,-W,-D flags, a `Symbol` for the flag itself and `Level` for which // flag. - specs: FxHashMap, + specs: FxHashMap, }, Node { - specs: FxHashMap, + specs: FxHashMap, parent: u32, }, } @@ -75,9 +75,9 @@ impl LintLevelSets { &self, lint: &'static Lint, idx: u32, - aux: Option<&FxHashMap>, + aux: Option<&FxHashMap>, sess: &Session, - ) -> LevelAndSource { + ) -> LevelSource { let (level, mut src) = self.get_lint_id_level(LintId::of(lint), idx, aux); // If `level` is none then we actually assume the default level for this @@ -113,7 +113,7 @@ impl LintLevelSets { &self, id: LintId, mut idx: u32, - aux: Option<&FxHashMap>, + aux: Option<&FxHashMap>, ) -> (Option, LintLevelSource) { if let Some(specs) = aux { if let Some(&(level, src)) = specs.get(&id) { @@ -157,7 +157,7 @@ impl LintLevelMap { lint: &'static Lint, id: HirId, session: &Session, - ) -> Option { + ) -> Option { self.id_to_set.get(&id).map(|idx| self.sets.get_lint_level(lint, *idx, None, session)) } } diff --git a/compiler/rustc_middle/src/mir/mono.rs b/compiler/rustc_middle/src/mir/mono.rs index 6d5d408f86c15..698c25215968b 100644 --- a/compiler/rustc_middle/src/mir/mono.rs +++ b/compiler/rustc_middle/src/mir/mono.rs @@ -1,7 +1,6 @@ -use crate::dep_graph::{DepNode, WorkProduct, WorkProductId}; +use crate::dep_graph::{dep_constructor, DepNode, WorkProduct, WorkProductId}; use crate::ich::{NodeIdHashingMode, StableHashingContext}; use crate::ty::{subst::InternalSubsts, Instance, InstanceDef, SymbolName, TyCtxt}; -use rustc_attr::InlineAttr; use rustc_data_structures::base_n; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::FxHashMap; @@ -79,14 +78,6 @@ impl<'tcx> MonoItem<'tcx> { } pub fn instantiation_mode(&self, tcx: TyCtxt<'tcx>) -> InstantiationMode { - let generate_cgu_internal_copies = tcx - .sess - .opts - .debugging_opts - .inline_in_all_cgus - .unwrap_or_else(|| tcx.sess.opts.optimize != OptLevel::No) - && !tcx.sess.link_dead_code(); - match *self { MonoItem::Fn(ref instance) => { let entry_def_id = tcx.entry_fn(LOCAL_CRATE).map(|(id, _)| id); @@ -99,21 +90,26 @@ impl<'tcx> MonoItem<'tcx> { return InstantiationMode::GloballyShared { may_conflict: false }; } + let generate_cgu_internal_copies = tcx + .sess + .opts + .debugging_opts + .inline_in_all_cgus + .unwrap_or_else(|| tcx.sess.opts.optimize != OptLevel::No) + && !tcx.sess.link_dead_code(); + // At this point we don't have explicit linkage and we're an - // inlined function. If we're inlining into all CGUs then we'll - // be creating a local copy per CGU. + // inlined function. If we should generate local copies for each CGU, + // then return `LocalCopy`, otherwise we'll just generate one copy + // and share it with all CGUs in this crate. if generate_cgu_internal_copies { - return InstantiationMode::LocalCopy; - } - - // Finally, if this is `#[inline(always)]` we're sure to respect - // that with an inline copy per CGU, but otherwise we'll be - // creating one copy of this `#[inline]` function which may - // conflict with upstream crates as it could be an exported - // symbol. - match tcx.codegen_fn_attrs(instance.def_id()).inline { - InlineAttr::Always => InstantiationMode::LocalCopy, - _ => InstantiationMode::GloballyShared { may_conflict: true }, + InstantiationMode::LocalCopy + } else { + // Finally, if we've reached this point, then we should optimize for + // compilation speed. In that regard, we will ignore any `#[inline]` + // annotations on the function and simply codegen it as usual. This could + // conflict with upstream crates as it could be an exported symbol. + InstantiationMode::GloballyShared { may_conflict: true } } } MonoItem::Static(..) | MonoItem::GlobalAsm(..) => { @@ -362,7 +358,7 @@ impl<'tcx> CodegenUnit<'tcx> { } pub fn codegen_dep_node(&self, tcx: TyCtxt<'tcx>) -> DepNode { - crate::dep_graph::make_compile_codegen_unit(tcx, self.name()) + dep_constructor::CompileCodegenUnit(tcx, self.name()) } } diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 00ee7b8ec7709..8bfa76b6e2e72 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -881,7 +881,6 @@ rustc_queries! { query def_kind(def_id: DefId) -> DefKind { desc { |tcx| "looking up definition kind of `{}`", tcx.def_path_str(def_id) } } - query def_span(def_id: DefId) -> Span { desc { |tcx| "looking up span for `{}`", tcx.def_path_str(def_id) } // FIXME(mw): DefSpans are not really inputs since they are derived from @@ -891,23 +890,15 @@ rustc_queries! { // regardless of HIR hashing. eval_always } - - query def_ident_span(def_id: DefId) -> Option { - desc { |tcx| "looking up span for `{}`'s identifier", tcx.def_path_str(def_id) } - } - query lookup_stability(def_id: DefId) -> Option<&'tcx attr::Stability> { desc { |tcx| "looking up stability of `{}`", tcx.def_path_str(def_id) } } - query lookup_const_stability(def_id: DefId) -> Option<&'tcx attr::ConstStability> { desc { |tcx| "looking up const stability of `{}`", tcx.def_path_str(def_id) } } - query lookup_deprecation_entry(def_id: DefId) -> Option { desc { |tcx| "checking whether `{}` is deprecated", tcx.def_path_str(def_id) } } - query item_attrs(def_id: DefId) -> &'tcx [ast::Attribute] { desc { |tcx| "collecting attributes of `{}`", tcx.def_path_str(def_id) } } @@ -1240,8 +1231,6 @@ rustc_queries! { eval_always desc { "looking up the disambiguator a crate" } } - // The macro which defines `rustc_metadata::provide_extern` depends on this query's name. - // Changing the name should cause a compiler error, but in case that changes, be aware. query crate_hash(_: CrateNum) -> Svh { eval_always desc { "looking up the hash a crate" } @@ -1281,6 +1270,11 @@ rustc_queries! { } Other { + query dllimport_foreign_items(_: CrateNum) + -> FxHashSet { + storage(ArenaCacheSelector<'tcx>) + desc { "dllimport_foreign_items" } + } query is_dllimport_foreign_item(def_id: DefId) -> bool { desc { |tcx| "is_dllimport_foreign_item({})", tcx.def_path_str(def_id) } } @@ -1311,7 +1305,7 @@ rustc_queries! { desc { "looking up a named region" } } query is_late_bound_map(_: LocalDefId) -> - Option<(LocalDefId, &'tcx FxHashSet)> { + Option<&'tcx FxHashSet> { desc { "testing if a region is late bound" } } query object_lifetime_defaults_map(_: LocalDefId) diff --git a/compiler/rustc_middle/src/ty/cast.rs b/compiler/rustc_middle/src/ty/cast.rs index d737d1ebf56c6..b47d9c50e1d0a 100644 --- a/compiler/rustc_middle/src/ty/cast.rs +++ b/compiler/rustc_middle/src/ty/cast.rs @@ -22,16 +22,15 @@ pub enum CastTy<'tcx> { /// Various types that are represented as ints and handled mostly /// in the same way, merged for easier matching. Int(IntTy), - /// Floating-point types. + /// Floating-Point types Float, - /// Function pointers. + /// Function Pointers FnPtr, - /// Raw pointers. + /// Raw pointers Ptr(ty::TypeAndMut<'tcx>), } -/// Cast Kind. See [RFC 401](https://rust-lang.github.io/rfcs/0401-coercions.html) -/// (or librustc_typeck/check/cast.rs). +/// Cast Kind. See RFC 401 (or librustc_typeck/check/cast.rs) #[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)] pub enum CastKind { CoercionCast, @@ -49,7 +48,7 @@ pub enum CastKind { impl<'tcx> CastTy<'tcx> { /// Returns `Some` for integral/pointer casts. - /// Casts like unsizing casts will return `None`. + /// casts like unsizing casts will return `None` pub fn from_ty(t: Ty<'tcx>) -> Option> { match *t.kind() { ty::Bool => Some(CastTy::Int(IntTy::Bool)), diff --git a/compiler/rustc_middle/src/ty/codec.rs b/compiler/rustc_middle/src/ty/codec.rs index 0dad5df48551e..9d371503e0a4c 100644 --- a/compiler/rustc_middle/src/ty/codec.rs +++ b/compiler/rustc_middle/src/ty/codec.rs @@ -18,6 +18,7 @@ use rustc_data_structures::fx::FxHashMap; use rustc_hir::def_id::{CrateNum, DefId}; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use rustc_span::Span; +use std::convert::{TryFrom, TryInto}; use std::hash::Hash; use std::intrinsics; use std::marker::DiscriminantKind; @@ -42,12 +43,10 @@ impl<'tcx, E: TyEncoder<'tcx>> EncodableWithShorthand<'tcx, E> for Ty<'tcx> { } } -impl<'tcx, E: TyEncoder<'tcx>> EncodableWithShorthand<'tcx, E> for ty::PredicateKind<'tcx> { +impl<'tcx, E: TyEncoder<'tcx>> EncodableWithShorthand<'tcx, E> for ty::Predicate<'tcx> { type Variant = ty::PredicateKind<'tcx>; - - #[inline] fn variant(&self) -> &Self::Variant { - self + self.kind() } } @@ -56,7 +55,7 @@ pub trait TyEncoder<'tcx>: Encoder { fn position(&self) -> usize; fn type_shorthands(&mut self) -> &mut FxHashMap, usize>; - fn predicate_shorthands(&mut self) -> &mut FxHashMap, usize>; + fn predicate_shorthands(&mut self) -> &mut FxHashMap, usize>; fn encode_alloc_id(&mut self, alloc_id: &AllocId) -> Result<(), Self::Error>; } @@ -80,8 +79,7 @@ where E: TyEncoder<'tcx>, M: for<'b> Fn(&'b mut E) -> &'b mut FxHashMap, T: EncodableWithShorthand<'tcx, E>, - // The discriminant and shorthand must have the same size. - T::Variant: DiscriminantKind, + ::Discriminant: Ord + TryFrom, { let existing_shorthand = cache(encoder).get(value).copied(); if let Some(shorthand) = existing_shorthand { @@ -97,7 +95,7 @@ where // The shorthand encoding uses the same usize as the // discriminant, with an offset so they can't conflict. let discriminant = intrinsics::discriminant_value(variant); - assert!(SHORTHAND_OFFSET > discriminant as usize); + assert!(discriminant < SHORTHAND_OFFSET.try_into().ok().unwrap()); let shorthand = start + SHORTHAND_OFFSET; @@ -120,15 +118,9 @@ impl<'tcx, E: TyEncoder<'tcx>> Encodable for Ty<'tcx> { } } -impl<'tcx, E: TyEncoder<'tcx>> Encodable for ty::Binder> { - fn encode(&self, e: &mut E) -> Result<(), E::Error> { - encode_with_shorthand(e, &self.skip_binder(), TyEncoder::predicate_shorthands) - } -} - impl<'tcx, E: TyEncoder<'tcx>> Encodable for ty::Predicate<'tcx> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { - self.kind().encode(e) + encode_with_shorthand(e, self, TyEncoder::predicate_shorthands) } } @@ -226,24 +218,18 @@ impl<'tcx, D: TyDecoder<'tcx>> Decodable for Ty<'tcx> { } } -impl<'tcx, D: TyDecoder<'tcx>> Decodable for ty::Binder> { - fn decode(decoder: &mut D) -> Result>, D::Error> { +impl<'tcx, D: TyDecoder<'tcx>> Decodable for ty::Predicate<'tcx> { + fn decode(decoder: &mut D) -> Result, D::Error> { // Handle shorthands first, if we have an usize > 0x80. - Ok(ty::Binder::bind(if decoder.positioned_at_shorthand() { + let predicate_kind = if decoder.positioned_at_shorthand() { let pos = decoder.read_usize()?; assert!(pos >= SHORTHAND_OFFSET); let shorthand = pos - SHORTHAND_OFFSET; - decoder.with_position(shorthand, ty::PredicateKind::decode)? + decoder.with_position(shorthand, ty::PredicateKind::decode) } else { - ty::PredicateKind::decode(decoder)? - })) - } -} - -impl<'tcx, D: TyDecoder<'tcx>> Decodable for ty::Predicate<'tcx> { - fn decode(decoder: &mut D) -> Result, D::Error> { - let predicate_kind = Decodable::decode(decoder)?; + ty::PredicateKind::decode(decoder) + }?; let predicate = decoder.tcx().mk_predicate(predicate_kind); Ok(predicate) } @@ -471,28 +457,3 @@ macro_rules! implement_ty_decoder { } } } - -macro_rules! impl_binder_encode_decode { - ($($t:ty),+ $(,)?) => { - $( - impl<'tcx, E: TyEncoder<'tcx>> Encodable for ty::Binder<$t> { - fn encode(&self, e: &mut E) -> Result<(), E::Error> { - self.as_ref().skip_binder().encode(e) - } - } - impl<'tcx, D: TyDecoder<'tcx>> Decodable for ty::Binder<$t> { - fn decode(decoder: &mut D) -> Result { - Ok(ty::Binder::bind(Decodable::decode(decoder)?)) - } - } - )* - } -} - -impl_binder_encode_decode! { - &'tcx ty::List>, - ty::FnSig<'tcx>, - ty::ExistentialPredicate<'tcx>, - ty::TraitRef<'tcx>, - Vec>, -} diff --git a/compiler/rustc_middle/src/ty/consts.rs b/compiler/rustc_middle/src/ty/consts.rs index 041c040f0b7e2..0af884a286d6e 100644 --- a/compiler/rustc_middle/src/ty/consts.rs +++ b/compiler/rustc_middle/src/ty/consts.rs @@ -92,7 +92,8 @@ impl<'tcx> Const<'tcx> { let item_id = tcx.hir().get_parent_node(hir_id); let item_def_id = tcx.hir().local_def_id(item_id); let generics = tcx.generics_of(item_def_id.to_def_id()); - let index = generics.param_def_id_to_index[&def_id]; + let index = + generics.param_def_id_to_index[&tcx.hir().local_def_id(hir_id).to_def_id()]; let name = tcx.hir().name(hir_id); ty::ConstKind::Param(ty::ParamConst::new(index, name)) } diff --git a/compiler/rustc_middle/src/ty/consts/kind.rs b/compiler/rustc_middle/src/ty/consts/kind.rs index a2638d8bddad0..ecf2837b3e423 100644 --- a/compiler/rustc_middle/src/ty/consts/kind.rs +++ b/compiler/rustc_middle/src/ty/consts/kind.rs @@ -82,7 +82,7 @@ impl<'tcx> ConstKind<'tcx> { /// Tries to evaluate the constant if it is `Unevaluated`. If that doesn't succeed, return the /// unevaluated constant. pub fn eval(self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Self { - self.try_eval(tcx, param_env).and_then(Result::ok).map_or(self, ConstKind::Value) + self.try_eval(tcx, param_env).and_then(Result::ok).map(ConstKind::Value).unwrap_or(self) } #[inline] diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 1cbf761e6c738..3540f0f06b6e6 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -1,9 +1,8 @@ //! Type context book-keeping. use crate::arena::Arena; -use crate::dep_graph::DepGraph; +use crate::dep_graph::{self, DepGraph, DepKind, DepNode, DepNodeExt}; use crate::hir::exports::ExportMap; -use crate::hir::place::Place as HirPlace; use crate::ich::{NodeIdHashingMode, StableHashingContext}; use crate::infer::canonical::{Canonical, CanonicalVarInfo, CanonicalVarInfos}; use crate::lint::{struct_lint_level, LintDiagnosticBuilder, LintLevelSource}; @@ -18,9 +17,9 @@ use crate::ty::query::{self, TyCtxtAt}; use crate::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, Subst, SubstsRef, UserSubsts}; use crate::ty::TyKind::*; use crate::ty::{ - self, AdtDef, AdtKind, Binder, BindingMode, BoundVar, CanonicalPolyFnSig, Const, ConstVid, - DefIdTree, ExistentialPredicate, FloatVar, FloatVid, GenericParamDefKind, InferConst, InferTy, - IntVar, IntVid, List, ParamConst, ParamTy, PolyFnSig, Predicate, PredicateInner, PredicateKind, + self, AdtDef, AdtKind, BindingMode, BoundVar, CanonicalPolyFnSig, Const, ConstVid, DefIdTree, + ExistentialPredicate, FloatVar, FloatVid, GenericParamDefKind, InferConst, InferTy, IntVar, + IntVid, List, ParamConst, ParamTy, PolyFnSig, Predicate, PredicateInner, PredicateKind, ProjectionTy, Region, RegionKind, ReprOptions, TraitObjectVisitor, Ty, TyKind, TyS, TyVar, TyVid, TypeAndMut, Visibility, }; @@ -38,7 +37,8 @@ use rustc_data_structures::sync::{self, Lock, Lrc, WorkerLocal}; use rustc_errors::ErrorReported; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LOCAL_CRATE}; +use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId}; +use rustc_hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE}; use rustc_hir::definitions::Definitions; use rustc_hir::intravisit::Visitor; use rustc_hir::lang_items::LangItem; @@ -134,7 +134,7 @@ impl<'tcx> CtxtInterners<'tcx> { } #[inline(never)] - fn intern_predicate(&self, kind: Binder>) -> &'tcx PredicateInner<'tcx> { + fn intern_predicate(&self, kind: PredicateKind<'tcx>) -> &'tcx PredicateInner<'tcx> { self.predicate .intern(kind, |kind| { let flags = super::flags::FlagComputation::for_predicate(kind); @@ -380,7 +380,7 @@ pub struct TypeckResults<'tcx> { /// Records the reasons that we picked the kind of each closure; /// not all closures are present in the map. - closure_kind_origins: ItemLocalMap<(Span, HirPlace<'tcx>)>, + closure_kind_origins: ItemLocalMap<(Span, Symbol)>, /// For each fn, records the "liberated" types of its arguments /// and return type. Liberated means that all bound regions @@ -643,13 +643,11 @@ impl<'tcx> TypeckResults<'tcx> { self.upvar_capture_map[&upvar_id] } - pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, HirPlace<'tcx>)> { + pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, Symbol)> { LocalTableInContext { hir_owner: self.hir_owner, data: &self.closure_kind_origins } } - pub fn closure_kind_origins_mut( - &mut self, - ) -> LocalTableInContextMut<'_, (Span, HirPlace<'tcx>)> { + pub fn closure_kind_origins_mut(&mut self) -> LocalTableInContextMut<'_, (Span, Symbol)> { LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.closure_kind_origins } } @@ -1317,8 +1315,30 @@ impl<'tcx> TyCtxt<'tcx> { StableHashingContext::ignore_spans(self.sess, krate, self.definitions, &*self.cstore) } + // This method makes sure that we have a DepNode and a Fingerprint for + // every upstream crate. It needs to be called once right after the tcx is + // created. + // With full-fledged red/green, the method will probably become unnecessary + // as this will be done on-demand. + pub fn allocate_metadata_dep_nodes(self) { + // We cannot use the query versions of crates() and crate_hash(), since + // those would need the DepNodes that we are allocating here. + for cnum in self.cstore.crates_untracked() { + let def_path_hash = self.def_path_hash(DefId { krate: cnum, index: CRATE_DEF_INDEX }); + let dep_node = DepNode::from_def_path_hash(def_path_hash, DepKind::CrateMetadata); + let crate_hash = self.cstore.crate_hash_untracked(cnum); + self.dep_graph.with_task( + dep_node, + self, + crate_hash, + |_, x| x, // No transformation needed + dep_graph::hash_result, + ); + } + } + pub fn serialize_query_result_cache(self, encoder: &mut FileEncoder) -> FileEncodeResult { - self.queries.on_disk_cache.as_ref().map_or(Ok(()), |c| c.serialize(self, encoder)) + self.queries.on_disk_cache.as_ref().map(|c| c.serialize(self, encoder)).unwrap_or(Ok(())) } /// If `true`, we should use the MIR-based borrowck, but also @@ -1951,8 +1971,8 @@ impl<'tcx> Hash for Interned<'tcx, PredicateInner<'tcx>> { } } -impl<'tcx> Borrow>> for Interned<'tcx, PredicateInner<'tcx>> { - fn borrow<'a>(&'a self) -> &'a Binder> { +impl<'tcx> Borrow> for Interned<'tcx, PredicateInner<'tcx>> { + fn borrow<'a>(&'a self) -> &'a PredicateKind<'tcx> { &self.0.kind } } @@ -1990,6 +2010,12 @@ impl<'tcx> Borrow> for Interned<'tcx, Const<'tcx>> { } } +impl<'tcx> Borrow> for Interned<'tcx, PredicateKind<'tcx>> { + fn borrow<'a>(&'a self) -> &'a PredicateKind<'tcx> { + &self.0 + } +} + macro_rules! direct_interners { ($($name:ident: $method:ident($ty:ty),)+) => { $(impl<'tcx> PartialEq for Interned<'tcx, $ty> { @@ -2088,8 +2114,8 @@ impl<'tcx> TyCtxt<'tcx> { } #[inline] - pub fn mk_predicate(self, binder: Binder>) -> Predicate<'tcx> { - let inner = self.interners.intern_predicate(binder); + pub fn mk_predicate(self, kind: PredicateKind<'tcx>) -> Predicate<'tcx> { + let inner = self.interners.intern_predicate(kind); Predicate { inner } } @@ -2097,9 +2123,9 @@ impl<'tcx> TyCtxt<'tcx> { pub fn reuse_or_mk_predicate( self, pred: Predicate<'tcx>, - binder: Binder>, + kind: PredicateKind<'tcx>, ) -> Predicate<'tcx> { - if pred.kind() != binder { self.mk_predicate(binder) } else { pred } + if *pred.kind() != kind { self.mk_predicate(kind) } else { pred } } pub fn mk_mach_int(self, tm: ast::IntTy) -> Ty<'tcx> { @@ -2575,8 +2601,7 @@ impl<'tcx> TyCtxt<'tcx> { } pub fn is_late_bound(self, id: HirId) -> bool { - self.is_late_bound_map(id.owner) - .map_or(false, |(owner, set)| owner == id.owner && set.contains(&id.local_id)) + self.is_late_bound_map(id.owner).map(|set| set.contains(&id.local_id)).unwrap_or(false) } pub fn object_lifetime_defaults(self, id: HirId) -> Option<&'tcx [ObjectLifetimeDefault]> { diff --git a/compiler/rustc_middle/src/ty/error.rs b/compiler/rustc_middle/src/ty/error.rs index f172790fe5fff..fe20925b38798 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -829,8 +829,7 @@ fn foo(&self) -> Self::T { String::new() } } } Some(hir::Node::Item(hir::Item { - kind: hir::ItemKind::Impl(hir::Impl { items, .. }), - .. + kind: hir::ItemKind::Impl { items, .. }, .. })) => { for item in &items[..] { if let hir::AssocItemKind::Type = item.kind { @@ -847,7 +846,7 @@ fn foo(&self) -> Self::T { String::new() } } /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref` - /// requirement, provide a structured suggestion to constrain it to a given type `ty`. + /// requirement, provide a strucuted suggestion to constrain it to a given type `ty`. fn constrain_generic_bound_associated_type_structured_suggestion( self, db: &mut DiagnosticBuilder<'_>, diff --git a/compiler/rustc_middle/src/ty/flags.rs b/compiler/rustc_middle/src/ty/flags.rs index 6ecd1ebf37039..4de3d15924862 100644 --- a/compiler/rustc_middle/src/ty/flags.rs +++ b/compiler/rustc_middle/src/ty/flags.rs @@ -22,9 +22,9 @@ impl FlagComputation { result } - pub fn for_predicate(binder: ty::Binder>) -> FlagComputation { + pub fn for_predicate(kind: ty::PredicateKind<'_>) -> FlagComputation { let mut result = FlagComputation::new(); - result.add_predicate(binder); + result.add_predicate_kind(kind); result } @@ -204,46 +204,53 @@ impl FlagComputation { } } - fn add_predicate(&mut self, binder: ty::Binder>) { - self.bound_computation(binder, |computation, atom| computation.add_predicate_atom(atom)); + fn add_predicate_kind(&mut self, kind: ty::PredicateKind<'_>) { + match kind { + ty::PredicateKind::ForAll(binder) => { + self.bound_computation(binder, |computation, atom| { + computation.add_predicate_atom(atom) + }); + } + ty::PredicateKind::Atom(atom) => self.add_predicate_atom(atom), + } } - fn add_predicate_atom(&mut self, atom: ty::PredicateKind<'_>) { + fn add_predicate_atom(&mut self, atom: ty::PredicateAtom<'_>) { match atom { - ty::PredicateKind::Trait(trait_pred, _constness) => { + ty::PredicateAtom::Trait(trait_pred, _constness) => { self.add_substs(trait_pred.trait_ref.substs); } - ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => { + ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate(a, b)) => { self.add_region(a); self.add_region(b); } - ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, region)) => { + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, region)) => { self.add_ty(ty); self.add_region(region); } - ty::PredicateKind::Subtype(ty::SubtypePredicate { a_is_expected: _, a, b }) => { + ty::PredicateAtom::Subtype(ty::SubtypePredicate { a_is_expected: _, a, b }) => { self.add_ty(a); self.add_ty(b); } - ty::PredicateKind::Projection(ty::ProjectionPredicate { projection_ty, ty }) => { + ty::PredicateAtom::Projection(ty::ProjectionPredicate { projection_ty, ty }) => { self.add_projection_ty(projection_ty); self.add_ty(ty); } - ty::PredicateKind::WellFormed(arg) => { + ty::PredicateAtom::WellFormed(arg) => { self.add_substs(slice::from_ref(&arg)); } - ty::PredicateKind::ObjectSafe(_def_id) => {} - ty::PredicateKind::ClosureKind(_def_id, substs, _kind) => { + ty::PredicateAtom::ObjectSafe(_def_id) => {} + ty::PredicateAtom::ClosureKind(_def_id, substs, _kind) => { self.add_substs(substs); } - ty::PredicateKind::ConstEvaluatable(_def_id, substs) => { + ty::PredicateAtom::ConstEvaluatable(_def_id, substs) => { self.add_substs(substs); } - ty::PredicateKind::ConstEquate(expected, found) => { + ty::PredicateAtom::ConstEquate(expected, found) => { self.add_const(expected); self.add_const(found); } - ty::PredicateKind::TypeWellFormedFromEnv(ty) => { + ty::PredicateAtom::TypeWellFormedFromEnv(ty) => { self.add_ty(ty); } } diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index 6ca5dcc532d22..413c9cca589d9 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -535,7 +535,7 @@ fn polymorphize<'tcx>( } else { None }; - let has_upvars = upvars_ty.map_or(false, |ty| ty.tuple_fields().count() > 0); + let has_upvars = upvars_ty.map(|ty| ty.tuple_fields().count() > 0).unwrap_or(false); debug!("polymorphize: upvars_ty={:?} has_upvars={:?}", upvars_ty, has_upvars); struct PolymorphizationFolder<'tcx> { diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 195e840866aec..4475d4e9f2dea 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -1466,12 +1466,10 @@ impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> { ) -> Result<&'tcx Layout, LayoutError<'tcx>> { use SavedLocalEligibility::*; let tcx = self.tcx; + let subst_field = |ty: Ty<'tcx>| ty.subst(tcx, substs); - let info = match tcx.generator_layout(def_id) { - None => return Err(LayoutError::Unknown(ty)), - Some(info) => info, - }; + let info = tcx.generator_layout(def_id); let (ineligible_locals, assignments) = self.generator_saved_local_eligibility(&info); // Build a prefix layout, including "promoting" all ineligible diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index c6970df01785e..9666affdbdf61 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -17,9 +17,7 @@ pub use self::IntVarValue::*; pub use self::Variance::*; use crate::hir::exports::ExportMap; -use crate::hir::place::{ - Place as HirPlace, PlaceBase as HirPlaceBase, ProjectionKind as HirProjectionKind, -}; +use crate::hir::place::Place as HirPlace; use crate::ich::StableHashingContext; use crate::middle::cstore::CrateStoreDyn; use crate::middle::resolve_lifetime::ObjectLifetimeDefault; @@ -736,43 +734,6 @@ pub struct CapturedPlace<'tcx> { pub info: CaptureInfo<'tcx>, } -pub fn place_to_string_for_capture(tcx: TyCtxt<'tcx>, place: &HirPlace<'tcx>) -> String { - let name = match place.base { - HirPlaceBase::Upvar(upvar_id) => tcx.hir().name(upvar_id.var_path.hir_id).to_string(), - _ => bug!("Capture_information should only contain upvars"), - }; - let mut curr_string = name; - - for (i, proj) in place.projections.iter().enumerate() { - match proj.kind { - HirProjectionKind::Deref => { - curr_string = format!("*{}", curr_string); - } - HirProjectionKind::Field(idx, variant) => match place.ty_before_projection(i).kind() { - ty::Adt(def, ..) => { - curr_string = format!( - "{}.{}", - curr_string, - def.variants[variant].fields[idx as usize].ident.name.as_str() - ); - } - ty::Tuple(_) => { - curr_string = format!("{}.{}", curr_string, idx); - } - _ => { - bug!( - "Field projection applied to a type other than Adt or Tuple: {:?}.", - place.ty_before_projection(i).kind() - ) - } - }, - proj => bug!("{:?} unexpected because it isn't captured", proj), - } - } - - curr_string.to_string() -} - /// Part of `MinCaptureInformationMap`; describes the capture kind (&, &mut, move) /// for a particular capture as well as identifying the part of the source code /// that triggered this capture to occur. @@ -910,37 +871,19 @@ impl<'tcx> Generics { // We could cache this as a property of `GenericParamCount`, but // the aim is to refactor this away entirely eventually and the // presence of this method will be a constant reminder. - let mut own_counts = GenericParamCount::default(); + let mut own_counts: GenericParamCount = Default::default(); for param in &self.params { match param.kind { GenericParamDefKind::Lifetime => own_counts.lifetimes += 1, GenericParamDefKind::Type { .. } => own_counts.types += 1, GenericParamDefKind::Const => own_counts.consts += 1, - } + }; } own_counts } - pub fn own_defaults(&self) -> GenericParamCount { - let mut own_defaults = GenericParamCount::default(); - - for param in &self.params { - match param.kind { - GenericParamDefKind::Lifetime => (), - GenericParamDefKind::Type { has_default, .. } => { - own_defaults.types += has_default as usize; - } - GenericParamDefKind::Const => { - // FIXME(const_generics:defaults) - } - } - } - - own_defaults - } - pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool { if self.own_requires_monomorphization() { return true; @@ -1069,14 +1012,14 @@ impl<'tcx> GenericPredicates<'tcx> { #[derive(Debug)] crate struct PredicateInner<'tcx> { - kind: Binder>, + kind: PredicateKind<'tcx>, flags: TypeFlags, /// See the comment for the corresponding field of [TyS]. outer_exclusive_binder: ty::DebruijnIndex, } #[cfg(target_arch = "x86_64")] -static_assert_size!(PredicateInner<'_>, 40); +static_assert_size!(PredicateInner<'_>, 48); #[derive(Clone, Copy, Lift)] pub struct Predicate<'tcx> { @@ -1099,9 +1042,59 @@ impl Hash for Predicate<'_> { impl<'tcx> Eq for Predicate<'tcx> {} impl<'tcx> Predicate<'tcx> { - /// Gets the inner `Binder>`. - pub fn kind(self) -> Binder> { - self.inner.kind + #[inline(always)] + pub fn kind(self) -> &'tcx PredicateKind<'tcx> { + &self.inner.kind + } + + /// Returns the inner `PredicateAtom`. + /// + /// The returned atom may contain unbound variables bound to binders skipped in this method. + /// It is safe to reapply binders to the given atom. + /// + /// Note that this method panics in case this predicate has unbound variables. + pub fn skip_binders(self) -> PredicateAtom<'tcx> { + match self.kind() { + &PredicateKind::ForAll(binder) => binder.skip_binder(), + &PredicateKind::Atom(atom) => { + debug_assert!(!atom.has_escaping_bound_vars()); + atom + } + } + } + + /// Returns the inner `PredicateAtom`. + /// + /// Note that this method does not check if the predicate has unbound variables. + /// + /// Rebinding the returned atom can causes the previously bound variables + /// to end up at the wrong binding level. + pub fn skip_binders_unchecked(self) -> PredicateAtom<'tcx> { + match self.kind() { + &PredicateKind::ForAll(binder) => binder.skip_binder(), + &PredicateKind::Atom(atom) => atom, + } + } + + /// Converts this to a `Binder>`. If the value was an + /// `Atom`, then it is not allowed to contain escaping bound vars. + pub fn bound_atom(self) -> Binder> { + match self.kind() { + &PredicateKind::ForAll(binder) => binder, + &PredicateKind::Atom(atom) => { + debug_assert!(!atom.has_escaping_bound_vars()); + Binder::dummy(atom) + } + } + } + + /// Allows using a `Binder>` even if the given predicate previously + /// contained unbound variables by shifting these variables outwards. + pub fn bound_atom_with_opt_escaping(self, tcx: TyCtxt<'tcx>) -> Binder> { + match self.kind() { + &PredicateKind::ForAll(binder) => binder, + &PredicateKind::Atom(atom) => Binder::wrap_nonbinding(tcx, atom), + } } } @@ -1123,6 +1116,14 @@ impl<'a, 'tcx> HashStable> for Predicate<'tcx> { #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] #[derive(HashStable, TypeFoldable)] pub enum PredicateKind<'tcx> { + /// `for<'a>: ...` + ForAll(Binder>), + Atom(PredicateAtom<'tcx>), +} + +#[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] +#[derive(HashStable, TypeFoldable)] +pub enum PredicateAtom<'tcx> { /// Corresponds to `where Foo: Bar`. `Foo` here would be /// the `Self` type of the trait reference and `A`, `B`, and `C` /// would be the type parameters. @@ -1168,6 +1169,21 @@ pub enum PredicateKind<'tcx> { TypeWellFormedFromEnv(Ty<'tcx>), } +impl<'tcx> Binder> { + /// Wraps `self` with the given qualifier if this predicate has any unbound variables. + pub fn potentially_quantified( + self, + tcx: TyCtxt<'tcx>, + qualifier: impl FnOnce(Binder>) -> PredicateKind<'tcx>, + ) -> Predicate<'tcx> { + match self.no_bound_vars() { + Some(atom) => PredicateKind::Atom(atom), + None => qualifier(self), + } + .to_predicate(tcx) + } +} + /// The crate outlives map is computed during typeck and contains the /// outlives of every item in the local crate. You should not use it /// directly, because to do so will make your pass dependent on the @@ -1253,9 +1269,13 @@ impl<'tcx> Predicate<'tcx> { // from the substitution and the value being substituted into, and // this trick achieves that). let substs = trait_ref.skip_binder().substs; - let pred = self.kind().skip_binder(); + let pred = self.skip_binders(); let new = pred.subst(tcx, substs); - tcx.reuse_or_mk_predicate(self, ty::Binder::bind(new)) + if new != pred { + ty::Binder::bind(new).potentially_quantified(tcx, PredicateKind::ForAll) + } else { + self + } } } @@ -1376,23 +1396,24 @@ pub trait ToPredicate<'tcx> { fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx>; } -impl ToPredicate<'tcx> for Binder> { +impl ToPredicate<'tcx> for PredicateKind<'tcx> { #[inline(always)] fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { tcx.mk_predicate(self) } } -impl ToPredicate<'tcx> for PredicateKind<'tcx> { +impl ToPredicate<'tcx> for PredicateAtom<'tcx> { #[inline(always)] fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { - tcx.mk_predicate(Binder::dummy(self)) + debug_assert!(!self.has_escaping_bound_vars(), "escaping bound vars for {:?}", self); + tcx.mk_predicate(PredicateKind::Atom(self)) } } impl<'tcx> ToPredicate<'tcx> for ConstnessAnd> { fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { - PredicateKind::Trait(ty::TraitPredicate { trait_ref: self.value }, self.constness) + PredicateAtom::Trait(ty::TraitPredicate { trait_ref: self.value }, self.constness) .to_predicate(tcx) } } @@ -1409,62 +1430,66 @@ impl<'tcx> ToPredicate<'tcx> for ConstnessAnd> { impl<'tcx> ToPredicate<'tcx> for ConstnessAnd> { fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { - self.value.map_bound(|value| PredicateKind::Trait(value, self.constness)).to_predicate(tcx) + self.value + .map_bound(|value| PredicateAtom::Trait(value, self.constness)) + .potentially_quantified(tcx, PredicateKind::ForAll) } } impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> { fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { - self.map_bound(PredicateKind::RegionOutlives).to_predicate(tcx) + self.map_bound(PredicateAtom::RegionOutlives) + .potentially_quantified(tcx, PredicateKind::ForAll) } } impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> { fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { - self.map_bound(PredicateKind::TypeOutlives).to_predicate(tcx) + self.map_bound(PredicateAtom::TypeOutlives) + .potentially_quantified(tcx, PredicateKind::ForAll) } } impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> { fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { - self.map_bound(PredicateKind::Projection).to_predicate(tcx) + self.map_bound(PredicateAtom::Projection).potentially_quantified(tcx, PredicateKind::ForAll) } } impl<'tcx> Predicate<'tcx> { pub fn to_opt_poly_trait_ref(self) -> Option>> { - let predicate = self.kind(); + let predicate = self.bound_atom(); match predicate.skip_binder() { - PredicateKind::Trait(t, constness) => { + PredicateAtom::Trait(t, constness) => { Some(ConstnessAnd { constness, value: predicate.rebind(t.trait_ref) }) } - PredicateKind::Projection(..) - | PredicateKind::Subtype(..) - | PredicateKind::RegionOutlives(..) - | PredicateKind::WellFormed(..) - | PredicateKind::ObjectSafe(..) - | PredicateKind::ClosureKind(..) - | PredicateKind::TypeOutlives(..) - | PredicateKind::ConstEvaluatable(..) - | PredicateKind::ConstEquate(..) - | PredicateKind::TypeWellFormedFromEnv(..) => None, + PredicateAtom::Projection(..) + | PredicateAtom::Subtype(..) + | PredicateAtom::RegionOutlives(..) + | PredicateAtom::WellFormed(..) + | PredicateAtom::ObjectSafe(..) + | PredicateAtom::ClosureKind(..) + | PredicateAtom::TypeOutlives(..) + | PredicateAtom::ConstEvaluatable(..) + | PredicateAtom::ConstEquate(..) + | PredicateAtom::TypeWellFormedFromEnv(..) => None, } } pub fn to_opt_type_outlives(self) -> Option> { - let predicate = self.kind(); + let predicate = self.bound_atom(); match predicate.skip_binder() { - PredicateKind::TypeOutlives(data) => Some(predicate.rebind(data)), - PredicateKind::Trait(..) - | PredicateKind::Projection(..) - | PredicateKind::Subtype(..) - | PredicateKind::RegionOutlives(..) - | PredicateKind::WellFormed(..) - | PredicateKind::ObjectSafe(..) - | PredicateKind::ClosureKind(..) - | PredicateKind::ConstEvaluatable(..) - | PredicateKind::ConstEquate(..) - | PredicateKind::TypeWellFormedFromEnv(..) => None, + PredicateAtom::TypeOutlives(data) => Some(predicate.rebind(data)), + PredicateAtom::Trait(..) + | PredicateAtom::Projection(..) + | PredicateAtom::Subtype(..) + | PredicateAtom::RegionOutlives(..) + | PredicateAtom::WellFormed(..) + | PredicateAtom::ObjectSafe(..) + | PredicateAtom::ClosureKind(..) + | PredicateAtom::ConstEvaluatable(..) + | PredicateAtom::ConstEquate(..) + | PredicateAtom::TypeWellFormedFromEnv(..) => None, } } } @@ -3025,10 +3050,8 @@ impl<'tcx> TyCtxt<'tcx> { self.trait_def(trait_def_id).has_auto_impl } - /// Returns layout of a generator. Layout might be unavailable if the - /// generator is tainted by errors. - pub fn generator_layout(self, def_id: DefId) -> Option<&'tcx GeneratorLayout<'tcx>> { - self.optimized_mir(def_id).generator_layout.as_ref() + pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> { + self.optimized_mir(def_id).generator_layout.as_ref().unwrap() } /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements. diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 8911de41c6d8e..893572785f76b 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -623,8 +623,12 @@ pub trait PrettyPrinter<'tcx>: p!("impl"); for (predicate, _) in bounds { let predicate = predicate.subst(self.tcx(), substs); - let bound_predicate = predicate.kind(); - if let ty::PredicateKind::Trait(pred, _) = bound_predicate.skip_binder() { + // Note: We can't use `to_opt_poly_trait_ref` here as `predicate` + // may contain unbound variables. We therefore do this manually. + // + // FIXME(lcnr): Find out why exactly this is the case :) + let bound_predicate = predicate.bound_atom_with_opt_escaping(self.tcx()); + if let ty::PredicateAtom::Trait(pred, _) = bound_predicate.skip_binder() { let trait_ref = bound_predicate.rebind(pred.trait_ref); // Don't print +Sized, but rather +?Sized if absent. if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() { @@ -2064,38 +2068,40 @@ define_print_and_forward_display! { } ty::Predicate<'tcx> { - let binder = self.kind(); - p!(print(binder)) + match self.kind() { + &ty::PredicateKind::Atom(atom) => p!(print(atom)), + ty::PredicateKind::ForAll(binder) => p!(print(binder)), + } } - ty::PredicateKind<'tcx> { + ty::PredicateAtom<'tcx> { match *self { - ty::PredicateKind::Trait(ref data, constness) => { + ty::PredicateAtom::Trait(ref data, constness) => { if let hir::Constness::Const = constness { p!("const "); } p!(print(data)) } - ty::PredicateKind::Subtype(predicate) => p!(print(predicate)), - ty::PredicateKind::RegionOutlives(predicate) => p!(print(predicate)), - ty::PredicateKind::TypeOutlives(predicate) => p!(print(predicate)), - ty::PredicateKind::Projection(predicate) => p!(print(predicate)), - ty::PredicateKind::WellFormed(arg) => p!(print(arg), " well-formed"), - ty::PredicateKind::ObjectSafe(trait_def_id) => { + ty::PredicateAtom::Subtype(predicate) => p!(print(predicate)), + ty::PredicateAtom::RegionOutlives(predicate) => p!(print(predicate)), + ty::PredicateAtom::TypeOutlives(predicate) => p!(print(predicate)), + ty::PredicateAtom::Projection(predicate) => p!(print(predicate)), + ty::PredicateAtom::WellFormed(arg) => p!(print(arg), " well-formed"), + ty::PredicateAtom::ObjectSafe(trait_def_id) => { p!("the trait `", print_def_path(trait_def_id, &[]), "` is object-safe") } - ty::PredicateKind::ClosureKind(closure_def_id, _closure_substs, kind) => { + ty::PredicateAtom::ClosureKind(closure_def_id, _closure_substs, kind) => { p!("the closure `", print_value_path(closure_def_id, &[]), write("` implements the trait `{}`", kind)) } - ty::PredicateKind::ConstEvaluatable(def, substs) => { + ty::PredicateAtom::ConstEvaluatable(def, substs) => { p!("the constant `", print_value_path(def.did, substs), "` can be evaluated") } - ty::PredicateKind::ConstEquate(c1, c2) => { + ty::PredicateAtom::ConstEquate(c1, c2) => { p!("the constant `", print(c1), "` equals `", print(c2), "`") } - ty::PredicateKind::TypeWellFormedFromEnv(ty) => { + ty::PredicateAtom::TypeWellFormedFromEnv(ty) => { p!("the type `", print(ty), "` is found in the environment") } } diff --git a/compiler/rustc_middle/src/ty/query/on_disk_cache.rs b/compiler/rustc_middle/src/ty/query/on_disk_cache.rs index cfe47004e01b6..abe58aacbb169 100644 --- a/compiler/rustc_middle/src/ty/query/on_disk_cache.rs +++ b/compiler/rustc_middle/src/ty/query/on_disk_cache.rs @@ -32,10 +32,8 @@ use std::mem; const TAG_FILE_FOOTER: u128 = 0xC0FFEE_C0FFEE_C0FFEE_C0FFEE_C0FFEE; -// A normal span encoded with both location information and a `SyntaxContext` -const TAG_FULL_SPAN: u8 = 0; -// A partial span with no location information, encoded only with a `SyntaxContext` -const TAG_PARTIAL_SPAN: u8 = 1; +const TAG_VALID_SPAN: u8 = 0; +const TAG_INVALID_SPAN: u8 = 1; const TAG_SYNTAX_CONTEXT: u8 = 0; const TAG_EXPN_DATA: u8 = 1; @@ -866,11 +864,10 @@ impl<'a, 'tcx> Decodable> for Span { fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Result { let tag: u8 = Decodable::decode(decoder)?; - if tag == TAG_PARTIAL_SPAN { - let ctxt = SyntaxContext::decode(decoder)?; - return Ok(DUMMY_SP.with_ctxt(ctxt)); + if tag == TAG_INVALID_SPAN { + return Ok(DUMMY_SP); } else { - debug_assert_eq!(tag, TAG_FULL_SPAN); + debug_assert_eq!(tag, TAG_VALID_SPAN); } let file_lo_index = SourceFileIndex::decode(decoder)?; @@ -989,7 +986,7 @@ struct CacheEncoder<'a, 'tcx, E: OpaqueEncoder> { tcx: TyCtxt<'tcx>, encoder: &'a mut E, type_shorthands: FxHashMap, usize>, - predicate_shorthands: FxHashMap, usize>, + predicate_shorthands: FxHashMap, usize>, interpret_allocs: FxIndexSet, source_map: CachingSourceMapView<'tcx>, file_to_file_index: FxHashMap<*const SourceFile, SourceFileIndex>, @@ -1060,29 +1057,24 @@ where { fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> { if *self == DUMMY_SP { - TAG_PARTIAL_SPAN.encode(s)?; - return SyntaxContext::root().encode(s); + return TAG_INVALID_SPAN.encode(s); } let span_data = self.data(); - let pos = s.source_map.byte_pos_to_line_and_col(span_data.lo); - let partial_span = match &pos { - Some((file_lo, _, _)) => !file_lo.contains(span_data.hi), - None => true, + let (file_lo, line_lo, col_lo) = match s.source_map.byte_pos_to_line_and_col(span_data.lo) { + Some(pos) => pos, + None => return TAG_INVALID_SPAN.encode(s), }; - if partial_span { - TAG_PARTIAL_SPAN.encode(s)?; - return span_data.ctxt.encode(s); + if !file_lo.contains(span_data.hi) { + return TAG_INVALID_SPAN.encode(s); } - let (file_lo, line_lo, col_lo) = pos.unwrap(); - let len = span_data.hi - span_data.lo; let source_file_index = s.source_file_index(file_lo); - TAG_FULL_SPAN.encode(s)?; + TAG_VALID_SPAN.encode(s)?; source_file_index.encode(s)?; line_lo.encode(s)?; col_lo.encode(s)?; @@ -1103,7 +1095,7 @@ where fn type_shorthands(&mut self) -> &mut FxHashMap, usize> { &mut self.type_shorthands } - fn predicate_shorthands(&mut self) -> &mut FxHashMap, usize> { + fn predicate_shorthands(&mut self) -> &mut FxHashMap, usize> { &mut self.predicate_shorthands } fn encode_alloc_id(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> { diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 44c173e356dfb..7a1ca6a6c2bfc 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -231,28 +231,37 @@ impl fmt::Debug for ty::Predicate<'tcx> { impl fmt::Debug for ty::PredicateKind<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - ty::PredicateKind::Trait(ref a, constness) => { + ty::PredicateKind::ForAll(binder) => write!(f, "ForAll({:?})", binder), + ty::PredicateKind::Atom(atom) => write!(f, "{:?}", atom), + } + } +} + +impl fmt::Debug for ty::PredicateAtom<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + ty::PredicateAtom::Trait(ref a, constness) => { if let hir::Constness::Const = constness { write!(f, "const ")?; } a.fmt(f) } - ty::PredicateKind::Subtype(ref pair) => pair.fmt(f), - ty::PredicateKind::RegionOutlives(ref pair) => pair.fmt(f), - ty::PredicateKind::TypeOutlives(ref pair) => pair.fmt(f), - ty::PredicateKind::Projection(ref pair) => pair.fmt(f), - ty::PredicateKind::WellFormed(data) => write!(f, "WellFormed({:?})", data), - ty::PredicateKind::ObjectSafe(trait_def_id) => { + ty::PredicateAtom::Subtype(ref pair) => pair.fmt(f), + ty::PredicateAtom::RegionOutlives(ref pair) => pair.fmt(f), + ty::PredicateAtom::TypeOutlives(ref pair) => pair.fmt(f), + ty::PredicateAtom::Projection(ref pair) => pair.fmt(f), + ty::PredicateAtom::WellFormed(data) => write!(f, "WellFormed({:?})", data), + ty::PredicateAtom::ObjectSafe(trait_def_id) => { write!(f, "ObjectSafe({:?})", trait_def_id) } - ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => { + ty::PredicateAtom::ClosureKind(closure_def_id, closure_substs, kind) => { write!(f, "ClosureKind({:?}, {:?}, {:?})", closure_def_id, closure_substs, kind) } - ty::PredicateKind::ConstEvaluatable(def_id, substs) => { + ty::PredicateAtom::ConstEvaluatable(def_id, substs) => { write!(f, "ConstEvaluatable({:?}, {:?})", def_id, substs) } - ty::PredicateKind::ConstEquate(c1, c2) => write!(f, "ConstEquate({:?}, {:?})", c1, c2), - ty::PredicateKind::TypeWellFormedFromEnv(ty) => { + ty::PredicateAtom::ConstEquate(c1, c2) => write!(f, "ConstEquate({:?}, {:?})", c1, c2), + ty::PredicateAtom::TypeWellFormedFromEnv(ty) => { write!(f, "TypeWellFormedFromEnv({:?})", ty) } } @@ -476,36 +485,46 @@ impl<'a, 'tcx> Lift<'tcx> for ty::PredicateKind<'a> { type Lifted = ty::PredicateKind<'tcx>; fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option { match self { - ty::PredicateKind::Trait(data, constness) => { - tcx.lift(data).map(|data| ty::PredicateKind::Trait(data, constness)) + ty::PredicateKind::ForAll(binder) => tcx.lift(binder).map(ty::PredicateKind::ForAll), + ty::PredicateKind::Atom(atom) => tcx.lift(atom).map(ty::PredicateKind::Atom), + } + } +} + +impl<'a, 'tcx> Lift<'tcx> for ty::PredicateAtom<'a> { + type Lifted = ty::PredicateAtom<'tcx>; + fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option { + match self { + ty::PredicateAtom::Trait(data, constness) => { + tcx.lift(data).map(|data| ty::PredicateAtom::Trait(data, constness)) } - ty::PredicateKind::Subtype(data) => tcx.lift(data).map(ty::PredicateKind::Subtype), - ty::PredicateKind::RegionOutlives(data) => { - tcx.lift(data).map(ty::PredicateKind::RegionOutlives) + ty::PredicateAtom::Subtype(data) => tcx.lift(data).map(ty::PredicateAtom::Subtype), + ty::PredicateAtom::RegionOutlives(data) => { + tcx.lift(data).map(ty::PredicateAtom::RegionOutlives) } - ty::PredicateKind::TypeOutlives(data) => { - tcx.lift(data).map(ty::PredicateKind::TypeOutlives) + ty::PredicateAtom::TypeOutlives(data) => { + tcx.lift(data).map(ty::PredicateAtom::TypeOutlives) } - ty::PredicateKind::Projection(data) => { - tcx.lift(data).map(ty::PredicateKind::Projection) + ty::PredicateAtom::Projection(data) => { + tcx.lift(data).map(ty::PredicateAtom::Projection) } - ty::PredicateKind::WellFormed(ty) => tcx.lift(ty).map(ty::PredicateKind::WellFormed), - ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => { + ty::PredicateAtom::WellFormed(ty) => tcx.lift(ty).map(ty::PredicateAtom::WellFormed), + ty::PredicateAtom::ClosureKind(closure_def_id, closure_substs, kind) => { tcx.lift(closure_substs).map(|closure_substs| { - ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) + ty::PredicateAtom::ClosureKind(closure_def_id, closure_substs, kind) }) } - ty::PredicateKind::ObjectSafe(trait_def_id) => { - Some(ty::PredicateKind::ObjectSafe(trait_def_id)) + ty::PredicateAtom::ObjectSafe(trait_def_id) => { + Some(ty::PredicateAtom::ObjectSafe(trait_def_id)) } - ty::PredicateKind::ConstEvaluatable(def_id, substs) => { - tcx.lift(substs).map(|substs| ty::PredicateKind::ConstEvaluatable(def_id, substs)) + ty::PredicateAtom::ConstEvaluatable(def_id, substs) => { + tcx.lift(substs).map(|substs| ty::PredicateAtom::ConstEvaluatable(def_id, substs)) } - ty::PredicateKind::ConstEquate(c1, c2) => { - tcx.lift((c1, c2)).map(|(c1, c2)| ty::PredicateKind::ConstEquate(c1, c2)) + ty::PredicateAtom::ConstEquate(c1, c2) => { + tcx.lift((c1, c2)).map(|(c1, c2)| ty::PredicateAtom::ConstEquate(c1, c2)) } - ty::PredicateKind::TypeWellFormedFromEnv(ty) => { - tcx.lift(ty).map(ty::PredicateKind::TypeWellFormedFromEnv) + ty::PredicateAtom::TypeWellFormedFromEnv(ty) => { + tcx.lift(ty).map(ty::PredicateAtom::TypeWellFormedFromEnv) } } } @@ -1017,12 +1036,12 @@ impl<'tcx> TypeFoldable<'tcx> for ty::Region<'tcx> { impl<'tcx> TypeFoldable<'tcx> for ty::Predicate<'tcx> { fn super_fold_with>(self, folder: &mut F) -> Self { - let new = self.inner.kind.fold_with(folder); + let new = ty::PredicateKind::super_fold_with(self.inner.kind, folder); folder.tcx().reuse_or_mk_predicate(self, new) } fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { - self.inner.kind.visit_with(visitor) + ty::PredicateKind::super_visit_with(&self.inner.kind, visitor) } fn visit_with>(&self, visitor: &mut V) -> ControlFlow { diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index e53977b5eb978..744c7a541a53c 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -605,7 +605,7 @@ impl<'tcx> GeneratorSubsts<'tcx> { #[inline] pub fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range { // FIXME requires optimized MIR - let num_variants = tcx.generator_layout(def_id).unwrap().variant_fields.len(); + let num_variants = tcx.generator_layout(def_id).variant_fields.len(); VariantIdx::new(0)..VariantIdx::new(num_variants) } @@ -666,7 +666,7 @@ impl<'tcx> GeneratorSubsts<'tcx> { def_id: DefId, tcx: TyCtxt<'tcx>, ) -> impl Iterator> + Captures<'tcx>> { - let layout = tcx.generator_layout(def_id).unwrap(); + let layout = tcx.generator_layout(def_id); layout.variant_fields.iter().map(move |variant| { variant.iter().map(move |field| layout.field_tys[*field].subst(tcx, self.substs)) }) @@ -955,9 +955,7 @@ impl<'tcx> PolyExistentialTraitRef<'tcx> { /// erase, or otherwise "discharge" these bound vars, we change the /// type from `Binder` to just `T` (see /// e.g., `liberate_late_bound_regions`). -/// -/// `Decodable` and `Encodable` are implemented for `Binder` using the `impl_binder_encode_decode!` macro. -#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] pub struct Binder(T); impl Binder { diff --git a/compiler/rustc_mir/src/borrow_check/borrow_set.rs b/compiler/rustc_mir/src/borrow_check/borrow_set.rs index 288eda32e414e..b4299fbc5a1fe 100644 --- a/compiler/rustc_mir/src/borrow_check/borrow_set.rs +++ b/compiler/rustc_mir/src/borrow_check/borrow_set.rs @@ -149,7 +149,7 @@ impl<'tcx> BorrowSet<'tcx> { } crate fn activations_at_location(&self, location: Location) -> &[BorrowIndex] { - self.activation_map.get(&location).map_or(&[], |activations| &activations[..]) + self.activation_map.get(&location).map(|activations| &activations[..]).unwrap_or(&[]) } crate fn len(&self) -> usize { diff --git a/compiler/rustc_mir/src/borrow_check/diagnostics/conflict_errors.rs b/compiler/rustc_mir/src/borrow_check/diagnostics/conflict_errors.rs index 8f41bfae2fdf5..db02ee67910b2 100644 --- a/compiler/rustc_mir/src/borrow_check/diagnostics/conflict_errors.rs +++ b/compiler/rustc_mir/src/borrow_check/diagnostics/conflict_errors.rs @@ -141,7 +141,6 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { self.add_moved_or_invoked_closure_note(location, used_place, &mut err); let mut is_loop_move = false; - let mut in_pattern = false; for move_site in &move_site_vec { let move_out = self.move_data.moves[(*move_site).moi]; @@ -257,7 +256,6 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { "ref ".to_string(), Applicability::MachineApplicable, ); - in_pattern = true; } if let Some(DesugaringKind::ForLoop(_)) = move_span.desugaring_kind() { @@ -304,8 +302,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { let place = &self.move_data.move_paths[mpi].place; let ty = place.ty(self.body, self.infcx.tcx).ty; - // If we're in pattern, we do nothing in favor of the previous suggestion (#80913). - if is_loop_move & !in_pattern { + if is_loop_move { if let ty::Ref(_, _, hir::Mutability::Mut) = ty.kind() { // We have a `&mut` ref, we need to reborrow on each iteration (#62112). err.span_suggestion_verbose( @@ -1321,30 +1318,21 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { Applicability::MachineApplicable, ); - match category { + let msg = match category { ConstraintCategory::Return(_) | ConstraintCategory::OpaqueType => { - let msg = format!("{} is returned here", kind); - err.span_note(constraint_span, &msg); + format!("{} is returned here", kind) } ConstraintCategory::CallArgument => { fr_name.highlight_region_name(&mut err); - if matches!(use_span.generator_kind(), Some(GeneratorKind::Async(_))) { - err.note( - "async blocks are not executed immediately and must either take a \ - reference or ownership of outside variables they use", - ); - } else { - let msg = format!("function requires argument type to outlive `{}`", fr_name); - err.span_note(constraint_span, &msg); - } + format!("function requires argument type to outlive `{}`", fr_name) } _ => bug!( "report_escaping_closure_capture called with unexpected constraint \ category: `{:?}`", category ), - } - + }; + err.span_note(constraint_span, &msg); err } @@ -1616,17 +1604,20 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { fn classify_drop_access_kind(&self, place: PlaceRef<'tcx>) -> StorageDeadOrDrop<'tcx> { let tcx = self.infcx.tcx; - match place.last_projection() { - None => StorageDeadOrDrop::LocalStorageDead, - Some((place_base, elem)) => { + match place.projection { + [] => StorageDeadOrDrop::LocalStorageDead, + [proj_base @ .., elem] => { // FIXME(spastorino) make this iterate - let base_access = self.classify_drop_access_kind(place_base); + let base_access = self.classify_drop_access_kind(PlaceRef { + local: place.local, + projection: proj_base, + }); match elem { ProjectionElem::Deref => match base_access { StorageDeadOrDrop::LocalStorageDead | StorageDeadOrDrop::BoxedStorageDead => { assert!( - place_base.ty(self.body, tcx).ty.is_box(), + Place::ty_from(place.local, proj_base, self.body, tcx).ty.is_box(), "Drop of value behind a reference or raw pointer" ); StorageDeadOrDrop::BoxedStorageDead @@ -1634,7 +1625,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { StorageDeadOrDrop::Destructor(_) => base_access, }, ProjectionElem::Field(..) | ProjectionElem::Downcast(..) => { - let base_ty = place_base.ty(self.body, tcx).ty; + let base_ty = Place::ty_from(place.local, proj_base, self.body, tcx).ty; match base_ty.kind() { ty::Adt(def, _) if def.has_dtor(tcx) => { // Report the outermost adt with a destructor @@ -1649,6 +1640,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { _ => base_access, } } + ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } | ProjectionElem::Index(_) => base_access, diff --git a/compiler/rustc_mir/src/borrow_check/diagnostics/explain_borrow.rs b/compiler/rustc_mir/src/borrow_check/diagnostics/explain_borrow.rs index a3d09c3a8d4c1..eccb6168229c2 100644 --- a/compiler/rustc_mir/src/borrow_check/diagnostics/explain_borrow.rs +++ b/compiler/rustc_mir/src/borrow_check/diagnostics/explain_borrow.rs @@ -75,7 +75,7 @@ impl BorrowExplanation { LaterUseKind::FakeLetRead => "stored here", LaterUseKind::Other => "used here", }; - if !borrow_span.map_or(false, |sp| sp.overlaps(var_or_use_span)) { + if !borrow_span.map(|sp| sp.overlaps(var_or_use_span)).unwrap_or(false) { err.span_label( var_or_use_span, format!("{}borrow later {}", borrow_desc, message), diff --git a/compiler/rustc_mir/src/borrow_check/diagnostics/mod.rs b/compiler/rustc_mir/src/borrow_check/diagnostics/mod.rs index 6d98bf554f1cf..4ebc1cdca6059 100644 --- a/compiler/rustc_mir/src/borrow_check/diagnostics/mod.rs +++ b/compiler/rustc_mir/src/borrow_check/diagnostics/mod.rs @@ -103,7 +103,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { let did = did.expect_local(); let hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(did); - if let Some((span, hir_place)) = + if let Some((span, name)) = self.infcx.tcx.typeck(did).closure_kind_origins().get(hir_id) { diag.span_note( @@ -111,7 +111,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { &format!( "closure cannot be invoked more than once because it moves the \ variable `{}` out of its environment", - ty::place_to_string_for_capture(self.infcx.tcx, hir_place) + name, ), ); return; @@ -127,7 +127,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { let did = did.expect_local(); let hir_id = self.infcx.tcx.hir().local_def_id_to_hir_id(did); - if let Some((span, hir_place)) = + if let Some((span, name)) = self.infcx.tcx.typeck(did).closure_kind_origins().get(hir_id) { diag.span_note( @@ -135,7 +135,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { &format!( "closure cannot be moved more than once as it is not `Copy` due to \ moving the variable `{}` out of its environment", - ty::place_to_string_for_capture(self.infcx.tcx, hir_place) + name ), ); } @@ -338,7 +338,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { self.describe_field(PlaceRef { local, projection: proj_base }, field) } ProjectionElem::Downcast(_, variant_index) => { - let base_ty = place.ty(self.body, self.infcx.tcx).ty; + let base_ty = + Place::ty_from(place.local, place.projection, self.body, self.infcx.tcx).ty; self.describe_field_from_ty(&base_ty, field, Some(*variant_index)) } ProjectionElem::Field(_, field_type) => { @@ -472,7 +473,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { // If we didn't find an overloaded deref or index, then assume it's a // built in deref and check the type of the base. - let base_ty = deref_base.ty(self.body, tcx).ty; + let base_ty = Place::ty_from(deref_base.local, deref_base.projection, self.body, tcx).ty; if base_ty.is_unsafe_ptr() { BorrowedContentSource::DerefRawPointer } else if base_ty.is_mutable_ptr() { diff --git a/compiler/rustc_mir/src/borrow_check/diagnostics/region_errors.rs b/compiler/rustc_mir/src/borrow_check/diagnostics/region_errors.rs index ab83fc8dfaf75..78da43c31c0fb 100644 --- a/compiler/rustc_mir/src/borrow_check/diagnostics/region_errors.rs +++ b/compiler/rustc_mir/src/borrow_check/diagnostics/region_errors.rs @@ -590,8 +590,8 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { let mut found = false; for (bound, _) in bounds { - if let ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_, r)) = - bound.kind().skip_binder() + if let ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(_, r)) = + bound.skip_binders() { let r = r.subst(self.infcx.tcx, substs); if let ty::RegionKind::ReStatic = r { diff --git a/compiler/rustc_mir/src/borrow_check/path_utils.rs b/compiler/rustc_mir/src/borrow_check/path_utils.rs index fa3ae2367e08e..934729553a73b 100644 --- a/compiler/rustc_mir/src/borrow_check/path_utils.rs +++ b/compiler/rustc_mir/src/borrow_check/path_utils.rs @@ -147,25 +147,27 @@ pub(crate) fn is_upvar_field_projection( place_ref: PlaceRef<'tcx>, body: &Body<'tcx>, ) -> Option { - let mut place_ref = place_ref; + let mut place_projection = place_ref.projection; let mut by_ref = false; - if let Some((place_base, ProjectionElem::Deref)) = place_ref.last_projection() { - place_ref = place_base; + if let [proj_base @ .., ProjectionElem::Deref] = place_projection { + place_projection = proj_base; by_ref = true; } - match place_ref.last_projection() { - Some((place_base, ProjectionElem::Field(field, _ty))) => { - let base_ty = place_base.ty(body, tcx).ty; + match place_projection { + [base @ .., ProjectionElem::Field(field, _ty)] => { + let base_ty = Place::ty_from(place_ref.local, base, body, tcx).ty; + if (base_ty.is_closure() || base_ty.is_generator()) && (!by_ref || upvars[field.index()].by_ref) { - Some(field) + Some(*field) } else { None } } + _ => None, } } diff --git a/compiler/rustc_mir/src/borrow_check/type_check/input_output.rs b/compiler/rustc_mir/src/borrow_check/type_check/input_output.rs index 157959b115947..b7d22fab3dde6 100644 --- a/compiler/rustc_mir/src/borrow_check/type_check/input_output.rs +++ b/compiler/rustc_mir/src/borrow_check/type_check/input_output.rs @@ -39,8 +39,10 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { user_provided_sig = None; } else { let typeck_results = self.tcx().typeck(mir_def_id); - user_provided_sig = typeck_results.user_provided_sigs.get(&mir_def_id.to_def_id()).map( - |user_provided_poly_sig| { + user_provided_sig = match typeck_results.user_provided_sigs.get(&mir_def_id.to_def_id()) + { + None => None, + Some(user_provided_poly_sig) => { // Instantiate the canonicalized variables from // user-provided signature (e.g., the `_` in the code // above) with fresh variables. @@ -52,16 +54,18 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { // Replace the bound items in the fn sig with fresh // variables, so that they represent the view from // "inside" the closure. - self.infcx - .replace_bound_vars_with_fresh_vars( - body.span, - LateBoundRegionConversionTime::FnCall, - poly_sig, - ) - .0 - }, - ); - } + Some( + self.infcx + .replace_bound_vars_with_fresh_vars( + body.span, + LateBoundRegionConversionTime::FnCall, + poly_sig, + ) + .0, + ) + } + } + }; debug!( "equate_inputs_and_outputs: normalized_input_tys = {:?}, local_decls = {:?}", diff --git a/compiler/rustc_mir/src/borrow_check/type_check/mod.rs b/compiler/rustc_mir/src/borrow_check/type_check/mod.rs index fb9820e853f8f..5aad7523c8903 100644 --- a/compiler/rustc_mir/src/borrow_check/type_check/mod.rs +++ b/compiler/rustc_mir/src/borrow_check/type_check/mod.rs @@ -1014,7 +1014,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { } self.prove_predicate( - ty::PredicateKind::WellFormed(inferred_ty.into()).to_predicate(self.tcx()), + ty::PredicateAtom::WellFormed(inferred_ty.into()).to_predicate(self.tcx()), Locations::All(span), ConstraintCategory::TypeAnnotation, ); @@ -1266,7 +1266,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { obligations.obligations.push(traits::Obligation::new( ObligationCause::dummy(), param_env, - ty::PredicateKind::WellFormed(revealed_ty.into()).to_predicate(infcx.tcx), + ty::PredicateAtom::WellFormed(revealed_ty.into()).to_predicate(infcx.tcx), )); obligations.add( infcx @@ -1611,7 +1611,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { self.check_call_dest(body, term, &sig, destination, term_location); self.prove_predicates( - sig.inputs_and_output.iter().map(|ty| ty::PredicateKind::WellFormed(ty.into())), + sig.inputs_and_output.iter().map(|ty| ty::PredicateAtom::WellFormed(ty.into())), term_location.to_locations(), ConstraintCategory::Boring, ); @@ -2694,7 +2694,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { category: ConstraintCategory, ) { self.prove_predicates( - Some(ty::PredicateKind::Trait( + Some(ty::PredicateAtom::Trait( ty::TraitPredicate { trait_ref }, hir::Constness::NotConst, )), diff --git a/compiler/rustc_mir/src/borrow_check/universal_regions.rs b/compiler/rustc_mir/src/borrow_check/universal_regions.rs index 02d951b70e28d..c1a0d9856b7ea 100644 --- a/compiler/rustc_mir/src/borrow_check/universal_regions.rs +++ b/compiler/rustc_mir/src/borrow_check/universal_regions.rs @@ -788,13 +788,13 @@ fn for_each_late_bound_region_defined_on<'tcx>( fn_def_id: DefId, mut f: impl FnMut(ty::Region<'tcx>), ) { - if let Some((owner, late_bounds)) = tcx.is_late_bound_map(fn_def_id.expect_local()) { - for &late_bound in late_bounds.iter() { - let hir_id = HirId { owner, local_id: late_bound }; + if let Some(late_bounds) = tcx.is_late_bound_map(fn_def_id.expect_local()) { + for late_bound in late_bounds.iter() { + let hir_id = HirId { owner: fn_def_id.expect_local(), local_id: *late_bound }; let name = tcx.hir().name(hir_id); let region_def_id = tcx.hir().local_def_id(hir_id); let liberated_region = tcx.mk_region(ty::ReFree(ty::FreeRegion { - scope: owner.to_def_id(), + scope: fn_def_id, bound_region: ty::BoundRegionKind::BrNamed(region_def_id.to_def_id(), name), })); f(liberated_region); diff --git a/compiler/rustc_mir/src/const_eval/fn_queries.rs b/compiler/rustc_mir/src/const_eval/fn_queries.rs index 8c18dfcb8d0cc..aca822a05bde9 100644 --- a/compiler/rustc_mir/src/const_eval/fn_queries.rs +++ b/compiler/rustc_mir/src/const_eval/fn_queries.rs @@ -126,7 +126,7 @@ fn is_const_impl_raw(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { matches!( node, hir::Node::Item(hir::Item { - kind: hir::ItemKind::Impl(hir::Impl { constness: hir::Constness::Const, .. }), + kind: hir::ItemKind::Impl { constness: hir::Constness::Const, .. }, .. }) ) diff --git a/compiler/rustc_mir/src/dataflow/move_paths/builder.rs b/compiler/rustc_mir/src/dataflow/move_paths/builder.rs index ee78ff00c9b2b..ab7fadac91e39 100644 --- a/compiler/rustc_mir/src/dataflow/move_paths/builder.rs +++ b/compiler/rustc_mir/src/dataflow/move_paths/builder.rs @@ -518,10 +518,14 @@ impl<'b, 'a, 'tcx> Gatherer<'b, 'a, 'tcx> { // Check if we are assigning into a field of a union, if so, lookup the place // of the union so it is marked as initialized again. - if let Some((place_base, ProjectionElem::Field(_, _))) = place.last_projection() { - if let ty::Adt(def, _) = place_base.ty(self.builder.body, self.builder.tcx).ty.kind() { + if let [proj_base @ .., ProjectionElem::Field(_, _)] = place.projection { + if let ty::Adt(def, _) = + Place::ty_from(place.local, proj_base, self.builder.body, self.builder.tcx) + .ty + .kind() + { if def.is_union() { - place = place_base; + place = PlaceRef { local: place.local, projection: proj_base } } } } diff --git a/compiler/rustc_mir/src/interpret/eval_context.rs b/compiler/rustc_mir/src/interpret/eval_context.rs index 7e9594dd6bfd7..6d7781671d8cc 100644 --- a/compiler/rustc_mir/src/interpret/eval_context.rs +++ b/compiler/rustc_mir/src/interpret/eval_context.rs @@ -370,7 +370,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { #[inline(always)] pub fn cur_span(&self) -> Span { - self.stack().last().map_or(self.tcx.span, |f| f.current_span()) + self.stack().last().map(|f| f.current_span()).unwrap_or(self.tcx.span) } #[inline(always)] diff --git a/compiler/rustc_mir/src/interpret/util.rs b/compiler/rustc_mir/src/interpret/util.rs index 89f34cd07aa4b..c2165db278fa0 100644 --- a/compiler/rustc_mir/src/interpret/util.rs +++ b/compiler/rustc_mir/src/interpret/util.rs @@ -47,7 +47,8 @@ where let index = index .try_into() .expect("more generic parameters than can fit into a `u32`"); - let is_used = unused_params.contains(index).map_or(true, |unused| !unused); + let is_used = + unused_params.contains(index).map(|unused| !unused).unwrap_or(true); // Only recurse when generic parameters in fns, closures and generators // are used and require substitution. match (is_used, subst.needs_subst()) { diff --git a/compiler/rustc_mir/src/monomorphize/collector.rs b/compiler/rustc_mir/src/monomorphize/collector.rs index 75f80f69beafc..6370ead97e798 100644 --- a/compiler/rustc_mir/src/monomorphize/collector.rs +++ b/compiler/rustc_mir/src/monomorphize/collector.rs @@ -823,7 +823,7 @@ fn should_codegen_locally<'tcx>(tcx: TyCtxt<'tcx>, instance: &Instance<'tcx>) -> } if !tcx.is_mir_available(def_id) { - bug!("no MIR available for {:?}", def_id); + bug!("cannot create local mono-item for {:?}", def_id) } true @@ -1146,8 +1146,8 @@ fn create_mono_items_for_default_impls<'tcx>( output: &mut Vec>>, ) { match item.kind { - hir::ItemKind::Impl(ref impl_) => { - for param in impl_.generics.params { + hir::ItemKind::Impl { ref generics, ref items, .. } => { + for param in generics.params { match param.kind { hir::GenericParamKind::Lifetime { .. } => {} hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => { @@ -1167,7 +1167,7 @@ fn create_mono_items_for_default_impls<'tcx>( let param_env = ty::ParamEnv::reveal_all(); let trait_ref = tcx.normalize_erasing_regions(param_env, trait_ref); let overridden_methods: FxHashSet<_> = - impl_.items.iter().map(|iiref| iiref.ident.normalize_to_macros_2_0()).collect(); + items.iter().map(|iiref| iiref.ident.normalize_to_macros_2_0()).collect(); for method in tcx.provided_trait_methods(trait_ref.def_id) { if overridden_methods.contains(&method.ident.normalize_to_macros_2_0()) { continue; diff --git a/compiler/rustc_mir/src/monomorphize/partitioning/mod.rs b/compiler/rustc_mir/src/monomorphize/partitioning/mod.rs index b9fcd32250dcf..db6d3b2d912d6 100644 --- a/compiler/rustc_mir/src/monomorphize/partitioning/mod.rs +++ b/compiler/rustc_mir/src/monomorphize/partitioning/mod.rs @@ -247,7 +247,8 @@ where for (mono_item, linkage) in cgu.items() { let symbol_name = mono_item.symbol_name(tcx).name; let symbol_hash_start = symbol_name.rfind('h'); - let symbol_hash = symbol_hash_start.map_or("", |i| &symbol_name[i..]); + let symbol_hash = + symbol_hash_start.map(|i| &symbol_name[i..]).unwrap_or(""); debug!( " - {} [{:?}] [{}] estimated size {}", diff --git a/compiler/rustc_mir/src/shim.rs b/compiler/rustc_mir/src/shim.rs index b740dfaca328d..aa5835686a291 100644 --- a/compiler/rustc_mir/src/shim.rs +++ b/compiler/rustc_mir/src/shim.rs @@ -165,7 +165,7 @@ fn build_drop_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, ty: Option>) let mut body = new_body(source, blocks, local_decls_for_sig(&sig, span), sig.inputs().len(), span); - if ty.is_some() { + if let Some(..) = ty { // The first argument (index 0), but add 1 for the return value. let dropee_ptr = Place::from(Local::new(1 + 0)); if tcx.sess.opts.debugging_opts.mir_emit_retag { diff --git a/compiler/rustc_mir/src/transform/check_consts/ops.rs b/compiler/rustc_mir/src/transform/check_consts/ops.rs index 99ffb0edce9e1..9e90a7519cf2c 100644 --- a/compiler/rustc_mir/src/transform/check_consts/ops.rs +++ b/compiler/rustc_mir/src/transform/check_consts/ops.rs @@ -72,7 +72,7 @@ impl NonConstOp for FnCallIndirect { /// A function call where the callee is not marked as `const`. #[derive(Debug)] -pub struct FnCallNonConst; +pub struct FnCallNonConst(pub DefId); impl NonConstOp for FnCallNonConst { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { struct_span_err!( diff --git a/compiler/rustc_mir/src/transform/check_consts/qualifs.rs b/compiler/rustc_mir/src/transform/check_consts/qualifs.rs index 0ce1980f10a11..c66d3ed76df90 100644 --- a/compiler/rustc_mir/src/transform/check_consts/qualifs.rs +++ b/compiler/rustc_mir/src/transform/check_consts/qualifs.rs @@ -174,10 +174,14 @@ where Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => { // Special-case reborrows to be more like a copy of the reference. - if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() { - let base_ty = place_base.ty(cx.body, cx.tcx).ty; + if let &[ref proj_base @ .., ProjectionElem::Deref] = place.projection.as_ref() { + let base_ty = Place::ty_from(place.local, proj_base, cx.body, cx.tcx).ty; if let ty::Ref(..) = base_ty.kind() { - return in_place::(cx, in_local, place_base); + return in_place::( + cx, + in_local, + PlaceRef { local: place.local, projection: proj_base }, + ); } } @@ -205,9 +209,9 @@ where Q: Qualif, F: FnMut(Local) -> bool, { - let mut place = place; - while let Some((place_base, elem)) = place.last_projection() { - match elem { + let mut projection = place.projection; + while let &[ref proj_base @ .., proj_elem] = projection { + match proj_elem { ProjectionElem::Index(index) if in_local(index) => return true, ProjectionElem::Deref @@ -218,16 +222,16 @@ where | ProjectionElem::Index(_) => {} } - let base_ty = place_base.ty(cx.body, cx.tcx); - let proj_ty = base_ty.projection_ty(cx.tcx, elem).ty; + let base_ty = Place::ty_from(place.local, proj_base, cx.body, cx.tcx); + let proj_ty = base_ty.projection_ty(cx.tcx, proj_elem).ty; if !Q::in_any_value_of_ty(cx, proj_ty) { return false; } - place = place_base; + projection = proj_base; } - assert!(place.projection.is_empty()); + assert!(projection.is_empty()); in_local(place.local) } diff --git a/compiler/rustc_mir/src/transform/check_consts/validation.rs b/compiler/rustc_mir/src/transform/check_consts/validation.rs index 08d969b27bea5..d1c07d1051d2f 100644 --- a/compiler/rustc_mir/src/transform/check_consts/validation.rs +++ b/compiler/rustc_mir/src/transform/check_consts/validation.rs @@ -411,24 +411,24 @@ impl Validator<'mir, 'tcx> { loop { let predicates = tcx.predicates_of(current); for (predicate, _) in predicates.predicates { - match predicate.kind().skip_binder() { - ty::PredicateKind::RegionOutlives(_) - | ty::PredicateKind::TypeOutlives(_) - | ty::PredicateKind::WellFormed(_) - | ty::PredicateKind::Projection(_) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) - | ty::PredicateKind::TypeWellFormedFromEnv(..) => continue, - ty::PredicateKind::ObjectSafe(_) => { + match predicate.skip_binders() { + ty::PredicateAtom::RegionOutlives(_) + | ty::PredicateAtom::TypeOutlives(_) + | ty::PredicateAtom::WellFormed(_) + | ty::PredicateAtom::Projection(_) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) + | ty::PredicateAtom::TypeWellFormedFromEnv(..) => continue, + ty::PredicateAtom::ObjectSafe(_) => { bug!("object safe predicate on function: {:#?}", predicate) } - ty::PredicateKind::ClosureKind(..) => { + ty::PredicateAtom::ClosureKind(..) => { bug!("closure kind predicate on function: {:#?}", predicate) } - ty::PredicateKind::Subtype(_) => { + ty::PredicateAtom::Subtype(_) => { bug!("subtype predicate on function: {:#?}", predicate) } - ty::PredicateKind::Trait(pred, constness) => { + ty::PredicateAtom::Trait(pred, constness) => { if Some(pred.def_id()) == tcx.lang_items().sized_trait() { continue; } @@ -789,10 +789,10 @@ impl Visitor<'tcx> for Validator<'mir, 'tcx> { } } - #[instrument(skip(self))] fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) { use rustc_target::spec::abi::Abi::RustIntrinsic; + trace!("visit_terminator: terminator={:?} location={:?}", terminator, location); self.super_terminator(terminator, location); match &terminator.kind { @@ -816,9 +816,8 @@ impl Visitor<'tcx> for Validator<'mir, 'tcx> { // Attempting to call a trait method? if let Some(trait_id) = tcx.trait_of_item(callee) { - trace!("attempting to call a trait method"); if !self.tcx.features().const_trait_impl { - self.check_op(ops::FnCallNonConst); + self.check_op(ops::FnCallNonConst(callee)); return; } @@ -872,26 +871,25 @@ impl Visitor<'tcx> for Validator<'mir, 'tcx> { return; } - let is_intrinsic = tcx.fn_sig(callee).abi() == RustIntrinsic; - // HACK: This is to "unstabilize" the `transmute` intrinsic // within const fns. `transmute` is allowed in all other const contexts. // This won't really scale to more intrinsics or functions. Let's allow const // transmutes in const fn before we add more hacks to this. - if is_intrinsic && tcx.item_name(callee) == sym::transmute { + if tcx.fn_sig(callee).abi() == RustIntrinsic + && tcx.item_name(callee) == sym::transmute + { self.check_op(ops::Transmute); return; } if !tcx.is_const_fn_raw(callee) { - self.check_op(ops::FnCallNonConst); + self.check_op(ops::FnCallNonConst(callee)); return; } // If the `const fn` we are trying to call is not const-stable, ensure that we have // the proper feature gate enabled. if let Some(gate) = is_unstable_const_fn(tcx, callee) { - trace!(?gate, "calling unstable const fn"); if self.span.allows_unstable(gate) { return; } @@ -906,14 +904,12 @@ impl Visitor<'tcx> for Validator<'mir, 'tcx> { // If this crate is not using stability attributes, or the caller is not claiming to be a // stable `const fn`, that is all that is required. if !self.ccx.is_const_stable_const_fn() { - trace!("crate not using stability attributes or caller not stably const"); return; } // Otherwise, we are something const-stable calling a const-unstable fn. if super::rustc_allow_const_fn_unstable(tcx, caller, gate) { - trace!("rustc_allow_const_fn_unstable gate active"); return; } @@ -927,16 +923,10 @@ impl Visitor<'tcx> for Validator<'mir, 'tcx> { let callee_is_unstable_unmarked = tcx.lookup_const_stability(callee).is_none() && tcx.lookup_stability(callee).map_or(false, |s| s.level.is_unstable()); if callee_is_unstable_unmarked { - trace!("callee_is_unstable_unmarked"); - // We do not use `const` modifiers for intrinsic "functions", as intrinsics are - // `extern` funtions, and these have no way to get marked `const`. So instead we - // use `rustc_const_(un)stable` attributes to mean that the intrinsic is `const` - if self.ccx.is_const_stable_const_fn() || is_intrinsic { + if self.ccx.is_const_stable_const_fn() { self.check_op(ops::FnCallUnstable(callee, None)); - return; } } - trace!("permitting call"); } // Forbid all `Drop` terminators unless the place being dropped is a local with no @@ -1017,26 +1007,27 @@ fn place_as_reborrow( body: &Body<'tcx>, place: Place<'tcx>, ) -> Option<&'a [PlaceElem<'tcx>]> { - match place.as_ref().last_projection() { - Some((place_base, ProjectionElem::Deref)) => { - // A borrow of a `static` also looks like `&(*_1)` in the MIR, but `_1` is a `const` - // that points to the allocation for the static. Don't treat these as reborrows. - if body.local_decls[place_base.local].is_ref_to_static() { - None - } else { - // Ensure the type being derefed is a reference and not a raw pointer. - // - // This is sufficient to prevent an access to a `static mut` from being marked as a - // reborrow, even if the check above were to disappear. - let inner_ty = place_base.ty(body, tcx).ty; - match inner_ty.kind() { - ty::Ref(..) => Some(place_base.projection), - _ => None, - } - } + place.projection.split_last().and_then(|(outermost, inner)| { + if outermost != &ProjectionElem::Deref { + return None; } - _ => None, - } + + // A borrow of a `static` also looks like `&(*_1)` in the MIR, but `_1` is a `const` + // that points to the allocation for the static. Don't treat these as reborrows. + if body.local_decls[place.local].is_ref_to_static() { + return None; + } + + // Ensure the type being derefed is a reference and not a raw pointer. + // + // This is sufficient to prevent an access to a `static mut` from being marked as a + // reborrow, even if the check above were to disappear. + let inner_ty = Place::ty_from(place.local, inner, body, tcx).ty; + match inner_ty.kind() { + ty::Ref(..) => Some(inner), + _ => None, + } + }) } fn is_int_bool_or_char(ty: Ty<'_>) -> bool { diff --git a/compiler/rustc_mir/src/transform/check_unsafety.rs b/compiler/rustc_mir/src/transform/check_unsafety.rs index f0472758dfb8e..e64955c4986ce 100644 --- a/compiler/rustc_mir/src/transform/check_unsafety.rs +++ b/compiler/rustc_mir/src/transform/check_unsafety.rs @@ -223,6 +223,13 @@ impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> { // Check for raw pointer `Deref`. for (base, proj) in place.iter_projections() { if proj == ProjectionElem::Deref { + let source_info = self.source_info; // Backup source_info so we can restore it later. + if base.projection.is_empty() && decl.internal { + // Internal locals are used in the `move_val_init` desugaring. + // We want to check unsafety against the source info of the + // desugaring, rather than the source info of the RHS. + self.source_info = self.body.local_decls[place.local].source_info; + } let base_ty = base.ty(self.body, self.tcx).ty; if base_ty.is_unsafe_ptr() { self.require_unsafe( @@ -230,6 +237,7 @@ impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> { UnsafetyViolationDetails::DerefOfRawPointer, ) } + self.source_info = source_info; // Restore backed-up source_info. } } @@ -399,13 +407,17 @@ impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> { place: Place<'tcx>, is_mut_use: bool, ) { - for (place_base, elem) in place.iter_projections().rev() { + let mut cursor = place.projection.as_ref(); + while let &[ref proj_base @ .., elem] = cursor { + cursor = proj_base; + match elem { // Modifications behind a dereference don't affect the value of // the pointer. ProjectionElem::Deref => return, ProjectionElem::Field(..) => { - let ty = place_base.ty(&self.body.local_decls, self.tcx).ty; + let ty = + Place::ty_from(place.local, proj_base, &self.body.local_decls, self.tcx).ty; if let ty::Adt(def, _) = ty.kind() { if self.tcx.layout_scalar_valid_range(def.did) != (Bound::Unbounded, Bound::Unbounded) @@ -568,23 +580,24 @@ fn is_enclosed( tcx: TyCtxt<'_>, used_unsafe: &FxHashSet, id: hir::HirId, - unsafe_op_in_unsafe_fn_allowed: bool, -) -> Option<(&'static str, hir::HirId)> { +) -> Option<(String, hir::HirId)> { let parent_id = tcx.hir().get_parent_node(id); if parent_id != id { if used_unsafe.contains(&parent_id) { - Some(("block", parent_id)) + Some(("block".to_string(), parent_id)) } else if let Some(Node::Item(&hir::Item { kind: hir::ItemKind::Fn(ref sig, _, _), .. })) = tcx.hir().find(parent_id) { - if sig.header.unsafety == hir::Unsafety::Unsafe && unsafe_op_in_unsafe_fn_allowed { - Some(("fn", parent_id)) + if sig.header.unsafety == hir::Unsafety::Unsafe + && !tcx.features().unsafe_block_in_unsafe_fn + { + Some(("fn".to_string(), parent_id)) } else { None } } else { - is_enclosed(tcx, used_unsafe, parent_id, unsafe_op_in_unsafe_fn_allowed) + is_enclosed(tcx, used_unsafe, parent_id) } } else { None @@ -597,9 +610,7 @@ fn report_unused_unsafe(tcx: TyCtxt<'_>, used_unsafe: &FxHashSet, id let msg = "unnecessary `unsafe` block"; let mut db = lint.build(msg); db.span_label(span, msg); - if let Some((kind, id)) = - is_enclosed(tcx, used_unsafe, id, unsafe_op_in_unsafe_fn_allowed(tcx, id)) - { + if let Some((kind, id)) = is_enclosed(tcx, used_unsafe, id) { db.span_label( tcx.sess.source_map().guess_head_span(tcx.hir().span(id)), format!("because it's nested under this `unsafe` {}", kind), diff --git a/compiler/rustc_mir/src/transform/const_prop.rs b/compiler/rustc_mir/src/transform/const_prop.rs index 354d213689ec2..a311e262dd4df 100644 --- a/compiler/rustc_mir/src/transform/const_prop.rs +++ b/compiler/rustc_mir/src/transform/const_prop.rs @@ -139,7 +139,7 @@ impl<'tcx> MirPass<'tcx> for ConstProp { Default::default(), body.arg_count, Default::default(), - body.span, + tcx.def_span(def_id), body.generator_kind, ); diff --git a/compiler/rustc_mir/src/transform/function_item_references.rs b/compiler/rustc_mir/src/transform/function_item_references.rs index 8d02ac6d9b774..7c8c349da1d6c 100644 --- a/compiler/rustc_mir/src/transform/function_item_references.rs +++ b/compiler/rustc_mir/src/transform/function_item_references.rs @@ -5,7 +5,7 @@ use rustc_middle::mir::*; use rustc_middle::ty::{ self, subst::{GenericArgKind, Subst, SubstsRef}, - PredicateKind, Ty, TyCtxt, TyS, + PredicateAtom, Ty, TyCtxt, TyS, }; use rustc_session::lint::builtin::FUNCTION_ITEM_REFERENCES; use rustc_span::{symbol::sym, Span}; @@ -105,7 +105,7 @@ impl<'a, 'tcx> FunctionItemRefChecker<'a, 'tcx> { let param_env = self.tcx.param_env(def_id); let bounds = param_env.caller_bounds(); for bound in bounds { - if let Some(bound_ty) = self.is_pointer_trait(&bound.kind().skip_binder()) { + if let Some(bound_ty) = self.is_pointer_trait(&bound.skip_binders()) { // Get the argument types as they appear in the function signature. let arg_defs = self.tcx.fn_sig(def_id).skip_binder().inputs(); for (arg_num, arg_def) in arg_defs.iter().enumerate() { @@ -131,8 +131,8 @@ impl<'a, 'tcx> FunctionItemRefChecker<'a, 'tcx> { } /// If the given predicate is the trait `fmt::Pointer`, returns the bound parameter type. - fn is_pointer_trait(&self, bound: &PredicateKind<'tcx>) -> Option> { - if let ty::PredicateKind::Trait(predicate, _) = bound { + fn is_pointer_trait(&self, bound: &PredicateAtom<'tcx>) -> Option> { + if let ty::PredicateAtom::Trait(predicate, _) = bound { if self.tcx.is_diagnostic_item(sym::pointer_trait, predicate.def_id()) { Some(predicate.trait_ref.self_ty()) } else { diff --git a/compiler/rustc_mir/src/transform/inline.rs b/compiler/rustc_mir/src/transform/inline.rs index 07e637b88f9c0..52350c5d07844 100644 --- a/compiler/rustc_mir/src/transform/inline.rs +++ b/compiler/rustc_mir/src/transform/inline.rs @@ -382,7 +382,7 @@ impl Inliner<'tcx> { // Cost of the var is the size in machine-words, if we know // it. if let Some(size) = type_size_of(tcx, self.param_env, ty) { - cost += ((size + ptr_size - 1) / ptr_size) as usize; + cost += (size / ptr_size) as usize; } else { cost += UNKNOWN_SIZE_COST; } diff --git a/compiler/rustc_mir/src/transform/instcombine.rs b/compiler/rustc_mir/src/transform/instcombine.rs index b0c70372b161a..990ca313c5ddc 100644 --- a/compiler/rustc_mir/src/transform/instcombine.rs +++ b/compiler/rustc_mir/src/transform/instcombine.rs @@ -277,9 +277,11 @@ impl OptimizationFinder<'b, 'tcx> { impl Visitor<'tcx> for OptimizationFinder<'b, 'tcx> { fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) { if let Rvalue::Ref(_, _, place) = rvalue { - if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() { + if let PlaceRef { local, projection: &[ref proj_base @ .., ProjectionElem::Deref] } = + place.as_ref() + { // The dereferenced place must have type `&_`. - let ty = place_base.ty(self.body, self.tcx).ty; + let ty = Place::ty_from(local, proj_base, self.body, self.tcx).ty; if let ty::Ref(_, _, Mutability::Not) = ty.kind() { self.optimizations.and_stars.insert(location); } diff --git a/compiler/rustc_mir/src/transform/promote_consts.rs b/compiler/rustc_mir/src/transform/promote_consts.rs index cac5abb1059a8..ea92e23e9bffb 100644 --- a/compiler/rustc_mir/src/transform/promote_consts.rs +++ b/compiler/rustc_mir/src/transform/promote_consts.rs @@ -445,50 +445,43 @@ impl<'tcx> Validator<'_, 'tcx> { } fn validate_place(&self, place: PlaceRef<'tcx>) -> Result<(), Unpromotable> { - match place.last_projection() { - None => self.validate_local(place.local), - Some((place_base, elem)) => { + match place { + PlaceRef { local, projection: [] } => self.validate_local(local), + PlaceRef { local, projection: [proj_base @ .., elem] } => { // Validate topmost projection, then recurse. - match elem { + match *elem { ProjectionElem::Deref => { let mut promotable = false; - // The `is_empty` predicate is introduced to exclude the case - // where the projection operations are [ .field, * ]. - // The reason is because promotion will be illegal if field - // accesses precede the dereferencing. - // Discussion can be found at - // https://github.com/rust-lang/rust/pull/74945#discussion_r463063247 - // There may be opportunity for generalization, but this needs to be - // accounted for. - if place_base.projection.is_empty() { - // This is a special treatment for cases like *&STATIC where STATIC is a - // global static variable. - // This pattern is generated only when global static variables are directly - // accessed and is qualified for promotion safely. - if let TempState::Defined { location, .. } = - self.temps[place_base.local] + // This is a special treatment for cases like *&STATIC where STATIC is a + // global static variable. + // This pattern is generated only when global static variables are directly + // accessed and is qualified for promotion safely. + if let TempState::Defined { location, .. } = self.temps[local] { + let def_stmt = + self.body[location.block].statements.get(location.statement_index); + if let Some(Statement { + kind: + StatementKind::Assign(box (_, Rvalue::Use(Operand::Constant(c)))), + .. + }) = def_stmt { - let def_stmt = self.body[location.block] - .statements - .get(location.statement_index); - if let Some(Statement { - kind: - StatementKind::Assign(box ( - _, - Rvalue::Use(Operand::Constant(c)), - )), - .. - }) = def_stmt - { - if let Some(did) = c.check_static_ptr(self.tcx) { - // Evaluating a promoted may not read statics except if it got - // promoted from a static (this is a CTFE check). So we - // can only promote static accesses inside statics. - if let Some(hir::ConstContext::Static(..)) = self.const_kind + if let Some(did) = c.check_static_ptr(self.tcx) { + // Evaluating a promoted may not read statics except if it got + // promoted from a static (this is a CTFE check). So we + // can only promote static accesses inside statics. + if let Some(hir::ConstContext::Static(..)) = self.const_kind { + // The `is_empty` predicate is introduced to exclude the case + // where the projection operations are [ .field, * ]. + // The reason is because promotion will be illegal if field + // accesses precede the dereferencing. + // Discussion can be found at + // https://github.com/rust-lang/rust/pull/74945#discussion_r463063247 + // There may be opportunity for generalization, but this needs to be + // accounted for. + if proj_base.is_empty() + && !self.tcx.is_thread_local_static(did) { - if !self.tcx.is_thread_local_static(did) { - promotable = true; - } + promotable = true; } } } @@ -509,7 +502,8 @@ impl<'tcx> Validator<'_, 'tcx> { } ProjectionElem::Field(..) => { - let base_ty = place_base.ty(self.body, self.tcx).ty; + let base_ty = + Place::ty_from(place.local, proj_base, self.body, self.tcx).ty; if let Some(def) = base_ty.ty_adt_def() { // No promotion of union field accesses. if def.is_union() { @@ -519,7 +513,7 @@ impl<'tcx> Validator<'_, 'tcx> { } } - self.validate_place(place_base) + self.validate_place(PlaceRef { local: place.local, projection: proj_base }) } } } @@ -666,11 +660,13 @@ impl<'tcx> Validator<'_, 'tcx> { Rvalue::AddressOf(_, place) => { // We accept `&raw *`, i.e., raw reborrows -- creating a raw pointer is // no problem, only using it is. - if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() - { - let base_ty = place_base.ty(self.body, self.tcx).ty; + if let [proj_base @ .., ProjectionElem::Deref] = place.projection.as_ref() { + let base_ty = Place::ty_from(place.local, proj_base, self.body, self.tcx).ty; if let ty::Ref(..) = base_ty.kind() { - return self.validate_place(place_base); + return self.validate_place(PlaceRef { + local: place.local, + projection: proj_base, + }); } } return Err(Unpromotable); @@ -679,12 +675,12 @@ impl<'tcx> Validator<'_, 'tcx> { Rvalue::Ref(_, kind, place) => { // Special-case reborrows to be more like a copy of the reference. let mut place_simplified = place.as_ref(); - if let Some((place_base, ProjectionElem::Deref)) = - place_simplified.last_projection() - { - let base_ty = place_base.ty(self.body, self.tcx).ty; + if let [proj_base @ .., ProjectionElem::Deref] = &place_simplified.projection { + let base_ty = + Place::ty_from(place_simplified.local, proj_base, self.body, self.tcx).ty; if let ty::Ref(..) = base_ty.kind() { - place_simplified = place_base; + place_simplified = + PlaceRef { local: place_simplified.local, projection: proj_base }; } } diff --git a/compiler/rustc_mir/src/transform/simplify.rs b/compiler/rustc_mir/src/transform/simplify.rs index 289231e52cb41..b7c9a3a8688ec 100644 --- a/compiler/rustc_mir/src/transform/simplify.rs +++ b/compiler/rustc_mir/src/transform/simplify.rs @@ -61,7 +61,7 @@ impl<'tcx> MirPass<'tcx> for SimplifyCfg { } fn run_pass(&self, _tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { - debug!("SimplifyCfg({:?}) - simplifying {:?}", self.label, body.source); + debug!("SimplifyCfg({:?}) - simplifying {:?}", self.label, body); simplify_cfg(body); } } diff --git a/compiler/rustc_mir/src/transform/simplify_try.rs b/compiler/rustc_mir/src/transform/simplify_try.rs index 05a88828070fb..a3459887a9a75 100644 --- a/compiler/rustc_mir/src/transform/simplify_try.rs +++ b/compiler/rustc_mir/src/transform/simplify_try.rs @@ -113,7 +113,7 @@ fn get_arm_identity_info<'a, 'tcx>( test: impl Fn(&'a Statement<'tcx>) -> bool, mut action: impl FnMut(usize, &'a Statement<'tcx>), ) { - while stmt_iter.peek().map_or(false, |(_, stmt)| test(stmt)) { + while stmt_iter.peek().map(|(_, stmt)| test(stmt)).unwrap_or(false) { let (idx, stmt) = stmt_iter.next().unwrap(); action(idx, stmt); @@ -635,7 +635,7 @@ impl<'a, 'tcx> SimplifyBranchSameOptimizationFinder<'a, 'tcx> { }) .peekable(); - let bb_first = iter_bbs_reachable.peek().map_or(&targets_and_values[0], |(idx, _)| *idx); + let bb_first = iter_bbs_reachable.peek().map(|(idx, _)| *idx).unwrap_or(&targets_and_values[0]); let mut all_successors_equivalent = StatementEquality::TrivialEqual; // All successor basic blocks must be equal or contain statements that are pairwise considered equal. diff --git a/compiler/rustc_mir/src/util/alignment.rs b/compiler/rustc_mir/src/util/alignment.rs index f567c9cfaab86..a0728a6a63015 100644 --- a/compiler/rustc_mir/src/util/alignment.rs +++ b/compiler/rustc_mir/src/util/alignment.rs @@ -38,12 +38,15 @@ fn is_within_packed<'tcx, L>(tcx: TyCtxt<'tcx>, local_decls: &L, place: Place<'t where L: HasLocalDecls<'tcx>, { - for (place_base, elem) in place.iter_projections().rev() { + let mut cursor = place.projection.as_ref(); + while let &[ref proj_base @ .., elem] = cursor { + cursor = proj_base; + match elem { // encountered a Deref, which is ABI-aligned ProjectionElem::Deref => break, ProjectionElem::Field(..) => { - let ty = place_base.ty(local_decls, tcx).ty; + let ty = Place::ty_from(place.local, proj_base, local_decls, tcx).ty; match ty.kind() { ty::Adt(def, _) if def.repr.packed() => return true, _ => {} diff --git a/compiler/rustc_mir_build/src/build/expr/as_place.rs b/compiler/rustc_mir_build/src/build/expr/as_place.rs index c11b8f7459389..cf2e4e8916d0a 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_place.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_place.rs @@ -531,7 +531,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { | ExprKind::Borrow { .. } | ExprKind::AddressOf { .. } | ExprKind::Match { .. } - | ExprKind::If { .. } | ExprKind::Loop { .. } | ExprKind::Block { .. } | ExprKind::Assign { .. } diff --git a/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs b/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs index 55bdbcfc5b916..3f381f3f15e8e 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs @@ -251,7 +251,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { | ExprKind::StaticRef { .. } | ExprKind::Block { .. } | ExprKind::Match { .. } - | ExprKind::If { .. } | ExprKind::NeverToAny { .. } | ExprKind::Use { .. } | ExprKind::Borrow { .. } diff --git a/compiler/rustc_mir_build/src/build/expr/category.rs b/compiler/rustc_mir_build/src/build/expr/category.rs index 9320b5810e396..8561170856fd4 100644 --- a/compiler/rustc_mir_build/src/build/expr/category.rs +++ b/compiler/rustc_mir_build/src/build/expr/category.rs @@ -45,7 +45,6 @@ impl Category { ExprKind::LogicalOp { .. } | ExprKind::Match { .. } - | ExprKind::If { .. } | ExprKind::NeverToAny { .. } | ExprKind::Use { .. } | ExprKind::Adt { .. } diff --git a/compiler/rustc_mir_build/src/build/expr/into.rs b/compiler/rustc_mir_build/src/build/expr/into.rs index 639f2bbc6e05f..09281799041ee 100644 --- a/compiler/rustc_mir_build/src/build/expr/into.rs +++ b/compiler/rustc_mir_build/src/build/expr/into.rs @@ -10,7 +10,9 @@ use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_hir as hir; use rustc_middle::middle::region; use rustc_middle::mir::*; -use rustc_middle::ty::{CanonicalUserTypeAnnotation}; +use rustc_middle::ty::{self, CanonicalUserTypeAnnotation}; +use rustc_span::symbol::sym; +use rustc_target::spec::abi::Abi; use std::slice; @@ -67,40 +69,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ExprKind::Match { scrutinee, arms } => { this.match_expr(destination, scope, expr_span, block, scrutinee, arms) } - ExprKind::If { cond, then, else_opt } => { - let place = unpack!(block = this.as_temp(block, Some(this.local_scope()), cond, Mutability::Mut)); - let operand = Operand::Move(Place::from(place)); - - let mut then_block = this.cfg.start_new_block(); - let mut else_block = this.cfg.start_new_block(); - let term = TerminatorKind::if_(this.hir.tcx(), operand, then_block, else_block); - this.cfg.terminate(block, source_info, term); - - unpack!(then_block = this.into(destination, scope, then_block, then)); - else_block = if let Some(else_opt) = else_opt { - unpack!(this.into(destination, None, else_block, else_opt)) - } else { - // Body of the `if` expression without an `else` clause must return `()`, thus - // we implicitly generate a `else {}` if it is not specified. - let correct_si = this.source_info(expr_span.shrink_to_hi()); - this.cfg.push_assign_unit(else_block, correct_si, destination, this.hir.tcx()); - else_block - }; - - let join_block = this.cfg.start_new_block(); - this.cfg.terminate( - then_block, - source_info, - TerminatorKind::Goto { target: join_block }, - ); - this.cfg.terminate( - else_block, - source_info, - TerminatorKind::Goto { target: join_block }, - ); - - join_block.unit() - }, ExprKind::NeverToAny { source } => { let source = this.hir.mirror(source); let is_call = matches!(source.kind, ExprKind::Call { .. } | ExprKind::InlineAsm { .. }); @@ -217,41 +185,79 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { }, ) } - ExprKind::Call { ty: _, fun, args, from_hir_call, fn_span } => { - let fun = unpack!(block = this.as_local_operand(block, fun)); - let args: Vec<_> = args - .into_iter() - .map(|arg| unpack!(block = this.as_local_call_operand(block, arg))) - .collect(); - - let success = this.cfg.start_new_block(); - - this.record_operands_moved(&args); - - debug!("into_expr: fn_span={:?}", fn_span); - - this.cfg.terminate( - block, - source_info, - TerminatorKind::Call { - func: fun, - args, - cleanup: None, - // FIXME(varkor): replace this with an uninhabitedness-based check. - // This requires getting access to the current module to call - // `tcx.is_ty_uninhabited_from`, which is currently tricky to do. - destination: if expr.ty.is_never() { - None + ExprKind::Call { ty, fun, args, from_hir_call, fn_span } => { + let intrinsic = match *ty.kind() { + ty::FnDef(def_id, _) => { + let f = ty.fn_sig(this.hir.tcx()); + if f.abi() == Abi::RustIntrinsic || f.abi() == Abi::PlatformIntrinsic { + Some(this.hir.tcx().item_name(def_id)) } else { - Some((destination, success)) + None + } + } + _ => None, + }; + let fun = unpack!(block = this.as_local_operand(block, fun)); + if let Some(sym::move_val_init) = intrinsic { + // `move_val_init` has "magic" semantics - the second argument is + // always evaluated "directly" into the first one. + + let mut args = args.into_iter(); + let ptr = args.next().expect("0 arguments to `move_val_init`"); + let val = args.next().expect("1 argument to `move_val_init`"); + assert!(args.next().is_none(), ">2 arguments to `move_val_init`"); + + let ptr = this.hir.mirror(ptr); + let ptr_ty = ptr.ty; + // Create an *internal* temp for the pointer, so that unsafety + // checking won't complain about the raw pointer assignment. + let ptr_temp = this + .local_decls + .push(LocalDecl::with_source_info(ptr_ty, source_info).internal()); + let ptr_temp = Place::from(ptr_temp); + // No need for a scope, ptr_temp doesn't need drop + let block = unpack!(this.into(ptr_temp, None, block, ptr)); + // Maybe we should provide a scope here so that + // `move_val_init` wouldn't leak on panic even with an + // arbitrary `val` expression, but `schedule_drop`, + // borrowck and drop elaboration all prevent us from + // dropping `ptr_temp.deref()`. + this.into(this.hir.tcx().mk_place_deref(ptr_temp), None, block, val) + } else { + let args: Vec<_> = args + .into_iter() + .map(|arg| unpack!(block = this.as_local_call_operand(block, arg))) + .collect(); + + let success = this.cfg.start_new_block(); + + this.record_operands_moved(&args); + + debug!("into_expr: fn_span={:?}", fn_span); + + this.cfg.terminate( + block, + source_info, + TerminatorKind::Call { + func: fun, + args, + cleanup: None, + // FIXME(varkor): replace this with an uninhabitedness-based check. + // This requires getting access to the current module to call + // `tcx.is_ty_uninhabited_from`, which is currently tricky to do. + destination: if expr.ty.is_never() { + None + } else { + Some((destination, success)) + }, + from_hir_call, + fn_span, }, - from_hir_call, - fn_span, - }, - ); - this.diverge_from(block); - schedule_drop(this); - success.unit() + ); + this.diverge_from(block); + schedule_drop(this); + success.unit() + } } ExprKind::Use { source } => this.into(destination, scope, block, source), ExprKind::Borrow { arg, borrow_kind } => { diff --git a/compiler/rustc_mir_build/src/build/matches/simplify.rs b/compiler/rustc_mir_build/src/build/matches/simplify.rs index f30745d71859d..705266d4a0bd8 100644 --- a/compiler/rustc_mir_build/src/build/matches/simplify.rs +++ b/compiler/rustc_mir_build/src/build/matches/simplify.rs @@ -55,7 +55,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // * the bindings from the previous iteration of the loop is prepended to the bindings from // the current iteration (in the implementation this is done by mem::swap and extend) // * after all iterations, these new bindings are then appended to the bindings that were - // preexisting (i.e. `candidate.binding` when the function was called). + // prexisting (i.e. `candidate.binding` when the function was called). // // example: // candidate.bindings = [1, 2, 3] diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index 595458702e9c9..417f9bded0988 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -537,11 +537,6 @@ fn make_mirror_unadjusted<'a, 'tcx>( }, Err(err) => bug!("invalid loop id for continue: {}", err), }, - hir::ExprKind::If(cond, then, else_opt) => ExprKind::If { - cond: cond.to_ref(), - then: then.to_ref(), - else_opt: else_opt.map(|el| el.to_ref()), - }, hir::ExprKind::Match(ref discr, ref arms, _) => ExprKind::Match { scrutinee: discr.to_ref(), arms: arms.iter().map(|a| convert_arm(cx, a)).collect(), @@ -818,7 +813,8 @@ fn convert_path_expr<'a, 'tcx>( let item_id = cx.tcx.hir().get_parent_node(hir_id); let item_def_id = cx.tcx.hir().local_def_id(item_id); let generics = cx.tcx.generics_of(item_def_id); - let index = generics.param_def_id_to_index[&def_id]; + let local_def_id = cx.tcx.hir().local_def_id(hir_id); + let index = generics.param_def_id_to_index[&local_def_id.to_def_id()]; let name = cx.tcx.hir().name(hir_id); let val = ty::ConstKind::Param(ty::ParamConst::new(index, name)); ExprKind::Literal { diff --git a/compiler/rustc_mir_build/src/thir/mod.rs b/compiler/rustc_mir_build/src/thir/mod.rs index ed3d3927825af..ace9cad4d2996 100644 --- a/compiler/rustc_mir_build/src/thir/mod.rs +++ b/compiler/rustc_mir_build/src/thir/mod.rs @@ -139,11 +139,6 @@ crate enum ExprKind<'tcx> { Box { value: ExprRef<'tcx>, }, - If { - cond: ExprRef<'tcx>, - then: ExprRef<'tcx>, - else_opt: Option>, - }, Call { ty: Ty<'tcx>, fun: ExprRef<'tcx>, diff --git a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs index 397706851cb79..a70c1a28176cd 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -403,7 +403,7 @@ fn report_arm_reachability<'p, 'tcx>( match is_useful { NotUseful => { match source { - hir::MatchSource::WhileDesugar => bug!(), + hir::MatchSource::IfDesugar { .. } | hir::MatchSource::WhileDesugar => bug!(), hir::MatchSource::IfLetDesugar { .. } | hir::MatchSource::WhileLetDesugar => { // Check which arm we're on. diff --git a/compiler/rustc_mir_build/src/thir/pattern/usefulness.rs b/compiler/rustc_mir_build/src/thir/pattern/usefulness.rs index d7c08a2d1af6b..83fee380ccce7 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/usefulness.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/usefulness.rs @@ -952,7 +952,7 @@ fn is_useful<'p, 'tcx>( assert!(rows.iter().all(|r| r.len() == v.len())); // FIXME(Nadrieril): Hack to work around type normalization issues (see #72476). - let ty = matrix.heads().next().map_or(v.head().ty, |r| r.ty); + let ty = matrix.heads().next().map(|r| r.ty).unwrap_or(v.head().ty); let pcx = PatCtxt { cx, ty, span: v.head().span, is_top_level }; debug!("is_useful_expand_first_col: ty={:#?}, expanding {:#?}", pcx.ty, v.head()); diff --git a/compiler/rustc_parse/src/parser/attr.rs b/compiler/rustc_parse/src/parser/attr.rs index 1b26fb3337043..fae09fa6fec65 100644 --- a/compiler/rustc_parse/src/parser/attr.rs +++ b/compiler/rustc_parse/src/parser/attr.rs @@ -89,7 +89,7 @@ impl<'a> Parser<'a> { inner_parse_policy, self.token ); let lo = self.token.span; - self.collect_tokens(|this| { + let ((item, style, span), tokens) = self.collect_tokens(|this| { if this.eat(&token::Pound) { let style = if this.eat(&token::Not) { ast::AttrStyle::Inner @@ -107,13 +107,15 @@ impl<'a> Parser<'a> { this.error_on_forbidden_inner_attr(attr_sp, inner_parse_policy); } - Ok(attr::mk_attr_from_item(item, None, style, attr_sp)) + Ok((item, style, attr_sp)) } else { let token_str = pprust::token_to_string(&this.token); let msg = &format!("expected `#`, found `{}`", token_str); Err(this.struct_span_err(this.token.span, msg)) } - }) + })?; + + Ok(attr::mk_attr_from_item(item, tokens, style, span)) } pub(super) fn error_on_forbidden_inner_attr(&self, attr_sp: Span, policy: InnerAttrPolicy<'_>) { @@ -163,7 +165,13 @@ impl<'a> Parser<'a> { let args = this.parse_attr_args()?; Ok(ast::AttrItem { path, args, tokens: None }) }; - if capture_tokens { self.collect_tokens(do_parse) } else { do_parse(self) }? + if capture_tokens { + let (mut item, tokens) = self.collect_tokens(do_parse)?; + item.tokens = tokens; + item + } else { + do_parse(self)? + } }) } diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 35435baea7019..98c7b9a63a55f 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -511,7 +511,7 @@ impl<'a> Parser<'a> { // // `x.foo::>>(3)` let parsed_angle_bracket_args = - segment.args.as_ref().map_or(false, |args| args.is_angle_bracketed()); + segment.args.as_ref().map(|args| args.is_angle_bracketed()).unwrap_or(false); debug!( "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}", diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index 6db415ead415c..f4332e4548a19 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -472,8 +472,7 @@ impl<'a> Parser<'a> { /// Parses a prefix-unary-operator expr. fn parse_prefix_expr(&mut self, attrs: Option) -> PResult<'a, P> { let attrs = self.parse_or_use_outer_attributes(attrs)?; - let needs_tokens = super::attr::maybe_needs_tokens(&attrs); - let do_parse = |this: &mut Parser<'a>| { + self.maybe_collect_tokens(super::attr::maybe_needs_tokens(&attrs), |this| { let lo = this.token.span; // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr() let (hi, ex) = match this.token.uninterpolate().kind { @@ -489,8 +488,7 @@ impl<'a> Parser<'a> { _ => return this.parse_dot_or_call_expr(Some(attrs)), }?; Ok(this.mk_expr(lo.to(hi), ex, attrs)) - }; - if needs_tokens { self.collect_tokens(do_parse) } else { do_parse(self) } + }) } fn parse_prefix_expr_common(&mut self, lo: Span) -> PResult<'a, (Span, P)> { @@ -1127,6 +1125,20 @@ impl<'a> Parser<'a> { } } + fn maybe_collect_tokens( + &mut self, + needs_tokens: bool, + f: impl FnOnce(&mut Self) -> PResult<'a, P>, + ) -> PResult<'a, P> { + if needs_tokens { + let (mut expr, tokens) = self.collect_tokens(f)?; + expr.tokens = tokens; + Ok(expr) + } else { + f(self) + } + } + fn parse_lit_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { let lo = self.token.span; match self.parse_opt_lit() { diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index 810ae61307c19..4fcc9edb7d91b 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -125,7 +125,19 @@ impl<'a> Parser<'a> { item }; - let item = if needs_tokens { self.collect_tokens(parse_item) } else { parse_item(self) }?; + let (mut item, tokens) = if needs_tokens { + let (item, tokens) = self.collect_tokens(parse_item)?; + (item, tokens) + } else { + (parse_item(self)?, None) + }; + if let Some(item) = &mut item { + // If we captured tokens during parsing (due to encountering an `NtItem`), + // use those instead + if item.tokens.is_none() { + item.tokens = tokens; + } + } self.unclosed_delims.append(&mut unclosed_delims); Ok(item) diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index 5d7ea5b8d578e..45964b1c988ed 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -19,8 +19,8 @@ use rustc_ast::token::{self, DelimToken, Token, TokenKind}; use rustc_ast::tokenstream::{self, DelimSpan, LazyTokenStream, Spacing}; use rustc_ast::tokenstream::{CreateTokenStream, TokenStream, TokenTree, TreeAndSpacing}; use rustc_ast::DUMMY_NODE_ID; -use rustc_ast::{self as ast, AnonConst, AttrStyle, AttrVec, Const, CrateSugar, Extern, HasTokens}; -use rustc_ast::{Async, Expr, ExprKind, MacArgs, MacDelimiter, Mutability, StrLit, Unsafe}; +use rustc_ast::{self as ast, AnonConst, AttrStyle, AttrVec, Const, CrateSugar, Extern, Unsafe}; +use rustc_ast::{Async, Expr, ExprKind, MacArgs, MacDelimiter, Mutability, StrLit}; use rustc_ast::{Visibility, VisibilityKind}; use rustc_ast_pretty::pprust; use rustc_data_structures::sync::Lrc; @@ -1234,10 +1234,10 @@ impl<'a> Parser<'a> { /// This restriction shouldn't be an issue in practice, /// since this function is used to record the tokens for /// a parsed AST item, which always has matching delimiters. - pub fn collect_tokens( + pub fn collect_tokens( &mut self, f: impl FnOnce(&mut Self) -> PResult<'a, R>, - ) -> PResult<'a, R> { + ) -> PResult<'a, (R, Option)> { let start_token = (self.token.clone(), self.token_spacing); let cursor_snapshot = TokenCursor { frame: self.token_cursor.frame.clone(), @@ -1249,7 +1249,7 @@ impl<'a> Parser<'a> { append_unglued_token: self.token_cursor.append_unglued_token.clone(), }; - let mut ret = f(self)?; + let ret = f(self)?; // Produces a `TokenStream` on-demand. Using `cursor_snapshot` // and `num_calls`, we can reconstruct the `TokenStream` seen @@ -1319,8 +1319,7 @@ impl<'a> Parser<'a> { trailing_semi: false, append_unglued_token: self.token_cursor.append_unglued_token.clone(), }; - ret.finalize_tokens(LazyTokenStream::new(lazy_impl)); - Ok(ret) + Ok((ret, Some(LazyTokenStream::new(lazy_impl)))) } /// `::{` or `::*` diff --git a/compiler/rustc_parse/src/parser/nonterminal.rs b/compiler/rustc_parse/src/parser/nonterminal.rs index 97d0c0d874583..eb5d7075f0081 100644 --- a/compiler/rustc_parse/src/parser/nonterminal.rs +++ b/compiler/rustc_parse/src/parser/nonterminal.rs @@ -99,34 +99,80 @@ impl<'a> Parser<'a> { // we always capture tokens for any `Nonterminal` which needs them. Ok(match kind { NonterminalKind::Item => match self.collect_tokens(|this| this.parse_item())? { - Some(item) => token::NtItem(item), - None => { + (Some(mut item), tokens) => { + // If we captured tokens during parsing (due to outer attributes), + // use those. + if item.tokens.is_none() { + item.tokens = tokens; + } + token::NtItem(item) + } + (None, _) => { return Err(self.struct_span_err(self.token.span, "expected an item keyword")); } }, NonterminalKind::Block => { - token::NtBlock(self.collect_tokens(|this| this.parse_block())?) + let (mut block, tokens) = self.collect_tokens(|this| this.parse_block())?; + // We have have eaten an NtBlock, which could already have tokens + if block.tokens.is_none() { + block.tokens = tokens; + } + token::NtBlock(block) } - NonterminalKind::Stmt => match self.collect_tokens(|this| this.parse_stmt())? { - Some(s) => token::NtStmt(s), - None => { - return Err(self.struct_span_err(self.token.span, "expected a statement")); + NonterminalKind::Stmt => { + let (stmt, tokens) = self.collect_tokens(|this| this.parse_stmt())?; + match stmt { + Some(mut s) => { + if s.tokens().is_none() { + s.set_tokens(tokens); + } + token::NtStmt(s) + } + None => { + return Err(self.struct_span_err(self.token.span, "expected a statement")); + } } - }, + } NonterminalKind::Pat2018 { .. } | NonterminalKind::Pat2021 { .. } => { - token::NtPat(self.collect_tokens(|this| match kind { + let (mut pat, tokens) = self.collect_tokens(|this| match kind { NonterminalKind::Pat2018 { .. } => this.parse_pat(None), NonterminalKind::Pat2021 { .. } => { this.parse_top_pat(GateOr::Yes, RecoverComma::No) } _ => unreachable!(), - })?) + })?; + // We have have eaten an NtPat, which could already have tokens + if pat.tokens.is_none() { + pat.tokens = tokens; + } + token::NtPat(pat) + } + NonterminalKind::Expr => { + let (mut expr, tokens) = self.collect_tokens(|this| this.parse_expr())?; + // If we captured tokens during parsing (due to outer attributes), + // use those. + if expr.tokens.is_none() { + expr.tokens = tokens; + } + token::NtExpr(expr) } - NonterminalKind::Expr => token::NtExpr(self.collect_tokens(|this| this.parse_expr())?), NonterminalKind::Literal => { - token::NtLiteral(self.collect_tokens(|this| this.parse_literal_maybe_minus())?) + let (mut lit, tokens) = + self.collect_tokens(|this| this.parse_literal_maybe_minus())?; + // We have have eaten a nonterminal, which could already have tokens + if lit.tokens.is_none() { + lit.tokens = tokens; + } + token::NtLiteral(lit) + } + NonterminalKind::Ty => { + let (mut ty, tokens) = self.collect_tokens(|this| this.parse_ty())?; + // We have an eaten an NtTy, which could already have tokens + if ty.tokens.is_none() { + ty.tokens = tokens; + } + token::NtTy(ty) } - NonterminalKind::Ty => token::NtTy(self.collect_tokens(|this| this.parse_ty())?), // this could be handled like a token, since it is one NonterminalKind::Ident => { if let Some((ident, is_raw)) = get_macro_ident(&self.token) { @@ -139,15 +185,32 @@ impl<'a> Parser<'a> { } } NonterminalKind::Path => { - token::NtPath(self.collect_tokens(|this| this.parse_path(PathStyle::Type))?) + let (mut path, tokens) = + self.collect_tokens(|this| this.parse_path(PathStyle::Type))?; + // We have have eaten an NtPath, which could already have tokens + if path.tokens.is_none() { + path.tokens = tokens; + } + token::NtPath(path) } NonterminalKind::Meta => { - token::NtMeta(P(self.collect_tokens(|this| this.parse_attr_item(false))?)) + let (mut attr, tokens) = self.collect_tokens(|this| this.parse_attr_item(false))?; + // We may have eaten a nonterminal, which could already have tokens + if attr.tokens.is_none() { + attr.tokens = tokens; + } + token::NtMeta(P(attr)) } NonterminalKind::TT => token::NtTT(self.parse_token_tree()), - NonterminalKind::Vis => token::NtVis( - self.collect_tokens(|this| this.parse_visibility(FollowedByType::Yes))?, - ), + NonterminalKind::Vis => { + let (mut vis, tokens) = + self.collect_tokens(|this| this.parse_visibility(FollowedByType::Yes))?; + // We may have etan an `NtVis`, which could already have tokens + if vis.tokens.is_none() { + vis.tokens = tokens; + } + token::NtVis(vis) + } NonterminalKind::Lifetime => { if self.check_lifetime() { token::NtLifetime(self.expect_lifetime().ident) diff --git a/compiler/rustc_parse/src/parser/path.rs b/compiler/rustc_parse/src/parser/path.rs index dd36122f6a10e..43dee391c171a 100644 --- a/compiler/rustc_parse/src/parser/path.rs +++ b/compiler/rustc_parse/src/parser/path.rs @@ -230,11 +230,10 @@ impl<'a> Parser<'a> { } else { // `(T, U) -> R` let (inputs, _) = self.parse_paren_comma_seq(|p| p.parse_ty())?; - let inputs_span = lo.to(self.prev_token.span); let span = ident.span.to(self.prev_token.span); let output = self.parse_ret_ty(AllowPlus::No, RecoverQPath::No, RecoverReturnSign::No)?; - ParenthesizedArgs { span, inputs, inputs_span, output }.into() + ParenthesizedArgs { inputs, output, span }.into() }; PathSegment { ident, args, id: ast::DUMMY_NODE_ID } diff --git a/compiler/rustc_parse/src/parser/stmt.rs b/compiler/rustc_parse/src/parser/stmt.rs index 641b29227db98..2942747991a1d 100644 --- a/compiler/rustc_parse/src/parser/stmt.rs +++ b/compiler/rustc_parse/src/parser/stmt.rs @@ -89,7 +89,15 @@ impl<'a> Parser<'a> { }; let stmt = if has_attrs { - self.collect_tokens(parse_stmt_inner)? + let (mut stmt, tokens) = self.collect_tokens(parse_stmt_inner)?; + if let Some(stmt) = &mut stmt { + // If we already have tokens (e.g. due to encounting an `NtStmt`), + // use those instead. + if stmt.tokens().is_none() { + stmt.set_tokens(tokens); + } + } + stmt } else { parse_stmt_inner(self)? }; diff --git a/compiler/rustc_parse_format/src/lib.rs b/compiler/rustc_parse_format/src/lib.rs index f150f7a41ae80..25e3e67e28e6c 100644 --- a/compiler/rustc_parse_format/src/lib.rs +++ b/compiler/rustc_parse_format/src/lib.rs @@ -347,7 +347,7 @@ impl<'a> Parser<'a> { let mut pos = pos; // This handles the raw string case, the raw argument is the number of # // in r###"..."### (we need to add one because of the `r`). - let raw = self.style.map_or(0, |raw| raw + 1); + let raw = self.style.map(|raw| raw + 1).unwrap_or(0); for skip in &self.skips { if pos > *skip { pos += 1; @@ -736,7 +736,7 @@ fn find_skips_from_snippet( fn find_skips(snippet: &str, is_raw: bool) -> Vec { let mut eat_ws = false; - let mut s = snippet.char_indices().peekable(); + let mut s = snippet.chars().enumerate().peekable(); let mut skips = vec![]; while let Some((pos, c)) = s.next() { match (c, s.peek()) { @@ -814,7 +814,7 @@ fn find_skips_from_snippet( skips } - let r_start = str_style.map_or(0, |r| r + 1); + let r_start = str_style.map(|r| r + 1).unwrap_or(0); let r_end = str_style.unwrap_or(0); let s = &snippet[r_start + 1..snippet.len() - r_end - 1]; (find_skips(s, str_style.is_some()), true) diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index ac73ba7062e76..a6a61ffc5dae5 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -32,7 +32,7 @@ pub(crate) fn target_from_impl_item<'tcx>( let parent_hir_id = tcx.hir().get_parent_item(impl_item.hir_id); let containing_item = tcx.hir().expect_item(parent_hir_id); let containing_impl_is_for_trait = match &containing_item.kind { - hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(), + hir::ItemKind::Impl { ref of_trait, .. } => of_trait.is_some(), _ => bug!("parent of an ImplItem must be an Impl"), }; if containing_impl_is_for_trait { @@ -343,7 +343,7 @@ impl CheckAttrVisitor<'tcx> { // We can't link to trait impl's consts. let err = "associated constant in trait implementation block"; match containing_item.kind { - ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => Some(err), + ItemKind::Impl { of_trait: Some(_), .. } => Some(err), _ => None, } } diff --git a/compiler/rustc_passes/src/check_const.rs b/compiler/rustc_passes/src/check_const.rs index c887a860303b5..2d6bbff460d7f 100644 --- a/compiler/rustc_passes/src/check_const.rs +++ b/compiler/rustc_passes/src/check_const.rs @@ -49,7 +49,9 @@ impl NonConstExpr { // All other expressions are allowed. Self::Loop(Loop | While | WhileLet) - | Self::Match(WhileDesugar | WhileLetDesugar | Normal | IfLetDesugar { .. }) => &[], + | Self::Match( + WhileDesugar | WhileLetDesugar | Normal | IfDesugar { .. } | IfLetDesugar { .. }, + ) => &[], }; Some(gates) diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index 80a24c90421e7..c4fb0cf5b28dc 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -396,7 +396,7 @@ impl<'v, 'k, 'tcx> ItemLikeVisitor<'v> for LifeSeeder<'k, 'tcx> { } } } - hir::ItemKind::Impl(hir::Impl { ref of_trait, items, .. }) => { + hir::ItemKind::Impl { ref of_trait, items, .. } => { if of_trait.is_some() { self.worklist.push(item.hir_id); } diff --git a/compiler/rustc_passes/src/liveness.rs b/compiler/rustc_passes/src/liveness.rs index 6202cc312fc0e..fcea1b29ec367 100644 --- a/compiler/rustc_passes/src/liveness.rs +++ b/compiler/rustc_passes/src/liveness.rs @@ -419,7 +419,7 @@ impl<'tcx> Visitor<'tcx> for IrMaps<'tcx> { } // live nodes required for interesting control flow: - hir::ExprKind::If(..) | hir::ExprKind::Match(..) | hir::ExprKind::Loop(..) => { + hir::ExprKind::Match(..) | hir::ExprKind::Loop(..) => { self.add_live_node_for_node(expr.hir_id, ExprNode(expr.span)); intravisit::walk_expr(self, expr); } @@ -846,29 +846,6 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { // at the label ident hir::ExprKind::Loop(ref blk, _, _) => self.propagate_through_loop(expr, &blk, succ), - hir::ExprKind::If(ref cond, ref then, ref else_opt) => { - // - // (cond) - // | - // v - // (expr) - // / \ - // | | - // v v - // (then)(els) - // | | - // v v - // ( succ ) - // - let else_ln = - self.propagate_through_opt_expr(else_opt.as_ref().map(|e| &**e), succ); - let then_ln = self.propagate_through_expr(&then, succ); - let ln = self.live_node(expr.hir_id, expr.span); - self.init_from_succ(ln, else_ln); - self.merge_from_succ(ln, then_ln); - self.propagate_through_expr(&cond, ln) - } - hir::ExprKind::Match(ref e, arms, _) => { // // (e) @@ -1359,7 +1336,6 @@ fn check_expr<'tcx>(this: &mut Liveness<'_, 'tcx>, expr: &'tcx Expr<'tcx>) { | hir::ExprKind::Tup(..) | hir::ExprKind::Binary(..) | hir::ExprKind::Cast(..) - | hir::ExprKind::If(..) | hir::ExprKind::DropTemps(..) | hir::ExprKind::Unary(..) | hir::ExprKind::Ret(..) diff --git a/compiler/rustc_passes/src/naked_functions.rs b/compiler/rustc_passes/src/naked_functions.rs index 93fb23c018bf0..788f1df328cc4 100644 --- a/compiler/rustc_passes/src/naked_functions.rs +++ b/compiler/rustc_passes/src/naked_functions.rs @@ -201,7 +201,6 @@ impl<'tcx> CheckInlineAssembly<'tcx> { | ExprKind::Type(..) | ExprKind::Loop(..) | ExprKind::Match(..) - | ExprKind::If(..) | ExprKind::Closure(..) | ExprKind::Assign(..) | ExprKind::AssignOp(..) diff --git a/compiler/rustc_passes/src/reachable.rs b/compiler/rustc_passes/src/reachable.rs index b237671f8e208..fde83af99a569 100644 --- a/compiler/rustc_passes/src/reachable.rs +++ b/compiler/rustc_passes/src/reachable.rs @@ -349,9 +349,7 @@ impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CollectPrivateImplItemsVisitor<'a, 'tcx } // We need only trait impls here, not inherent impls, and only non-exported ones - if let hir::ItemKind::Impl(hir::Impl { of_trait: Some(ref trait_ref), ref items, .. }) = - item.kind - { + if let hir::ItemKind::Impl { of_trait: Some(ref trait_ref), ref items, .. } = item.kind { if !self.access_levels.is_reachable(item.hir_id) { // FIXME(#53488) remove `let` let tcx = self.tcx; diff --git a/compiler/rustc_passes/src/region.rs b/compiler/rustc_passes/src/region.rs index 91421d7f5f22b..1af79abe4b911 100644 --- a/compiler/rustc_passes/src/region.rs +++ b/compiler/rustc_passes/src/region.rs @@ -241,17 +241,6 @@ fn resolve_expr<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, expr: &'tcx h terminating(r.hir_id.local_id); } - hir::ExprKind::If(ref expr, ref then, Some(ref otherwise)) => { - terminating(expr.hir_id.local_id); - terminating(then.hir_id.local_id); - terminating(otherwise.hir_id.local_id); - } - - hir::ExprKind::If(ref expr, ref then, None) => { - terminating(expr.hir_id.local_id); - terminating(then.hir_id.local_id); - } - hir::ExprKind::Loop(ref body, _, _) => { terminating(body.hir_id.local_id); } diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index b70cec25dfb5a..def2a501cf475 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -55,21 +55,6 @@ impl InheritDeprecation { } } -/// Whether to inherit const stability flags for nested items. In most cases, we do not want to -/// inherit const stability: just because an enclosing `fn` is const-stable does not mean -/// all `extern` imports declared in it should be const-stable! However, trait methods -/// inherit const stability attributes from their parent and do not have their own. -enum InheritConstStability { - Yes, - No, -} - -impl InheritConstStability { - fn yes(&self) -> bool { - matches!(self, InheritConstStability::Yes) - } -} - // A private tree-walker for producing an Index. struct Annotator<'a, 'tcx> { tcx: TyCtxt<'tcx>, @@ -90,7 +75,6 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { item_sp: Span, kind: AnnotationKind, inherit_deprecation: InheritDeprecation, - inherit_const_stability: InheritConstStability, visit_children: F, ) where F: FnOnce(&mut Self), @@ -156,8 +140,6 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { const_stab }); - // `impl const Trait for Type` items forward their const stability to their - // immediate children. if const_stab.is_none() { debug!("annotate: const_stab not found, parent = {:?}", self.parent_const_stab); if let Some(parent) = self.parent_const_stab { @@ -246,7 +228,7 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { self.recurse_with_stability_attrs( depr.map(|(d, _)| DeprecationEntry::local(d, hir_id)), stab, - if inherit_const_stability.yes() { const_stab } else { None }, + const_stab, visit_children, ); } @@ -343,21 +325,18 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { fn visit_item(&mut self, i: &'tcx Item<'tcx>) { let orig_in_trait_impl = self.in_trait_impl; let mut kind = AnnotationKind::Required; - let mut const_stab_inherit = InheritConstStability::No; match i.kind { // Inherent impls and foreign modules serve only as containers for other items, // they don't have their own stability. They still can be annotated as unstable // and propagate this unstability to children, but this annotation is completely // optional. They inherit stability from their parents when unannotated. - hir::ItemKind::Impl(hir::Impl { of_trait: None, .. }) - | hir::ItemKind::ForeignMod { .. } => { + hir::ItemKind::Impl { of_trait: None, .. } | hir::ItemKind::ForeignMod { .. } => { self.in_trait_impl = false; kind = AnnotationKind::Container; } - hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => { + hir::ItemKind::Impl { of_trait: Some(_), .. } => { self.in_trait_impl = true; kind = AnnotationKind::DeprecationProhibited; - const_stab_inherit = InheritConstStability::Yes; } hir::ItemKind::Struct(ref sd, _) => { if let Some(ctor_hir_id) = sd.ctor_hir_id() { @@ -367,7 +346,6 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { i.span, AnnotationKind::Required, InheritDeprecation::Yes, - InheritConstStability::No, |_| {}, ) } @@ -375,15 +353,9 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { _ => {} } - self.annotate( - i.hir_id, - &i.attrs, - i.span, - kind, - InheritDeprecation::Yes, - const_stab_inherit, - |v| intravisit::walk_item(v, i), - ); + self.annotate(i.hir_id, &i.attrs, i.span, kind, InheritDeprecation::Yes, |v| { + intravisit::walk_item(v, i) + }); self.in_trait_impl = orig_in_trait_impl; } @@ -394,7 +366,6 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { ti.span, AnnotationKind::Required, InheritDeprecation::Yes, - InheritConstStability::No, |v| { intravisit::walk_trait_item(v, ti); }, @@ -404,17 +375,9 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) { let kind = if self.in_trait_impl { AnnotationKind::Prohibited } else { AnnotationKind::Required }; - self.annotate( - ii.hir_id, - &ii.attrs, - ii.span, - kind, - InheritDeprecation::Yes, - InheritConstStability::No, - |v| { - intravisit::walk_impl_item(v, ii); - }, - ); + self.annotate(ii.hir_id, &ii.attrs, ii.span, kind, InheritDeprecation::Yes, |v| { + intravisit::walk_impl_item(v, ii); + }); } fn visit_variant(&mut self, var: &'tcx Variant<'tcx>, g: &'tcx Generics<'tcx>, item_id: HirId) { @@ -424,7 +387,6 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { var.span, AnnotationKind::Required, InheritDeprecation::Yes, - InheritConstStability::No, |v| { if let Some(ctor_hir_id) = var.data.ctor_hir_id() { v.annotate( @@ -433,7 +395,6 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { var.span, AnnotationKind::Required, InheritDeprecation::Yes, - InheritConstStability::No, |_| {}, ); } @@ -450,7 +411,6 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { s.span, AnnotationKind::Required, InheritDeprecation::Yes, - InheritConstStability::No, |v| { intravisit::walk_struct_field(v, s); }, @@ -464,7 +424,6 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { i.span, AnnotationKind::Required, InheritDeprecation::Yes, - InheritConstStability::No, |v| { intravisit::walk_foreign_item(v, i); }, @@ -478,7 +437,6 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { md.span, AnnotationKind::Required, InheritDeprecation::Yes, - InheritConstStability::No, |_| {}, ); } @@ -492,17 +450,9 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { _ => AnnotationKind::Prohibited, }; - self.annotate( - p.hir_id, - &p.attrs, - p.span, - kind, - InheritDeprecation::No, - InheritConstStability::No, - |v| { - intravisit::walk_generic_param(v, p); - }, - ); + self.annotate(p.hir_id, &p.attrs, p.span, kind, InheritDeprecation::No, |v| { + intravisit::walk_generic_param(v, p); + }); } } @@ -553,7 +503,7 @@ impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> { // optional. They inherit stability from their parents when unannotated. if !matches!( i.kind, - hir::ItemKind::Impl(hir::Impl { of_trait: None, .. }) | hir::ItemKind::ForeignMod { .. } + hir::ItemKind::Impl { of_trait: None, .. } | hir::ItemKind::ForeignMod { .. } ) { self.check_missing_stability(i.hir_id, i.span); } @@ -667,7 +617,6 @@ fn new_index(tcx: TyCtxt<'tcx>) -> Index<'tcx> { krate.item.span, AnnotationKind::Required, InheritDeprecation::Yes, - InheritConstStability::No, |v| intravisit::walk_crate(v, krate), ); } @@ -723,7 +672,7 @@ impl Visitor<'tcx> for Checker<'tcx> { // For implementations of traits, check the stability of each item // individually as it's possible to have a stable trait with unstable // items. - hir::ItemKind::Impl(hir::Impl { of_trait: Some(ref t), self_ty, items, .. }) => { + hir::ItemKind::Impl { of_trait: Some(ref t), self_ty, items, .. } => { if self.tcx.features().staged_api { // If this impl block has an #[unstable] attribute, give an // error if all involved types and traits are stable, because diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 66206ca46c3a7..c2db2c82fa1c4 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -100,19 +100,19 @@ where } fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow { - match predicate.kind().skip_binder() { - ty::PredicateKind::Trait(ty::TraitPredicate { trait_ref }, _) => { + match predicate.skip_binders() { + ty::PredicateAtom::Trait(ty::TraitPredicate { trait_ref }, _) => { self.visit_trait(trait_ref) } - ty::PredicateKind::Projection(ty::ProjectionPredicate { projection_ty, ty }) => { + ty::PredicateAtom::Projection(ty::ProjectionPredicate { projection_ty, ty }) => { ty.visit_with(self)?; self.visit_trait(projection_ty.trait_ref(self.def_id_visitor.tcx())) } - ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _region)) => { + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, _region)) => { ty.visit_with(self) } - ty::PredicateKind::RegionOutlives(..) => ControlFlow::CONTINUE, - ty::PredicateKind::ConstEvaluatable(..) + ty::PredicateAtom::RegionOutlives(..) => ControlFlow::CONTINUE, + ty::PredicateAtom::ConstEvaluatable(..) if self.def_id_visitor.tcx().features().const_evaluatable_checked => { // FIXME(const_evaluatable_checked): If the constant used here depends on a @@ -632,9 +632,9 @@ impl Visitor<'tcx> for EmbargoVisitor<'tcx> { } } } - hir::ItemKind::Impl(ref impl_) => { - for impl_item_ref in impl_.items { - if impl_.of_trait.is_some() || impl_item_ref.vis.node.is_pub() { + hir::ItemKind::Impl { ref of_trait, items, .. } => { + for impl_item_ref in items { + if of_trait.is_some() || impl_item_ref.vis.node.is_pub() { self.update(impl_item_ref.id.hir_id, item_level); } } @@ -736,11 +736,11 @@ impl Visitor<'tcx> for EmbargoVisitor<'tcx> { } } // Visit everything except for private impl items. - hir::ItemKind::Impl(ref impl_) => { + hir::ItemKind::Impl { items, .. } => { if item_level.is_some() { self.reach(item.hir_id, item_level).generics().predicates().ty().trait_ref(); - for impl_item_ref in impl_.items { + for impl_item_ref in items { let impl_item_level = self.get(impl_item_ref.id.hir_id); if impl_item_level.is_some() { self.reach(impl_item_ref.id.hir_id, impl_item_level) @@ -1450,7 +1450,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { // (i.e., we could just return here to not check them at // all, or some worse estimation of whether an impl is // publicly visible). - hir::ItemKind::Impl(ref impl_) => { + hir::ItemKind::Impl { generics: ref g, ref of_trait, ref self_ty, items, .. } => { // `impl [... for] Private` is never visible. let self_contains_private; // `impl [... for] Public<...>`, but not `impl [... for] @@ -1465,7 +1465,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { at_outer_type: true, outer_type_is_public_path: false, }; - visitor.visit_ty(&impl_.self_ty); + visitor.visit_ty(&self_ty); self_contains_private = visitor.contains_private; self_is_public_path = visitor.outer_type_is_public_path; } @@ -1473,7 +1473,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { // Miscellaneous info about the impl: // `true` iff this is `impl Private for ...`. - let not_private_trait = impl_.of_trait.as_ref().map_or( + let not_private_trait = of_trait.as_ref().map_or( true, // no trait counts as public trait |tr| { let did = tr.path.res.def_id(); @@ -1494,8 +1494,8 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { // directly because we might have `impl> ...`, // and we shouldn't warn about the generics if all the methods // are private (because `T` won't be visible externally). - let trait_or_some_public_method = impl_.of_trait.is_some() - || impl_.items.iter().any(|impl_item_ref| { + let trait_or_some_public_method = of_trait.is_some() + || items.iter().any(|impl_item_ref| { let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); match impl_item.kind { hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..) => { @@ -1506,11 +1506,11 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { }); if !self_contains_private && not_private_trait && trait_or_some_public_method { - intravisit::walk_generics(self, &impl_.generics); + intravisit::walk_generics(self, g); - match impl_.of_trait { + match of_trait { None => { - for impl_item_ref in impl_.items { + for impl_item_ref in items { // This is where we choose whether to walk down // further into the impl to check its items. We // should only walk into public items so that we @@ -1531,7 +1531,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { } } } - Some(ref tr) => { + Some(tr) => { // Any private types in a trait impl fall into three // categories. // 1. mentioned in the trait definition @@ -1548,7 +1548,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { intravisit::walk_path(self, &tr.path); // Those in 3. are warned with this call. - for impl_item_ref in impl_.items { + for impl_item_ref in items { let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); if let hir::ImplItemKind::TyAlias(ref ty) = impl_item.kind { self.visit_ty(ty); @@ -1556,11 +1556,11 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { } } } - } else if impl_.of_trait.is_none() && self_is_public_path { + } else if of_trait.is_none() && self_is_public_path { // `impl Public { ... }`. Any public static // methods will be visible as `Public::foo`. let mut found_pub_static = false; - for impl_item_ref in impl_.items { + for impl_item_ref in items { if self.item_is_public(&impl_item_ref.id.hir_id, &impl_item_ref.vis) { let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); match impl_item_ref.kind { @@ -1577,7 +1577,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { } } if found_pub_static { - intravisit::walk_generics(self, &impl_.generics) + intravisit::walk_generics(self, g) } } return; @@ -1970,11 +1970,11 @@ impl<'a, 'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> // Subitems of inherent impls have their own publicity. // A trait impl is public when both its type and its trait are public // Subitems of trait impls have inherited publicity. - hir::ItemKind::Impl(ref impl_) => { + hir::ItemKind::Impl { ref of_trait, items, .. } => { let impl_vis = ty::Visibility::of_impl(item.hir_id, tcx, &Default::default()); self.check(item.hir_id, impl_vis).generics().predicates(); - for impl_item_ref in impl_.items { - let impl_item_vis = if impl_.of_trait.is_none() { + for impl_item_ref in items { + let impl_item_vis = if of_trait.is_none() { min( tcx.visibility(tcx.hir().local_def_id(impl_item_ref.id.hir_id)), impl_vis, @@ -2032,7 +2032,7 @@ fn visibility(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Visibility { Node::ImplItem(impl_item) => { match tcx.hir().get(tcx.hir().get_parent_item(hir_id)) { Node::Item(hir::Item { - kind: hir::ItemKind::Impl(hir::Impl { of_trait: Some(tr), .. }), + kind: hir::ItemKind::Impl { of_trait: Some(tr), .. }, .. }) => tr.path.res.opt_def_id().map_or_else( || { diff --git a/compiler/rustc_query_system/src/dep_graph/graph.rs b/compiler/rustc_query_system/src/dep_graph/graph.rs index 4fb3a683ea225..605d7ae4af678 100644 --- a/compiler/rustc_query_system/src/dep_graph/graph.rs +++ b/compiler/rustc_query_system/src/dep_graph/graph.rs @@ -7,7 +7,6 @@ use rustc_data_structures::sync::{AtomicU32, AtomicU64, Lock, LockGuard, Lrc, Or use rustc_data_structures::unlikely; use rustc_errors::Diagnostic; use rustc_index::vec::{Idx, IndexVec}; -use rustc_serialize::{Encodable, Encoder}; use parking_lot::{Condvar, Mutex}; use smallvec::{smallvec, SmallVec}; @@ -22,7 +21,7 @@ use std::sync::atomic::Ordering::Relaxed; use super::debug::EdgeFilter; use super::prev::PreviousDepGraph; use super::query::DepGraphQuery; -use super::serialized::SerializedDepNodeIndex; +use super::serialized::{SerializedDepGraph, SerializedDepNodeIndex}; use super::{DepContext, DepKind, DepNode, WorkProductId}; #[derive(Clone)] @@ -149,7 +148,7 @@ impl DepGraph { let mut edge_list_indices = Vec::with_capacity(node_count); let mut edge_list_data = Vec::with_capacity(edge_count); - // See `DepGraph`'s `Encodable` implementation for notes on the approach used here. + // See `serialize` for notes on the approach used here. edge_list_data.extend(data.unshared_edges.iter().map(|i| i.index())); @@ -552,6 +551,19 @@ impl DepGraph { self.data.as_ref()?.dep_node_debug.borrow().get(&dep_node).cloned() } + pub fn edge_deduplication_data(&self) -> Option<(u64, u64)> { + if cfg!(debug_assertions) { + let current_dep_graph = &self.data.as_ref().unwrap().current; + + Some(( + current_dep_graph.total_read_count.load(Relaxed), + current_dep_graph.total_duplicate_read_count.load(Relaxed), + )) + } else { + None + } + } + fn edge_count(&self, node_data: &LockGuard<'_, DepNodeData>) -> usize { let data = self.data.as_ref().unwrap(); let previous = &data.previous; @@ -567,6 +579,84 @@ impl DepGraph { edge_count } + pub fn serialize(&self) -> SerializedDepGraph { + type SDNI = SerializedDepNodeIndex; + + let data = self.data.as_ref().unwrap(); + let previous = &data.previous; + + // Note locking order: `prev_index_to_index`, then `data`. + let prev_index_to_index = data.current.prev_index_to_index.lock(); + let data = data.current.data.lock(); + let node_count = data.hybrid_indices.len(); + let edge_count = self.edge_count(&data); + + let mut nodes = IndexVec::with_capacity(node_count); + let mut fingerprints = IndexVec::with_capacity(node_count); + let mut edge_list_indices = IndexVec::with_capacity(node_count); + let mut edge_list_data = Vec::with_capacity(edge_count); + + // `rustc_middle::ty::query::OnDiskCache` expects nodes to be in + // `DepNodeIndex` order. The edges in `edge_list_data`, on the other + // hand, don't need to be in a particular order, as long as each node + // can reference its edges as a contiguous range within it. This is why + // we're able to copy `unshared_edges` directly into `edge_list_data`. + // It meets the above requirements, and each non-dark-green node already + // knows the range of edges to reference within it, which they'll push + // onto `edge_list_indices`. Dark green nodes, however, don't have their + // edges in `unshared_edges`, so need to add them to `edge_list_data`. + + edge_list_data.extend(data.unshared_edges.iter().map(|i| SDNI::new(i.index()))); + + for &hybrid_index in data.hybrid_indices.iter() { + match hybrid_index.into() { + HybridIndex::New(i) => { + let new = &data.new; + nodes.push(new.nodes[i]); + fingerprints.push(new.fingerprints[i]); + let edges = &new.edges[i]; + edge_list_indices.push((edges.start.as_u32(), edges.end.as_u32())); + } + HybridIndex::Red(i) => { + let red = &data.red; + nodes.push(previous.index_to_node(red.node_indices[i])); + fingerprints.push(red.fingerprints[i]); + let edges = &red.edges[i]; + edge_list_indices.push((edges.start.as_u32(), edges.end.as_u32())); + } + HybridIndex::LightGreen(i) => { + let lg = &data.light_green; + nodes.push(previous.index_to_node(lg.node_indices[i])); + fingerprints.push(previous.fingerprint_by_index(lg.node_indices[i])); + let edges = &lg.edges[i]; + edge_list_indices.push((edges.start.as_u32(), edges.end.as_u32())); + } + HybridIndex::DarkGreen(prev_index) => { + nodes.push(previous.index_to_node(prev_index)); + fingerprints.push(previous.fingerprint_by_index(prev_index)); + + let edges_iter = previous + .edge_targets_from(prev_index) + .iter() + .map(|&dst| prev_index_to_index[dst].as_ref().unwrap()); + + let start = edge_list_data.len() as u32; + edge_list_data.extend(edges_iter.map(|i| SDNI::new(i.index()))); + let end = edge_list_data.len() as u32; + edge_list_indices.push((start, end)); + } + } + } + + debug_assert_eq!(nodes.len(), node_count); + debug_assert_eq!(fingerprints.len(), node_count); + debug_assert_eq!(edge_list_indices.len(), node_count); + debug_assert_eq!(edge_list_data.len(), edge_count); + debug_assert!(edge_list_data.len() <= u32::MAX as usize); + + SerializedDepGraph { nodes, fingerprints, edge_list_indices, edge_list_data } + } + pub fn node_color(&self, dep_node: &DepNode) -> Option { if let Some(ref data) = self.data { if let Some(prev_index) = data.previous.node_to_index_opt(dep_node) { @@ -863,7 +953,7 @@ impl DepGraph { // Returns true if the given node has been marked as green during the // current compilation session. Used in various assertions pub fn is_green(&self, dep_node: &DepNode) -> bool { - self.node_color(dep_node).map_or(false, |c| c.is_green()) + self.node_color(dep_node).map(|c| c.is_green()).unwrap_or(false) } // This method loads all on-disk cacheable query results into memory, so @@ -907,251 +997,12 @@ impl DepGraph { } } - pub fn print_incremental_info(&self) { - #[derive(Clone)] - struct Stat { - kind: Kind, - node_counter: u64, - edge_counter: u64, - } - - let data = self.data.as_ref().unwrap(); - let prev = &data.previous; - let current = &data.current; - let data = current.data.lock(); - - let mut stats: FxHashMap<_, Stat> = FxHashMap::with_hasher(Default::default()); - - for &hybrid_index in data.hybrid_indices.iter() { - let (kind, edge_count) = match hybrid_index.into() { - HybridIndex::New(new_index) => { - let kind = data.new.nodes[new_index].kind; - let edge_range = &data.new.edges[new_index]; - (kind, edge_range.end.as_usize() - edge_range.start.as_usize()) - } - HybridIndex::Red(red_index) => { - let kind = prev.index_to_node(data.red.node_indices[red_index]).kind; - let edge_range = &data.red.edges[red_index]; - (kind, edge_range.end.as_usize() - edge_range.start.as_usize()) - } - HybridIndex::LightGreen(lg_index) => { - let kind = prev.index_to_node(data.light_green.node_indices[lg_index]).kind; - let edge_range = &data.light_green.edges[lg_index]; - (kind, edge_range.end.as_usize() - edge_range.start.as_usize()) - } - HybridIndex::DarkGreen(prev_index) => { - let kind = prev.index_to_node(prev_index).kind; - let edge_count = prev.edge_targets_from(prev_index).len(); - (kind, edge_count) - } - }; - - let stat = stats.entry(kind).or_insert(Stat { kind, node_counter: 0, edge_counter: 0 }); - stat.node_counter += 1; - stat.edge_counter += edge_count as u64; - } - - let total_node_count = data.hybrid_indices.len(); - let total_edge_count = self.edge_count(&data); - - // Drop the lock guard. - std::mem::drop(data); - - let mut stats: Vec<_> = stats.values().cloned().collect(); - stats.sort_by_key(|s| -(s.node_counter as i64)); - - const SEPARATOR: &str = "[incremental] --------------------------------\ - ----------------------------------------------\ - ------------"; - - println!("[incremental]"); - println!("[incremental] DepGraph Statistics"); - println!("{}", SEPARATOR); - println!("[incremental]"); - println!("[incremental] Total Node Count: {}", total_node_count); - println!("[incremental] Total Edge Count: {}", total_edge_count); - - if cfg!(debug_assertions) { - let total_edge_reads = current.total_read_count.load(Relaxed); - let total_duplicate_edge_reads = current.total_duplicate_read_count.load(Relaxed); - - println!("[incremental] Total Edge Reads: {}", total_edge_reads); - println!("[incremental] Total Duplicate Edge Reads: {}", total_duplicate_edge_reads); - } - - println!("[incremental]"); - - println!( - "[incremental] {:<36}| {:<17}| {:<12}| {:<17}|", - "Node Kind", "Node Frequency", "Node Count", "Avg. Edge Count" - ); - - println!( - "[incremental] -------------------------------------\ - |------------------\ - |-------------\ - |------------------|" - ); - - for stat in stats { - let node_kind_ratio = (100.0 * (stat.node_counter as f64)) / (total_node_count as f64); - let node_kind_avg_edges = (stat.edge_counter as f64) / (stat.node_counter as f64); - - println!( - "[incremental] {:<36}|{:>16.1}% |{:>12} |{:>17.1} |", - format!("{:?}", stat.kind), - node_kind_ratio, - stat.node_counter, - node_kind_avg_edges, - ); - } - - println!("{}", SEPARATOR); - println!("[incremental]"); - } - fn next_virtual_depnode_index(&self) -> DepNodeIndex { let index = self.virtual_dep_node_index.fetch_add(1, Relaxed); DepNodeIndex::from_u32(index) } } -impl> Encodable for DepGraph { - fn encode(&self, e: &mut E) -> Result<(), E::Error> { - // We used to serialize the dep graph by creating and serializing a `SerializedDepGraph` - // using data copied from the `DepGraph`. But copying created a large memory spike, so we - // now serialize directly from the `DepGraph` as if it's a `SerializedDepGraph`. Because we - // deserialize that data into a `SerializedDepGraph` in the next compilation session, we - // need `DepGraph`'s `Encodable` and `SerializedDepGraph`'s `Decodable` implementations to - // be in sync. If you update this encoding, be sure to update the decoding, and vice-versa. - - let data = self.data.as_ref().unwrap(); - let prev = &data.previous; - - // Note locking order: `prev_index_to_index`, then `data`. - let prev_index_to_index = data.current.prev_index_to_index.lock(); - let data = data.current.data.lock(); - let new = &data.new; - let red = &data.red; - let lg = &data.light_green; - - let node_count = data.hybrid_indices.len(); - let edge_count = self.edge_count(&data); - - // `rustc_middle::ty::query::OnDiskCache` expects nodes to be encoded in `DepNodeIndex` - // order. The edges in `edge_list_data` don't need to be in a particular order, as long as - // each node references its edges as a contiguous range within it. Therefore, we can encode - // `edge_list_data` directly from `unshared_edges`. It meets the above requirements, as - // each non-dark-green node already knows the range of edges to reference within it, which - // they'll encode in `edge_list_indices`. Dark green nodes, however, don't have their edges - // in `unshared_edges`, so need to add them to `edge_list_data`. - - use HybridIndex::*; - - // Encoded values (nodes, etc.) are explicitly typed below to avoid inadvertently - // serializing data in the wrong format (i.e. one incompatible with `SerializedDepGraph`). - e.emit_struct("SerializedDepGraph", 4, |e| { - e.emit_struct_field("nodes", 0, |e| { - // `SerializedDepGraph` expects this to be encoded as a sequence of `DepNode`s. - e.emit_seq(node_count, |e| { - for (seq_index, &hybrid_index) in data.hybrid_indices.iter().enumerate() { - let node: DepNode = match hybrid_index.into() { - New(i) => new.nodes[i], - Red(i) => prev.index_to_node(red.node_indices[i]), - LightGreen(i) => prev.index_to_node(lg.node_indices[i]), - DarkGreen(prev_index) => prev.index_to_node(prev_index), - }; - - e.emit_seq_elt(seq_index, |e| node.encode(e))?; - } - - Ok(()) - }) - })?; - - e.emit_struct_field("fingerprints", 1, |e| { - // `SerializedDepGraph` expects this to be encoded as a sequence of `Fingerprints`s. - e.emit_seq(node_count, |e| { - for (seq_index, &hybrid_index) in data.hybrid_indices.iter().enumerate() { - let fingerprint: Fingerprint = match hybrid_index.into() { - New(i) => new.fingerprints[i], - Red(i) => red.fingerprints[i], - LightGreen(i) => prev.fingerprint_by_index(lg.node_indices[i]), - DarkGreen(prev_index) => prev.fingerprint_by_index(prev_index), - }; - - e.emit_seq_elt(seq_index, |e| fingerprint.encode(e))?; - } - - Ok(()) - }) - })?; - - e.emit_struct_field("edge_list_indices", 2, |e| { - // `SerializedDepGraph` expects this to be encoded as a sequence of `(u32, u32)`s. - e.emit_seq(node_count, |e| { - // Dark green node edges start after the unshared (all other nodes') edges. - let mut dark_green_edge_index = data.unshared_edges.len(); - - for (seq_index, &hybrid_index) in data.hybrid_indices.iter().enumerate() { - let edge_indices: (u32, u32) = match hybrid_index.into() { - New(i) => (new.edges[i].start.as_u32(), new.edges[i].end.as_u32()), - Red(i) => (red.edges[i].start.as_u32(), red.edges[i].end.as_u32()), - LightGreen(i) => (lg.edges[i].start.as_u32(), lg.edges[i].end.as_u32()), - DarkGreen(prev_index) => { - let edge_count = prev.edge_targets_from(prev_index).len(); - let start = dark_green_edge_index as u32; - dark_green_edge_index += edge_count; - let end = dark_green_edge_index as u32; - (start, end) - } - }; - - e.emit_seq_elt(seq_index, |e| edge_indices.encode(e))?; - } - - assert_eq!(dark_green_edge_index, edge_count); - - Ok(()) - }) - })?; - - e.emit_struct_field("edge_list_data", 3, |e| { - // `SerializedDepGraph` expects this to be encoded as a sequence of - // `SerializedDepNodeIndex`. - e.emit_seq(edge_count, |e| { - for (seq_index, &edge) in data.unshared_edges.iter().enumerate() { - let serialized_edge = SerializedDepNodeIndex::new(edge.index()); - e.emit_seq_elt(seq_index, |e| serialized_edge.encode(e))?; - } - - let mut seq_index = data.unshared_edges.len(); - - for &hybrid_index in data.hybrid_indices.iter() { - if let DarkGreen(prev_index) = hybrid_index.into() { - for &edge in prev.edge_targets_from(prev_index) { - // Dark green node edges are stored in the previous graph - // and must be converted to edges in the current graph, - // and then serialized as `SerializedDepNodeIndex`. - let serialized_edge = SerializedDepNodeIndex::new( - prev_index_to_index[edge].as_ref().unwrap().index(), - ); - - e.emit_seq_elt(seq_index, |e| serialized_edge.encode(e))?; - seq_index += 1; - } - } - } - - assert_eq!(seq_index, edge_count); - - Ok(()) - }) - }) - }) - } -} - /// A "work product" is an intermediate result that we save into the /// incremental directory for later re-use. The primary example are /// the object files that we save for each partition at code diff --git a/compiler/rustc_query_system/src/dep_graph/prev.rs b/compiler/rustc_query_system/src/dep_graph/prev.rs index c3d0f79525572..29357ce9449ce 100644 --- a/compiler/rustc_query_system/src/dep_graph/prev.rs +++ b/compiler/rustc_query_system/src/dep_graph/prev.rs @@ -3,7 +3,7 @@ use super::{DepKind, DepNode}; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::FxHashMap; -#[derive(Debug)] +#[derive(Debug, Encodable, Decodable)] pub struct PreviousDepGraph { data: SerializedDepGraph, index: FxHashMap, SerializedDepNodeIndex>, diff --git a/compiler/rustc_query_system/src/dep_graph/serialized.rs b/compiler/rustc_query_system/src/dep_graph/serialized.rs index 9bb922b0a9008..28e0740691852 100644 --- a/compiler/rustc_query_system/src/dep_graph/serialized.rs +++ b/compiler/rustc_query_system/src/dep_graph/serialized.rs @@ -3,7 +3,6 @@ use super::{DepKind, DepNode}; use rustc_data_structures::fingerprint::Fingerprint; use rustc_index::vec::IndexVec; -use rustc_serialize::{Decodable, Decoder}; // The maximum value of `SerializedDepNodeIndex` leaves the upper two bits // unused so that we can store multiple index types in `CompressedHybridIndex`, @@ -15,7 +14,7 @@ rustc_index::newtype_index! { } /// Data for use when recompiling the **current crate**. -#[derive(Debug)] +#[derive(Debug, Encodable, Decodable)] pub struct SerializedDepGraph { /// The set of all DepNodes in the graph pub nodes: IndexVec>, @@ -49,79 +48,3 @@ impl SerializedDepGraph { &self.edge_list_data[targets.0 as usize..targets.1 as usize] } } - -impl> Decodable for SerializedDepGraph { - fn decode(d: &mut D) -> Result, D::Error> { - // We used to serialize the dep graph by creating and serializing a `SerializedDepGraph` - // using data copied from the `DepGraph`. But copying created a large memory spike, so we - // now serialize directly from the `DepGraph` as if it's a `SerializedDepGraph`. Because we - // deserialize that data into a `SerializedDepGraph` in the next compilation session, we - // need `DepGraph`'s `Encodable` and `SerializedDepGraph`'s `Decodable` implementations to - // be in sync. If you update this decoding, be sure to update the encoding, and vice-versa. - // - // We mimic the sequence of `Encode` and `Encodable` method calls used by the `DepGraph`'s - // `Encodable` implementation with the corresponding sequence of `Decode` and `Decodable` - // method calls. E.g. `Decode::read_struct` pairs with `Encode::emit_struct`, `DepNode`'s - // `decode` pairs with `DepNode`'s `encode`, and so on. Any decoding methods not associated - // with corresponding encoding methods called in `DepGraph`'s `Encodable` implementation - // are off limits, because we'd be relying on their implementation details. - // - // For example, because we know it happens to do the right thing, its tempting to just use - // `IndexVec`'s `Decodable` implementation to decode into some of the collections below, - // even though `DepGraph` doesn't use its `Encodable` implementation. But the `IndexVec` - // implementation could change, and we'd have a bug. - // - // Variables below are explicitly typed so that anyone who changes the `SerializedDepGraph` - // representation without updating this function will encounter a compilation error, and - // know to update this and possibly the `DepGraph` `Encodable` implementation accordingly - // (the latter should serialize data in a format compatible with our representation). - - d.read_struct("SerializedDepGraph", 4, |d| { - let nodes: IndexVec> = - d.read_struct_field("nodes", 0, |d| { - d.read_seq(|d, len| { - let mut v = IndexVec::with_capacity(len); - for i in 0..len { - v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?); - } - Ok(v) - }) - })?; - - let fingerprints: IndexVec = - d.read_struct_field("fingerprints", 1, |d| { - d.read_seq(|d, len| { - let mut v = IndexVec::with_capacity(len); - for i in 0..len { - v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?); - } - Ok(v) - }) - })?; - - let edge_list_indices: IndexVec = d - .read_struct_field("edge_list_indices", 2, |d| { - d.read_seq(|d, len| { - let mut v = IndexVec::with_capacity(len); - for i in 0..len { - v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?); - } - Ok(v) - }) - })?; - - let edge_list_data: Vec = - d.read_struct_field("edge_list_data", 3, |d| { - d.read_seq(|d, len| { - let mut v = Vec::with_capacity(len); - for i in 0..len { - v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?); - } - Ok(v) - }) - })?; - - Ok(SerializedDepGraph { nodes, fingerprints, edge_list_indices, edge_list_data }) - }) - } -} diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index 4ab14c158d337..e96fc185b7e03 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -115,7 +115,7 @@ impl<'a> Resolver<'a> { self.get_module(parent_id) } - pub fn get_module(&mut self, def_id: DefId) -> Module<'a> { + crate fn get_module(&mut self, def_id: DefId) -> Module<'a> { // If this is a local module, it will be in `module_map`, no need to recalculate it. if let Some(def_id) = def_id.as_local() { return self.module_map[&def_id]; diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 69fb6870d2c67..4f8047ac2dff0 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -683,7 +683,7 @@ impl<'a> Resolver<'a> { )); } Scope::BuiltinAttrs => { - let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(kw::Empty)); + let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin); if filter_fn(res) { suggestions.extend( BUILTIN_ATTRIBUTES diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index 97e556f5a338d..6219d1b08eb68 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -14,6 +14,7 @@ use crate::{ResolutionError, Resolver, Segment, UseError}; use rustc_ast::ptr::P; use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor}; use rustc_ast::*; +use rustc_ast::{unwrap_or, walk_list}; use rustc_ast_lowering::ResolverAstLowering; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_errors::DiagnosticId; @@ -1910,7 +1911,7 @@ impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> { // it needs to be added to the trait map. if ns == ValueNS { let item_name = path.last().unwrap().ident; - let traits = self.traits_in_scope(item_name, ns); + let traits = self.get_traits_containing_item(item_name, ns); self.r.trait_map.insert(id, traits); } @@ -1924,7 +1925,7 @@ impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> { { // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8` let item_span = - path.iter().last().map_or(span, |segment| segment.ident.span); + path.iter().last().map(|segment| segment.ident.span).unwrap_or(span); let mut hm = self.r.session.confused_type_with_std_module.borrow_mut(); hm.insert(item_span, span); @@ -2370,12 +2371,12 @@ impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> { // field, we need to add any trait methods we find that match // the field name so that we can do some nice error reporting // later on in typeck. - let traits = self.traits_in_scope(ident, ValueNS); + let traits = self.get_traits_containing_item(ident, ValueNS); self.r.trait_map.insert(expr.id, traits); } ExprKind::MethodCall(ref segment, ..) => { debug!("(recording candidate traits for expr) recording traits for {}", expr.id); - let traits = self.traits_in_scope(segment.ident, ValueNS); + let traits = self.get_traits_containing_item(segment.ident, ValueNS); self.r.trait_map.insert(expr.id, traits); } _ => { @@ -2384,13 +2385,64 @@ impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> { } } - fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec { - self.r.traits_in_scope( - self.current_trait_ref.as_ref().map(|(module, _)| *module), - &self.parent_scope, - ident.span.ctxt(), - Some((ident.name, ns)), - ) + fn get_traits_containing_item( + &mut self, + mut ident: Ident, + ns: Namespace, + ) -> Vec { + debug!("(getting traits containing item) looking for '{}'", ident.name); + + let mut found_traits = Vec::new(); + // Look for the current trait. + if let Some((module, _)) = self.current_trait_ref { + if self + .r + .resolve_ident_in_module( + ModuleOrUniformRoot::Module(module), + ident, + ns, + &self.parent_scope, + false, + module.span, + ) + .is_ok() + { + let def_id = module.def_id().unwrap(); + found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] }); + } + } + + ident.span = ident.span.normalize_to_macros_2_0(); + let mut search_module = self.parent_scope.module; + loop { + self.r.get_traits_in_module_containing_item( + ident, + ns, + search_module, + &mut found_traits, + &self.parent_scope, + ); + let mut span_data = ident.span.data(); + search_module = unwrap_or!( + self.r.hygienic_lexical_parent(search_module, &mut span_data.ctxt), + break + ); + ident.span = span_data.span(); + } + + if let Some(prelude) = self.r.prelude { + if !search_module.no_implicit_prelude { + self.r.get_traits_in_module_containing_item( + ident, + ns, + prelude, + &mut found_traits, + &self.parent_scope, + ); + } + } + + found_traits } } diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index 3945afb4724a8..55623c9bd9cf6 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -264,7 +264,7 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> { // The current function has a `self' parameter, but we were unable to resolve // a reference to `self`. This can only happen if the `self` identifier we // are resolving came from a different hygiene context. - if fn_kind.decl().inputs.get(0).map_or(false, |p| p.is_self()) { + if fn_kind.decl().inputs.get(0).map(|p| p.is_self()).unwrap_or(false) { err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters"); } else { let doesnt = if is_assoc_fn { @@ -1452,7 +1452,8 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> { } } else { let needs_placeholder = |def_id: DefId, kind: CtorKind| { - let has_no_fields = self.r.field_names.get(&def_id).map_or(false, |f| f.is_empty()); + let has_no_fields = + self.r.field_names.get(&def_id).map(|f| f.is_empty()).unwrap_or(false); match kind { CtorKind::Const => false, CtorKind::Fn | CtorKind::Fictive if has_no_fields => false, diff --git a/compiler/rustc_resolve/src/late/lifetimes.rs b/compiler/rustc_resolve/src/late/lifetimes.rs index 64cc113dffe7e..d5ba6f3b53b21 100644 --- a/compiler/rustc_resolve/src/late/lifetimes.rs +++ b/compiler/rustc_resolve/src/late/lifetimes.rs @@ -11,8 +11,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::def_id::{CrateNum, DefIdMap, LOCAL_CRATE}; -use rustc_hir::hir_id::ItemLocalId; +use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LOCAL_CRATE}; use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor}; use rustc_hir::{GenericArg, GenericParam, LifetimeName, Node, ParamName, QPath}; use rustc_hir::{GenericParamKind, HirIdMap, HirIdSet, LifetimeParamKind}; @@ -21,7 +20,6 @@ use rustc_middle::middle::resolve_lifetime::*; use rustc_middle::ty::{self, DefIdTree, GenericParamDefKind, TyCtxt}; use rustc_middle::{bug, span_bug}; use rustc_session::lint; -use rustc_span::def_id::{DefId, LocalDefId}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::Span; use std::borrow::Cow; @@ -286,7 +284,7 @@ pub fn provide(providers: &mut ty::query::Providers) { resolve_lifetimes, named_region_map: |tcx, id| tcx.resolve_lifetimes(LOCAL_CRATE).defs.get(&id), - is_late_bound_map, + is_late_bound_map: |tcx, id| tcx.resolve_lifetimes(LOCAL_CRATE).late_bound.get(&id), object_lifetime_defaults_map: |tcx, id| { tcx.resolve_lifetimes(LOCAL_CRATE).object_lifetime_defaults.get(&id) }, @@ -322,32 +320,6 @@ fn resolve_lifetimes(tcx: TyCtxt<'_>, for_krate: CrateNum) -> ResolveLifetimes { rl } -fn is_late_bound_map<'tcx>( - tcx: TyCtxt<'tcx>, - def_id: LocalDefId, -) -> Option<(LocalDefId, &'tcx FxHashSet)> { - match tcx.def_kind(def_id) { - DefKind::AnonConst => { - let mut def_id = tcx - .parent(def_id.to_def_id()) - .unwrap_or_else(|| bug!("anon const or closure without a parent")); - // We search for the next outer anon const or fn here - // while skipping closures. - // - // Note that for `AnonConst` we still just recurse until we - // find a function body, but who cares :shrug: - while tcx.is_closure(def_id) { - def_id = tcx - .parent(def_id) - .unwrap_or_else(|| bug!("anon const or closure without a parent")); - } - - tcx.is_late_bound_map(def_id.expect_local()) - } - _ => tcx.resolve_lifetimes(LOCAL_CRATE).late_bound.get(&def_id).map(|lt| (def_id, lt)), - } -} - fn krate(tcx: TyCtxt<'_>) -> NamedRegionMap { let krate = tcx.hir().krate(); let mut map = NamedRegionMap { @@ -437,11 +409,11 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { | hir::ItemKind::Union(_, ref generics) | hir::ItemKind::Trait(_, _, ref generics, ..) | hir::ItemKind::TraitAlias(ref generics, ..) - | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) => { + | hir::ItemKind::Impl { ref generics, .. } => { self.missing_named_lifetime_spots.push(generics.into()); // Impls permit `'_` to be used and it is equivalent to "some fresh lifetime name". - // This is not true for other kinds of items. + // This is not true for other kinds of items.x let track_lifetime_uses = matches!(item.kind, hir::ItemKind::Impl { .. }); // These kinds of items have only early-bound lifetime parameters. let mut index = if sub_items_have_self_param(&item.kind) { @@ -672,17 +644,17 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { } else { bug!(); }; - // We cannot predict what lifetimes are unused in opaque type. - self.lifetime_uses.insert(def_id, LifetimeUseSet::Many); - if let hir::ParamName::Plain(Ident { - name: kw::UnderscoreLifetime, - .. - }) = name - { - // Pick the elided lifetime "definition" if one exists - // and use it to make an elision scope. - elision = Some(reg); + if let hir::ParamName::Plain(param_name) = name { + if param_name.name == kw::UnderscoreLifetime { + // Pick the elided lifetime "definition" if one exists + // and use it to make an elision scope. + self.lifetime_uses.insert(def_id, LifetimeUseSet::Many); + elision = Some(reg); + } else { + lifetimes.insert(name, reg); + } } else { + self.lifetime_uses.insert(def_id, LifetimeUseSet::Many); lifetimes.insert(name, reg); } } @@ -1398,10 +1370,12 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { fn lifetime_deletion_span(&self, name: Ident, generics: &hir::Generics<'_>) -> Option { generics.params.iter().enumerate().find_map(|(i, param)| { if param.name.ident() == name { - let in_band = matches!( - param.kind, - hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::InBand } - ); + let mut in_band = false; + if let hir::GenericParamKind::Lifetime { kind } = param.kind { + if let hir::LifetimeParamKind::InBand = kind { + in_band = true; + } + } if in_band { Some(param.span) } else if generics.params.len() == 1 { @@ -1431,11 +1405,12 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { lifetime: &hir::Lifetime, ) { let name = lifetime.name.ident(); - let remove_decl = self - .tcx - .parent(def_id) - .and_then(|parent_def_id| self.tcx.hir().get_generics(parent_def_id)) - .and_then(|generics| self.lifetime_deletion_span(name, generics)); + let mut remove_decl = None; + if let Some(parent_def_id) = self.tcx.parent(def_id) { + if let Some(generics) = self.tcx.hir().get_generics(parent_def_id) { + remove_decl = self.lifetime_deletion_span(name, generics); + } + } let mut remove_use = None; let mut elide_use = None; @@ -1458,7 +1433,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { hir::TyKind::Path(ref qpath) => { if let QPath::Resolved(_, path) = qpath { let last_segment = &path.segments[path.segments.len() - 1]; - let generics = last_segment.args(); + let generics = last_segment.generic_args(); for arg in generics.args.iter() { if let GenericArg::Lifetime(lt) = arg { if lt.name.ident() == name { @@ -1702,7 +1677,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } match parent.kind { hir::ItemKind::Trait(_, _, ref generics, ..) - | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) => { + | hir::ItemKind::Impl { ref generics, .. } => { index += generics.params.len() as u32; } _ => {} @@ -2127,7 +2102,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body), .. }) => { - if let hir::ItemKind::Impl(hir::Impl { ref self_ty, ref items, .. }) = + if let hir::ItemKind::Impl { ref self_ty, ref items, .. } = self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind { impl_self = Some(self_ty); diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index af5341623758a..fb364053e241e 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -44,9 +44,9 @@ use rustc_index::vec::IndexVec; use rustc_metadata::creader::{CStore, CrateLoader}; use rustc_middle::hir::exports::ExportMap; use rustc_middle::middle::cstore::{CrateStore, MetadataLoaderDyn}; -use rustc_middle::span_bug; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, DefIdTree, ResolverOutputs}; +use rustc_middle::{bug, span_bug}; use rustc_session::lint; use rustc_session::lint::{BuiltinLintDiagnostics, LintBuffer}; use rustc_session::Session; @@ -1052,7 +1052,7 @@ pub struct ResolverArenas<'a> { impl<'a> ResolverArenas<'a> { fn alloc_module(&'a self, module: ModuleData<'a>) -> Module<'a> { let module = self.modules.alloc(module); - if module.def_id().map_or(true, |def_id| def_id.is_local()) { + if module.def_id().map(|def_id| def_id.is_local()).unwrap_or(true) { self.local_modules.borrow_mut().push(module); } module @@ -1477,76 +1477,49 @@ impl<'a> Resolver<'a> { self.crate_loader.postprocess(krate); } - pub fn traits_in_scope( - &mut self, - current_trait: Option>, - parent_scope: &ParentScope<'a>, - ctxt: SyntaxContext, - assoc_item: Option<(Symbol, Namespace)>, - ) -> Vec { - let mut found_traits = Vec::new(); - - if let Some(module) = current_trait { - if self.trait_may_have_item(Some(module), assoc_item) { - let def_id = module.def_id().unwrap(); - found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] }); - } - } - - self.visit_scopes(ScopeSet::All(TypeNS, false), parent_scope, ctxt, |this, scope, _, _| { - match scope { - Scope::Module(module) => { - this.traits_in_module(module, assoc_item, &mut found_traits); - } - Scope::StdLibPrelude => { - if let Some(module) = this.prelude { - this.traits_in_module(module, assoc_item, &mut found_traits); - } - } - Scope::ExternPrelude | Scope::ToolPrelude | Scope::BuiltinTypes => {} - _ => unreachable!(), - } - None::<()> - }); - - found_traits - } - - fn traits_in_module( + fn get_traits_in_module_containing_item( &mut self, + ident: Ident, + ns: Namespace, module: Module<'a>, - assoc_item: Option<(Symbol, Namespace)>, found_traits: &mut Vec, + parent_scope: &ParentScope<'a>, ) { + assert!(ns == TypeNS || ns == ValueNS); module.ensure_traits(self); let traits = module.traits.borrow(); - for (trait_name, trait_binding) in traits.as_ref().unwrap().iter() { - if self.trait_may_have_item(trait_binding.module(), assoc_item) { - let def_id = trait_binding.res().def_id(); - let import_ids = self.find_transitive_imports(&trait_binding.kind, *trait_name); - found_traits.push(TraitCandidate { def_id, import_ids }); - } - } - } - // List of traits in scope is pruned on best effort basis. We reject traits not having an - // associated item with the given name and namespace (if specified). This is a conservative - // optimization, proper hygienic type-based resolution of associated items is done in typeck. - // We don't reject trait aliases (`trait_module == None`) because we don't have access to their - // associated items. - fn trait_may_have_item( - &mut self, - trait_module: Option>, - assoc_item: Option<(Symbol, Namespace)>, - ) -> bool { - match (trait_module, assoc_item) { - (Some(trait_module), Some((name, ns))) => { - self.resolutions(trait_module).borrow().iter().any(|resolution| { - let (&BindingKey { ident: assoc_ident, ns: assoc_ns, .. }, _) = resolution; - assoc_ns == ns && assoc_ident.name == name - }) + for &(trait_name, binding) in traits.as_ref().unwrap().iter() { + // Traits have pseudo-modules that can be used to search for the given ident. + if let Some(module) = binding.module() { + let mut ident = ident; + if ident.span.glob_adjust(module.expansion, binding.span).is_none() { + continue; + } + if self + .resolve_ident_in_module_unadjusted( + ModuleOrUniformRoot::Module(module), + ident, + ns, + parent_scope, + false, + module.span, + ) + .is_ok() + { + let import_ids = self.find_transitive_imports(&binding.kind, trait_name); + let trait_def_id = module.def_id().unwrap(); + found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids }); + } + } else if let Res::Def(DefKind::TraitAlias, _) = binding.res() { + // For now, just treat all trait aliases as possible candidates, since we don't + // know if the ident is somewhere in the transitive bounds. + let import_ids = self.find_transitive_imports(&binding.kind, trait_name); + let trait_def_id = binding.res().def_id(); + found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids }); + } else { + bug!("candidate is not trait or trait alias?") } - _ => true, } } @@ -3058,7 +3031,7 @@ impl<'a> Resolver<'a> { let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id(); let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy(); let from_item = - self.extern_prelude.get(&ident).map_or(true, |entry| entry.introduced_by_item); + self.extern_prelude.get(&ident).map(|entry| entry.introduced_by_item).unwrap_or(true); // Only suggest removing an import if both bindings are to the same def, if both spans // aren't dummy spans. Further, if both bindings are imports, then the ident must have // been introduced by a item. @@ -3254,6 +3227,34 @@ impl<'a> Resolver<'a> { }) } + /// This is equivalent to `get_traits_in_module_containing_item`, but without filtering by the associated item. + /// + /// This is used by rustdoc for intra-doc links. + pub fn traits_in_scope(&mut self, module_id: DefId) -> Vec { + let module = self.get_module(module_id); + module.ensure_traits(self); + let traits = module.traits.borrow(); + let to_candidate = + |this: &mut Self, &(trait_name, binding): &(Ident, &NameBinding<'_>)| TraitCandidate { + def_id: binding.res().def_id(), + import_ids: this.find_transitive_imports(&binding.kind, trait_name), + }; + + let mut candidates: Vec<_> = + traits.as_ref().unwrap().iter().map(|x| to_candidate(self, x)).collect(); + + if let Some(prelude) = self.prelude { + if !module.no_implicit_prelude { + prelude.ensure_traits(self); + candidates.extend( + prelude.traits.borrow().as_ref().unwrap().iter().map(|x| to_candidate(self, x)), + ); + } + } + + candidates + } + /// Rustdoc uses this to resolve things in a recoverable way. `ResolutionError<'a>` /// isn't something that can be returned because it can't be made to live that long, /// and also it's a private type. Fortunately rustdoc doesn't need to know the error, diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index 5d6120cd31076..5c74094ecd3ee 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -757,11 +757,7 @@ impl<'a> Resolver<'a> { } Scope::BuiltinAttrs => { if is_builtin_attr_name(ident.name) { - ok( - Res::NonMacroAttr(NonMacroAttrKind::Builtin(ident.name)), - DUMMY_SP, - this.arenas, - ) + ok(Res::NonMacroAttr(NonMacroAttrKind::Builtin), DUMMY_SP, this.arenas) } else { Err(Determinacy::Determined) } @@ -814,15 +810,13 @@ impl<'a> Resolver<'a> { // Found another solution, if the first one was "weak", report an error. let (res, innermost_res) = (binding.res(), innermost_binding.res()); if res != innermost_res { - let is_builtin = |res| { - matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Builtin(..))) - }; + let builtin = Res::NonMacroAttr(NonMacroAttrKind::Builtin); let derive_helper_compat = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat); let ambiguity_error_kind = if is_import { Some(AmbiguityKind::Import) - } else if is_builtin(innermost_res) || is_builtin(res) { + } else if innermost_res == builtin || res == builtin { Some(AmbiguityKind::BuiltinAttr) } else if innermost_res == derive_helper_compat || res == derive_helper_compat diff --git a/compiler/rustc_save_analysis/src/dump_visitor.rs b/compiler/rustc_save_analysis/src/dump_visitor.rs index 2834e7b6322ed..617a28ed51938 100644 --- a/compiler/rustc_save_analysis/src/dump_visitor.rs +++ b/compiler/rustc_save_analysis/src/dump_visitor.rs @@ -631,7 +631,14 @@ impl<'tcx> DumpVisitor<'tcx> { self.dumper.dump_def(&access, enum_data); } - fn process_impl(&mut self, item: &'tcx hir::Item<'tcx>, impl_: &'tcx hir::Impl<'tcx>) { + fn process_impl( + &mut self, + item: &'tcx hir::Item<'tcx>, + generics: &'tcx hir::Generics<'tcx>, + trait_ref: &'tcx Option>, + typ: &'tcx hir::Ty<'tcx>, + impl_items: &'tcx [hir::ImplItemRef<'tcx>], + ) { if let Some(impl_data) = self.save_ctxt.get_item_data(item) { if !self.span.filter_generated(item.span) { if let super::Data::RelationData(rel, imp) = impl_data { @@ -645,12 +652,12 @@ impl<'tcx> DumpVisitor<'tcx> { let map = &self.tcx.hir(); self.nest_typeck_results(map.local_def_id(item.hir_id), |v| { - v.visit_ty(&impl_.self_ty); - if let Some(trait_ref) = &impl_.of_trait { + v.visit_ty(&typ); + if let Some(trait_ref) = trait_ref { v.process_path(trait_ref.hir_ref_id, &hir::QPath::Resolved(None, &trait_ref.path)); } - v.process_generic_params(&impl_.generics, "", item.hir_id); - for impl_item in impl_.items { + v.process_generic_params(generics, "", item.hir_id); + for impl_item in impl_items { v.process_impl_item( map.impl_item(impl_item.id), map.local_def_id(item.hir_id).to_def_id(), @@ -1280,7 +1287,9 @@ impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> { self.process_struct(item, def, ty_params) } hir::ItemKind::Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params), - hir::ItemKind::Impl(ref impl_) => self.process_impl(item, impl_), + hir::ItemKind::Impl { ref generics, ref of_trait, ref self_ty, ref items, .. } => { + self.process_impl(item, generics, of_trait, &self_ty, items) + } hir::ItemKind::Trait(_, _, ref generics, ref trait_refs, methods) => { self.process_trait(item, generics, trait_refs, methods) } diff --git a/compiler/rustc_save_analysis/src/lib.rs b/compiler/rustc_save_analysis/src/lib.rs index 129123349a028..056c0b3d9d513 100644 --- a/compiler/rustc_save_analysis/src/lib.rs +++ b/compiler/rustc_save_analysis/src/lib.rs @@ -318,7 +318,7 @@ impl<'tcx> SaveContext<'tcx> { attributes: lower_attributes(item.attrs.to_vec(), self), })) } - hir::ItemKind::Impl(hir::Impl { ref of_trait, ref self_ty, ref items, .. }) => { + hir::ItemKind::Impl { ref of_trait, ref self_ty, ref items, .. } => { if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = self_ty.kind { // Common case impl for a struct or something basic. if generated_code(path.span) { @@ -410,7 +410,7 @@ impl<'tcx> SaveContext<'tcx> { match self.tcx.impl_of_method(def_id) { Some(impl_id) => match self.tcx.hir().get_if_local(impl_id) { Some(Node::Item(item)) => match item.kind { - hir::ItemKind::Impl(hir::Impl { ref self_ty, .. }) => { + hir::ItemKind::Impl { ref self_ty, .. } => { let hir = self.tcx.hir(); let mut qualname = String::from("<"); @@ -670,7 +670,7 @@ impl<'tcx> SaveContext<'tcx> { ) -> Option { // Returns true if the path is function type sugar, e.g., `Fn(A) -> B`. fn fn_type(seg: &hir::PathSegment<'_>) -> bool { - seg.args.map_or(false, |args| args.parenthesized) + seg.args.map(|args| args.parenthesized).unwrap_or(false) } let res = self.get_path_res(id); diff --git a/compiler/rustc_save_analysis/src/sig.rs b/compiler/rustc_save_analysis/src/sig.rs index 8ada7e34fe844..ab3da270fe66f 100644 --- a/compiler/rustc_save_analysis/src/sig.rs +++ b/compiler/rustc_save_analysis/src/sig.rs @@ -501,7 +501,7 @@ impl<'hir> Sig for hir::Item<'hir> { Ok(sig) } - hir::ItemKind::Impl(hir::Impl { + hir::ItemKind::Impl { unsafety, polarity, defaultness, @@ -511,7 +511,7 @@ impl<'hir> Sig for hir::Item<'hir> { ref of_trait, ref self_ty, items: _, - }) => { + } => { let mut text = String::new(); if let hir::Defaultness::Default { .. } = defaultness { text.push_str("default "); diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index 49833601c9e91..0cafdec1495bb 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -403,20 +403,6 @@ impl OutputTypes { OutputType::Metadata | OutputType::DepInfo => false, }) } - - // Returns `true` if any of the output types require linking. - pub fn should_link(&self) -> bool { - self.0.keys().any(|k| match *k { - OutputType::Bitcode - | OutputType::Assembly - | OutputType::LlvmAssembly - | OutputType::Mir - | OutputType::Metadata - | OutputType::Object - | OutputType::DepInfo => false, - OutputType::Exe => true, - }) - } } /// Use tree-based collections to cheaply get a deterministic `Hash` implementation. diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 6d01854228662..1f9a1af0f6872 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -1358,7 +1358,7 @@ pub fn build_session( let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone()); let optimization_fuel = Lock::new(OptimizationFuel { - remaining: sopts.debugging_opts.fuel.as_ref().map_or(0, |i| i.1), + remaining: sopts.debugging_opts.fuel.as_ref().map(|i| i.1).unwrap_or(0), out_of_fuel: false, }); let print_fuel_crate = sopts.debugging_opts.print_fuel.clone(); diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index 50cb15554864f..f0f9f940446db 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -1899,9 +1899,8 @@ where return; } - if self.is_dummy() { + if *self == DUMMY_SP { Hash::hash(&TAG_INVALID_SPAN, hasher); - self.ctxt().hash_stable(ctx, hasher); return; } diff --git a/compiler/rustc_span/src/source_map.rs b/compiler/rustc_span/src/source_map.rs index 4e0ce0d344de4..6635d44496c03 100644 --- a/compiler/rustc_span/src/source_map.rs +++ b/compiler/rustc_span/src/source_map.rs @@ -539,7 +539,7 @@ impl SourceMap { pub fn is_line_before_span_empty(&self, sp: Span) -> bool { match self.span_to_prev_source(sp) { - Ok(s) => s.split('\n').last().map_or(false, |l| l.trim_start().is_empty()), + Ok(s) => s.split('\n').last().map(|l| l.trim_start().is_empty()).unwrap_or(false), Err(_) => false, } } @@ -568,7 +568,7 @@ impl SourceMap { // asserting that the line numbers here are all indeed 1-based. let hi_line = hi.line.saturating_sub(1); for line_index in lo.line.saturating_sub(1)..hi_line { - let line_len = lo.file.get_line(line_index).map_or(0, |s| s.chars().count()); + let line_len = lo.file.get_line(line_index).map(|s| s.chars().count()).unwrap_or(0); lines.push(LineInfo { line_index, start_col, end_col: CharPos::from_usize(line_len) }); start_col = CharPos::from_usize(0); } @@ -582,9 +582,9 @@ impl SourceMap { /// Extracts the source surrounding the given `Span` using the `extract_source` function. The /// extract function takes three arguments: a string slice containing the source, an index in /// the slice for the beginning of the span and an index in the slice for the end of the span. - fn span_to_source(&self, sp: Span, extract_source: F) -> Result + fn span_to_source(&self, sp: Span, extract_source: F) -> Result where - F: Fn(&str, usize, usize) -> Result, + F: Fn(&str, usize, usize) -> Result, { let local_begin = self.lookup_byte_offset(sp.lo()); let local_end = self.lookup_byte_offset(sp.hi()); @@ -648,10 +648,10 @@ impl SourceMap { /// Extends the given `Span` to just after the previous occurrence of `c`. Return the same span /// if no character could be found or if an error occurred while retrieving the code snippet. - pub fn span_extend_to_prev_char(&self, sp: Span, c: char, accept_newlines: bool) -> Span { + pub fn span_extend_to_prev_char(&self, sp: Span, c: char) -> Span { if let Ok(prev_source) = self.span_to_prev_source(sp) { - let prev_source = prev_source.rsplit(c).next().unwrap_or(""); - if !prev_source.is_empty() && (!prev_source.contains('\n') || accept_newlines) { + let prev_source = prev_source.rsplit(c).next().unwrap_or("").trim_start(); + if !prev_source.is_empty() && !prev_source.contains('\n') { return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32)); } } @@ -682,25 +682,6 @@ impl SourceMap { sp } - /// Returns the source snippet as `String` after the given `Span`. - pub fn span_to_next_source(&self, sp: Span) -> Result { - self.span_to_source(sp, |src, _, end_index| { - src.get(end_index..).map(|s| s.to_string()).ok_or(SpanSnippetError::IllFormedSpan(sp)) - }) - } - - /// Extends the given `Span` to just after the next occurrence of `c`. - pub fn span_extend_to_next_char(&self, sp: Span, c: char, accept_newlines: bool) -> Span { - if let Ok(next_source) = self.span_to_next_source(sp) { - let next_source = next_source.split(c).next().unwrap_or(""); - if !next_source.is_empty() && (!next_source.contains('\n') || accept_newlines) { - return sp.with_hi(BytePos(sp.hi().0 + next_source.len() as u32)); - } - } - - sp - } - /// Given a `Span`, tries to get a shorter span ending before the first occurrence of `char` /// `c`. pub fn span_until_char(&self, sp: Span, c: char) -> Span { @@ -891,10 +872,8 @@ impl SourceMap { } pub fn get_source_file(&self, filename: &FileName) -> Option> { - // Remap filename before lookup - let filename = self.path_mapping().map_filename_prefix(filename).0; for sf in self.files.borrow().source_files.iter() { - if filename == sf.name { + if *filename == sf.name { return Some(sf.clone()); } } @@ -1062,15 +1041,4 @@ impl FilePathMapping { (path, false) } - - fn map_filename_prefix(&self, file: &FileName) -> (FileName, bool) { - match file { - FileName::Real(realfile) => { - let path = realfile.local_path(); - let (path, mapped) = self.map_prefix(path.to_path_buf()); - (FileName::Real(RealFileName::Named(path)), mapped) - } - other => (other.clone(), false), - } - } } diff --git a/compiler/rustc_span/src/source_map/tests.rs b/compiler/rustc_span/src/source_map/tests.rs index 3f22829b049fe..b8459eee4ecf0 100644 --- a/compiler/rustc_span/src/source_map/tests.rs +++ b/compiler/rustc_span/src/source_map/tests.rs @@ -107,7 +107,7 @@ fn t7() { fn span_from_selection(input: &str, selection: &str) -> Span { assert_eq!(input.len(), selection.len()); let left_index = selection.find('~').unwrap() as u32; - let right_index = selection.rfind('~').map_or(left_index, |x| x as u32); + let right_index = selection.rfind('~').map(|x| x as u32).unwrap_or(left_index); Span::with_root_ctxt(BytePos(left_index), BytePos(right_index + 1)) } diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 7b90e5b611cd1..b6cf584d875f1 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -622,7 +622,6 @@ symbols! { intel, into_iter, into_result, - intra_doc_pointers, intrinsics, irrefutable_let_patterns, isa_attribute, @@ -717,6 +716,7 @@ symbols! { more_struct_aliases, movbe_target_feature, move_ref_pattern, + move_val_init, mul, mul_assign, mul_with_overflow, diff --git a/compiler/rustc_target/src/spec/i386_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/i386_unknown_linux_gnu.rs deleted file mode 100644 index f329b2d2c8858..0000000000000 --- a/compiler/rustc_target/src/spec/i386_unknown_linux_gnu.rs +++ /dev/null @@ -1,8 +0,0 @@ -use crate::spec::Target; - -pub fn target() -> Target { - let mut base = super::i686_unknown_linux_gnu::target(); - base.cpu = "i386".to_string(); - base.llvm_target = "i386-unknown-linux-gnu".to_string(); - base -} diff --git a/compiler/rustc_target/src/spec/i486_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/i486_unknown_linux_gnu.rs deleted file mode 100644 index 5d96a558cb72a..0000000000000 --- a/compiler/rustc_target/src/spec/i486_unknown_linux_gnu.rs +++ /dev/null @@ -1,8 +0,0 @@ -use crate::spec::Target; - -pub fn target() -> Target { - let mut base = super::i686_unknown_linux_gnu::target(); - base.cpu = "i486".to_string(); - base.llvm_target = "i486-unknown-linux-gnu".to_string(); - base -} diff --git a/compiler/rustc_trait_selection/src/opaque_types.rs b/compiler/rustc_trait_selection/src/opaque_types.rs index 25ba489032bf1..f5bc90e6f9621 100644 --- a/compiler/rustc_trait_selection/src/opaque_types.rs +++ b/compiler/rustc_trait_selection/src/opaque_types.rs @@ -1153,7 +1153,7 @@ impl<'a, 'tcx> Instantiator<'a, 'tcx> { debug!("instantiate_opaque_types: ty_var={:?}", ty_var); for predicate in &bounds { - if let ty::PredicateKind::Projection(projection) = predicate.kind().skip_binder() { + if let ty::PredicateAtom::Projection(projection) = predicate.skip_binders() { if projection.ty.references_error() { // No point on adding these obligations since there's a type error involved. return ty_var; @@ -1251,18 +1251,18 @@ crate fn required_region_bounds( traits::elaborate_predicates(tcx, predicates) .filter_map(|obligation| { debug!("required_region_bounds(obligation={:?})", obligation); - match obligation.predicate.kind().skip_binder() { - ty::PredicateKind::Projection(..) - | ty::PredicateKind::Trait(..) - | ty::PredicateKind::Subtype(..) - | ty::PredicateKind::WellFormed(..) - | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::RegionOutlives(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) - | ty::PredicateKind::TypeWellFormedFromEnv(..) => None, - ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ref t, ref r)) => { + match obligation.predicate.skip_binders() { + ty::PredicateAtom::Projection(..) + | ty::PredicateAtom::Trait(..) + | ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::WellFormed(..) + | ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::RegionOutlives(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) + | ty::PredicateAtom::TypeWellFormedFromEnv(..) => None, + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ref t, ref r)) => { // Search for a bound of the form `erased_self_ty // : 'a`, but be wary of something like `for<'a> // erased_self_ty : 'a` (we interpret a diff --git a/compiler/rustc_trait_selection/src/traits/auto_trait.rs b/compiler/rustc_trait_selection/src/traits/auto_trait.rs index 6593c1000f283..d677103df1f58 100644 --- a/compiler/rustc_trait_selection/src/traits/auto_trait.rs +++ b/compiler/rustc_trait_selection/src/traits/auto_trait.rs @@ -414,9 +414,9 @@ impl AutoTraitFinder<'tcx> { let mut should_add_new = true; user_computed_preds.retain(|&old_pred| { if let ( - ty::PredicateKind::Trait(new_trait, _), - ty::PredicateKind::Trait(old_trait, _), - ) = (new_pred.kind().skip_binder(), old_pred.kind().skip_binder()) + ty::PredicateAtom::Trait(new_trait, _), + ty::PredicateAtom::Trait(old_trait, _), + ) = (new_pred.skip_binders(), old_pred.skip_binders()) { if new_trait.def_id() == old_trait.def_id() { let new_substs = new_trait.trait_ref.substs; @@ -633,16 +633,18 @@ impl AutoTraitFinder<'tcx> { // We check this by calling is_of_param on the relevant types // from the various possible predicates - let bound_predicate = predicate.kind(); + let bound_predicate = predicate.bound_atom(); match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(p, _) => { - // Add this to `predicates` so that we end up calling `select` - // with it. If this predicate ends up being unimplemented, - // then `evaluate_predicates` will handle adding it the `ParamEnv` - // if possible. + ty::PredicateAtom::Trait(p, _) => { + if self.is_param_no_infer(p.trait_ref.substs) + && !only_projections + && is_new_pred + { + self.add_user_pred(computed_preds, predicate); + } predicates.push_back(bound_predicate.rebind(p)); } - ty::PredicateKind::Projection(p) => { + ty::PredicateAtom::Projection(p) => { let p = bound_predicate.rebind(p); debug!( "evaluate_nested_obligations: examining projection predicate {:?}", @@ -772,13 +774,13 @@ impl AutoTraitFinder<'tcx> { } } } - ty::PredicateKind::RegionOutlives(binder) => { + ty::PredicateAtom::RegionOutlives(binder) => { let binder = bound_predicate.rebind(binder); if select.infcx().region_outlives_predicate(&dummy_cause, binder).is_err() { return false; } } - ty::PredicateKind::TypeOutlives(binder) => { + ty::PredicateAtom::TypeOutlives(binder) => { let binder = bound_predicate.rebind(binder); match ( binder.no_bound_vars(), @@ -801,7 +803,7 @@ impl AutoTraitFinder<'tcx> { _ => {} }; } - ty::PredicateKind::ConstEquate(c1, c2) => { + ty::PredicateAtom::ConstEquate(c1, c2) => { let evaluate = |c: &'tcx ty::Const<'tcx>| { if let ty::ConstKind::Unevaluated(def, substs, promoted) = c.val { match select.infcx().const_eval_resolve( diff --git a/compiler/rustc_trait_selection/src/traits/const_evaluatable.rs b/compiler/rustc_trait_selection/src/traits/const_evaluatable.rs index ad229e03b0b6b..370ad577170ba 100644 --- a/compiler/rustc_trait_selection/src/traits/const_evaluatable.rs +++ b/compiler/rustc_trait_selection/src/traits/const_evaluatable.rs @@ -41,8 +41,8 @@ pub fn is_const_evaluatable<'cx, 'tcx>( // We are looking at a generic abstract constant. Some(ct) => { for pred in param_env.caller_bounds() { - match pred.kind().skip_binder() { - ty::PredicateKind::ConstEvaluatable(b_def, b_substs) => { + match pred.skip_binders() { + ty::PredicateAtom::ConstEvaluatable(b_def, b_substs) => { debug!( "is_const_evaluatable: caller_bound={:?}, {:?}", b_def, b_substs diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs index a42a05c5f0284..0186d164a4c53 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -256,9 +256,9 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { return; } - let bound_predicate = obligation.predicate.kind(); + let bound_predicate = obligation.predicate.bound_atom(); match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(trait_predicate, _) => { + ty::PredicateAtom::Trait(trait_predicate, _) => { let trait_predicate = bound_predicate.rebind(trait_predicate); let trait_predicate = self.resolve_vars_if_possible(trait_predicate); @@ -517,14 +517,14 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { err } - ty::PredicateKind::Subtype(predicate) => { + ty::PredicateAtom::Subtype(predicate) => { // Errors for Subtype predicates show up as // `FulfillmentErrorCode::CodeSubtypeError`, // not selection error. span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate) } - ty::PredicateKind::RegionOutlives(predicate) => { + ty::PredicateAtom::RegionOutlives(predicate) => { let predicate = bound_predicate.rebind(predicate); let predicate = self.resolve_vars_if_possible(predicate); let err = self @@ -541,7 +541,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { ) } - ty::PredicateKind::Projection(..) | ty::PredicateKind::TypeOutlives(..) => { + ty::PredicateAtom::Projection(..) | ty::PredicateAtom::TypeOutlives(..) => { let predicate = self.resolve_vars_if_possible(obligation.predicate); struct_span_err!( self.tcx.sess, @@ -552,12 +552,12 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { ) } - ty::PredicateKind::ObjectSafe(trait_def_id) => { + ty::PredicateAtom::ObjectSafe(trait_def_id) => { let violations = self.tcx.object_safety_violations(trait_def_id); report_object_safety_error(self.tcx, span, trait_def_id, violations) } - ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => { + ty::PredicateAtom::ClosureKind(closure_def_id, closure_substs, kind) => { let found_kind = self.closure_kind(closure_substs).unwrap(); let closure_span = self.tcx.sess.source_map().guess_head_span( @@ -589,23 +589,23 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { if let Some(typeck_results) = self.in_progress_typeck_results { let typeck_results = typeck_results.borrow(); match (found_kind, typeck_results.closure_kind_origins().get(hir_id)) { - (ty::ClosureKind::FnOnce, Some((span, place))) => { + (ty::ClosureKind::FnOnce, Some((span, name))) => { err.span_label( *span, format!( "closure is `FnOnce` because it moves the \ variable `{}` out of its environment", - ty::place_to_string_for_capture(tcx, place) + name ), ); } - (ty::ClosureKind::FnMut, Some((span, place))) => { + (ty::ClosureKind::FnMut, Some((span, name))) => { err.span_label( *span, format!( "closure is `FnMut` because it mutates the \ variable `{}` here", - ty::place_to_string_for_capture(tcx, place) + name ), ); } @@ -617,7 +617,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { return; } - ty::PredicateKind::WellFormed(ty) => { + ty::PredicateAtom::WellFormed(ty) => { if !self.tcx.sess.opts.debugging_opts.chalk { // WF predicates cannot themselves make // errors. They can only block due to @@ -635,7 +635,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { } } - ty::PredicateKind::ConstEvaluatable(..) => { + ty::PredicateAtom::ConstEvaluatable(..) => { // Errors for `ConstEvaluatable` predicates show up as // `SelectionError::ConstEvalFailure`, // not `Unimplemented`. @@ -646,7 +646,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { ) } - ty::PredicateKind::ConstEquate(..) => { + ty::PredicateAtom::ConstEquate(..) => { // Errors for `ConstEquate` predicates show up as // `SelectionError::ConstEvalFailure`, // not `Unimplemented`. @@ -657,7 +657,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { ) } - ty::PredicateKind::TypeWellFormedFromEnv(..) => span_bug!( + ty::PredicateAtom::TypeWellFormedFromEnv(..) => span_bug!( span, "TypeWellFormedFromEnv predicate should only exist in the environment" ), @@ -830,7 +830,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { .collect::>(), ), Node::Ctor(ref variant_data) => { - let span = variant_data.ctor_hir_id().map_or(DUMMY_SP, |id| hir.span(id)); + let span = variant_data.ctor_hir_id().map(|id| hir.span(id)).unwrap_or(DUMMY_SP); let span = sm.guess_head_span(span); (span, vec![ArgKind::empty(); variant_data.fields().len()]) } @@ -1069,9 +1069,9 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { } // FIXME: It should be possible to deal with `ForAll` in a cleaner way. - let bound_error = error.kind(); - let (cond, error) = match (cond.kind().skip_binder(), bound_error.skip_binder()) { - (ty::PredicateKind::Trait(..), ty::PredicateKind::Trait(error, _)) => { + let bound_error = error.bound_atom(); + let (cond, error) = match (cond.skip_binders(), bound_error.skip_binder()) { + (ty::PredicateAtom::Trait(..), ty::PredicateAtom::Trait(error, _)) => { (cond, bound_error.rebind(error)) } _ => { @@ -1081,8 +1081,8 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { }; for obligation in super::elaborate_predicates(self.tcx, std::iter::once(cond)) { - let bound_predicate = obligation.predicate.kind(); - if let ty::PredicateKind::Trait(implication, _) = bound_predicate.skip_binder() { + let bound_predicate = obligation.predicate.bound_atom(); + if let ty::PredicateAtom::Trait(implication, _) = bound_predicate.skip_binder() { let error = error.to_poly_trait_ref(); let implication = bound_predicate.rebind(implication.trait_ref); // FIXME: I'm just not taking associated types at all here. @@ -1162,8 +1162,8 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { // // this can fail if the problem was higher-ranked, in which // cause I have no idea for a good error message. - let bound_predicate = predicate.kind(); - if let ty::PredicateKind::Projection(data) = bound_predicate.skip_binder() { + let bound_predicate = predicate.bound_atom(); + if let ty::PredicateAtom::Projection(data) = bound_predicate.skip_binder() { let mut selcx = SelectionContext::new(self); let (data, _) = self.replace_bound_vars_with_fresh_vars( obligation.cause.span, @@ -1452,9 +1452,9 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { return; } - let bound_predicate = predicate.kind(); + let bound_predicate = predicate.bound_atom(); let mut err = match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(data, _) => { + ty::PredicateAtom::Trait(data, _) => { let trait_ref = bound_predicate.rebind(data.trait_ref); debug!("trait_ref {:?}", trait_ref); @@ -1498,18 +1498,11 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { // check upstream for type errors and don't add the obligations to // begin with in those cases. if self.tcx.lang_items().sized_trait() == Some(trait_ref.def_id()) { - self.emit_inference_failure_err(body_id, span, subst, vec![], ErrorCode::E0282) - .emit(); + self.emit_inference_failure_err(body_id, span, subst, ErrorCode::E0282).emit(); return; } - let impl_candidates = self.find_similar_impl_candidates(trait_ref); - let mut err = self.emit_inference_failure_err( - body_id, - span, - subst, - impl_candidates, - ErrorCode::E0283, - ); + let mut err = + self.emit_inference_failure_err(body_id, span, subst, ErrorCode::E0283); err.note(&format!("cannot satisfy `{}`", predicate)); if let ObligationCauseCode::ItemObligation(def_id) = obligation.cause.code { self.suggest_fully_qualified_path(&mut err, def_id, span, trait_ref.def_id()); @@ -1566,17 +1559,17 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { err } - ty::PredicateKind::WellFormed(arg) => { + ty::PredicateAtom::WellFormed(arg) => { // Same hacky approach as above to avoid deluging user // with error messages. if arg.references_error() || self.tcx.sess.has_errors() { return; } - self.emit_inference_failure_err(body_id, span, arg, vec![], ErrorCode::E0282) + self.emit_inference_failure_err(body_id, span, arg, ErrorCode::E0282) } - ty::PredicateKind::Subtype(data) => { + ty::PredicateAtom::Subtype(data) => { if data.references_error() || self.tcx.sess.has_errors() { // no need to overload user in such cases return; @@ -1584,9 +1577,9 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { let SubtypePredicate { a_is_expected: _, a, b } = data; // both must be type variables, or the other would've been instantiated assert!(a.is_ty_var() && b.is_ty_var()); - self.emit_inference_failure_err(body_id, span, a.into(), vec![], ErrorCode::E0282) + self.emit_inference_failure_err(body_id, span, a.into(), ErrorCode::E0282) } - ty::PredicateKind::Projection(data) => { + ty::PredicateAtom::Projection(data) => { let trait_ref = bound_predicate.rebind(data).to_poly_trait_ref(self.tcx); let self_ty = trait_ref.skip_binder().self_ty(); let ty = data.ty; @@ -1599,7 +1592,6 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { body_id, span, self_ty.into(), - vec![], ErrorCode::E0284, ); err.note(&format!("cannot satisfy `{}`", predicate)); @@ -1717,10 +1709,9 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { obligation: &PredicateObligation<'tcx>, ) { let (pred, item_def_id, span) = - match (obligation.predicate.kind().skip_binder(), obligation.cause.code.peel_derives()) - { + match (obligation.predicate.skip_binders(), obligation.cause.code.peel_derives()) { ( - ty::PredicateKind::Trait(pred, _), + ty::PredicateAtom::Trait(pred, _), &ObligationCauseCode::BindingObligation(item_def_id, span), ) => (pred, item_def_id, span), _ => return, diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index 1830aaa4471a6..79fea83a6674d 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -393,7 +393,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(_, _, generics, _, _) - | hir::ItemKind::Impl(hir::Impl { generics, .. }), + | hir::ItemKind::Impl { generics, .. }, .. }) if projection.is_some() => { // Missing restriction on associated type of type parameter (unmet projection). @@ -416,7 +416,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { | hir::ItemKind::Enum(_, generics) | hir::ItemKind::Union(_, generics) | hir::ItemKind::Trait(_, _, generics, ..) - | hir::ItemKind::Impl(hir::Impl { generics, .. }) + | hir::ItemKind::Impl { generics, .. } | hir::ItemKind::Fn(_, generics, _) | hir::ItemKind::TyAlias(_, generics) | hir::ItemKind::TraitAlias(generics, _) @@ -1292,8 +1292,8 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { // the type. The last generator (`outer_generator` below) has information about where the // bound was introduced. At least one generator should be present for this diagnostic to be // modified. - let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() { - ty::PredicateKind::Trait(p, _) => (Some(p.trait_ref), Some(p.self_ty())), + let (mut trait_ref, mut target_ty) = match obligation.predicate.skip_binders() { + ty::PredicateAtom::Trait(p, _) => (Some(p.trait_ref), Some(p.self_ty())), _ => (None, None), }; let mut generator = None; @@ -2278,12 +2278,6 @@ impl<'v> Visitor<'v> for ReturnsVisitor<'v> { self.visit_expr(expr); } } - hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => { - self.visit_expr(then); - if let Some(el) = else_opt { - self.visit_expr(el); - } - } hir::ExprKind::Match(_, arms, _) if self.in_block_tail => { for arm in arms { self.visit_expr(arm.body); diff --git a/compiler/rustc_trait_selection/src/traits/fulfill.rs b/compiler/rustc_trait_selection/src/traits/fulfill.rs index d4ced20f86319..a04f816b0f8a0 100644 --- a/compiler/rustc_trait_selection/src/traits/fulfill.rs +++ b/compiler/rustc_trait_selection/src/traits/fulfill.rs @@ -345,13 +345,12 @@ impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> { let infcx = self.selcx.infcx(); - let binder = obligation.predicate.kind(); - match binder.no_bound_vars() { - None => match binder.skip_binder() { + match *obligation.predicate.kind() { + ty::PredicateKind::ForAll(binder) => match binder.skip_binder() { // Evaluation will discard candidates using the leak check. // This means we need to pass it the bound version of our // predicate. - ty::PredicateKind::Trait(trait_ref, _constness) => { + ty::PredicateAtom::Trait(trait_ref, _constness) => { let trait_obligation = obligation.with(binder.rebind(trait_ref)); self.process_trait_obligation( @@ -360,7 +359,7 @@ impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> { &mut pending_obligation.stalled_on, ) } - ty::PredicateKind::Projection(data) => { + ty::PredicateAtom::Projection(data) => { let project_obligation = obligation.with(binder.rebind(data)); self.process_projection_obligation( @@ -368,25 +367,25 @@ impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> { &mut pending_obligation.stalled_on, ) } - ty::PredicateKind::RegionOutlives(_) - | ty::PredicateKind::TypeOutlives(_) - | ty::PredicateKind::WellFormed(_) - | ty::PredicateKind::ObjectSafe(_) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::Subtype(_) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) => { + ty::PredicateAtom::RegionOutlives(_) + | ty::PredicateAtom::TypeOutlives(_) + | ty::PredicateAtom::WellFormed(_) + | ty::PredicateAtom::ObjectSafe(_) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::Subtype(_) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) => { let pred = infcx.replace_bound_vars_with_placeholders(binder); ProcessResult::Changed(mk_pending(vec![ obligation.with(pred.to_predicate(self.selcx.tcx())), ])) } - ty::PredicateKind::TypeWellFormedFromEnv(..) => { + ty::PredicateAtom::TypeWellFormedFromEnv(..) => { bug!("TypeWellFormedFromEnv is only used for Chalk") } }, - Some(pred) => match pred { - ty::PredicateKind::Trait(data, _) => { + ty::PredicateKind::Atom(atom) => match atom { + ty::PredicateAtom::Trait(data, _) => { let trait_obligation = obligation.with(Binder::dummy(data)); self.process_trait_obligation( @@ -396,14 +395,14 @@ impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> { ) } - ty::PredicateKind::RegionOutlives(data) => { + ty::PredicateAtom::RegionOutlives(data) => { match infcx.region_outlives_predicate(&obligation.cause, Binder::dummy(data)) { Ok(()) => ProcessResult::Changed(vec![]), Err(_) => ProcessResult::Error(CodeSelectionError(Unimplemented)), } } - ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(t_a, r_b)) => { + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(t_a, r_b)) => { if self.register_region_obligations { self.selcx.infcx().register_region_obligation_with_cause( t_a, @@ -414,7 +413,7 @@ impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> { ProcessResult::Changed(vec![]) } - ty::PredicateKind::Projection(ref data) => { + ty::PredicateAtom::Projection(ref data) => { let project_obligation = obligation.with(Binder::dummy(*data)); self.process_projection_obligation( @@ -423,7 +422,7 @@ impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> { ) } - ty::PredicateKind::ObjectSafe(trait_def_id) => { + ty::PredicateAtom::ObjectSafe(trait_def_id) => { if !self.selcx.tcx().is_object_safe(trait_def_id) { ProcessResult::Error(CodeSelectionError(Unimplemented)) } else { @@ -431,7 +430,7 @@ impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> { } } - ty::PredicateKind::ClosureKind(_, closure_substs, kind) => { + ty::PredicateAtom::ClosureKind(_, closure_substs, kind) => { match self.selcx.infcx().closure_kind(closure_substs) { Some(closure_kind) => { if closure_kind.extends(kind) { @@ -444,7 +443,7 @@ impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> { } } - ty::PredicateKind::WellFormed(arg) => { + ty::PredicateAtom::WellFormed(arg) => { match wf::obligations( self.selcx.infcx(), obligation.param_env, @@ -462,7 +461,7 @@ impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> { } } - ty::PredicateKind::Subtype(subtype) => { + ty::PredicateAtom::Subtype(subtype) => { match self.selcx.infcx().subtype_predicate( &obligation.cause, obligation.param_env, @@ -488,7 +487,7 @@ impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> { } } - ty::PredicateKind::ConstEvaluatable(def_id, substs) => { + ty::PredicateAtom::ConstEvaluatable(def_id, substs) => { match const_evaluatable::is_const_evaluatable( self.selcx.infcx(), def_id, @@ -508,7 +507,7 @@ impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> { } } - ty::PredicateKind::ConstEquate(c1, c2) => { + ty::PredicateAtom::ConstEquate(c1, c2) => { debug!(?c1, ?c2, "equating consts"); if self.selcx.tcx().features().const_evaluatable_checked { // FIXME: we probably should only try to unify abstract constants @@ -594,7 +593,7 @@ impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> { } } } - ty::PredicateKind::TypeWellFormedFromEnv(..) => { + ty::PredicateAtom::TypeWellFormedFromEnv(..) => { bug!("TypeWellFormedFromEnv is only used for Chalk") } }, diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index dbc40a2eb9662..9c894e99a389a 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -324,7 +324,7 @@ pub fn normalize_param_env_or_error<'tcx>( // TypeOutlives predicates - these are normally used by regionck. let outlives_predicates: Vec<_> = predicates .drain_filter(|predicate| { - matches!(predicate.kind().skip_binder(), ty::PredicateKind::TypeOutlives(..)) + matches!(predicate.skip_binders(), ty::PredicateAtom::TypeOutlives(..)) }) .collect(); diff --git a/compiler/rustc_trait_selection/src/traits/object_safety.rs b/compiler/rustc_trait_selection/src/traits/object_safety.rs index a9723611f8113..8b6e30f34fd4a 100644 --- a/compiler/rustc_trait_selection/src/traits/object_safety.rs +++ b/compiler/rustc_trait_selection/src/traits/object_safety.rs @@ -273,12 +273,12 @@ fn predicate_references_self( ) -> Option { let self_ty = tcx.types.self_param; let has_self_ty = |arg: &GenericArg<'_>| arg.walk().any(|arg| arg == self_ty.into()); - match predicate.kind().skip_binder() { - ty::PredicateKind::Trait(ref data, _) => { + match predicate.skip_binders() { + ty::PredicateAtom::Trait(ref data, _) => { // In the case of a trait predicate, we can skip the "self" type. if data.trait_ref.substs[1..].iter().any(has_self_ty) { Some(sp) } else { None } } - ty::PredicateKind::Projection(ref data) => { + ty::PredicateAtom::Projection(ref data) => { // And similarly for projections. This should be redundant with // the previous check because any projection should have a // matching `Trait` predicate with the same inputs, but we do @@ -300,15 +300,15 @@ fn predicate_references_self( None } } - ty::PredicateKind::WellFormed(..) - | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::TypeOutlives(..) - | ty::PredicateKind::RegionOutlives(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::Subtype(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) - | ty::PredicateKind::TypeWellFormedFromEnv(..) => None, + ty::PredicateAtom::WellFormed(..) + | ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::TypeOutlives(..) + | ty::PredicateAtom::RegionOutlives(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) + | ty::PredicateAtom::TypeWellFormedFromEnv(..) => None, } } @@ -328,20 +328,20 @@ fn generics_require_sized_self(tcx: TyCtxt<'_>, def_id: DefId) -> bool { let predicates = tcx.predicates_of(def_id); let predicates = predicates.instantiate_identity(tcx).predicates; elaborate_predicates(tcx, predicates.into_iter()).any(|obligation| { - match obligation.predicate.kind().skip_binder() { - ty::PredicateKind::Trait(ref trait_pred, _) => { + match obligation.predicate.skip_binders() { + ty::PredicateAtom::Trait(ref trait_pred, _) => { trait_pred.def_id() == sized_def_id && trait_pred.self_ty().is_param(0) } - ty::PredicateKind::Projection(..) - | ty::PredicateKind::Subtype(..) - | ty::PredicateKind::RegionOutlives(..) - | ty::PredicateKind::WellFormed(..) - | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::TypeOutlives(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) - | ty::PredicateKind::TypeWellFormedFromEnv(..) => false, + ty::PredicateAtom::Projection(..) + | ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::RegionOutlives(..) + | ty::PredicateAtom::WellFormed(..) + | ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::TypeOutlives(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) + | ty::PredicateAtom::TypeWellFormedFromEnv(..) => false, } }) } @@ -843,7 +843,7 @@ fn contains_illegal_self_type_reference<'tcx, T: TypeFoldable<'tcx>>( } fn visit_predicate(&mut self, pred: ty::Predicate<'tcx>) -> ControlFlow { - if let ty::PredicateKind::ConstEvaluatable(def, substs) = pred.kind().skip_binder() { + if let ty::PredicateAtom::ConstEvaluatable(def, substs) = pred.skip_binders() { // FIXME(const_evaluatable_checked): We should probably deduplicate the logic for // `AbstractConst`s here, it might make sense to change `ConstEvaluatable` to // take a `ty::Const` instead. diff --git a/compiler/rustc_trait_selection/src/traits/project.rs b/compiler/rustc_trait_selection/src/traits/project.rs index 75ff93197126c..fa0526445c194 100644 --- a/compiler/rustc_trait_selection/src/traits/project.rs +++ b/compiler/rustc_trait_selection/src/traits/project.rs @@ -625,7 +625,7 @@ fn prune_cache_value_obligations<'a, 'tcx>( .obligations .iter() .filter(|obligation| { - let bound_predicate = obligation.predicate.kind(); + let bound_predicate = obligation.predicate.bound_atom(); match bound_predicate.skip_binder() { // We found a `T: Foo` predicate, let's check // if `U` references any unresolved type @@ -636,7 +636,7 @@ fn prune_cache_value_obligations<'a, 'tcx>( // indirect obligations (e.g., we project to `?0`, // but we have `T: Foo` and `?1: Bar`). - ty::PredicateKind::Projection(data) => { + ty::PredicateAtom::Projection(data) => { infcx.unresolved_type_vars(&bound_predicate.rebind(data.ty)).is_some() } @@ -917,8 +917,8 @@ fn assemble_candidates_from_predicates<'cx, 'tcx>( let infcx = selcx.infcx(); for predicate in env_predicates { debug!(?predicate); - let bound_predicate = predicate.kind(); - if let ty::PredicateKind::Projection(data) = predicate.kind().skip_binder() { + let bound_predicate = predicate.bound_atom(); + if let ty::PredicateAtom::Projection(data) = predicate.skip_binders() { let data = bound_predicate.rebind(data); let same_def_id = data.projection_def_id() == obligation.predicate.item_def_id; diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/prove_predicate.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/prove_predicate.rs index de538c62c5e39..93ddcb6855400 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/prove_predicate.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/prove_predicate.rs @@ -15,7 +15,7 @@ impl<'tcx> super::QueryTypeOp<'tcx> for ProvePredicate<'tcx> { // `&T`, accounts for about 60% percentage of the predicates // we have to prove. No need to canonicalize and all that for // such cases. - if let ty::PredicateKind::Trait(trait_ref, _) = key.value.predicate.kind().skip_binder() { + if let ty::PredicateAtom::Trait(trait_ref, _) = key.value.predicate.skip_binders() { if let Some(sized_def_id) = tcx.lang_items().sized_trait() { if trait_ref.def_id() == sized_def_id { if trait_ref.self_ty().is_trivially_sized(tcx) { diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index 3015188fd447a..030c29171a153 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -432,7 +432,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { .predicates .into_iter() { - if let ty::PredicateKind::Trait(..) = super_trait.kind().skip_binder() { + if let ty::PredicateAtom::Trait(..) = super_trait.skip_binders() { let normalized_super_trait = normalize_with_depth_to( self, obligation.param_env, @@ -641,7 +641,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { obligations.push(Obligation::new( obligation.cause.clone(), obligation.param_env, - ty::PredicateKind::ClosureKind(closure_def_id, substs, kind) + ty::PredicateAtom::ClosureKind(closure_def_id, substs, kind) .to_predicate(self.tcx()), )); } diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 614a551004ecf..8ca540fc8933c 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -454,16 +454,16 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } let result = ensure_sufficient_stack(|| { - let bound_predicate = obligation.predicate.kind(); + let bound_predicate = obligation.predicate.bound_atom(); match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(t, _) => { + ty::PredicateAtom::Trait(t, _) => { let t = bound_predicate.rebind(t); debug_assert!(!t.has_escaping_bound_vars()); let obligation = obligation.with(t); self.evaluate_trait_predicate_recursively(previous_stack, obligation) } - ty::PredicateKind::Subtype(p) => { + ty::PredicateAtom::Subtype(p) => { let p = bound_predicate.rebind(p); // Does this code ever run? match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) { @@ -479,7 +479,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } } - ty::PredicateKind::WellFormed(arg) => match wf::obligations( + ty::PredicateAtom::WellFormed(arg) => match wf::obligations( self.infcx, obligation.param_env, obligation.cause.body_id, @@ -494,12 +494,12 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { None => Ok(EvaluatedToAmbig), }, - ty::PredicateKind::TypeOutlives(..) | ty::PredicateKind::RegionOutlives(..) => { + ty::PredicateAtom::TypeOutlives(..) | ty::PredicateAtom::RegionOutlives(..) => { // We do not consider region relationships when evaluating trait matches. Ok(EvaluatedToOkModuloRegions) } - ty::PredicateKind::ObjectSafe(trait_def_id) => { + ty::PredicateAtom::ObjectSafe(trait_def_id) => { if self.tcx().is_object_safe(trait_def_id) { Ok(EvaluatedToOk) } else { @@ -507,7 +507,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } } - ty::PredicateKind::Projection(data) => { + ty::PredicateAtom::Projection(data) => { let data = bound_predicate.rebind(data); let project_obligation = obligation.with(data); match project::poly_project_and_unify_type(self, &project_obligation) { @@ -528,7 +528,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } } - ty::PredicateKind::ClosureKind(_, closure_substs, kind) => { + ty::PredicateAtom::ClosureKind(_, closure_substs, kind) => { match self.infcx.closure_kind(closure_substs) { Some(closure_kind) => { if closure_kind.extends(kind) { @@ -541,7 +541,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } } - ty::PredicateKind::ConstEvaluatable(def_id, substs) => { + ty::PredicateAtom::ConstEvaluatable(def_id, substs) => { match const_evaluatable::is_const_evaluatable( self.infcx, def_id, @@ -555,7 +555,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } } - ty::PredicateKind::ConstEquate(c1, c2) => { + ty::PredicateAtom::ConstEquate(c1, c2) => { debug!(?c1, ?c2, "evaluate_predicate_recursively: equating consts"); let evaluate = |c: &'tcx ty::Const<'tcx>| { @@ -598,7 +598,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } } } - ty::PredicateKind::TypeWellFormedFromEnv(..) => { + ty::PredicateAtom::TypeWellFormedFromEnv(..) => { bug!("TypeWellFormedFromEnv is only used for chalk") } } @@ -845,8 +845,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool { - let result = match predicate.kind().skip_binder() { - ty::PredicateKind::Trait(ref data, _) => self.tcx().trait_is_auto(data.def_id()), + let result = match predicate.skip_binders() { + ty::PredicateAtom::Trait(ref data, _) => self.tcx().trait_is_auto(data.def_id()), _ => false, }; debug!(?predicate, ?result, "coinductive_predicate"); @@ -1174,8 +1174,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { .iter() .enumerate() .filter_map(|(idx, bound)| { - let bound_predicate = bound.kind(); - if let ty::PredicateKind::Trait(pred, _) = bound_predicate.skip_binder() { + let bound_predicate = bound.bound_atom(); + if let ty::PredicateAtom::Trait(pred, _) = bound_predicate.skip_binder() { let bound = bound_predicate.rebind(pred.trait_ref); if self.infcx.probe(|_| { match self.match_normalize_trait_ref( diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index e6ef9b137d899..3f58fd72f409c 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -106,28 +106,28 @@ pub fn predicate_obligations<'a, 'tcx>( }; // It's ok to skip the binder here because wf code is prepared for it - match predicate.kind().skip_binder() { - ty::PredicateKind::Trait(t, _) => { + match predicate.skip_binders() { + ty::PredicateAtom::Trait(t, _) => { wf.compute_trait_ref(&t.trait_ref, Elaborate::None); } - ty::PredicateKind::RegionOutlives(..) => {} - ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => { + ty::PredicateAtom::RegionOutlives(..) => {} + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => { wf.compute(ty.into()); } - ty::PredicateKind::Projection(t) => { + ty::PredicateAtom::Projection(t) => { wf.compute_projection(t.projection_ty); wf.compute(t.ty.into()); } - ty::PredicateKind::WellFormed(arg) => { + ty::PredicateAtom::WellFormed(arg) => { wf.compute(arg); } - ty::PredicateKind::ObjectSafe(_) => {} - ty::PredicateKind::ClosureKind(..) => {} - ty::PredicateKind::Subtype(ty::SubtypePredicate { a, b, a_is_expected: _ }) => { + ty::PredicateAtom::ObjectSafe(_) => {} + ty::PredicateAtom::ClosureKind(..) => {} + ty::PredicateAtom::Subtype(ty::SubtypePredicate { a, b, a_is_expected: _ }) => { wf.compute(a.into()); wf.compute(b.into()); } - ty::PredicateKind::ConstEvaluatable(def, substs) => { + ty::PredicateAtom::ConstEvaluatable(def, substs) => { let obligations = wf.nominal_obligations(def.did, substs); wf.out.extend(obligations); @@ -135,11 +135,11 @@ pub fn predicate_obligations<'a, 'tcx>( wf.compute(arg); } } - ty::PredicateKind::ConstEquate(c1, c2) => { + ty::PredicateAtom::ConstEquate(c1, c2) => { wf.compute(c1.into()); wf.compute(c2.into()); } - ty::PredicateKind::TypeWellFormedFromEnv(..) => { + ty::PredicateAtom::TypeWellFormedFromEnv(..) => { bug!("TypeWellFormedFromEnv is only used for Chalk") } } @@ -199,7 +199,7 @@ fn extend_cause_with_original_assoc_item_obligation<'tcx>( trait_ref, item, cause, pred ); let items = match item { - Some(hir::Item { kind: hir::ItemKind::Impl(impl_), .. }) => impl_.items, + Some(hir::Item { kind: hir::ItemKind::Impl { items, .. }, .. }) => items, _ => return, }; let fix_span = @@ -209,8 +209,8 @@ fn extend_cause_with_original_assoc_item_obligation<'tcx>( }; // It is fine to skip the binder as we don't care about regions here. - match pred.kind().skip_binder() { - ty::PredicateKind::Projection(proj) => { + match pred.skip_binders() { + ty::PredicateAtom::Projection(proj) => { // The obligation comes not from the current `impl` nor the `trait` being implemented, // but rather from a "second order" obligation, where an associated type has a // projection coming from another associated type. See @@ -225,7 +225,7 @@ fn extend_cause_with_original_assoc_item_obligation<'tcx>( } } } - ty::PredicateKind::Trait(pred, _) => { + ty::PredicateAtom::Trait(pred, _) => { // An associated item obligation born out of the `trait` failed to be met. An example // can be seen in `ui/associated-types/point-at-type-on-obligation-failure-2.rs`. debug!("extended_cause_with_original_assoc_item_obligation trait proj {:?}", pred); @@ -333,9 +333,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { let mut new_cause = cause.clone(); // The first subst is the self ty - use the correct span for it. if i == 0 { - if let Some(hir::ItemKind::Impl(hir::Impl { self_ty, .. })) = - item.map(|i| &i.kind) - { + if let Some(hir::ItemKind::Impl { self_ty, .. }) = item.map(|i| &i.kind) { new_cause.make_mut().span = self_ty.span; } } @@ -343,7 +341,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { new_cause, depth, param_env, - ty::PredicateKind::WellFormed(arg).to_predicate(tcx), + ty::PredicateAtom::WellFormed(arg).to_predicate(tcx), ) }), ); @@ -393,7 +391,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { cause.clone(), depth, param_env, - ty::PredicateKind::WellFormed(arg).to_predicate(tcx), + ty::PredicateAtom::WellFormed(arg).to_predicate(tcx), ) }), ); @@ -436,7 +434,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { let obligations = self.nominal_obligations(def.did, substs); self.out.extend(obligations); - let predicate = ty::PredicateKind::ConstEvaluatable(def, substs) + let predicate = ty::PredicateAtom::ConstEvaluatable(def, substs) .to_predicate(self.tcx()); let cause = self.cause(traits::MiscObligation); self.out.push(traits::Obligation::with_depth( @@ -460,7 +458,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { cause, self.recursion_depth, self.param_env, - ty::PredicateKind::WellFormed(resolved_constant.into()) + ty::PredicateAtom::WellFormed(resolved_constant.into()) .to_predicate(self.tcx()), )); } @@ -547,7 +545,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { cause, depth, param_env, - ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(rty, r)) + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(rty, r)) .to_predicate(self.tcx()), )); } @@ -637,7 +635,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { cause.clone(), depth, param_env, - ty::PredicateKind::ObjectSafe(did).to_predicate(tcx), + ty::PredicateAtom::ObjectSafe(did).to_predicate(tcx), ) })); } @@ -664,7 +662,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { cause, self.recursion_depth, param_env, - ty::PredicateKind::WellFormed(ty.into()).to_predicate(self.tcx()), + ty::PredicateAtom::WellFormed(ty.into()).to_predicate(self.tcx()), )); } else { // Yes, resolved, proceed with the result. diff --git a/compiler/rustc_traits/src/chalk/lowering.rs b/compiler/rustc_traits/src/chalk/lowering.rs index 48d47054a4182..8aa68e533a2e1 100644 --- a/compiler/rustc_traits/src/chalk/lowering.rs +++ b/compiler/rustc_traits/src/chalk/lowering.rs @@ -81,36 +81,39 @@ impl<'tcx> LowerInto<'tcx, chalk_ir::InEnvironment, ) -> chalk_ir::InEnvironment>> { let clauses = self.environment.into_iter().map(|predicate| { - let (predicate, binders, _named_regions) = - collect_bound_vars(interner, interner.tcx, predicate.kind()); + let (predicate, binders, _named_regions) = collect_bound_vars( + interner, + interner.tcx, + predicate.bound_atom_with_opt_escaping(interner.tcx), + ); let consequence = match predicate { - ty::PredicateKind::TypeWellFormedFromEnv(ty) => { + ty::PredicateAtom::TypeWellFormedFromEnv(ty) => { chalk_ir::DomainGoal::FromEnv(chalk_ir::FromEnv::Ty(ty.lower_into(interner))) } - ty::PredicateKind::Trait(predicate, _) => chalk_ir::DomainGoal::FromEnv( + ty::PredicateAtom::Trait(predicate, _) => chalk_ir::DomainGoal::FromEnv( chalk_ir::FromEnv::Trait(predicate.trait_ref.lower_into(interner)), ), - ty::PredicateKind::RegionOutlives(predicate) => chalk_ir::DomainGoal::Holds( + ty::PredicateAtom::RegionOutlives(predicate) => chalk_ir::DomainGoal::Holds( chalk_ir::WhereClause::LifetimeOutlives(chalk_ir::LifetimeOutlives { a: predicate.0.lower_into(interner), b: predicate.1.lower_into(interner), }), ), - ty::PredicateKind::TypeOutlives(predicate) => chalk_ir::DomainGoal::Holds( + ty::PredicateAtom::TypeOutlives(predicate) => chalk_ir::DomainGoal::Holds( chalk_ir::WhereClause::TypeOutlives(chalk_ir::TypeOutlives { ty: predicate.0.lower_into(interner), lifetime: predicate.1.lower_into(interner), }), ), - ty::PredicateKind::Projection(predicate) => chalk_ir::DomainGoal::Holds( + ty::PredicateAtom::Projection(predicate) => chalk_ir::DomainGoal::Holds( chalk_ir::WhereClause::AliasEq(predicate.lower_into(interner)), ), - ty::PredicateKind::WellFormed(..) - | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::Subtype(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) => bug!("unexpected predicate {}", predicate), + ty::PredicateAtom::WellFormed(..) + | ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) => bug!("unexpected predicate {}", predicate), }; let value = chalk_ir::ProgramClauseImplication { consequence, @@ -133,16 +136,19 @@ impl<'tcx> LowerInto<'tcx, chalk_ir::InEnvironment LowerInto<'tcx, chalk_ir::GoalData>> for ty::Predicate<'tcx> { fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::GoalData> { - let (predicate, binders, _named_regions) = - collect_bound_vars(interner, interner.tcx, self.kind()); + let (predicate, binders, _named_regions) = collect_bound_vars( + interner, + interner.tcx, + self.bound_atom_with_opt_escaping(interner.tcx), + ); let value = match predicate { - ty::PredicateKind::Trait(predicate, _) => { + ty::PredicateAtom::Trait(predicate, _) => { chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::Holds( chalk_ir::WhereClause::Implemented(predicate.trait_ref.lower_into(interner)), )) } - ty::PredicateKind::RegionOutlives(predicate) => { + ty::PredicateAtom::RegionOutlives(predicate) => { chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::Holds( chalk_ir::WhereClause::LifetimeOutlives(chalk_ir::LifetimeOutlives { a: predicate.0.lower_into(interner), @@ -150,7 +156,7 @@ impl<'tcx> LowerInto<'tcx, chalk_ir::GoalData>> for ty::Predi }), )) } - ty::PredicateKind::TypeOutlives(predicate) => { + ty::PredicateAtom::TypeOutlives(predicate) => { chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::Holds( chalk_ir::WhereClause::TypeOutlives(chalk_ir::TypeOutlives { ty: predicate.0.lower_into(interner), @@ -158,12 +164,12 @@ impl<'tcx> LowerInto<'tcx, chalk_ir::GoalData>> for ty::Predi }), )) } - ty::PredicateKind::Projection(predicate) => { + ty::PredicateAtom::Projection(predicate) => { chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::Holds( chalk_ir::WhereClause::AliasEq(predicate.lower_into(interner)), )) } - ty::PredicateKind::WellFormed(arg) => match arg.unpack() { + ty::PredicateAtom::WellFormed(arg) => match arg.unpack() { GenericArgKind::Type(ty) => match ty.kind() { // FIXME(chalk): In Chalk, a placeholder is WellFormed if it // `FromEnv`. However, when we "lower" Params, we don't update @@ -183,7 +189,7 @@ impl<'tcx> LowerInto<'tcx, chalk_ir::GoalData>> for ty::Predi GenericArgKind::Lifetime(lt) => bug!("unexpect well formed predicate: {:?}", lt), }, - ty::PredicateKind::ObjectSafe(t) => chalk_ir::GoalData::DomainGoal( + ty::PredicateAtom::ObjectSafe(t) => chalk_ir::GoalData::DomainGoal( chalk_ir::DomainGoal::ObjectSafe(chalk_ir::TraitId(t)), ), @@ -191,13 +197,13 @@ impl<'tcx> LowerInto<'tcx, chalk_ir::GoalData>> for ty::Predi // // We can defer this, but ultimately we'll want to express // some of these in terms of chalk operations. - ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::Subtype(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) => { + ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) => { chalk_ir::GoalData::All(chalk_ir::Goals::empty(interner)) } - ty::PredicateKind::TypeWellFormedFromEnv(ty) => chalk_ir::GoalData::DomainGoal( + ty::PredicateAtom::TypeWellFormedFromEnv(ty) => chalk_ir::GoalData::DomainGoal( chalk_ir::DomainGoal::FromEnv(chalk_ir::FromEnv::Ty(ty.lower_into(interner))), ), }; @@ -567,35 +573,38 @@ impl<'tcx> LowerInto<'tcx, Option, ) -> Option>> { - let (predicate, binders, _named_regions) = - collect_bound_vars(interner, interner.tcx, self.kind()); + let (predicate, binders, _named_regions) = collect_bound_vars( + interner, + interner.tcx, + self.bound_atom_with_opt_escaping(interner.tcx), + ); let value = match predicate { - ty::PredicateKind::Trait(predicate, _) => { + ty::PredicateAtom::Trait(predicate, _) => { Some(chalk_ir::WhereClause::Implemented(predicate.trait_ref.lower_into(interner))) } - ty::PredicateKind::RegionOutlives(predicate) => { + ty::PredicateAtom::RegionOutlives(predicate) => { Some(chalk_ir::WhereClause::LifetimeOutlives(chalk_ir::LifetimeOutlives { a: predicate.0.lower_into(interner), b: predicate.1.lower_into(interner), })) } - ty::PredicateKind::TypeOutlives(predicate) => { + ty::PredicateAtom::TypeOutlives(predicate) => { Some(chalk_ir::WhereClause::TypeOutlives(chalk_ir::TypeOutlives { ty: predicate.0.lower_into(interner), lifetime: predicate.1.lower_into(interner), })) } - ty::PredicateKind::Projection(predicate) => { + ty::PredicateAtom::Projection(predicate) => { Some(chalk_ir::WhereClause::AliasEq(predicate.lower_into(interner))) } - ty::PredicateKind::WellFormed(_ty) => None, - - ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::Subtype(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) - | ty::PredicateKind::TypeWellFormedFromEnv(..) => { + ty::PredicateAtom::WellFormed(_ty) => None, + + ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) + | ty::PredicateAtom::TypeWellFormedFromEnv(..) => { bug!("unexpected predicate {}", &self) } }; @@ -698,29 +707,32 @@ impl<'tcx> LowerInto<'tcx, Option, ) -> Option>> { - let (predicate, binders, _named_regions) = - collect_bound_vars(interner, interner.tcx, self.kind()); + let (predicate, binders, _named_regions) = collect_bound_vars( + interner, + interner.tcx, + self.bound_atom_with_opt_escaping(interner.tcx), + ); match predicate { - ty::PredicateKind::Trait(predicate, _) => Some(chalk_ir::Binders::new( + ty::PredicateAtom::Trait(predicate, _) => Some(chalk_ir::Binders::new( binders, chalk_solve::rust_ir::InlineBound::TraitBound( predicate.trait_ref.lower_into(interner), ), )), - ty::PredicateKind::Projection(predicate) => Some(chalk_ir::Binders::new( + ty::PredicateAtom::Projection(predicate) => Some(chalk_ir::Binders::new( binders, chalk_solve::rust_ir::InlineBound::AliasEqBound(predicate.lower_into(interner)), )), - ty::PredicateKind::TypeOutlives(_predicate) => None, - ty::PredicateKind::WellFormed(_ty) => None, - - ty::PredicateKind::RegionOutlives(..) - | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::Subtype(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) - | ty::PredicateKind::TypeWellFormedFromEnv(..) => { + ty::PredicateAtom::TypeOutlives(_predicate) => None, + ty::PredicateAtom::WellFormed(_ty) => None, + + ty::PredicateAtom::RegionOutlives(..) + | ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) + | ty::PredicateAtom::TypeWellFormedFromEnv(..) => { bug!("unexpected predicate {}", &self) } } diff --git a/compiler/rustc_traits/src/implied_outlives_bounds.rs b/compiler/rustc_traits/src/implied_outlives_bounds.rs index 90ba90259c32b..97017fbf2e56a 100644 --- a/compiler/rustc_traits/src/implied_outlives_bounds.rs +++ b/compiler/rustc_traits/src/implied_outlives_bounds.rs @@ -94,27 +94,27 @@ fn compute_implied_outlives_bounds<'tcx>( // region relationships. implied_bounds.extend(obligations.into_iter().flat_map(|obligation| { assert!(!obligation.has_escaping_bound_vars()); - match obligation.predicate.kind().no_bound_vars() { - None => vec![], - Some(pred) => match pred { - ty::PredicateKind::Trait(..) - | ty::PredicateKind::Subtype(..) - | ty::PredicateKind::Projection(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) - | ty::PredicateKind::TypeWellFormedFromEnv(..) => vec![], - ty::PredicateKind::WellFormed(arg) => { + match obligation.predicate.kind() { + &ty::PredicateKind::ForAll(..) => vec![], + &ty::PredicateKind::Atom(atom) => match atom { + ty::PredicateAtom::Trait(..) + | ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::Projection(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) + | ty::PredicateAtom::TypeWellFormedFromEnv(..) => vec![], + ty::PredicateAtom::WellFormed(arg) => { wf_args.push(arg); vec![] } - ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(r_a, r_b)) => { + ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate(r_a, r_b)) => { vec![OutlivesBound::RegionSubRegion(r_b, r_a)] } - ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty_a, r_b)) => { + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty_a, r_b)) => { let ty_a = infcx.resolve_vars_if_possible(ty_a); let mut components = smallvec![]; tcx.push_outlives_components(ty_a, &mut components); diff --git a/compiler/rustc_traits/src/normalize_erasing_regions.rs b/compiler/rustc_traits/src/normalize_erasing_regions.rs index 1213e5539084e..4841e4286a994 100644 --- a/compiler/rustc_traits/src/normalize_erasing_regions.rs +++ b/compiler/rustc_traits/src/normalize_erasing_regions.rs @@ -46,16 +46,16 @@ fn normalize_generic_arg_after_erasing_regions<'tcx>( } fn not_outlives_predicate(p: &ty::Predicate<'tcx>) -> bool { - match p.kind().skip_binder() { - ty::PredicateKind::RegionOutlives(..) | ty::PredicateKind::TypeOutlives(..) => false, - ty::PredicateKind::Trait(..) - | ty::PredicateKind::Projection(..) - | ty::PredicateKind::WellFormed(..) - | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::Subtype(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) - | ty::PredicateKind::TypeWellFormedFromEnv(..) => true, + match p.skip_binders() { + ty::PredicateAtom::RegionOutlives(..) | ty::PredicateAtom::TypeOutlives(..) => false, + ty::PredicateAtom::Trait(..) + | ty::PredicateAtom::Projection(..) + | ty::PredicateAtom::WellFormed(..) + | ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) + | ty::PredicateAtom::TypeWellFormedFromEnv(..) => true, } } diff --git a/compiler/rustc_traits/src/type_op.rs b/compiler/rustc_traits/src/type_op.rs index 6304f696b00fa..0addde5c44c89 100644 --- a/compiler/rustc_traits/src/type_op.rs +++ b/compiler/rustc_traits/src/type_op.rs @@ -140,7 +140,7 @@ impl AscribeUserTypeCx<'me, 'tcx> { self.relate(self_ty, Variance::Invariant, impl_self_ty)?; self.prove_predicate( - ty::PredicateKind::WellFormed(impl_self_ty.into()).to_predicate(self.tcx()), + ty::PredicateAtom::WellFormed(impl_self_ty.into()).to_predicate(self.tcx()), ); } @@ -155,7 +155,7 @@ impl AscribeUserTypeCx<'me, 'tcx> { // them? This would only be relevant if some input // type were ill-formed but did not appear in `ty`, // which...could happen with normalization... - self.prove_predicate(ty::PredicateKind::WellFormed(ty.into()).to_predicate(self.tcx())); + self.prove_predicate(ty::PredicateAtom::WellFormed(ty.into()).to_predicate(self.tcx())); Ok(()) } } diff --git a/compiler/rustc_ty_utils/src/ty.rs b/compiler/rustc_ty_utils/src/ty.rs index bd1d9cc895fb0..aa1de6d51cba2 100644 --- a/compiler/rustc_ty_utils/src/ty.rs +++ b/compiler/rustc_ty_utils/src/ty.rs @@ -5,7 +5,7 @@ use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}; use rustc_middle::hir::map as hir_map; use rustc_middle::ty::subst::Subst; use rustc_middle::ty::{ - self, Binder, Predicate, PredicateKind, ToPredicate, Ty, TyCtxt, WithConstness, + self, Binder, Predicate, PredicateAtom, PredicateKind, ToPredicate, Ty, TyCtxt, WithConstness, }; use rustc_session::CrateDisambiguator; use rustc_span::symbol::Symbol; @@ -129,8 +129,8 @@ fn associated_item(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItem { let parent_def_id = tcx.hir().local_def_id(parent_id); let parent_item = tcx.hir().expect_item(parent_id); match parent_item.kind { - hir::ItemKind::Impl(ref impl_) => { - if let Some(impl_item_ref) = impl_.items.iter().find(|i| i.id.hir_id == id) { + hir::ItemKind::Impl { ref items, .. } => { + if let Some(impl_item_ref) = items.iter().find(|i| i.id.hir_id == id) { let assoc_item = associated_item_from_impl_item_ref(tcx, parent_def_id, impl_item_ref); debug_assert_eq!(assoc_item.def_id, def_id); @@ -160,8 +160,8 @@ fn associated_item(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItem { fn impl_defaultness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::Defaultness { let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); let item = tcx.hir().expect_item(hir_id); - if let hir::ItemKind::Impl(impl_) = &item.kind { - impl_.defaultness + if let hir::ItemKind::Impl { defaultness, .. } = item.kind { + defaultness } else { bug!("`impl_defaultness` called on {:?}", item); } @@ -201,9 +201,8 @@ fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: DefId) -> &[DefId] { .map(|trait_item_ref| trait_item_ref.id) .map(|id| tcx.hir().local_def_id(id.hir_id).to_def_id()), ), - hir::ItemKind::Impl(ref impl_) => tcx.arena.alloc_from_iter( - impl_ - .items + hir::ItemKind::Impl { ref items, .. } => tcx.arena.alloc_from_iter( + items .iter() .map(|impl_item_ref| impl_item_ref.id) .map(|id| tcx.hir().local_def_id(id.hir_id).to_def_id()), @@ -222,10 +221,6 @@ fn def_span(tcx: TyCtxt<'_>, def_id: DefId) -> Span { tcx.hir().span_if_local(def_id).unwrap() } -fn def_ident_span(tcx: TyCtxt<'_>, def_id: DefId) -> Option { - tcx.hir().get_if_local(def_id).and_then(|node| node.ident()).map(|ident| ident.span) -} - /// If the given `DefId` describes an item belonging to a trait, /// returns the `DefId` of the trait that the trait item belongs to; /// otherwise, returns `None`. @@ -328,8 +323,8 @@ fn well_formed_types_in_env<'tcx>( }, Node::Item(item) => match item.kind { - ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => NodeKind::TraitImpl, - ItemKind::Impl(hir::Impl { of_trait: None, .. }) => NodeKind::InherentImpl, + ItemKind::Impl { of_trait: Some(_), .. } => NodeKind::TraitImpl, + ItemKind::Impl { of_trait: None, .. } => NodeKind::InherentImpl, ItemKind::Fn(..) => NodeKind::Fn, _ => NodeKind::Other, }, @@ -378,8 +373,8 @@ fn well_formed_types_in_env<'tcx>( let input_clauses = inputs.into_iter().filter_map(|arg| { match arg.unpack() { GenericArgKind::Type(ty) => { - let binder = Binder::dummy(PredicateKind::TypeWellFormedFromEnv(ty)); - Some(tcx.mk_predicate(binder)) + let binder = Binder::dummy(PredicateAtom::TypeWellFormedFromEnv(ty)); + Some(tcx.mk_predicate(PredicateKind::ForAll(binder))) } // FIXME(eddyb) no WF conditions from lifetimes? @@ -496,7 +491,6 @@ pub fn provide(providers: &mut ty::query::Providers) { associated_items, adt_sized_constraint, def_span, - def_ident_span, param_env, param_env_reveal_all_normalized, trait_of_item, diff --git a/compiler/rustc_typeck/src/astconv/errors.rs b/compiler/rustc_typeck/src/astconv/errors.rs index 545c30169b91e..b04acd9660d45 100644 --- a/compiler/rustc_typeck/src/astconv/errors.rs +++ b/compiler/rustc_typeck/src/astconv/errors.rs @@ -96,7 +96,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let trait_def = self.tcx().trait_def(trait_def_id); if !self.tcx().features().unboxed_closures - && trait_segment.args().parenthesized != trait_def.paren_sugar + && trait_segment.generic_args().parenthesized != trait_def.paren_sugar { let sess = &self.tcx().sess.parse_sess; // For now, require that parenthetical notation be used only with `Fn()` etc. @@ -126,7 +126,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { }) .unwrap_or_else(|| "()".to_string()), trait_segment - .args() + .generic_args() .bindings .iter() .find_map(|b| match (b.ident.name == sym::Output, &b.kind) { diff --git a/compiler/rustc_typeck/src/astconv/generics.rs b/compiler/rustc_typeck/src/astconv/generics.rs index 0797c95636260..1100401ed12dd 100644 --- a/compiler/rustc_typeck/src/astconv/generics.rs +++ b/compiler/rustc_typeck/src/astconv/generics.rs @@ -1,12 +1,10 @@ -use super::IsMethodCall; use crate::astconv::{ AstConv, CreateSubstsForGenericArgsCtxt, ExplicitLateBound, GenericArgCountMismatch, GenericArgCountResult, GenericArgPosition, }; use crate::errors::AssocTypeBindingNotAllowed; -use crate::structured_errors::{StructuredDiagnostic, WrongNumberOfGenericArgs}; use rustc_ast::ast::ParamKindOrd; -use rustc_errors::{struct_span_err, Applicability, ErrorReported}; +use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId, ErrorReported}; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::GenericArg; @@ -15,6 +13,7 @@ use rustc_middle::ty::{ }; use rustc_session::lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS; use rustc_span::{symbol::kw, MultiSpan, Span}; + use smallvec::SmallVec; impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { @@ -354,25 +353,20 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { pub fn check_generic_arg_count_for_call( tcx: TyCtxt<'_>, span: Span, - def_id: DefId, - generics: &ty::Generics, + def: &ty::Generics, seg: &hir::PathSegment<'_>, - is_method_call: IsMethodCall, + is_method_call: bool, ) -> GenericArgCountResult { let empty_args = hir::GenericArgs::none(); - let suppress_mismatch = Self::check_impl_trait(tcx, seg, &generics); - - let gen_args = seg.args.unwrap_or(&empty_args); - let gen_pos = if is_method_call == IsMethodCall::Yes { - GenericArgPosition::MethodCall - } else { - GenericArgPosition::Value - }; - let has_self = generics.parent.is_none() && generics.has_self; - let infer_args = seg.infer_args || suppress_mismatch; - + let suppress_mismatch = Self::check_impl_trait(tcx, seg, &def); Self::check_generic_arg_count( - tcx, span, def_id, seg, generics, gen_args, gen_pos, has_self, infer_args, + tcx, + span, + def, + if let Some(ref args) = seg.args { args } else { &empty_args }, + if is_method_call { GenericArgPosition::MethodCall } else { GenericArgPosition::Value }, + def.parent.is_none() && def.has_self, // `has_self` + seg.infer_args || suppress_mismatch, // `infer_args` ) } @@ -381,109 +375,156 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { pub(crate) fn check_generic_arg_count( tcx: TyCtxt<'_>, span: Span, - def_id: DefId, - seg: &hir::PathSegment<'_>, - gen_params: &ty::Generics, - gen_args: &hir::GenericArgs<'_>, - gen_pos: GenericArgPosition, + def: &ty::Generics, + args: &hir::GenericArgs<'_>, + position: GenericArgPosition, has_self: bool, infer_args: bool, ) -> GenericArgCountResult { - let default_counts = gen_params.own_defaults(); - let param_counts = gen_params.own_counts(); + // At this stage we are guaranteed that the generic arguments are in the correct order, e.g. + // that lifetimes will proceed types. So it suffices to check the number of each generic + // arguments in order to validate them with respect to the generic parameters. + let param_counts = def.own_counts(); let named_type_param_count = param_counts.types - has_self as usize; - let arg_counts = gen_args.own_counts(); - let infer_lifetimes = gen_pos != GenericArgPosition::Type && arg_counts.lifetimes == 0; + let arg_counts = args.own_counts(); + let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0; - if gen_pos != GenericArgPosition::Type && !gen_args.bindings.is_empty() { - Self::prohibit_assoc_ty_binding(tcx, gen_args.bindings[0].span); + let mut defaults: ty::GenericParamCount = Default::default(); + for param in &def.params { + match param.kind { + GenericParamDefKind::Lifetime => {} + GenericParamDefKind::Type { has_default, .. } => { + defaults.types += has_default as usize + } + GenericParamDefKind::Const => { + // FIXME(const_generics_defaults) + } + }; + } + + if position != GenericArgPosition::Type && !args.bindings.is_empty() { + AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span); } let explicit_late_bound = - Self::prohibit_explicit_late_bound_lifetimes(tcx, gen_params, gen_args, gen_pos); + Self::prohibit_explicit_late_bound_lifetimes(tcx, def, args, position); + + let check_kind_count = |kind, + required, + permitted, + provided, + offset, + unexpected_spans: &mut Vec, + silent| { + debug!( + "check_kind_count: kind: {} required: {} permitted: {} provided: {} offset: {}", + kind, required, permitted, provided, offset + ); + // We enforce the following: `required` <= `provided` <= `permitted`. + // For kinds without defaults (e.g.., lifetimes), `required == permitted`. + // For other kinds (i.e., types), `permitted` may be greater than `required`. + if required <= provided && provided <= permitted { + return true; + } - let mut invalid_args = vec![]; + if silent { + return false; + } - let mut check_generics = - |kind, expected_min, expected_max, provided, params_offset, args_offset, silent| { - if (expected_min..=expected_max).contains(&provided) { - return true; + // Unfortunately lifetime and type parameter mismatches are typically styled + // differently in diagnostics, which means we have a few cases to consider here. + let (bound, quantifier) = if required != permitted { + if provided < required { + (required, "at least ") + } else { + // provided > permitted + (permitted, "at most ") } + } else { + (required, "") + }; - if silent { - return false; - } + let (spans, labels) = if provided > permitted { + // In the case when the user has provided too many arguments, + // we want to point to the unexpected arguments. + let (spans, labels): (Vec, Vec) = args.args + [offset + permitted..offset + provided] + .iter() + .map(|arg| (arg.span(), format!("unexpected {} argument", arg.short_descr()))) + .unzip(); + unexpected_spans.extend(spans.clone()); + (spans, labels) + } else { + ( + vec![span], + vec![format!( + "expected {}{} {} argument{}", + quantifier, + bound, + kind, + pluralize!(bound), + )], + ) + }; - if provided > expected_max { - invalid_args.extend( - gen_args.args[args_offset + expected_max..args_offset + provided] - .iter() - .map(|arg| arg.span()), - ); - }; - - WrongNumberOfGenericArgs { - tcx, - kind, - expected_min, - expected_max, - provided, - params_offset, - args_offset, - path_segment: seg, - gen_params, - gen_args, - def_id, - span, - } - .diagnostic() - .emit(); + let mut err = tcx.sess.struct_span_err_with_code( + spans.clone(), + &format!( + "wrong number of {} arguments: expected {}{}, found {}", + kind, quantifier, bound, provided, + ), + DiagnosticId::Error("E0107".into()), + ); + for (span, label) in spans.into_iter().zip(labels) { + err.span_label(span, label.as_str()); + } + err.emit(); + false + }; - false - }; + let mut unexpected_spans = vec![]; - let lifetimes_correct = check_generics( + let lifetime_count_correct = check_kind_count( "lifetime", if infer_lifetimes { 0 } else { param_counts.lifetimes }, param_counts.lifetimes, arg_counts.lifetimes, - has_self as usize, 0, + &mut unexpected_spans, explicit_late_bound == ExplicitLateBound::Yes, ); - let args_correct = { - let kind = if param_counts.consts + arg_counts.consts == 0 { - "type" - } else if named_type_param_count + arg_counts.types == 0 { - "const" - } else { - "generic" - }; + let kind_str = if param_counts.consts + arg_counts.consts == 0 { + "type" + } else if named_type_param_count + arg_counts.types == 0 { + "const" + } else { + "generic" + }; - let expected_min = if infer_args { + let arg_count_correct = check_kind_count( + kind_str, + if infer_args { 0 } else { - param_counts.consts + named_type_param_count - default_counts.types - }; - - check_generics( - kind, - expected_min, - param_counts.consts + named_type_param_count, - arg_counts.consts + arg_counts.types, - param_counts.lifetimes + has_self as usize, - arg_counts.lifetimes, - false, - ) - }; + param_counts.consts + named_type_param_count - defaults.types + }, + param_counts.consts + named_type_param_count, + arg_counts.consts + arg_counts.types, + arg_counts.lifetimes, + &mut unexpected_spans, + false, + ); GenericArgCountResult { explicit_late_bound, - correct: if lifetimes_correct && args_correct { + correct: if lifetime_count_correct && arg_count_correct { Ok(()) } else { - Err(GenericArgCountMismatch { reported: Some(ErrorReported), invalid_args }) + Err(GenericArgCountMismatch { + reported: Some(ErrorReported), + invalid_args: unexpected_spans, + }) }, } } @@ -508,7 +549,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { if explicit && impl_trait { let spans = seg - .args() + .generic_args() .args .iter() .filter_map(|arg| match arg { @@ -553,15 +594,12 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0; if infer_lifetimes { - return ExplicitLateBound::No; - } - - if let Some(span_late) = def.has_late_bound_regions { + ExplicitLateBound::No + } else if let Some(span_late) = def.has_late_bound_regions { let msg = "cannot specify lifetime arguments explicitly \ if late bound lifetime parameters are present"; let note = "the late bound lifetime parameter is introduced here"; let span = args.args[0].span(); - if position == GenericArgPosition::Value && arg_counts.lifetimes != param_counts.lifetimes { @@ -578,7 +616,6 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { |lint| lint.build(msg).emit(), ); } - ExplicitLateBound::Yes } else { ExplicitLateBound::No diff --git a/compiler/rustc_typeck/src/astconv/mod.rs b/compiler/rustc_typeck/src/astconv/mod.rs index 059f9b41068c7..405a88fd639f3 100644 --- a/compiler/rustc_typeck/src/astconv/mod.rs +++ b/compiler/rustc_typeck/src/astconv/mod.rs @@ -138,12 +138,6 @@ pub enum ExplicitLateBound { No, } -#[derive(Copy, Clone, PartialEq)] -pub enum IsMethodCall { - Yes, - No, -} - /// Denotes the "position" of a generic argument, indicating if it is a generic type, /// generic function or generic method call. #[derive(Copy, Clone, PartialEq)] @@ -258,8 +252,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { span, def_id, &[], - item_segment, - item_segment.args(), + item_segment.generic_args(), item_segment.infer_args, None, ); @@ -307,7 +300,6 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { span: Span, def_id: DefId, parent_substs: &[subst::GenericArg<'tcx>], - seg: &hir::PathSegment<'_>, generic_args: &'a hir::GenericArgs<'_>, infer_args: bool, self_ty: Option>, @@ -322,10 +314,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ); let tcx = self.tcx(); - let generics = tcx.generics_of(def_id); + let generic_params = tcx.generics_of(def_id); - if generics.has_self { - if generics.parent.is_some() { + if generic_params.has_self { + if generic_params.parent.is_some() { // The parent is a trait so it should have at least one subst // for the `Self` type. assert!(!parent_substs.is_empty()) @@ -340,9 +332,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let arg_count = Self::check_generic_arg_count( tcx, span, - def_id, - seg, - &generics, + &generic_params, &generic_args, GenericArgPosition::Type, self_ty.is_some(), @@ -353,7 +343,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // Traits always have `Self` as a generic parameter, which means they will not return early // here and so associated type bindings will be handled regardless of whether there are any // non-`Self` generic parameters. - if generics.params.len() == 0 { + if generic_params.params.len() == 0 { return (tcx.intern_substs(&[]), vec![], arg_count); } @@ -563,7 +553,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { debug!( "create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}", - generics, self_ty, substs + generic_params, self_ty, substs ); (substs, assoc_bindings, arg_count) @@ -586,8 +576,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { span, item_def_id, parent_substs, - item_segment, - item_segment.args(), + item_segment.generic_args(), item_segment.infer_args, None, ) @@ -712,15 +701,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ) { let trait_def_id = self.tcx().require_lang_item(lang_item, Some(span)); - let (substs, assoc_bindings, _) = self.create_substs_for_ast_path( - span, - trait_def_id, - &[], - &hir::PathSegment::invalid(), - args, - false, - Some(self_ty), - ); + let (substs, assoc_bindings, _) = + self.create_substs_for_ast_path(span, trait_def_id, &[], args, false, Some(self_ty)); let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs)); bounds.trait_bounds.push((poly_trait_ref, span, Constness::NotConst)); @@ -768,8 +750,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { span, trait_def_id, &[], - trait_segment, - trait_segment.args(), + trait_segment.generic_args(), trait_segment.infer_args, Some(self_ty), ) @@ -1095,7 +1076,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { dummy_self, &mut bounds, ) { - potential_assoc_types.extend(cur_potential_assoc_types); + potential_assoc_types.extend(cur_potential_assoc_types.into_iter()); } } @@ -1177,9 +1158,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { obligation.predicate ); - let bound_predicate = obligation.predicate.kind(); + let bound_predicate = obligation.predicate.bound_atom(); match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(pred, _) => { + ty::PredicateAtom::Trait(pred, _) => { let pred = bound_predicate.rebind(pred); associated_types.entry(span).or_default().extend( tcx.associated_items(pred.def_id()) @@ -1188,7 +1169,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { .map(|item| item.def_id), ); } - ty::PredicateKind::Projection(pred) => { + ty::PredicateAtom::Projection(pred) => { let pred = bound_predicate.rebind(pred); // A `Self` within the original bound will be substituted with a // `trait_object_dummy_self`, so check for that. @@ -1770,7 +1751,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let mut has_err = false; for segment in segments { let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false); - for arg in segment.args().args { + for arg in segment.generic_args().args { let (span, kind) = match arg { hir::GenericArg::Lifetime(lt) => { if err_for_lt { @@ -1812,7 +1793,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } // Only emit the first error to avoid overloading the user with error messages. - if let [binding, ..] = segment.args().bindings { + if let [binding, ..] = segment.generic_args().bindings { has_err = true; Self::prohibit_assoc_ty_binding(self.tcx(), binding.span); } @@ -2030,11 +2011,11 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { "generic `Self` types are currently not permitted in anonymous constants", ); if let Some(hir::Node::Item(&hir::Item { - kind: hir::ItemKind::Impl(ref impl_), + kind: hir::ItemKind::Impl { self_ty, .. }, .. })) = tcx.hir().get_if_local(def_id) { - err.span_note(impl_.self_ty.span, "not a concrete type"); + err.span_note(self_ty.span, "not a concrete type"); } err.emit(); tcx.ty_error() @@ -2149,7 +2130,6 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { span, def_id, &[], - &hir::PathSegment::invalid(), &GenericArgs::none(), true, None, diff --git a/compiler/rustc_typeck/src/check/_match.rs b/compiler/rustc_typeck/src/check/_match.rs index 30e0e3eecd4a3..6467e04407939 100644 --- a/compiler/rustc_typeck/src/check/_match.rs +++ b/compiler/rustc_typeck/src/check/_match.rs @@ -1,9 +1,9 @@ -use crate::check::coercion::{AsCoercionSite, CoerceMany}; +use crate::check::coercion::CoerceMany; use crate::check::{Diverges, Expectation, FnCtxt, Needs}; use rustc_hir::{self as hir, ExprKind}; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_infer::traits::Obligation; -use rustc_middle::ty::{self, ToPredicate, Ty, TyS}; +use rustc_middle::ty::{self, ToPredicate, Ty}; use rustc_span::Span; use rustc_trait_selection::opaque_types::InferCtxtExt as _; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; @@ -12,41 +12,6 @@ use rustc_trait_selection::traits::{ StatementAsExpression, }; -macro_rules! create_maybe_get_coercion_reason { - ($fn_name:ident, $node:expr) => { - pub(crate) fn $fn_name(&self, hir_id: hir::HirId, sp: Span) -> Option<(Span, String)> { - let node = $node(self.tcx.hir(), hir_id); - if let hir::Node::Block(block) = node { - // check that the body's parent is an fn - let parent = self.tcx.hir().get( - self.tcx.hir().get_parent_node(self.tcx.hir().get_parent_node(block.hir_id)), - ); - if let ( - Some(expr), - hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. }), - ) = (&block.expr, parent) - { - // check that the `if` expr without `else` is the fn body's expr - if expr.span == sp { - return self.get_fn_decl(hir_id).and_then(|(fn_decl, _)| { - let span = fn_decl.output.span(); - let snippet = self.tcx.sess.source_map().span_to_snippet(span).ok()?; - Some(( - span, - format!("expected `{}` because of this return type", snippet), - )) - }); - } - } - } - if let hir::Node::Local(hir::Local { ty: Some(_), pat, .. }) = node { - return Some((pat.span, "expected because of this assignment".to_string())); - } - None - } - }; -} - impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub fn check_match( &self, @@ -60,6 +25,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { use hir::MatchSource::*; let (source_if, if_no_else, force_scrutinee_bool) = match match_src { + IfDesugar { contains_else_clause } => (true, !contains_else_clause, true), IfLetDesugar { contains_else_clause, .. } => (true, !contains_else_clause, false), WhileDesugar => (false, false, true), _ => (false, false, false), @@ -149,12 +115,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let arm_ty = if source_if && if_no_else && i != 0 - && self.if_fallback_coercion( - expr.span, - &arms[0].body, - &mut coercion, - |hir_id, span| self.maybe_get_coercion_reason(hir_id, span), - ) { + && self.if_fallback_coercion(expr.span, &arms[0].body, &mut coercion) + { tcx.ty_error() } else { // Only call this if this is not an `if` expr with an expected type and no `else` @@ -163,8 +125,58 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; all_arms_diverge &= self.diverges.get(); - let opt_suggest_box_span = - self.opt_suggest_box_span(arm.body.span, arm_ty, orig_expected); + // When we have a `match` as a tail expression in a `fn` with a returned `impl Trait` + // we check if the different arms would work with boxed trait objects instead and + // provide a structured suggestion in that case. + let opt_suggest_box_span = match ( + orig_expected, + self.ret_coercion_impl_trait.map(|ty| (self.body_id.owner, ty)), + ) { + (Expectation::ExpectHasType(expected), Some((id, ty))) + if self.in_tail_expr && self.can_coerce(arm_ty, expected) => + { + let impl_trait_ret_ty = self.infcx.instantiate_opaque_types( + id, + self.body_id, + self.param_env, + ty, + arm.body.span, + ); + let mut suggest_box = !impl_trait_ret_ty.obligations.is_empty(); + for o in impl_trait_ret_ty.obligations { + match o.predicate.skip_binders_unchecked() { + ty::PredicateAtom::Trait(t, constness) => { + let pred = ty::PredicateAtom::Trait( + ty::TraitPredicate { + trait_ref: ty::TraitRef { + def_id: t.def_id(), + substs: self.infcx.tcx.mk_substs_trait(arm_ty, &[]), + }, + }, + constness, + ); + let obl = Obligation::new( + o.cause.clone(), + self.param_env, + pred.to_predicate(self.infcx.tcx), + ); + suggest_box &= self.infcx.predicate_must_hold_modulo_regions(&obl); + if !suggest_box { + // We've encountered some obligation that didn't hold, so the + // return expression can't just be boxed. We don't need to + // evaluate the rest of the obligations. + break; + } + } + _ => {} + } + } + // If all the obligations hold (or there are no obligations) the tail expression + // we can suggest to return a boxed trait object instead of an opaque type. + if suggest_box { self.ret_type_span } else { None } + } + _ => None, + }; if source_if { let then_expr = &arms[0].body; @@ -267,7 +279,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) { use hir::MatchSource::*; let msg = match source { - IfLetDesugar { .. } => "block in `if` expression", + IfDesugar { .. } | IfLetDesugar { .. } => "block in `if` expression", WhileDesugar { .. } | WhileLetDesugar { .. } => "block in `while` expression", _ => "arm", }; @@ -279,20 +291,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Handle the fallback arm of a desugared if(-let) like a missing else. /// /// Returns `true` if there was an error forcing the coercion to the `()` type. - pub(crate) fn if_fallback_coercion( + fn if_fallback_coercion( &self, span: Span, then_expr: &'tcx hir::Expr<'tcx>, - coercion: &mut CoerceMany<'tcx, '_, T>, - ret_reason: F, - ) -> bool - where - F: Fn(hir::HirId, Span) -> Option<(Span, String)>, - T: AsCoercionSite, - { + coercion: &mut CoerceMany<'tcx, '_, rustc_hir::Arm<'tcx>>, + ) -> bool { // If this `if` expr is the parent's function return expr, // the cause of the type coercion is the return type, point at it. (#25228) - let ret_reason = ret_reason(then_expr.hir_id, span); + let ret_reason = self.maybe_get_coercion_reason(then_expr.hir_id, span); let cause = self.cause(span, ObligationCauseCode::IfExpressionWithNoElse); let mut error = false; coercion.coerce_forced_unit( @@ -315,25 +322,38 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { error } - create_maybe_get_coercion_reason!( - maybe_get_coercion_reason, - |hir: rustc_middle::hir::map::Map<'a>, id| { - let arm_id = hir.get_parent_node(id); - let match_id = hir.get_parent_node(arm_id); - let containing_id = hir.get_parent_node(match_id); - hir.get(containing_id) - } - ); + fn maybe_get_coercion_reason(&self, hir_id: hir::HirId, span: Span) -> Option<(Span, String)> { + use hir::Node::{Block, Item, Local}; + + let hir = self.tcx.hir(); + let arm_id = hir.get_parent_node(hir_id); + let match_id = hir.get_parent_node(arm_id); + let containing_id = hir.get_parent_node(match_id); - create_maybe_get_coercion_reason!( - maybe_get_coercion_reason_if, - |hir: rustc_middle::hir::map::Map<'a>, id| { - let rslt = hir.get_parent_node(hir.get_parent_node(id)); - hir.get(rslt) + let node = hir.get(containing_id); + if let Block(block) = node { + // check that the body's parent is an fn + let parent = hir.get(hir.get_parent_node(hir.get_parent_node(block.hir_id))); + if let (Some(expr), Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })) = + (&block.expr, parent) + { + // check that the `if` expr without `else` is the fn body's expr + if expr.span == span { + return self.get_fn_decl(hir_id).and_then(|(fn_decl, _)| { + let span = fn_decl.output.span(); + let snippet = self.tcx.sess.source_map().span_to_snippet(span).ok()?; + Some((span, format!("expected `{}` because of this return type", snippet))) + }); + } + } } - ); + if let Local(hir::Local { ty: Some(_), pat, .. }) = node { + return Some((pat.span, "expected because of this assignment".to_string())); + } + None + } - pub(crate) fn if_cause( + fn if_cause( &self, span: Span, then_expr: &'tcx hir::Expr<'tcx>, @@ -526,58 +546,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { (block.span, None) } } - - // When we have a `match` as a tail expression in a `fn` with a returned `impl Trait` - // we check if the different arms would work with boxed trait objects instead and - // provide a structured suggestion in that case. - pub(crate) fn opt_suggest_box_span( - &self, - span: Span, - outer_ty: &'tcx TyS<'tcx>, - orig_expected: Expectation<'tcx>, - ) -> Option { - match (orig_expected, self.ret_coercion_impl_trait.map(|ty| (self.body_id.owner, ty))) { - (Expectation::ExpectHasType(expected), Some((id, ty))) - if self.in_tail_expr && self.can_coerce(outer_ty, expected) => - { - let impl_trait_ret_ty = - self.infcx.instantiate_opaque_types(id, self.body_id, self.param_env, ty, span); - let mut suggest_box = !impl_trait_ret_ty.obligations.is_empty(); - for o in impl_trait_ret_ty.obligations { - match o.predicate.kind().skip_binder() { - ty::PredicateKind::Trait(t, constness) => { - let pred = ty::PredicateKind::Trait( - ty::TraitPredicate { - trait_ref: ty::TraitRef { - def_id: t.def_id(), - substs: self.infcx.tcx.mk_substs_trait(outer_ty, &[]), - }, - }, - constness, - ); - let obl = Obligation::new( - o.cause.clone(), - self.param_env, - pred.to_predicate(self.infcx.tcx), - ); - suggest_box &= self.infcx.predicate_must_hold_modulo_regions(&obl); - if !suggest_box { - // We've encountered some obligation that didn't hold, so the - // return expression can't just be boxed. We don't need to - // evaluate the rest of the obligations. - break; - } - } - _ => {} - } - } - // If all the obligations hold (or there are no obligations) the tail expression - // we can suggest to return a boxed trait object instead of an opaque type. - if suggest_box { self.ret_type_span } else { None } - } - _ => None, - } - } } fn arms_contain_ref_bindings(arms: &'tcx [hir::Arm<'tcx>]) -> Option { diff --git a/compiler/rustc_typeck/src/check/callee.rs b/compiler/rustc_typeck/src/check/callee.rs index 4836418b3c210..116b079e7425a 100644 --- a/compiler/rustc_typeck/src/check/callee.rs +++ b/compiler/rustc_typeck/src/check/callee.rs @@ -25,24 +25,24 @@ pub fn check_legal_trait_for_method_call( tcx: TyCtxt<'_>, span: Span, receiver: Option, - expr_span: Span, trait_id: DefId, ) { if tcx.lang_items().drop_trait() == Some(trait_id) { let mut err = struct_span_err!(tcx.sess, span, E0040, "explicit use of destructor method"); err.span_label(span, "explicit destructor calls not allowed"); - let (sp, suggestion) = receiver + let snippet = receiver .and_then(|s| tcx.sess.source_map().span_to_snippet(s).ok()) - .filter(|snippet| !snippet.is_empty()) - .map(|snippet| (expr_span, format!("drop({})", snippet))) - .unwrap_or_else(|| (span, "drop".to_string())); + .unwrap_or_default(); + + let suggestion = + if snippet.is_empty() { "drop".to_string() } else { format!("drop({})", snippet) }; err.span_suggestion( - sp, - "consider using `drop` function", - suggestion, - Applicability::MaybeIncorrect, + span, + &format!("consider using `drop` function: `{}`", suggestion), + String::new(), + Applicability::Unspecified, ); err.emit(); diff --git a/compiler/rustc_typeck/src/check/cast.rs b/compiler/rustc_typeck/src/check/cast.rs index 39dac0a909f6f..36240a9b41e7d 100644 --- a/compiler/rustc_typeck/src/check/cast.rs +++ b/compiler/rustc_typeck/src/check/cast.rs @@ -418,14 +418,13 @@ impl<'a, 'tcx> CastCheck<'tcx> { err.emit(); } CastError::SizedUnsizedCast => { - use crate::structured_errors::{SizedUnsizedCast, StructuredDiagnostic}; - - SizedUnsizedCast { - sess: &fcx.tcx.sess, - span: self.span, - expr_ty: self.expr_ty, - cast_ty: fcx.ty_to_string(self.cast_ty), - } + use crate::structured_errors::{SizedUnsizedCastError, StructuredDiagnostic}; + SizedUnsizedCastError::new( + &fcx.tcx.sess, + self.span, + self.expr_ty, + fcx.ty_to_string(self.cast_ty), + ) .diagnostic() .emit(); } diff --git a/compiler/rustc_typeck/src/check/check.rs b/compiler/rustc_typeck/src/check/check.rs index 8e339eb26b26c..9bb4c9b3719e3 100644 --- a/compiler/rustc_typeck/src/check/check.rs +++ b/compiler/rustc_typeck/src/check/check.rs @@ -692,17 +692,11 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { check_enum(tcx, it.span, &enum_definition.variants, it.hir_id); } hir::ItemKind::Fn(..) => {} // entirely within check_item_body - hir::ItemKind::Impl(ref impl_) => { + hir::ItemKind::Impl { ref items, .. } => { debug!("ItemKind::Impl {} with id {}", it.ident, it.hir_id); let impl_def_id = tcx.hir().local_def_id(it.hir_id); if let Some(impl_trait_ref) = tcx.impl_trait_ref(impl_def_id) { - check_impl_items_against_trait( - tcx, - it.span, - impl_def_id, - impl_trait_ref, - &impl_.items, - ); + check_impl_items_against_trait(tcx, it.span, impl_def_id, impl_trait_ref, items); let trait_def_id = impl_trait_ref.def_id; check_on_unimplemented(tcx, trait_def_id, it); } @@ -1259,8 +1253,8 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, adt: &'tcx ty let layout = tcx.layout_of(param_env.and(ty)); // We are currently checking the type this field came from, so it must be local let span = tcx.hir().span_if_local(field.did).unwrap(); - let zst = layout.map_or(false, |layout| layout.is_zst()); - let align1 = layout.map_or(false, |layout| layout.align.abi.bytes() == 1); + let zst = layout.map(|layout| layout.is_zst()).unwrap_or(false); + let align1 = layout.map(|layout| layout.align.abi.bytes() == 1).unwrap_or(false); (span, zst, align1) }); diff --git a/compiler/rustc_typeck/src/check/closure.rs b/compiler/rustc_typeck/src/check/closure.rs index f34aaec10a9b9..7470c1a76a943 100644 --- a/compiler/rustc_typeck/src/check/closure.rs +++ b/compiler/rustc_typeck/src/check/closure.rs @@ -192,9 +192,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { obligation.predicate ); - let bound_predicate = obligation.predicate.kind(); - if let ty::PredicateKind::Projection(proj_predicate) = - obligation.predicate.kind().skip_binder() + let bound_predicate = obligation.predicate.bound_atom(); + if let ty::PredicateAtom::Projection(proj_predicate) = + obligation.predicate.skip_binders() { // Given a Projection predicate, we can potentially infer // the complete signature. @@ -622,8 +622,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // where R is the return type we are expecting. This type `T` // will be our output. let output_ty = self.obligations_for_self_ty(ret_vid).find_map(|(_, obligation)| { - let bound_predicate = obligation.predicate.kind(); - if let ty::PredicateKind::Projection(proj_predicate) = bound_predicate.skip_binder() { + let bound_predicate = obligation.predicate.bound_atom(); + if let ty::PredicateAtom::Projection(proj_predicate) = bound_predicate.skip_binder() { self.deduce_future_output_from_projection( obligation.cause.span, bound_predicate.rebind(proj_predicate), diff --git a/compiler/rustc_typeck/src/check/coercion.rs b/compiler/rustc_typeck/src/check/coercion.rs index 34ad8ec08984e..67ec739d8614d 100644 --- a/compiler/rustc_typeck/src/check/coercion.rs +++ b/compiler/rustc_typeck/src/check/coercion.rs @@ -583,9 +583,9 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { while !queue.is_empty() { let obligation = queue.remove(0); debug!("coerce_unsized resolve step: {:?}", obligation); - let bound_predicate = obligation.predicate.kind(); + let bound_predicate = obligation.predicate.bound_atom(); let trait_pred = match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(trait_pred, _) + ty::PredicateAtom::Trait(trait_pred, _) if traits.contains(&trait_pred.def_id()) => { if unsize_did == trait_pred.def_id() { @@ -1443,14 +1443,14 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { &mut err, expr, expected, found, cause.span, blk_id, ); let parent = fcx.tcx.hir().get(parent_id); - if let (Some(cond_expr), true, false) = ( - fcx.tcx.hir().get_if_cause(expr.hir_id), + if let (Some(match_expr), true, false) = ( + fcx.tcx.hir().get_match_if_cause(expr.hir_id), expected.is_unit(), pointing_at_return_type, ) { - if cond_expr.span.desugaring_kind().is_none() { - err.span_label(cond_expr.span, "expected this to be `()`"); - fcx.suggest_semicolon_at_end(cond_expr.span, &mut err); + if match_expr.span.desugaring_kind().is_none() { + err.span_label(match_expr.span, "expected this to be `()`"); + fcx.suggest_semicolon_at_end(match_expr.span, &mut err); } } fcx.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main)) diff --git a/compiler/rustc_typeck/src/check/compare_method.rs b/compiler/rustc_typeck/src/check/compare_method.rs index d37d6bc4f2df6..320ded5334e21 100644 --- a/compiler/rustc_typeck/src/check/compare_method.rs +++ b/compiler/rustc_typeck/src/check/compare_method.rs @@ -364,12 +364,13 @@ fn check_region_bounds_on_impl_item<'tcx>( if trait_params != impl_params { let item_kind = assoc_item_kind_str(impl_m); let def_span = tcx.sess.source_map().guess_head_span(span); - let span = tcx.hir().get_generics(impl_m.def_id).map_or(def_span, |g| g.span); - let generics_span = tcx.hir().span_if_local(trait_m.def_id).map(|sp| { + let span = tcx.hir().get_generics(impl_m.def_id).map(|g| g.span).unwrap_or(def_span); + let generics_span = if let Some(sp) = tcx.hir().span_if_local(trait_m.def_id) { let def_sp = tcx.sess.source_map().guess_head_span(sp); - tcx.hir().get_generics(trait_m.def_id).map_or(def_sp, |g| g.span) - }); - + Some(tcx.hir().get_generics(trait_m.def_id).map(|g| g.span).unwrap_or(def_sp)) + } else { + None + }; tcx.sess.emit_err(LifetimesOrBoundsMismatchOnTrait { span, item_kind, diff --git a/compiler/rustc_typeck/src/check/demand.rs b/compiler/rustc_typeck/src/check/demand.rs index c22f001744639..2728e03171a75 100644 --- a/compiler/rustc_typeck/src/check/demand.rs +++ b/compiler/rustc_typeck/src/check/demand.rs @@ -32,7 +32,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if self.suggest_calling_boxed_future_when_appropriate(err, expr, expected, expr_ty) { return; } - self.suggest_no_capture_closure(err, expected, expr_ty); self.suggest_boxing_when_appropriate(err, expr, expected, expr_ty); self.suggest_missing_parentheses(err, expr); self.note_need_for_fn_pointer(err, expected, expr_ty); diff --git a/compiler/rustc_typeck/src/check/dropck.rs b/compiler/rustc_typeck/src/check/dropck.rs index 4c3c4fd447058..be19919c0ea1f 100644 --- a/compiler/rustc_typeck/src/check/dropck.rs +++ b/compiler/rustc_typeck/src/check/dropck.rs @@ -226,13 +226,13 @@ fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>( // could be extended easily also to the other `Predicate`. let predicate_matches_closure = |p: Predicate<'tcx>| { let mut relator: SimpleEqRelation<'tcx> = SimpleEqRelation::new(tcx, self_param_env); - let predicate = predicate.kind(); - let p = p.kind(); + let predicate = predicate.bound_atom(); + let p = p.bound_atom(); match (predicate.skip_binder(), p.skip_binder()) { - (ty::PredicateKind::Trait(a, _), ty::PredicateKind::Trait(b, _)) => { + (ty::PredicateAtom::Trait(a, _), ty::PredicateAtom::Trait(b, _)) => { relator.relate(predicate.rebind(a), p.rebind(b)).is_ok() } - (ty::PredicateKind::Projection(a), ty::PredicateKind::Projection(b)) => { + (ty::PredicateAtom::Projection(a), ty::PredicateAtom::Projection(b)) => { relator.relate(predicate.rebind(a), p.rebind(b)).is_ok() } _ => predicate == p, diff --git a/compiler/rustc_typeck/src/check/expr.rs b/compiler/rustc_typeck/src/check/expr.rs index 8aa6c6d924a53..d76a80d5a3990 100644 --- a/compiler/rustc_typeck/src/check/expr.rs +++ b/compiler/rustc_typeck/src/check/expr.rs @@ -10,7 +10,6 @@ use crate::check::method::{probe, MethodError, SelfSource}; use crate::check::report_unexpected_variant_res; use crate::check::BreakableCtxt; use crate::check::Diverges; -use crate::check::DynamicCoerceMany; use crate::check::Expectation::{self, ExpectCastableToType, ExpectHasType, NoExpectation}; use crate::check::FnCtxt; use crate::check::Needs; @@ -189,7 +188,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Warn for non-block expressions with diverging children. match expr.kind { - ExprKind::Block(..) | ExprKind::If(..) | ExprKind::Loop(..) | ExprKind::Match(..) => {} + ExprKind::Block(..) | ExprKind::Loop(..) | ExprKind::Match(..) => {} // If `expr` is a result of desugaring the try block and is an ok-wrapped // diverging expression (e.g. it arose from desugaring of `try { return }`), // we skip issuing a warning because it is autogenerated code. @@ -286,13 +285,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.check_expr_eq_type(&e, ty); ty } - ExprKind::If(ref cond, ref then_expr, ref opt_else_expr) => self.check_then_else( - &cond, - then_expr, - opt_else_expr.as_ref().map(|e| &**e), - expr.span, - expected, - ), ExprKind::DropTemps(ref e) => self.check_expr_with_expectation(e, expected), ExprKind::Array(ref args) => self.check_expr_array(args, expected, expr), ExprKind::ConstBlock(ref anon_const) => self.to_const(anon_const).ty, @@ -747,67 +739,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { err.emit(); } - // A generic function for checking the 'then' and 'else' clauses in an 'if' - // or 'if-else' expression. - fn check_then_else( - &self, - cond_expr: &'tcx hir::Expr<'tcx>, - then_expr: &'tcx hir::Expr<'tcx>, - opt_else_expr: Option<&'tcx hir::Expr<'tcx>>, - sp: Span, - orig_expected: Expectation<'tcx>, - ) -> Ty<'tcx> { - let cond_ty = self.check_expr_has_type_or_error(cond_expr, self.tcx.types.bool, |_| {}); - - self.warn_if_unreachable(cond_expr.hir_id, then_expr.span, "block in `if` expression"); - - let cond_diverges = self.diverges.get(); - self.diverges.set(Diverges::Maybe); - - let expected = orig_expected.adjust_for_branches(self); - let then_ty = self.check_expr_with_expectation(then_expr, expected); - let then_diverges = self.diverges.get(); - self.diverges.set(Diverges::Maybe); - - // We've already taken the expected type's preferences - // into account when typing the `then` branch. To figure - // out the initial shot at a LUB, we thus only consider - // `expected` if it represents a *hard* constraint - // (`only_has_type`); otherwise, we just go with a - // fresh type variable. - let coerce_to_ty = expected.coercion_target_type(self, sp); - let mut coerce: DynamicCoerceMany<'_> = CoerceMany::new(coerce_to_ty); - - coerce.coerce(self, &self.misc(sp), then_expr, then_ty); - - if let Some(else_expr) = opt_else_expr { - let else_ty = self.check_expr_with_expectation(else_expr, expected); - let else_diverges = self.diverges.get(); - - let opt_suggest_box_span = - self.opt_suggest_box_span(else_expr.span, else_ty, orig_expected); - let if_cause = - self.if_cause(sp, then_expr, else_expr, then_ty, else_ty, opt_suggest_box_span); - - coerce.coerce(self, &if_cause, else_expr, else_ty); - - // We won't diverge unless both branches do (or the condition does). - self.diverges.set(cond_diverges | then_diverges & else_diverges); - } else { - self.if_fallback_coercion(sp, then_expr, &mut coerce, |hir_id, span| { - self.maybe_get_coercion_reason_if(hir_id, span) - }); - - // If the condition is false we can't diverge. - self.diverges.set(cond_diverges); - } - - let result_ty = coerce.complete(self); - if cond_ty.references_error() { self.tcx.ty_error() } else { result_ty } - } - /// Type check assignment expression `expr` of form `lhs = rhs`. - /// The expected type is `()` and is passed to the function for the purposes of diagnostics. + /// The expected type is `()` and is passsed to the function for the purposes of diagnostics. fn check_expr_assign( &self, expr: &'tcx hir::Expr<'tcx>, @@ -832,7 +765,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; if !lhs.is_syntactic_place_expr() { // Do not suggest `if let x = y` as `==` is way more likely to be the intention. - let mut span_err = || { + if let hir::Node::Expr(hir::Expr { + kind: + ExprKind::Match( + _, + _, + hir::MatchSource::IfDesugar { .. } | hir::MatchSource::WhileDesugar, + ), + .. + }) = self.tcx.hir().get( + self.tcx.hir().get_parent_node(self.tcx.hir().get_parent_node(expr.hir_id)), + ) { // Likely `if let` intended. err.span_suggestion_verbose( expr.span.shrink_to_lo(), @@ -840,18 +783,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { "let ".to_string(), applicability, ); - }; - if let hir::Node::Expr(hir::Expr { - kind: ExprKind::Match(_, _, hir::MatchSource::WhileDesugar), - .. - }) = self.tcx.hir().get( - self.tcx.hir().get_parent_node(self.tcx.hir().get_parent_node(expr.hir_id)), - ) { - span_err(); - } else if let hir::Node::Expr(hir::Expr { kind: ExprKind::If { .. }, .. }) = - self.tcx.hir().get(self.tcx.hir().get_parent_node(expr.hir_id)) - { - span_err(); } } if eq { diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs b/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs index ed48a0bc801cf..7126b62405968 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs @@ -1,6 +1,6 @@ use crate::astconv::{ AstConv, CreateSubstsForGenericArgsCtxt, ExplicitLateBound, GenericArgCountMismatch, - GenericArgCountResult, IsMethodCall, PathSeg, + GenericArgCountResult, PathSeg, }; use crate::check::callee::{self, DeferredCallResolution}; use crate::check::method::{self, MethodCallee, SelfSource}; @@ -542,7 +542,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.register_predicate(traits::Obligation::new( cause, self.param_env, - ty::PredicateKind::WellFormed(arg).to_predicate(self.tcx), + ty::PredicateAtom::WellFormed(arg).to_predicate(self.tcx), )); } @@ -764,21 +764,21 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .pending_obligations() .into_iter() .filter_map(move |obligation| { - let bound_predicate = obligation.predicate.kind(); + let bound_predicate = obligation.predicate.bound_atom(); match bound_predicate.skip_binder() { - ty::PredicateKind::Projection(data) => { + ty::PredicateAtom::Projection(data) => { Some((bound_predicate.rebind(data).to_poly_trait_ref(self.tcx), obligation)) } - ty::PredicateKind::Trait(data, _) => { + ty::PredicateAtom::Trait(data, _) => { Some((bound_predicate.rebind(data).to_poly_trait_ref(), obligation)) } - ty::PredicateKind::Subtype(..) => None, - ty::PredicateKind::RegionOutlives(..) => None, - ty::PredicateKind::TypeOutlives(..) => None, - ty::PredicateKind::WellFormed(..) => None, - ty::PredicateKind::ObjectSafe(..) => None, - ty::PredicateKind::ConstEvaluatable(..) => None, - ty::PredicateKind::ConstEquate(..) => None, + ty::PredicateAtom::Subtype(..) => None, + ty::PredicateAtom::RegionOutlives(..) => None, + ty::PredicateAtom::TypeOutlives(..) => None, + ty::PredicateAtom::WellFormed(..) => None, + ty::PredicateAtom::ObjectSafe(..) => None, + ty::PredicateAtom::ConstEvaluatable(..) => None, + ty::PredicateAtom::ConstEquate(..) => None, // N.B., this predicate is created by breaking down a // `ClosureType: FnFoo()` predicate, where // `ClosureType` represents some `Closure`. It can't @@ -787,8 +787,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // this closure yet; this is exactly why the other // code is looking for a self type of a unresolved // inference variable. - ty::PredicateKind::ClosureKind(..) => None, - ty::PredicateKind::TypeWellFormedFromEnv(..) => None, + ty::PredicateAtom::ClosureKind(..) => None, + ty::PredicateAtom::TypeWellFormedFromEnv(..) => None, } }) .filter(move |(tr, _)| self.self_type_matches_expected_vid(*tr, ty_var_root)) @@ -904,7 +904,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { { // Return directly on cache hit. This is useful to avoid doubly reporting // errors with default match binding modes. See #44614. - let def = cached_result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)); + let def = + cached_result.map(|(kind, def_id)| Res::Def(kind, def_id)).unwrap_or(Res::Err); return (def, Some(ty), slice::from_ref(&**item_segment)); } let item_name = item_segment.ident; @@ -931,7 +932,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Write back the new resolution. self.write_resolution(hir_id, result); ( - result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), + result.map(|(kind, def_id)| Res::Def(kind, def_id)).unwrap_or(Res::Err), Some(ty), slice::from_ref(&**item_segment), ) @@ -1163,7 +1164,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { debug!("instantiate_value_path: def_id={:?} container={:?}", def_id, container); match container { ty::TraitContainer(trait_did) => { - callee::check_legal_trait_for_method_call(tcx, span, None, span, trait_did) + callee::check_legal_trait_for_method_call(tcx, span, None, trait_did) } ty::ImplContainer(impl_def_id) => { if segments.len() == 1 { @@ -1218,25 +1219,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // a problem. let mut infer_args_for_err = FxHashSet::default(); - for &PathSeg(def_id, index) in &path_segs { let seg = &segments[index]; let generics = tcx.generics_of(def_id); - // Argument-position `impl Trait` is treated as a normal generic // parameter internally, but we don't allow users to specify the // parameter's value explicitly, so we have to do some error- // checking here. if let GenericArgCountResult { - correct: Err(GenericArgCountMismatch { reported: Some(_), .. }), + correct: Err(GenericArgCountMismatch { reported: Some(ErrorReported), .. }), .. } = AstConv::check_generic_arg_count_for_call( - tcx, - span, - def_id, - &generics, - seg, - IsMethodCall::No, + tcx, span, &generics, &seg, false, // `is_method_call` ) { infer_args_for_err.insert(index); self.set_tainted_by_errors(); // See issue #53251. @@ -1479,7 +1473,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ty } else { if !self.is_tainted_by_errors() { - self.emit_inference_failure_err((**self).body_id, sp, ty.into(), vec![], E0282) + self.emit_inference_failure_err((**self).body_id, sp, ty.into(), E0282) .note("type must be known at this point") .emit(); } diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs index 6df9e3ab7dbe8..3e60924d6fcf8 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs @@ -22,7 +22,6 @@ use rustc_span::symbol::{sym, Ident}; use rustc_span::{self, MultiSpan, Span}; use rustc_trait_selection::traits::{self, ObligationCauseCode, StatementAsExpression}; -use crate::structured_errors::StructuredDiagnostic; use std::mem::replace; use std::slice; @@ -174,19 +173,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } if let Some(def_id) = def_id { - if let Some(def_span) = tcx.def_ident_span(def_id) { - let mut spans: MultiSpan = def_span.into(); - - let params = tcx - .hir() - .get_if_local(def_id) - .and_then(|node| node.body_id()) - .into_iter() - .map(|id| tcx.hir().body(id).params) - .flatten(); - - for param in params { - spans.push_span_label(param.span, String::new()); + if let Some(node) = tcx.hir().get_if_local(def_id) { + let mut spans: MultiSpan = node + .ident() + .map(|ident| ident.span) + .unwrap_or_else(|| tcx.hir().span(node.hir_id().unwrap())) + .into(); + + if let Some(id) = node.body_id() { + let body = tcx.hir().body(id); + for param in body.params { + spans.push_span_label(param.span, String::new()); + } } let def_kind = tcx.def_kind(def_id); @@ -360,10 +358,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // We also need to make sure we at least write the ty of the other // arguments which we skipped above. if c_variadic { - fn variadic_error<'tcx>(sess: &Session, span: Span, ty: Ty<'tcx>, cast_ty: &str) { - use crate::structured_errors::MissingCastForVariadicArg; - - MissingCastForVariadicArg { sess, span, ty, cast_ty }.diagnostic().emit() + fn variadic_error<'tcx>(s: &Session, span: Span, t: Ty<'tcx>, cast_ty: &str) { + use crate::structured_errors::{StructuredDiagnostic, VariadicError}; + VariadicError::new(s, span, t, cast_ty).diagnostic().emit(); } for arg in args.iter().skip(expected_arg_count) { @@ -806,39 +803,33 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// // ^^^^ point at this instead of the whole `if` expression /// ``` fn get_expr_coercion_span(&self, expr: &hir::Expr<'_>) -> rustc_span::Span { - let check_in_progress = |elem: &hir::Expr<'_>| { - self.in_progress_typeck_results - .and_then(|typeck_results| typeck_results.borrow().node_type_opt(elem.hir_id)) - .and_then(|ty| { - if ty.is_never() { - None - } else { - Some(match elem.kind { - // Point at the tail expression when possible. - hir::ExprKind::Block(block, _) => { - block.expr.map_or(block.span, |e| e.span) + if let hir::ExprKind::Match(_, arms, _) = &expr.kind { + let arm_spans: Vec = arms + .iter() + .filter_map(|arm| { + self.in_progress_typeck_results + .and_then(|typeck_results| { + typeck_results.borrow().node_type_opt(arm.body.hir_id) + }) + .and_then(|arm_ty| { + if arm_ty.is_never() { + None + } else { + Some(match &arm.body.kind { + // Point at the tail expression when possible. + hir::ExprKind::Block(block, _) => { + block.expr.as_ref().map(|e| e.span).unwrap_or(block.span) + } + _ => arm.body.span, + }) } - _ => elem.span, }) - } }) - }; - - if let hir::ExprKind::If(_, _, Some(el)) = expr.kind { - if let Some(rslt) = check_in_progress(el) { - return rslt; - } - } - - if let hir::ExprKind::Match(_, arms, _) = expr.kind { - let mut iter = arms.iter().filter_map(|arm| check_in_progress(arm.body)); - if let Some(span) = iter.next() { - if iter.next().is_none() { - return span; - } + .collect(); + if arm_spans.len() == 1 { + return arm_spans[0]; } } - expr.span } @@ -888,7 +879,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Write back the new resolution. self.write_resolution(hir_id, result); - (result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), ty) + (result.map(|(kind, def_id)| Res::Def(kind, def_id)).unwrap_or(Res::Err), ty) } QPath::LangItem(lang_item, span) => { self.resolve_lang_item_path(lang_item, span, hir_id) @@ -923,8 +914,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { continue; } - if let ty::PredicateKind::Trait(predicate, _) = - error.obligation.predicate.kind().skip_binder() + if let ty::PredicateAtom::Trait(predicate, _) = + error.obligation.predicate.skip_binders() { // Collect the argument position for all arguments that could have caused this // `FulfillmentError`. @@ -974,8 +965,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let hir::ExprKind::Path(qpath) = &path.kind { if let hir::QPath::Resolved(_, path) = &qpath { for error in errors { - if let ty::PredicateKind::Trait(predicate, _) = - error.obligation.predicate.kind().skip_binder() + if let ty::PredicateAtom::Trait(predicate, _) = + error.obligation.predicate.skip_binders() { // If any of the type arguments in this path segment caused the // `FullfillmentError`, point at its span (#61860). diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/mod.rs b/compiler/rustc_typeck/src/check/fn_ctxt/mod.rs index 6d09043bd5033..f635e0b6f931c 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/mod.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/mod.rs @@ -194,8 +194,8 @@ impl<'a, 'tcx> AstConv<'tcx> for FnCtxt<'a, 'tcx> { parent: None, predicates: tcx.arena.alloc_from_iter( self.param_env.caller_bounds().iter().filter_map(|predicate| { - match predicate.kind().skip_binder() { - ty::PredicateKind::Trait(data, _) if data.self_ty().is_param(index) => { + match predicate.skip_binders() { + ty::PredicateAtom::Trait(data, _) if data.self_ty().is_param(index) => { // HACK(eddyb) should get the original `Span`. let span = tcx.def_span(def_id); Some((predicate, span)) diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/suggestions.rs b/compiler/rustc_typeck/src/check/fn_ctxt/suggestions.rs index a0465ca6aef07..17dbf989d6683 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/suggestions.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/suggestions.rs @@ -2,7 +2,7 @@ use super::FnCtxt; use crate::astconv::AstConv; use rustc_ast::util::parser::ExprPrecedence; -use rustc_span::{self, MultiSpan, Span}; +use rustc_span::{self, Span}; use rustc_errors::{Applicability, DiagnosticBuilder}; use rustc_hir as hir; @@ -287,38 +287,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - /// When encountering a closure that captures variables, where a FnPtr is expected, - /// suggest a non-capturing closure - pub(in super::super) fn suggest_no_capture_closure( - &self, - err: &mut DiagnosticBuilder<'_>, - expected: Ty<'tcx>, - found: Ty<'tcx>, - ) { - if let (ty::FnPtr(_), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) { - if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) { - // Report upto four upvars being captured to reduce the amount error messages - // reported back to the user. - let spans_and_labels = upvars - .iter() - .take(4) - .map(|(var_hir_id, upvar)| { - let var_name = self.tcx.hir().name(*var_hir_id).to_string(); - let msg = format!("`{}` captured here", var_name); - (upvar.span, msg) - }) - .collect::>(); - - let mut multi_span: MultiSpan = - spans_and_labels.iter().map(|(sp, _)| *sp).collect::>().into(); - for (sp, label) in spans_and_labels { - multi_span.push_span_label(sp, label); - } - err.span_note(multi_span, "closures can only be coerced to `fn` types if they do not capture any variables"); - } - } - } - /// When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`. pub(in super::super) fn suggest_calling_boxed_future_when_appropriate( &self, @@ -390,7 +358,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ExprKind::Call(..) | ExprKind::MethodCall(..) | ExprKind::Loop(..) - | ExprKind::If(..) | ExprKind::Match(..) | ExprKind::Block(..) => { err.span_suggestion( diff --git a/compiler/rustc_typeck/src/check/intrinsic.rs b/compiler/rustc_typeck/src/check/intrinsic.rs index e99db7a247c46..e4e6cf73c7e23 100644 --- a/compiler/rustc_typeck/src/check/intrinsic.rs +++ b/compiler/rustc_typeck/src/check/intrinsic.rs @@ -157,6 +157,7 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { } sym::forget => (1, vec![param(0)], tcx.mk_unit()), sym::transmute => (2, vec![param(0)], param(1)), + sym::move_val_init => (1, vec![tcx.mk_mut_ptr(param(0)), param(0)], tcx.mk_unit()), sym::prefetch_read_data | sym::prefetch_write_data | sym::prefetch_read_instruction diff --git a/compiler/rustc_typeck/src/check/method/confirm.rs b/compiler/rustc_typeck/src/check/method/confirm.rs index e5f19281b0773..8ef723d590285 100644 --- a/compiler/rustc_typeck/src/check/method/confirm.rs +++ b/compiler/rustc_typeck/src/check/method/confirm.rs @@ -1,6 +1,6 @@ use super::{probe, MethodCallee}; -use crate::astconv::{AstConv, CreateSubstsForGenericArgsCtxt, IsMethodCall}; +use crate::astconv::{AstConv, CreateSubstsForGenericArgsCtxt}; use crate::check::{callee, FnCtxt}; use crate::hir::def_id::DefId; use crate::hir::GenericArg; @@ -31,7 +31,6 @@ impl<'a, 'tcx> Deref for ConfirmContext<'a, 'tcx> { } } -#[derive(Debug)] pub struct ConfirmResult<'tcx> { pub callee: MethodCallee<'tcx>, pub illegal_sized_bound: Option, @@ -299,14 +298,8 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { // If they were not explicitly supplied, just construct fresh // variables. let generics = self.tcx.generics_of(pick.item.def_id); - let arg_count_correct = AstConv::check_generic_arg_count_for_call( - self.tcx, - self.span, - pick.item.def_id, - &generics, - seg, - IsMethodCall::Yes, + self.tcx, self.span, &generics, &seg, true, // `is_method_call` ); // Create subst for early-bound lifetime parameters, combining @@ -479,8 +472,8 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { traits::elaborate_predicates(self.tcx, predicates.predicates.iter().copied()) // We don't care about regions here. - .filter_map(|obligation| match obligation.predicate.kind().skip_binder() { - ty::PredicateKind::Trait(trait_pred, _) if trait_pred.def_id() == sized_def_id => { + .filter_map(|obligation| match obligation.predicate.skip_binders() { + ty::PredicateAtom::Trait(trait_pred, _) if trait_pred.def_id() == sized_def_id => { let span = predicates .predicates .iter() @@ -508,7 +501,6 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { self.tcx, self.span, Some(self.self_expr.span), - self.call_expr.span, trait_def_id, ), ty::ImplContainer(..) => {} diff --git a/compiler/rustc_typeck/src/check/method/mod.rs b/compiler/rustc_typeck/src/check/method/mod.rs index 9a3d1e42b732a..8e13b3746992a 100644 --- a/compiler/rustc_typeck/src/check/method/mod.rs +++ b/compiler/rustc_typeck/src/check/method/mod.rs @@ -102,7 +102,6 @@ pub enum CandidateSource { impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Determines whether the type `self_ty` supports a method name `method_name` or not. - #[instrument(level = "debug", skip(self))] pub fn method_exists( &self, method_name: Ident, @@ -130,7 +129,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } /// Adds a suggestion to call the given method to the provided diagnostic. - #[instrument(level = "debug", skip(self, err, call_expr))] crate fn suggest_method_call( &self, err: &mut DiagnosticBuilder<'a>, @@ -179,7 +177,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// * `span`: the span for the method call /// * `call_expr`: the complete method call: (`foo.bar::(...)`) /// * `self_expr`: the self expression (`foo`) - #[instrument(level = "debug", skip(self, call_expr, self_expr))] pub fn lookup_method( &self, self_ty: Ty<'tcx>, @@ -207,7 +204,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let result = self.confirm_method(span, self_expr, call_expr, self_ty, pick.clone(), segment); - debug!("result = {:?}", result); if let Some(span) = result.illegal_sized_bound { let mut needs_mut = false; @@ -260,7 +256,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Ok(result.callee) } - #[instrument(level = "debug", skip(self, call_expr))] pub fn lookup_probe( &self, span: Span, @@ -291,7 +286,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // FIXME(#18741): it seems likely that we can consolidate some of this // code with the other method-lookup code. In particular, the second half // of this method is basically the same as confirmation. - #[instrument(level = "debug", skip(self, span, opt_input_types))] pub fn lookup_method_in_trait( &self, span: Span, @@ -405,7 +399,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { obligations.push(traits::Obligation::new( cause, self.param_env, - ty::PredicateKind::WellFormed(method_ty.into()).to_predicate(tcx), + ty::PredicateAtom::WellFormed(method_ty.into()).to_predicate(tcx), )); let callee = MethodCallee { def_id, substs: trait_ref.substs, sig: fn_sig }; @@ -415,7 +409,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Some(InferOk { obligations, value: callee }) } - #[instrument(level = "debug", skip(self))] pub fn resolve_ufcs( &self, span: Span, diff --git a/compiler/rustc_typeck/src/check/method/probe.rs b/compiler/rustc_typeck/src/check/method/probe.rs index 8335239f804b0..d4631c465a3a7 100644 --- a/compiler/rustc_typeck/src/check/method/probe.rs +++ b/compiler/rustc_typeck/src/check/method/probe.rs @@ -48,7 +48,7 @@ pub use self::PickKind::*; /// Boolean flag used to indicate if this search is for a suggestion /// or not. If true, we can allow ambiguity and so forth. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy)] pub struct IsSuggestion(pub bool); struct ProbeContext<'a, 'tcx> { @@ -219,7 +219,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// would result in an error (basically, the same criteria we /// would use to decide if a method is a plausible fit for /// ambiguity purposes). - #[instrument(level = "debug", skip(self, scope_expr_id))] pub fn probe_for_return_type( &self, span: Span, @@ -265,7 +264,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .collect() } - #[instrument(level = "debug", skip(self, scope_expr_id))] pub fn probe_for_name( &self, span: Span, @@ -772,7 +770,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { // will be reported by `object_safety.rs` if the method refers to the // `Self` type anywhere other than the receiver. Here, we use a // substitution that replaces `Self` with the object type itself. Hence, - // a `&self` method will wind up with an argument type like `&dyn Trait`. + // a `&self` method will wind up with an argument type like `&Trait`. let trait_ref = principal.with_self_ty(self.tcx, self_ty); self.elaborate_bounds(iter::once(trait_ref), |this, new_trait_ref, item| { let new_trait_ref = this.erase_late_bound_regions(new_trait_ref); @@ -797,9 +795,9 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { debug!("assemble_inherent_candidates_from_param(param_ty={:?})", param_ty); let bounds = self.param_env.caller_bounds().iter().filter_map(|predicate| { - let bound_predicate = predicate.kind(); + let bound_predicate = predicate.bound_atom(); match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(trait_predicate, _) => { + ty::PredicateAtom::Trait(trait_predicate, _) => { match *trait_predicate.trait_ref.self_ty().kind() { ty::Param(p) if p == param_ty => { Some(bound_predicate.rebind(trait_predicate.trait_ref)) @@ -807,16 +805,16 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { _ => None, } } - ty::PredicateKind::Subtype(..) - | ty::PredicateKind::Projection(..) - | ty::PredicateKind::RegionOutlives(..) - | ty::PredicateKind::WellFormed(..) - | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::TypeOutlives(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) - | ty::PredicateKind::TypeWellFormedFromEnv(..) => None, + ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::Projection(..) + | ty::PredicateAtom::RegionOutlives(..) + | ty::PredicateAtom::WellFormed(..) + | ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::TypeOutlives(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) + | ty::PredicateAtom::TypeWellFormedFromEnv(..) => None, } }); diff --git a/compiler/rustc_typeck/src/check/method/suggest.rs b/compiler/rustc_typeck/src/check/method/suggest.rs index c553fda49c308..5cfd78ebeacad 100644 --- a/compiler/rustc_typeck/src/check/method/suggest.rs +++ b/compiler/rustc_typeck/src/check/method/suggest.rs @@ -582,8 +582,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut collect_type_param_suggestions = |self_ty: Ty<'tcx>, parent_pred: &ty::Predicate<'tcx>, obligation: &str| { // We don't care about regions here, so it's fine to skip the binder here. - if let (ty::Param(_), ty::PredicateKind::Trait(p, _)) = - (self_ty.kind(), parent_pred.kind().skip_binder()) + if let (ty::Param(_), ty::PredicateAtom::Trait(p, _)) = + (self_ty.kind(), parent_pred.skip_binders()) { if let ty::Adt(def, _) = p.trait_ref.self_ty().kind() { let node = def.did.as_local().map(|def_id| { @@ -637,9 +637,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } }; let mut format_pred = |pred: ty::Predicate<'tcx>| { - let bound_predicate = pred.kind(); + let bound_predicate = pred.bound_atom(); match bound_predicate.skip_binder() { - ty::PredicateKind::Projection(pred) => { + ty::PredicateAtom::Projection(pred) => { let pred = bound_predicate.rebind(pred); // `::Item = String`. let trait_ref = @@ -658,7 +658,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { bound_span_label(trait_ref.self_ty(), &obligation, &quiet); Some((obligation, trait_ref.self_ty())) } - ty::PredicateKind::Trait(poly_trait_ref, _) => { + ty::PredicateAtom::Trait(poly_trait_ref, _) => { let p = poly_trait_ref.trait_ref; let self_ty = p.self_ty(); let path = p.print_only_trait_path(); @@ -992,11 +992,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // implementing a trait would be legal but is rejected // here). unsatisfied_predicates.iter().all(|(p, _)| { - match p.kind().skip_binder() { + match p.skip_binders() { // Hide traits if they are present in predicates as they can be fixed without // having to implement them. - ty::PredicateKind::Trait(t, _) => t.def_id() == info.def_id, - ty::PredicateKind::Projection(p) => { + ty::PredicateAtom::Trait(t, _) => t.def_id() == info.def_id, + ty::PredicateAtom::Projection(p) => { p.projection_ty.item_def_id == info.def_id } _ => false, @@ -1193,7 +1193,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .any(|imp_did| { let imp = self.tcx.impl_trait_ref(imp_did).unwrap(); let imp_simp = simplify_type(self.tcx, imp.self_ty(), true); - imp_simp.map_or(false, |s| s == simp_rcvr_ty) + imp_simp.map(|s| s == simp_rcvr_ty).unwrap_or(false) }) { explicitly_negative.push(candidate); @@ -1270,7 +1270,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { match ty.kind() { ty::Adt(def, _) => def.did.is_local(), ty::Foreign(did) => did.is_local(), - ty::Dynamic(ref tr, ..) => tr.principal().map_or(false, |d| d.def_id().is_local()), + + ty::Dynamic(ref tr, ..) => { + tr.principal().map(|d| d.def_id().is_local()).unwrap_or(false) + } + ty::Param(_) => true, // Everything else (primitive types, etc.) is effectively diff --git a/compiler/rustc_typeck/src/check/mod.rs b/compiler/rustc_typeck/src/check/mod.rs index 52276ed4beeaa..8177b363a5a5b 100644 --- a/compiler/rustc_typeck/src/check/mod.rs +++ b/compiler/rustc_typeck/src/check/mod.rs @@ -864,9 +864,9 @@ fn bounds_from_generic_predicates<'tcx>( let mut projections = vec![]; for (predicate, _) in predicates.predicates { debug!("predicate {:?}", predicate); - let bound_predicate = predicate.kind(); + let bound_predicate = predicate.bound_atom(); match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(trait_predicate, _) => { + ty::PredicateAtom::Trait(trait_predicate, _) => { let entry = types.entry(trait_predicate.self_ty()).or_default(); let def_id = trait_predicate.def_id(); if Some(def_id) != tcx.lang_items().sized_trait() { @@ -875,7 +875,7 @@ fn bounds_from_generic_predicates<'tcx>( entry.push(trait_predicate.def_id()); } } - ty::PredicateKind::Projection(projection_pred) => { + ty::PredicateAtom::Projection(projection_pred) => { projections.push(bound_predicate.rebind(projection_pred)); } _ => {} diff --git a/compiler/rustc_typeck/src/check/pat.rs b/compiler/rustc_typeck/src/check/pat.rs index 79234f076acd1..5fc573a57ad0b 100644 --- a/compiler/rustc_typeck/src/check/pat.rs +++ b/compiler/rustc_typeck/src/check/pat.rs @@ -15,7 +15,6 @@ use rustc_span::hygiene::DesugaringKind; use rustc_span::lev_distance::find_best_match_for_name; use rustc_span::source_map::{Span, Spanned}; use rustc_span::symbol::Ident; -use rustc_span::{BytePos, DUMMY_SP}; use rustc_trait_selection::traits::{ObligationCause, Pattern}; use std::cmp; @@ -1002,7 +1001,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // More generally, the expected type wants a tuple variant with one field of an // N-arity-tuple, e.g., `V_i((p_0, .., p_N))`. Meanwhile, the user supplied a pattern // with the subpatterns directly in the tuple variant pattern, e.g., `V_i(p_0, .., p_N)`. - let missing_parentheses = match (&expected.kind(), fields, had_err) { + let missing_parenthesis = match (&expected.kind(), fields, had_err) { // #67037: only do this if we could successfully type-check the expected type against // the tuple struct pattern. Otherwise the substs could get out of range on e.g., // `let P() = U;` where `P != U` with `struct P(T);`. @@ -1015,13 +1014,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } _ => false, }; - if missing_parentheses { + if missing_parenthesis { let (left, right) = match subpats { // This is the zero case; we aim to get the "hi" part of the `QPath`'s // span as the "lo" and then the "hi" part of the pattern's span as the "hi". // This looks like: // - // help: missing parentheses + // help: missing parenthesis // | // L | let A(()) = A(()); // | ^ ^ @@ -1030,63 +1029,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // last sub-pattern. In the case of `A(x)` the first and last may coincide. // This looks like: // - // help: missing parentheses + // help: missing parenthesis // | // L | let A((x, y)) = A((1, 2)); // | ^ ^ [first, ..] => (first.span.shrink_to_lo(), subpats.last().unwrap().span), }; err.multipart_suggestion( - "missing parentheses", + "missing parenthesis", vec![(left, "(".to_string()), (right.shrink_to_hi(), ")".to_string())], Applicability::MachineApplicable, ); - } else if fields.len() > subpats.len() { - let after_fields_span = if pat_span == DUMMY_SP { - pat_span - } else { - pat_span.with_hi(pat_span.hi() - BytePos(1)).shrink_to_hi() - }; - let all_fields_span = match subpats { - [] => after_fields_span, - [field] => field.span, - [first, .., last] => first.span.to(last.span), - }; - - // Check if all the fields in the pattern are wildcards. - let all_wildcards = subpats.iter().all(|pat| matches!(pat.kind, PatKind::Wild)); - - let mut wildcard_sugg = vec!["_"; fields.len() - subpats.len()].join(", "); - if !subpats.is_empty() { - wildcard_sugg = String::from(", ") + &wildcard_sugg; - } - - err.span_suggestion_verbose( - after_fields_span, - "use `_` to explicitly ignore each field", - wildcard_sugg, - Applicability::MaybeIncorrect, - ); - - // Only suggest `..` if more than one field is missing - // or the pattern consists of all wildcards. - if fields.len() - subpats.len() > 1 || all_wildcards { - if subpats.is_empty() || all_wildcards { - err.span_suggestion_verbose( - all_fields_span, - "use `..` to ignore all fields", - String::from(".."), - Applicability::MaybeIncorrect, - ); - } else { - err.span_suggestion_verbose( - after_fields_span, - "use `..` to ignore the rest of the fields", - String::from(", .."), - Applicability::MaybeIncorrect, - ); - } - } } err.emit(); @@ -1486,11 +1439,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Returns a diagnostic reporting a struct pattern which does not mention some fields. /// /// ```text - /// error[E0027]: pattern does not mention field `bar` + /// error[E0027]: pattern does not mention field `you_cant_use_this_field` /// --> src/main.rs:15:9 /// | /// LL | let foo::Foo {} = foo::Foo::new(); - /// | ^^^^^^^^^^^ missing field `bar` + /// | ^^^^^^^^^^^ missing field `you_cant_use_this_field` /// ``` fn error_unmentioned_fields( &self, @@ -1524,26 +1477,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } _ => return err, }, - [.., field] => { - // if last field has a trailing comma, use the comma - // as the span to avoid trailing comma in ultimate - // suggestion (Issue #78511) - let tail = field.span.shrink_to_hi().until(pat.span.shrink_to_hi()); - let tail_through_comma = self.tcx.sess.source_map().span_through_char(tail, ','); - let sp = if tail_through_comma == tail { - field.span.shrink_to_hi() - } else { - tail_through_comma - }; - ( - match pat.kind { - PatKind::Struct(_, [_, ..], _) => ", ", - _ => "", - }, - "", - sp, - ) - } + [.., field] => ( + match pat.kind { + PatKind::Struct(_, [_, ..], _) => ", ", + _ => "", + }, + "", + field.span.shrink_to_hi(), + ), }; err.span_suggestion( sp, diff --git a/compiler/rustc_typeck/src/check/upvar.rs b/compiler/rustc_typeck/src/check/upvar.rs index feda35daa617d..e8cbefd44ee6d 100644 --- a/compiler/rustc_typeck/src/check/upvar.rs +++ b/compiler/rustc_typeck/src/check/upvar.rs @@ -176,17 +176,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.demand_eqtype(span, inferred_kind.to_ty(self.tcx), closure_kind_ty); // If we have an origin, store it. - if let Some(origin) = delegate.current_origin.clone() { - let origin = if self.tcx.features().capture_disjoint_fields { - origin - } else { - // FIXME(project-rfc-2229#26): Once rust-lang#80092 is merged, we should restrict the - // precision of origin as well. Otherwise, this will cause issues when project-rfc-2229#26 - // is fixed as we might see Index projections in the origin, which we can't print because - // we don't store enough information. - (origin.0, Place { projections: vec![], ..origin.1 }) - }; - + if let Some(origin) = delegate.current_origin { self.typeck_results .borrow_mut() .closure_kind_origins_mut() @@ -573,7 +563,7 @@ struct InferBorrowKind<'a, 'tcx> { // If we modified `current_closure_kind`, this field contains a `Some()` with the // variable access that caused us to do so. - current_origin: Option<(Span, Place<'tcx>)>, + current_origin: Option<(Span, Symbol)>, /// For each Place that is captured by the closure, we track the minimal kind of /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access. @@ -638,7 +628,7 @@ impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> { upvar_id.closure_expr_id, ty::ClosureKind::FnOnce, usage_span, - place_with_id.place.clone(), + var_name(tcx, upvar_id.var_path.hir_id), ); let capture_info = ty::CaptureInfo { @@ -730,7 +720,7 @@ impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> { upvar_id.closure_expr_id, ty::ClosureKind::FnMut, tcx.hir().span(diag_expr_id), - place_with_id.place.clone(), + var_name(tcx, upvar_id.var_path.hir_id), ); } } @@ -775,11 +765,11 @@ impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> { closure_id: LocalDefId, new_kind: ty::ClosureKind, upvar_span: Span, - place: Place<'tcx>, + var_name: Symbol, ) { debug!( - "adjust_closure_kind(closure_id={:?}, new_kind={:?}, upvar_span={:?}, place={:?})", - closure_id, new_kind, upvar_span, place + "adjust_closure_kind(closure_id={:?}, new_kind={:?}, upvar_span={:?}, var_name={})", + closure_id, new_kind, upvar_span, var_name ); // Is this the closure whose kind is currently being inferred? @@ -807,7 +797,7 @@ impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> { | (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => { // new kind is stronger than the old kind self.current_closure_kind = new_kind; - self.current_origin = Some((upvar_span, place)); + self.current_origin = Some((upvar_span, var_name)); } } } diff --git a/compiler/rustc_typeck/src/check/wfcheck.rs b/compiler/rustc_typeck/src/check/wfcheck.rs index c90db4786e35f..d81d83f60bd13 100644 --- a/compiler/rustc_typeck/src/check/wfcheck.rs +++ b/compiler/rustc_typeck/src/check/wfcheck.rs @@ -103,28 +103,35 @@ pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) { // // won't be allowed unless there's an *explicit* implementation of `Send` // for `T` - hir::ItemKind::Impl(ref impl_) => { + hir::ItemKind::Impl { + defaultness, + defaultness_span, + polarity, + ref of_trait, + ref self_ty, + .. + } => { let is_auto = tcx .impl_trait_ref(tcx.hir().local_def_id(item.hir_id)) .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id)); - if let (hir::Defaultness::Default { .. }, true) = (impl_.defaultness, is_auto) { - let sp = impl_.of_trait.as_ref().map_or(item.span, |t| t.path.span); + if let (hir::Defaultness::Default { .. }, true) = (defaultness, is_auto) { + let sp = of_trait.as_ref().map(|t| t.path.span).unwrap_or(item.span); let mut err = tcx.sess.struct_span_err(sp, "impls of auto traits cannot be default"); - err.span_labels(impl_.defaultness_span, "default because of this"); + err.span_labels(defaultness_span, "default because of this"); err.span_label(sp, "auto trait"); err.emit(); } // We match on both `ty::ImplPolarity` and `ast::ImplPolarity` just to get the `!` span. - match (tcx.impl_polarity(def_id), impl_.polarity) { + match (tcx.impl_polarity(def_id), polarity) { (ty::ImplPolarity::Positive, _) => { - check_impl(tcx, item, impl_.self_ty, &impl_.of_trait); + check_impl(tcx, item, self_ty, of_trait); } (ty::ImplPolarity::Negative, ast::ImplPolarity::Negative(span)) => { // FIXME(#27579): what amount of WF checking do we need for neg impls? - if let hir::Defaultness::Default { .. } = impl_.defaultness { + if let hir::Defaultness::Default { .. } = defaultness { let mut spans = vec![span]; - spans.extend(impl_.defaultness_span); + spans.extend(defaultness_span); struct_span_err!( tcx.sess, spans, @@ -532,7 +539,7 @@ fn check_type_defn<'tcx, F>( fcx.register_predicate(traits::Obligation::new( cause, fcx.param_env, - ty::PredicateKind::ConstEvaluatable( + ty::PredicateAtom::ConstEvaluatable( ty::WithOptConstParam::unknown(discr_def_id.to_def_id()), discr_substs, ) diff --git a/compiler/rustc_typeck/src/check/writeback.rs b/compiler/rustc_typeck/src/check/writeback.rs index 9e6bf5ce52d8a..7c9cfe69fc94b 100644 --- a/compiler/rustc_typeck/src/check/writeback.rs +++ b/compiler/rustc_typeck/src/check/writeback.rs @@ -384,11 +384,9 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); let common_hir_owner = fcx_typeck_results.hir_owner; - for (id, origin) in fcx_typeck_results.closure_kind_origins().iter() { - let hir_id = hir::HirId { owner: common_hir_owner, local_id: *id }; - let place_span = origin.0; - let place = self.resolve(origin.1.clone(), &place_span); - self.typeck_results.closure_kind_origins_mut().insert(hir_id, (place_span, place)); + for (&id, &origin) in fcx_typeck_results.closure_kind_origins().iter() { + let hir_id = hir::HirId { owner: common_hir_owner, local_id: id }; + self.typeck_results.closure_kind_origins_mut().insert(hir_id, origin); } } @@ -694,7 +692,6 @@ impl<'cx, 'tcx> Resolver<'cx, 'tcx> { Some(self.body.id()), self.span.to_span(self.tcx), t.into(), - vec![], E0282, ) .emit(); @@ -708,7 +705,6 @@ impl<'cx, 'tcx> Resolver<'cx, 'tcx> { Some(self.body.id()), self.span.to_span(self.tcx), c.into(), - vec![], E0282, ) .emit(); diff --git a/compiler/rustc_typeck/src/coherence/builtin.rs b/compiler/rustc_typeck/src/coherence/builtin.rs index 6726b9b4a4b65..89270fb6c77a5 100644 --- a/compiler/rustc_typeck/src/coherence/builtin.rs +++ b/compiler/rustc_typeck/src/coherence/builtin.rs @@ -55,7 +55,7 @@ fn visit_implementation_of_drop(tcx: TyCtxt<'_>, impl_did: LocalDefId) { let impl_hir_id = tcx.hir().local_def_id_to_hir_id(impl_did); let sp = match tcx.hir().expect_item(impl_hir_id).kind { - ItemKind::Impl(ref impl_) => impl_.self_ty.span, + ItemKind::Impl { self_ty, .. } => self_ty.span, _ => bug!("expected Drop impl item"), }; @@ -80,7 +80,7 @@ fn visit_implementation_of_copy(tcx: TyCtxt<'_>, impl_did: LocalDefId) { Ok(()) => {} Err(CopyImplementationError::InfrigingFields(fields)) => { let item = tcx.hir().expect_item(impl_hir_id); - let span = if let ItemKind::Impl(hir::Impl { of_trait: Some(ref tr), .. }) = item.kind { + let span = if let ItemKind::Impl { of_trait: Some(ref tr), .. } = item.kind { tr.path.span } else { span @@ -100,7 +100,7 @@ fn visit_implementation_of_copy(tcx: TyCtxt<'_>, impl_did: LocalDefId) { Err(CopyImplementationError::NotAnAdt) => { let item = tcx.hir().expect_item(impl_hir_id); let span = - if let ItemKind::Impl(ref impl_) = item.kind { impl_.self_ty.span } else { span }; + if let ItemKind::Impl { self_ty, .. } = item.kind { self_ty.span } else { span }; tcx.sess.emit_err(CopyImplOnNonAdt { span }); } @@ -453,9 +453,7 @@ pub fn coerce_unsized_info(tcx: TyCtxt<'tcx>, impl_did: DefId) -> CoerceUnsizedI return err_info; } else if diff_fields.len() > 1 { let item = tcx.hir().expect_item(impl_hir_id); - let span = if let ItemKind::Impl(hir::Impl { of_trait: Some(ref t), .. }) = - item.kind - { + let span = if let ItemKind::Impl { of_trait: Some(ref t), .. } = item.kind { t.path.span } else { tcx.hir().span(impl_hir_id) diff --git a/compiler/rustc_typeck/src/coherence/inherent_impls.rs b/compiler/rustc_typeck/src/coherence/inherent_impls.rs index 6b6c66932c868..0c1578498b846 100644 --- a/compiler/rustc_typeck/src/coherence/inherent_impls.rs +++ b/compiler/rustc_typeck/src/coherence/inherent_impls.rs @@ -45,9 +45,7 @@ struct InherentCollect<'tcx> { impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { fn visit_item(&mut self, item: &hir::Item<'_>) { let (ty, assoc_items) = match item.kind { - hir::ItemKind::Impl(hir::Impl { of_trait: None, ref self_ty, items, .. }) => { - (self_ty, items) - } + hir::ItemKind::Impl { of_trait: None, ref self_ty, items, .. } => (self_ty, items), _ => return, }; diff --git a/compiler/rustc_typeck/src/coherence/orphan.rs b/compiler/rustc_typeck/src/coherence/orphan.rs index 9333aac6018fe..253dcf06e01de 100644 --- a/compiler/rustc_typeck/src/coherence/orphan.rs +++ b/compiler/rustc_typeck/src/coherence/orphan.rs @@ -26,10 +26,7 @@ impl ItemLikeVisitor<'v> for OrphanChecker<'tcx> { fn visit_item(&mut self, item: &hir::Item<'_>) { let def_id = self.tcx.hir().local_def_id(item.hir_id); // "Trait" impl - if let hir::ItemKind::Impl(hir::Impl { - generics, of_trait: Some(ref tr), self_ty, .. - }) = &item.kind - { + if let hir::ItemKind::Impl { generics, of_trait: Some(ref tr), self_ty, .. } = &item.kind { debug!( "coherence2::orphan check: trait impl {}", self.tcx.hir().node_to_string(item.hir_id) diff --git a/compiler/rustc_typeck/src/coherence/unsafety.rs b/compiler/rustc_typeck/src/coherence/unsafety.rs index 3a290b7756e13..2d9128e7dc0b7 100644 --- a/compiler/rustc_typeck/src/coherence/unsafety.rs +++ b/compiler/rustc_typeck/src/coherence/unsafety.rs @@ -86,13 +86,8 @@ impl UnsafetyChecker<'tcx> { impl ItemLikeVisitor<'v> for UnsafetyChecker<'tcx> { fn visit_item(&mut self, item: &'v hir::Item<'v>) { - if let hir::ItemKind::Impl(ref impl_) = item.kind { - self.check_unsafety_coherence( - item, - Some(&impl_.generics), - impl_.unsafety, - impl_.polarity, - ); + if let hir::ItemKind::Impl { unsafety, polarity, ref generics, .. } = item.kind { + self.check_unsafety_coherence(item, Some(generics), unsafety, polarity); } } diff --git a/compiler/rustc_typeck/src/collect.rs b/compiler/rustc_typeck/src/collect.rs index d589989511db1..ae97fa3f7e423 100644 --- a/compiler/rustc_typeck/src/collect.rs +++ b/compiler/rustc_typeck/src/collect.rs @@ -189,7 +189,7 @@ fn reject_placeholder_type_signatures_in_item(tcx: TyCtxt<'tcx>, item: &'tcx hir | hir::ItemKind::Enum(_, generics) | hir::ItemKind::TraitAlias(generics, _) | hir::ItemKind::Trait(_, _, generics, ..) - | hir::ItemKind::Impl(hir::Impl { generics, .. }) + | hir::ItemKind::Impl { generics, .. } | hir::ItemKind::Struct(_, generics) => (generics, true), hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }) | hir::ItemKind::TyAlias(_, generics) => (generics, false), @@ -531,7 +531,7 @@ fn type_param_predicates( Node::Item(item) => { match item.kind { ItemKind::Fn(.., ref generics, _) - | ItemKind::Impl(hir::Impl { ref generics, .. }) + | ItemKind::Impl { ref generics, .. } | ItemKind::TyAlias(_, ref generics) | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. }) | ItemKind::Enum(_, ref generics) @@ -562,8 +562,8 @@ fn type_param_predicates( let extra_predicates = extend.into_iter().chain( icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty, OnlySelfBounds(true)) .into_iter() - .filter(|(predicate, _)| match predicate.kind().skip_binder() { - ty::PredicateKind::Trait(data, _) => data.self_ty().is_param(index), + .filter(|(predicate, _)| match predicate.skip_binders() { + ty::PredicateAtom::Trait(data, _) => data.self_ty().is_param(index), _ => false, }), ); @@ -1027,7 +1027,7 @@ fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredi // which will, in turn, reach indirect supertraits. for &(pred, span) in superbounds { debug!("superbound: {:?}", pred); - if let ty::PredicateKind::Trait(bound, _) = pred.kind().skip_binder() { + if let ty::PredicateAtom::Trait(bound, _) = pred.skip_binders() { tcx.at(span).super_predicates_of(bound.def_id()); } } @@ -1310,8 +1310,7 @@ fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Generics { Node::Item(item) => { match item.kind { - ItemKind::Fn(.., ref generics, _) - | ItemKind::Impl(hir::Impl { ref generics, .. }) => generics, + ItemKind::Fn(.., ref generics, _) | ItemKind::Impl { ref generics, .. } => generics, ItemKind::TyAlias(_, ref generics) | ItemKind::Enum(_, ref generics) @@ -1498,11 +1497,13 @@ fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool { Ptr(mut_ty) | Rptr(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty), OpaqueDef(_, generic_args) => are_suggestable_generic_args(generic_args), Path(hir::QPath::TypeRelative(ty, segment)) => { - is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.args().args) + is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.generic_args().args) } Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => { ty_opt.map_or(false, is_suggestable_infer_ty) - || segments.iter().any(|segment| are_suggestable_generic_args(segment.args().args)) + || segments + .iter() + .any(|segment| are_suggestable_generic_args(segment.generic_args().args)) } _ => false, } @@ -1637,7 +1638,7 @@ fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option> { let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); match tcx.hir().expect_item(hir_id).kind { - hir::ItemKind::Impl(ref impl_) => impl_.of_trait.as_ref().map(|ast_trait_ref| { + hir::ItemKind::Impl { ref of_trait, .. } => of_trait.as_ref().map(|ast_trait_ref| { let selfty = tcx.type_of(def_id); AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty) }), @@ -1650,39 +1651,29 @@ fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity { let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl); let item = tcx.hir().expect_item(hir_id); match &item.kind { - hir::ItemKind::Impl(hir::Impl { - polarity: hir::ImplPolarity::Negative(span), - of_trait, - .. - }) => { + hir::ItemKind::Impl { polarity: hir::ImplPolarity::Negative(span), of_trait, .. } => { if is_rustc_reservation { - let span = span.to(of_trait.as_ref().map_or(*span, |t| t.path.span)); + let span = span.to(of_trait.as_ref().map(|t| t.path.span).unwrap_or(*span)); tcx.sess.span_err(span, "reservation impls can't be negative"); } ty::ImplPolarity::Negative } - hir::ItemKind::Impl(hir::Impl { - polarity: hir::ImplPolarity::Positive, - of_trait: None, - .. - }) => { + hir::ItemKind::Impl { polarity: hir::ImplPolarity::Positive, of_trait: None, .. } => { if is_rustc_reservation { tcx.sess.span_err(item.span, "reservation impls can't be inherent"); } ty::ImplPolarity::Positive } - hir::ItemKind::Impl(hir::Impl { - polarity: hir::ImplPolarity::Positive, - of_trait: Some(_), - .. - }) => { + hir::ItemKind::Impl { + polarity: hir::ImplPolarity::Positive, of_trait: Some(_), .. + } => { if is_rustc_reservation { ty::ImplPolarity::Reservation } else { ty::ImplPolarity::Positive } } - item => bug!("impl_polarity: {:?} not an impl", item), + ref item => bug!("impl_polarity: {:?} not an impl", item), } } @@ -1786,11 +1777,11 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericP Node::Item(item) => { match item.kind { - ItemKind::Impl(ref impl_) => { - if impl_.defaultness.is_default() { + ItemKind::Impl { defaultness, ref generics, .. } => { + if defaultness.is_default() { is_default_impl_trait = tcx.impl_trait_ref(def_id); } - &impl_.generics + generics } ItemKind::Fn(.., ref generics, _) | ItemKind::TyAlias(_, ref generics) @@ -1946,10 +1937,13 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericP } else { let span = bound_pred.bounded_ty.span; let re_root_empty = tcx.lifetimes.re_root_empty; - let predicate = ty::Binder::bind(ty::PredicateKind::TypeOutlives( + let predicate = ty::Binder::bind(ty::PredicateAtom::TypeOutlives( ty::OutlivesPredicate(ty, re_root_empty), )); - predicates.insert((predicate.to_predicate(tcx), span)); + predicates.insert(( + predicate.potentially_quantified(tcx, ty::PredicateKind::ForAll), + span, + )); } } @@ -1990,10 +1984,10 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericP hir::GenericBound::Outlives(lifetime) => { let region = AstConv::ast_region_to_region(&icx, lifetime, None); predicates.insert(( - ty::Binder::bind(ty::PredicateKind::TypeOutlives( + ty::Binder::bind(ty::PredicateAtom::TypeOutlives( ty::OutlivesPredicate(ty, region), )) - .to_predicate(tcx), + .potentially_quantified(tcx, ty::PredicateKind::ForAll), lifetime.span, )); } @@ -2010,7 +2004,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericP } _ => bug!(), }; - let pred = ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(r1, r2)) + let pred = ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate(r1, r2)) .to_predicate(icx.tcx); (pred, span) @@ -2075,7 +2069,7 @@ fn const_evaluatable_predicates_of<'tcx>( if let ty::ConstKind::Unevaluated(def, substs, None) = ct.val { let span = self.tcx.hir().span(c.hir_id); self.preds.insert(( - ty::PredicateKind::ConstEvaluatable(def, substs).to_predicate(self.tcx), + ty::PredicateAtom::ConstEvaluatable(def, substs).to_predicate(self.tcx), span, )); } @@ -2094,7 +2088,7 @@ fn const_evaluatable_predicates_of<'tcx>( fn visit_const(&mut self, ct: &'tcx Const<'tcx>) -> ControlFlow { if let ty::ConstKind::Unevaluated(def, substs, None) = ct.val { self.preds.insert(( - ty::PredicateKind::ConstEvaluatable(def, substs).to_predicate(self.tcx), + ty::PredicateAtom::ConstEvaluatable(def, substs).to_predicate(self.tcx), self.span, )); } @@ -2119,14 +2113,14 @@ fn const_evaluatable_predicates_of<'tcx>( let mut collector = ConstCollector { tcx, preds: FxIndexSet::default() }; if let hir::Node::Item(item) = node { - if let hir::ItemKind::Impl(ref impl_) = item.kind { - if let Some(of_trait) = &impl_.of_trait { + if let hir::ItemKind::Impl { ref of_trait, ref self_ty, .. } = item.kind { + if let Some(of_trait) = of_trait { debug!("const_evaluatable_predicates_of({:?}): visit impl trait_ref", def_id); collector.visit_trait_ref(of_trait); } debug!("const_evaluatable_predicates_of({:?}): visit_self_ty", def_id); - collector.visit_ty(impl_.self_ty); + collector.visit_ty(self_ty); } } @@ -2180,12 +2174,12 @@ fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicat .predicates .iter() .copied() - .filter(|(pred, _)| match pred.kind().skip_binder() { - ty::PredicateKind::Trait(tr, _) => !is_assoc_item_ty(tr.self_ty()), - ty::PredicateKind::Projection(proj) => { + .filter(|(pred, _)| match pred.skip_binders() { + ty::PredicateAtom::Trait(tr, _) => !is_assoc_item_ty(tr.self_ty()), + ty::PredicateAtom::Projection(proj) => { !is_assoc_item_ty(proj.projection_ty.self_ty()) } - ty::PredicateKind::TypeOutlives(outlives) => !is_assoc_item_ty(outlives.0), + ty::PredicateAtom::TypeOutlives(outlives) => !is_assoc_item_ty(outlives.0), _ => true, }) .collect(); @@ -2214,8 +2208,7 @@ fn projection_ty_from_predicates( let (ty_def_id, item_def_id) = key; let mut projection_ty = None; for (predicate, _) in tcx.predicates_of(ty_def_id).predicates { - if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() - { + if let ty::PredicateAtom::Projection(projection_predicate) = predicate.skip_binders() { if item_def_id == projection_predicate.projection_ty.item_def_id { projection_ty = Some(projection_predicate.projection_ty); break; @@ -2262,7 +2255,7 @@ fn predicates_from_bound<'tcx>( } hir::GenericBound::Outlives(ref lifetime) => { let region = astconv.ast_region_to_region(lifetime, None); - let pred = ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(param_ty, region)) + let pred = ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(param_ty, region)) .to_predicate(astconv.tcx()); vec![(pred, lifetime.span)] } @@ -2959,7 +2952,7 @@ fn check_target_feature_trait_unsafe(tcx: TyCtxt<'_>, id: LocalDefId, attr_span: if let Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) = node { let parent_id = tcx.hir().get_parent_item(hir_id); let parent_item = tcx.hir().expect_item(parent_id); - if let hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = parent_item.kind { + if let hir::ItemKind::Impl { of_trait: Some(_), .. } = parent_item.kind { tcx.sess .struct_span_err( attr_span, diff --git a/compiler/rustc_typeck/src/collect/item_bounds.rs b/compiler/rustc_typeck/src/collect/item_bounds.rs index 537a58328942b..e596dd1a396c9 100644 --- a/compiler/rustc_typeck/src/collect/item_bounds.rs +++ b/compiler/rustc_typeck/src/collect/item_bounds.rs @@ -36,14 +36,13 @@ fn associated_type_bounds<'tcx>( let trait_def_id = tcx.associated_item(assoc_item_def_id).container.id(); let trait_predicates = tcx.trait_explicit_predicates_and_bounds(trait_def_id.expect_local()); - let bounds_from_parent = trait_predicates.predicates.iter().copied().filter(|(pred, _)| { - match pred.kind().skip_binder() { - ty::PredicateKind::Trait(tr, _) => tr.self_ty() == item_ty, - ty::PredicateKind::Projection(proj) => proj.projection_ty.self_ty() == item_ty, - ty::PredicateKind::TypeOutlives(outlives) => outlives.0 == item_ty, + let bounds_from_parent = + trait_predicates.predicates.iter().copied().filter(|(pred, _)| match pred.skip_binders() { + ty::PredicateAtom::Trait(tr, _) => tr.self_ty() == item_ty, + ty::PredicateAtom::Projection(proj) => proj.projection_ty.self_ty() == item_ty, + ty::PredicateAtom::TypeOutlives(outlives) => outlives.0 == item_ty, _ => false, - } - }); + }); let all_bounds = tcx .arena diff --git a/compiler/rustc_typeck/src/collect/type_of.rs b/compiler/rustc_typeck/src/collect/type_of.rs index e4eabca9c3b76..3c97b55005c44 100644 --- a/compiler/rustc_typeck/src/collect/type_of.rs +++ b/compiler/rustc_typeck/src/collect/type_of.rs @@ -243,8 +243,9 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> { icx.to_ty(ty) } } - ItemKind::TyAlias(ref self_ty, _) - | ItemKind::Impl(hir::Impl { ref self_ty, .. }) => icx.to_ty(self_ty), + ItemKind::TyAlias(ref self_ty, _) | ItemKind::Impl { ref self_ty, .. } => { + icx.to_ty(self_ty) + } ItemKind::Fn(..) => { let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id()); tcx.mk_fn_def(def_id.to_def_id(), substs) diff --git a/compiler/rustc_typeck/src/constrained_generic_params.rs b/compiler/rustc_typeck/src/constrained_generic_params.rs index 95670b9bdb983..e389fd4d9f00f 100644 --- a/compiler/rustc_typeck/src/constrained_generic_params.rs +++ b/compiler/rustc_typeck/src/constrained_generic_params.rs @@ -183,8 +183,7 @@ pub fn setup_constraining_predicates<'tcx>( for j in i..predicates.len() { // Note that we don't have to care about binders here, // as the impl trait ref never contains any late-bound regions. - if let ty::PredicateKind::Projection(projection) = predicates[j].0.kind().skip_binder() - { + if let ty::PredicateAtom::Projection(projection) = predicates[j].0.skip_binders() { // Special case: watch out for some kind of sneaky attempt // to project out an associated type defined by this very // trait. diff --git a/compiler/rustc_typeck/src/expr_use_visitor.rs b/compiler/rustc_typeck/src/expr_use_visitor.rs index 01519e4c8f7c4..3ce244e11bf45 100644 --- a/compiler/rustc_typeck/src/expr_use_visitor.rs +++ b/compiler/rustc_typeck/src/expr_use_visitor.rs @@ -219,14 +219,6 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { self.consume_exprs(exprs); } - hir::ExprKind::If(ref cond_expr, ref then_expr, ref opt_else_expr) => { - self.consume_expr(&cond_expr); - self.consume_expr(&then_expr); - if let Some(ref else_expr) = *opt_else_expr { - self.consume_expr(&else_expr); - } - } - hir::ExprKind::Match(ref discr, arms, _) => { let discr_place = return_if_err!(self.mc.cat_expr(&discr)); self.borrow_expr(&discr, ty::ImmBorrow); diff --git a/compiler/rustc_typeck/src/impl_wf_check.rs b/compiler/rustc_typeck/src/impl_wf_check.rs index 0bdcbaac0e984..14daa97c2c587 100644 --- a/compiler/rustc_typeck/src/impl_wf_check.rs +++ b/compiler/rustc_typeck/src/impl_wf_check.rs @@ -80,10 +80,10 @@ struct ImplWfCheck<'tcx> { impl ItemLikeVisitor<'tcx> for ImplWfCheck<'tcx> { fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { - if let hir::ItemKind::Impl(ref impl_) = item.kind { + if let hir::ItemKind::Impl { ref items, .. } = item.kind { let impl_def_id = self.tcx.hir().local_def_id(item.hir_id); - enforce_impl_params_are_constrained(self.tcx, impl_def_id, impl_.items); - enforce_impl_items_are_distinct(self.tcx, impl_.items); + enforce_impl_params_are_constrained(self.tcx, impl_def_id, items); + enforce_impl_items_are_distinct(self.tcx, items); if self.min_specialization { check_min_specialization(self.tcx, impl_def_id.to_def_id(), item.span); } diff --git a/compiler/rustc_typeck/src/impl_wf_check/min_specialization.rs b/compiler/rustc_typeck/src/impl_wf_check/min_specialization.rs index 505d9a59d9c2f..5db9ff9524de0 100644 --- a/compiler/rustc_typeck/src/impl_wf_check/min_specialization.rs +++ b/compiler/rustc_typeck/src/impl_wf_check/min_specialization.rs @@ -198,7 +198,7 @@ fn unconstrained_parent_impl_substs<'tcx>( // the functions in `cgp` add the constrained parameters to a list of // unconstrained parameters. for (predicate, _) in impl_generic_predicates.predicates.iter() { - if let ty::PredicateKind::Projection(proj) = predicate.kind().skip_binder() { + if let ty::PredicateAtom::Projection(proj) = predicate.skip_binders() { let projection_ty = proj.projection_ty; let projected_ty = proj.ty; @@ -360,13 +360,13 @@ fn check_predicates<'tcx>( fn check_specialization_on<'tcx>(tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tcx>, span: Span) { debug!("can_specialize_on(predicate = {:?})", predicate); - match predicate.kind().skip_binder() { + match predicate.skip_binders() { // Global predicates are either always true or always false, so we // are fine to specialize on. _ if predicate.is_global() => (), // We allow specializing on explicitly marked traits with no associated // items. - ty::PredicateKind::Trait(pred, hir::Constness::NotConst) => { + ty::PredicateAtom::Trait(pred, hir::Constness::NotConst) => { if !matches!( trait_predicate_kind(tcx, predicate), Some(TraitSpecializationKind::Marker) @@ -393,20 +393,20 @@ fn trait_predicate_kind<'tcx>( tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tcx>, ) -> Option { - match predicate.kind().skip_binder() { - ty::PredicateKind::Trait(pred, hir::Constness::NotConst) => { + match predicate.skip_binders() { + ty::PredicateAtom::Trait(pred, hir::Constness::NotConst) => { Some(tcx.trait_def(pred.def_id()).specialization_kind) } - ty::PredicateKind::Trait(_, hir::Constness::Const) - | ty::PredicateKind::RegionOutlives(_) - | ty::PredicateKind::TypeOutlives(_) - | ty::PredicateKind::Projection(_) - | ty::PredicateKind::WellFormed(_) - | ty::PredicateKind::Subtype(_) - | ty::PredicateKind::ObjectSafe(_) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) - | ty::PredicateKind::TypeWellFormedFromEnv(..) => None, + ty::PredicateAtom::Trait(_, hir::Constness::Const) + | ty::PredicateAtom::RegionOutlives(_) + | ty::PredicateAtom::TypeOutlives(_) + | ty::PredicateAtom::Projection(_) + | ty::PredicateAtom::WellFormed(_) + | ty::PredicateAtom::Subtype(_) + | ty::PredicateAtom::ObjectSafe(_) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) + | ty::PredicateAtom::TypeWellFormedFromEnv(..) => None, } } diff --git a/compiler/rustc_typeck/src/mem_categorization.rs b/compiler/rustc_typeck/src/mem_categorization.rs index fef52a3f87c95..a601123c8d055 100644 --- a/compiler/rustc_typeck/src/mem_categorization.rs +++ b/compiler/rustc_typeck/src/mem_categorization.rs @@ -364,7 +364,6 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { | hir::ExprKind::Cast(..) | hir::ExprKind::DropTemps(..) | hir::ExprKind::Array(..) - | hir::ExprKind::If(..) | hir::ExprKind::Tup(..) | hir::ExprKind::Binary(..) | hir::ExprKind::Block(..) @@ -654,7 +653,9 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { // Then we see that to get the same result, we must start with // `deref { deref { place_foo }}` instead of `place_foo` since the pattern is now `Some(x,)` // and not `&&Some(x,)`, even though its assigned type is that of `&&Some(x,)`. - for _ in 0..self.typeck_results.pat_adjustments().get(pat.hir_id).map_or(0, |v| v.len()) { + for _ in + 0..self.typeck_results.pat_adjustments().get(pat.hir_id).map(|v| v.len()).unwrap_or(0) + { debug!("cat_pattern: applying adjustment to place_with_id={:?}", place_with_id); place_with_id = self.cat_deref(pat, place_with_id)?; } diff --git a/compiler/rustc_typeck/src/outlives/explicit.rs b/compiler/rustc_typeck/src/outlives/explicit.rs index 6e5be87928d59..ae336ccca457d 100644 --- a/compiler/rustc_typeck/src/outlives/explicit.rs +++ b/compiler/rustc_typeck/src/outlives/explicit.rs @@ -29,8 +29,8 @@ impl<'tcx> ExplicitPredicatesMap<'tcx> { // process predicates and convert to `RequiredPredicates` entry, see below for &(predicate, span) in predicates.predicates { - match predicate.kind().skip_binder() { - ty::PredicateKind::TypeOutlives(OutlivesPredicate(ref ty, ref reg)) => { + match predicate.skip_binders() { + ty::PredicateAtom::TypeOutlives(OutlivesPredicate(ref ty, ref reg)) => { insert_outlives_predicate( tcx, (*ty).into(), @@ -40,7 +40,7 @@ impl<'tcx> ExplicitPredicatesMap<'tcx> { ) } - ty::PredicateKind::RegionOutlives(OutlivesPredicate(ref reg1, ref reg2)) => { + ty::PredicateAtom::RegionOutlives(OutlivesPredicate(ref reg1, ref reg2)) => { insert_outlives_predicate( tcx, (*reg1).into(), @@ -50,15 +50,15 @@ impl<'tcx> ExplicitPredicatesMap<'tcx> { ) } - ty::PredicateKind::Trait(..) - | ty::PredicateKind::Projection(..) - | ty::PredicateKind::WellFormed(..) - | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::Subtype(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) - | ty::PredicateKind::TypeWellFormedFromEnv(..) => (), + ty::PredicateAtom::Trait(..) + | ty::PredicateAtom::Projection(..) + | ty::PredicateAtom::WellFormed(..) + | ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) + | ty::PredicateAtom::TypeWellFormedFromEnv(..) => (), } } diff --git a/compiler/rustc_typeck/src/outlives/implicit_infer.rs b/compiler/rustc_typeck/src/outlives/implicit_infer.rs index 02008e180b34d..3d0635e3fe437 100644 --- a/compiler/rustc_typeck/src/outlives/implicit_infer.rs +++ b/compiler/rustc_typeck/src/outlives/implicit_infer.rs @@ -99,7 +99,7 @@ impl<'cx, 'tcx> ItemLikeVisitor<'tcx> for InferVisitor<'cx, 'tcx> { // we walk the crates again and re-calculate predicates for all // items. let item_predicates_len: usize = - self.global_inferred_outlives.get(&item_did.to_def_id()).map_or(0, |p| p.len()); + self.global_inferred_outlives.get(&item_did.to_def_id()).map(|p| p.len()).unwrap_or(0); if item_required_predicates.len() > item_predicates_len { *self.predicates_added = true; self.global_inferred_outlives.insert(item_did.to_def_id(), item_required_predicates); diff --git a/compiler/rustc_typeck/src/outlives/mod.rs b/compiler/rustc_typeck/src/outlives/mod.rs index e94b8450bfd05..b1f79331d5f62 100644 --- a/compiler/rustc_typeck/src/outlives/mod.rs +++ b/compiler/rustc_typeck/src/outlives/mod.rs @@ -30,9 +30,13 @@ fn inferred_outlives_of(tcx: TyCtxt<'_>, item_def_id: DefId) -> &[(ty::Predicate if tcx.has_attr(item_def_id, sym::rustc_outlives) { let mut pred: Vec = predicates .iter() - .map(|(out_pred, _)| match out_pred.kind().skip_binder() { - ty::PredicateKind::RegionOutlives(p) => p.to_string(), - ty::PredicateKind::TypeOutlives(p) => p.to_string(), + .map(|(out_pred, _)| match out_pred.kind() { + ty::PredicateKind::Atom(ty::PredicateAtom::RegionOutlives(p)) => { + p.to_string() + } + ty::PredicateKind::Atom(ty::PredicateAtom::TypeOutlives(p)) => { + p.to_string() + } err => bug!("unexpected predicate {:?}", err), }) .collect(); @@ -85,12 +89,12 @@ fn inferred_outlives_crate(tcx: TyCtxt<'_>, crate_num: CrateNum) -> CratePredica |(ty::OutlivesPredicate(kind1, region2), &span)| { match kind1.unpack() { GenericArgKind::Type(ty1) => Some(( - ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty1, region2)) + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty1, region2)) .to_predicate(tcx), span, )), GenericArgKind::Lifetime(region1) => Some(( - ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate( + ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate( region1, region2, )) .to_predicate(tcx), diff --git a/compiler/rustc_typeck/src/structured_errors.rs b/compiler/rustc_typeck/src/structured_errors.rs index 04d04304e70f9..83125a3e2feb6 100644 --- a/compiler/rustc_typeck/src/structured_errors.rs +++ b/compiler/rustc_typeck/src/structured_errors.rs @@ -1,36 +1,149 @@ -mod missing_cast_for_variadic_arg; -mod sized_unsized_cast; -mod wrong_number_of_generic_args; - -pub use self::{ - missing_cast_for_variadic_arg::*, sized_unsized_cast::*, wrong_number_of_generic_args::*, -}; - -use rustc_errors::{DiagnosticBuilder, DiagnosticId}; +use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticId}; +use rustc_middle::ty::{Ty, TypeFoldable}; use rustc_session::Session; +use rustc_span::Span; pub trait StructuredDiagnostic<'tcx> { fn session(&self) -> &Session; fn code(&self) -> DiagnosticId; + fn common(&self) -> DiagnosticBuilder<'tcx>; + fn diagnostic(&self) -> DiagnosticBuilder<'tcx> { - let err = self.diagnostic_common(); + let err = self.common(); + if self.session().teach(&self.code()) { self.extended(err) } else { self.regular(err) } + } + + fn regular(&self, err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> { + err + } + + fn extended(&self, err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> { + err + } +} + +pub struct VariadicError<'tcx> { + sess: &'tcx Session, + span: Span, + t: Ty<'tcx>, + cast_ty: &'tcx str, +} + +impl<'tcx> VariadicError<'tcx> { + pub fn new( + sess: &'tcx Session, + span: Span, + t: Ty<'tcx>, + cast_ty: &'tcx str, + ) -> VariadicError<'tcx> { + VariadicError { sess, span, t, cast_ty } + } +} + +impl<'tcx> StructuredDiagnostic<'tcx> for VariadicError<'tcx> { + fn session(&self) -> &Session { + self.sess + } + + fn code(&self) -> DiagnosticId { + rustc_errors::error_code!(E0617) + } - if self.session().teach(&self.code()) { - self.diagnostic_extended(err) + fn common(&self) -> DiagnosticBuilder<'tcx> { + let mut err = if self.t.references_error() { + self.sess.diagnostic().struct_dummy() } else { - self.diagnostic_regular(err) + self.sess.struct_span_fatal_with_code( + self.span, + &format!("can't pass `{}` to variadic function", self.t), + self.code(), + ) + }; + if let Ok(snippet) = self.sess.source_map().span_to_snippet(self.span) { + err.span_suggestion( + self.span, + &format!("cast the value to `{}`", self.cast_ty), + format!("{} as {}", snippet, self.cast_ty), + Applicability::MachineApplicable, + ); + } else { + err.help(&format!("cast the value to `{}`", self.cast_ty)); } + err } - fn diagnostic_common(&self) -> DiagnosticBuilder<'tcx>; - - fn diagnostic_regular(&self, err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> { + fn extended(&self, mut err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> { + err.note(&format!( + "certain types, like `{}`, must be cast before passing them to a \ + variadic function, because of arcane ABI rules dictated by the C \ + standard", + self.t + )); err } +} + +pub struct SizedUnsizedCastError<'tcx> { + sess: &'tcx Session, + span: Span, + expr_ty: Ty<'tcx>, + cast_ty: String, +} + +impl<'tcx> SizedUnsizedCastError<'tcx> { + pub fn new( + sess: &'tcx Session, + span: Span, + expr_ty: Ty<'tcx>, + cast_ty: String, + ) -> SizedUnsizedCastError<'tcx> { + SizedUnsizedCastError { sess, span, expr_ty, cast_ty } + } +} + +impl<'tcx> StructuredDiagnostic<'tcx> for SizedUnsizedCastError<'tcx> { + fn session(&self) -> &Session { + self.sess + } + + fn code(&self) -> DiagnosticId { + rustc_errors::error_code!(E0607) + } + + fn common(&self) -> DiagnosticBuilder<'tcx> { + if self.expr_ty.references_error() { + self.sess.diagnostic().struct_dummy() + } else { + self.sess.struct_span_fatal_with_code( + self.span, + &format!( + "cannot cast thin pointer `{}` to fat pointer `{}`", + self.expr_ty, self.cast_ty + ), + self.code(), + ) + } + } + + fn extended(&self, mut err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> { + err.help( + "Thin pointers are \"simple\" pointers: they are purely a reference to a +memory address. + +Fat pointers are pointers referencing \"Dynamically Sized Types\" (also +called DST). DST don't have a statically known size, therefore they can +only exist behind some kind of pointers that contain additional +information. Slices and trait objects are DSTs. In the case of slices, +the additional information the fat pointer holds is their size. + +To fix this error, don't try to cast directly between thin and fat +pointers. - fn diagnostic_extended(&self, err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> { +For more information about casts, take a look at The Book: +https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions", + ); err } } diff --git a/compiler/rustc_typeck/src/structured_errors/missing_cast_for_variadic_arg.rs b/compiler/rustc_typeck/src/structured_errors/missing_cast_for_variadic_arg.rs deleted file mode 100644 index 674b0e463f51d..0000000000000 --- a/compiler/rustc_typeck/src/structured_errors/missing_cast_for_variadic_arg.rs +++ /dev/null @@ -1,58 +0,0 @@ -use crate::structured_errors::StructuredDiagnostic; -use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticId}; -use rustc_middle::ty::{Ty, TypeFoldable}; -use rustc_session::Session; -use rustc_span::Span; - -pub struct MissingCastForVariadicArg<'tcx> { - pub sess: &'tcx Session, - pub span: Span, - pub ty: Ty<'tcx>, - pub cast_ty: &'tcx str, -} - -impl<'tcx> StructuredDiagnostic<'tcx> for MissingCastForVariadicArg<'tcx> { - fn session(&self) -> &Session { - self.sess - } - - fn code(&self) -> DiagnosticId { - rustc_errors::error_code!(E0617) - } - - fn diagnostic_common(&self) -> DiagnosticBuilder<'tcx> { - let mut err = if self.ty.references_error() { - self.sess.diagnostic().struct_dummy() - } else { - self.sess.struct_span_fatal_with_code( - self.span, - &format!("can't pass `{}` to variadic function", self.ty), - self.code(), - ) - }; - - if let Ok(snippet) = self.sess.source_map().span_to_snippet(self.span) { - err.span_suggestion( - self.span, - &format!("cast the value to `{}`", self.cast_ty), - format!("{} as {}", snippet, self.cast_ty), - Applicability::MachineApplicable, - ); - } else { - err.help(&format!("cast the value to `{}`", self.cast_ty)); - } - - err - } - - fn diagnostic_extended(&self, mut err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> { - err.note(&format!( - "certain types, like `{}`, must be casted before passing them to a \ - variadic function, because of arcane ABI rules dictated by the C \ - standard", - self.ty - )); - - err - } -} diff --git a/compiler/rustc_typeck/src/structured_errors/sized_unsized_cast.rs b/compiler/rustc_typeck/src/structured_errors/sized_unsized_cast.rs deleted file mode 100644 index d0477a3e74829..0000000000000 --- a/compiler/rustc_typeck/src/structured_errors/sized_unsized_cast.rs +++ /dev/null @@ -1,57 +0,0 @@ -use crate::structured_errors::StructuredDiagnostic; -use rustc_errors::{DiagnosticBuilder, DiagnosticId}; -use rustc_middle::ty::{Ty, TypeFoldable}; -use rustc_session::Session; -use rustc_span::Span; - -pub struct SizedUnsizedCast<'tcx> { - pub sess: &'tcx Session, - pub span: Span, - pub expr_ty: Ty<'tcx>, - pub cast_ty: String, -} - -impl<'tcx> StructuredDiagnostic<'tcx> for SizedUnsizedCast<'tcx> { - fn session(&self) -> &Session { - self.sess - } - - fn code(&self) -> DiagnosticId { - rustc_errors::error_code!(E0607) - } - - fn diagnostic_common(&self) -> DiagnosticBuilder<'tcx> { - if self.expr_ty.references_error() { - self.sess.diagnostic().struct_dummy() - } else { - self.sess.struct_span_fatal_with_code( - self.span, - &format!( - "cannot cast thin pointer `{}` to fat pointer `{}`", - self.expr_ty, self.cast_ty - ), - self.code(), - ) - } - } - - fn diagnostic_extended(&self, mut err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> { - err.help( - "Thin pointers are \"simple\" pointers: they are purely a reference to a -memory address. - -Fat pointers are pointers referencing \"Dynamically Sized Types\" (also -called DST). DST don't have a statically known size, therefore they can -only exist behind some kind of pointers that contain additional -information. Slices and trait objects are DSTs. In the case of slices, -the additional information the fat pointer holds is their size. - -To fix this error, don't try to cast directly between thin and fat -pointers. - -For more information about casts, take a look at The Book: -https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions", - ); - err - } -} diff --git a/compiler/rustc_typeck/src/structured_errors/wrong_number_of_generic_args.rs b/compiler/rustc_typeck/src/structured_errors/wrong_number_of_generic_args.rs deleted file mode 100644 index e35c155746642..0000000000000 --- a/compiler/rustc_typeck/src/structured_errors/wrong_number_of_generic_args.rs +++ /dev/null @@ -1,393 +0,0 @@ -use crate::structured_errors::StructuredDiagnostic; -use hir::def::DefKind; -use rustc_errors::{pluralize, Applicability, DiagnosticBuilder, DiagnosticId}; -use rustc_hir as hir; -use rustc_middle::ty::{self as ty, TyCtxt}; -use rustc_session::Session; -use rustc_span::Span; -use rustc_span::{def_id::DefId, MultiSpan}; - -/// Handles the `wrong number of type / lifetime / ... arguments` family of error messages. -pub struct WrongNumberOfGenericArgs<'a, 'tcx> { - crate tcx: TyCtxt<'tcx>, - - /// "type", "lifetime" etc., put verbatim into the message - crate kind: &'static str, - - /// Minimum number of expected generic arguments (e.g. `2` for `HashMap`) - crate expected_min: usize, - - /// Maximum number of expected generic arguments (e.g. `3` for `HashMap`) - crate expected_max: usize, - - /// Number of generic arguments provided by the user - crate provided: usize, - - /// Offset into `gen_params` - depends on the `kind`; might be different than `args_offset` when - /// user passed e.g. more arguments than was actually expected - crate params_offset: usize, - - /// Offset into `gen_args` - depends on the `kind` - crate args_offset: usize, - - /// Offending path segment - crate path_segment: &'a hir::PathSegment<'a>, - - /// Generic parameters as expected by type or trait - crate gen_params: &'a ty::Generics, - - /// Generic arguments as provided by user - crate gen_args: &'a hir::GenericArgs<'a>, - - /// DefId of the generic type - crate def_id: DefId, - - /// Offending place where the generic type has been misused - crate span: Span, -} - -impl<'tcx> WrongNumberOfGenericArgs<'_, 'tcx> { - fn quantifier_and_bound(&self) -> (&'static str, usize) { - if self.expected_min == self.expected_max { - ("", self.expected_min) - } else if self.provided < self.expected_min { - ("at least ", self.expected_min) - } else { - ("at most ", self.expected_max) - } - } - - fn start_diagnostics(&self) -> DiagnosticBuilder<'tcx> { - let span = self.path_segment.ident.span; - - let msg = { - let def_path = self.tcx.def_path_str(self.def_id); - let def_kind = self.tcx.def_kind(self.def_id).descr(self.def_id); - let (quantifier, bound) = self.quantifier_and_bound(); - - if self.gen_args.span().is_some() { - format!( - "this {} takes {}{} {} argument{} but {}{} {} argument{} {} supplied", - def_kind, - quantifier, - bound, - self.kind, - pluralize!(bound), - if self.provided > 0 && self.provided < self.expected_min { - "only " - } else { - "" - }, - self.provided, - self.kind, - pluralize!(self.provided), - if self.provided == 1 { "was" } else { "were" }, - ) - } else { - format!("missing generics for {} `{}`", def_kind, def_path) - } - }; - - self.tcx.sess.struct_span_err_with_code(span, &msg, self.code()) - } - - /// Builds the `expected 1 type argument / supplied 2 type arguments` message. - fn notify(&self, err: &mut DiagnosticBuilder<'_>) { - let (quantifier, bound) = self.quantifier_and_bound(); - - err.span_label( - self.path_segment.ident.span, - format!( - "expected {}{} {} argument{}", - quantifier, - bound, - self.kind, - pluralize!(bound), - ), - ); - - // When user's provided too many arguments, we don't highlight each of them, because it - // would overlap with the suggestion to remove them: - // - // ``` - // type Foo = Bar; - // ----- ----- supplied 2 type arguments - // ^^^^^^^ remove this type argument - // ``` - if self.provided > self.expected_max { - return; - } - - let args = self.gen_args.args.iter().skip(self.args_offset).take(self.provided).enumerate(); - - for (i, arg) in args { - err.span_label( - arg.span(), - if i + 1 == self.provided { - format!( - "supplied {} {} argument{}", - self.provided, - self.kind, - pluralize!(self.provided) - ) - } else { - String::new() - }, - ); - } - } - - fn suggest(&self, err: &mut DiagnosticBuilder<'_>) { - if self.provided == 0 { - if self.gen_args.span().is_some() { - self.suggest_adding_args(err); - } else { - self.suggest_creating_generics(err); - } - } else if self.provided < self.expected_min { - self.suggest_adding_args(err); - } else { - self.suggest_removing_args_or_generics(err); - } - } - - /// Suggests to create generics (`<...>`) when current invocation site contains no generics at - /// all: - /// - /// ```text - /// type Map = HashMap; - /// ``` - fn suggest_creating_generics(&self, err: &mut DiagnosticBuilder<'_>) { - let params = self - .gen_params - .params - .iter() - .skip(self.params_offset) - .take(self.expected_min) - .map(|param| param.name.to_string()) - .collect::>() - .join(", "); - - let def_kind = self.tcx.def_kind(self.def_id); - - let sugg = if matches!(def_kind, DefKind::Fn | DefKind::AssocFn) { - format!("::<{}>", params) - } else { - format!("<{}>", params) - }; - - let msg = format!( - "use angle brackets to add missing {} argument{}", - self.kind, - pluralize!(self.expected_min), - ); - - err.span_suggestion_verbose( - self.path_segment.ident.span.shrink_to_hi(), - &msg, - sugg, - Applicability::HasPlaceholders, - ); - } - - /// Suggests to add missing argument(s) when current invocation site already contains some - /// generics: - /// - /// ```text - /// type Map = HashMap; - /// ``` - fn suggest_adding_args(&self, err: &mut DiagnosticBuilder<'_>) { - assert!(!self.gen_args.is_empty()); - - if self.gen_args.parenthesized { - return; - } - - let missing_arg_count = self.expected_min - self.provided; - - let (span, sugg_prefix) = if self.args_offset + self.provided == 0 { - let span = self.gen_args.args[0].span().shrink_to_lo(); - (span, "") - } else { - let span = - self.gen_args.args[self.args_offset + self.provided - 1].span().shrink_to_hi(); - (span, ", ") - }; - - let msg = format!("add missing {} argument{}", self.kind, pluralize!(missing_arg_count)); - - let sugg = self - .gen_params - .params - .iter() - .skip(self.params_offset + self.provided) - .take(missing_arg_count) - .map(|param| param.name.to_string()) - .collect::>() - .join(", "); - - let sugg = format!("{}{}", sugg_prefix, sugg); - - err.span_suggestion_verbose(span, &msg, sugg, Applicability::HasPlaceholders); - } - - /// Suggests to remove redundant argument(s): - /// - /// ```text - /// type Map = HashMap; - /// ``` - fn suggest_removing_args_or_generics(&self, err: &mut DiagnosticBuilder<'_>) { - assert!(self.provided > 0); - - let redundant_args_count = self.provided - self.expected_max; - let remove_entire_generics = redundant_args_count >= self.gen_args.args.len(); - - let (span, msg) = if remove_entire_generics { - let sm = self.tcx.sess.source_map(); - - let span = self - .path_segment - .args - .unwrap() - .span_ext(sm) - .unwrap() - .with_lo(self.path_segment.ident.span.hi()); - - let msg = format!( - "remove these {}generics", - if self.gen_args.parenthesized { "parenthetical " } else { "" }, - ); - - (span, msg) - } else { - // When it comes to removing particular argument(s) from the generics, there are two - // edge cases we have to consider: - // - // When the first redundant argument is at the beginning or in the middle of the - // generics, like so: - // - // ``` - // type Map = HashMap; - // ^^^^^^^^^^^^^^^^ - // | span must start with the argument - // ``` - // - // When the last redundant argument is at the ending of the generics, like so: - // - // ``` - // type Map = HashMap; - // ^^^^^^^^^^^^^^^^ - // | span must start with the comma - // ``` - - // Index of the first redundant argument - let from_idx = self.args_offset + self.expected_max; - - // Index of the last redundant argument - let to_idx = self.args_offset + self.provided - 1; - - assert!(from_idx <= to_idx); - - let (from, comma_eaten) = { - let first_argument_starts_generics = from_idx == 0; - let last_argument_ends_generics = to_idx + 1 == self.gen_args.args.len(); - - if !first_argument_starts_generics && last_argument_ends_generics { - (self.gen_args.args[from_idx - 1].span().hi(), true) - } else { - (self.gen_args.args[from_idx].span().lo(), false) - } - }; - - let to = { - let hi = self.gen_args.args[to_idx].span().hi(); - - if comma_eaten { - hi - } else { - self.gen_args.args.get(to_idx + 1).map(|arg| arg.span().lo()).unwrap_or(hi) - } - }; - - let span = Span::new(from, to, self.span.ctxt()); - - let msg = format!( - "remove {} {} argument{}", - if redundant_args_count == 1 { "this" } else { "these" }, - self.kind, - pluralize!(redundant_args_count), - ); - - (span, msg) - }; - - err.span_suggestion(span, &msg, String::new(), Applicability::MaybeIncorrect); - } - - /// Builds the `type defined here` message. - fn show_definition(&self, err: &mut DiagnosticBuilder<'_>) { - let mut spans: MultiSpan = if let Some(def_span) = self.tcx.def_ident_span(self.def_id) { - def_span.into() - } else { - return; - }; - - let msg = { - let def_kind = self.tcx.def_kind(self.def_id).descr(self.def_id); - let (quantifier, bound) = self.quantifier_and_bound(); - - let params = if bound == 0 { - String::new() - } else { - let params = self - .gen_params - .params - .iter() - .skip(self.params_offset) - .take(bound) - .map(|param| { - let span = self.tcx.def_span(param.def_id); - spans.push_span_label(span, String::new()); - param - }) - .map(|param| format!("`{}`", param.name)) - .collect::>() - .join(", "); - - format!(": {}", params) - }; - - format!( - "{} defined here, with {}{} {} parameter{}{}", - def_kind, - quantifier, - bound, - self.kind, - pluralize!(bound), - params, - ) - }; - - err.span_note(spans, &msg); - } -} - -impl<'tcx> StructuredDiagnostic<'tcx> for WrongNumberOfGenericArgs<'_, 'tcx> { - fn session(&self) -> &Session { - self.tcx.sess - } - - fn code(&self) -> DiagnosticId { - rustc_errors::error_code!(E0107) - } - - fn diagnostic_common(&self) -> DiagnosticBuilder<'tcx> { - let mut err = self.start_diagnostics(); - - self.notify(&mut err); - self.suggest(&mut err); - self.show_definition(&mut err); - - err - } -} diff --git a/config.toml.example b/config.toml.example index 55b20adabd045..9e08ce9b27e0c 100644 --- a/config.toml.example +++ b/config.toml.example @@ -35,11 +35,9 @@ changelog-seen = 2 # Unless you're developing for a target where Rust CI doesn't build a compiler # toolchain or changing LLVM locally, you probably want to set this to true. # -# This is false by default so that distributions don't unexpectedly download -# LLVM from the internet. -# -# All tier 1 targets are currently supported; set this to `"if-supported"` if -# you are not sure whether you're on a tier 1 target. +# It's currently false by default due to being newly added; please file bugs if +# enabling this did not work for you on x86_64-unknown-linux-gnu. +# Other target triples are currently not supported; see #77084. # # We also currently only support this when building LLVM for the build triple. # diff --git a/library/alloc/src/alloc.rs b/library/alloc/src/alloc.rs index cb9daaea0001b..4fbcc4590f1a9 100644 --- a/library/alloc/src/alloc.rs +++ b/library/alloc/src/alloc.rs @@ -397,26 +397,3 @@ pub mod __alloc_error_handler { unsafe { oom_impl(layout) } } } - -/// Specialize clones into pre-allocated, uninitialized memory. -/// Used by `Box::clone` and `Rc`/`Arc::make_mut`. -pub(crate) trait WriteCloneIntoRaw: Sized { - unsafe fn write_clone_into_raw(&self, target: *mut Self); -} - -impl WriteCloneIntoRaw for T { - #[inline] - default unsafe fn write_clone_into_raw(&self, target: *mut Self) { - // Having allocated *first* may allow the optimizer to create - // the cloned value in-place, skipping the local and move. - unsafe { target.write(self.clone()) }; - } -} - -impl WriteCloneIntoRaw for T { - #[inline] - unsafe fn write_clone_into_raw(&self, target: *mut Self) { - // We can always copy in-place, without ever involving a local value. - unsafe { target.copy_from_nonoverlapping(self, 1) }; - } -} diff --git a/library/alloc/src/boxed.rs b/library/alloc/src/boxed.rs index 0aa52b35ced45..33b812ec59ff9 100644 --- a/library/alloc/src/boxed.rs +++ b/library/alloc/src/boxed.rs @@ -151,7 +151,7 @@ use core::pin::Pin; use core::ptr::{self, Unique}; use core::task::{Context, Poll}; -use crate::alloc::{handle_alloc_error, AllocError, Allocator, Global, Layout, WriteCloneIntoRaw}; +use crate::alloc::{handle_alloc_error, AllocError, Allocator, Global, Layout}; use crate::borrow::Cow; use crate::raw_vec::RawVec; use crate::str::from_boxed_utf8_unchecked; @@ -1014,14 +1014,10 @@ impl Clone for Box { /// // But they are unique objects /// assert_ne!(&*x as *const i32, &*y as *const i32); /// ``` + #[rustfmt::skip] #[inline] fn clone(&self) -> Self { - // Pre-allocate memory to allow writing the cloned value directly. - let mut boxed = Self::new_uninit_in(self.1.clone()); - unsafe { - (**self).write_clone_into_raw(boxed.as_mut_ptr()); - boxed.assume_init() - } + Self::new_in((**self).clone(), self.1.clone()) } /// Copies `source`'s contents into `self` without creating a new allocation. diff --git a/library/alloc/src/collections/binary_heap.rs b/library/alloc/src/collections/binary_heap.rs index 3c515af71f5ff..76051d9e1dffd 100644 --- a/library/alloc/src/collections/binary_heap.rs +++ b/library/alloc/src/collections/binary_heap.rs @@ -161,10 +161,7 @@ use super::SpecExtend; /// It is a logic error for an item to be modified in such a way that the /// item's ordering relative to any other item, as determined by the `Ord` /// trait, changes while it is in the heap. This is normally only possible -/// through `Cell`, `RefCell`, global state, I/O, or unsafe code. The -/// behavior resulting from such a logic error is not specified, but will -/// not result in undefined behavior. This could include panics, incorrect -/// results, aborts, memory leaks, and non-termination. +/// through `Cell`, `RefCell`, global state, I/O, or unsafe code. /// /// # Examples /// @@ -633,16 +630,10 @@ impl BinaryHeap { // and about 2 * (len1 + len2) comparisons in the worst case // while `extend` takes O(len2 * log(len1)) operations // and about 1 * len2 * log_2(len1) comparisons in the worst case, - // assuming len1 >= len2. For larger heaps, the crossover point - // no longer follows this reasoning and was determined empirically. + // assuming len1 >= len2. #[inline] fn better_to_rebuild(len1: usize, len2: usize) -> bool { - let tot_len = len1 + len2; - if tot_len <= 2048 { - 2 * tot_len < len2 * log2_fast(len1) - } else { - 2 * tot_len < len2 * 11 - } + 2 * (len1 + len2) < len2 * log2_fast(len1) } if better_to_rebuild(self.len(), other.len()) { diff --git a/library/alloc/src/collections/btree/map.rs b/library/alloc/src/collections/btree/map.rs index ecc2873187467..944e0e65cf7c1 100644 --- a/library/alloc/src/collections/btree/map.rs +++ b/library/alloc/src/collections/btree/map.rs @@ -10,7 +10,7 @@ use core::ptr; use super::borrow::DormantMutRef; use super::node::{self, marker, ForceResult::*, Handle, NodeRef, Root}; -use super::search::SearchResult::*; +use super::search::{self, SearchResult::*}; use super::unwrap_unchecked; mod entry; @@ -51,9 +51,6 @@ pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT; /// It is a logic error for a key to be modified in such a way that the key's ordering relative to /// any other key, as determined by the [`Ord`] trait, changes while it is in the map. This is /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code. -/// The behavior resulting from such a logic error is not specified, but will not result in -/// undefined behavior. This could include panics, incorrect results, aborts, memory leaks, and -/// non-termination. /// /// [`Cell`]: core::cell::Cell /// [`RefCell`]: core::cell::RefCell @@ -230,7 +227,7 @@ where fn get(&self, key: &Q) -> Option<&K> { let root_node = self.root.as_ref()?.reborrow(); - match root_node.search_tree(key) { + match search::search_tree(root_node, key) { Found(handle) => Some(handle.into_kv().0), GoDown(_) => None, } @@ -239,7 +236,7 @@ where fn take(&mut self, key: &Q) -> Option { let (map, dormant_map) = DormantMutRef::new(self); let root_node = map.root.as_mut()?.borrow_mut(); - match root_node.search_tree(key) { + match search::search_tree(root_node, key) { Found(handle) => { Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_kv().0) } @@ -250,7 +247,7 @@ where fn replace(&mut self, key: K) -> Option { let (map, dormant_map) = DormantMutRef::new(self); let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut(); - match root_node.search_tree::(&key) { + match search::search_tree::, K, (), K>(root_node, &key) { Found(mut kv) => Some(mem::replace(kv.key_mut(), key)), GoDown(handle) => { VacantEntry { key, handle, dormant_map, _marker: PhantomData }.insert(()); @@ -526,7 +523,7 @@ impl BTreeMap { Q: Ord, { let root_node = self.root.as_ref()?.reborrow(); - match root_node.search_tree(key) { + match search::search_tree(root_node, key) { Found(handle) => Some(handle.into_kv().1), GoDown(_) => None, } @@ -554,7 +551,7 @@ impl BTreeMap { Q: Ord, { let root_node = self.root.as_ref()?.reborrow(); - match root_node.search_tree(k) { + match search::search_tree(root_node, k) { Found(handle) => Some(handle.into_kv()), GoDown(_) => None, } @@ -762,7 +759,7 @@ impl BTreeMap { Q: Ord, { let root_node = self.root.as_mut()?.borrow_mut(); - match root_node.search_tree(key) { + match search::search_tree(root_node, key) { Found(handle) => Some(handle.into_val_mut()), GoDown(_) => None, } @@ -858,7 +855,7 @@ impl BTreeMap { { let (map, dormant_map) = DormantMutRef::new(self); let root_node = map.root.as_mut()?.borrow_mut(); - match root_node.search_tree(key) { + match search::search_tree(root_node, key) { Found(handle) => { Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_entry()) } @@ -1051,7 +1048,7 @@ impl BTreeMap { // FIXME(@porglezomp) Avoid allocating if we don't insert let (map, dormant_map) = DormantMutRef::new(self); let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut(); - match root_node.search_tree(&key) { + match search::search_tree(root_node, &key) { Found(handle) => Occupied(OccupiedEntry { handle, dormant_map, _marker: PhantomData }), GoDown(handle) => { Vacant(VacantEntry { key, handle, dormant_map, _marker: PhantomData }) diff --git a/library/alloc/src/collections/btree/navigate.rs b/library/alloc/src/collections/btree/navigate.rs index 17b4689e4a0ee..cce8b21a2bc41 100644 --- a/library/alloc/src/collections/btree/navigate.rs +++ b/library/alloc/src/collections/btree/navigate.rs @@ -5,7 +5,7 @@ use core::ops::RangeBounds; use core::ptr; use super::node::{marker, ForceResult::*, Handle, NodeRef}; -use super::search::SearchResult; +use super::search::{self, SearchResult}; use super::unwrap_unchecked; /// Finds the leaf edges delimiting a specified range in or underneath a node. @@ -25,12 +25,7 @@ where K: Borrow, R: RangeBounds, { - // WARNING: Inlining these variables would be unsound (#81138) - // We assume the bounds reported by `range` remain the same, but - // an adversarial implementation could change between calls - let start = range.start_bound(); - let end = range.end_bound(); - match (start, end) { + match (range.start_bound(), range.end_bound()) { (Excluded(s), Excluded(e)) if s == e => { panic!("range start and end are equal and excluded in BTreeMap") } @@ -46,16 +41,15 @@ where let mut max_found = false; loop { - // Using `range` again would be unsound (#81138) - let front = match (min_found, start) { - (false, Included(key)) => match min_node.search_node(key) { + let front = match (min_found, range.start_bound()) { + (false, Included(key)) => match search::search_node(min_node, key) { SearchResult::Found(kv) => { min_found = true; kv.left_edge() } SearchResult::GoDown(edge) => edge, }, - (false, Excluded(key)) => match min_node.search_node(key) { + (false, Excluded(key)) => match search::search_node(min_node, key) { SearchResult::Found(kv) => { min_found = true; kv.right_edge() @@ -67,16 +61,15 @@ where (_, Unbounded) => min_node.first_edge(), }; - // Using `range` again would be unsound (#81138) - let back = match (max_found, end) { - (false, Included(key)) => match max_node.search_node(key) { + let back = match (max_found, range.end_bound()) { + (false, Included(key)) => match search::search_node(max_node, key) { SearchResult::Found(kv) => { max_found = true; kv.right_edge() } SearchResult::GoDown(edge) => edge, }, - (false, Excluded(key)) => match max_node.search_node(key) { + (false, Excluded(key)) => match search::search_node(max_node, key) { SearchResult::Found(kv) => { max_found = true; kv.left_edge() diff --git a/library/alloc/src/collections/btree/node.rs b/library/alloc/src/collections/btree/node.rs index 8ab3f58c1adba..bef6850f06f95 100644 --- a/library/alloc/src/collections/btree/node.rs +++ b/library/alloc/src/collections/btree/node.rs @@ -142,17 +142,8 @@ impl NodeRef { } impl NodeRef { - fn new_internal(child: Root) -> Self { - let mut new_node = Box::new(unsafe { InternalNode::new() }); - new_node.edges[0].write(child.node); - NodeRef::from_new_internal(new_node, child.height + 1) - } - fn from_new_internal(internal: Box>, height: usize) -> Self { - let node = NonNull::from(Box::leak(internal)).cast(); - let mut this = NodeRef { height, node, _marker: PhantomData }; - this.borrow_mut().correct_all_childrens_parent_links(); - this + NodeRef { height, node: NonNull::from(Box::leak(internal)).cast(), _marker: PhantomData } } } @@ -176,7 +167,11 @@ impl NodeRef { /// make that new node the root node, and return it. This increases the height by 1 /// and is the opposite of `pop_internal_level`. pub fn push_internal_level(&mut self) -> NodeRef, K, V, marker::Internal> { - super::mem::take_mut(self, |old_root| NodeRef::new_internal(old_root).forget_type()); + let mut new_node = Box::new(unsafe { InternalNode::new() }); + new_node.edges[0].write(self.node); + let mut new_root = NodeRef::from_new_internal(new_node, self.height + 1); + new_root.borrow_mut().first_edge().correct_parent_link(); + *self = new_root.forget_type(); // `self.borrow_mut()`, except that we just forgot we're internal now: NodeRef { height: self.height, node: self.node, _marker: PhantomData } @@ -184,7 +179,7 @@ impl NodeRef { /// Removes the internal root node, using its first child as the new root node. /// As it is intended only to be called when the root node has only one child, - /// no cleanup is done on any of the keys, values and other children. + /// no cleanup is done on any of the other children. /// This decreases the height by 1 and is the opposite of `push_internal_level`. /// /// Requires exclusive access to the `Root` object but not to the root node; @@ -225,7 +220,7 @@ impl NodeRef { /// - When this is `Owned`, the `NodeRef` acts roughly like `Box`, /// but does not have a destructor, and must be cleaned up manually. /// Since any `NodeRef` allows navigating through the tree, `BorrowType` -/// effectively applies to the entire tree, not just to the node itself. +/// effectively applies to the entire tree, not just the node itself. /// - `K` and `V`: These are the types of keys and values stored in the nodes. /// - `Type`: This can be `Leaf`, `Internal`, or `LeafOrInternal`. When this is /// `Leaf`, the `NodeRef` points to a leaf node, when this is `Internal` the @@ -425,7 +420,7 @@ impl<'a, K: 'a, V: 'a, Type> NodeRef, K, V, Type> { impl NodeRef { /// Similar to `ascend`, gets a reference to a node's parent node, but also - /// deallocates the current node in the process. This is unsafe because the + /// deallocate the current node in the process. This is unsafe because the /// current node will still be accessible despite being deallocated. pub unsafe fn deallocate_and_ascend( self, @@ -592,6 +587,17 @@ impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::Leaf> { self.val_area_mut(idx).write(val); } } + + /// Adds a key-value pair to the beginning of the node. + fn push_front(&mut self, key: K, val: V) { + let new_len = self.len() + 1; + assert!(new_len <= CAPACITY); + unsafe { + slice_insert(self.key_area_mut(..new_len), 0, key); + slice_insert(self.val_area_mut(..new_len), 0, val); + *self.len_mut() = new_len as u16; + } + } } impl<'a, K, V> NodeRef, K, V, marker::Internal> { @@ -627,6 +633,92 @@ impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::Internal> { Handle::new_edge(self.reborrow_mut(), idx + 1).correct_parent_link(); } } + + /// Adds a key-value pair, and an edge to go to the left of that pair, + /// to the beginning of the node. + fn push_front(&mut self, key: K, val: V, edge: Root) { + let new_len = self.len() + 1; + assert!(edge.height == self.height - 1); + assert!(new_len <= CAPACITY); + + unsafe { + slice_insert(self.key_area_mut(..new_len), 0, key); + slice_insert(self.val_area_mut(..new_len), 0, val); + slice_insert(self.edge_area_mut(..new_len + 1), 0, edge.node); + *self.len_mut() = new_len as u16; + } + + self.correct_all_childrens_parent_links(); + } +} + +impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::LeafOrInternal> { + /// Removes a key-value pair from the end of the node and returns the pair. + /// Also removes the edge that was to the right of that pair and, if the node + /// is internal, returns the orphaned subtree that this edge owned. + fn pop(&mut self) -> (K, V, Option>) { + debug_assert!(self.len() > 0); + + let idx = self.len() - 1; + + unsafe { + let key = self.key_area_mut(idx).assume_init_read(); + let val = self.val_area_mut(idx).assume_init_read(); + let edge = match self.reborrow_mut().force() { + ForceResult::Leaf(_) => None, + ForceResult::Internal(mut internal) => { + let node = internal.edge_area_mut(idx + 1).assume_init_read(); + let mut edge = Root { node, height: internal.height - 1, _marker: PhantomData }; + // Currently, clearing the parent link is superfluous, because we will + // insert the node elsewhere and set its parent link again. + edge.clear_parent_link(); + Some(edge) + } + }; + + *self.len_mut() -= 1; + (key, val, edge) + } + } + + /// Removes a key-value pair from the beginning of the node and returns the pair. + /// Also removes the edge that was to the left of that pair and, if the node is + /// internal, returns the orphaned subtree that this edge owned. + fn pop_front(&mut self) -> (K, V, Option>) { + debug_assert!(self.len() > 0); + + let old_len = self.len(); + + unsafe { + let key = slice_remove(self.key_area_mut(..old_len), 0); + let val = slice_remove(self.val_area_mut(..old_len), 0); + let edge = match self.reborrow_mut().force() { + ForceResult::Leaf(_) => None, + ForceResult::Internal(mut internal) => { + let node = slice_remove(internal.edge_area_mut(..old_len + 1), 0); + let mut edge = Root { node, height: internal.height - 1, _marker: PhantomData }; + // Currently, clearing the parent link is superfluous, because we will + // insert the node elsewhere and set its parent link again. + edge.clear_parent_link(); + + internal.correct_childrens_parent_links(0..old_len); + + Some(edge) + } + }; + + *self.len_mut() -= 1; + + (key, val, edge) + } + } + + fn into_kv_pointers_mut(mut self) -> (*mut K, *mut V) { + let leaf = self.as_leaf_mut(); + let keys = MaybeUninit::slice_as_mut_ptr(&mut leaf.keys); + let vals = MaybeUninit::slice_as_mut_ptr(&mut leaf.vals); + (keys, vals) + } } impl NodeRef { @@ -1108,7 +1200,9 @@ impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, ); let height = self.node.height; - let right = NodeRef::from_new_internal(new_node, height); + let mut right = NodeRef::from_new_internal(new_node, height); + + right.borrow_mut().correct_childrens_parent_links(0..new_len + 1); SplitResult { left: self.node, kv, right } } @@ -1189,25 +1283,25 @@ impl<'a, K, V> BalancingContext<'a, K, V> { self.right_child } - /// Returns whether merging is possible, i.e., whether there is enough room - /// in a node to combine the central KV with both adjacent child nodes. + /// Returns `true` if it is valid to call `.merge()` in the balancing context, + /// i.e., whether there is enough room in a node to hold the combination of + /// both adjacent child nodes, along with the key-value pair in the parent. pub fn can_merge(&self) -> bool { self.left_child.len() + 1 + self.right_child.len() <= CAPACITY } } impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { - /// Performs a merge and lets a closure decide what to return. - fn do_merge< - F: FnOnce( - NodeRef, K, V, marker::Internal>, - NodeRef, K, V, marker::LeafOrInternal>, - ) -> R, - R, - >( + /// Merges the parent's key-value pair and both adjacent child nodes into + /// the left node and returns an edge handle in that expanded left node. + /// If `track_edge_idx` is given some value, the returned edge corresponds + /// to where the edge in that child node ended up, + /// + /// Panics unless we `.can_merge()`. + pub fn merge( self, - result: F, - ) -> R { + track_edge_idx: Option>, + ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { let Handle { node: mut parent_node, idx: parent_idx, _marker } = self.parent; let old_parent_len = parent_node.len(); let mut left_node = self.left_child; @@ -1217,6 +1311,11 @@ impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { let new_left_len = old_left_len + 1 + right_len; assert!(new_left_len <= CAPACITY); + assert!(match track_edge_idx { + None => true, + Some(LeftOrRight::Left(idx)) => idx <= old_left_len, + Some(LeftOrRight::Right(idx)) => idx <= right_len, + }); unsafe { *left_node.len_mut() = new_left_len as u16; @@ -1255,47 +1354,14 @@ impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { } else { Global.deallocate(right_node.node.cast(), Layout::new::>()); } - } - result(parent_node, left_node) - } - /// Merges the parent's key-value pair and both adjacent child nodes into - /// the left child node and returns the shrunk parent node. - /// - /// Panics unless we `.can_merge()`. - pub fn merge_tracking_parent(self) -> NodeRef, K, V, marker::Internal> { - self.do_merge(|parent, _child| parent) - } - - /// Merges the parent's key-value pair and both adjacent child nodes into - /// the left child node and returns that child node. - /// - /// Panics unless we `.can_merge()`. - pub fn merge_tracking_child(self) -> NodeRef, K, V, marker::LeafOrInternal> { - self.do_merge(|_parent, child| child) - } - - /// Merges the parent's key-value pair and both adjacent child nodes into - /// the left child node and returns the edge handle in that child node - /// where the tracked child edge ended up, - /// - /// Panics unless we `.can_merge()`. - pub fn merge_tracking_child_edge( - self, - track_edge_idx: LeftOrRight, - ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { - let old_left_len = self.left_child.len(); - let right_len = self.right_child.len(); - assert!(match track_edge_idx { - LeftOrRight::Left(idx) => idx <= old_left_len, - LeftOrRight::Right(idx) => idx <= right_len, - }); - let child = self.merge_tracking_child(); - let new_idx = match track_edge_idx { - LeftOrRight::Left(idx) => idx, - LeftOrRight::Right(idx) => old_left_len + 1 + idx, - }; - unsafe { Handle::new_edge(child, new_idx) } + let new_idx = match track_edge_idx { + None => 0, + Some(LeftOrRight::Left(idx)) => idx, + Some(LeftOrRight::Right(idx)) => old_left_len + 1 + idx, + }; + Handle::new_edge(left_node, new_idx) + } } /// Removes a key-value pair from the left child and places it in the key-value storage @@ -1306,8 +1372,18 @@ impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { mut self, track_right_edge_idx: usize, ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { - self.bulk_steal_left(1); - unsafe { Handle::new_edge(self.right_child, 1 + track_right_edge_idx) } + unsafe { + let (k, v, edge) = self.left_child.pop(); + + let (k, v) = self.parent.replace_kv(k, v); + + match self.right_child.reborrow_mut().force() { + ForceResult::Leaf(mut leaf) => leaf.push_front(k, v), + ForceResult::Internal(mut internal) => internal.push_front(k, v, edge.unwrap()), + } + + Handle::new_edge(self.right_child, 1 + track_right_edge_idx) + } } /// Removes a key-value pair from the right child and places it in the key-value storage @@ -1318,8 +1394,18 @@ impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { mut self, track_left_edge_idx: usize, ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { - self.bulk_steal_right(1); - unsafe { Handle::new_edge(self.left_child, track_left_edge_idx) } + unsafe { + let (k, v, edge) = self.right_child.pop_front(); + + let (k, v) = self.parent.replace_kv(k, v); + + match self.left_child.reborrow_mut().force() { + ForceResult::Leaf(mut leaf) => leaf.push(k, v), + ForceResult::Internal(mut internal) => internal.push(k, v, edge.unwrap()), + } + + Handle::new_edge(self.left_child, track_left_edge_idx) + } } /// This does stealing similar to `steal_left` but steals multiple elements at once. @@ -1342,42 +1428,36 @@ impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { // Move leaf data. { + let left_kv = left_node.reborrow_mut().into_kv_pointers_mut(); + let right_kv = right_node.reborrow_mut().into_kv_pointers_mut(); + let parent_kv = { + let kv = self.parent.kv_mut(); + (kv.0 as *mut K, kv.1 as *mut V) + }; + // Make room for stolen elements in the right child. - slice_shr(right_node.key_area_mut(..new_right_len), count); - slice_shr(right_node.val_area_mut(..new_right_len), count); + ptr::copy(right_kv.0, right_kv.0.add(count), old_right_len); + ptr::copy(right_kv.1, right_kv.1.add(count), old_right_len); // Move elements from the left child to the right one. - move_to_slice( - left_node.key_area_mut(new_left_len + 1..old_left_len), - right_node.key_area_mut(..count - 1), - ); - move_to_slice( - left_node.val_area_mut(new_left_len + 1..old_left_len), - right_node.val_area_mut(..count - 1), - ); - - // Move the left-most stolen pair to the parent. - let k = left_node.key_area_mut(new_left_len).assume_init_read(); - let v = left_node.val_area_mut(new_left_len).assume_init_read(); - let (k, v) = self.parent.replace_kv(k, v); + move_kv(left_kv, new_left_len + 1, right_kv, 0, count - 1); // Move parent's key-value pair to the right child. - right_node.key_area_mut(count - 1).write(k); - right_node.val_area_mut(count - 1).write(v); + move_kv(parent_kv, 0, right_kv, count - 1, 1); + + // Move the left-most stolen pair to the parent. + move_kv(left_kv, new_left_len, parent_kv, 0, 1); } match (left_node.reborrow_mut().force(), right_node.reborrow_mut().force()) { - (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => { + (ForceResult::Internal(left), ForceResult::Internal(mut right)) => { // Make room for stolen edges. - slice_shr(right.edge_area_mut(..new_right_len + 1), count); + let right_edges = right.edge_area_mut(..).as_mut_ptr(); + ptr::copy(right_edges, right_edges.add(count), old_right_len + 1); + right.correct_childrens_parent_links(count..new_right_len + 1); // Steal edges. - move_to_slice( - left.edge_area_mut(new_left_len + 1..old_left_len + 1), - right.edge_area_mut(..count), - ); - - right.correct_childrens_parent_links(0..new_right_len + 1); + move_edges(left, new_left_len + 1, right, 0, count); } (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {} _ => unreachable!(), @@ -1405,43 +1485,36 @@ impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { // Move leaf data. { - // Move the right-most stolen pair to the parent. - let k = right_node.key_area_mut(count - 1).assume_init_read(); - let v = right_node.val_area_mut(count - 1).assume_init_read(); - let (k, v) = self.parent.replace_kv(k, v); + let left_kv = left_node.reborrow_mut().into_kv_pointers_mut(); + let right_kv = right_node.reborrow_mut().into_kv_pointers_mut(); + let parent_kv = { + let kv = self.parent.kv_mut(); + (kv.0 as *mut K, kv.1 as *mut V) + }; // Move parent's key-value pair to the left child. - left_node.key_area_mut(old_left_len).write(k); - left_node.val_area_mut(old_left_len).write(v); + move_kv(parent_kv, 0, left_kv, old_left_len, 1); // Move elements from the right child to the left one. - move_to_slice( - right_node.key_area_mut(..count - 1), - left_node.key_area_mut(old_left_len + 1..new_left_len), - ); - move_to_slice( - right_node.val_area_mut(..count - 1), - left_node.val_area_mut(old_left_len + 1..new_left_len), - ); + move_kv(right_kv, 0, left_kv, old_left_len + 1, count - 1); + + // Move the right-most stolen pair to the parent. + move_kv(right_kv, count - 1, parent_kv, 0, 1); // Fill gap where stolen elements used to be. - slice_shl(right_node.key_area_mut(..old_right_len), count); - slice_shl(right_node.val_area_mut(..old_right_len), count); + ptr::copy(right_kv.0.add(count), right_kv.0, new_right_len); + ptr::copy(right_kv.1.add(count), right_kv.1, new_right_len); } match (left_node.reborrow_mut().force(), right_node.reborrow_mut().force()) { - (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => { + (ForceResult::Internal(left), ForceResult::Internal(mut right)) => { // Steal edges. - move_to_slice( - right.edge_area_mut(..count), - left.edge_area_mut(old_left_len + 1..new_left_len + 1), - ); + move_edges(right.reborrow_mut(), 0, left, old_left_len + 1, count); // Fill gap where stolen edges used to be. - slice_shl(right.edge_area_mut(..old_right_len + 1), count); - - left.correct_childrens_parent_links(old_left_len + 1..new_left_len + 1); - right.correct_childrens_parent_links(0..new_right_len + 1); + let right_edges = right.edge_area_mut(..).as_mut_ptr(); + ptr::copy(right_edges.add(count), right_edges, new_right_len + 1); + right.correct_childrens_parent_links(0..=new_right_len); } (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {} _ => unreachable!(), @@ -1450,6 +1523,35 @@ impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { } } +unsafe fn move_kv( + source: (*mut K, *mut V), + source_offset: usize, + dest: (*mut K, *mut V), + dest_offset: usize, + count: usize, +) { + unsafe { + ptr::copy_nonoverlapping(source.0.add(source_offset), dest.0.add(dest_offset), count); + ptr::copy_nonoverlapping(source.1.add(source_offset), dest.1.add(dest_offset), count); + } +} + +// Source and destination must have the same height. +unsafe fn move_edges<'a, K: 'a, V: 'a>( + mut source: NodeRef, K, V, marker::Internal>, + source_offset: usize, + mut dest: NodeRef, K, V, marker::Internal>, + dest_offset: usize, + count: usize, +) { + unsafe { + let source_ptr = source.edge_area_mut(..).as_ptr(); + let dest_ptr = dest.edge_area_mut(dest_offset..).as_mut_ptr(); + ptr::copy_nonoverlapping(source_ptr.add(source_offset), dest_ptr, count); + dest.correct_childrens_parent_links(dest_offset..dest_offset + count); + } +} + impl NodeRef { /// Removes any static information asserting that this node is a `Leaf` node. pub fn forget_type(self) -> NodeRef { @@ -1527,33 +1629,25 @@ impl<'a, K, V> Handle, K, V, marker::LeafOrInternal>, ma unsafe { let new_left_len = self.idx; let mut left_node = self.reborrow_mut().into_node(); - let old_left_len = left_node.len(); - let new_right_len = old_left_len - new_left_len; + let new_right_len = left_node.len() - new_left_len; let mut right_node = right.reborrow_mut(); assert!(right_node.len() == 0); assert!(left_node.height == right_node.height); if new_right_len > 0 { + let left_kv = left_node.reborrow_mut().into_kv_pointers_mut(); + let right_kv = right_node.reborrow_mut().into_kv_pointers_mut(); + + move_kv(left_kv, new_left_len, right_kv, 0, new_right_len); + *left_node.len_mut() = new_left_len as u16; *right_node.len_mut() = new_right_len as u16; - move_to_slice( - left_node.key_area_mut(new_left_len..old_left_len), - right_node.key_area_mut(..new_right_len), - ); - move_to_slice( - left_node.val_area_mut(new_left_len..old_left_len), - right_node.val_area_mut(..new_right_len), - ); match (left_node.force(), right_node.force()) { - (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => { - move_to_slice( - left.edge_area_mut(new_left_len + 1..old_left_len + 1), - right.edge_area_mut(1..new_right_len + 1), - ); - right.correct_childrens_parent_links(1..new_right_len + 1); + (ForceResult::Internal(left), ForceResult::Internal(right)) => { + move_edges(left, new_left_len + 1, right, 1, new_right_len); } (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {} _ => unreachable!(), @@ -1643,28 +1737,6 @@ unsafe fn slice_remove(slice: &mut [MaybeUninit], idx: usize) -> T { } } -/// Shifts the elements in a slice `distance` positions to the left. -/// -/// # Safety -/// The slice has at least `distance` elements. -unsafe fn slice_shl(slice: &mut [MaybeUninit], distance: usize) { - unsafe { - let slice_ptr = slice.as_mut_ptr(); - ptr::copy(slice_ptr.add(distance), slice_ptr, slice.len() - distance); - } -} - -/// Shifts the elements in a slice `distance` positions to the right. -/// -/// # Safety -/// The slice has at least `distance` elements. -unsafe fn slice_shr(slice: &mut [MaybeUninit], distance: usize) { - unsafe { - let slice_ptr = slice.as_mut_ptr(); - ptr::copy(slice_ptr, slice_ptr.add(distance), slice.len() - distance); - } -} - /// Moves all values from a slice of initialized elements to a slice /// of uninitialized elements, leaving behind `src` as all uninitialized. /// Works like `dst.copy_from_slice(src)` but does not require `T` to be `Copy`. diff --git a/library/alloc/src/collections/btree/node/tests.rs b/library/alloc/src/collections/btree/node/tests.rs index 48ce9f2bd89c8..7fe8ff743c040 100644 --- a/library/alloc/src/collections/btree/node/tests.rs +++ b/library/alloc/src/collections/btree/node/tests.rs @@ -79,8 +79,10 @@ fn test_splitpoint() { #[test] fn test_partial_cmp_eq() { let mut root1 = NodeRef::new_leaf(); - root1.borrow_mut().push(1, ()); - let mut root1 = NodeRef::new_internal(root1.forget_type()).forget_type(); + let mut leaf1 = root1.borrow_mut(); + leaf1.push(1, ()); + let mut root1 = root1.forget_type(); + root1.push_internal_level(); let root2 = Root::new(); root1.reborrow().assert_back_pointers(); root2.reborrow().assert_back_pointers(); diff --git a/library/alloc/src/collections/btree/remove.rs b/library/alloc/src/collections/btree/remove.rs index ff842197d1918..7aeb39cbc320f 100644 --- a/library/alloc/src/collections/btree/remove.rs +++ b/library/alloc/src/collections/btree/remove.rs @@ -33,7 +33,7 @@ impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, mark Ok(Left(left_parent_kv)) => { debug_assert!(left_parent_kv.right_child_len() == MIN_LEN - 1); if left_parent_kv.can_merge() { - left_parent_kv.merge_tracking_child_edge(Right(idx)) + left_parent_kv.merge(Some(Right(idx))) } else { debug_assert!(left_parent_kv.left_child_len() > MIN_LEN); left_parent_kv.steal_left(idx) @@ -42,7 +42,7 @@ impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, mark Ok(Right(right_parent_kv)) => { debug_assert!(right_parent_kv.left_child_len() == MIN_LEN - 1); if right_parent_kv.can_merge() { - right_parent_kv.merge_tracking_child_edge(Left(idx)) + right_parent_kv.merge(Some(Left(idx))) } else { debug_assert!(right_parent_kv.right_child_len() > MIN_LEN); right_parent_kv.steal_right(idx) @@ -121,25 +121,27 @@ impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::Internal> { self, ) -> Option, K, V, marker::Internal>> { match self.forget_type().choose_parent_kv() { - Ok(Left(mut left_parent_kv)) => { + Ok(Left(left_parent_kv)) => { debug_assert_eq!(left_parent_kv.right_child_len(), MIN_LEN - 1); if left_parent_kv.can_merge() { - let parent = left_parent_kv.merge_tracking_parent(); - Some(parent) + let pos = left_parent_kv.merge(None); + let parent_edge = unsafe { unwrap_unchecked(pos.into_node().ascend().ok()) }; + Some(parent_edge.into_node()) } else { debug_assert!(left_parent_kv.left_child_len() > MIN_LEN); - left_parent_kv.bulk_steal_left(1); + left_parent_kv.steal_left(0); None } } - Ok(Right(mut right_parent_kv)) => { + Ok(Right(right_parent_kv)) => { debug_assert_eq!(right_parent_kv.left_child_len(), MIN_LEN - 1); if right_parent_kv.can_merge() { - let parent = right_parent_kv.merge_tracking_parent(); - Some(parent) + let pos = right_parent_kv.merge(None); + let parent_edge = unsafe { unwrap_unchecked(pos.into_node().ascend().ok()) }; + Some(parent_edge.into_node()) } else { debug_assert!(right_parent_kv.right_child_len() > MIN_LEN); - right_parent_kv.bulk_steal_right(1); + right_parent_kv.steal_right(0); None } } diff --git a/library/alloc/src/collections/btree/search.rs b/library/alloc/src/collections/btree/search.rs index f62eae3f4d5a2..ed7f95fe632fa 100644 --- a/library/alloc/src/collections/btree/search.rs +++ b/library/alloc/src/collections/btree/search.rs @@ -10,79 +10,80 @@ pub enum SearchResult { GoDown(Handle, marker::Edge>), } -pub enum IndexResult { - KV(usize), - Edge(usize), -} - -impl NodeRef { - /// Looks up a given key in a (sub)tree headed by the node, recursively. - /// Returns a `Found` with the handle of the matching KV, if any. Otherwise, - /// returns a `GoDown` with the handle of the leaf edge where the key belongs. - /// - /// The result is meaningful only if the tree is ordered by key, like the tree - /// in a `BTreeMap` is. - pub fn search_tree( - mut self, - key: &Q, - ) -> SearchResult - where - Q: Ord, - K: Borrow, - { - loop { - self = match self.search_node(key) { - Found(handle) => return Found(handle), - GoDown(handle) => match handle.force() { - Leaf(leaf) => return GoDown(leaf), - Internal(internal) => internal.descend(), - }, - } +/// Looks up a given key in a (sub)tree headed by the given node, recursively. +/// Returns a `Found` with the handle of the matching KV, if any. Otherwise, +/// returns a `GoDown` with the handle of the possible leaf edge where the key +/// belongs. +/// +/// The result is meaningful only if the tree is ordered by key, like the tree +/// in a `BTreeMap` is. +pub fn search_tree( + mut node: NodeRef, + key: &Q, +) -> SearchResult +where + Q: Ord, + K: Borrow, +{ + loop { + match search_node(node, key) { + Found(handle) => return Found(handle), + GoDown(handle) => match handle.force() { + Leaf(leaf) => return GoDown(leaf), + Internal(internal) => { + node = internal.descend(); + continue; + } + }, } } } -impl NodeRef { - /// Looks up a given key in the node, without recursion. - /// Returns a `Found` with the handle of the matching KV, if any. Otherwise, - /// returns a `GoDown` with the handle of the edge where the key might be found - /// (if the node is internal) or where the key can be inserted. - /// - /// The result is meaningful only if the tree is ordered by key, like the tree - /// in a `BTreeMap` is. - pub fn search_node(self, key: &Q) -> SearchResult - where - Q: Ord, - K: Borrow, - { - match self.find_index(key) { - IndexResult::KV(idx) => Found(unsafe { Handle::new_kv(self, idx) }), - IndexResult::Edge(idx) => GoDown(unsafe { Handle::new_edge(self, idx) }), - } +/// Looks up a given key in a given node, without recursion. +/// Returns a `Found` with the handle of the matching KV, if any. Otherwise, +/// returns a `GoDown` with the handle of the edge where the key might be found +/// (if the node is internal) or where the key can be inserted. +/// +/// The result is meaningful only if the tree is ordered by key, like the tree +/// in a `BTreeMap` is. +pub fn search_node( + node: NodeRef, + key: &Q, +) -> SearchResult +where + Q: Ord, + K: Borrow, +{ + match search_linear(&node, key) { + (idx, true) => Found(unsafe { Handle::new_kv(node, idx) }), + (idx, false) => GoDown(unsafe { Handle::new_edge(node, idx) }), } +} - /// Returns either the KV index in the node at which the key (or an equivalent) - /// exists, or the edge index where the key belongs. - /// - /// The result is meaningful only if the tree is ordered by key, like the tree - /// in a `BTreeMap` is. - fn find_index(&self, key: &Q) -> IndexResult - where - Q: Ord, - K: Borrow, - { - // This function is defined over all borrow types (immutable, mutable, owned). - // Using `keys_at()` is fine here even if BorrowType is mutable, as all we return - // is an index -- not a reference. - let len = self.len(); - for i in 0..len { - let k = unsafe { self.reborrow().key_at(i) }; - match key.cmp(k.borrow()) { - Ordering::Greater => {} - Ordering::Equal => return IndexResult::KV(i), - Ordering::Less => return IndexResult::Edge(i), - } +/// Returns either the KV index in the node at which the key (or an equivalent) +/// exists and `true`, or the edge index where the key belongs and `false`. +/// +/// The result is meaningful only if the tree is ordered by key, like the tree +/// in a `BTreeMap` is. +fn search_linear( + node: &NodeRef, + key: &Q, +) -> (usize, bool) +where + Q: Ord, + K: Borrow, +{ + // This function is defined over all borrow types (immutable, mutable, owned). + // Using `keys_at()` is fine here even if BorrowType is mutable, as all we return + // is an index -- not a reference. + let len = node.len(); + for i in 0..len { + let k = unsafe { node.reborrow().key_at(i) }; + match key.cmp(k.borrow()) { + Ordering::Greater => {} + Ordering::Equal => return (i, true), + Ordering::Less => return (i, false), } - IndexResult::Edge(len) } + (len, false) } diff --git a/library/alloc/src/collections/btree/set.rs b/library/alloc/src/collections/btree/set.rs index c2a96dd8ef471..c72e305a1f947 100644 --- a/library/alloc/src/collections/btree/set.rs +++ b/library/alloc/src/collections/btree/set.rs @@ -22,9 +22,6 @@ use super::Recover; /// It is a logic error for an item to be modified in such a way that the item's ordering relative /// to any other item, as determined by the [`Ord`] trait, changes while it is in the set. This is /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code. -/// The behavior resulting from such a logic error is not specified, but will not result in -/// undefined behavior. This could include panics, incorrect results, aborts, memory leaks, and -/// non-termination. /// /// [`Ord`]: core::cmp::Ord /// [`Cell`]: core::cell::Cell diff --git a/library/alloc/src/collections/btree/split.rs b/library/alloc/src/collections/btree/split.rs index 62c5e3a46d74d..4561c8eaf47fb 100644 --- a/library/alloc/src/collections/btree/split.rs +++ b/library/alloc/src/collections/btree/split.rs @@ -1,6 +1,6 @@ use super::map::MIN_LEN; use super::node::{ForceResult::*, Root}; -use super::search::SearchResult::*; +use super::search::{search_node, SearchResult::*}; use core::borrow::Borrow; impl Root { @@ -21,7 +21,7 @@ impl Root { let mut right_node = right_root.borrow_mut(); loop { - let mut split_edge = match left_node.search_node(key) { + let mut split_edge = match search_node(left_node, key) { // key is going to the right tree Found(kv) => kv.left_edge(), GoDown(edge) => edge, @@ -66,7 +66,7 @@ impl Root { let mut last_kv = node.last_kv().consider_for_balancing(); if last_kv.can_merge() { - cur_node = last_kv.merge_tracking_child(); + cur_node = last_kv.merge(None).into_node(); } else { let right_len = last_kv.right_child_len(); // `MIN_LEN + 1` to avoid readjust if merge happens on the next level. @@ -93,7 +93,7 @@ impl Root { let mut first_kv = node.first_kv().consider_for_balancing(); if first_kv.can_merge() { - cur_node = first_kv.merge_tracking_child(); + cur_node = first_kv.merge(None).into_node(); } else { let left_len = first_kv.left_child_len(); // `MIN_LEN + 1` to avoid readjust if merge happens on the next level. diff --git a/library/alloc/src/collections/vec_deque/mod.rs b/library/alloc/src/collections/vec_deque/mod.rs index 5b61e8911a59a..f8fad6de1a3cc 100644 --- a/library/alloc/src/collections/vec_deque/mod.rs +++ b/library/alloc/src/collections/vec_deque/mod.rs @@ -1292,7 +1292,7 @@ impl VecDeque { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn front(&self) -> Option<&T> { - self.get(0) + if !self.is_empty() { Some(&self[0]) } else { None } } /// Provides a mutable reference to the front element, or `None` if the @@ -1316,7 +1316,7 @@ impl VecDeque { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn front_mut(&mut self) -> Option<&mut T> { - self.get_mut(0) + if !self.is_empty() { Some(&mut self[0]) } else { None } } /// Provides a reference to the back element, or `None` if the `VecDeque` is @@ -1336,7 +1336,7 @@ impl VecDeque { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn back(&self) -> Option<&T> { - self.get(self.len().wrapping_sub(1)) + if !self.is_empty() { Some(&self[self.len() - 1]) } else { None } } /// Provides a mutable reference to the back element, or `None` if the @@ -1360,7 +1360,8 @@ impl VecDeque { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn back_mut(&mut self) -> Option<&mut T> { - self.get_mut(self.len().wrapping_sub(1)) + let len = self.len(); + if !self.is_empty() { Some(&mut self[len - 1]) } else { None } } /// Removes the first element and returns it, or `None` if the `VecDeque` is diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs index 8d721ed7487ae..cfad111aa546f 100644 --- a/library/alloc/src/lib.rs +++ b/library/alloc/src/lib.rs @@ -120,7 +120,6 @@ #![feature(receiver_trait)] #![cfg_attr(bootstrap, feature(min_const_generics))] #![feature(min_specialization)] -#![feature(set_ptr_value)] #![feature(slice_ptr_get)] #![feature(slice_ptr_len)] #![feature(staged_api)] @@ -140,7 +139,6 @@ #![feature(type_alias_impl_trait)] #![feature(associated_type_bounds)] #![feature(slice_group_by)] -#![feature(decl_macro)] // Allow testing this library #[cfg(test)] @@ -185,15 +183,13 @@ pub mod task; mod tests; pub mod vec; +#[cfg(not(test))] +mod std { + pub use core::ops; // RangeFull +} + #[doc(hidden)] #[unstable(feature = "liballoc_internals", issue = "none", reason = "implementation detail")] pub mod __export { pub use core::format_args; - - /// Force AST node to an expression to improve diagnostics in pattern position. - #[rustc_macro_transparency = "semitransparent"] - #[unstable(feature = "liballoc_internals", issue = "none", reason = "implementation detail")] - pub macro force_expr($e:expr) { - $e - } } diff --git a/library/alloc/src/macros.rs b/library/alloc/src/macros.rs index 3a46763c3f608..7d4eff6185dbe 100644 --- a/library/alloc/src/macros.rs +++ b/library/alloc/src/macros.rs @@ -37,16 +37,16 @@ #[cfg(not(test))] #[macro_export] #[stable(feature = "rust1", since = "1.0.0")] -#[allow_internal_unstable(box_syntax, liballoc_internals)] +#[allow_internal_unstable(box_syntax)] macro_rules! vec { () => ( - $crate::__export::force_expr!($crate::vec::Vec::new()) + $crate::vec::Vec::new() ); ($elem:expr; $n:expr) => ( - $crate::__export::force_expr!($crate::vec::from_elem($elem, $n)) + $crate::vec::from_elem($elem, $n) ); ($($x:expr),+ $(,)?) => ( - $crate::__export::force_expr!(<[_]>::into_vec(box [$($x),+])) + <[_]>::into_vec(box [$($x),+]) ); } diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index ee03f15eece3f..8183a582d337a 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -263,9 +263,7 @@ use core::pin::Pin; use core::ptr::{self, NonNull}; use core::slice::from_raw_parts_mut; -use crate::alloc::{ - box_free, handle_alloc_error, AllocError, Allocator, Global, Layout, WriteCloneIntoRaw, -}; +use crate::alloc::{box_free, handle_alloc_error, AllocError, Allocator, Global, Layout}; use crate::borrow::{Cow, ToOwned}; use crate::string::String; use crate::vec::Vec; @@ -353,26 +351,6 @@ impl Rc { /// to upgrade the weak reference before this function returns will result /// in a `None` value. However, the weak reference may be cloned freely and /// stored for use at a later time. - /// - /// # Examples - /// - /// ``` - /// #![feature(arc_new_cyclic)] - /// #![allow(dead_code)] - /// use std::rc::{Rc, Weak}; - /// - /// struct Gadget { - /// self_weak: Weak, - /// // ... more fields - /// } - /// impl Gadget { - /// pub fn new() -> Rc { - /// Rc::new_cyclic(|self_weak| { - /// Gadget { self_weak: self_weak.clone(), /* ... */ } - /// }) - /// } - /// } - /// ``` #[unstable(feature = "arc_new_cyclic", issue = "75861")] pub fn new_cyclic(data_fn: impl FnOnce(&Weak) -> T) -> Rc { // Construct the inner in the "uninitialized" state with a single @@ -849,8 +827,8 @@ impl Rc { let offset = unsafe { data_offset(ptr) }; // Reverse the offset to find the original RcBox. - let rc_ptr = - unsafe { (ptr as *mut RcBox).set_ptr_value((ptr as *mut u8).offset(-offset)) }; + let fake_ptr = ptr as *mut RcBox; + let rc_ptr = unsafe { set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset)) }; unsafe { Self::from_ptr(rc_ptr) } } @@ -870,7 +848,7 @@ impl Rc { pub fn downgrade(this: &Self) -> Weak { this.inner().inc_weak(); // Make sure we do not create a dangling Weak - debug_assert!(!is_dangling(this.ptr.as_ptr())); + debug_assert!(!is_dangling(this.ptr)); Weak { ptr: this.ptr } } @@ -1059,26 +1037,18 @@ impl Rc { #[stable(feature = "rc_unique", since = "1.4.0")] pub fn make_mut(this: &mut Self) -> &mut T { if Rc::strong_count(this) != 1 { - // Gotta clone the data, there are other Rcs. - // Pre-allocate memory to allow writing the cloned value directly. - let mut rc = Self::new_uninit(); - unsafe { - let data = Rc::get_mut_unchecked(&mut rc); - (**this).write_clone_into_raw(data.as_mut_ptr()); - *this = rc.assume_init(); - } + // Gotta clone the data, there are other Rcs + *this = Rc::new((**this).clone()) } else if Rc::weak_count(this) != 0 { // Can just steal the data, all that's left is Weaks - let mut rc = Self::new_uninit(); unsafe { - let data = Rc::get_mut_unchecked(&mut rc); - data.as_mut_ptr().copy_from_nonoverlapping(&**this, 1); - - this.inner().dec_strong(); + let mut swap = Rc::new(ptr::read(&this.ptr.as_ref().value)); + mem::swap(this, &mut swap); + swap.inner().dec_strong(); // Remove implicit strong-weak ref (no need to craft a fake // Weak here -- we know other Weaks can clean up for us) - this.inner().dec_weak(); - ptr::write(this, rc.assume_init()); + swap.inner().dec_weak(); + forget(swap); } } // This unsafety is ok because we're guaranteed that the pointer @@ -1184,7 +1154,7 @@ impl Rc { Self::allocate_for_layout( Layout::for_value(&*ptr), |layout| Global.allocate(layout), - |mem| (ptr as *mut RcBox).set_ptr_value(mem), + |mem| set_data_ptr(ptr as *mut T, mem) as *mut RcBox, ) } } @@ -1223,7 +1193,20 @@ impl Rc<[T]> { ) } } +} + +/// Sets the data pointer of a `?Sized` raw pointer. +/// +/// For a slice/trait object, this sets the `data` field and leaves the rest +/// unchanged. For a sized raw pointer, this simply sets the pointer. +unsafe fn set_data_ptr(mut ptr: *mut T, data: *mut U) -> *mut T { + unsafe { + ptr::write(&mut ptr as *mut _ as *mut *mut u8, data as *mut u8); + } + ptr +} +impl Rc<[T]> { /// Copy elements from slice into newly allocated Rc<\[T\]> /// /// Unsafe because the caller must either take ownership or bind `T: Copy` @@ -1867,8 +1850,8 @@ impl Weak { } } -pub(crate) fn is_dangling(ptr: *mut T) -> bool { - let address = ptr as *mut () as usize; +pub(crate) fn is_dangling(ptr: NonNull) -> bool { + let address = ptr.as_ptr() as *mut () as usize; address == usize::MAX } @@ -1879,7 +1862,7 @@ struct WeakInner<'a> { strong: &'a Cell, } -impl Weak { +impl Weak { /// Returns a raw pointer to the object `T` pointed to by this `Weak`. /// /// The pointer is valid only if there are some strong references. The pointer may be dangling, @@ -1909,15 +1892,15 @@ impl Weak { pub fn as_ptr(&self) -> *const T { let ptr: *mut RcBox = NonNull::as_ptr(self.ptr); - if is_dangling(ptr) { - // If the pointer is dangling, we return the sentinel directly. This cannot be - // a valid payload address, as the payload is at least as aligned as RcBox (usize). - ptr as *const T - } else { - // SAFETY: if is_dangling returns false, then the pointer is dereferencable. - // The payload may be dropped at this point, and we have to maintain provenance, - // so use raw pointer manipulation. - unsafe { &raw const (*ptr).value } + // SAFETY: we must offset the pointer manually, and said pointer may be + // a dangling weak (usize::MAX) if T is sized. data_offset is safe to call, + // because we know that a pointer to unsized T was derived from a real + // unsized T, as dangling weaks are only created for sized T. wrapping_offset + // is used so that we can use the same code path for the non-dangling + // unsized case and the potentially dangling sized case. + unsafe { + let offset = data_offset(ptr as *mut T); + set_data_ptr(ptr as *mut T, (ptr as *mut u8).wrapping_offset(offset)) } } @@ -1999,24 +1982,22 @@ impl Weak { /// [`new`]: Weak::new #[stable(feature = "weak_into_raw", since = "1.45.0")] pub unsafe fn from_raw(ptr: *const T) -> Self { + // SAFETY: data_offset is safe to call, because this pointer originates from a Weak. // See Weak::as_ptr for context on how the input pointer is derived. + let offset = unsafe { data_offset(ptr) }; - let ptr = if is_dangling(ptr as *mut T) { - // This is a dangling Weak. - ptr as *mut RcBox - } else { - // Otherwise, we're guaranteed the pointer came from a nondangling Weak. - // SAFETY: data_offset is safe to call, as ptr references a real (potentially dropped) T. - let offset = unsafe { data_offset(ptr) }; - // Thus, we reverse the offset to get the whole RcBox. - // SAFETY: the pointer originated from a Weak, so this offset is safe. - unsafe { (ptr as *mut RcBox).set_ptr_value((ptr as *mut u8).offset(-offset)) } + // Reverse the offset to find the original RcBox. + // SAFETY: we use wrapping_offset here because the pointer may be dangling (but only if T: Sized). + let ptr = unsafe { + set_data_ptr(ptr as *mut RcBox, (ptr as *mut u8).wrapping_offset(-offset)) }; // SAFETY: we now have recovered the original Weak pointer, so can create the Weak. Weak { ptr: unsafe { NonNull::new_unchecked(ptr) } } } +} +impl Weak { /// Attempts to upgrade the `Weak` pointer to an [`Rc`], delaying /// dropping of the inner value if successful. /// @@ -2079,7 +2060,7 @@ impl Weak { /// (i.e., when this `Weak` was created by `Weak::new`). #[inline] fn inner(&self) -> Option> { - if is_dangling(self.ptr.as_ptr()) { + if is_dangling(self.ptr) { None } else { // We are careful to *not* create a reference covering the "data" field, as @@ -2334,19 +2315,21 @@ impl AsRef for Rc { #[stable(feature = "pin", since = "1.33.0")] impl Unpin for Rc {} -/// Get the offset within an `RcBox` for the payload behind a pointer. +/// Get the offset within an `RcBox` for +/// a payload of type described by a pointer. /// /// # Safety /// -/// The pointer must point to (and have valid metadata for) a previously -/// valid instance of T, but the T is allowed to be dropped. +/// This has the same safety requirements as `align_of_val_raw`. In effect: +/// +/// - This function is safe for any argument if `T` is sized, and +/// - if `T` is unsized, the pointer must have appropriate pointer metadata +/// acquired from the real instance that you are getting this offset for. unsafe fn data_offset(ptr: *const T) -> isize { - // Align the unsized value to the end of the RcBox. - // Because RcBox is repr(C), it will always be the last field in memory. - // SAFETY: since the only unsized types possible are slices, trait objects, - // and extern types, the input safety requirement is currently enough to - // satisfy the requirements of align_of_val_raw; this is an implementation - // detail of the language that may not be relied upon outside of std. + // Align the unsized value to the end of the `RcBox`. + // Because it is ?Sized, it will always be the last field in memory. + // Note: This is a detail of the current implementation of the compiler, + // and is not a guaranteed language detail. Do not rely on it outside of std. unsafe { data_offset_align(align_of_val_raw(ptr)) } } diff --git a/library/alloc/src/rc/tests.rs b/library/alloc/src/rc/tests.rs index 843a9b07fa934..2d183a8c88c64 100644 --- a/library/alloc/src/rc/tests.rs +++ b/library/alloc/src/rc/tests.rs @@ -208,30 +208,6 @@ fn into_from_weak_raw() { } } -#[test] -fn test_into_from_weak_raw_unsized() { - use std::fmt::Display; - use std::string::ToString; - - let arc: Rc = Rc::from("foo"); - let weak: Weak = Rc::downgrade(&arc); - - let ptr = Weak::into_raw(weak.clone()); - let weak2 = unsafe { Weak::from_raw(ptr) }; - - assert_eq!(unsafe { &*ptr }, "foo"); - assert!(weak.ptr_eq(&weak2)); - - let arc: Rc = Rc::new(123); - let weak: Weak = Rc::downgrade(&arc); - - let ptr = Weak::into_raw(weak.clone()); - let weak2 = unsafe { Weak::from_raw(ptr) }; - - assert_eq!(unsafe { &*ptr }.to_string(), "123"); - assert!(weak.ptr_eq(&weak2)); -} - #[test] fn get_mut() { let mut x = Rc::new(3); @@ -318,23 +294,6 @@ fn test_unsized() { assert_eq!(foo, foo.clone()); } -#[test] -fn test_maybe_thin_unsized() { - // If/when custom thin DSTs exist, this test should be updated to use one - use std::ffi::{CStr, CString}; - - let x: Rc = Rc::from(CString::new("swordfish").unwrap().into_boxed_c_str()); - assert_eq!(format!("{:?}", x), "\"swordfish\""); - let y: Weak = Rc::downgrade(&x); - drop(x); - - // At this point, the weak points to a dropped DST - assert!(y.upgrade().is_none()); - // But we still need to be able to get the alloc layout to drop. - // CStr has no drop glue, but custom DSTs might, and need to work. - drop(y); -} - #[test] fn test_from_owned() { let foo = 123; diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index 6f2a497598dd7..9198892859317 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -1553,25 +1553,18 @@ impl String { // Replace_range does not have the memory safety issues of a vector Splice. // of the vector version. The data is just plain bytes. - // WARNING: Inlining this variable would be unsound (#81138) - let start = range.start_bound(); - match start { + match range.start_bound() { Included(&n) => assert!(self.is_char_boundary(n)), Excluded(&n) => assert!(self.is_char_boundary(n + 1)), Unbounded => {} }; - // WARNING: Inlining this variable would be unsound (#81138) - let end = range.end_bound(); - match end { + match range.end_bound() { Included(&n) => assert!(self.is_char_boundary(n + 1)), Excluded(&n) => assert!(self.is_char_boundary(n)), Unbounded => {} }; - // Using `range` again would be unsound (#81138) - // We assume the bounds reported by `range` remain the same, but - // an adversarial implementation could change between calls - unsafe { self.as_mut_vec() }.splice((start, end), replace_with.bytes()); + unsafe { self.as_mut_vec() }.splice(range, replace_with.bytes()); } /// Converts this `String` into a [`Box`]`<`[`str`]`>`. diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index c0d684fbb4573..06ad621727166 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -22,9 +22,7 @@ use core::slice::from_raw_parts_mut; use core::sync::atomic; use core::sync::atomic::Ordering::{Acquire, Relaxed, Release, SeqCst}; -use crate::alloc::{ - box_free, handle_alloc_error, AllocError, Allocator, Global, Layout, WriteCloneIntoRaw, -}; +use crate::alloc::{box_free, handle_alloc_error, AllocError, Allocator, Global, Layout}; use crate::borrow::{Cow, ToOwned}; use crate::boxed::Box; use crate::rc::is_dangling; @@ -846,7 +844,8 @@ impl Arc { let offset = data_offset(ptr); // Reverse the offset to find the original ArcInner. - let arc_ptr = (ptr as *mut ArcInner).set_ptr_value((ptr as *mut u8).offset(-offset)); + let fake_ptr = ptr as *mut ArcInner; + let arc_ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset)); Self::from_ptr(arc_ptr) } @@ -887,7 +886,7 @@ impl Arc { match this.inner().weak.compare_exchange_weak(cur, cur + 1, Acquire, Relaxed) { Ok(_) => { // Make sure we do not create a dangling Weak - debug_assert!(!is_dangling(this.ptr.as_ptr())); + debug_assert!(!is_dangling(this.ptr)); return Weak { ptr: this.ptr }; } Err(old) => cur = old, @@ -1130,7 +1129,7 @@ impl Arc { Self::allocate_for_layout( Layout::for_value(&*ptr), |layout| Global.allocate(layout), - |mem| (ptr as *mut ArcInner).set_ptr_value(mem) as *mut ArcInner, + |mem| set_data_ptr(ptr as *mut T, mem) as *mut ArcInner, ) } } @@ -1169,7 +1168,20 @@ impl Arc<[T]> { ) } } +} + +/// Sets the data pointer of a `?Sized` raw pointer. +/// +/// For a slice/trait object, this sets the `data` field and leaves the rest +/// unchanged. For a sized raw pointer, this simply sets the pointer. +unsafe fn set_data_ptr(mut ptr: *mut T, data: *mut U) -> *mut T { + unsafe { + ptr::write(&mut ptr as *mut _ as *mut *mut u8, data as *mut u8); + } + ptr +} +impl Arc<[T]> { /// Copy elements from slice into newly allocated Arc<\[T\]> /// /// Unsafe because the caller must either take ownership or bind `T: Copy`. @@ -1357,14 +1369,8 @@ impl Arc { // weak count, there's no chance the ArcInner itself could be // deallocated. if this.inner().strong.compare_exchange(1, 0, Acquire, Relaxed).is_err() { - // Another strong pointer exists, so we must clone. - // Pre-allocate memory to allow writing the cloned value directly. - let mut arc = Self::new_uninit(); - unsafe { - let data = Arc::get_mut_unchecked(&mut arc); - (**this).write_clone_into_raw(data.as_mut_ptr()); - *this = arc.assume_init(); - } + // Another strong pointer exists; clone + *this = Arc::new((**this).clone()); } else if this.inner().weak.load(Relaxed) != 1 { // Relaxed suffices in the above because this is fundamentally an // optimization: we are always racing with weak pointers being @@ -1380,14 +1386,17 @@ impl Arc { // Materialize our own implicit weak pointer, so that it can clean // up the ArcInner as needed. - let _weak = Weak { ptr: this.ptr }; + let weak = Weak { ptr: this.ptr }; - // Can just steal the data, all that's left is Weaks - let mut arc = Self::new_uninit(); + // mark the data itself as already deallocated unsafe { - let data = Arc::get_mut_unchecked(&mut arc); - data.as_mut_ptr().copy_from_nonoverlapping(&**this, 1); - ptr::write(this, arc.assume_init()); + // there is no data race in the implicit write caused by `read` + // here (due to zeroing) because data is no longer accessed by + // other threads (due to there being no more strong refs at this + // point). + let mut swap = Arc::new(ptr::read(&weak.ptr.as_ref().data)); + mem::swap(this, &mut swap); + mem::forget(swap); } } else { // We were the sole reference of either kind; bump back up the @@ -1639,7 +1648,7 @@ struct WeakInner<'a> { strong: &'a atomic::AtomicUsize, } -impl Weak { +impl Weak { /// Returns a raw pointer to the object `T` pointed to by this `Weak`. /// /// The pointer is valid only if there are some strong references. The pointer may be dangling, @@ -1669,15 +1678,15 @@ impl Weak { pub fn as_ptr(&self) -> *const T { let ptr: *mut ArcInner = NonNull::as_ptr(self.ptr); - if is_dangling(ptr) { - // If the pointer is dangling, we return the sentinel directly. This cannot be - // a valid payload address, as the payload is at least as aligned as ArcInner (usize). - ptr as *const T - } else { - // SAFETY: if is_dangling returns false, then the pointer is dereferencable. - // The payload may be dropped at this point, and we have to maintain provenance, - // so use raw pointer manipulation. - unsafe { &raw mut (*ptr).data } + // SAFETY: we must offset the pointer manually, and said pointer may be + // a dangling weak (usize::MAX) if T is sized. data_offset is safe to call, + // because we know that a pointer to unsized T was derived from a real + // unsized T, as dangling weaks are only created for sized T. wrapping_offset + // is used so that we can use the same code path for the non-dangling + // unsized case and the potentially dangling sized case. + unsafe { + let offset = data_offset(ptr as *mut T); + set_data_ptr(ptr as *mut T, (ptr as *mut u8).wrapping_offset(offset)) } } @@ -1759,22 +1768,18 @@ impl Weak { /// [`forget`]: std::mem::forget #[stable(feature = "weak_into_raw", since = "1.45.0")] pub unsafe fn from_raw(ptr: *const T) -> Self { + // SAFETY: data_offset is safe to call, because this pointer originates from a Weak. // See Weak::as_ptr for context on how the input pointer is derived. + let offset = unsafe { data_offset(ptr) }; - let ptr = if is_dangling(ptr as *mut T) { - // This is a dangling Weak. - ptr as *mut ArcInner - } else { - // Otherwise, we're guaranteed the pointer came from a nondangling Weak. - // SAFETY: data_offset is safe to call, as ptr references a real (potentially dropped) T. - let offset = unsafe { data_offset(ptr) }; - // Thus, we reverse the offset to get the whole RcBox. - // SAFETY: the pointer originated from a Weak, so this offset is safe. - unsafe { (ptr as *mut ArcInner).set_ptr_value((ptr as *mut u8).offset(-offset)) } + // Reverse the offset to find the original ArcInner. + // SAFETY: we use wrapping_offset here because the pointer may be dangling (but only if T: Sized) + let ptr = unsafe { + set_data_ptr(ptr as *mut ArcInner, (ptr as *mut u8).wrapping_offset(-offset)) }; // SAFETY: we now have recovered the original Weak pointer, so can create the Weak. - Weak { ptr: unsafe { NonNull::new_unchecked(ptr) } } + unsafe { Weak { ptr: NonNull::new_unchecked(ptr) } } } } @@ -1879,7 +1884,7 @@ impl Weak { /// (i.e., when this `Weak` was created by `Weak::new`). #[inline] fn inner(&self) -> Option> { - if is_dangling(self.ptr.as_ptr()) { + if is_dangling(self.ptr) { None } else { // We are careful to *not* create a reference covering the "data" field, as @@ -2459,19 +2464,21 @@ impl AsRef for Arc { #[stable(feature = "pin", since = "1.33.0")] impl Unpin for Arc {} -/// Get the offset within an `ArcInner` for the payload behind a pointer. +/// Get the offset within an `ArcInner` for +/// a payload of type described by a pointer. /// /// # Safety /// -/// The pointer must point to (and have valid metadata for) a previously -/// valid instance of T, but the T is allowed to be dropped. +/// This has the same safety requirements as `align_of_val_raw`. In effect: +/// +/// - This function is safe for any argument if `T` is sized, and +/// - if `T` is unsized, the pointer must have appropriate pointer metadata +/// acquired from the real instance that you are getting this offset for. unsafe fn data_offset(ptr: *const T) -> isize { - // Align the unsized value to the end of the ArcInner. - // Because RcBox is repr(C), it will always be the last field in memory. - // SAFETY: since the only unsized types possible are slices, trait objects, - // and extern types, the input safety requirement is currently enough to - // satisfy the requirements of align_of_val_raw; this is an implementation - // detail of the language that may not be relied upon outside of std. + // Align the unsized value to the end of the `ArcInner`. + // Because it is `?Sized`, it will always be the last field in memory. + // Note: This is a detail of the current implementation of the compiler, + // and is not a guaranteed language detail. Do not rely on it outside of std. unsafe { data_offset_align(align_of_val_raw(ptr)) } } diff --git a/library/alloc/src/sync/tests.rs b/library/alloc/src/sync/tests.rs index 4ccb32fbbf63d..e8e1e66da5ed4 100644 --- a/library/alloc/src/sync/tests.rs +++ b/library/alloc/src/sync/tests.rs @@ -158,30 +158,6 @@ fn into_from_weak_raw() { } } -#[test] -fn test_into_from_weak_raw_unsized() { - use std::fmt::Display; - use std::string::ToString; - - let arc: Arc = Arc::from("foo"); - let weak: Weak = Arc::downgrade(&arc); - - let ptr = Weak::into_raw(weak.clone()); - let weak2 = unsafe { Weak::from_raw(ptr) }; - - assert_eq!(unsafe { &*ptr }, "foo"); - assert!(weak.ptr_eq(&weak2)); - - let arc: Arc = Arc::new(123); - let weak: Weak = Arc::downgrade(&arc); - - let ptr = Weak::into_raw(weak.clone()); - let weak2 = unsafe { Weak::from_raw(ptr) }; - - assert_eq!(unsafe { &*ptr }.to_string(), "123"); - assert!(weak.ptr_eq(&weak2)); -} - #[test] fn test_cowarc_clone_make_mut() { let mut cow0 = Arc::new(75); @@ -353,23 +329,6 @@ fn test_unsized() { assert!(y.upgrade().is_none()); } -#[test] -fn test_maybe_thin_unsized() { - // If/when custom thin DSTs exist, this test should be updated to use one - use std::ffi::{CStr, CString}; - - let x: Arc = Arc::from(CString::new("swordfish").unwrap().into_boxed_c_str()); - assert_eq!(format!("{:?}", x), "\"swordfish\""); - let y: Weak = Arc::downgrade(&x); - drop(x); - - // At this point, the weak points to a dropped DST - assert!(y.upgrade().is_none()); - // But we still need to be able to get the alloc layout to drop. - // CStr has no drop glue, but custom DSTs might, and need to work. - drop(y); -} - #[test] fn test_from_owned() { let foo = 123; @@ -411,7 +370,7 @@ fn test_weak_count_locked() { let n = Arc::weak_count(&a2); assert!(n < 2, "bad weak count: {}", n); #[cfg(miri)] // Miri's scheduler does not guarantee liveness, and thus needs this hint. - std::hint::spin_loop(); + atomic::spin_loop_hint(); } t.join().unwrap(); } diff --git a/library/alloc/src/task.rs b/library/alloc/src/task.rs index 69690494196bf..fcab3fd0badce 100644 --- a/library/alloc/src/task.rs +++ b/library/alloc/src/task.rs @@ -33,8 +33,7 @@ pub trait Wake { } } -#[cfg_attr(bootstrap, allow(rustc::ineffective_unstable_trait_impl))] -#[cfg_attr(not(bootstrap), allow(ineffective_unstable_trait_impl))] +#[allow(rustc::ineffective_unstable_trait_impl)] #[unstable(feature = "wake_trait", issue = "69912")] impl From> for Waker { fn from(waker: Arc) -> Waker { @@ -44,8 +43,7 @@ impl From> for Waker { } } -#[cfg_attr(bootstrap, allow(rustc::ineffective_unstable_trait_impl))] -#[cfg_attr(not(bootstrap), allow(ineffective_unstable_trait_impl))] +#[allow(rustc::ineffective_unstable_trait_impl)] #[unstable(feature = "wake_trait", issue = "69912")] impl From> for RawWaker { fn from(waker: Arc) -> RawWaker { diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index ccc4f03a1e505..1ca194c336112 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -1953,6 +1953,27 @@ impl Vec { } } +impl Vec { + /// Removes the first instance of `item` from the vector if the item exists. + /// + /// This method will be removed soon. + #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")] + #[rustc_deprecated( + reason = "Removing the first item equal to a needle is already easily possible \ + with iterators and the current Vec methods. Furthermore, having a method for \ + one particular case of removal (linear search, only the first item, no swap remove) \ + but not for others is inconsistent. This method will be removed soon.", + since = "1.46.0" + )] + pub fn remove_item(&mut self, item: &V) -> Option + where + T: PartialEq, + { + let pos = self.iter().position(|x| *x == *item)?; + Some(self.remove(pos)) + } +} + //////////////////////////////////////////////////////////////////////////////// // Internal methods and functions //////////////////////////////////////////////////////////////////////////////// diff --git a/library/alloc/tests/lib.rs b/library/alloc/tests/lib.rs index 0b7eeab4e9679..cd4174ed4007a 100644 --- a/library/alloc/tests/lib.rs +++ b/library/alloc/tests/lib.rs @@ -14,6 +14,7 @@ #![feature(binary_heap_into_iter_sorted)] #![feature(binary_heap_drain_sorted)] #![feature(slice_ptr_get)] +#![feature(split_inclusive)] #![feature(binary_heap_retain)] #![feature(inplace_iteration)] #![feature(iter_map_while)] diff --git a/library/alloc/tests/string.rs b/library/alloc/tests/string.rs index f3d74e0514d29..b28694186b65e 100644 --- a/library/alloc/tests/string.rs +++ b/library/alloc/tests/string.rs @@ -1,11 +1,7 @@ use std::borrow::Cow; -use std::cell::Cell; use std::collections::TryReserveError::*; -use std::ops::Bound; use std::ops::Bound::*; -use std::ops::RangeBounds; use std::panic; -use std::str; pub trait IntoCow<'a, B: ?Sized> where @@ -565,52 +561,6 @@ fn test_replace_range_unbounded() { assert_eq!(s, ""); } -#[test] -fn test_replace_range_evil_start_bound() { - struct EvilRange(Cell); - - impl RangeBounds for EvilRange { - fn start_bound(&self) -> Bound<&usize> { - Bound::Included(if self.0.get() { - &1 - } else { - self.0.set(true); - &0 - }) - } - fn end_bound(&self) -> Bound<&usize> { - Bound::Unbounded - } - } - - let mut s = String::from("🦀"); - s.replace_range(EvilRange(Cell::new(false)), ""); - assert_eq!(Ok(""), str::from_utf8(s.as_bytes())); -} - -#[test] -fn test_replace_range_evil_end_bound() { - struct EvilRange(Cell); - - impl RangeBounds for EvilRange { - fn start_bound(&self) -> Bound<&usize> { - Bound::Included(&0) - } - fn end_bound(&self) -> Bound<&usize> { - Bound::Excluded(if self.0.get() { - &3 - } else { - self.0.set(true); - &4 - }) - } - } - - let mut s = String::from("🦀"); - s.replace_range(EvilRange(Cell::new(false)), ""); - assert_eq!(Ok(""), str::from_utf8(s.as_bytes())); -} - #[test] fn test_extend_ref() { let mut a = "foo".to_string(); diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs index fa0fbaa35c95c..c5ab7a39ff0ca 100644 --- a/library/core/src/cell.rs +++ b/library/core/src/cell.rs @@ -1261,40 +1261,6 @@ impl<'b, T: ?Sized> Ref<'b, T> { Ref { value: f(orig.value), borrow: orig.borrow } } - /// Makes a new `Ref` for an optional component of the borrowed data. The - /// original guard is returned as an `Err(..)` if the closure returns - /// `None`. - /// - /// The `RefCell` is already immutably borrowed, so this cannot fail. - /// - /// This is an associated function that needs to be used as - /// `Ref::filter_map(...)`. A method would interfere with methods of the same - /// name on the contents of a `RefCell` used through `Deref`. - /// - /// # Examples - /// - /// ``` - /// #![feature(cell_filter_map)] - /// - /// use std::cell::{RefCell, Ref}; - /// - /// let c = RefCell::new(vec![1, 2, 3]); - /// let b1: Ref> = c.borrow(); - /// let b2: Result, _> = Ref::filter_map(b1, |v| v.get(1)); - /// assert_eq!(*b2.unwrap(), 2); - /// ``` - #[unstable(feature = "cell_filter_map", reason = "recently added", issue = "81061")] - #[inline] - pub fn filter_map(orig: Ref<'b, T>, f: F) -> Result, Self> - where - F: FnOnce(&T) -> Option<&U>, - { - match f(orig.value) { - Some(value) => Ok(Ref { value, borrow: orig.borrow }), - None => Err(orig), - } - } - /// Splits a `Ref` into multiple `Ref`s for different components of the /// borrowed data. /// @@ -1406,58 +1372,6 @@ impl<'b, T: ?Sized> RefMut<'b, T> { RefMut { value: f(value), borrow } } - /// Makes a new `RefMut` for an optional component of the borrowed data. The - /// original guard is returned as an `Err(..)` if the closure returns - /// `None`. - /// - /// The `RefCell` is already mutably borrowed, so this cannot fail. - /// - /// This is an associated function that needs to be used as - /// `RefMut::filter_map(...)`. A method would interfere with methods of the - /// same name on the contents of a `RefCell` used through `Deref`. - /// - /// # Examples - /// - /// ``` - /// #![feature(cell_filter_map)] - /// - /// use std::cell::{RefCell, RefMut}; - /// - /// let c = RefCell::new(vec![1, 2, 3]); - /// - /// { - /// let b1: RefMut> = c.borrow_mut(); - /// let mut b2: Result, _> = RefMut::filter_map(b1, |v| v.get_mut(1)); - /// - /// if let Ok(mut b2) = b2 { - /// *b2 += 2; - /// } - /// } - /// - /// assert_eq!(*c.borrow(), vec![1, 4, 3]); - /// ``` - #[unstable(feature = "cell_filter_map", reason = "recently added", issue = "81061")] - #[inline] - pub fn filter_map(orig: RefMut<'b, T>, f: F) -> Result, Self> - where - F: FnOnce(&mut T) -> Option<&mut U>, - { - // FIXME(nll-rfc#40): fix borrow-check - let RefMut { value, borrow } = orig; - let value = value as *mut T; - // SAFETY: function holds onto an exclusive reference for the duration - // of its call through `orig`, and the pointer is only de-referenced - // inside of the function call never allowing the exclusive reference to - // escape. - match f(unsafe { &mut *value }) { - Some(value) => Ok(RefMut { value, borrow }), - None => { - // SAFETY: same as above. - Err(RefMut { value: unsafe { &mut *value }, borrow }) - } - } - } - /// Splits a `RefMut` into multiple `RefMut`s for different components of the /// borrowed data. /// diff --git a/library/core/src/cmp.rs b/library/core/src/cmp.rs index b983f49eb1782..38c6bfb0ef361 100644 --- a/library/core/src/cmp.rs +++ b/library/core/src/cmp.rs @@ -541,7 +541,7 @@ impl Ordering { /// assert_eq!(result, Ordering::Equal); /// /// let x: (i64, i64, i64) = (1, 2, 7); - /// let y: (i64, i64, i64) = (1, 5, 3); + /// let y: (i64, i64, i64) = (1, 5, 3); /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2)); /// /// assert_eq!(result, Ordering::Less); diff --git a/library/core/src/fmt/mod.rs b/library/core/src/fmt/mod.rs index 73cf5d138bf75..0c65c1c9eb7e9 100644 --- a/library/core/src/fmt/mod.rs +++ b/library/core/src/fmt/mod.rs @@ -456,9 +456,7 @@ impl Display for Arguments<'_> { /// /// When used with the alternate format specifier `#?`, the output is pretty-printed. /// -/// For more information on formatters, see [the module-level documentation][module]. -/// -/// [module]: ../../std/fmt/index.html +/// For more information on formatters, see [the module-level documentation][self]. /// /// This trait can be used with `#[derive]` if all fields implement `Debug`. When /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a @@ -604,9 +602,7 @@ pub use macros::Debug; /// `Display` is similar to [`Debug`], but `Display` is for user-facing /// output, and so cannot be derived. /// -/// For more information on formatters, see [the module-level documentation][module]. -/// -/// [module]: ../../std/fmt/index.html +/// For more information on formatters, see [the module-level documentation][self]. /// /// # Examples /// @@ -678,9 +674,7 @@ pub trait Display { /// /// The alternate flag, `#`, adds a `0o` in front of the output. /// -/// For more information on formatters, see [the module-level documentation][module]. -/// -/// [module]: ../../std/fmt/index.html +/// For more information on formatters, see [the module-level documentation][self]. /// /// # Examples /// @@ -732,9 +726,7 @@ pub trait Octal { /// /// The alternate flag, `#`, adds a `0b` in front of the output. /// -/// For more information on formatters, see [the module-level documentation][module]. -/// -/// [module]: ../../std/fmt/index.html +/// For more information on formatters, see [the module-level documentation][self]. /// /// # Examples /// @@ -790,9 +782,7 @@ pub trait Binary { /// /// The alternate flag, `#`, adds a `0x` in front of the output. /// -/// For more information on formatters, see [the module-level documentation][module]. -/// -/// [module]: ../../std/fmt/index.html +/// For more information on formatters, see [the module-level documentation][self]. /// /// # Examples /// @@ -845,9 +835,7 @@ pub trait LowerHex { /// /// The alternate flag, `#`, adds a `0x` in front of the output. /// -/// For more information on formatters, see [the module-level documentation][module]. -/// -/// [module]: ../../std/fmt/index.html +/// For more information on formatters, see [the module-level documentation][self]. /// /// # Examples /// @@ -895,9 +883,7 @@ pub trait UpperHex { /// The `Pointer` trait should format its output as a memory location. This is commonly presented /// as hexadecimal. /// -/// For more information on formatters, see [the module-level documentation][module]. -/// -/// [module]: ../../std/fmt/index.html +/// For more information on formatters, see [the module-level documentation][self]. /// /// # Examples /// @@ -946,9 +932,7 @@ pub trait Pointer { /// /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`. /// -/// For more information on formatters, see [the module-level documentation][module]. -/// -/// [module]: ../../std/fmt/index.html +/// For more information on formatters, see [the module-level documentation][self]. /// /// # Examples /// @@ -997,9 +981,7 @@ pub trait LowerExp { /// /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`. /// -/// For more information on formatters, see [the module-level documentation][module]. -/// -/// [module]: ../../std/fmt/index.html +/// For more information on formatters, see [the module-level documentation][self]. /// /// # Examples /// @@ -1573,7 +1555,7 @@ impl<'a> Formatter<'a> { /// } /// } /// - /// // We set alignment to the right with ">". + /// // We set alignment to the left with ">". /// assert_eq!(&format!("{:G>3}", Foo), "GGG"); /// assert_eq!(&format!("{:t>6}", Foo), "tttttt"); /// ``` diff --git a/library/core/src/intrinsics.rs b/library/core/src/intrinsics.rs index 7c1a9b82f99b2..0130586b43042 100644 --- a/library/core/src/intrinsics.rs +++ b/library/core/src/intrinsics.rs @@ -768,6 +768,13 @@ extern "rust-intrinsic" { #[rustc_const_stable(feature = "const_size_of", since = "1.40.0")] pub fn size_of() -> usize; + /// Moves a value to an uninitialized memory location. + /// + /// Drop glue is not run on the destination. + /// + /// The stabilized version of this intrinsic is [`core::ptr::write`](crate::ptr::write). + pub fn move_val_init(dst: *mut T, src: T); + /// The minimum alignment of a type. /// /// The stabilized version of this intrinsic is [`core::mem::align_of`](crate::mem::align_of). @@ -1842,7 +1849,6 @@ pub(crate) fn is_nonoverlapping(src: *const T, dst: *const T, count: usize) - #[inline] pub const unsafe fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize) { extern "rust-intrinsic" { - #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize); } @@ -1927,7 +1933,6 @@ pub const unsafe fn copy_nonoverlapping(src: *const T, dst: *mut T, count: us #[inline] pub const unsafe fn copy(src: *const T, dst: *mut T, count: usize) { extern "rust-intrinsic" { - #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] fn copy(src: *const T, dst: *mut T, count: usize); } diff --git a/library/core/src/iter/adapters/intersperse.rs b/library/core/src/iter/adapters/intersperse.rs index 1d01e9b5fb7dc..362326725490f 100644 --- a/library/core/src/iter/adapters/intersperse.rs +++ b/library/core/src/iter/adapters/intersperse.rs @@ -1,9 +1,6 @@ use super::Peekable; /// An iterator adapter that places a separator between all elements. -/// -/// This `struct` is created by [`Iterator::intersperse`]. See its documentation -/// for more information. #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] #[derive(Debug, Clone)] pub struct Intersperse @@ -43,146 +40,37 @@ where } } - fn fold(self, init: B, f: F) -> B + fn fold(mut self, init: B, mut f: F) -> B where Self: Sized, F: FnMut(B, Self::Item) -> B, { - let separator = self.separator; - intersperse_fold(self.iter, init, f, move || separator.clone(), self.needs_sep) - } - - fn size_hint(&self) -> (usize, Option) { - intersperse_size_hint(&self.iter, self.needs_sep) - } -} - -/// An iterator adapter that places a separator between all elements. -/// -/// This `struct` is created by [`Iterator::intersperse_with`]. See its -/// documentation for more information. -#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] -pub struct IntersperseWith -where - I: Iterator, -{ - separator: G, - iter: Peekable, - needs_sep: bool, -} - -#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] -impl crate::fmt::Debug for IntersperseWith -where - I: Iterator + crate::fmt::Debug, - I::Item: crate::fmt::Debug, - G: crate::fmt::Debug, -{ - fn fmt(&self, f: &mut crate::fmt::Formatter<'_>) -> crate::fmt::Result { - f.debug_struct("IntersperseWith") - .field("separator", &self.separator) - .field("iter", &self.iter) - .field("needs_sep", &self.needs_sep) - .finish() - } -} + let mut accum = init; -#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] -impl crate::clone::Clone for IntersperseWith -where - I: Iterator + crate::clone::Clone, - I::Item: crate::clone::Clone, - G: Clone, -{ - fn clone(&self) -> Self { - IntersperseWith { - separator: self.separator.clone(), - iter: self.iter.clone(), - needs_sep: self.needs_sep.clone(), + // Use `peek()` first to avoid calling `next()` on an empty iterator. + if !self.needs_sep || self.iter.peek().is_some() { + if let Some(x) = self.iter.next() { + accum = f(accum, x); + } } - } -} - -impl IntersperseWith -where - I: Iterator, - G: FnMut() -> I::Item, -{ - pub(in crate::iter) fn new(iter: I, separator: G) -> Self { - Self { iter: iter.peekable(), separator, needs_sep: false } - } -} - -#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] -impl Iterator for IntersperseWith -where - I: Iterator, - G: FnMut() -> I::Item, -{ - type Item = I::Item; - #[inline] - fn next(&mut self) -> Option { - if self.needs_sep && self.iter.peek().is_some() { - self.needs_sep = false; - Some((self.separator)()) - } else { - self.needs_sep = true; - self.iter.next() - } - } + let element = &self.separator; - fn fold(self, init: B, f: F) -> B - where - Self: Sized, - F: FnMut(B, Self::Item) -> B, - { - intersperse_fold(self.iter, init, f, self.separator, self.needs_sep) + self.iter.fold(accum, |mut accum, x| { + accum = f(accum, element.clone()); + accum = f(accum, x); + accum + }) } fn size_hint(&self) -> (usize, Option) { - intersperse_size_hint(&self.iter, self.needs_sep) + let (lo, hi) = self.iter.size_hint(); + let next_is_elem = !self.needs_sep; + let lo = lo.saturating_sub(next_is_elem as usize).saturating_add(lo); + let hi = match hi { + Some(hi) => hi.saturating_sub(next_is_elem as usize).checked_add(hi), + None => None, + }; + (lo, hi) } } - -fn intersperse_size_hint(iter: &I, needs_sep: bool) -> (usize, Option) -where - I: Iterator, -{ - let (lo, hi) = iter.size_hint(); - let next_is_elem = !needs_sep; - let lo = lo.saturating_sub(next_is_elem as usize).saturating_add(lo); - let hi = match hi { - Some(hi) => hi.saturating_sub(next_is_elem as usize).checked_add(hi), - None => None, - }; - (lo, hi) -} - -fn intersperse_fold( - mut iter: Peekable, - init: B, - mut f: F, - mut separator: G, - needs_sep: bool, -) -> B -where - I: Iterator, - F: FnMut(B, I::Item) -> B, - G: FnMut() -> I::Item, -{ - let mut accum = init; - - // Use `peek()` first to avoid calling `next()` on an empty iterator. - if !needs_sep || iter.peek().is_some() { - if let Some(x) = iter.next() { - accum = f(accum, x); - } - } - - iter.fold(accum, |mut accum, x| { - accum = f(accum, separator()); - accum = f(accum, x); - accum - }) -} diff --git a/library/core/src/iter/adapters/mod.rs b/library/core/src/iter/adapters/mod.rs index 41a7b13232adf..7dfbf32cea7b8 100644 --- a/library/core/src/iter/adapters/mod.rs +++ b/library/core/src/iter/adapters/mod.rs @@ -43,7 +43,7 @@ pub use self::flatten::Flatten; pub use self::copied::Copied; #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] -pub use self::intersperse::{Intersperse, IntersperseWith}; +pub use self::intersperse::Intersperse; #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")] pub use self::map_while::MapWhile; diff --git a/library/core/src/iter/adapters/zip.rs b/library/core/src/iter/adapters/zip.rs index 98b8dca961407..5766fd3c88744 100644 --- a/library/core/src/iter/adapters/zip.rs +++ b/library/core/src/iter/adapters/zip.rs @@ -286,7 +286,6 @@ where #[inline] unsafe fn get_unchecked(&mut self, idx: usize) -> ::Item { - let idx = self.index + idx; // SAFETY: the caller must uphold the contract for // `Iterator::__iterator_get_unchecked`. unsafe { (self.a.__iterator_get_unchecked(idx), self.b.__iterator_get_unchecked(idx)) } diff --git a/library/core/src/iter/mod.rs b/library/core/src/iter/mod.rs index c57ba2bf62645..569de719d03d6 100644 --- a/library/core/src/iter/mod.rs +++ b/library/core/src/iter/mod.rs @@ -395,6 +395,8 @@ pub use self::adapters::Cloned; pub use self::adapters::Copied; #[stable(feature = "iterator_flatten", since = "1.29.0")] pub use self::adapters::Flatten; +#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] +pub use self::adapters::Intersperse; #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")] pub use self::adapters::MapWhile; #[unstable(feature = "inplace_iteration", issue = "none")] @@ -408,8 +410,6 @@ pub use self::adapters::{ Chain, Cycle, Enumerate, Filter, FilterMap, FlatMap, Fuse, Inspect, Map, Peekable, Rev, Scan, Skip, SkipWhile, Take, TakeWhile, Zip, }; -#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] -pub use self::adapters::{Intersperse, IntersperseWith}; pub(crate) use self::adapters::process_results; diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index 83d339d8f40a5..0023de65d2b3b 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -8,7 +8,7 @@ use crate::ops::{Add, ControlFlow, Try}; use super::super::TrustedRandomAccess; use super::super::{Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, Fuse}; use super::super::{FlatMap, Flatten}; -use super::super::{FromIterator, Intersperse, IntersperseWith, Product, Sum, Zip}; +use super::super::{FromIterator, Intersperse, Product, Sum, Zip}; use super::super::{ Inspect, Map, MapWhile, Peekable, Rev, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile, }; @@ -571,9 +571,6 @@ pub trait Iterator { /// Places a copy of `separator` between all elements. /// - /// In case the separator does not implement [`Clone`] or needs to be - /// computed every time, use [`intersperse_with`]. - /// /// # Examples /// /// Basic usage: @@ -581,12 +578,9 @@ pub trait Iterator { /// ``` /// #![feature(iter_intersperse)] /// - /// let hello = ["Hello", "World", "!"].iter().copied().intersperse(" ").collect::(); - /// assert_eq!(hello, "Hello World !"); + /// let hello = ["Hello", "World"].iter().copied().intersperse(" ").collect::(); + /// assert_eq!(hello, "Hello World"); /// ``` - /// - /// [`Clone`]: crate::clone::Clone - /// [`intersperse_with`]: Iterator::intersperse_with #[inline] #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] fn intersperse(self, separator: Self::Item) -> Intersperse @@ -597,33 +591,6 @@ pub trait Iterator { Intersperse::new(self, separator) } - /// Places an element generated by `separator` between all elements. - /// - /// # Examples - /// - /// Basic usage: - /// - /// ``` - /// #![feature(iter_intersperse)] - /// - /// let src = ["Hello", "to", "all", "people", "!!"].iter().copied(); - /// - /// let mut happy_emojis = [" ❤️ ", " 😀 "].iter().copied(); - /// let separator = || happy_emojis.next().unwrap_or(" 🦀 "); - /// - /// let result = src.intersperse_with(separator).collect::(); - /// assert_eq!(result, "Hello ❤️ to 😀 all 🦀 people 🦀 !!"); - /// ``` - #[inline] - #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] - fn intersperse_with(self, separator: G) -> IntersperseWith - where - Self: Sized, - G: FnMut() -> Self::Item, - { - IntersperseWith::new(self, separator) - } - /// Takes a closure and creates an iterator which calls that closure on each /// element. /// diff --git a/library/core/src/macros/mod.rs b/library/core/src/macros/mod.rs index 90964bae98c89..1634aff7b4dc9 100644 --- a/library/core/src/macros/mod.rs +++ b/library/core/src/macros/mod.rs @@ -401,7 +401,7 @@ macro_rules! write { /// For more information, see [`write!`]. For information on the format string syntax, see /// [`std::fmt`]. /// -/// [`std::fmt`]: ../std/fmt/index.html +/// [`std::fmt`]: crate::fmt /// /// # Examples /// @@ -730,7 +730,7 @@ pub(crate) mod builtin { /// [`Display`]: crate::fmt::Display /// [`Debug`]: crate::fmt::Debug /// [`fmt::Arguments`]: crate::fmt::Arguments - /// [`std::fmt`]: ../std/fmt/index.html + /// [`std::fmt`]: crate::fmt /// [`format!`]: ../std/macro.format.html /// [`println!`]: ../std/macro.println.html /// @@ -1194,7 +1194,7 @@ pub(crate) mod builtin { /// be provided with or without arguments for formatting. See [`std::fmt`] /// for syntax for this form. /// - /// [`std::fmt`]: ../std/fmt/index.html + /// [`std::fmt`]: crate::fmt /// /// # Examples /// diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs index 111feb7dbec69..ba8918b192fa3 100644 --- a/library/core/src/num/nonzero.rs +++ b/library/core/src/num/nonzero.rs @@ -286,43 +286,3 @@ nonzero_integers_div! { NonZeroU128(u128); NonZeroUsize(usize); } - -macro_rules! nonzero_unsigned_is_power_of_two { - ( $( $Ty: ident )+ ) => { - $( - impl $Ty { - - /// Returns `true` if and only if `self == (1 << k)` for some `k`. - /// - /// On many architectures, this function can perform better than `is_power_of_two()` - /// on the underlying integer type, as special handling of zero can be avoided. - /// - /// # Examples - /// - /// Basic usage: - /// - /// ``` - /// #![feature(nonzero_is_power_of_two)] - /// - #[doc = concat!("let eight = std::num::", stringify!($Ty), "::new(8).unwrap();")] - /// assert!(eight.is_power_of_two()); - #[doc = concat!("let ten = std::num::", stringify!($Ty), "::new(10).unwrap();")] - /// assert!(!ten.is_power_of_two()); - /// ``` - #[unstable(feature = "nonzero_is_power_of_two", issue = "81106")] - #[inline] - pub const fn is_power_of_two(self) -> bool { - // LLVM 11 normalizes `unchecked_sub(x, 1) & x == 0` to the implementation seen here. - // On the basic x86-64 target, this saves 3 instructions for the zero check. - // On x86_64 with BMI1, being nonzero lets it codegen to `BLSR`, which saves an instruction - // compared to the `POPCNT` implementation on the underlying integer type. - - intrinsics::ctpop(self.get()) < 2 - } - - } - )+ - } -} - -nonzero_unsigned_is_power_of_two! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize } diff --git a/library/core/src/ops/range.rs b/library/core/src/ops/range.rs index 0571dc74b9af9..1d67e65e51f5f 100644 --- a/library/core/src/ops/range.rs +++ b/library/core/src/ops/range.rs @@ -678,29 +678,6 @@ pub enum Bound { Unbounded, } -#[unstable(feature = "bound_as_ref", issue = "80996")] -impl Bound { - /// Converts from `&Bound` to `Bound<&T>`. - #[inline] - pub fn as_ref(&self) -> Bound<&T> { - match *self { - Included(ref x) => Included(x), - Excluded(ref x) => Excluded(x), - Unbounded => Unbounded, - } - } - - /// Converts from `&mut Bound` to `Bound<&T>`. - #[inline] - pub fn as_mut(&mut self) -> Bound<&mut T> { - match *self { - Included(ref mut x) => Included(x), - Excluded(ref mut x) => Excluded(x), - Unbounded => Unbounded, - } - } -} - impl Bound<&T> { /// Map a `Bound<&T>` to a `Bound` by cloning the contents of the bound. /// diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs index 28de28c70e4b4..663001167865a 100644 --- a/library/core/src/ptr/const_ptr.rs +++ b/library/core/src/ptr/const_ptr.rs @@ -633,7 +633,7 @@ impl *const T { } /// Calculates the offset from a pointer using wrapping arithmetic. - /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`) + /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`) /// /// `count` is in units of T; e.g., a `count` of 3 represents a pointer /// offset of `3 * size_of::()` bytes. diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index 8d901c08f91a3..807f114ea466c 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -687,6 +687,7 @@ pub unsafe fn replace(dst: *mut T, mut src: T) -> T { #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")] pub const unsafe fn read(src: *const T) -> T { + // `copy_nonoverlapping` takes care of debug_assert. let mut tmp = MaybeUninit::::uninit(); // SAFETY: the caller must guarantee that `src` is valid for reads. // `src` cannot overlap `tmp` because `tmp` was just allocated on @@ -786,6 +787,7 @@ pub const unsafe fn read(src: *const T) -> T { #[stable(feature = "ptr_unaligned", since = "1.17.0")] #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")] pub const unsafe fn read_unaligned(src: *const T) -> T { + // `copy_nonoverlapping` takes care of debug_assert. let mut tmp = MaybeUninit::::uninit(); // SAFETY: the caller must guarantee that `src` is valid for reads. // `src` cannot overlap `tmp` because `tmp` was just allocated on @@ -881,19 +883,12 @@ pub const unsafe fn read_unaligned(src: *const T) -> T { #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn write(dst: *mut T, src: T) { - // We are calling the intrinsics directly to avoid function calls in the generated code - // as `intrinsics::copy_nonoverlapping` is a wrapper function. - extern "rust-intrinsic" { - fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize); - } - - // SAFETY: the caller must guarantee that `dst` is valid for writes. - // `dst` cannot overlap `src` because the caller has mutable access - // to `dst` while `src` is owned by this function. - unsafe { - copy_nonoverlapping(&src as *const T, dst, 1); - intrinsics::forget(src); + if cfg!(debug_assertions) && !is_aligned_and_not_null(dst) { + // Not panicking to keep codegen impact smaller. + abort(); } + // SAFETY: the caller must uphold the safety contract for `move_val_init`. + unsafe { intrinsics::move_val_init(&mut *dst, src) } } /// Overwrites a memory location with the given value without reading or @@ -986,6 +981,7 @@ pub unsafe fn write_unaligned(dst: *mut T, src: T) { // `dst` cannot overlap `src` because the caller has mutable access // to `dst` while `src` is owned by this function. unsafe { + // `copy_nonoverlapping` takes care of debug_assert. copy_nonoverlapping(&src as *const T as *const u8, dst as *mut u8, mem::size_of::()); } mem::forget(src); diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs index 99744fc711216..785bf70c2992c 100644 --- a/library/core/src/ptr/mut_ptr.rs +++ b/library/core/src/ptr/mut_ptr.rs @@ -740,7 +740,7 @@ impl *mut T { } /// Calculates the offset from a pointer using wrapping arithmetic. - /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`) + /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`) /// /// `count` is in units of T; e.g., a `count` of 3 represents a pointer /// offset of `3 * size_of::()` bytes. diff --git a/library/core/src/slice/iter.rs b/library/core/src/slice/iter.rs index 50664267a6755..769b673d80ab5 100644 --- a/library/core/src/slice/iter.rs +++ b/library/core/src/slice/iter.rs @@ -446,13 +446,15 @@ impl FusedIterator for Split<'_, T, P> where P: FnMut(&T) -> bool {} /// # Example /// /// ``` +/// #![feature(split_inclusive)] +/// /// let slice = [10, 40, 33, 20]; /// let mut iter = slice.split_inclusive(|num| num % 3 == 0); /// ``` /// /// [`split_inclusive`]: ../../std/primitive.slice.html#method.split_inclusive /// [slices]: ../../std/primitive.slice.html -#[stable(feature = "split_inclusive", since = "1.51.0")] +#[unstable(feature = "split_inclusive", issue = "72360")] pub struct SplitInclusive<'a, T: 'a, P> where P: FnMut(&T) -> bool, @@ -469,7 +471,7 @@ impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitInclusive<'a, T, P> { } } -#[stable(feature = "split_inclusive", since = "1.51.0")] +#[unstable(feature = "split_inclusive", issue = "72360")] impl fmt::Debug for SplitInclusive<'_, T, P> where P: FnMut(&T) -> bool, @@ -483,7 +485,7 @@ where } // FIXME(#26925) Remove in favor of `#[derive(Clone)]` -#[stable(feature = "split_inclusive", since = "1.51.0")] +#[unstable(feature = "split_inclusive", issue = "72360")] impl Clone for SplitInclusive<'_, T, P> where P: Clone + FnMut(&T) -> bool, @@ -493,7 +495,7 @@ where } } -#[stable(feature = "split_inclusive", since = "1.51.0")] +#[unstable(feature = "split_inclusive", issue = "72360")] impl<'a, T, P> Iterator for SplitInclusive<'a, T, P> where P: FnMut(&T) -> bool, @@ -522,7 +524,7 @@ where } } -#[stable(feature = "split_inclusive", since = "1.51.0")] +#[unstable(feature = "split_inclusive", issue = "72360")] impl<'a, T, P> DoubleEndedIterator for SplitInclusive<'a, T, P> where P: FnMut(&T) -> bool, @@ -547,7 +549,7 @@ where } } -#[stable(feature = "split_inclusive", since = "1.51.0")] +#[unstable(feature = "split_inclusive", issue = "72360")] impl FusedIterator for SplitInclusive<'_, T, P> where P: FnMut(&T) -> bool {} /// An iterator over the mutable subslices of the vector which are separated @@ -687,13 +689,15 @@ impl FusedIterator for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {} /// # Example /// /// ``` +/// #![feature(split_inclusive)] +/// /// let mut v = [10, 40, 30, 20, 60, 50]; /// let iter = v.split_inclusive_mut(|num| *num % 3 == 0); /// ``` /// /// [`split_inclusive_mut`]: ../../std/primitive.slice.html#method.split_inclusive_mut /// [slices]: ../../std/primitive.slice.html -#[stable(feature = "split_inclusive", since = "1.51.0")] +#[unstable(feature = "split_inclusive", issue = "72360")] pub struct SplitInclusiveMut<'a, T: 'a, P> where P: FnMut(&T) -> bool, @@ -710,7 +714,7 @@ impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitInclusiveMut<'a, T, P> { } } -#[stable(feature = "split_inclusive", since = "1.51.0")] +#[unstable(feature = "split_inclusive", issue = "72360")] impl fmt::Debug for SplitInclusiveMut<'_, T, P> where P: FnMut(&T) -> bool, @@ -723,7 +727,7 @@ where } } -#[stable(feature = "split_inclusive", since = "1.51.0")] +#[unstable(feature = "split_inclusive", issue = "72360")] impl<'a, T, P> Iterator for SplitInclusiveMut<'a, T, P> where P: FnMut(&T) -> bool, @@ -763,7 +767,7 @@ where } } -#[stable(feature = "split_inclusive", since = "1.51.0")] +#[unstable(feature = "split_inclusive", issue = "72360")] impl<'a, T, P> DoubleEndedIterator for SplitInclusiveMut<'a, T, P> where P: FnMut(&T) -> bool, @@ -797,7 +801,7 @@ where } } -#[stable(feature = "split_inclusive", since = "1.51.0")] +#[unstable(feature = "split_inclusive", issue = "72360")] impl FusedIterator for SplitInclusiveMut<'_, T, P> where P: FnMut(&T) -> bool {} /// An iterator over subslices separated by elements that match a predicate diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index de8d7fc29dc05..439a39b8276a2 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -60,7 +60,7 @@ pub use iter::ArrayWindows; #[unstable(feature = "slice_group_by", issue = "80552")] pub use iter::{GroupBy, GroupByMut}; -#[stable(feature = "split_inclusive", since = "1.51.0")] +#[unstable(feature = "split_inclusive", issue = "72360")] pub use iter::{SplitInclusive, SplitInclusiveMut}; #[stable(feature = "rust1", since = "1.0.0")] @@ -888,46 +888,6 @@ impl [T] { ChunksExactMut::new(self, chunk_size) } - /// Splits the slice into a slice of `N`-element arrays, - /// assuming that there's no remainder. - /// - /// # Safety - /// - /// This may only be called when - /// - The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`). - /// - `N != 0`. - /// - /// # Examples - /// - /// ``` - /// #![feature(slice_as_chunks)] - /// let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!']; - /// let chunks: &[[char; 1]] = - /// // SAFETY: 1-element chunks never have remainder - /// unsafe { slice.as_chunks_unchecked() }; - /// assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]); - /// let chunks: &[[char; 3]] = - /// // SAFETY: The slice length (6) is a multiple of 3 - /// unsafe { slice.as_chunks_unchecked() }; - /// assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]); - /// - /// // These would be unsound: - /// // let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 5 - /// // let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed - /// ``` - #[unstable(feature = "slice_as_chunks", issue = "74985")] - #[inline] - pub unsafe fn as_chunks_unchecked(&self) -> &[[T; N]] { - debug_assert_ne!(N, 0); - debug_assert_eq!(self.len() % N, 0); - let new_len = - // SAFETY: Our precondition is exactly what's needed to call this - unsafe { crate::intrinsics::exact_div(self.len(), N) }; - // SAFETY: We cast a slice of `new_len * N` elements into - // a slice of `new_len` many `N` elements chunks. - unsafe { from_raw_parts(self.as_ptr().cast(), new_len) } - } - /// Splits the slice into a slice of `N`-element arrays, /// starting at the beginning of the slice, /// and a remainder slice with length strictly less than `N`. @@ -952,42 +912,12 @@ impl [T] { assert_ne!(N, 0); let len = self.len() / N; let (multiple_of_n, remainder) = self.split_at(len * N); - // SAFETY: We already panicked for zero, and ensured by construction - // that the length of the subslice is a multiple of N. - let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() }; + // SAFETY: We cast a slice of `len * N` elements into + // a slice of `len` many `N` elements chunks. + let array_slice: &[[T; N]] = unsafe { from_raw_parts(multiple_of_n.as_ptr().cast(), len) }; (array_slice, remainder) } - /// Splits the slice into a slice of `N`-element arrays, - /// starting at the end of the slice, - /// and a remainder slice with length strictly less than `N`. - /// - /// # Panics - /// - /// Panics if `N` is 0. This check will most probably get changed to a compile time - /// error before this method gets stabilized. - /// - /// # Examples - /// - /// ``` - /// #![feature(slice_as_chunks)] - /// let slice = ['l', 'o', 'r', 'e', 'm']; - /// let (remainder, chunks) = slice.as_rchunks(); - /// assert_eq!(remainder, &['l']); - /// assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]); - /// ``` - #[unstable(feature = "slice_as_chunks", issue = "74985")] - #[inline] - pub fn as_rchunks(&self) -> (&[T], &[[T; N]]) { - assert_ne!(N, 0); - let len = self.len() / N; - let (remainder, multiple_of_n) = self.split_at(self.len() - len * N); - // SAFETY: We already panicked for zero, and ensured by construction - // that the length of the subslice is a multiple of N. - let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() }; - (remainder, array_slice) - } - /// Returns an iterator over `N` elements of the slice at a time, starting at the /// beginning of the slice. /// @@ -1022,48 +952,6 @@ impl [T] { ArrayChunks::new(self) } - /// Splits the slice into a slice of `N`-element arrays, - /// assuming that there's no remainder. - /// - /// # Safety - /// - /// This may only be called when - /// - The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`). - /// - `N != 0`. - /// - /// # Examples - /// - /// ``` - /// #![feature(slice_as_chunks)] - /// let slice: &mut [char] = &mut ['l', 'o', 'r', 'e', 'm', '!']; - /// let chunks: &mut [[char; 1]] = - /// // SAFETY: 1-element chunks never have remainder - /// unsafe { slice.as_chunks_unchecked_mut() }; - /// chunks[0] = ['L']; - /// assert_eq!(chunks, &[['L'], ['o'], ['r'], ['e'], ['m'], ['!']]); - /// let chunks: &mut [[char; 3]] = - /// // SAFETY: The slice length (6) is a multiple of 3 - /// unsafe { slice.as_chunks_unchecked_mut() }; - /// chunks[1] = ['a', 'x', '?']; - /// assert_eq!(slice, &['L', 'o', 'r', 'a', 'x', '?']); - /// - /// // These would be unsound: - /// // let chunks: &[[_; 5]] = slice.as_chunks_unchecked_mut() // The slice length is not a multiple of 5 - /// // let chunks: &[[_; 0]] = slice.as_chunks_unchecked_mut() // Zero-length chunks are never allowed - /// ``` - #[unstable(feature = "slice_as_chunks", issue = "74985")] - #[inline] - pub unsafe fn as_chunks_unchecked_mut(&mut self) -> &mut [[T; N]] { - debug_assert_ne!(N, 0); - debug_assert_eq!(self.len() % N, 0); - let new_len = - // SAFETY: Our precondition is exactly what's needed to call this - unsafe { crate::intrinsics::exact_div(self.len(), N) }; - // SAFETY: We cast a slice of `new_len * N` elements into - // a slice of `new_len` many `N` elements chunks. - unsafe { from_raw_parts_mut(self.as_mut_ptr().cast(), new_len) } - } - /// Splits the slice into a slice of `N`-element arrays, /// starting at the beginning of the slice, /// and a remainder slice with length strictly less than `N`. @@ -1094,48 +982,13 @@ impl [T] { assert_ne!(N, 0); let len = self.len() / N; let (multiple_of_n, remainder) = self.split_at_mut(len * N); - // SAFETY: We already panicked for zero, and ensured by construction - // that the length of the subslice is a multiple of N. - let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() }; + let array_slice: &mut [[T; N]] = + // SAFETY: We cast a slice of `len * N` elements into + // a slice of `len` many `N` elements chunks. + unsafe { from_raw_parts_mut(multiple_of_n.as_mut_ptr().cast(), len) }; (array_slice, remainder) } - /// Splits the slice into a slice of `N`-element arrays, - /// starting at the end of the slice, - /// and a remainder slice with length strictly less than `N`. - /// - /// # Panics - /// - /// Panics if `N` is 0. This check will most probably get changed to a compile time - /// error before this method gets stabilized. - /// - /// # Examples - /// - /// ``` - /// #![feature(slice_as_chunks)] - /// let v = &mut [0, 0, 0, 0, 0]; - /// let mut count = 1; - /// - /// let (remainder, chunks) = v.as_rchunks_mut(); - /// remainder[0] = 9; - /// for chunk in chunks { - /// *chunk = [count; 2]; - /// count += 1; - /// } - /// assert_eq!(v, &[9, 1, 1, 2, 2]); - /// ``` - #[unstable(feature = "slice_as_chunks", issue = "74985")] - #[inline] - pub fn as_rchunks_mut(&mut self) -> (&mut [T], &mut [[T; N]]) { - assert_ne!(N, 0); - let len = self.len() / N; - let (remainder, multiple_of_n) = self.split_at_mut(self.len() - len * N); - // SAFETY: We already panicked for zero, and ensured by construction - // that the length of the subslice is a multiple of N. - let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() }; - (remainder, array_slice) - } - /// Returns an iterator over `N` elements of the slice at a time, starting at the /// beginning of the slice. /// @@ -1693,6 +1546,7 @@ impl [T] { /// # Examples /// /// ``` + /// #![feature(split_inclusive)] /// let slice = [10, 40, 33, 20]; /// let mut iter = slice.split_inclusive(|num| num % 3 == 0); /// @@ -1706,6 +1560,7 @@ impl [T] { /// That slice will be the last item returned by the iterator. /// /// ``` + /// #![feature(split_inclusive)] /// let slice = [3, 10, 40, 33]; /// let mut iter = slice.split_inclusive(|num| num % 3 == 0); /// @@ -1713,7 +1568,7 @@ impl [T] { /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]); /// assert!(iter.next().is_none()); /// ``` - #[stable(feature = "split_inclusive", since = "1.51.0")] + #[unstable(feature = "split_inclusive", issue = "72360")] #[inline] pub fn split_inclusive(&self, pred: F) -> SplitInclusive<'_, T, F> where @@ -1729,6 +1584,7 @@ impl [T] { /// # Examples /// /// ``` + /// #![feature(split_inclusive)] /// let mut v = [10, 40, 30, 20, 60, 50]; /// /// for group in v.split_inclusive_mut(|num| *num % 3 == 0) { @@ -1737,7 +1593,7 @@ impl [T] { /// } /// assert_eq!(v, [10, 40, 1, 20, 1, 1]); /// ``` - #[stable(feature = "split_inclusive", since = "1.51.0")] + #[unstable(feature = "split_inclusive", issue = "72360")] #[inline] pub fn split_inclusive_mut(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F> where @@ -2024,7 +1880,7 @@ impl [T] { /// Some(b"llo".as_ref())); /// ``` #[must_use = "returns the subslice without modifying the original"] - #[stable(feature = "slice_strip", since = "1.51.0")] + #[stable(feature = "slice_strip", since = "1.50.0")] pub fn strip_prefix + ?Sized>(&self, prefix: &P) -> Option<&[T]> where T: PartialEq, @@ -2058,7 +1914,7 @@ impl [T] { /// assert_eq!(v.strip_suffix(&[50, 30]), None); /// ``` #[must_use = "returns the subslice without modifying the original"] - #[stable(feature = "slice_strip", since = "1.51.0")] + #[stable(feature = "slice_strip", since = "1.50.0")] pub fn strip_suffix + ?Sized>(&self, suffix: &P) -> Option<&[T]> where T: PartialEq, @@ -3470,7 +3326,7 @@ pub trait SlicePattern { fn as_slice(&self) -> &[Self::Item]; } -#[stable(feature = "slice_strip", since = "1.51.0")] +#[stable(feature = "slice_strip", since = "1.50.0")] impl SlicePattern for [T] { type Item = T; @@ -3480,7 +3336,7 @@ impl SlicePattern for [T] { } } -#[stable(feature = "slice_strip", since = "1.51.0")] +#[stable(feature = "slice_strip", since = "1.50.0")] impl SlicePattern for [T; N] { type Item = T; diff --git a/library/core/src/slice/raw.rs b/library/core/src/slice/raw.rs index 117db6e3e3bf7..09209306c9d0f 100644 --- a/library/core/src/slice/raw.rs +++ b/library/core/src/slice/raw.rs @@ -103,7 +103,7 @@ pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] { /// /// Behavior is undefined if any of the following conditions are violated: /// -/// * `data` must be [valid] for both reads and writes for `len * mem::size_of::()` many bytes, +/// * `data` must be [valid] for boths reads and writes for `len * mem::size_of::()` many bytes, /// and it must be properly aligned. This means in particular: /// /// * The entire memory range of this slice must be contained within a single allocated object! diff --git a/library/core/src/str/iter.rs b/library/core/src/str/iter.rs index 8b952eab2946d..28cd350019ebf 100644 --- a/library/core/src/str/iter.rs +++ b/library/core/src/str/iter.rs @@ -1174,7 +1174,7 @@ pub struct SplitAsciiWhitespace<'a> { /// See its documentation for more. /// /// [`split_inclusive`]: str::split_inclusive -#[stable(feature = "split_inclusive", since = "1.51.0")] +#[unstable(feature = "split_inclusive", issue = "72360")] pub struct SplitInclusive<'a, P: Pattern<'a>>(pub(super) SplitInternal<'a, P>); #[stable(feature = "split_whitespace", since = "1.1.0")] @@ -1239,7 +1239,7 @@ impl<'a> DoubleEndedIterator for SplitAsciiWhitespace<'a> { #[stable(feature = "split_ascii_whitespace", since = "1.34.0")] impl FusedIterator for SplitAsciiWhitespace<'_> {} -#[stable(feature = "split_inclusive", since = "1.51.0")] +#[unstable(feature = "split_inclusive", issue = "72360")] impl<'a, P: Pattern<'a>> Iterator for SplitInclusive<'a, P> { type Item = &'a str; @@ -1249,7 +1249,7 @@ impl<'a, P: Pattern<'a>> Iterator for SplitInclusive<'a, P> { } } -#[stable(feature = "split_inclusive", since = "1.51.0")] +#[unstable(feature = "split_inclusive", issue = "72360")] impl<'a, P: Pattern<'a, Searcher: fmt::Debug>> fmt::Debug for SplitInclusive<'a, P> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("SplitInclusive").field("0", &self.0).finish() @@ -1257,14 +1257,14 @@ impl<'a, P: Pattern<'a, Searcher: fmt::Debug>> fmt::Debug for SplitInclusive<'a, } // FIXME(#26925) Remove in favor of `#[derive(Clone)]` -#[stable(feature = "split_inclusive", since = "1.51.0")] +#[unstable(feature = "split_inclusive", issue = "72360")] impl<'a, P: Pattern<'a, Searcher: Clone>> Clone for SplitInclusive<'a, P> { fn clone(&self) -> Self { SplitInclusive(self.0.clone()) } } -#[stable(feature = "split_inclusive", since = "1.51.0")] +#[unstable(feature = "split_inclusive", issue = "72360")] impl<'a, P: Pattern<'a, Searcher: ReverseSearcher<'a>>> DoubleEndedIterator for SplitInclusive<'a, P> { @@ -1274,7 +1274,7 @@ impl<'a, P: Pattern<'a, Searcher: ReverseSearcher<'a>>> DoubleEndedIterator } } -#[stable(feature = "split_inclusive", since = "1.51.0")] +#[unstable(feature = "split_inclusive", issue = "72360")] impl<'a, P: Pattern<'a>> FusedIterator for SplitInclusive<'a, P> {} impl<'a, P: Pattern<'a>> SplitInclusive<'a, P> { @@ -1284,6 +1284,7 @@ impl<'a, P: Pattern<'a>> SplitInclusive<'a, P> { /// /// ``` /// #![feature(str_split_inclusive_as_str)] + /// #![feature(split_inclusive)] /// let mut split = "Mary had a little lamb".split_inclusive(' '); /// assert_eq!(split.as_str(), "Mary had a little lamb"); /// split.next(); diff --git a/library/core/src/str/mod.rs b/library/core/src/str/mod.rs index 6a35378ca7b50..ae7892291ed19 100644 --- a/library/core/src/str/mod.rs +++ b/library/core/src/str/mod.rs @@ -65,7 +65,7 @@ pub use iter::{EscapeDebug, EscapeDefault, EscapeUnicode}; #[stable(feature = "split_ascii_whitespace", since = "1.34.0")] pub use iter::SplitAsciiWhitespace; -#[stable(feature = "split_inclusive", since = "1.51.0")] +#[unstable(feature = "split_inclusive", issue = "72360")] use iter::SplitInclusive; #[unstable(feature = "str_internals", issue = "none")] @@ -1227,6 +1227,7 @@ impl str { /// # Examples /// /// ``` + /// #![feature(split_inclusive)] /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb." /// .split_inclusive('\n').collect(); /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]); @@ -1237,11 +1238,12 @@ impl str { /// That substring will be the last item returned by the iterator. /// /// ``` + /// #![feature(split_inclusive)] /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n" /// .split_inclusive('\n').collect(); /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]); /// ``` - #[stable(feature = "split_inclusive", since = "1.51.0")] + #[unstable(feature = "split_inclusive", issue = "72360")] #[inline] pub fn split_inclusive<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitInclusive<'a, P> { SplitInclusive(SplitInternal { diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs index 81c9e1d1c10b2..d03c19e51f3fa 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs @@ -120,6 +120,21 @@ use crate::intrinsics; use crate::hint::spin_loop; +/// Signals the processor that it is inside a busy-wait spin-loop ("spin lock"). +/// +/// This function is expected to be deprecated in favor of +/// [`hint::spin_loop`]. +/// +/// **Note**: On platforms that do not support receiving spin-loop hints this function does not +/// do anything at all. +/// +/// [`hint::spin_loop`]: crate::hint::spin_loop +#[inline] +#[stable(feature = "spin_loop_hint", since = "1.24.0")] +pub fn spin_loop_hint() { + spin_loop() +} + /// A boolean type which can be safely shared between threads. /// /// This type has the same in-memory representation as a [`bool`]. @@ -794,7 +809,7 @@ impl AtomicBool { /// ```ignore (extern-declaration) /// # fn main() { /// use std::sync::atomic::AtomicBool; - /// extern "C" { + /// extern { /// fn my_atomic_op(arg: *mut bool); /// } /// @@ -2053,7 +2068,7 @@ macro_rules! atomic_int { /// # fn main() { #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")] /// - /// extern "C" { + /// extern { #[doc = concat!(" fn my_atomic_op(arg: *mut ", stringify!($int_type), ");")] /// } /// @@ -2776,15 +2791,3 @@ impl fmt::Pointer for AtomicPtr { fmt::Pointer::fmt(&self.load(Ordering::SeqCst), f) } } - -/// Signals the processor that it is inside a busy-wait spin-loop ("spin lock"). -/// -/// This function is deprecated in favor of [`hint::spin_loop`]. -/// -/// [`hint::spin_loop`]: crate::hint::spin_loop -#[inline] -#[stable(feature = "spin_loop_hint", since = "1.24.0")] -#[rustc_deprecated(since = "1.51.0", reason = "use hint::spin_loop instead")] -pub fn spin_loop_hint() { - spin_loop() -} diff --git a/library/core/src/task/poll.rs b/library/core/src/task/poll.rs index 42c9d9f0cc039..6851f3fcd2fc7 100644 --- a/library/core/src/task/poll.rs +++ b/library/core/src/task/poll.rs @@ -84,7 +84,7 @@ impl Poll> { impl Poll>> { /// Changes the success value of this `Poll` with the closure provided. - #[stable(feature = "poll_map", since = "1.51.0")] + #[unstable(feature = "poll_map", issue = "63514")] pub fn map_ok(self, f: F) -> Poll>> where F: FnOnce(T) -> U, @@ -98,7 +98,7 @@ impl Poll>> { } /// Changes the error value of this `Poll` with the closure provided. - #[stable(feature = "poll_map", since = "1.51.0")] + #[unstable(feature = "poll_map", issue = "63514")] pub fn map_err(self, f: F) -> Poll>> where F: FnOnce(E) -> U, diff --git a/library/core/tests/iter.rs b/library/core/tests/iter.rs index bc5421bfb5f8f..7376e7848eff5 100644 --- a/library/core/tests/iter.rs +++ b/library/core/tests/iter.rs @@ -2,7 +2,6 @@ use core::cell::Cell; use core::convert::TryFrom; -use core::iter::TrustedRandomAccess; use core::iter::*; /// An iterator wrapper that panics whenever `next` or `next_back` is called @@ -602,26 +601,6 @@ fn test_zip_nth_back_side_effects_exhausted() { assert_eq!(b, vec![200, 300, 400]); } -#[test] -fn test_zip_trusted_random_access_composition() { - let a = [0, 1, 2, 3, 4]; - let b = a; - let c = a; - - let a = a.iter().copied(); - let b = b.iter().copied(); - let mut c = c.iter().copied(); - c.next(); - - let mut z1 = a.zip(b); - assert_eq!(z1.next().unwrap(), (0, 0)); - - let mut z2 = z1.zip(c); - fn assert_trusted_random_access(_a: &T) {} - assert_trusted_random_access(&z2); - assert_eq!(z2.next().unwrap(), ((1, 1), 1)); -} - #[test] fn test_iterator_step_by() { // Identity @@ -3529,12 +3508,6 @@ pub fn extend_for_unit() { #[test] fn test_intersperse() { - let v = std::iter::empty().intersperse(0u32).collect::>(); - assert_eq!(v, vec![]); - - let v = std::iter::once(1).intersperse(0).collect::>(); - assert_eq!(v, vec![1]); - let xs = ["a", "", "b", "c"]; let v: Vec<&str> = xs.iter().map(|x| x.clone()).intersperse(", ").collect(); let text: String = v.concat(); @@ -3547,9 +3520,6 @@ fn test_intersperse() { #[test] fn test_intersperse_size_hint() { - let iter = std::iter::empty::().intersperse(0); - assert_eq!(iter.size_hint(), (0, Some(0))); - let xs = ["a", "", "b", "c"]; let mut iter = xs.iter().map(|x| x.clone()).intersperse(", "); assert_eq!(iter.size_hint(), (7, Some(7))); @@ -3617,24 +3587,3 @@ fn test_try_fold_specialization_intersperse_err() { iter.try_for_each(|item| if item == "b" { None } else { Some(()) }); assert_eq!(iter.next(), None); } - -#[test] -fn test_intersperse_with() { - #[derive(PartialEq, Debug)] - struct NotClone { - u: u32, - } - let r = vec![NotClone { u: 0 }, NotClone { u: 1 }] - .into_iter() - .intersperse_with(|| NotClone { u: 2 }) - .collect::>(); - assert_eq!(r, vec![NotClone { u: 0 }, NotClone { u: 2 }, NotClone { u: 1 }]); - - let mut ctr = 100; - let separator = || { - ctr *= 2; - ctr - }; - let r = (0..3).intersperse_with(separator).collect::>(); - assert_eq!(r, vec![0, 200, 1, 400, 2]); -} diff --git a/library/core/tests/lib.rs b/library/core/tests/lib.rs index 98f5982fbb2c1..bc737cd1927cf 100644 --- a/library/core/tests/lib.rs +++ b/library/core/tests/lib.rs @@ -75,7 +75,6 @@ #![feature(const_option)] #![feature(integer_atomics)] #![feature(slice_group_by)] -#![feature(trusted_random_access)] #![deny(unsafe_op_in_unsafe_fn)] extern crate test; diff --git a/library/core/tests/num/dec2flt/mod.rs b/library/core/tests/num/dec2flt/mod.rs index 32f05d1def50a..1c172f49c279c 100644 --- a/library/core/tests/num/dec2flt/mod.rs +++ b/library/core/tests/num/dec2flt/mod.rs @@ -21,6 +21,7 @@ macro_rules! test_literal { }}; } +#[cfg_attr(all(target_arch = "wasm32", target_os = "emscripten"), ignore)] // issue 42630 #[test] fn ordinary() { test_literal!(1.0); @@ -37,6 +38,7 @@ fn ordinary() { test_literal!(2.2250738585072014e-308); } +#[cfg_attr(all(target_arch = "wasm32", target_os = "emscripten"), ignore)] // issue 42630 #[test] fn special_code_paths() { test_literal!(36893488147419103229.0); // 2^65 - 3, triggers half-to-even with even significand diff --git a/library/core/tests/num/dec2flt/rawfp.rs b/library/core/tests/num/dec2flt/rawfp.rs index 34a37209d99f8..c098b9c2ba27d 100644 --- a/library/core/tests/num/dec2flt/rawfp.rs +++ b/library/core/tests/num/dec2flt/rawfp.rs @@ -81,6 +81,7 @@ fn rounding_overflow() { assert_eq!(rounded.k, adjusted_k + 1); } +#[cfg_attr(all(target_arch = "wasm32", target_os = "emscripten"), ignore)] // issue 42630 #[test] fn prev_float_monotonic() { let mut x = 1.0; @@ -116,6 +117,7 @@ fn next_float_inf() { assert_eq!(next_float(f64::INFINITY), f64::INFINITY); } +#[cfg_attr(all(target_arch = "wasm32", target_os = "emscripten"), ignore)] // issue 42630 #[test] fn next_prev_identity() { for &x in &SOME_FLOATS { @@ -126,6 +128,7 @@ fn next_prev_identity() { } } +#[cfg_attr(all(target_arch = "wasm32", target_os = "emscripten"), ignore)] // issue 42630 #[test] fn next_float_monotonic() { let mut x = 0.49999999999999; diff --git a/library/core/tests/num/flt2dec/strategy/dragon.rs b/library/core/tests/num/flt2dec/strategy/dragon.rs index fc2e724a20c7c..3d985c6796b16 100644 --- a/library/core/tests/num/flt2dec/strategy/dragon.rs +++ b/library/core/tests/num/flt2dec/strategy/dragon.rs @@ -13,6 +13,7 @@ fn test_mul_pow10() { } } +#[cfg_attr(all(target_arch = "wasm32", target_os = "emscripten"), ignore)] // issue 42630 #[test] fn shortest_sanity_test() { f64_shortest_sanity_test(format_shortest); diff --git a/library/core/tests/num/flt2dec/strategy/grisu.rs b/library/core/tests/num/flt2dec/strategy/grisu.rs index b59a3b9b72d3b..7e6c8add3339d 100644 --- a/library/core/tests/num/flt2dec/strategy/grisu.rs +++ b/library/core/tests/num/flt2dec/strategy/grisu.rs @@ -33,6 +33,7 @@ fn test_max_pow10_no_more_than() { } } +#[cfg_attr(all(target_arch = "wasm32", target_os = "emscripten"), ignore)] // issue 42630 #[test] fn shortest_sanity_test() { f64_shortest_sanity_test(format_shortest); diff --git a/library/core/tests/num/mod.rs b/library/core/tests/num/mod.rs index e66a73ac1289b..012ab4ea5c573 100644 --- a/library/core/tests/num/mod.rs +++ b/library/core/tests/num/mod.rs @@ -29,8 +29,6 @@ mod u8; mod bignum; mod dec2flt; mod flt2dec; -mod ops; -mod wrapping; mod nan; diff --git a/library/core/tests/num/ops.rs b/library/core/tests/num/ops.rs deleted file mode 100644 index 9979cc8fde434..0000000000000 --- a/library/core/tests/num/ops.rs +++ /dev/null @@ -1,244 +0,0 @@ -use core::ops::*; - -// For types L and R, checks that a trait implementation exists for -// * binary ops: L op R, L op &R, &L op R and &L op &R -// * assign ops: &mut L op R, &mut L op &R -macro_rules! impl_defined { - ($op:ident, $method:ident($lhs:literal, $rhs:literal), $result:literal, $lt:ty, $rt:ty) => { - let lhs = $lhs as $lt; - let rhs = $rhs as $rt; - assert_eq!($result as $lt, $op::$method(lhs, rhs)); - assert_eq!($result as $lt, $op::$method(lhs, &rhs)); - assert_eq!($result as $lt, $op::$method(&lhs, rhs)); - assert_eq!($result as $lt, $op::$method(&lhs, &rhs)); - }; - ($op:ident, $method:ident(&mut $lhs:literal, $rhs:literal), $result:literal, $lt:ty, $rt:ty) => { - let rhs = $rhs as $rt; - let mut lhs = $lhs as $lt; - $op::$method(&mut lhs, rhs); - assert_eq!($result as $lt, lhs); - - let mut lhs = $lhs as $lt; - $op::$method(&mut lhs, &rhs); - assert_eq!($result as $lt, lhs); - }; -} - -// For all specified types T, checks that a trait implementation exists for -// * binary ops: T op T, T op &T, &T op T and &T op &T -// * assign ops: &mut T op T, &mut T op &T -// * unary ops: op T and op &T -macro_rules! impls_defined { - ($op:ident, $method:ident($lhs:literal, $rhs:literal), $result:literal, $($t:ty),+) => {$( - impl_defined!($op, $method($lhs, $rhs), $result, $t, $t); - )+}; - ($op:ident, $method:ident(&mut $lhs:literal, $rhs:literal), $result:literal, $($t:ty),+) => {$( - impl_defined!($op, $method(&mut $lhs, $rhs), $result, $t, $t); - )+}; - ($op:ident, $method:ident($operand:literal), $result:literal, $($t:ty),+) => {$( - let operand = $operand as $t; - assert_eq!($result as $t, $op::$method(operand)); - assert_eq!($result as $t, $op::$method(&operand)); - )+}; -} - -macro_rules! test_op { - ($fn_name:ident, $op:ident::$method:ident($lhs:literal, $rhs:literal), $result:literal, $($t:ty),+) => { - #[test] - fn $fn_name() { - impls_defined!($op, $method($lhs, $rhs), $result, $($t),+); - } - }; - ($fn_name:ident, $op:ident::$method:ident(&mut $lhs:literal, $rhs:literal), $result:literal, $($t:ty),+) => { - #[test] - fn $fn_name() { - impls_defined!($op, $method(&mut $lhs, $rhs), $result, $($t),+); - } - }; - ($fn_name:ident, $op:ident::$method:ident($lhs:literal), $result:literal, $($t:ty),+) => { - #[test] - fn $fn_name() { - impls_defined!($op, $method($lhs), $result, $($t),+); - } - }; -} - -test_op!(test_neg_defined, Neg::neg(0), 0, i8, i16, i32, i64, f32, f64); -#[cfg(not(target_os = "emscripten"))] -test_op!(test_neg_defined_128, Neg::neg(0), 0, i128); - -test_op!(test_not_defined_bool, Not::not(true), false, bool); - -macro_rules! test_arith_op { - ($fn_name:ident, $op:ident::$method:ident($lhs:literal, $rhs:literal)) => { - #[test] - fn $fn_name() { - impls_defined!( - $op, - $method($lhs, $rhs), - 0, - i8, - i16, - i32, - i64, - isize, - u8, - u16, - u32, - u64, - usize, - f32, - f64 - ); - #[cfg(not(target_os = "emscripten"))] - impls_defined!($op, $method($lhs, $rhs), 0, i128, u128); - } - }; - ($fn_name:ident, $op:ident::$method:ident(&mut $lhs:literal, $rhs:literal)) => { - #[test] - fn $fn_name() { - impls_defined!( - $op, - $method(&mut $lhs, $rhs), - 0, - i8, - i16, - i32, - i64, - isize, - u8, - u16, - u32, - u64, - usize, - f32, - f64 - ); - #[cfg(not(target_os = "emscripten"))] - impls_defined!($op, $method(&mut $lhs, $rhs), 0, i128, u128); - } - }; -} - -test_arith_op!(test_add_defined, Add::add(0, 0)); -test_arith_op!(test_add_assign_defined, AddAssign::add_assign(&mut 0, 0)); -test_arith_op!(test_sub_defined, Sub::sub(0, 0)); -test_arith_op!(test_sub_assign_defined, SubAssign::sub_assign(&mut 0, 0)); -test_arith_op!(test_mul_defined, Mul::mul(0, 0)); -test_arith_op!(test_mul_assign_defined, MulAssign::mul_assign(&mut 0, 0)); -test_arith_op!(test_div_defined, Div::div(0, 1)); -test_arith_op!(test_div_assign_defined, DivAssign::div_assign(&mut 0, 1)); -test_arith_op!(test_rem_defined, Rem::rem(0, 1)); -test_arith_op!(test_rem_assign_defined, RemAssign::rem_assign(&mut 0, 1)); - -macro_rules! test_bitop { - ($test_name:ident, $op:ident::$method:ident) => { - #[test] - fn $test_name() { - impls_defined!( - $op, - $method(0, 0), - 0, - i8, - i16, - i32, - i64, - isize, - u8, - u16, - u32, - u64, - usize - ); - #[cfg(not(target_os = "emscripten"))] - impls_defined!($op, $method(0, 0), 0, i128, u128); - impls_defined!($op, $method(false, false), false, bool); - } - }; -} -macro_rules! test_bitop_assign { - ($test_name:ident, $op:ident::$method:ident) => { - #[test] - fn $test_name() { - impls_defined!( - $op, - $method(&mut 0, 0), - 0, - i8, - i16, - i32, - i64, - isize, - u8, - u16, - u32, - u64, - usize - ); - #[cfg(not(target_os = "emscripten"))] - impls_defined!($op, $method(&mut 0, 0), 0, i128, u128); - impls_defined!($op, $method(&mut false, false), false, bool); - } - }; -} - -test_bitop!(test_bitand_defined, BitAnd::bitand); -test_bitop_assign!(test_bitand_assign_defined, BitAndAssign::bitand_assign); -test_bitop!(test_bitor_defined, BitOr::bitor); -test_bitop_assign!(test_bitor_assign_defined, BitOrAssign::bitor_assign); -test_bitop!(test_bitxor_defined, BitXor::bitxor); -test_bitop_assign!(test_bitxor_assign_defined, BitXorAssign::bitxor_assign); - -macro_rules! test_shift_inner { - ($op:ident::$method:ident, $lt:ty, $($rt:ty),+) => { - $(impl_defined!($op, $method(0,0), 0, $lt, $rt);)+ - }; - ($op:ident::$method:ident, $lt:ty) => { - test_shift_inner!($op::$method, $lt, i8, i16, i32, i64, isize, u8, u16, u32, u64, usize); - #[cfg(not(target_os = "emscripten"))] - test_shift_inner!($op::$method, $lt, i128, u128); - }; -} - -macro_rules! test_shift { - ($op:ident::$method:ident, $($lt:ty),+) => { - $(test_shift_inner!($op::$method, $lt);)+ - }; - ($test_name:ident, $op:ident::$method:ident) => { - #[test] - fn $test_name() { - test_shift!($op::$method, i8, i16, i32, i64, isize, u8, u16, u32, u64, usize); - #[cfg(not(target_os = "emscripten"))] - test_shift!($op::$method, i128, u128); - } - }; -} - -macro_rules! test_shift_assign_inner { - ($op:ident::$method:ident, $lt:ty, $($rt:ty),+) => { - $(impl_defined!($op, $method(&mut 0,0), 0, $lt, $rt);)+ - }; - ($op:ident::$method:ident, $lt:ty) => { - test_shift_assign_inner!($op::$method, $lt, i8, i16, i32, i64, isize, u8, u16, u32, u64, usize); - #[cfg(not(target_os = "emscripten"))] - test_shift_assign_inner!($op::$method, $lt, i128, u128); - }; -} - -macro_rules! test_shift_assign { - ($op:ident::$method:ident, $($lt:ty),+) => { - $(test_shift_assign_inner!($op::$method, $lt);)+ - }; - ($test_name:ident, $op:ident::$method:ident) => { - #[test] - fn $test_name() { - test_shift_assign!($op::$method, i8, i16, i32, i64, isize, u8, u16, u32, u64, usize); - #[cfg(not(target_os = "emscripten"))] - test_shift_assign!($op::$method, i128, u128); - } - }; -} -test_shift!(test_shl_defined, Shl::shl); -test_shift_assign!(test_shl_assign_defined, ShlAssign::shl_assign); -test_shift!(test_shr_defined, Shr::shr); -test_shift_assign!(test_shr_assign_defined, ShrAssign::shr_assign); diff --git a/library/core/tests/num/wrapping.rs b/library/core/tests/num/wrapping.rs index c4fb321ef26cf..01defab2b38f0 100644 --- a/library/core/tests/num/wrapping.rs +++ b/library/core/tests/num/wrapping.rs @@ -26,9 +26,9 @@ macro_rules! wrapping_assignment { } macro_rules! wrapping_test { - ($fn_name:ident, $type:ty, $min:expr, $max:expr) => { + ($type:ty, $min:expr, $max:expr) => { #[test] - fn $fn_name() { + fn wrapping_$type() { let zero: Wrapping<$type> = Wrapping(0); let one: Wrapping<$type> = Wrapping(1); let min: Wrapping<$type> = Wrapping($min); @@ -60,24 +60,23 @@ macro_rules! wrapping_test { }; } -wrapping_test!(test_wrapping_i8, i8, i8::MIN, i8::MAX); -wrapping_test!(test_wrapping_i16, i16, i16::MIN, i16::MAX); -wrapping_test!(test_wrapping_i32, i32, i32::MIN, i32::MAX); -wrapping_test!(test_wrapping_i64, i64, i64::MIN, i64::MAX); +wrapping_test!(i8, i8::MIN, i8::MAX); +wrapping_test!(i16, i16::MIN, i16::MAX); +wrapping_test!(i32, i32::MIN, i32::MAX); +wrapping_test!(i64, i64::MIN, i64::MAX); #[cfg(not(target_os = "emscripten"))] -wrapping_test!(test_wrapping_i128, i128, i128::MIN, i128::MAX); -wrapping_test!(test_wrapping_isize, isize, isize::MIN, isize::MAX); -wrapping_test!(test_wrapping_u8, u8, u8::MIN, u8::MAX); -wrapping_test!(test_wrapping_u16, u16, u16::MIN, u16::MAX); -wrapping_test!(test_wrapping_u32, u32, u32::MIN, u32::MAX); -wrapping_test!(test_wrapping_u64, u64, u64::MIN, u64::MAX); +wrapping_test!(i128, i128::MIN, i128::MAX); +wrapping_test!(isize, isize::MIN, isize::MAX); +wrapping_test!(u8, u8::MIN, u8::MAX); +wrapping_test!(u16, u16::MIN, u16::MAX); +wrapping_test!(u32, u32::MIN, u32::MAX); +wrapping_test!(u64, u64::MIN, u64::MAX); #[cfg(not(target_os = "emscripten"))] -wrapping_test!(test_wrapping_u128, u128, u128::MIN, u128::MAX); -wrapping_test!(test_wrapping_usize, usize, usize::MIN, usize::MAX); +wrapping_test!(u128, u128::MIN, u128::MAX); +wrapping_test!(usize, usize::MIN, usize::MAX); // Don't warn about overflowing ops on 32-bit platforms #[cfg_attr(target_pointer_width = "32", allow(const_err))] -#[test] fn wrapping_int_api() { assert_eq!(i8::MAX.wrapping_add(1), i8::MIN); assert_eq!(i16::MAX.wrapping_add(1), i16::MIN); diff --git a/library/std/src/backtrace.rs b/library/std/src/backtrace.rs index 95e18ef2a6543..7e8e0a621e31c 100644 --- a/library/std/src/backtrace.rs +++ b/library/std/src/backtrace.rs @@ -95,12 +95,11 @@ mod tests; // a backtrace or actually symbolizing it. use crate::backtrace_rs::{self, BytesOrWideString}; -use crate::cell::UnsafeCell; use crate::env; use crate::ffi::c_void; use crate::fmt; use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst}; -use crate::sync::Once; +use crate::sync::Mutex; use crate::sys_common::backtrace::{lock, output_filename}; use crate::vec::Vec; @@ -133,7 +132,7 @@ pub enum BacktraceStatus { enum Inner { Unsupported, Disabled, - Captured(LazilyResolvedCapture), + Captured(Mutex), } struct Capture { @@ -172,11 +171,12 @@ enum BytesOrWide { impl fmt::Debug for Backtrace { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - let capture = match &self.inner { + let mut capture = match &self.inner { Inner::Unsupported => return fmt.write_str(""), Inner::Disabled => return fmt.write_str(""), - Inner::Captured(c) => c.force(), + Inner::Captured(c) => c.lock().unwrap(), }; + capture.resolve(); let frames = &capture.frames[capture.actual_start..]; @@ -331,7 +331,7 @@ impl Backtrace { let inner = if frames.is_empty() { Inner::Unsupported } else { - Inner::Captured(LazilyResolvedCapture::new(Capture { + Inner::Captured(Mutex::new(Capture { actual_start: actual_start.unwrap_or(0), frames, resolved: false, @@ -355,11 +355,12 @@ impl Backtrace { impl fmt::Display for Backtrace { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - let capture = match &self.inner { + let mut capture = match &self.inner { Inner::Unsupported => return fmt.write_str("unsupported backtrace"), Inner::Disabled => return fmt.write_str("disabled backtrace"), - Inner::Captured(c) => c.force(), + Inner::Captured(c) => c.lock().unwrap(), }; + capture.resolve(); let full = fmt.alternate(); let (frames, style) = if full { @@ -403,33 +404,6 @@ impl fmt::Display for Backtrace { } } -struct LazilyResolvedCapture { - sync: Once, - capture: UnsafeCell, -} - -impl LazilyResolvedCapture { - fn new(capture: Capture) -> Self { - LazilyResolvedCapture { sync: Once::new(), capture: UnsafeCell::new(capture) } - } - - fn force(&self) -> &Capture { - self.sync.call_once(|| { - // SAFETY: This exclusive reference can't overlap with any others - // `Once` guarantees callers will block until this closure returns - // `Once` also guarantees only a single caller will enter this closure - unsafe { &mut *self.capture.get() }.resolve(); - }); - - // SAFETY: This shared reference can't overlap with the exclusive reference above - unsafe { &*self.capture.get() } - } -} - -// SAFETY: Access to the inner value is synchronized using a thread-safe `Once` -// So long as `Capture` is `Sync`, `LazilyResolvedCapture` is too -unsafe impl Sync for LazilyResolvedCapture where Capture: Sync {} - impl Capture { fn resolve(&mut self) { // If we're already resolved, nothing to do! diff --git a/library/std/src/backtrace/tests.rs b/library/std/src/backtrace/tests.rs index 31cf0f702185c..f5f74d1eb9ae6 100644 --- a/library/std/src/backtrace/tests.rs +++ b/library/std/src/backtrace/tests.rs @@ -3,7 +3,7 @@ use super::*; #[test] fn test_debug() { let backtrace = Backtrace { - inner: Inner::Captured(LazilyResolvedCapture::new(Capture { + inner: Inner::Captured(Mutex::new(Capture { actual_start: 1, resolved: true, frames: vec![ @@ -54,7 +54,4 @@ fn test_debug() { \n]"; assert_eq!(format!("{:#?}", backtrace), expected); - - // Format the backtrace a second time, just to make sure lazily resolved state is stable - assert_eq!(format!("{:#?}", backtrace), expected); } diff --git a/library/std/src/collections/hash/map.rs b/library/std/src/collections/hash/map.rs index 829fc3817af2d..0680b1fc32975 100644 --- a/library/std/src/collections/hash/map.rs +++ b/library/std/src/collections/hash/map.rs @@ -52,9 +52,6 @@ use crate::sys; /// hash, as determined by the [`Hash`] trait, or its equality, as determined by /// the [`Eq`] trait, changes while it is in the map. This is normally only /// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code. -/// The behavior resulting from such a logic error is not specified, but will -/// not result in undefined behavior. This could include panics, incorrect results, -/// aborts, memory leaks, and non-termination. /// /// The hash table implementation is a Rust port of Google's [SwissTable]. /// The original C++ version of SwissTable can be found [here], and this diff --git a/library/std/src/collections/hash/set.rs b/library/std/src/collections/hash/set.rs index baa3026ff7514..f49e5801c3535 100644 --- a/library/std/src/collections/hash/set.rs +++ b/library/std/src/collections/hash/set.rs @@ -37,9 +37,7 @@ use super::map::{map_try_reserve_error, RandomState}; /// item's hash, as determined by the [`Hash`] trait, or its equality, as /// determined by the [`Eq`] trait, changes while it is in the set. This is /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or -/// unsafe code. The behavior resulting from such a logic error is not -/// specified, but will not result in undefined behavior. This could include -/// panics, incorrect results, aborts, memory leaks, and non-termination. +/// unsafe code. /// /// # Examples /// diff --git a/library/std/src/ffi/c_str.rs b/library/std/src/ffi/c_str.rs index 230ef0b23db6d..60b642a6dba44 100644 --- a/library/std/src/ffi/c_str.rs +++ b/library/std/src/ffi/c_str.rs @@ -86,7 +86,7 @@ use crate::sys; /// use std::ffi::CString; /// use std::os::raw::c_char; /// -/// extern "C" { +/// extern { /// fn my_printer(s: *const c_char); /// } /// @@ -144,7 +144,7 @@ pub struct CString { /// use std::ffi::CStr; /// use std::os::raw::c_char; /// -/// extern "C" { fn my_string() -> *const c_char; } +/// extern { fn my_string() -> *const c_char; } /// /// unsafe { /// let slice = CStr::from_ptr(my_string()); @@ -159,7 +159,7 @@ pub struct CString { /// use std::os::raw::c_char; /// /// fn work(data: &CStr) { -/// extern "C" { fn work_with(data: *const c_char); } +/// extern { fn work_with(data: *const c_char); } /// /// unsafe { work_with(data.as_ptr()) } /// } @@ -174,7 +174,7 @@ pub struct CString { /// use std::ffi::CStr; /// use std::os::raw::c_char; /// -/// extern "C" { fn my_string() -> *const c_char; } +/// extern { fn my_string() -> *const c_char; } /// /// fn my_string_safe() -> String { /// unsafe { @@ -359,7 +359,7 @@ impl CString { /// use std::ffi::CString; /// use std::os::raw::c_char; /// - /// extern "C" { fn puts(s: *const c_char); } + /// extern { fn puts(s: *const c_char); } /// /// let to_print = CString::new("Hello!").expect("CString::new failed"); /// unsafe { @@ -465,7 +465,7 @@ impl CString { /// use std::ffi::CString; /// use std::os::raw::c_char; /// - /// extern "C" { + /// extern { /// fn some_extern_function(s: *mut c_char); /// } /// @@ -1147,7 +1147,7 @@ impl CStr { /// use std::ffi::CStr; /// use std::os::raw::c_char; /// - /// extern "C" { + /// extern { /// fn my_string() -> *const c_char; /// } /// diff --git a/library/std/src/io/buffered/bufreader.rs b/library/std/src/io/buffered/bufreader.rs index 8bae3da1273eb..16c18d6e14645 100644 --- a/library/std/src/io/buffered/bufreader.rs +++ b/library/std/src/io/buffered/bufreader.rs @@ -271,20 +271,6 @@ impl Read for BufReader { Ok(nread) } - // Small read_exacts from a BufReader are extremely common when used with a deserializer. - // The default implementation calls read in a loop, which results in surprisingly poor code - // generation for the common path where the buffer has enough bytes to fill the passed-in - // buffer. - fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { - if self.buffer().len() >= buf.len() { - buf.copy_from_slice(&self.buffer()[..buf.len()]); - self.consume(buf.len()); - return Ok(()); - } - - crate::io::default_read_exact(self, buf) - } - fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result { let total_len = bufs.iter().map(|b| b.len()).sum::(); if self.pos == self.cap && total_len >= self.buf.len() { diff --git a/library/std/src/io/buffered/bufwriter.rs b/library/std/src/io/buffered/bufwriter.rs index fa7bd0d72d157..3b3399860ba7d 100644 --- a/library/std/src/io/buffered/bufwriter.rs +++ b/library/std/src/io/buffered/bufwriter.rs @@ -1,9 +1,7 @@ -use crate::error; use crate::fmt; use crate::io::{ self, Error, ErrorKind, IntoInnerError, IoSlice, Seek, SeekFrom, Write, DEFAULT_BUF_SIZE, }; -use crate::mem; /// Wraps a writer and buffers its output. /// @@ -289,103 +287,6 @@ impl BufWriter { Ok(()) => Ok(self.inner.take().unwrap()), } } - - /// Disassembles this `BufWriter`, returning the underlying writer, and any buffered but - /// unwritten data. - /// - /// If the underlying writer panicked, it is not known what portion of the data was written. - /// In this case, we return `WriterPanicked` for the buffered data (from which the buffer - /// contents can still be recovered). - /// - /// `into_raw_parts` makes no attempt to flush data and cannot fail. - /// - /// # Examples - /// - /// ``` - /// #![feature(bufwriter_into_raw_parts)] - /// use std::io::{BufWriter, Write}; - /// - /// let mut buffer = [0u8; 10]; - /// let mut stream = BufWriter::new(buffer.as_mut()); - /// write!(stream, "too much data").unwrap(); - /// stream.flush().expect_err("it doesn't fit"); - /// let (recovered_writer, buffered_data) = stream.into_raw_parts(); - /// assert_eq!(recovered_writer.len(), 0); - /// assert_eq!(&buffered_data.unwrap(), b"ata"); - /// ``` - #[unstable(feature = "bufwriter_into_raw_parts", issue = "80690")] - pub fn into_raw_parts(mut self) -> (W, Result, WriterPanicked>) { - let buf = mem::take(&mut self.buf); - let buf = if !self.panicked { Ok(buf) } else { Err(WriterPanicked { buf }) }; - (self.inner.take().unwrap(), buf) - } -} - -#[unstable(feature = "bufwriter_into_raw_parts", issue = "80690")] -/// Error returned for the buffered data from `BufWriter::into_raw_parts`, when the underlying -/// writer has previously panicked. Contains the (possibly partly written) buffered data. -/// -/// # Example -/// -/// ``` -/// #![feature(bufwriter_into_raw_parts)] -/// use std::io::{self, BufWriter, Write}; -/// use std::panic::{catch_unwind, AssertUnwindSafe}; -/// -/// struct PanickingWriter; -/// impl Write for PanickingWriter { -/// fn write(&mut self, buf: &[u8]) -> io::Result { panic!() } -/// fn flush(&mut self) -> io::Result<()> { panic!() } -/// } -/// -/// let mut stream = BufWriter::new(PanickingWriter); -/// write!(stream, "some data").unwrap(); -/// let result = catch_unwind(AssertUnwindSafe(|| { -/// stream.flush().unwrap() -/// })); -/// assert!(result.is_err()); -/// let (recovered_writer, buffered_data) = stream.into_raw_parts(); -/// assert!(matches!(recovered_writer, PanickingWriter)); -/// assert_eq!(buffered_data.unwrap_err().into_inner(), b"some data"); -/// ``` -pub struct WriterPanicked { - buf: Vec, -} - -impl WriterPanicked { - /// Returns the perhaps-unwritten data. Some of this data may have been written by the - /// panicking call(s) to the underlying writer, so simply writing it again is not a good idea. - #[unstable(feature = "bufwriter_into_raw_parts", issue = "80690")] - pub fn into_inner(self) -> Vec { - self.buf - } - - const DESCRIPTION: &'static str = - "BufWriter inner writer panicked, what data remains unwritten is not known"; -} - -#[unstable(feature = "bufwriter_into_raw_parts", issue = "80690")] -impl error::Error for WriterPanicked { - #[allow(deprecated, deprecated_in_future)] - fn description(&self) -> &str { - Self::DESCRIPTION - } -} - -#[unstable(feature = "bufwriter_into_raw_parts", issue = "80690")] -impl fmt::Display for WriterPanicked { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", Self::DESCRIPTION) - } -} - -#[unstable(feature = "bufwriter_into_raw_parts", issue = "80690")] -impl fmt::Debug for WriterPanicked { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("WriterPanicked") - .field("buffer", &format_args!("{}/{}", self.buf.len(), self.buf.capacity())) - .finish() - } } #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/std/src/io/buffered/tests.rs b/library/std/src/io/buffered/tests.rs index f6c2b499567ab..66a64f667baa4 100644 --- a/library/std/src/io/buffered/tests.rs +++ b/library/std/src/io/buffered/tests.rs @@ -443,18 +443,6 @@ fn bench_buffered_reader(b: &mut test::Bencher) { b.iter(|| BufReader::new(io::empty())); } -#[bench] -fn bench_buffered_reader_small_reads(b: &mut test::Bencher) { - let data = (0..u8::MAX).cycle().take(1024 * 4).collect::>(); - b.iter(|| { - let mut reader = BufReader::new(&data[..]); - let mut buf = [0u8; 4]; - for _ in 0..1024 { - reader.read_exact(&mut buf).unwrap(); - } - }); -} - #[bench] fn bench_buffered_writer(b: &mut test::Bencher) { b.iter(|| BufWriter::new(io::sink())); diff --git a/library/std/src/io/mod.rs b/library/std/src/io/mod.rs index c87a56586c65e..7ad9e446c5997 100644 --- a/library/std/src/io/mod.rs +++ b/library/std/src/io/mod.rs @@ -366,6 +366,7 @@ where { let start_len = buf.len(); let mut g = Guard { len: buf.len(), buf }; + let ret; loop { if g.len == g.buf.len() { unsafe { @@ -384,20 +385,21 @@ where } } - let buf = &mut g.buf[g.len..]; - match r.read(buf) { - Ok(0) => return Ok(g.len - start_len), - Ok(n) => { - // We can't allow bogus values from read. If it is too large, the returned vec could have its length - // set past its capacity, or if it overflows the vec could be shortened which could create an invalid - // string if this is called via read_to_string. - assert!(n <= buf.len()); - g.len += n; + match r.read(&mut g.buf[g.len..]) { + Ok(0) => { + ret = Ok(g.len - start_len); + break; } + Ok(n) => g.len += n, Err(ref e) if e.kind() == ErrorKind::Interrupted => {} - Err(e) => return Err(e), + Err(e) => { + ret = Err(e); + break; + } } } + + ret } pub(crate) fn default_read_vectored(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result @@ -416,25 +418,6 @@ where write(buf) } -pub(crate) fn default_read_exact(this: &mut R, mut buf: &mut [u8]) -> Result<()> { - while !buf.is_empty() { - match this.read(buf) { - Ok(0) => break, - Ok(n) => { - let tmp = buf; - buf = &mut tmp[n..]; - } - Err(ref e) if e.kind() == ErrorKind::Interrupted => {} - Err(e) => return Err(e), - } - } - if !buf.is_empty() { - Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill whole buffer")) - } else { - Ok(()) - } -} - /// The `Read` trait allows for reading bytes from a source. /// /// Implementors of the `Read` trait are called 'readers'. @@ -785,8 +768,23 @@ pub trait Read { /// } /// ``` #[stable(feature = "read_exact", since = "1.6.0")] - fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> { - default_read_exact(self, buf) + fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> { + while !buf.is_empty() { + match self.read(buf) { + Ok(0) => break, + Ok(n) => { + let tmp = buf; + buf = &mut tmp[n..]; + } + Err(ref e) if e.kind() == ErrorKind::Interrupted => {} + Err(e) => return Err(e), + } + } + if !buf.is_empty() { + Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill whole buffer")) + } else { + Ok(()) + } } /// Creates a "by reference" adaptor for this instance of `Read`. @@ -946,54 +944,6 @@ pub trait Read { } } -/// Read all bytes from a [reader][Read] into a new [`String`]. -/// -/// This is a convenience function for [`Read::read_to_string`]. Using this -/// function avoids having to create a variable first and provides more type -/// safety since you can only get the buffer out if there were no errors. (If you -/// use [`Read::read_to_string`] you have to remember to check whether the read -/// succeeded because otherwise your buffer will be empty or only partially full.) -/// -/// # Performance -/// -/// The downside of this function's increased ease of use and type safety is -/// that it gives you less control over performance. For example, you can't -/// pre-allocate memory like you can using [`String::with_capacity`] and -/// [`Read::read_to_string`]. Also, you can't re-use the buffer if an error -/// occurs while reading. -/// -/// In many cases, this function's performance will be adequate and the ease of use -/// and type safety tradeoffs will be worth it. However, there are cases where you -/// need more control over performance, and in those cases you should definitely use -/// [`Read::read_to_string`] directly. -/// -/// # Errors -/// -/// This function forces you to handle errors because the output (the `String`) -/// is wrapped in a [`Result`]. See [`Read::read_to_string`] for the errors -/// that can occur. If any error occurs, you will get an [`Err`], so you -/// don't have to worry about your buffer being empty or partially full. -/// -/// # Examples -/// -/// ```no_run -/// #![feature(io_read_to_string)] -/// -/// # use std::io; -/// fn main() -> io::Result<()> { -/// let stdin = io::read_to_string(&mut io::stdin())?; -/// println!("Stdin was:"); -/// println!("{}", stdin); -/// Ok(()) -/// } -/// ``` -#[unstable(feature = "io_read_to_string", issue = "80218")] -pub fn read_to_string(reader: &mut R) -> Result { - let mut buf = String::new(); - reader.read_to_string(&mut buf)?; - Ok(buf) -} - /// A buffer type used with `Read::read_vectored`. /// /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be diff --git a/library/std/src/keyword_docs.rs b/library/std/src/keyword_docs.rs index 6b06539a0940f..417a54e9dffb0 100644 --- a/library/std/src/keyword_docs.rs +++ b/library/std/src/keyword_docs.rs @@ -401,7 +401,7 @@ mod enum_keyword {} /// /// ```rust /// #[no_mangle] -/// pub extern "C" fn callable_from_c(x: i32) -> bool { +/// pub extern fn callable_from_c(x: i32) -> bool { /// x % 3 == 0 /// } /// ``` diff --git a/library/std/src/sys/hermit/mutex.rs b/library/std/src/sys/hermit/mutex.rs index 885389ca54cd4..f988a019cfedb 100644 --- a/library/std/src/sys/hermit/mutex.rs +++ b/library/std/src/sys/hermit/mutex.rs @@ -1,10 +1,9 @@ use crate::cell::UnsafeCell; use crate::collections::VecDeque; use crate::ffi::c_void; -use crate::hint; use crate::ops::{Deref, DerefMut, Drop}; use crate::ptr; -use crate::sync::atomic::{AtomicUsize, Ordering}; +use crate::sync::atomic::{spin_loop_hint, AtomicUsize, Ordering}; use crate::sys::hermit::abi; /// This type provides a lock based on busy waiting to realize mutual exclusion @@ -47,7 +46,7 @@ impl Spinlock { fn obtain_lock(&self) { let ticket = self.queue.fetch_add(1, Ordering::SeqCst) + 1; while self.dequeue.load(Ordering::SeqCst) != ticket { - hint::spin_loop(); + spin_loop_hint(); } } diff --git a/library/std/src/sys/sgx/waitqueue/spin_mutex.rs b/library/std/src/sys/sgx/waitqueue/spin_mutex.rs index 7f1a671bab4eb..9140041c58414 100644 --- a/library/std/src/sys/sgx/waitqueue/spin_mutex.rs +++ b/library/std/src/sys/sgx/waitqueue/spin_mutex.rs @@ -2,9 +2,8 @@ mod tests; use crate::cell::UnsafeCell; -use crate::hint; use crate::ops::{Deref, DerefMut}; -use crate::sync::atomic::{AtomicBool, Ordering}; +use crate::sync::atomic::{spin_loop_hint, AtomicBool, Ordering}; #[derive(Default)] pub struct SpinMutex { @@ -33,7 +32,7 @@ impl SpinMutex { match self.try_lock() { None => { while self.lock.load(Ordering::Relaxed) { - hint::spin_loop() + spin_loop_hint() } } Some(guard) => return guard, diff --git a/library/std/src/sys/unix/ext/process.rs b/library/std/src/sys/unix/ext/process.rs index f4c67b225e6e1..3615a8a5ee8b0 100644 --- a/library/std/src/sys/unix/ext/process.rs +++ b/library/std/src/sys/unix/ext/process.rs @@ -9,14 +9,6 @@ use crate::process; use crate::sys; use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; -mod private { - /// This trait being unreachable from outside the crate - /// prevents other implementations of the `ExitStatusExt` trait, - /// which allows potentially adding more trait methods in the future. - #[stable(feature = "none", since = "1.51.0")] - pub trait Sealed {} -} - /// Unix-specific extensions to the [`process::Command`] builder. #[stable(feature = "rust1", since = "1.0.0")] pub trait CommandExt { @@ -171,48 +163,18 @@ impl CommandExt for process::Command { } /// Unix-specific extensions to [`process::ExitStatus`]. -/// -/// This trait is sealed: it cannot be implemented outside the standard library. -/// This is so that future additional methods are not breaking changes. #[stable(feature = "rust1", since = "1.0.0")] -pub trait ExitStatusExt: private::Sealed { +pub trait ExitStatusExt { /// Creates a new `ExitStatus` from the raw underlying `i32` return value of /// a process. #[stable(feature = "exit_status_from", since = "1.12.0")] fn from_raw(raw: i32) -> Self; /// If the process was terminated by a signal, returns that signal. - /// - /// In other words, if `WIFSIGNALED`, this returns `WTERMSIG`. #[stable(feature = "rust1", since = "1.0.0")] fn signal(&self) -> Option; - - /// If the process was terminated by a signal, says whether it dumped core. - #[unstable(feature = "unix_process_wait_more", issue = "80695")] - fn core_dumped(&self) -> bool; - - /// If the process was stopped by a signal, returns that signal. - /// - /// In other words, if `WIFSTOPPED`, this returns `WSTOPSIG`. This is only possible if the status came from - /// a `wait` system call which was passed `WUNTRACED`, was then converted into an `ExitStatus`. - #[unstable(feature = "unix_process_wait_more", issue = "80695")] - fn stopped_signal(&self) -> Option; - - /// Whether the process was continued from a stopped status. - /// - /// Ie, `WIFCONTINUED`. This is only possible if the status came from a `wait` system call - /// which was passed `WCONTINUED`, was then converted into an `ExitStatus`. - #[unstable(feature = "unix_process_wait_more", issue = "80695")] - fn continued(&self) -> bool; - - /// Returns the underlying raw `wait` status. - #[unstable(feature = "unix_process_wait_more", issue = "80695")] - fn into_raw(self) -> i32; } -#[stable(feature = "none", since = "1.51.0")] -impl private::Sealed for process::ExitStatus {} - #[stable(feature = "rust1", since = "1.0.0")] impl ExitStatusExt for process::ExitStatus { fn from_raw(raw: i32) -> Self { @@ -222,22 +184,6 @@ impl ExitStatusExt for process::ExitStatus { fn signal(&self) -> Option { self.as_inner().signal() } - - fn core_dumped(&self) -> bool { - self.as_inner().core_dumped() - } - - fn stopped_signal(&self) -> Option { - self.as_inner().stopped_signal() - } - - fn continued(&self) -> bool { - self.as_inner().continued() - } - - fn into_raw(self) -> i32 { - self.as_inner().into_raw().into() - } } #[stable(feature = "process_extensions", since = "1.2.0")] diff --git a/library/std/src/sys/unix/process/process_fuchsia.rs b/library/std/src/sys/unix/process/process_fuchsia.rs index 0d4703d7f503a..b64636c3f3d15 100644 --- a/library/std/src/sys/unix/process/process_fuchsia.rs +++ b/library/std/src/sys/unix/process/process_fuchsia.rs @@ -245,50 +245,6 @@ impl ExitStatus { pub fn signal(&self) -> Option { None } - - // FIXME: The actually-Unix implementation in process_unix.rs uses WSTOPSIG, WCOREDUMP et al. - // I infer from the implementation of `success`, `code` and `signal` above that these are not - // available on Fuchsia. - // - // It does not appear that Fuchsia is Unix-like enough to implement ExitStatus (or indeed many - // other things from std::os::unix) properly. This veneer is always going to be a bodge. So - // while I don't know if these implementations are actually correct, I think they will do for - // now at least. - pub fn core_dumped(&self) -> bool { - false - } - pub fn stopped_signal(&self) -> Option { - None - } - pub fn continued(&self) -> bool { - false - } - - pub fn into_raw(&self) -> c_int { - // We don't know what someone who calls into_raw() will do with this value, but it should - // have the conventional Unix representation. Despite the fact that this is not - // standardised in SuS or POSIX, all Unix systems encode the signal and exit status the - // same way. (Ie the WIFEXITED, WEXITSTATUS etc. macros have identical behaviour on every - // Unix.) - // - // The caller of `std::os::unix::into_raw` is probably wanting a Unix exit status, and may - // do their own shifting and masking, or even pass the status to another computer running a - // different Unix variant. - // - // The other view would be to say that the caller on Fuchsia ought to know that `into_raw` - // will give a raw Fuchsia status (whatever that is - I don't know, personally). That is - // not possible here becaause we must return a c_int because that's what Unix (including - // SuS and POSIX) say a wait status is, but Fuchsia apparently uses a u64, so it won't - // necessarily fit. - // - // It seems to me that that the right answer would be to provide std::os::fuchsia with its - // own ExitStatusExt, rather that trying to provide a not very convincing imitation of - // Unix. Ie, std::os::unix::process:ExitStatusExt ought not to exist on Fuchsia. But - // fixing this up that is beyond the scope of my efforts now. - let exit_status_as_if_unix: u8 = self.0.try_into().expect("Fuchsia process return code bigger than 8 bits, but std::os::unix::ExitStatusExt::into_raw() was called to try to convert the value into a traditional Unix-style wait status, which cannot represent values greater than 255."); - let wait_status_as_if_unix = (exit_status_as_if_unix as c_int) << 8; - wait_status_as_if_unix - } } /// Converts a raw `c_int` to a type-safe `ExitStatus` by wrapping it without copying. diff --git a/library/std/src/sys/unix/process/process_unix.rs b/library/std/src/sys/unix/process/process_unix.rs index ddcb404c60ebc..a590c74435639 100644 --- a/library/std/src/sys/unix/process/process_unix.rs +++ b/library/std/src/sys/unix/process/process_unix.rs @@ -314,20 +314,10 @@ impl Command { ) -> libc::c_int } let addchdir = match self.get_cwd() { - Some(cwd) => { - if cfg!(target_os = "macos") { - // There is a bug in macOS where a relative executable - // path like "../myprogram" will cause `posix_spawn` to - // successfully launch the program, but erroneously return - // ENOENT when used with posix_spawn_file_actions_addchdir_np - // which was introduced in macOS 10.15. - return Ok(None); - } - match posix_spawn_file_actions_addchdir_np.get() { - Some(f) => Some((f, cwd)), - None => return Ok(None), - } - } + Some(cwd) => match posix_spawn_file_actions_addchdir_np.get() { + Some(f) => Some((f, cwd)), + None => return Ok(None), + }, None => None, }; @@ -489,23 +479,7 @@ impl ExitStatus { } pub fn signal(&self) -> Option { - if libc::WIFSIGNALED(self.0) { Some(libc::WTERMSIG(self.0)) } else { None } - } - - pub fn core_dumped(&self) -> bool { - libc::WIFSIGNALED(self.0) && libc::WCOREDUMP(self.0) - } - - pub fn stopped_signal(&self) -> Option { - if libc::WIFSTOPPED(self.0) { Some(libc::WSTOPSIG(self.0)) } else { None } - } - - pub fn continued(&self) -> bool { - libc::WIFCONTINUED(self.0) - } - - pub fn into_raw(&self) -> c_int { - self.0 + if !self.exited() { Some(libc::WTERMSIG(self.0)) } else { None } } } diff --git a/library/std/src/sys/unix/weak.rs b/library/std/src/sys/unix/weak.rs index 432fe4c33bcc4..e93a4972caa3e 100644 --- a/library/std/src/sys/unix/weak.rs +++ b/library/std/src/sys/unix/weak.rs @@ -28,7 +28,7 @@ use crate::sync::atomic::{self, AtomicUsize, Ordering}; macro_rules! weak { (fn $name:ident($($t:ty),*) -> $ret:ty) => ( - static $name: crate::sys::weak::Weak $ret> = + static $name: crate::sys::weak::Weak $ret> = crate::sys::weak::Weak::new(concat!(stringify!($name), '\0')); ) } diff --git a/library/std/src/sys/wasi/fs.rs b/library/std/src/sys/wasi/fs.rs index 4134ef676719c..120b9f59f1e99 100644 --- a/library/std/src/sys/wasi/fs.rs +++ b/library/std/src/sys/wasi/fs.rs @@ -627,50 +627,33 @@ fn open_at(fd: &WasiFd, path: &Path, opts: &OpenOptions) -> io::Result { /// to any pre-opened file descriptor. fn open_parent(p: &Path) -> io::Result<(ManuallyDrop, PathBuf)> { let p = CString::new(p.as_os_str().as_bytes())?; - let mut buf = Vec::::with_capacity(512); - loop { - unsafe { - let mut relative_path = buf.as_ptr().cast(); - let mut abs_prefix = ptr::null(); - let fd = __wasilibc_find_relpath( - p.as_ptr(), - &mut abs_prefix, - &mut relative_path, - buf.capacity(), + unsafe { + let mut ret = ptr::null(); + let fd = __wasilibc_find_relpath(p.as_ptr(), &mut ret); + if fd == -1 { + let msg = format!( + "failed to find a pre-opened file descriptor \ + through which {:?} could be opened", + p ); - if fd == -1 { - if io::Error::last_os_error().raw_os_error() == Some(libc::ENOMEM) { - // Trigger the internal buffer resizing logic of `Vec` by requiring - // more space than the current capacity. - let cap = buf.capacity(); - buf.set_len(cap); - buf.reserve(1); - continue; - } - let msg = format!( - "failed to find a pre-opened file descriptor \ - through which {:?} could be opened", - p - ); - return Err(io::Error::new(io::ErrorKind::Other, msg)); - } - let len = CStr::from_ptr(buf.as_ptr().cast()).to_bytes().len(); - buf.set_len(len); - buf.shrink_to_fit(); - - return Ok(( - ManuallyDrop::new(WasiFd::from_raw(fd as u32)), - PathBuf::from(OsString::from_vec(buf)), - )); + return Err(io::Error::new(io::ErrorKind::Other, msg)); } + let path = Path::new(OsStr::from_bytes(CStr::from_ptr(ret).to_bytes())); + + // FIXME: right now `path` is a pointer into `p`, the `CString` above. + // When we return `p` is deallocated and we can't use it, so we need to + // currently separately allocate `path`. If this becomes an issue though + // we should probably turn this into a closure-taking interface or take + // `&CString` and then pass off `&Path` tied to the same lifetime. + let path = path.to_path_buf(); + + return Ok((ManuallyDrop::new(WasiFd::from_raw(fd as u32)), path)); } extern "C" { pub fn __wasilibc_find_relpath( path: *const libc::c_char, - abs_prefix: *mut *const libc::c_char, relative_path: *mut *const libc::c_char, - relative_path_len: libc::size_t, ) -> libc::c_int; } } diff --git a/library/std/src/sys/wasi/os.rs b/library/std/src/sys/wasi/os.rs index 185d6109cb93e..33c796ae9415d 100644 --- a/library/std/src/sys/wasi/os.rs +++ b/library/std/src/sys/wasi/os.rs @@ -13,16 +13,6 @@ use crate::sys::memchr; use crate::sys::{unsupported, Void}; use crate::vec; -// Add a few symbols not in upstream `libc` just yet. -mod libc { - pub use libc::*; - - extern "C" { - pub fn getcwd(buf: *mut c_char, size: size_t) -> *mut c_char; - pub fn chdir(dir: *const c_char) -> c_int; - } -} - #[cfg(not(target_feature = "atomics"))] pub unsafe fn env_lock() -> impl Any { // No need for a lock if we're single-threaded, but this function will need @@ -51,40 +41,11 @@ pub fn error_string(errno: i32) -> String { } pub fn getcwd() -> io::Result { - let mut buf = Vec::with_capacity(512); - loop { - unsafe { - let ptr = buf.as_mut_ptr() as *mut libc::c_char; - if !libc::getcwd(ptr, buf.capacity()).is_null() { - let len = CStr::from_ptr(buf.as_ptr() as *const libc::c_char).to_bytes().len(); - buf.set_len(len); - buf.shrink_to_fit(); - return Ok(PathBuf::from(OsString::from_vec(buf))); - } else { - let error = io::Error::last_os_error(); - if error.raw_os_error() != Some(libc::ERANGE) { - return Err(error); - } - } - - // Trigger the internal buffer resizing logic of `Vec` by requiring - // more space than the current capacity. - let cap = buf.capacity(); - buf.set_len(cap); - buf.reserve(1); - } - } + unsupported() } -pub fn chdir(p: &path::Path) -> io::Result<()> { - let p: &OsStr = p.as_ref(); - let p = CString::new(p.as_bytes())?; - unsafe { - match libc::chdir(p.as_ptr()) == (0 as libc::c_int) { - true => Ok(()), - false => Err(io::Error::last_os_error()), - } - } +pub fn chdir(_: &path::Path) -> io::Result<()> { + unsupported() } pub struct SplitPaths<'a>(&'a Void); diff --git a/library/std/src/sys/windows/ext/process.rs b/library/std/src/sys/windows/ext/process.rs index 7a92381d6609b..61e4c6a1d1718 100644 --- a/library/std/src/sys/windows/ext/process.rs +++ b/library/std/src/sys/windows/ext/process.rs @@ -7,14 +7,6 @@ use crate::process; use crate::sys; use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; -mod private { - /// This trait being unreachable from outside the crate - /// prevents other implementations of the `ExitStatusExt` trait, - /// which allows potentially adding more trait methods in the future. - #[stable(feature = "none", since = "1.51.0")] - pub trait Sealed {} -} - #[stable(feature = "process_extensions", since = "1.2.0")] impl FromRawHandle for process::Stdio { unsafe fn from_raw_handle(handle: RawHandle) -> process::Stdio { @@ -81,11 +73,8 @@ impl IntoRawHandle for process::ChildStderr { } /// Windows-specific extensions to [`process::ExitStatus`]. -/// -/// This trait is sealed: it cannot be implemented outside the standard library. -/// This is so that future additional methods are not breaking changes. #[stable(feature = "exit_status_from", since = "1.12.0")] -pub trait ExitStatusExt: private::Sealed { +pub trait ExitStatusExt { /// Creates a new `ExitStatus` from the raw underlying `u32` return value of /// a process. #[stable(feature = "exit_status_from", since = "1.12.0")] @@ -99,9 +88,6 @@ impl ExitStatusExt for process::ExitStatus { } } -#[stable(feature = "none", since = "1.51.0")] -impl private::Sealed for process::ExitStatus {} - /// Windows-specific extensions to the [`process::Command`] builder. #[stable(feature = "windows_process_extensions", since = "1.16.0")] pub trait CommandExt { diff --git a/library/std/src/thread/mod.rs b/library/std/src/thread/mod.rs index 0d004a516f594..5d65f960fcd39 100644 --- a/library/std/src/thread/mod.rs +++ b/library/std/src/thread/mod.rs @@ -1186,37 +1186,32 @@ impl fmt::Debug for Thread { /// the [`Error`](crate::error::Error) trait. /// /// Thus, a sensible way to handle a thread panic is to either: -/// -/// 1. propagate the panic with [`std::panic::resume_unwind`] +/// 1. `unwrap` the `Result`, propagating the panic /// 2. or in case the thread is intended to be a subsystem boundary /// that is supposed to isolate system-level failures, -/// match on the `Err` variant and handle the panic in an appropriate way +/// match on the `Err` variant and handle the panic in an appropriate way. /// /// A thread that completes without panicking is considered to exit successfully. /// /// # Examples /// -/// Matching on the result of a joined thread: -/// /// ```no_run -/// use std::{fs, thread, panic}; +/// use std::thread; +/// use std::fs; /// /// fn copy_in_thread() -> thread::Result<()> { -/// thread::spawn(|| { -/// fs::copy("foo.txt", "bar.txt").unwrap(); -/// }).join() +/// thread::spawn(move || { fs::copy("foo.txt", "bar.txt").unwrap(); }).join() /// } /// /// fn main() { /// match copy_in_thread() { -/// Ok(_) => println!("copy succeeded"), -/// Err(e) => panic::resume_unwind(e), +/// Ok(_) => println!("this is fine"), +/// Err(_) => println!("thread panicked"), /// } /// } /// ``` /// /// [`Result`]: crate::result::Result -/// [`std::panic::resume_unwind`]: crate::panic::resume_unwind #[stable(feature = "rust1", since = "1.0.0")] pub type Result = crate::result::Result>; diff --git a/src/bootstrap/bootstrap.py b/src/bootstrap/bootstrap.py index 5350c9eefe753..6d2d7bbbef92c 100644 --- a/src/bootstrap/bootstrap.py +++ b/src/bootstrap/bootstrap.py @@ -465,21 +465,8 @@ def download_stage0(self): def downloading_llvm(self): opt = self.get_toml('download-ci-llvm', 'llvm') - # This is currently all tier 1 targets (since others may not have CI - # artifacts) - # https://doc.rust-lang.org/rustc/platform-support.html#tier-1 - supported_platforms = [ - "aarch64-unknown-linux-gnu", - "i686-pc-windows-gnu", - "i686-pc-windows-msvc", - "i686-unknown-linux-gnu", - "x86_64-unknown-linux-gnu", - "x86_64-apple-darwin", - "x86_64-pc-windows-gnu", - "x86_64-pc-windows-msvc", - ] return opt == "true" \ - or (opt == "if-available" and self.build in supported_platforms) + or (opt == "if-available" and self.build == "x86_64-unknown-linux-gnu") def _download_stage0_helper(self, filename, pattern, tarball_suffix, date=None): if date is None: diff --git a/src/bootstrap/builder.rs b/src/bootstrap/builder.rs index 62065e27dd966..ec9ce4c820c69 100644 --- a/src/bootstrap/builder.rs +++ b/src/bootstrap/builder.rs @@ -814,22 +814,12 @@ impl<'a> Builder<'a> { cargo.env("REAL_LIBRARY_PATH", e); } - // Found with `rg "init_env_logger\("`. If anyone uses `init_env_logger` - // from out of tree it shouldn't matter, since x.py is only used for - // building in-tree. - let color_logs = ["RUSTDOC_LOG_COLOR", "RUSTC_LOG_COLOR", "RUST_LOG_COLOR"]; match self.build.config.color { Color::Always => { cargo.arg("--color=always"); - for log in &color_logs { - cargo.env(log, "always"); - } } Color::Never => { cargo.arg("--color=never"); - for log in &color_logs { - cargo.env(log, "never"); - } } Color::Auto => {} // nothing to do } diff --git a/src/bootstrap/check.rs b/src/bootstrap/check.rs index c19bb536ce83c..72a979338a549 100644 --- a/src/bootstrap/check.rs +++ b/src/bootstrap/check.rs @@ -73,7 +73,7 @@ impl Step for Std { fn run(self, builder: &Builder<'_>) { let target = self.target; - let compiler = builder.compiler(builder.top_stage, builder.config.build); + let compiler = builder.compiler(0, builder.config.build); let mut cargo = builder.cargo( compiler, @@ -84,10 +84,7 @@ impl Step for Std { ); std_cargo(builder, target, compiler.stage, &mut cargo); - builder.info(&format!( - "Checking stage{} std artifacts ({} -> {})", - builder.top_stage, &compiler.host, target - )); + builder.info(&format!("Checking std artifacts ({} -> {})", &compiler.host, target)); run_cargo( builder, cargo, @@ -97,13 +94,9 @@ impl Step for Std { true, ); - // We skip populating the sysroot in non-zero stage because that'll lead - // to rlib/rmeta conflicts if std gets built during this session. - if compiler.stage == 0 { - let libdir = builder.sysroot_libdir(compiler, target); - let hostdir = builder.sysroot_libdir(compiler, compiler.host); - add_to_sysroot(&builder, &libdir, &hostdir, &libstd_stamp(builder, compiler, target)); - } + let libdir = builder.sysroot_libdir(compiler, target); + let hostdir = builder.sysroot_libdir(compiler, compiler.host); + add_to_sysroot(&builder, &libdir, &hostdir, &libstd_stamp(builder, compiler, target)); // Then run cargo again, once we've put the rmeta files for the library // crates into the sysroot. This is needed because e.g., core's tests @@ -131,8 +124,8 @@ impl Step for Std { } builder.info(&format!( - "Checking stage{} std test/bench/example targets ({} -> {})", - builder.top_stage, &compiler.host, target + "Checking std test/bench/example targets ({} -> {})", + &compiler.host, target )); run_cargo( builder, @@ -170,20 +163,10 @@ impl Step for Rustc { /// the `compiler` targeting the `target` architecture. The artifacts /// created will also be linked into the sysroot directory. fn run(self, builder: &Builder<'_>) { - let compiler = builder.compiler(builder.top_stage, builder.config.build); + let compiler = builder.compiler(0, builder.config.build); let target = self.target; - if compiler.stage != 0 { - // If we're not in stage 0, then we won't have a std from the beta - // compiler around. That means we need to make sure there's one in - // the sysroot for the compiler to find. Otherwise, we're going to - // fail when building crates that need to generate code (e.g., build - // scripts and their dependencies). - builder.ensure(crate::compile::Std { target: compiler.host, compiler }); - builder.ensure(crate::compile::Std { target, compiler }); - } else { - builder.ensure(Std { target }); - } + builder.ensure(Std { target }); let mut cargo = builder.cargo( compiler, @@ -204,10 +187,7 @@ impl Step for Rustc { cargo.arg("-p").arg(krate.name); } - builder.info(&format!( - "Checking stage{} compiler artifacts ({} -> {})", - builder.top_stage, &compiler.host, target - )); + builder.info(&format!("Checking compiler artifacts ({} -> {})", &compiler.host, target)); run_cargo( builder, cargo, @@ -245,7 +225,7 @@ impl Step for CodegenBackend { } fn run(self, builder: &Builder<'_>) { - let compiler = builder.compiler(builder.top_stage, builder.config.build); + let compiler = builder.compiler(0, builder.config.build); let target = self.target; let backend = self.backend; @@ -264,8 +244,8 @@ impl Step for CodegenBackend { rustc_cargo_env(builder, &mut cargo, target); builder.info(&format!( - "Checking stage{} {} artifacts ({} -> {})", - builder.top_stage, backend, &compiler.host.triple, target.triple + "Checking {} artifacts ({} -> {})", + backend, &compiler.host.triple, target.triple )); run_cargo( @@ -300,7 +280,7 @@ macro_rules! tool_check_step { } fn run(self, builder: &Builder<'_>) { - let compiler = builder.compiler(builder.top_stage, builder.config.build); + let compiler = builder.compiler(0, builder.config.build); let target = self.target; builder.ensure(Rustc { target }); @@ -321,8 +301,7 @@ macro_rules! tool_check_step { } builder.info(&format!( - "Checking stage{} {} artifacts ({} -> {})", - builder.top_stage, + "Checking {} artifacts ({} -> {})", stringify!($name).to_lowercase(), &compiler.host.triple, target.triple diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index ec1308ab82b51..f4d89a89c1467 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -377,7 +377,6 @@ struct Build { configure_args: Option>, local_rebuild: Option, print_step_timings: Option, - check_stage: Option, doc_stage: Option, build_stage: Option, test_stage: Option, @@ -677,7 +676,6 @@ impl Config { // See https://github.com/rust-lang/compiler-team/issues/326 config.stage = match config.cmd { - Subcommand::Check { .. } => flags.stage.or(build.check_stage).unwrap_or(0), Subcommand::Doc { .. } => flags.stage.or(build.doc_stage).unwrap_or(0), Subcommand::Build { .. } => flags.stage.or(build.build_stage).unwrap_or(1), Subcommand::Test { .. } => flags.stage.or(build.test_stage).unwrap_or(1), @@ -687,6 +685,7 @@ impl Config { // These are all bootstrap tools, which don't depend on the compiler. // The stage we pass shouldn't matter, but use 0 just in case. Subcommand::Clean { .. } + | Subcommand::Check { .. } | Subcommand::Clippy { .. } | Subcommand::Fix { .. } | Subcommand::Run { .. } @@ -817,10 +816,8 @@ impl Config { check_ci_llvm!(llvm.allow_old_toolchain); check_ci_llvm!(llvm.polly); - // CI-built LLVM can be either dynamic or static. - let ci_llvm = config.out.join(&*config.build.triple).join("ci-llvm"); - let link_type = t!(std::fs::read_to_string(ci_llvm.join("link-type.txt"))); - config.llvm_link_shared = link_type == "dynamic"; + // CI-built LLVM is shared + config.llvm_link_shared = true; } if config.llvm_thin_lto { diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index af9c0fb04bc9d..e2c2e19b0bc17 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -1800,11 +1800,19 @@ fn add_env(builder: &Builder<'_>, cmd: &mut Command, target: TargetSelection) { } } -/// Maybe add LLVM object files to the given destination lib-dir. Allows either static or dynamic linking. +/// Maybe add libLLVM.so to the given destination lib-dir. It will only have +/// been built if LLVM tools are linked dynamically. /// +/// Note: This function does not yet support Windows, but we also don't support +/// linking LLVM tools dynamically on Windows yet. +fn maybe_install_llvm(builder: &Builder<'_>, target: TargetSelection, dst_libdir: &Path) { + if !builder.config.llvm_link_shared { + // We do not need to copy LLVM files into the sysroot if it is not + // dynamically linked; it is already included into librustc_llvm + // statically. + return; + } -/// Returns whether the files were actually copied. -fn maybe_install_llvm(builder: &Builder<'_>, target: TargetSelection, dst_libdir: &Path) -> bool { if let Some(config) = builder.config.target_config.get(&target) { if config.llvm_config.is_some() && !builder.config.llvm_from_ci { // If the LLVM was externally provided, then we don't currently copy @@ -1820,7 +1828,7 @@ fn maybe_install_llvm(builder: &Builder<'_>, target: TargetSelection, dst_libdir // // If the LLVM is coming from ourselves (just from CI) though, we // still want to install it, as it otherwise won't be available. - return false; + return; } } @@ -1829,48 +1837,31 @@ fn maybe_install_llvm(builder: &Builder<'_>, target: TargetSelection, dst_libdir // clear why this is the case, though. llvm-config will emit the versioned // paths and we don't want those in the sysroot (as we're expecting // unversioned paths). - if target.contains("apple-darwin") && builder.config.llvm_link_shared { + if target.contains("apple-darwin") { let src_libdir = builder.llvm_out(target).join("lib"); let llvm_dylib_path = src_libdir.join("libLLVM.dylib"); if llvm_dylib_path.exists() { builder.install(&llvm_dylib_path, dst_libdir, 0o644); } - !builder.config.dry_run } else if let Ok(llvm_config) = crate::native::prebuilt_llvm_config(builder, target) { - let mut cmd = Command::new(llvm_config); - cmd.arg("--libfiles"); - builder.verbose(&format!("running {:?}", cmd)); - let files = output(&mut cmd); - for file in files.trim_end().split(' ') { + let files = output(Command::new(llvm_config).arg("--libfiles")); + for file in files.lines() { builder.install(Path::new(file), dst_libdir, 0o644); } - !builder.config.dry_run - } else { - false } } /// Maybe add libLLVM.so to the target lib-dir for linking. pub fn maybe_install_llvm_target(builder: &Builder<'_>, target: TargetSelection, sysroot: &Path) { let dst_libdir = sysroot.join("lib/rustlib").join(&*target.triple).join("lib"); - // We do not need to copy LLVM files into the sysroot if it is not - // dynamically linked; it is already included into librustc_llvm - // statically. - if builder.config.llvm_link_shared { - maybe_install_llvm(builder, target, &dst_libdir); - } + maybe_install_llvm(builder, target, &dst_libdir); } /// Maybe add libLLVM.so to the runtime lib-dir for rustc itself. pub fn maybe_install_llvm_runtime(builder: &Builder<'_>, target: TargetSelection, sysroot: &Path) { let dst_libdir = sysroot.join(builder.sysroot_libdir_relative(Compiler { stage: 1, host: target })); - // We do not need to copy LLVM files into the sysroot if it is not - // dynamically linked; it is already included into librustc_llvm - // statically. - if builder.config.llvm_link_shared { - maybe_install_llvm(builder, target, &dst_libdir); - } + maybe_install_llvm(builder, target, &dst_libdir); } #[derive(Clone, Debug, Eq, Hash, PartialEq)] @@ -1982,10 +1973,7 @@ impl Step for RustDev { // `$ORIGIN/../lib` can find it. It may also be used as a dependency // of `rustc-dev` to support the inherited `-lLLVM` when using the // compiler libraries. - let dst_libdir = tarball.image_dir().join("lib"); - maybe_install_llvm(builder, target, &dst_libdir); - let link_type = if builder.config.llvm_link_shared { "dynamic" } else { "static" }; - t!(std::fs::write(tarball.image_dir().join("link-type.txt"), link_type), dst_libdir); + maybe_install_llvm(builder, target, &tarball.image_dir().join("lib")); Some(tarball.generate()) } diff --git a/src/bootstrap/download-ci-llvm-stamp b/src/bootstrap/download-ci-llvm-stamp index fb5b058cb4d74..b29ecd65401df 100644 --- a/src/bootstrap/download-ci-llvm-stamp +++ b/src/bootstrap/download-ci-llvm-stamp @@ -1,4 +1,4 @@ Change this file to make users of the `download-ci-llvm` configuration download a new version of LLVM from CI, even if the LLVM submodule hasn’t changed. -Last change is for: https://github.com/rust-lang/rust/pull/80932 +Last change is for: https://github.com/rust-lang/rust/pull/80087 diff --git a/src/bootstrap/flags.rs b/src/bootstrap/flags.rs index 55062e11e029a..d6a45f1c17076 100644 --- a/src/bootstrap/flags.rs +++ b/src/bootstrap/flags.rs @@ -614,10 +614,14 @@ Arguments: }; if let Subcommand::Check { .. } = &cmd { + if matches.opt_str("stage").is_some() { + println!("--stage not supported for x.py check, always treated as stage 0"); + process::exit(1); + } if matches.opt_str("keep-stage").is_some() || matches.opt_str("keep-stage-std").is_some() { - println!("--keep-stage not yet supported for x.py check"); + println!("--keep-stage not supported for x.py check, only one stage available"); process::exit(1); } } diff --git a/src/bootstrap/native.rs b/src/bootstrap/native.rs index 609ac8b366952..6412df3fd904e 100644 --- a/src/bootstrap/native.rs +++ b/src/bootstrap/native.rs @@ -171,6 +171,7 @@ impl Step for Llvm { .define("LLVM_TARGETS_TO_BUILD", llvm_targets) .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets) .define("LLVM_INCLUDE_EXAMPLES", "OFF") + .define("LLVM_INCLUDE_TESTS", "OFF") .define("LLVM_INCLUDE_DOCS", "OFF") .define("LLVM_INCLUDE_BENCHMARKS", "OFF") .define("LLVM_ENABLE_TERMINFO", "OFF") diff --git a/src/bootstrap/test.rs b/src/bootstrap/test.rs index 335a173100290..2e8c574044ed9 100644 --- a/src/bootstrap/test.rs +++ b/src/bootstrap/test.rs @@ -1011,13 +1011,6 @@ note: if you're sure you want to do this, please open an issue as to why. In the cmd.arg("--rustdoc-path").arg(builder.rustdoc(compiler)); } - if mode == "rustdoc-json" { - // Use the beta compiler for jsondocck - let json_compiler = compiler.with_stage(0); - cmd.arg("--jsondocck-path") - .arg(builder.ensure(tool::JsonDocCk { compiler: json_compiler, target })); - } - if mode == "run-make" && suite.ends_with("fulldeps") { cmd.arg("--rust-demangler-path").arg(builder.tool_exe(Tool::RustDemangler)); } diff --git a/src/bootstrap/tool.rs b/src/bootstrap/tool.rs index 835b8beb0e7df..dc786249d9965 100644 --- a/src/bootstrap/tool.rs +++ b/src/bootstrap/tool.rs @@ -367,7 +367,6 @@ bootstrap_tool!( RustdocTheme, "src/tools/rustdoc-themes", "rustdoc-themes"; ExpandYamlAnchors, "src/tools/expand-yaml-anchors", "expand-yaml-anchors"; LintDocs, "src/tools/lint-docs", "lint-docs"; - JsonDocCk, "src/tools/jsondocck", "jsondocck"; ); #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)] diff --git a/src/ci/docker/host-x86_64/dist-various-2/build-wasi-toolchain.sh b/src/ci/docker/host-x86_64/dist-various-2/build-wasi-toolchain.sh index 82d0f7dc471e8..c6db200f8660f 100755 --- a/src/ci/docker/host-x86_64/dist-various-2/build-wasi-toolchain.sh +++ b/src/ci/docker/host-x86_64/dist-various-2/build-wasi-toolchain.sh @@ -1,16 +1,18 @@ #!/bin/sh +# +# ignore-tidy-linelength set -ex -# Originally from https://github.com/llvm/llvm-project/releases/download/llvmorg-11.0.0/clang+llvm-11.0.0-x86_64-linux-gnu-ubuntu-16.04.tar.xz -curl https://ci-mirrors.rust-lang.org/rustc/2021-01-14-clang%2Bllvm-11.0.1-x86_64-linux-gnu-ubuntu-16.04.tar.xz | \ +# Originally from https://github.com/llvm/llvm-project/releases/download/llvmorg-10.0.0/clang+llvm-10.0.0-x86_64-linux-gnu-ubuntu-18.04.tar.xz +curl https://ci-mirrors.rust-lang.org/rustc/clang%2Bllvm-10.0.0-x86_64-linux-gnu-ubuntu-18.04.tar.xz | \ tar xJf - -export PATH=`pwd`/clang+llvm-11.0.1-x86_64-linux-gnu-ubuntu-16.04/bin:$PATH +export PATH=`pwd`/clang+llvm-10.0.0-x86_64-linux-gnu-ubuntu-18.04/bin:$PATH git clone https://github.com/WebAssembly/wasi-libc cd wasi-libc -git reset --hard 58795582905e08fa7748846c1971b4ab911d1e16 +git reset --hard 215adc8ac9f91eb055311acc72683fd2eb1ae15a make -j$(nproc) INSTALL_DIR=/wasm32-wasi install cd .. diff --git a/src/doc/book b/src/doc/book index ac57a0ddd23d1..5bb44f8b5b0aa 160000 --- a/src/doc/book +++ b/src/doc/book @@ -1 +1 @@ -Subproject commit ac57a0ddd23d173b26731ccf939f3ba729753275 +Subproject commit 5bb44f8b5b0aa105c8b22602e9b18800484afa21 diff --git a/src/doc/embedded-book b/src/doc/embedded-book index ceec19e873be8..ba34b8a968f95 160000 --- a/src/doc/embedded-book +++ b/src/doc/embedded-book @@ -1 +1 @@ -Subproject commit ceec19e873be87c6ee5666b030c6bb612f889a96 +Subproject commit ba34b8a968f9531d38c4dc4411d5568b7c076bfe diff --git a/src/doc/nomicon b/src/doc/nomicon index a8584998eacde..a5a48441d411f 160000 --- a/src/doc/nomicon +++ b/src/doc/nomicon @@ -1 +1 @@ -Subproject commit a8584998eacdea7106a1dfafcbf6c1c06fcdf925 +Subproject commit a5a48441d411f61556b57d762b03d6874afe575d diff --git a/src/doc/reference b/src/doc/reference index 50af691f83893..b278478b76617 160000 --- a/src/doc/reference +++ b/src/doc/reference @@ -1 +1 @@ -Subproject commit 50af691f838937c300b47812d0507c6d88c14f97 +Subproject commit b278478b766178491a8b6f67afa4bcd6b64d977a diff --git a/src/doc/rust-by-example b/src/doc/rust-by-example index 03e23af01f0b4..1cce0737d6a7d 160000 --- a/src/doc/rust-by-example +++ b/src/doc/rust-by-example @@ -1 +1 @@ -Subproject commit 03e23af01f0b4f83a3a513da280e1ca92587f2ec +Subproject commit 1cce0737d6a7d3ceafb139b4a206861fb1dcb2ab diff --git a/src/doc/unstable-book/src/language-features/intra-doc-pointers.md b/src/doc/unstable-book/src/language-features/intra-doc-pointers.md deleted file mode 100644 index fbc83f4b4f489..0000000000000 --- a/src/doc/unstable-book/src/language-features/intra-doc-pointers.md +++ /dev/null @@ -1,15 +0,0 @@ -# `intra-doc-pointers` - -The tracking issue for this feature is: [#80896] - -[#80896]: https://github.com/rust-lang/rust/issues/80896 - ------------------------- - -Rustdoc does not currently allow disambiguating between `*const` and `*mut`, and -raw pointers in intra-doc links are unstable until it does. - -```rust -#![feature(intra_doc_pointers)] -//! [pointer::add] -``` diff --git a/src/doc/unstable-book/src/language-features/link-args.md b/src/doc/unstable-book/src/language-features/link-args.md index da36e1580012b..2507197661a9d 100644 --- a/src/doc/unstable-book/src/language-features/link-args.md +++ b/src/doc/unstable-book/src/language-features/link-args.md @@ -15,7 +15,7 @@ usage would be: #![feature(link_args)] #[link_args = "-foo -bar -baz"] -extern "C" {} +extern {} # fn main() {} ``` diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index 83114a72b8d5a..43fb53ba18fda 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -313,12 +313,12 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> { tcx: TyCtxt<'tcx>, pred: ty::Predicate<'tcx>, ) -> FxHashSet { - let bound_predicate = pred.kind(); + let bound_predicate = pred.bound_atom(); let regions = match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(poly_trait_pred, _) => { + ty::PredicateAtom::Trait(poly_trait_pred, _) => { tcx.collect_referenced_late_bound_regions(&bound_predicate.rebind(poly_trait_pred)) } - ty::PredicateKind::Projection(poly_proj_pred) => { + ty::PredicateAtom::Projection(poly_proj_pred) => { tcx.collect_referenced_late_bound_regions(&bound_predicate.rebind(poly_proj_pred)) } _ => return FxHashSet::default(), @@ -463,8 +463,8 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> { .iter() .filter(|p| { !orig_bounds.contains(p) - || match p.kind().skip_binder() { - ty::PredicateKind::Trait(pred, _) => pred.def_id() == sized_trait, + || match p.skip_binders() { + ty::PredicateAtom::Trait(pred, _) => pred.def_id() == sized_trait, _ => false, } }) diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index 916684baf855d..4c46771fd7170 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -121,7 +121,7 @@ crate fn try_inline( }; let target_attrs = load_attrs(cx, did); - let attrs = box merge_attrs(cx, Some(parent_module), target_attrs, attrs_clone); + let attrs = merge_attrs(cx, Some(parent_module), target_attrs, attrs_clone); cx.renderinfo.borrow_mut().inlined.insert(did); let what_rustc_thinks = clean::Item::from_def_id_and_parts(did, Some(name), kind, cx); @@ -358,16 +358,18 @@ crate fn build_impl( let impl_item = match did.as_local() { Some(did) => { let hir_id = tcx.hir().local_def_id_to_hir_id(did); - match &tcx.hir().expect_item(hir_id).kind { - hir::ItemKind::Impl(impl_) => Some(impl_), + match tcx.hir().expect_item(hir_id).kind { + hir::ItemKind::Impl { self_ty, ref generics, ref items, .. } => { + Some((self_ty, generics, items)) + } _ => panic!("`DefID` passed to `build_impl` is not an `impl"), } } None => None, }; - let for_ = match &impl_item { - Some(impl_) => impl_.self_ty.clean(cx), + let for_ = match impl_item { + Some((self_ty, _, _)) => self_ty.clean(cx), None => tcx.type_of(did).clean(cx), }; @@ -389,13 +391,9 @@ crate fn build_impl( let predicates = tcx.explicit_predicates_of(did); let (trait_items, generics) = match impl_item { - Some(impl_) => ( - impl_ - .items - .iter() - .map(|item| tcx.hir().impl_item(item.id).clean(cx)) - .collect::>(), - impl_.generics.clean(cx), + Some((_, generics, items)) => ( + items.iter().map(|item| tcx.hir().impl_item(item.id).clean(cx)).collect::>(), + generics.clean(cx), ), None => ( tcx.associated_items(did) @@ -446,7 +444,7 @@ crate fn build_impl( }), cx, ); - item.attrs = box merge_attrs(cx, parent_module.into(), load_attrs(cx, did), attrs); + item.attrs = merge_attrs(cx, parent_module.into(), load_attrs(cx, did), attrs); debug!("merged_attrs={:?}", item.attrs); ret.push(item); } @@ -468,7 +466,7 @@ fn build_module(cx: &DocContext<'_>, did: DefId, visited: &mut FxHashSet) // Primitive types can't be inlined so generate an import instead. items.push(clean::Item { name: None, - attrs: box clean::Attributes::default(), + attrs: clean::Attributes::default(), source: clean::Span::dummy(), def_id: DefId::local(CRATE_DEF_INDEX), visibility: clean::Public, diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 3ddb2adbf0aa7..14564e7f64aa5 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -219,6 +219,7 @@ impl Clean for CrateNum { impl Clean for doctree::Module<'_> { fn clean(&self, cx: &DocContext<'_>) -> Item { let mut items: Vec = vec![]; + items.extend(self.imports.iter().flat_map(|x| x.clean(cx))); items.extend(self.foreigns.iter().map(|x| x.clean(cx))); items.extend(self.mods.iter().map(|x| x.clean(cx))); items.extend(self.items.iter().map(|x| x.clean(cx)).flatten()); @@ -465,20 +466,20 @@ impl Clean for hir::WherePredicate<'_> { impl<'a> Clean> for ty::Predicate<'a> { fn clean(&self, cx: &DocContext<'_>) -> Option { - let bound_predicate = self.kind(); + let bound_predicate = self.bound_atom(); match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(pred, _) => Some(bound_predicate.rebind(pred).clean(cx)), - ty::PredicateKind::RegionOutlives(pred) => pred.clean(cx), - ty::PredicateKind::TypeOutlives(pred) => pred.clean(cx), - ty::PredicateKind::Projection(pred) => Some(pred.clean(cx)), - - ty::PredicateKind::Subtype(..) - | ty::PredicateKind::WellFormed(..) - | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) - | ty::PredicateKind::TypeWellFormedFromEnv(..) => panic!("not user writable"), + ty::PredicateAtom::Trait(pred, _) => Some(bound_predicate.rebind(pred).clean(cx)), + ty::PredicateAtom::RegionOutlives(pred) => pred.clean(cx), + ty::PredicateAtom::TypeOutlives(pred) => pred.clean(cx), + ty::PredicateAtom::Projection(pred) => Some(pred.clean(cx)), + + ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::WellFormed(..) + | ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) + | ty::PredicateAtom::TypeWellFormedFromEnv(..) => panic!("not user writable"), } } } @@ -743,19 +744,19 @@ impl<'a, 'tcx> Clean for (&'a ty::Generics, ty::GenericPredicates<'tcx .flat_map(|(p, _)| { let mut projection = None; let param_idx = (|| { - let bound_p = p.kind(); + let bound_p = p.bound_atom(); match bound_p.skip_binder() { - ty::PredicateKind::Trait(pred, _constness) => { + ty::PredicateAtom::Trait(pred, _constness) => { if let ty::Param(param) = pred.self_ty().kind() { return Some(param.index); } } - ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => { + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => { if let ty::Param(param) = ty.kind() { return Some(param.index); } } - ty::PredicateKind::Projection(p) => { + ty::PredicateAtom::Projection(p) => { if let ty::Param(param) = p.projection_ty.self_ty().kind() { projection = Some(bound_p.rebind(p)); return Some(param.index); @@ -1327,7 +1328,7 @@ fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &DocContext<'_>) -> Type { let mut ty_substs = FxHashMap::default(); let mut lt_substs = FxHashMap::default(); let mut ct_substs = FxHashMap::default(); - let generic_args = provided_params.args(); + let generic_args = provided_params.generic_args(); { let mut indices: GenericParamCount = Default::default(); for param in generics.params.iter() { @@ -1684,12 +1685,14 @@ impl<'tcx> Clean for Ty<'tcx> { let mut bounds = bounds .iter() .filter_map(|bound| { - let bound_predicate = bound.kind(); + // Note: The substs of opaque types can contain unbound variables, + // meaning that we have to use `ignore_quantifiers_with_unbound_vars` here. + let bound_predicate = bound.bound_atom_with_opt_escaping(cx.tcx); let trait_ref = match bound_predicate.skip_binder() { - ty::PredicateKind::Trait(tr, _constness) => { + ty::PredicateAtom::Trait(tr, _constness) => { bound_predicate.rebind(tr.trait_ref) } - ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => { + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => { if let Some(r) = reg.clean(cx) { regions.push(GenericBound::Outlives(r)); } @@ -1708,8 +1711,8 @@ impl<'tcx> Clean for Ty<'tcx> { let bounds: Vec<_> = bounds .iter() .filter_map(|bound| { - if let ty::PredicateKind::Projection(proj) = - bound.kind().skip_binder() + if let ty::PredicateAtom::Projection(proj) = + bound.bound_atom_with_opt_escaping(cx.tcx).skip_binder() { if proj.projection_ty.trait_ref(cx.tcx) == trait_ref.skip_binder() @@ -1834,14 +1837,27 @@ impl Clean for rustc_hir::VariantData<'_> { } } +impl Clean for doctree::Variant<'_> { + fn clean(&self, cx: &DocContext<'_>) -> Item { + let what_rustc_thinks = Item::from_hir_id_and_parts( + self.id, + Some(self.name), + VariantItem(Variant { kind: self.def.clean(cx) }), + cx, + ); + // don't show `pub` for variants, which are always public + Item { visibility: Inherited, ..what_rustc_thinks } + } +} + impl Clean for ty::VariantDef { fn clean(&self, cx: &DocContext<'_>) -> Item { let kind = match self.ctor_kind { - CtorKind::Const => Variant::CLike, - CtorKind::Fn => Variant::Tuple( + CtorKind::Const => VariantKind::CLike, + CtorKind::Fn => VariantKind::Tuple( self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(), ), - CtorKind::Fictive => Variant::Struct(VariantStruct { + CtorKind::Fictive => VariantKind::Struct(VariantStruct { struct_type: doctree::Plain, fields_stripped: false, fields: self @@ -1858,21 +1874,25 @@ impl Clean for ty::VariantDef { .collect(), }), }; - let what_rustc_thinks = - Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), VariantItem(kind), cx); + let what_rustc_thinks = Item::from_def_id_and_parts( + self.def_id, + Some(self.ident.name), + VariantItem(Variant { kind }), + cx, + ); // don't show `pub` for fields, which are always public Item { visibility: Inherited, ..what_rustc_thinks } } } -impl Clean for hir::VariantData<'_> { - fn clean(&self, cx: &DocContext<'_>) -> Variant { +impl Clean for hir::VariantData<'_> { + fn clean(&self, cx: &DocContext<'_>) -> VariantKind { match self { - hir::VariantData::Struct(..) => Variant::Struct(self.clean(cx)), + hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)), hir::VariantData::Tuple(..) => { - Variant::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect()) + VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect()) } - hir::VariantData::Unit(..) => Variant::CLike, + hir::VariantData::Unit(..) => VariantKind::CLike, } } } @@ -1923,7 +1943,7 @@ impl Clean for hir::GenericArgs<'_> { impl Clean for hir::PathSegment<'_> { fn clean(&self, cx: &DocContext<'_>) -> PathSegment { - PathSegment { name: self.ident.name, args: self.args().clean(cx) } + PathSegment { name: self.ident.name, args: self.generic_args().clean(cx) } } } @@ -2007,12 +2027,12 @@ impl Clean> for (&hir::Item<'_>, Option) { fields: variant_data.fields().clean(cx), fields_stripped: false, }), - ItemKind::Impl(ref impl_) => return clean_impl(impl_, item.hir_id, cx), + ItemKind::Impl { .. } => return clean_impl(item, cx), // proc macros can have a name set by attributes ItemKind::Fn(ref sig, ref generics, body_id) => { clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx) } - ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => { + hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => { let items = item_ids .iter() .map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx)) @@ -2031,9 +2051,6 @@ impl Clean> for (&hir::Item<'_>, Option) { ItemKind::ExternCrate(orig_name) => { return clean_extern_crate(item, name, orig_name, cx); } - ItemKind::Use(path, kind) => { - return clean_use_statement(item, name, path, kind, cx); - } _ => unreachable!("not yet converted"), }; @@ -2044,7 +2061,7 @@ impl Clean> for (&hir::Item<'_>, Option) { impl Clean for hir::Variant<'_> { fn clean(&self, cx: &DocContext<'_>) -> Item { - let kind = VariantItem(self.data.clean(cx)); + let kind = VariantItem(Variant { kind: self.data.clean(cx) }); let what_rustc_thinks = Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx); // don't show `pub` for variants, which are always public @@ -2064,12 +2081,17 @@ impl Clean for ty::ImplPolarity { } } -fn clean_impl(impl_: &hir::Impl<'_>, hir_id: hir::HirId, cx: &DocContext<'_>) -> Vec { +fn clean_impl(impl_: &hir::Item<'_>, cx: &DocContext<'_>) -> Vec { let mut ret = Vec::new(); - let trait_ = impl_.of_trait.clean(cx); - let items = - impl_.items.iter().map(|ii| cx.tcx.hir().impl_item(ii.id).clean(cx)).collect::>(); - let def_id = cx.tcx.hir().local_def_id(hir_id); + let (trait_, items, for_, unsafety, generics) = match &impl_.kind { + hir::ItemKind::Impl { of_trait, items, self_ty, unsafety, generics, .. } => { + (of_trait, items, self_ty, *unsafety, generics) + } + _ => unreachable!(), + }; + let trait_ = trait_.clean(cx); + let items = items.iter().map(|ii| cx.tcx.hir().impl_item(ii.id).clean(cx)).collect::>(); + let def_id = cx.tcx.hir().local_def_id(impl_.hir_id); // If this impl block is an implementation of the Deref trait, then we // need to try inlining the target's inherent impl blocks as well. @@ -2082,15 +2104,15 @@ fn clean_impl(impl_: &hir::Impl<'_>, hir_id: hir::HirId, cx: &DocContext<'_>) -> .map(|did| cx.tcx.provided_trait_methods(did).map(|meth| meth.ident.name).collect()) .unwrap_or_default(); - let for_ = impl_.self_ty.clean(cx); + let for_ = for_.clean(cx); let type_alias = for_.def_id().and_then(|did| match cx.tcx.def_kind(did) { DefKind::TyAlias => Some(cx.tcx.type_of(did).clean(cx)), _ => None, }); let make_item = |trait_: Option, for_: Type, items: Vec| { let kind = ImplItem(Impl { - unsafety: impl_.unsafety, - generics: impl_.generics.clean(cx), + unsafety, + generics: generics.clean(cx), provided_trait_methods: provided.clone(), trait_, for_, @@ -2099,7 +2121,7 @@ fn clean_impl(impl_: &hir::Impl<'_>, hir_id: hir::HirId, cx: &DocContext<'_>) -> synthetic: false, blanket_impl: None, }); - Item::from_hir_id_and_parts(hir_id, None, kind, cx) + Item::from_hir_id_and_parts(impl_.hir_id, None, kind, cx) }; if let Some(type_alias) = type_alias { ret.push(make_item(trait_.clone(), type_alias, items.clone())); @@ -2147,7 +2169,7 @@ fn clean_extern_crate( // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason vec![Item { name: None, - attrs: box krate.attrs.clean(cx), + attrs: krate.attrs.clean(cx), source: krate.span.clean(cx), def_id: crate_def_id, visibility: krate.vis.clean(cx), @@ -2155,97 +2177,105 @@ fn clean_extern_crate( }] } -fn clean_use_statement( - import: &hir::Item<'_>, - name: Symbol, - path: &hir::Path<'_>, - kind: hir::UseKind, - cx: &DocContext<'_>, -) -> Vec { - // We need this comparison because some imports (for std types for example) - // are "inserted" as well but directly by the compiler and they should not be - // taken into account. - if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) { - return Vec::new(); - } - - let (doc_meta_item, please_inline) = import.attrs.lists(sym::doc).get_word_attr(sym::inline); - let pub_underscore = import.vis.node.is_pub() && name == kw::Underscore; - - if pub_underscore && please_inline { - rustc_errors::struct_span_err!( - cx.tcx.sess, - doc_meta_item.unwrap().span(), - E0780, - "anonymous imports cannot be inlined" - ) - .span_label(import.span, "anonymous import") - .emit(); - } +impl Clean> for doctree::Import<'_> { + fn clean(&self, cx: &DocContext<'_>) -> Vec { + // We need this comparison because some imports (for std types for example) + // are "inserted" as well but directly by the compiler and they should not be + // taken into account. + if self.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) { + return Vec::new(); + } - // We consider inlining the documentation of `pub use` statements, but we - // forcefully don't inline if this is not public or if the - // #[doc(no_inline)] attribute is present. - // Don't inline doc(hidden) imports so they can be stripped at a later stage. - let mut denied = !import.vis.node.is_pub() - || pub_underscore - || import.attrs.iter().any(|a| { - a.has_name(sym::doc) - && match a.meta_item_list() { - Some(l) => { - attr::list_contains_name(&l, sym::no_inline) - || attr::list_contains_name(&l, sym::hidden) + let (doc_meta_item, please_inline) = self.attrs.lists(sym::doc).get_word_attr(sym::inline); + let pub_underscore = self.vis.node.is_pub() && self.name == kw::Underscore; + + if pub_underscore && please_inline { + rustc_errors::struct_span_err!( + cx.tcx.sess, + doc_meta_item.unwrap().span(), + E0780, + "anonymous imports cannot be inlined" + ) + .span_label(self.span, "anonymous import") + .emit(); + } + + // We consider inlining the documentation of `pub use` statements, but we + // forcefully don't inline if this is not public or if the + // #[doc(no_inline)] attribute is present. + // Don't inline doc(hidden) imports so they can be stripped at a later stage. + let mut denied = !self.vis.node.is_pub() + || pub_underscore + || self.attrs.iter().any(|a| { + a.has_name(sym::doc) + && match a.meta_item_list() { + Some(l) => { + attr::list_contains_name(&l, sym::no_inline) + || attr::list_contains_name(&l, sym::hidden) + } + None => false, } - None => false, + }); + // Also check whether imports were asked to be inlined, in case we're trying to re-export a + // crate in Rust 2018+ + let path = self.path.clean(cx); + let inner = if self.glob { + if !denied { + let mut visited = FxHashSet::default(); + if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) { + return items; } - }); - - // Also check whether imports were asked to be inlined, in case we're trying to re-export a - // crate in Rust 2018+ - let def_id = cx.tcx.hir().local_def_id(import.hir_id).to_def_id(); - let path = path.clean(cx); - let inner = if kind == hir::UseKind::Glob { - if !denied { - let mut visited = FxHashSet::default(); - if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) { - return items; } - } - Import::new_glob(resolve_use_source(cx, path), true) - } else { - if !please_inline { - if let Res::Def(DefKind::Mod, did) = path.res { - if !did.is_local() && did.index == CRATE_DEF_INDEX { - // if we're `pub use`ing an extern crate root, don't inline it unless we - // were specifically asked for it - denied = true; + Import::new_glob(resolve_use_source(cx, path), true) + } else { + let name = self.name; + if !please_inline { + if let Res::Def(DefKind::Mod, did) = path.res { + if !did.is_local() && did.index == CRATE_DEF_INDEX { + // if we're `pub use`ing an extern crate root, don't inline it unless we + // were specifically asked for it + denied = true; + } } } - } - if !denied { - let mut visited = FxHashSet::default(); + if !denied { + let mut visited = FxHashSet::default(); - if let Some(mut items) = inline::try_inline( - cx, - cx.tcx.parent_module(import.hir_id).to_def_id(), - path.res, - name, - Some(import.attrs), - &mut visited, - ) { - items.push(Item::from_def_id_and_parts( - def_id, - None, - ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)), + if let Some(mut items) = inline::try_inline( cx, - )); - return items; + cx.tcx.parent_module(self.id).to_def_id(), + path.res, + name, + Some(self.attrs), + &mut visited, + ) { + items.push(Item { + name: None, + attrs: self.attrs.clean(cx), + source: self.span.clean(cx), + def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(), + visibility: self.vis.clean(cx), + kind: box ImportItem(Import::new_simple( + self.name, + resolve_use_source(cx, path), + false, + )), + }); + return items; + } } - } - Import::new_simple(name, resolve_use_source(cx, path), true) - }; + Import::new_simple(name, resolve_use_source(cx, path), true) + }; - vec![Item::from_def_id_and_parts(def_id, None, ImportItem(inner), cx)] + vec![Item { + name: None, + attrs: self.attrs.clean(cx), + source: self.span.clean(cx), + def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(), + visibility: self.vis.clean(cx), + kind: box ImportItem(inner), + }] + } } impl Clean for (&hir::ForeignItem<'_>, Option) { diff --git a/src/librustdoc/clean/simplify.rs b/src/librustdoc/clean/simplify.rs index d4d0a8ce24c7b..16aaa9cfd20eb 100644 --- a/src/librustdoc/clean/simplify.rs +++ b/src/librustdoc/clean/simplify.rs @@ -129,7 +129,7 @@ fn trait_is_same_or_supertrait(cx: &DocContext<'_>, child: DefId, trait_: DefId) .predicates .iter() .filter_map(|(pred, _)| { - if let ty::PredicateKind::Trait(pred, _) = pred.kind().skip_binder() { + if let ty::PredicateAtom::Trait(pred, _) = pred.skip_binders() { if pred.trait_ref.self_ty() == self_ty { Some(pred.def_id()) } else { None } } else { None diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 666b11b5f806d..7e567bedc7875 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -82,7 +82,7 @@ crate struct Item { crate source: Span, /// Not everything has a name. E.g., impls crate name: Option, - crate attrs: Box, + crate attrs: Attributes, crate visibility: Visibility, crate kind: Box, crate def_id: DefId, @@ -90,7 +90,7 @@ crate struct Item { // `Item` is used a lot. Make sure it doesn't unintentionally get bigger. #[cfg(target_arch = "x86_64")] -rustc_data_structures::static_assert_size!(Item, 48); +rustc_data_structures::static_assert_size!(Item, 136); impl fmt::Debug for Item { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -159,7 +159,7 @@ impl Item { kind: box kind, name, source: source.clean(cx), - attrs: box cx.tcx.get_attrs(def_id).clean(cx), + attrs: cx.tcx.get_attrs(def_id).clean(cx), visibility: cx.tcx.visibility(def_id).clean(cx), } } @@ -237,7 +237,9 @@ impl Item { match *self.kind { StructItem(ref _struct) => Some(_struct.fields_stripped), UnionItem(ref union) => Some(union.fields_stripped), - VariantItem(Variant::Struct(ref vstruct)) => Some(vstruct.fields_stripped), + VariantItem(Variant { kind: VariantKind::Struct(ref vstruct) }) => { + Some(vstruct.fields_stripped) + } _ => None, } } @@ -351,7 +353,7 @@ impl ItemKind { match self { StructItem(s) => s.fields.iter(), UnionItem(u) => u.fields.iter(), - VariantItem(Variant::Struct(v)) => v.fields.iter(), + VariantItem(Variant { kind: VariantKind::Struct(v) }) => v.fields.iter(), EnumItem(e) => e.variants.iter(), TraitItem(t) => t.items.iter(), ImplItem(i) => i.items.iter(), @@ -1717,7 +1719,12 @@ crate struct Enum { } #[derive(Clone, Debug)] -crate enum Variant { +crate struct Variant { + crate kind: VariantKind, +} + +#[derive(Clone, Debug)] +crate enum VariantKind { CLike, Tuple(Vec), Struct(VariantStruct), diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index 3de97f2dd2e59..09627be9701c9 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -500,12 +500,6 @@ crate fn make_test( } } - // Reset errors so that they won't be reported as compiler bugs when dropping the - // handler. Any errors in the tests will be reported when the test file is compiled, - // Note that we still need to cancel the errors above otherwise `DiagnosticBuilder` - // will panic on drop. - sess.span_diagnostic.reset_err_count(); - (found_main, found_extern_crate, found_macro) }) }); @@ -1032,8 +1026,8 @@ impl<'a, 'hir, 'tcx> intravisit::Visitor<'hir> for HirCollector<'a, 'hir, 'tcx> } fn visit_item(&mut self, item: &'hir hir::Item<'_>) { - let name = if let hir::ItemKind::Impl(impl_) = &item.kind { - rustc_hir_pretty::id_to_string(&self.map, impl_.self_ty.hir_id) + let name = if let hir::ItemKind::Impl { ref self_ty, .. } = item.kind { + rustc_hir_pretty::id_to_string(&self.map, self_ty.hir_id) } else { item.ident.to_string() }; diff --git a/src/librustdoc/doctree.rs b/src/librustdoc/doctree.rs index f90623c03118b..bc9f1cf8806ab 100644 --- a/src/librustdoc/doctree.rs +++ b/src/librustdoc/doctree.rs @@ -2,6 +2,7 @@ //! manner (and with prettier names) before cleaning. crate use self::StructType::*; +use rustc_ast as ast; use rustc_span::{self, Span, Symbol}; use rustc_hir as hir; @@ -10,6 +11,7 @@ crate struct Module<'hir> { crate name: Option, crate where_outer: Span, crate where_inner: Span, + crate imports: Vec>, crate mods: Vec>, crate id: hir::HirId, // (item, renamed) @@ -26,6 +28,7 @@ impl Module<'hir> { id: hir::CRATE_HIR_ID, where_outer: rustc_span::DUMMY_SP, where_inner: rustc_span::DUMMY_SP, + imports: Vec::new(), mods: Vec::new(), items: Vec::new(), foreigns: Vec::new(), @@ -45,6 +48,23 @@ crate enum StructType { Unit, } +crate struct Variant<'hir> { + crate name: Symbol, + crate id: hir::HirId, + crate def: &'hir hir::VariantData<'hir>, +} + +#[derive(Debug)] +crate struct Import<'hir> { + crate name: Symbol, + crate id: hir::HirId, + crate vis: &'hir hir::Visibility<'hir>, + crate attrs: &'hir [ast::Attribute], + crate path: &'hir hir::Path<'hir>, + crate glob: bool, + crate span: Span, +} + crate fn struct_type_from_def(vdata: &hir::VariantData<'_>) -> StructType { match *vdata { hir::VariantData::Struct(..) => Plain, diff --git a/src/librustdoc/fold.rs b/src/librustdoc/fold.rs index b2773a29e2905..4d45c8866a793 100644 --- a/src/librustdoc/fold.rs +++ b/src/librustdoc/fold.rs @@ -55,13 +55,13 @@ crate trait DocFolder: Sized { } VariantItem(i) => { let i2 = i.clone(); // this clone is small - match i { - Variant::Struct(mut j) => { + match i.kind { + VariantKind::Struct(mut j) => { let num_fields = j.fields.len(); j.fields = j.fields.into_iter().filter_map(|x| self.fold_item(x)).collect(); j.fields_stripped |= num_fields != j.fields.len() || j.fields.iter().any(|f| f.is_stripped()); - VariantItem(Variant::Struct(j)) + VariantItem(Variant { kind: VariantKind::Struct(j) }) } _ => VariantItem(i2), } diff --git a/src/librustdoc/html/layout.rs b/src/librustdoc/html/layout.rs index 4458eea95f3e1..b5169b0599773 100644 --- a/src/librustdoc/html/layout.rs +++ b/src/librustdoc/html/layout.rs @@ -111,7 +111,10 @@ crate fn render(
\
\ {after_content}\ -
+ \ \ {static_extra_scripts}\ {extra_scripts}\ diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index cfa6cd96595d6..33639055b59ef 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -1313,8 +1313,6 @@ fn init_id_map() -> FxHashMap { map.insert("toggle-all-docs".to_owned(), 1); map.insert("all-types".to_owned(), 1); map.insert("default-settings".to_owned(), 1); - map.insert("rustdoc-vars".to_owned(), 1); - map.insert("sidebar-vars".to_owned(), 1); // This is the list of IDs used by rustdoc sections. map.insert("fields".to_owned(), 1); map.insert("variants".to_owned(), 1); diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index 03e091297e5b6..6a32be609911a 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -3200,9 +3200,9 @@ fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum write!(w, " "); let name = v.name.as_ref().unwrap(); match *v.kind { - clean::VariantItem(ref var) => match var { - clean::Variant::CLike => write!(w, "{}", name), - clean::Variant::Tuple(ref tys) => { + clean::VariantItem(ref var) => match var.kind { + clean::VariantKind::CLike => write!(w, "{}", name), + clean::VariantKind::Tuple(ref tys) => { write!(w, "{}(", name); for (i, ty) in tys.iter().enumerate() { if i > 0 { @@ -3212,7 +3212,7 @@ fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum } write!(w, ")"); } - clean::Variant::Struct(ref s) => { + clean::VariantKind::Struct(ref s) => { render_struct(w, v, None, s.struct_type, &s.fields, " ", false, cx); } }, @@ -3249,22 +3249,25 @@ fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum id = id, name = variant.name.as_ref().unwrap() ); - if let clean::VariantItem(clean::Variant::Tuple(ref tys)) = *variant.kind { - write!(w, "("); - for (i, ty) in tys.iter().enumerate() { - if i > 0 { - write!(w, ", "); + if let clean::VariantItem(ref var) = *variant.kind { + if let clean::VariantKind::Tuple(ref tys) = var.kind { + write!(w, "("); + for (i, ty) in tys.iter().enumerate() { + if i > 0 { + write!(w, ", "); + } + write!(w, "{}", ty.print()); } - write!(w, "{}", ty.print()); + write!(w, ")"); } - write!(w, ")"); } write!(w, ""); document(w, cx, variant, Some(it)); document_non_exhaustive(w, variant); - use crate::clean::Variant; - if let clean::VariantItem(Variant::Struct(ref s)) = *variant.kind { + use crate::clean::{Variant, VariantKind}; + if let clean::VariantItem(Variant { kind: VariantKind::Struct(ref s) }) = *variant.kind + { let variant_id = cx.derive_id(format!( "{}.{}.fields", ItemType::Variant, @@ -4216,8 +4219,11 @@ fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer, cache: let relpath = if it.is_mod() { "../" } else { "" }; write!( buffer, - "
\ -
", + "", name = it.name.unwrap_or(kw::Empty), ty = it.type_(), path = relpath diff --git a/src/librustdoc/html/static/main.js b/src/librustdoc/html/static/main.js index 74bd348e9ac1c..ec8024ffca529 100644 --- a/src/librustdoc/html/static/main.js +++ b/src/librustdoc/html/static/main.js @@ -1,5 +1,5 @@ // From rust: -/* global ALIASES */ +/* global ALIASES, currentCrate, rootPath */ // Local js definitions: /* global addClass, getCurrentValue, hasClass */ @@ -40,21 +40,6 @@ if (!DOMTokenList.prototype.remove) { }; } -(function () { - var rustdocVars = document.getElementById("rustdoc-vars"); - if (rustdocVars) { - window.rootPath = rustdocVars.attributes["data-root-path"].value; - window.currentCrate = rustdocVars.attributes["data-current-crate"].value; - } - var sidebarVars = document.getElementById("sidebar-vars"); - if (sidebarVars) { - window.sidebarCurrent = { - name: sidebarVars.attributes["data-name"].value, - ty: sidebarVars.attributes["data-ty"].value, - relpath: sidebarVars.attributes["data-relpath"].value, - }; - } -}()); // Gets the human-readable string for the virtual-key code of the // given KeyboardEvent, ev. @@ -580,7 +565,7 @@ function defocusSearchBar() { var i, match, url = document.location.href, stripped = "", - len = window.rootPath.match(/\.\.\//g).length + 1; + len = rootPath.match(/\.\.\//g).length + 1; for (i = 0; i < len; ++i) { match = url.match(/\/[^\/]*$/); @@ -663,7 +648,8 @@ function defocusSearchBar() { */ function execQuery(query, searchWords, filterCrates) { function itemTypeFromName(typename) { - for (var i = 0, len = itemTypes.length; i < len; ++i) { + var length = itemTypes.length; + for (var i = 0; i < length; ++i) { if (itemTypes[i] === typename) { return i; } @@ -681,7 +667,8 @@ function defocusSearchBar() { function transformResults(results, isType) { var out = []; - for (var i = 0, len = results.length; i < len; ++i) { + var length = results.length; + for (var i = 0; i < length; ++i) { if (results[i].id > -1) { var obj = searchIndex[results[i].id]; obj.lev = results[i].lev; @@ -710,11 +697,11 @@ function defocusSearchBar() { } } results = ar; - var i, len, result; - for (i = 0, len = results.length; i < len; ++i) { - result = results[i]; - result.word = searchWords[result.id]; - result.item = searchIndex[result.id] || {}; + var i; + var nresults = results.length; + for (i = 0; i < nresults; ++i) { + results[i].word = searchWords[results[i].id]; + results[i].item = searchIndex[results[i].id] || {}; } // if there are no results then return to default and fail if (results.length === 0) { @@ -788,7 +775,8 @@ function defocusSearchBar() { return 0; }); - for (i = 0, len = results.length; i < len; ++i) { + var length = results.length; + for (i = 0; i < length; ++i) { var result = results[i]; // this validation does not make sense when searching by types @@ -845,10 +833,11 @@ function defocusSearchBar() { var vlength = val.generics.length; for (var y = 0; y < vlength; ++y) { var lev = { pos: -1, lev: MAX_LEV_DISTANCE + 1}; + var elength = elems.length; var firstGeneric = getObjectFromId(val.generics[y]).name; - for (var x = 0, elength = elems.length; x < elength; ++x) { + for (var x = 0; x < elength; ++x) { var tmp_lev = levenshtein(getObjectFromId(elems[x]).name, - firstGeneric); + firstGeneric); if (tmp_lev < lev.lev) { lev.lev = tmp_lev; lev.pos = x; @@ -872,7 +861,7 @@ function defocusSearchBar() { // Check for type name and type generics (if any). function checkType(obj, val, literalSearch) { var lev_distance = MAX_LEV_DISTANCE + 1; - var len, x, y, e_len, firstGeneric; + var x; if (obj[NAME] === val.name) { if (literalSearch === true) { if (val.generics && val.generics.length !== 0) { @@ -881,12 +870,10 @@ function defocusSearchBar() { var elems = obj[GENERICS_DATA].slice(0); var allFound = true; - len = val.generics.length; - for (y = 0; allFound === true && y < len; ++y) { + for (var y = 0; allFound === true && y < val.generics.length; ++y) { allFound = false; - firstGeneric = getObjectFromId(val.generics[y]).name; - e_len = elems.length; - for (x = 0; allFound === false && x < e_len; ++x) { + var firstGeneric = getObjectFromId(val.generics[y]).name; + for (x = 0; allFound === false && x < elems.length; ++x) { allFound = getObjectFromId(elems[x]).name === firstGeneric; } if (allFound === true) { @@ -916,10 +903,12 @@ function defocusSearchBar() { // Names didn't match so let's check if one of the generic types could. if (literalSearch === true) { if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) { - return obj[GENERICS_DATA].some( - function(name) { - return name === val.name; - }); + var length = obj[GENERICS_DATA].length; + for (x = 0; x < length; ++x) { + if (obj[GENERICS_DATA][x] === val.name) { + return true; + } + } } return false; } @@ -976,7 +965,7 @@ function defocusSearchBar() { if (typeof ret[0] === "string") { ret = [ret]; } - for (var x = 0, len = ret.length; x < len; ++x) { + for (var x = 0; x < ret.length; ++x) { var tmp = ret[x]; if (typePassesFilter(typeFilter, tmp[1]) === false) { continue; @@ -1083,22 +1072,23 @@ function defocusSearchBar() { // aliases to be before the others in the displayed results. var aliases = []; var crateAliases = []; + var i; if (filterCrates !== undefined) { if (ALIASES[filterCrates] && ALIASES[filterCrates][query.search]) { - var query_aliases = ALIASES[filterCrates][query.search]; - var len = query_aliases.length; - for (var i = 0; i < len; ++i) { - aliases.push(createAliasFromItem(searchIndex[query_aliases[i]])); + for (i = 0; i < ALIASES[filterCrates][query.search].length; ++i) { + aliases.push( + createAliasFromItem( + searchIndex[ALIASES[filterCrates][query.search][i]])); } } } else { Object.keys(ALIASES).forEach(function(crate) { if (ALIASES[crate][query.search]) { var pushTo = crate === window.currentCrate ? crateAliases : aliases; - var query_aliases = ALIASES[crate][query.search]; - var len = query_aliases.length; - for (var i = 0; i < len; ++i) { - pushTo.push(createAliasFromItem(searchIndex[query_aliases[i]])); + for (i = 0; i < ALIASES[crate][query.search].length; ++i) { + pushTo.push( + createAliasFromItem( + searchIndex[ALIASES[crate][query.search][i]])); } } }); @@ -1133,12 +1123,11 @@ function defocusSearchBar() { // quoted values mean literal search var nSearchWords = searchWords.length; - var i, it; + var i; var ty; var fullId; var returned; var in_args; - var len; if ((val.charAt(0) === "\"" || val.charAt(0) === "'") && val.charAt(val.length - 1) === val.charAt(0)) { @@ -1186,7 +1175,7 @@ function defocusSearchBar() { var input = parts[0]; // sort inputs so that order does not matter var inputs = input.split(",").map(trimmer).sort(); - for (i = 0, len = inputs.length; i < len; ++i) { + for (i = 0; i < inputs.length; ++i) { inputs[i] = extractGenerics(inputs[i]); } var output = extractGenerics(parts[1]); @@ -1211,7 +1200,7 @@ function defocusSearchBar() { is_module = true; } else { var allFound = true; - for (it = 0, len = inputs.length; allFound === true && it < len; it++) { + for (var it = 0; allFound === true && it < inputs.length; it++) { allFound = checkType(type, inputs[it], true); } in_args = allFound; @@ -1254,7 +1243,7 @@ function defocusSearchBar() { var paths = valLower.split("::"); var j; - for (j = 0, len = paths.length; j < len; ++j) { + for (j = 0; j < paths.length; ++j) { if (paths[j] === "") { paths.splice(j, 1); j -= 1; @@ -1376,7 +1365,7 @@ function defocusSearchBar() { * @return {[boolean]} [Whether the result is valid or not] */ function validateResult(name, path, keys, parent) { - for (var i = 0, len = keys.length; i < len; ++i) { + for (var i = 0; i < keys.length; ++i) { // each check is for validation so we negate the conditions and invalidate if (!( // check for an exact name match @@ -1519,15 +1508,15 @@ function defocusSearchBar() { if (type === "mod") { displayPath = path + "::"; - href = window.rootPath + path.replace(/::/g, "/") + "/" + + href = rootPath + path.replace(/::/g, "/") + "/" + name + "/index.html"; } else if (type === "primitive" || type === "keyword") { displayPath = ""; - href = window.rootPath + path.replace(/::/g, "/") + + href = rootPath + path.replace(/::/g, "/") + "/" + type + "." + name + ".html"; } else if (type === "externcrate") { displayPath = ""; - href = window.rootPath + name + "/index.html"; + href = rootPath + name + "/index.html"; } else if (item.parent !== undefined) { var myparent = item.parent; var anchor = "#" + type + "." + name; @@ -1550,13 +1539,13 @@ function defocusSearchBar() { } else { displayPath = path + "::" + myparent.name + "::"; } - href = window.rootPath + path.replace(/::/g, "/") + + href = rootPath + path.replace(/::/g, "/") + "/" + pageType + "." + pageName + ".html" + anchor; } else { displayPath = item.path + "::"; - href = window.rootPath + item.path.replace(/::/g, "/") + + href = rootPath + item.path.replace(/::/g, "/") + "/" + type + "." + name + ".html"; } return [displayPath, href]; @@ -1665,21 +1654,6 @@ function defocusSearchBar() { var ret_in_args = addTab(results.in_args, query, false); var ret_returned = addTab(results.returned, query, false); - // Navigate to the relevant tab if the current tab is empty, like in case users search - // for "-> String". If they had selected another tab previously, they have to click on - // it again. - if ((currentTab === 0 && ret_others[1] === 0) || - (currentTab === 1 && ret_in_args[1] === 0) || - (currentTab === 2 && ret_returned[1] === 0)) { - if (ret_others[1] !== 0) { - currentTab = 0; - } else if (ret_in_args[1] !== 0) { - currentTab = 1; - } else if (ret_returned[1] !== 0) { - currentTab = 2; - } - } - var output = "

Results for " + escape(query.query) + (query.type ? " (type: " + escape(query.type) + ")" : "") + "

" + "
" + @@ -1712,7 +1686,7 @@ function defocusSearchBar() { function getSmallest(arrays, positions, notDuplicates) { var start = null; - for (var it = 0, len = positions.length; it < len; ++it) { + for (var it = 0; it < positions.length; ++it) { if (arrays[it].length > positions[it] && (start === null || start > arrays[it][positions[it]].lev) && !notDuplicates[arrays[it][positions[it]].fullPath]) { @@ -1727,7 +1701,7 @@ function defocusSearchBar() { var positions = []; var notDuplicates = {}; - for (var x = 0, arrays_len = arrays.length; x < arrays_len; ++x) { + for (var x = 0; x < arrays.length; ++x) { positions.push(0); } while (ret.length < MAX_RESULTS) { @@ -1736,7 +1710,7 @@ function defocusSearchBar() { if (smallest === null) { break; } - for (x = 0; x < arrays_len && ret.length < MAX_RESULTS; ++x) { + for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) { if (arrays[x].length > positions[x] && arrays[x][positions[x]].lev === smallest && !notDuplicates[arrays[x][positions[x]].fullPath]) { @@ -1756,7 +1730,7 @@ function defocusSearchBar() { "others": [], }; - for (var i = 0, len = queries.length; i < len; ++i) { + for (var i = 0; i < queries.length; ++i) { query = queries[i].trim(); if (query.length !== 0) { var tmp = execQuery(getQuery(query), searchWords, filterCrates); @@ -1910,7 +1884,7 @@ function defocusSearchBar() { ALIASES[crate][alias_name] = []; } local_aliases = aliases[alias_name]; - for (j = 0, len = local_aliases.length; j < len; ++j) { + for (j = 0; j < local_aliases.length; ++j) { ALIASES[crate][alias_name].push(local_aliases[j] + currentIndex); } } @@ -2003,7 +1977,7 @@ function defocusSearchBar() { startSearch(); // Draw a convenient sidebar of known crates if we have a listing - if (window.rootPath === "../" || window.rootPath === "./") { + if (rootPath === "../" || rootPath === "./") { var sidebar = document.getElementsByClassName("sidebar-elems")[0]; if (sidebar) { var div = document.createElement("div"); @@ -2022,11 +1996,11 @@ function defocusSearchBar() { crates.sort(); for (var i = 0; i < crates.length; ++i) { var klass = "crate"; - if (window.rootPath !== "./" && crates[i] === window.currentCrate) { + if (rootPath !== "./" && crates[i] === window.currentCrate) { klass += " current"; } var link = document.createElement("a"); - link.href = window.rootPath + crates[i] + "/index.html"; + link.href = rootPath + crates[i] + "/index.html"; // The summary in the search index has HTML, so we need to // dynamically render it as plaintext. link.title = convertHTMLToPlaintext(rawSearchIndex[crates[i]].doc); @@ -2078,7 +2052,8 @@ function defocusSearchBar() { div.appendChild(h3); var ul = document.createElement("ul"); - for (var i = 0, len = filtered.length; i < len; ++i) { + var length = filtered.length; + for (var i = 0; i < length; ++i) { var item = filtered[i]; var name = item[0]; var desc = item[1]; // can be null @@ -2147,18 +2122,21 @@ function defocusSearchBar() { } var libs = Object.getOwnPropertyNames(imp); - for (var i = 0, llength = libs.length; i < llength; ++i) { - if (libs[i] === window.currentCrate) { continue; } + var llength = libs.length; + for (var i = 0; i < llength; ++i) { + if (libs[i] === currentCrate) { continue; } var structs = imp[libs[i]]; + var slength = structs.length; struct_loop: - for (var j = 0, slength = structs.length; j < slength; ++j) { + for (var j = 0; j < slength; ++j) { var struct = structs[j]; var list = struct.synthetic ? synthetic_implementors : implementors; if (struct.synthetic) { - for (var k = 0, stlength = struct.types.length; k < stlength; k++) { + var stlength = struct.types.length; + for (var k = 0; k < stlength; k++) { if (inlined_types.has(struct.types[k])) { continue struct_loop; } @@ -2173,7 +2151,7 @@ function defocusSearchBar() { var href = elem.getAttribute("href"); if (href && href.indexOf("http") !== 0) { - elem.setAttribute("href", window.rootPath + href); + elem.setAttribute("href", rootPath + href); } }); @@ -2875,7 +2853,7 @@ function defocusSearchBar() { return 0; }); var savedCrate = getSettingValue("saved-filter-crate"); - for (var i = 0, len = crates_text.length; i < len; ++i) { + for (var i = 0; i < crates_text.length; ++i) { var option = document.createElement("option"); option.value = crates_text[i]; option.innerText = crates_text[i]; diff --git a/src/librustdoc/html/static/source-script.js b/src/librustdoc/html/static/source-script.js index a9cc0ffdf79b0..6805f2a266f09 100644 --- a/src/librustdoc/html/static/source-script.js +++ b/src/librustdoc/html/static/source-script.js @@ -8,7 +8,7 @@ function getCurrentFilePath() { var parts = window.location.pathname.split("/"); var rootPathParts = window.rootPath.split("/"); - for (var i = 0, len = rootPathParts.length; i < len; ++i) { + for (var i = 0; i < rootPathParts.length; ++i) { if (rootPathParts[i] === "..") { parts.pop(); } @@ -35,14 +35,12 @@ function createDirEntry(elem, parent, fullPath, currentFile, hasFoundFile) { }; name.innerText = elem["name"]; - var i, len; - var children = document.createElement("div"); children.className = "children"; var folders = document.createElement("div"); folders.className = "folders"; if (elem.dirs) { - for (i = 0, len = elem.dirs.length; i < len; ++i) { + for (var i = 0; i < elem.dirs.length; ++i) { if (createDirEntry(elem.dirs[i], folders, fullPath, currentFile, hasFoundFile) === true) { addClass(name, "expand"); @@ -55,7 +53,7 @@ function createDirEntry(elem, parent, fullPath, currentFile, hasFoundFile) { var files = document.createElement("div"); files.className = "files"; if (elem.files) { - for (i = 0, len = elem.files.length; i < len; ++i) { + for (i = 0; i < elem.files.length; ++i) { var file = document.createElement("a"); file.innerText = elem.files[i]; file.href = window.rootPath + "src/" + fullPath + elem.files[i] + ".html"; diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index 7d05cb016b67c..5dea64ef14587 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -482,8 +482,8 @@ impl From for Struct { impl From for Variant { fn from(variant: clean::Variant) -> Self { - use clean::Variant::*; - match variant { + use clean::VariantKind::*; + match variant.kind { CLike => Variant::Plain, Tuple(t) => Variant::Tuple(t.into_iter().map(Into::into).collect()), Struct(s) => Variant::Struct(ids(s.fields)), diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 719aca612f50d..7ed64c5813fcd 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -15,6 +15,7 @@ #![feature(never_type)] #![feature(once_cell)] #![feature(type_ascription)] +#![feature(split_inclusive)] #![feature(str_split_once)] #![feature(iter_intersperse)] #![recursion_limit = "256"] @@ -411,7 +412,11 @@ fn opts() -> Vec { ) }), unstable("test-builder", |o| { - o.optopt("", "test-builder", "The rustc-like binary to use as the test builder", "PATH") + o.optflag( + "", + "test-builder", + "specified the rustc-like binary to use as the test builder", + ) }), unstable("check", |o| o.optflag("", "check", "Run rustdoc checks")), ] diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index 2694450a520c9..708d7710058d5 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -19,8 +19,9 @@ use rustc_session::lint::{ builtin::{BROKEN_INTRA_DOC_LINKS, PRIVATE_INTRA_DOC_LINKS}, Lint, }; -use rustc_span::hygiene::{MacroKind, SyntaxContext}; -use rustc_span::symbol::{sym, Ident, Symbol}; +use rustc_span::hygiene::MacroKind; +use rustc_span::symbol::Ident; +use rustc_span::symbol::Symbol; use rustc_span::DUMMY_SP; use smallvec::{smallvec, SmallVec}; @@ -769,12 +770,7 @@ fn traits_implemented_by(cx: &DocContext<'_>, type_: DefId, module: DefId) -> Fx let mut cache = cx.module_trait_cache.borrow_mut(); let in_scope_traits = cache.entry(module).or_insert_with(|| { cx.enter_resolver(|resolver| { - let parent_scope = &ParentScope::module(resolver.get_module(module), resolver); - resolver - .traits_in_scope(None, parent_scope, SyntaxContext::root(), None) - .into_iter() - .map(|candidate| candidate.def_id) - .collect() + resolver.traits_in_scope(module).into_iter().map(|candidate| candidate.def_id).collect() }) }); @@ -1194,7 +1190,7 @@ impl LinkCollector<'_, '_> { }; match res { - Res::Primitive(prim) => { + Res::Primitive(_) => { if let Some((kind, id)) = self.kind_side_channel.take() { // We're actually resolving an associated item of a primitive, so we need to // verify the disambiguator (if any) matches the type of the associated item. @@ -1205,29 +1201,6 @@ impl LinkCollector<'_, '_> { // valid omission. See https://github.com/rust-lang/rust/pull/80660#discussion_r551585677 // for discussion on the matter. verify(kind, id)?; - - if prim == PrimitiveType::RawPointer - && !self.cx.tcx.features().intra_doc_pointers - { - let span = super::source_span_for_markdown_range( - cx, - dox, - &ori_link.range, - &item.attrs, - ) - .unwrap_or_else(|| { - span_of_attrs(&item.attrs).unwrap_or(item.source.span()) - }); - - rustc_session::parse::feature_err( - &self.cx.tcx.sess.parse_sess, - sym::intra_doc_pointers, - span, - "linking to associated items of raw pointers is experimental", - ) - .note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does") - .emit(); - } } else { match disambiguator { Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {} @@ -1237,7 +1210,6 @@ impl LinkCollector<'_, '_> { } } } - Some(ItemLink { link: ori_link.link, link_text, did: None, fragment }) } Res::Def(kind, id) => { diff --git a/src/librustdoc/passes/stripper.rs b/src/librustdoc/passes/stripper.rs index 162b70973b418..a1924422f0e5e 100644 --- a/src/librustdoc/passes/stripper.rs +++ b/src/librustdoc/passes/stripper.rs @@ -94,7 +94,7 @@ impl<'a> DocFolder for Stripper<'a> { // implementations of traits are always public. clean::ImplItem(ref imp) if imp.trait_.is_some() => true, // Struct variant fields have inherited visibility - clean::VariantItem(clean::Variant::Struct(..)) => true, + clean::VariantItem(clean::Variant { kind: clean::VariantKind::Struct(..) }) => true, _ => false, }; diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index 7d161ca3648cc..1fedd26a1ef2f 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -316,7 +316,15 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { } } - om.items.push((item, renamed)) + om.imports.push(Import { + name, + id: item.hir_id, + vis: &item.vis, + attrs: &item.attrs, + path, + glob: is_glob, + span: item.span, + }); } hir::ItemKind::Mod(ref m) => { om.mods.push(self.visit_mod_contents( @@ -344,10 +352,10 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { om.items.push((item, renamed)); } } - hir::ItemKind::Impl(ref impl_) => { + hir::ItemKind::Impl { ref of_trait, .. } => { // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick // them up regardless of where they're located. - if !self.inlining && impl_.of_trait.is_none() { + if !self.inlining && of_trait.is_none() { om.items.push((item, None)); } } diff --git a/src/llvm-project b/src/llvm-project index f9a8d70b6e036..fb115ee43b776 160000 --- a/src/llvm-project +++ b/src/llvm-project @@ -1 +1 @@ -Subproject commit f9a8d70b6e0365ac2172ca6b7f1de0341297458d +Subproject commit fb115ee43b77601b237717c21ab0a8f5b5b9d50a diff --git a/src/test/assembly/stack-probes.rs b/src/test/assembly/stack-probes.rs deleted file mode 100644 index 9597e242f1b0f..0000000000000 --- a/src/test/assembly/stack-probes.rs +++ /dev/null @@ -1,42 +0,0 @@ -// min-llvm-version: 11.0.1 -// revisions: x86_64 i686 -// assembly-output: emit-asm -//[x86_64] compile-flags: --target x86_64-unknown-linux-gnu -//[i686] compile-flags: --target i686-unknown-linux-gnu -// compile-flags: -C llvm-args=--x86-asm-syntax=intel - -#![feature(no_core, lang_items)] -#![crate_type = "lib"] -#![no_core] - -#[lang = "sized"] -trait Sized {} -#[lang = "copy"] -trait Copy {} - -impl Copy for u8 {} - -// Check that inline-asm stack probes are generated correctly. -// To avoid making this test fragile to slight asm changes, -// we only check that the stack pointer is decremented by a page at a time, -// instead of matching the whole probe sequence. - -// CHECK-LABEL: small_stack_probe: -#[no_mangle] -pub fn small_stack_probe(x: u8, f: fn([u8; 8192])) { - // CHECK-NOT: __rust_probestack - // x86_64: sub rsp, 4096 - // i686: sub esp, 4096 - let a = [x; 8192]; - f(a); -} - -// CHECK-LABEL: big_stack_probe: -#[no_mangle] -pub fn big_stack_probe(x: u8, f: fn([u8; 65536])) { - // CHECK-NOT: __rust_probestack - // x86_64: sub rsp, 4096 - // i686: sub esp, 4096 - let a = [x; 65536]; - f(a); -} diff --git a/src/test/codegen/call-llvm-intrinsics.rs b/src/test/codegen/call-llvm-intrinsics.rs index 998099c239098..24e3d3cd64b58 100644 --- a/src/test/codegen/call-llvm-intrinsics.rs +++ b/src/test/codegen/call-llvm-intrinsics.rs @@ -13,7 +13,7 @@ impl Drop for A { } } -extern "C" { +extern { #[link_name = "llvm.sqrt.f32"] fn sqrt(x: f32) -> f32; } diff --git a/src/test/codegen/dealloc-no-unwind.rs b/src/test/codegen/dealloc-no-unwind.rs index f047c7a180ce2..ff21b4caa83c3 100644 --- a/src/test/codegen/dealloc-no-unwind.rs +++ b/src/test/codegen/dealloc-no-unwind.rs @@ -8,7 +8,7 @@ struct A; impl Drop for A { fn drop(&mut self) { - extern "C" { fn foo(); } + extern { fn foo(); } unsafe { foo(); } } } diff --git a/src/test/codegen/debug-column.rs b/src/test/codegen/debug-column.rs index 5d3afef5289bf..f348c48566d51 100644 --- a/src/test/codegen/debug-column.rs +++ b/src/test/codegen/debug-column.rs @@ -18,7 +18,7 @@ fn main() { } } -extern "C" { +extern { fn giraffe(); fn turtle(); } diff --git a/src/test/codegen/debug-linkage-name.rs b/src/test/codegen/debug-linkage-name.rs index 9011a7da51db8..0d7dca3aba344 100644 --- a/src/test/codegen/debug-linkage-name.rs +++ b/src/test/codegen/debug-linkage-name.rs @@ -26,17 +26,17 @@ pub mod xyz { // CHECK: !DISubprogram(name: "e", // CHECK: linkageName: // CHECK-SAME: line: 29, - pub extern "C" fn e() {} + pub extern fn e() {} // CHECK: !DISubprogram(name: "f", // CHECK-NOT: linkageName: // CHECK-SAME: line: 35, #[no_mangle] - pub extern "C" fn f() {} + pub extern fn f() {} // CHECK: !DISubprogram(name: "g", // CHECK-NOT: linkageName: // CHECK-SAME: line: 41, #[export_name = "g"] - pub extern "C" fn g() {} + pub extern fn g() {} } diff --git a/src/test/codegen/export-no-mangle.rs b/src/test/codegen/export-no-mangle.rs index a89d48ee1533f..59e97601c838d 100644 --- a/src/test/codegen/export-no-mangle.rs +++ b/src/test/codegen/export-no-mangle.rs @@ -13,19 +13,19 @@ mod private { // CHECK: void @a() #[no_mangle] - pub extern "C" fn a() {} + pub extern fn a() {} // CHECK: void @b() #[export_name = "b"] - extern "C" fn b() {} + extern fn b() {} // CHECK: void @c() #[export_name = "c"] #[inline] - extern "C" fn c() {} + extern fn c() {} // CHECK: void @d() #[export_name = "d"] #[inline(always)] - extern "C" fn d() {} + extern fn d() {} } diff --git a/src/test/codegen/ffi-const.rs b/src/test/codegen/ffi-const.rs index 67baf6fdd3e03..440d022a12cba 100644 --- a/src/test/codegen/ffi-const.rs +++ b/src/test/codegen/ffi-const.rs @@ -4,7 +4,7 @@ pub fn bar() { unsafe { foo() } } -extern "C" { +extern { // CHECK-LABEL: declare void @foo() // CHECK-SAME: [[ATTRS:#[0-9]+]] // CHECK-DAG: attributes [[ATTRS]] = { {{.*}}readnone{{.*}} } diff --git a/src/test/codegen/ffi-out-of-bounds-loads.rs b/src/test/codegen/ffi-out-of-bounds-loads.rs index dc16306eb96be..139a06ab53d05 100644 --- a/src/test/codegen/ffi-out-of-bounds-loads.rs +++ b/src/test/codegen/ffi-out-of-bounds-loads.rs @@ -11,7 +11,7 @@ struct S { f3: i32, } -extern "C" { +extern { fn foo(s: S); } diff --git a/src/test/codegen/ffi-pure.rs b/src/test/codegen/ffi-pure.rs index 3afb0856c9d72..f0ebc1caa09bd 100644 --- a/src/test/codegen/ffi-pure.rs +++ b/src/test/codegen/ffi-pure.rs @@ -4,7 +4,7 @@ pub fn bar() { unsafe { foo() } } -extern "C" { +extern { // CHECK-LABEL: declare void @foo() // CHECK-SAME: [[ATTRS:#[0-9]+]] // CHECK-DAG: attributes [[ATTRS]] = { {{.*}}readonly{{.*}} } diff --git a/src/test/codegen/ffi-returns-twice.rs b/src/test/codegen/ffi-returns-twice.rs index 75301dfd346eb..4db328f1cdfaf 100644 --- a/src/test/codegen/ffi-returns-twice.rs +++ b/src/test/codegen/ffi-returns-twice.rs @@ -4,7 +4,7 @@ pub fn bar() { unsafe { foo() } } -extern "C" { +extern { // CHECK-LABEL: declare void @foo() // CHECK-SAME: [[ATTRS:#[0-9]+]] // CHECK-DAG: attributes [[ATTRS]] = { {{.*}}returns_twice{{.*}} } diff --git a/src/test/codegen/intrinsics/move-val-init.rs b/src/test/codegen/intrinsics/move-val-init.rs new file mode 100644 index 0000000000000..6222536b50600 --- /dev/null +++ b/src/test/codegen/intrinsics/move-val-init.rs @@ -0,0 +1,19 @@ +// compile-flags: -C no-prepopulate-passes + +#![feature(core_intrinsics)] +#![crate_type = "lib"] + +// test that `move_val_init` actually avoids big allocas + +use std::intrinsics::move_val_init; + +pub struct Big { + pub data: [u8; 65536] +} + +// CHECK-LABEL: @test_mvi +#[no_mangle] +pub unsafe fn test_mvi(target: *mut Big, make_big: fn() -> Big) { + // CHECK: call void %make_big(%Big*{{[^%]*}} %target) + move_val_init(target, make_big()); +} diff --git a/src/test/codegen/issue-47278.rs b/src/test/codegen/issue-47278.rs index 9076274f45e94..590e8ea850290 100644 --- a/src/test/codegen/issue-47278.rs +++ b/src/test/codegen/issue-47278.rs @@ -6,4 +6,4 @@ pub struct Foo(u64); // CHECK: define {{.*}} @foo( #[no_mangle] -pub extern "C" fn foo(_: Foo) -> Foo { loop {} } +pub extern fn foo(_: Foo) -> Foo { loop {} } diff --git a/src/test/codegen/issue-59352.rs b/src/test/codegen/issue-59352.rs deleted file mode 100644 index 28bb85912324e..0000000000000 --- a/src/test/codegen/issue-59352.rs +++ /dev/null @@ -1,18 +0,0 @@ -// This test is a mirror of mir-opt/issues/issue-59352.rs. The LLVM inliner doesn't inline -// `char::method::is_digit()` and `char::method::to_digit()`, probably because of their size. -// -// Currently, the MIR optimizer isn't capable of removing the unreachable panic in this test case. -// Once the optimizer can do that, mir-opt/issues/issue-59352.rs will need to be updated and this -// test case should be removed as it will become redundant. - -// mir-opt-level=2 enables inlining and enables LLVM to optimize away the unreachable panic call. -// compile-flags: -O -Z mir-opt-level=2 - -#![crate_type = "rlib"] - -// CHECK-LABEL: @num_to_digit -#[no_mangle] -pub fn num_to_digit(num: char) -> u32 { - // CHECK-NOT: panic - if num.is_digit(8) { num.to_digit(8).unwrap() } else { 0 } -} diff --git a/src/test/codegen/repr-transparent-aggregates-1.rs b/src/test/codegen/repr-transparent-aggregates-1.rs index 2b8d3c8bc1d22..59f29e756fc9a 100644 --- a/src/test/codegen/repr-transparent-aggregates-1.rs +++ b/src/test/codegen/repr-transparent-aggregates-1.rs @@ -36,19 +36,19 @@ pub enum TeBigS { // CHECK: define void @test_BigS(%BigS* [[BIGS_RET_ATTRS:.*]], %BigS* [[BIGS_ARG_ATTRS1:.*]] byval(%BigS) [[BIGS_ARG_ATTRS2:.*]]) #[no_mangle] -pub extern "C" fn test_BigS(_: BigS) -> BigS { loop {} } +pub extern fn test_BigS(_: BigS) -> BigS { loop {} } // CHECK: define void @test_TsBigS(%TsBigS* [[BIGS_RET_ATTRS]], %TsBigS* [[BIGS_ARG_ATTRS1]] byval(%TsBigS) [[BIGS_ARG_ATTRS2:.*]]) #[no_mangle] -pub extern "C" fn test_TsBigS(_: TsBigS) -> TsBigS { loop {} } +pub extern fn test_TsBigS(_: TsBigS) -> TsBigS { loop {} } // CHECK: define void @test_TuBigS(%TuBigS* [[BIGS_RET_ATTRS]], %TuBigS* [[BIGS_ARG_ATTRS1]] byval(%TuBigS) [[BIGS_ARG_ATTRS2:.*]]) #[no_mangle] -pub extern "C" fn test_TuBigS(_: TuBigS) -> TuBigS { loop {} } +pub extern fn test_TuBigS(_: TuBigS) -> TuBigS { loop {} } // CHECK: define void @test_TeBigS(%"TeBigS::Variant"* [[BIGS_RET_ATTRS]], %"TeBigS::Variant"* [[BIGS_ARG_ATTRS1]] byval(%"TeBigS::Variant") [[BIGS_ARG_ATTRS2]]) #[no_mangle] -pub extern "C" fn test_TeBigS(_: TeBigS) -> TeBigS { loop {} } +pub extern fn test_TeBigS(_: TeBigS) -> TeBigS { loop {} } #[derive(Clone, Copy)] @@ -72,16 +72,16 @@ pub enum TeBigU { // CHECK: define void @test_BigU(%BigU* [[BIGU_RET_ATTRS:.*]], %BigU* [[BIGU_ARG_ATTRS1:.*]] byval(%BigU) [[BIGU_ARG_ATTRS2:.*]]) #[no_mangle] -pub extern "C" fn test_BigU(_: BigU) -> BigU { loop {} } +pub extern fn test_BigU(_: BigU) -> BigU { loop {} } // CHECK: define void @test_TsBigU(%TsBigU* [[BIGU_RET_ATTRS:.*]], %TsBigU* [[BIGU_ARG_ATTRS1]] byval(%TsBigU) [[BIGU_ARG_ATTRS2]]) #[no_mangle] -pub extern "C" fn test_TsBigU(_: TsBigU) -> TsBigU { loop {} } +pub extern fn test_TsBigU(_: TsBigU) -> TsBigU { loop {} } // CHECK: define void @test_TuBigU(%TuBigU* [[BIGU_RET_ATTRS]], %TuBigU* [[BIGU_ARG_ATTRS1]] byval(%TuBigU) [[BIGU_ARG_ATTRS2]]) #[no_mangle] -pub extern "C" fn test_TuBigU(_: TuBigU) -> TuBigU { loop {} } +pub extern fn test_TuBigU(_: TuBigU) -> TuBigU { loop {} } // CHECK: define void @test_TeBigU(%"TeBigU::Variant"* [[BIGU_RET_ATTRS]], %"TeBigU::Variant"* [[BIGU_ARG_ATTRS1]] byval(%"TeBigU::Variant") [[BIGU_ARG_ATTRS2]]) #[no_mangle] -pub extern "C" fn test_TeBigU(_: TeBigU) -> TeBigU { loop {} } +pub extern fn test_TeBigU(_: TeBigU) -> TeBigU { loop {} } diff --git a/src/test/codegen/repr-transparent.rs b/src/test/codegen/repr-transparent.rs index 29997313511b2..7647e0198769c 100644 --- a/src/test/codegen/repr-transparent.rs +++ b/src/test/codegen/repr-transparent.rs @@ -19,21 +19,21 @@ pub struct F32(f32); // CHECK: define float @test_F32(float %_1) #[no_mangle] -pub extern "C" fn test_F32(_: F32) -> F32 { loop {} } +pub extern fn test_F32(_: F32) -> F32 { loop {} } #[repr(transparent)] pub struct Ptr(*mut u8); // CHECK: define i8* @test_Ptr(i8* %_1) #[no_mangle] -pub extern "C" fn test_Ptr(_: Ptr) -> Ptr { loop {} } +pub extern fn test_Ptr(_: Ptr) -> Ptr { loop {} } #[repr(transparent)] pub struct WithZst(u64, Zst1); // CHECK: define i64 @test_WithZst(i64 %_1) #[no_mangle] -pub extern "C" fn test_WithZst(_: WithZst) -> WithZst { loop {} } +pub extern fn test_WithZst(_: WithZst) -> WithZst { loop {} } #[repr(transparent)] pub struct WithZeroSizedArray(*const f32, [i8; 0]); @@ -41,14 +41,14 @@ pub struct WithZeroSizedArray(*const f32, [i8; 0]); // Apparently we use i32* when newtype-unwrapping f32 pointers. Whatever. // CHECK: define i32* @test_WithZeroSizedArray(i32* %_1) #[no_mangle] -pub extern "C" fn test_WithZeroSizedArray(_: WithZeroSizedArray) -> WithZeroSizedArray { loop {} } +pub extern fn test_WithZeroSizedArray(_: WithZeroSizedArray) -> WithZeroSizedArray { loop {} } #[repr(transparent)] pub struct Generic(T); // CHECK: define double @test_Generic(double %_1) #[no_mangle] -pub extern "C" fn test_Generic(_: Generic) -> Generic { loop {} } +pub extern fn test_Generic(_: Generic) -> Generic { loop {} } #[repr(transparent)] pub struct GenericPlusZst(T, Zst2); @@ -58,14 +58,14 @@ pub enum Bool { True, False, FileNotFound } // CHECK: define{{( zeroext)?}} i8 @test_Gpz(i8{{( zeroext)?}} %_1) #[no_mangle] -pub extern "C" fn test_Gpz(_: GenericPlusZst) -> GenericPlusZst { loop {} } +pub extern fn test_Gpz(_: GenericPlusZst) -> GenericPlusZst { loop {} } #[repr(transparent)] pub struct LifetimePhantom<'a, T: 'a>(*const T, PhantomData<&'a T>); // CHECK: define i16* @test_LifetimePhantom(i16* %_1) #[no_mangle] -pub extern "C" fn test_LifetimePhantom(_: LifetimePhantom) -> LifetimePhantom { loop {} } +pub extern fn test_LifetimePhantom(_: LifetimePhantom) -> LifetimePhantom { loop {} } // This works despite current alignment resrictions because PhantomData is always align(1) #[repr(transparent)] @@ -75,28 +75,28 @@ pub struct Px; // CHECK: define float @test_UnitPhantom(float %_1) #[no_mangle] -pub extern "C" fn test_UnitPhantom(_: UnitPhantom) -> UnitPhantom { loop {} } +pub extern fn test_UnitPhantom(_: UnitPhantom) -> UnitPhantom { loop {} } #[repr(transparent)] pub struct TwoZsts(Zst1, i8, Zst2); // CHECK: define{{( signext)?}} i8 @test_TwoZsts(i8{{( signext)?}} %_1) #[no_mangle] -pub extern "C" fn test_TwoZsts(_: TwoZsts) -> TwoZsts { loop {} } +pub extern fn test_TwoZsts(_: TwoZsts) -> TwoZsts { loop {} } #[repr(transparent)] pub struct Nested1(Zst2, Generic); // CHECK: define double @test_Nested1(double %_1) #[no_mangle] -pub extern "C" fn test_Nested1(_: Nested1) -> Nested1 { loop {} } +pub extern fn test_Nested1(_: Nested1) -> Nested1 { loop {} } #[repr(transparent)] pub struct Nested2(Nested1, Zst1); // CHECK: define double @test_Nested2(double %_1) #[no_mangle] -pub extern "C" fn test_Nested2(_: Nested2) -> Nested2 { loop {} } +pub extern fn test_Nested2(_: Nested2) -> Nested2 { loop {} } #[repr(simd)] struct f32x4(f32, f32, f32, f32); @@ -106,7 +106,7 @@ pub struct Vector(f32x4); // CHECK: define <4 x float> @test_Vector(<4 x float> %_1) #[no_mangle] -pub extern "C" fn test_Vector(_: Vector) -> Vector { loop {} } +pub extern fn test_Vector(_: Vector) -> Vector { loop {} } trait Mirror { type It: ?Sized; } impl Mirror for T { type It = Self; } @@ -116,7 +116,7 @@ pub struct StructWithProjection(::It); // CHECK: define float @test_Projection(float %_1) #[no_mangle] -pub extern "C" fn test_Projection(_: StructWithProjection) -> StructWithProjection { loop {} } +pub extern fn test_Projection(_: StructWithProjection) -> StructWithProjection { loop {} } #[repr(transparent)] pub enum EnumF32 { @@ -125,7 +125,7 @@ pub enum EnumF32 { // CHECK: define float @test_EnumF32(float %_1) #[no_mangle] -pub extern "C" fn test_EnumF32(_: EnumF32) -> EnumF32 { loop {} } +pub extern fn test_EnumF32(_: EnumF32) -> EnumF32 { loop {} } #[repr(transparent)] pub enum EnumF32WithZsts { @@ -134,7 +134,7 @@ pub enum EnumF32WithZsts { // CHECK: define float @test_EnumF32WithZsts(float %_1) #[no_mangle] -pub extern "C" fn test_EnumF32WithZsts(_: EnumF32WithZsts) -> EnumF32WithZsts { loop {} } +pub extern fn test_EnumF32WithZsts(_: EnumF32WithZsts) -> EnumF32WithZsts { loop {} } #[repr(transparent)] pub union UnionF32 { @@ -143,7 +143,7 @@ pub union UnionF32 { // CHECK: define float @test_UnionF32(float %_1) #[no_mangle] -pub extern "C" fn test_UnionF32(_: UnionF32) -> UnionF32 { loop {} } +pub extern fn test_UnionF32(_: UnionF32) -> UnionF32 { loop {} } #[repr(transparent)] pub union UnionF32WithZsts { @@ -154,7 +154,7 @@ pub union UnionF32WithZsts { // CHECK: define float @test_UnionF32WithZsts(float %_1) #[no_mangle] -pub extern "C" fn test_UnionF32WithZsts(_: UnionF32WithZsts) -> UnionF32WithZsts { loop {} } +pub extern fn test_UnionF32WithZsts(_: UnionF32WithZsts) -> UnionF32WithZsts { loop {} } // All that remains to be tested are aggregates. They are tested in separate files called repr- diff --git a/src/test/codegen/riscv-abi/call-llvm-intrinsics.rs b/src/test/codegen/riscv-abi/call-llvm-intrinsics.rs index 31a88f2c0a981..f100a23a31897 100644 --- a/src/test/codegen/riscv-abi/call-llvm-intrinsics.rs +++ b/src/test/codegen/riscv-abi/call-llvm-intrinsics.rs @@ -13,7 +13,7 @@ impl Drop for A { } } -extern "C" { +extern { #[link_name = "llvm.sqrt.f32"] fn sqrt(x: f32) -> f32; } diff --git a/src/test/codegen/slice-as_chunks.rs b/src/test/codegen/slice-as_chunks.rs deleted file mode 100644 index 48e3f73fc8637..0000000000000 --- a/src/test/codegen/slice-as_chunks.rs +++ /dev/null @@ -1,33 +0,0 @@ -// no-system-llvm -// compile-flags: -O -// only-64bit (because the LLVM type of i64 for usize shows up) -// ignore-debug: the debug assertions get in the way - -#![crate_type = "lib"] -#![feature(slice_as_chunks)] - -// CHECK-LABEL: @chunks4 -#[no_mangle] -pub fn chunks4(x: &[u8]) -> &[[u8; 4]] { - // CHECK-NEXT: start: - // CHECK-NEXT: lshr i64 %x.1, 2 - // CHECK-NOT: shl - // CHECK-NOT: mul - // CHECK-NOT: udiv - // CHECK-NOT: urem - // CHECK: ret - x.as_chunks().0 -} - -// CHECK-LABEL: @chunks4_with_remainder -#[no_mangle] -pub fn chunks4_with_remainder(x: &[u8]) -> (&[[u8; 4]], &[u8]) { - // CHECK: and i64 %x.1, -4 - // CHECK: and i64 %x.1, 3 - // CHECK: lshr exact - // CHECK-NOT: mul - // CHECK-NOT: udiv - // CHECK-NOT: urem - // CHECK: ret - x.as_chunks() -} diff --git a/src/test/codegen/stack-probes.rs b/src/test/codegen/stack-probes.rs index b05787df8e30b..3e3222d4735ad 100644 --- a/src/test/codegen/stack-probes.rs +++ b/src/test/codegen/stack-probes.rs @@ -13,12 +13,11 @@ // ignore-emscripten // ignore-windows // compile-flags: -C no-prepopulate-passes -// min-llvm-version: 11.0.1 #![crate_type = "lib"] #[no_mangle] pub fn foo() { // CHECK: @foo() unnamed_addr #0 -// CHECK: attributes #0 = { {{.*}}"probe-stack"="inline-asm"{{.*}} } +// CHECK: attributes #0 = { {{.*}}"probe-stack"="__rust_probestack"{{.*}} } } diff --git a/src/test/codegen/target-cpu-on-functions.rs b/src/test/codegen/target-cpu-on-functions.rs index 7544ac0130952..523216deb8400 100644 --- a/src/test/codegen/target-cpu-on-functions.rs +++ b/src/test/codegen/target-cpu-on-functions.rs @@ -9,7 +9,7 @@ // CHECK-LABEL: define {{.*}} @exported() {{.*}} #0 #[no_mangle] -pub extern "C" fn exported() { +pub extern fn exported() { not_exported(); } diff --git a/src/test/codegen/unwind-extern-exports.rs b/src/test/codegen/unwind-extern-exports.rs index 487de20671a2c..e5a2936b92497 100644 --- a/src/test/codegen/unwind-extern-exports.rs +++ b/src/test/codegen/unwind-extern-exports.rs @@ -11,7 +11,7 @@ // "C" ABI // pub extern fn foo() {} // FIXME right now we don't abort-on-panic but add `nounwind` nevertheless #[unwind(allowed)] -pub extern "C" fn foo_allowed() {} +pub extern fn foo_allowed() {} // "Rust" // (`extern "Rust"` could be removed as all `fn` get it implicitly; we leave it in for clarity.) diff --git a/src/test/codegen/unwind-extern-imports.rs b/src/test/codegen/unwind-extern-imports.rs index a2ba24aca259b..8403e1e9da9fa 100644 --- a/src/test/codegen/unwind-extern-imports.rs +++ b/src/test/codegen/unwind-extern-imports.rs @@ -4,7 +4,7 @@ #![crate_type = "lib"] #![feature(unwind_attributes)] -extern "C" { +extern { // CHECK: Function Attrs:{{.*}}nounwind // CHECK-NEXT: declare void @extern_fn fn extern_fn(); diff --git a/src/test/codegen/vecdeque_no_panic.rs b/src/test/codegen/vecdeque_no_panic.rs deleted file mode 100644 index cbf420bada994..0000000000000 --- a/src/test/codegen/vecdeque_no_panic.rs +++ /dev/null @@ -1,19 +0,0 @@ -// This test checks that `VecDeque::front[_mut]()` and `VecDeque::back[_mut]()` can't panic. - -// compile-flags: -O -// ignore-debug: the debug assertions get in the way - -#![crate_type = "lib"] - -use std::collections::VecDeque; - -// CHECK-LABEL: @dont_panic -#[no_mangle] -pub fn dont_panic(v: &mut VecDeque) { - // CHECK-NOT: expect - // CHECK-NOT: panic - v.front(); - v.front_mut(); - v.back(); - v.back_mut(); -} diff --git a/src/test/debuginfo/type-names.rs b/src/test/debuginfo/type-names.rs index 43e68fedbfafb..1e0e8beb10f9d 100644 --- a/src/test/debuginfo/type-names.rs +++ b/src/test/debuginfo/type-names.rs @@ -23,6 +23,7 @@ // gdbg-check:type = struct Struct2 // gdbr-check:type = type_names::mod1::Struct2 + // ENUMS // gdb-command:whatis simple_enum_1 // gdbg-check:type = union Enum1 @@ -44,6 +45,7 @@ // gdbg-check:type = union Enum3 // gdbr-check:type = type_names::mod1::mod2::Enum3 + // TUPLES // gdb-command:whatis tuple1 // gdbg-check:type = struct (u32, type_names::Struct1, type_names::mod1::mod2::Enum3) @@ -53,6 +55,7 @@ // gdbg-check:type = struct ((type_names::Struct1, type_names::mod1::mod2::Struct3), type_names::mod1::Enum2, char) // gdbr-check:type = ((type_names::Struct1, type_names::mod1::mod2::Struct3), type_names::mod1::Enum2, char) + // BOX // gdb-command:whatis box1 // gdbg-check:type = struct (alloc::boxed::Box, i32) @@ -62,6 +65,7 @@ // gdbg-check:type = struct (alloc::boxed::Box>, i32) // gdbr-check:type = (alloc::boxed::Box>, i32) + // REFERENCES // gdb-command:whatis ref1 // gdbg-check:type = struct (&type_names::Struct1, i32) @@ -79,6 +83,7 @@ // gdbg-check:type = struct (&mut type_names::GenericStruct, i32) // gdbr-check:type = (&mut type_names::GenericStruct, i32) + // RAW POINTERS // gdb-command:whatis mut_ptr1 // gdbg-check:type = struct (*mut type_names::Struct1, isize) @@ -104,6 +109,7 @@ // gdbg-check:type = struct (*const type_names::mod1::mod2::Enum3, isize) // gdbr-check:type = (*const type_names::mod1::mod2::Enum3, isize) + // VECTORS // gdb-command:whatis fixed_size_vec1 // gdbg-check:type = struct ([type_names::Struct1; 3], i16) @@ -121,6 +127,7 @@ // gdbg-check:type = struct &[type_names::mod1::Enum2] // gdbr-check:type = &[type_names::mod1::Enum2] + // TRAITS // gdb-command:whatis box_trait // gdbg-check:type = struct Box @@ -146,6 +153,7 @@ // gdbg-check:type = struct &mut Trait2> // gdbr-check:type = type_names::&mut Trait2> + // BARE FUNCTIONS // gdb-command:whatis rust_fn // gdbg-check:type = struct (fn(core::option::Option, core::option::Option<&type_names::mod1::Struct2>), usize) @@ -191,6 +199,7 @@ // gdbg-check:type = struct (unsafe extern "C" fn(*const u8, ...) -> isize, usize) // gdbr-check:type = (unsafe extern "C" fn(*const u8, ...) -> isize, usize) + // CLOSURES // gdb-command:whatis closure1 // gdbg-check:type = struct (closure, usize) @@ -210,7 +219,7 @@ use std::marker::PhantomData; use std::ptr; pub struct Struct1; -struct GenericStruct(PhantomData<(T1, T2)>); +struct GenericStruct(PhantomData<(T1,T2)>); enum Enum1 { Variant1, @@ -237,12 +246,8 @@ mod mod1 { } } -trait Trait1 { - fn dummy(&self) {} -} -trait Trait2 { - fn dummy(&self, _: T1, _: T2) {} -} +trait Trait1 { fn dummy(&self) { } } +trait Trait2 { fn dummy(&self, _: T1, _:T2) { } } impl Trait1 for isize {} impl Trait2 for isize {} @@ -252,26 +257,16 @@ extern "C" fn extern_c_fn(_: isize) {} unsafe fn unsafe_fn(_: Result) {} extern "stdcall" fn extern_stdcall_fn() {} -fn rust_fn_with_return_value(_: f64) -> usize { - 4 -} -extern "C" fn extern_c_fn_with_return_value() -> Struct1 { - Struct1 -} -unsafe fn unsafe_fn_with_return_value(_: GenericStruct) -> mod1::Struct2 { - mod1::Struct2 -} -extern "stdcall" fn extern_stdcall_fn_with_return_value(_: Box) -> usize { - 0 -} +fn rust_fn_with_return_value(_: f64) -> usize { 4 } +extern "C" fn extern_c_fn_with_return_value() -> Struct1 { Struct1 } +unsafe fn unsafe_fn_with_return_value(_: GenericStruct) -> mod1::Struct2 { mod1::Struct2 } +extern "stdcall" fn extern_stdcall_fn_with_return_value(_: Box) -> usize { 0 } -fn generic_function(x: T) -> T { - x -} +fn generic_function(x: T) -> T { x } #[allow(improper_ctypes)] -extern "C" { - fn printf(_: *const u8, ...) -> isize; +extern { + fn printf(_:*const u8, ...) -> isize; } // In many of the cases below, the type that is actually under test is wrapped @@ -282,6 +277,7 @@ extern "C" { // printed correctly, so the tests below just construct a tuple type that will // then *contain* the type name that we want to see. fn main() { + // Structs let simple_struct = Struct1; let generic_struct1: GenericStruct = @@ -340,11 +336,11 @@ fn main() { let mut_ref_trait = (&mut mut_int1) as &mut Trait1; let generic_box_trait = (box 0_isize) as Box>; - let generic_ref_trait = (&0_isize) as &Trait2; + let generic_ref_trait = (&0_isize) as &Trait2; let mut generic_mut_ref_trait_impl = 0_isize; - let generic_mut_ref_trait = (&mut generic_mut_ref_trait_impl) - as &mut Trait2>; + let generic_mut_ref_trait = (&mut generic_mut_ref_trait_impl) as + &mut Trait2>; // Bare Functions let rust_fn = (rust_fn, 0_usize); @@ -368,13 +364,11 @@ fn main() { // how that maps to rustc's internal representation of these forms. // Once closures have reached their 1.0 form, the tests below should // probably be expanded. - let closure1 = (|x: isize| {}, 0_usize); - let closure2 = (|x: i8, y: f32| (x as f32) + y, 0_usize); + let closure1 = (|x:isize| {}, 0_usize); + let closure2 = (|x:i8, y: f32| { (x as f32) + y }, 0_usize); zzz(); // #break } #[inline(never)] -fn zzz() { - () -} +fn zzz() { () } diff --git a/src/test/incremental/foreign.rs b/src/test/incremental/foreign.rs index f46f92eb50020..498bf89225000 100644 --- a/src/test/incremental/foreign.rs +++ b/src/test/incremental/foreign.rs @@ -13,7 +13,7 @@ use std::ffi::CString; mod mlibc { use libc::{c_char, c_long, c_longlong}; - extern "C" { + extern { pub fn atol(x: *const c_char) -> c_long; pub fn atoll(x: *const c_char) -> c_longlong; } @@ -31,8 +31,6 @@ fn atoll(s: String) -> i64 { pub fn main() { assert_eq!(atol("1024".to_string()) * 10, atol("10240".to_string())); - assert_eq!( - (atoll("11111111111111111".to_string()) * 10), - atoll("111111111111111110".to_string()) - ); + assert_eq!((atoll("11111111111111111".to_string()) * 10), + atoll("111111111111111110".to_string())); } diff --git a/src/test/incremental/hashes/if_expressions.rs b/src/test/incremental/hashes/if_expressions.rs index ca8daae152cdd..59af1fc09c2de 100644 --- a/src/test/incremental/hashes/if_expressions.rs +++ b/src/test/incremental/hashes/if_expressions.rs @@ -94,7 +94,7 @@ pub fn add_else_branch(x: bool) -> u32 { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,typeck")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes")] #[rustc_clean(cfg="cfail3")] pub fn add_else_branch(x: bool) -> u32 { let mut ret = 1; diff --git a/src/test/incremental/hashes/inherent_impls.rs b/src/test/incremental/hashes/inherent_impls.rs index 2e98abae58b3d..fcd12ad30ebc9 100644 --- a/src/test/incremental/hashes/inherent_impls.rs +++ b/src/test/incremental/hashes/inherent_impls.rs @@ -271,7 +271,7 @@ impl Foo { impl Foo { #[rustc_clean(cfg="cfail2", except="hir_owner,hir_owner_nodes,fn_sig,typeck")] #[rustc_clean(cfg="cfail3")] - pub extern "C" fn make_method_extern(&self) { } + pub extern fn make_method_extern(&self) { } } diff --git a/src/test/incremental/hashes/trait_defs.rs b/src/test/incremental/hashes/trait_defs.rs index 4dab032e47f35..aa39ea88e0ec0 100644 --- a/src/test/incremental/hashes/trait_defs.rs +++ b/src/test/incremental/hashes/trait_defs.rs @@ -312,7 +312,7 @@ trait TraitAddExternModifier { trait TraitAddExternModifier { #[rustc_dirty(label="hir_owner", cfg="cfail2")] #[rustc_clean(label="hir_owner", cfg="cfail3")] - extern "C" fn method(); + extern fn method(); } diff --git a/src/test/incremental/hygiene/load_cached_hygiene.rs b/src/test/incremental/hygiene/load_cached_hygiene.rs index 8124141418bc3..d6a5cb993a467 100644 --- a/src/test/incremental/hygiene/load_cached_hygiene.rs +++ b/src/test/incremental/hygiene/load_cached_hygiene.rs @@ -1,5 +1,5 @@ // revisions:rpass1 rpass2 -// compile-flags: -Z query-dep-graph +// compile-flags: -Z query-dep-graph -O // aux-build:cached_hygiene.rs // This tests the folllowing scenario @@ -19,7 +19,12 @@ // the metadata. Specifically, we were not resetting `orig_id` // for an `EpxnData` generate in the current crate, which would cause // us to serialize the `ExpnId` pointing to a garbage location in -// the metadata. +// the metadata.o + +// NOTE: We're explicitly passing the `-O` optimization flag because if optimizations are not +// enabled, then rustc will ignore the `#[inline(always)]` attribute which means we do not load +// the optimized mir for the unmodified function to be loaded and so the CGU containing that +// function will be reused. #![feature(rustc_attrs)] diff --git a/src/test/incremental/issue-80336-invalid-span.rs b/src/test/incremental/issue-80336-invalid-span.rs deleted file mode 100644 index 7757d915911df..0000000000000 --- a/src/test/incremental/issue-80336-invalid-span.rs +++ /dev/null @@ -1,10 +0,0 @@ -// Regression test for issue #80336 -// Test that we properly handle encoding, decoding, and hashing -// of spans with an invalid location and non-root `SyntaxContext` - -// revisions:rpass1 rpass2 -// only-x86_64 - -pub fn main() { - let _ = is_x86_feature_detected!("avx2"); -} diff --git a/src/test/incremental/remapped_paths_cc/main.rs b/src/test/incremental/remapped_paths_cc/main.rs index b01f02444eae8..735635029dac9 100644 --- a/src/test/incremental/remapped_paths_cc/main.rs +++ b/src/test/incremental/remapped_paths_cc/main.rs @@ -1,11 +1,18 @@ // revisions:rpass1 rpass2 rpass3 -// compile-flags: -Z query-dep-graph -g +// compile-flags: -Z query-dep-graph -g -O // aux-build:extern_crate.rs // ignore-asmjs wasm2js does not support source maps yet + // This test case makes sure that we detect if paths emitted into debuginfo // are changed, even when the change happens in an external crate. +// NOTE: We're explicitly passing the `-O` optimization flag because if no optimizations are +// requested, rustc will ignore the `#[inline]` attribute. This is a performance optimization for +// non-optimized builds which causes us to generate fewer copies of inlined functions when +// runtime performance doesn't matter. Without this flag, the function will go into a different +// CGU which can be reused by this crate. + #![feature(rustc_attrs)] #![rustc_partition_reused(module="main", cfg="rpass2")] diff --git a/src/test/mir-opt/const_prop/control_flow_simplification.hello.ConstProp.diff b/src/test/mir-opt/const_prop/control_flow_simplification.hello.ConstProp.diff index 64c270393735a..0d06c4960b363 100644 --- a/src/test/mir-opt/const_prop/control_flow_simplification.hello.ConstProp.diff +++ b/src/test/mir-opt/const_prop/control_flow_simplification.hello.ConstProp.diff @@ -9,12 +9,18 @@ bb0: { StorageLive(_1); // scope 0 at $DIR/control-flow-simplification.rs:12:8: 12:21 - _1 = const ::NEEDS; // scope 0 at $DIR/control-flow-simplification.rs:12:8: 12:21 -- switchInt(move _1) -> [false: bb2, otherwise: bb1]; // scope 0 at $DIR/control-flow-simplification.rs:12:5: 14:6 +- switchInt(_1) -> [false: bb1, otherwise: bb2]; // scope 0 at $DIR/control-flow-simplification.rs:12:5: 14:6 + _1 = const false; // scope 0 at $DIR/control-flow-simplification.rs:12:8: 12:21 -+ switchInt(const false) -> [false: bb2, otherwise: bb1]; // scope 0 at $DIR/control-flow-simplification.rs:12:5: 14:6 ++ switchInt(const false) -> [false: bb1, otherwise: bb2]; // scope 0 at $DIR/control-flow-simplification.rs:12:5: 14:6 } bb1: { + _0 = const (); // scope 0 at $DIR/control-flow-simplification.rs:14:6: 14:6 + StorageDead(_1); // scope 0 at $DIR/control-flow-simplification.rs:15:1: 15:2 + return; // scope 0 at $DIR/control-flow-simplification.rs:15:2: 15:2 + } + + bb2: { StorageLive(_2); // scope 0 at $SRC_DIR/std/src/macros.rs:LL:COL begin_panic::<&str>(const "explicit panic"); // scope 0 at $SRC_DIR/std/src/macros.rs:LL:COL // mir::Constant @@ -27,11 +33,5 @@ // + span: $SRC_DIR/std/src/macros.rs:LL:COL // + literal: Const { ty: &str, val: Value(Slice { data: Allocation { bytes: [101, 120, 112, 108, 105, 99, 105, 116, 32, 112, 97, 110, 105, 99], relocations: Relocations(SortedMap { data: [] }), init_mask: InitMask { blocks: [16383], len: Size { raw: 14 } }, size: Size { raw: 14 }, align: Align { pow2: 0 }, mutability: Not, extra: () }, start: 0, end: 14 }) } } - - bb2: { - _0 = const (); // scope 0 at $DIR/control-flow-simplification.rs:14:6: 14:6 - StorageDead(_1); // scope 0 at $DIR/control-flow-simplification.rs:14:5: 14:6 - return; // scope 0 at $DIR/control-flow-simplification.rs:15:2: 15:2 - } } diff --git a/src/test/mir-opt/coverage_graphviz.main.InstrumentCoverage.0.dot b/src/test/mir-opt/coverage_graphviz.main.InstrumentCoverage.0.dot index eeedbb215c0dd..5b6d73a7deefb 100644 --- a/src/test/mir-opt/coverage_graphviz.main.InstrumentCoverage.0.dot +++ b/src/test/mir-opt/coverage_graphviz.main.InstrumentCoverage.0.dot @@ -3,8 +3,8 @@ digraph Cov_0_3 { node [fontname="Courier, monospace"]; edge [fontname="Courier, monospace"]; bcb2__Cov_0_3 [shape="none", label=<
bcb2
Expression(bcb0 - bcb1) at 13:10-13:10
13:10-13:10: @4[0]: Coverage::Expression(4294967295) = 1 - 2 for $DIR/coverage_graphviz.rs:13:10 - 13:11
bb4: Goto
>]; - bcb1__Cov_0_3 [shape="none", label=<
bcb1
Counter(bcb1) at 12:13-12:18
12:13-12:18: @3[0]: Coverage::Expression(4294967294) = 2 + 0 for $DIR/coverage_graphviz.rs:15:1 - 15:2
Expression(bcb1 + 0) at 15:2-15:2
15:2-15:2: @3.Return: return
bb3: Return
>]; - bcb0__Cov_0_3 [shape="none", label=<
bcb0
Counter(bcb0) at 9:1-11:17
11:12-11:17: @1.Call: _2 = bar() -> [return: bb2, unwind: bb5]
bb0: FalseUnwind
bb1: Call
bb2: SwitchInt
>]; + bcb1__Cov_0_3 [shape="none", label=<
bcb1
Counter(bcb1) at 12:13-12:18
12:13-12:18: @5[0]: _0 = const ()
Expression(bcb1 + 0) at 15:2-15:2
15:2-15:2: @5.Return: return
bb3: FalseEdge
bb5: Return
>]; + bcb0__Cov_0_3 [shape="none", label=<
bcb0
Counter(bcb0) at 9:1-11:17
11:12-11:17: @1.Call: _2 = bar() -> [return: bb2, unwind: bb6]
11:12-11:17: @2[0]: FakeRead(ForMatchedPlace, _2)
bb0: FalseUnwind
bb1: Call
bb2: SwitchInt
>]; bcb2__Cov_0_3 -> bcb0__Cov_0_3 [label=<>]; bcb0__Cov_0_3 -> bcb2__Cov_0_3 [label=]; bcb0__Cov_0_3 -> bcb1__Cov_0_3 [label=]; diff --git a/src/test/mir-opt/deaggregator_test_enum_2.test1.Deaggregator.diff b/src/test/mir-opt/deaggregator_test_enum_2.test1.Deaggregator.diff index 6d2dbb820f962..bf99f7efb4dd6 100644 --- a/src/test/mir-opt/deaggregator_test_enum_2.test1.Deaggregator.diff +++ b/src/test/mir-opt/deaggregator_test_enum_2.test1.Deaggregator.diff @@ -12,20 +12,10 @@ bb0: { StorageLive(_3); // scope 0 at $DIR/deaggregator_test_enum_2.rs:10:8: 10:9 _3 = _1; // scope 0 at $DIR/deaggregator_test_enum_2.rs:10:8: 10:9 - switchInt(move _3) -> [false: bb2, otherwise: bb1]; // scope 0 at $DIR/deaggregator_test_enum_2.rs:10:5: 14:6 + switchInt(_3) -> [false: bb1, otherwise: bb2]; // scope 0 at $DIR/deaggregator_test_enum_2.rs:10:5: 14:6 } bb1: { - StorageLive(_4); // scope 0 at $DIR/deaggregator_test_enum_2.rs:11:16: 11:17 - _4 = _2; // scope 0 at $DIR/deaggregator_test_enum_2.rs:11:16: 11:17 -- _0 = Foo::A(move _4); // scope 0 at $DIR/deaggregator_test_enum_2.rs:11:9: 11:18 -+ ((_0 as A).0: i32) = move _4; // scope 0 at $DIR/deaggregator_test_enum_2.rs:11:9: 11:18 -+ discriminant(_0) = 0; // scope 0 at $DIR/deaggregator_test_enum_2.rs:11:9: 11:18 - StorageDead(_4); // scope 0 at $DIR/deaggregator_test_enum_2.rs:11:17: 11:18 - goto -> bb3; // scope 0 at $DIR/deaggregator_test_enum_2.rs:10:5: 14:6 - } - - bb2: { StorageLive(_5); // scope 0 at $DIR/deaggregator_test_enum_2.rs:13:16: 13:17 _5 = _2; // scope 0 at $DIR/deaggregator_test_enum_2.rs:13:16: 13:17 - _0 = Foo::B(move _5); // scope 0 at $DIR/deaggregator_test_enum_2.rs:13:9: 13:18 @@ -35,8 +25,18 @@ goto -> bb3; // scope 0 at $DIR/deaggregator_test_enum_2.rs:10:5: 14:6 } + bb2: { + StorageLive(_4); // scope 0 at $DIR/deaggregator_test_enum_2.rs:11:16: 11:17 + _4 = _2; // scope 0 at $DIR/deaggregator_test_enum_2.rs:11:16: 11:17 +- _0 = Foo::A(move _4); // scope 0 at $DIR/deaggregator_test_enum_2.rs:11:9: 11:18 ++ ((_0 as A).0: i32) = move _4; // scope 0 at $DIR/deaggregator_test_enum_2.rs:11:9: 11:18 ++ discriminant(_0) = 0; // scope 0 at $DIR/deaggregator_test_enum_2.rs:11:9: 11:18 + StorageDead(_4); // scope 0 at $DIR/deaggregator_test_enum_2.rs:11:17: 11:18 + goto -> bb3; // scope 0 at $DIR/deaggregator_test_enum_2.rs:10:5: 14:6 + } + bb3: { - StorageDead(_3); // scope 0 at $DIR/deaggregator_test_enum_2.rs:14:5: 14:6 + StorageDead(_3); // scope 0 at $DIR/deaggregator_test_enum_2.rs:15:1: 15:2 return; // scope 0 at $DIR/deaggregator_test_enum_2.rs:15:2: 15:2 } } diff --git a/src/test/mir-opt/dest-prop/branch.main.DestinationPropagation.diff b/src/test/mir-opt/dest-prop/branch.main.DestinationPropagation.diff index e11d24cac8c2e..9c213eaed3c04 100644 --- a/src/test/mir-opt/dest-prop/branch.main.DestinationPropagation.diff +++ b/src/test/mir-opt/dest-prop/branch.main.DestinationPropagation.diff @@ -36,16 +36,10 @@ } bb2: { - switchInt(move _3) -> [false: bb4, otherwise: bb3]; // scope 1 at $DIR/branch.rs:15:13: 20:6 + switchInt(_3) -> [false: bb3, otherwise: bb4]; // scope 1 at $DIR/branch.rs:15:13: 20:6 } bb3: { -- _2 = _1; // scope 1 at $DIR/branch.rs:16:9: 16:10 -+ nop; // scope 1 at $DIR/branch.rs:16:9: 16:10 - goto -> bb6; // scope 1 at $DIR/branch.rs:15:13: 20:6 - } - - bb4: { StorageLive(_4); // scope 1 at $DIR/branch.rs:18:9: 18:14 _4 = val() -> bb5; // scope 1 at $DIR/branch.rs:18:9: 18:14 // mir::Constant @@ -53,6 +47,12 @@ // + literal: Const { ty: fn() -> i32 {val}, val: Value(Scalar()) } } + bb4: { +- _2 = _1; // scope 1 at $DIR/branch.rs:16:9: 16:10 ++ nop; // scope 1 at $DIR/branch.rs:16:9: 16:10 + goto -> bb6; // scope 1 at $DIR/branch.rs:15:13: 20:6 + } + bb5: { StorageDead(_4); // scope 1 at $DIR/branch.rs:18:14: 18:15 - _2 = _1; // scope 1 at $DIR/branch.rs:19:9: 19:10 @@ -61,7 +61,7 @@ } bb6: { - StorageDead(_3); // scope 1 at $DIR/branch.rs:20:5: 20:6 + StorageDead(_3); // scope 1 at $DIR/branch.rs:20:6: 20:7 _0 = const (); // scope 0 at $DIR/branch.rs:12:11: 21:2 - StorageDead(_2); // scope 1 at $DIR/branch.rs:21:1: 21:2 - StorageDead(_1); // scope 0 at $DIR/branch.rs:21:1: 21:2 diff --git a/src/test/mir-opt/equal_true.opt.InstCombine.diff b/src/test/mir-opt/equal_true.opt.InstCombine.diff index 1bc4c0f8b37e3..a26776e70d6b9 100644 --- a/src/test/mir-opt/equal_true.opt.InstCombine.diff +++ b/src/test/mir-opt/equal_true.opt.InstCombine.diff @@ -14,21 +14,21 @@ - _2 = Eq(move _3, const true); // scope 0 at $DIR/equal_true.rs:4:8: 4:17 + _2 = move _3; // scope 0 at $DIR/equal_true.rs:4:8: 4:17 StorageDead(_3); // scope 0 at $DIR/equal_true.rs:4:16: 4:17 - switchInt(move _2) -> [false: bb2, otherwise: bb1]; // scope 0 at $DIR/equal_true.rs:4:5: 4:34 + switchInt(_2) -> [false: bb1, otherwise: bb2]; // scope 0 at $DIR/equal_true.rs:4:5: 4:34 } bb1: { - _0 = const 0_i32; // scope 0 at $DIR/equal_true.rs:4:20: 4:21 + _0 = const 1_i32; // scope 0 at $DIR/equal_true.rs:4:31: 4:32 goto -> bb3; // scope 0 at $DIR/equal_true.rs:4:5: 4:34 } bb2: { - _0 = const 1_i32; // scope 0 at $DIR/equal_true.rs:4:31: 4:32 + _0 = const 0_i32; // scope 0 at $DIR/equal_true.rs:4:20: 4:21 goto -> bb3; // scope 0 at $DIR/equal_true.rs:4:5: 4:34 } bb3: { - StorageDead(_2); // scope 0 at $DIR/equal_true.rs:4:33: 4:34 + StorageDead(_2); // scope 0 at $DIR/equal_true.rs:5:1: 5:2 return; // scope 0 at $DIR/equal_true.rs:5:2: 5:2 } } diff --git a/src/test/mir-opt/if_condition_int.dont_opt_bool.SimplifyComparisonIntegral.diff b/src/test/mir-opt/if_condition_int.dont_opt_bool.SimplifyComparisonIntegral.diff index 875e5a0a71f33..993ff660caaac 100644 --- a/src/test/mir-opt/if_condition_int.dont_opt_bool.SimplifyComparisonIntegral.diff +++ b/src/test/mir-opt/if_condition_int.dont_opt_bool.SimplifyComparisonIntegral.diff @@ -9,21 +9,21 @@ bb0: { StorageLive(_2); // scope 0 at $DIR/if-condition-int.rs:17:8: 17:9 _2 = _1; // scope 0 at $DIR/if-condition-int.rs:17:8: 17:9 - switchInt(move _2) -> [false: bb2, otherwise: bb1]; // scope 0 at $DIR/if-condition-int.rs:17:5: 17:26 + switchInt(_2) -> [false: bb1, otherwise: bb2]; // scope 0 at $DIR/if-condition-int.rs:17:5: 17:26 } bb1: { - _0 = const 0_u32; // scope 0 at $DIR/if-condition-int.rs:17:12: 17:13 + _0 = const 1_u32; // scope 0 at $DIR/if-condition-int.rs:17:23: 17:24 goto -> bb3; // scope 0 at $DIR/if-condition-int.rs:17:5: 17:26 } bb2: { - _0 = const 1_u32; // scope 0 at $DIR/if-condition-int.rs:17:23: 17:24 + _0 = const 0_u32; // scope 0 at $DIR/if-condition-int.rs:17:12: 17:13 goto -> bb3; // scope 0 at $DIR/if-condition-int.rs:17:5: 17:26 } bb3: { - StorageDead(_2); // scope 0 at $DIR/if-condition-int.rs:17:25: 17:26 + StorageDead(_2); // scope 0 at $DIR/if-condition-int.rs:18:1: 18:2 return; // scope 0 at $DIR/if-condition-int.rs:18:2: 18:2 } } diff --git a/src/test/mir-opt/if_condition_int.dont_opt_floats.SimplifyComparisonIntegral.diff b/src/test/mir-opt/if_condition_int.dont_opt_floats.SimplifyComparisonIntegral.diff index 2c4952402a49d..8ae9168c95098 100644 --- a/src/test/mir-opt/if_condition_int.dont_opt_floats.SimplifyComparisonIntegral.diff +++ b/src/test/mir-opt/if_condition_int.dont_opt_floats.SimplifyComparisonIntegral.diff @@ -16,21 +16,21 @@ // + span: $DIR/if-condition-int.rs:53:13: 53:18 // + literal: Const { ty: f32, val: Value(Scalar(0xc2280000)) } StorageDead(_3); // scope 0 at $DIR/if-condition-int.rs:53:17: 53:18 - switchInt(move _2) -> [false: bb2, otherwise: bb1]; // scope 0 at $DIR/if-condition-int.rs:53:5: 53:35 + switchInt(_2) -> [false: bb1, otherwise: bb2]; // scope 0 at $DIR/if-condition-int.rs:53:5: 53:35 } bb1: { - _0 = const 0_i32; // scope 0 at $DIR/if-condition-int.rs:53:21: 53:22 + _0 = const 1_i32; // scope 0 at $DIR/if-condition-int.rs:53:32: 53:33 goto -> bb3; // scope 0 at $DIR/if-condition-int.rs:53:5: 53:35 } bb2: { - _0 = const 1_i32; // scope 0 at $DIR/if-condition-int.rs:53:32: 53:33 + _0 = const 0_i32; // scope 0 at $DIR/if-condition-int.rs:53:21: 53:22 goto -> bb3; // scope 0 at $DIR/if-condition-int.rs:53:5: 53:35 } bb3: { - StorageDead(_2); // scope 0 at $DIR/if-condition-int.rs:53:34: 53:35 + StorageDead(_2); // scope 0 at $DIR/if-condition-int.rs:54:1: 54:2 return; // scope 0 at $DIR/if-condition-int.rs:54:2: 54:2 } } diff --git a/src/test/mir-opt/if_condition_int.opt_char.SimplifyComparisonIntegral.diff b/src/test/mir-opt/if_condition_int.opt_char.SimplifyComparisonIntegral.diff index 661591658df89..ae0960028a8b4 100644 --- a/src/test/mir-opt/if_condition_int.opt_char.SimplifyComparisonIntegral.diff +++ b/src/test/mir-opt/if_condition_int.opt_char.SimplifyComparisonIntegral.diff @@ -13,26 +13,26 @@ _3 = _1; // scope 0 at $DIR/if-condition-int.rs:21:8: 21:9 - _2 = Eq(move _3, const 'x'); // scope 0 at $DIR/if-condition-int.rs:21:8: 21:16 - StorageDead(_3); // scope 0 at $DIR/if-condition-int.rs:21:15: 21:16 -- switchInt(move _2) -> [false: bb2, otherwise: bb1]; // scope 0 at $DIR/if-condition-int.rs:21:5: 21:33 -+ nop; // scope 0 at $DIR/if-condition-int.rs:21:8: 21:16 +- switchInt(_2) -> [false: bb1, otherwise: bb2]; // scope 0 at $DIR/if-condition-int.rs:21:5: 21:33 ++ _2 = Eq(_3, const 'x'); // scope 0 at $DIR/if-condition-int.rs:21:8: 21:16 + nop; // scope 0 at $DIR/if-condition-int.rs:21:15: 21:16 -+ switchInt(move _3) -> ['x': bb1, otherwise: bb2]; // scope 0 at $DIR/if-condition-int.rs:21:5: 21:33 ++ switchInt(move _3) -> ['x': bb2, otherwise: bb1]; // scope 0 at $DIR/if-condition-int.rs:21:5: 21:33 } bb1: { + StorageDead(_3); // scope 0 at $DIR/if-condition-int.rs:21:5: 21:33 - _0 = const 0_u32; // scope 0 at $DIR/if-condition-int.rs:21:19: 21:20 + _0 = const 1_u32; // scope 0 at $DIR/if-condition-int.rs:21:30: 21:31 goto -> bb3; // scope 0 at $DIR/if-condition-int.rs:21:5: 21:33 } bb2: { + StorageDead(_3); // scope 0 at $DIR/if-condition-int.rs:21:5: 21:33 - _0 = const 1_u32; // scope 0 at $DIR/if-condition-int.rs:21:30: 21:31 + _0 = const 0_u32; // scope 0 at $DIR/if-condition-int.rs:21:19: 21:20 goto -> bb3; // scope 0 at $DIR/if-condition-int.rs:21:5: 21:33 } bb3: { - StorageDead(_2); // scope 0 at $DIR/if-condition-int.rs:21:32: 21:33 + StorageDead(_2); // scope 0 at $DIR/if-condition-int.rs:22:1: 22:2 return; // scope 0 at $DIR/if-condition-int.rs:22:2: 22:2 } } diff --git a/src/test/mir-opt/if_condition_int.opt_i8.SimplifyComparisonIntegral.diff b/src/test/mir-opt/if_condition_int.opt_i8.SimplifyComparisonIntegral.diff index 7d0ed7338d7d2..8d59e51ac2b11 100644 --- a/src/test/mir-opt/if_condition_int.opt_i8.SimplifyComparisonIntegral.diff +++ b/src/test/mir-opt/if_condition_int.opt_i8.SimplifyComparisonIntegral.diff @@ -13,26 +13,26 @@ _3 = _1; // scope 0 at $DIR/if-condition-int.rs:25:8: 25:9 - _2 = Eq(move _3, const 42_i8); // scope 0 at $DIR/if-condition-int.rs:25:8: 25:15 - StorageDead(_3); // scope 0 at $DIR/if-condition-int.rs:25:14: 25:15 -- switchInt(move _2) -> [false: bb2, otherwise: bb1]; // scope 0 at $DIR/if-condition-int.rs:25:5: 25:32 -+ nop; // scope 0 at $DIR/if-condition-int.rs:25:8: 25:15 +- switchInt(_2) -> [false: bb1, otherwise: bb2]; // scope 0 at $DIR/if-condition-int.rs:25:5: 25:32 ++ _2 = Eq(_3, const 42_i8); // scope 0 at $DIR/if-condition-int.rs:25:8: 25:15 + nop; // scope 0 at $DIR/if-condition-int.rs:25:14: 25:15 -+ switchInt(move _3) -> [42_i8: bb1, otherwise: bb2]; // scope 0 at $DIR/if-condition-int.rs:25:5: 25:32 ++ switchInt(move _3) -> [42_i8: bb2, otherwise: bb1]; // scope 0 at $DIR/if-condition-int.rs:25:5: 25:32 } bb1: { + StorageDead(_3); // scope 0 at $DIR/if-condition-int.rs:25:5: 25:32 - _0 = const 0_u32; // scope 0 at $DIR/if-condition-int.rs:25:18: 25:19 + _0 = const 1_u32; // scope 0 at $DIR/if-condition-int.rs:25:29: 25:30 goto -> bb3; // scope 0 at $DIR/if-condition-int.rs:25:5: 25:32 } bb2: { + StorageDead(_3); // scope 0 at $DIR/if-condition-int.rs:25:5: 25:32 - _0 = const 1_u32; // scope 0 at $DIR/if-condition-int.rs:25:29: 25:30 + _0 = const 0_u32; // scope 0 at $DIR/if-condition-int.rs:25:18: 25:19 goto -> bb3; // scope 0 at $DIR/if-condition-int.rs:25:5: 25:32 } bb3: { - StorageDead(_2); // scope 0 at $DIR/if-condition-int.rs:25:31: 25:32 + StorageDead(_2); // scope 0 at $DIR/if-condition-int.rs:26:1: 26:2 return; // scope 0 at $DIR/if-condition-int.rs:26:2: 26:2 } } diff --git a/src/test/mir-opt/if_condition_int.opt_multiple_ifs.SimplifyComparisonIntegral.diff b/src/test/mir-opt/if_condition_int.opt_multiple_ifs.SimplifyComparisonIntegral.diff index bf388a141b617..c4975661efe50 100644 --- a/src/test/mir-opt/if_condition_int.opt_multiple_ifs.SimplifyComparisonIntegral.diff +++ b/src/test/mir-opt/if_condition_int.opt_multiple_ifs.SimplifyComparisonIntegral.diff @@ -15,40 +15,40 @@ _3 = _1; // scope 0 at $DIR/if-condition-int.rs:33:8: 33:9 - _2 = Eq(move _3, const 42_u32); // scope 0 at $DIR/if-condition-int.rs:33:8: 33:15 - StorageDead(_3); // scope 0 at $DIR/if-condition-int.rs:33:14: 33:15 -- switchInt(move _2) -> [false: bb2, otherwise: bb1]; // scope 0 at $DIR/if-condition-int.rs:33:5: 39:6 -+ nop; // scope 0 at $DIR/if-condition-int.rs:33:8: 33:15 +- switchInt(_2) -> [false: bb1, otherwise: bb2]; // scope 0 at $DIR/if-condition-int.rs:33:5: 39:6 ++ _2 = Eq(_3, const 42_u32); // scope 0 at $DIR/if-condition-int.rs:33:8: 33:15 + nop; // scope 0 at $DIR/if-condition-int.rs:33:14: 33:15 -+ switchInt(move _3) -> [42_u32: bb1, otherwise: bb2]; // scope 0 at $DIR/if-condition-int.rs:33:5: 39:6 ++ switchInt(move _3) -> [42_u32: bb2, otherwise: bb1]; // scope 0 at $DIR/if-condition-int.rs:33:5: 39:6 } bb1: { -+ StorageDead(_3); // scope 0 at $DIR/if-condition-int.rs:33:5: 39:6 - _0 = const 0_u32; // scope 0 at $DIR/if-condition-int.rs:34:9: 34:10 - goto -> bb6; // scope 0 at $DIR/if-condition-int.rs:33:5: 39:6 - } - - bb2: { + StorageDead(_3); // scope 0 at $DIR/if-condition-int.rs:33:5: 39:6 StorageLive(_4); // scope 0 at $DIR/if-condition-int.rs:35:15: 35:22 StorageLive(_5); // scope 0 at $DIR/if-condition-int.rs:35:15: 35:16 _5 = _1; // scope 0 at $DIR/if-condition-int.rs:35:15: 35:16 - _4 = Ne(move _5, const 21_u32); // scope 0 at $DIR/if-condition-int.rs:35:15: 35:22 - StorageDead(_5); // scope 0 at $DIR/if-condition-int.rs:35:21: 35:22 -- switchInt(move _4) -> [false: bb4, otherwise: bb3]; // scope 0 at $DIR/if-condition-int.rs:35:12: 39:6 -+ nop; // scope 0 at $DIR/if-condition-int.rs:35:15: 35:22 +- switchInt(_4) -> [false: bb3, otherwise: bb4]; // scope 0 at $DIR/if-condition-int.rs:35:12: 39:6 ++ _4 = Ne(_5, const 21_u32); // scope 0 at $DIR/if-condition-int.rs:35:15: 35:22 + nop; // scope 0 at $DIR/if-condition-int.rs:35:21: 35:22 -+ switchInt(move _5) -> [21_u32: bb4, otherwise: bb3]; // scope 0 at $DIR/if-condition-int.rs:35:12: 39:6 ++ switchInt(move _5) -> [21_u32: bb3, otherwise: bb4]; // scope 0 at $DIR/if-condition-int.rs:35:12: 39:6 + } + + bb2: { ++ StorageDead(_3); // scope 0 at $DIR/if-condition-int.rs:33:5: 39:6 + _0 = const 0_u32; // scope 0 at $DIR/if-condition-int.rs:34:9: 34:10 + goto -> bb6; // scope 0 at $DIR/if-condition-int.rs:33:5: 39:6 } bb3: { + StorageDead(_5); // scope 0 at $DIR/if-condition-int.rs:35:12: 39:6 - _0 = const 1_u32; // scope 0 at $DIR/if-condition-int.rs:36:9: 36:10 + _0 = const 2_u32; // scope 0 at $DIR/if-condition-int.rs:38:9: 38:10 goto -> bb5; // scope 0 at $DIR/if-condition-int.rs:35:12: 39:6 } bb4: { + StorageDead(_5); // scope 0 at $DIR/if-condition-int.rs:35:12: 39:6 - _0 = const 2_u32; // scope 0 at $DIR/if-condition-int.rs:38:9: 38:10 + _0 = const 1_u32; // scope 0 at $DIR/if-condition-int.rs:36:9: 36:10 goto -> bb5; // scope 0 at $DIR/if-condition-int.rs:35:12: 39:6 } @@ -58,7 +58,7 @@ } bb6: { - StorageDead(_2); // scope 0 at $DIR/if-condition-int.rs:39:5: 39:6 + StorageDead(_2); // scope 0 at $DIR/if-condition-int.rs:40:1: 40:2 return; // scope 0 at $DIR/if-condition-int.rs:40:2: 40:2 } } diff --git a/src/test/mir-opt/if_condition_int.opt_negative.SimplifyComparisonIntegral.diff b/src/test/mir-opt/if_condition_int.opt_negative.SimplifyComparisonIntegral.diff index bee2e030b7ed5..d7f544e44c0fe 100644 --- a/src/test/mir-opt/if_condition_int.opt_negative.SimplifyComparisonIntegral.diff +++ b/src/test/mir-opt/if_condition_int.opt_negative.SimplifyComparisonIntegral.diff @@ -13,26 +13,26 @@ _3 = _1; // scope 0 at $DIR/if-condition-int.rs:29:8: 29:9 - _2 = Eq(move _3, const -42_i32); // scope 0 at $DIR/if-condition-int.rs:29:8: 29:16 - StorageDead(_3); // scope 0 at $DIR/if-condition-int.rs:29:15: 29:16 -- switchInt(move _2) -> [false: bb2, otherwise: bb1]; // scope 0 at $DIR/if-condition-int.rs:29:5: 29:33 -+ nop; // scope 0 at $DIR/if-condition-int.rs:29:8: 29:16 +- switchInt(_2) -> [false: bb1, otherwise: bb2]; // scope 0 at $DIR/if-condition-int.rs:29:5: 29:33 ++ _2 = Eq(_3, const -42_i32); // scope 0 at $DIR/if-condition-int.rs:29:8: 29:16 + nop; // scope 0 at $DIR/if-condition-int.rs:29:15: 29:16 -+ switchInt(move _3) -> [-42_i32: bb1, otherwise: bb2]; // scope 0 at $DIR/if-condition-int.rs:29:5: 29:33 ++ switchInt(move _3) -> [-42_i32: bb2, otherwise: bb1]; // scope 0 at $DIR/if-condition-int.rs:29:5: 29:33 } bb1: { + StorageDead(_3); // scope 0 at $DIR/if-condition-int.rs:29:5: 29:33 - _0 = const 0_u32; // scope 0 at $DIR/if-condition-int.rs:29:19: 29:20 + _0 = const 1_u32; // scope 0 at $DIR/if-condition-int.rs:29:30: 29:31 goto -> bb3; // scope 0 at $DIR/if-condition-int.rs:29:5: 29:33 } bb2: { + StorageDead(_3); // scope 0 at $DIR/if-condition-int.rs:29:5: 29:33 - _0 = const 1_u32; // scope 0 at $DIR/if-condition-int.rs:29:30: 29:31 + _0 = const 0_u32; // scope 0 at $DIR/if-condition-int.rs:29:19: 29:20 goto -> bb3; // scope 0 at $DIR/if-condition-int.rs:29:5: 29:33 } bb3: { - StorageDead(_2); // scope 0 at $DIR/if-condition-int.rs:29:32: 29:33 + StorageDead(_2); // scope 0 at $DIR/if-condition-int.rs:30:1: 30:2 return; // scope 0 at $DIR/if-condition-int.rs:30:2: 30:2 } } diff --git a/src/test/mir-opt/if_condition_int.opt_u32.SimplifyComparisonIntegral.diff b/src/test/mir-opt/if_condition_int.opt_u32.SimplifyComparisonIntegral.diff index 09a87591be107..51e00e680c286 100644 --- a/src/test/mir-opt/if_condition_int.opt_u32.SimplifyComparisonIntegral.diff +++ b/src/test/mir-opt/if_condition_int.opt_u32.SimplifyComparisonIntegral.diff @@ -13,26 +13,26 @@ _3 = _1; // scope 0 at $DIR/if-condition-int.rs:12:8: 12:9 - _2 = Eq(move _3, const 42_u32); // scope 0 at $DIR/if-condition-int.rs:12:8: 12:15 - StorageDead(_3); // scope 0 at $DIR/if-condition-int.rs:12:14: 12:15 -- switchInt(move _2) -> [false: bb2, otherwise: bb1]; // scope 0 at $DIR/if-condition-int.rs:12:5: 12:32 -+ nop; // scope 0 at $DIR/if-condition-int.rs:12:8: 12:15 +- switchInt(_2) -> [false: bb1, otherwise: bb2]; // scope 0 at $DIR/if-condition-int.rs:12:5: 12:32 ++ _2 = Eq(_3, const 42_u32); // scope 0 at $DIR/if-condition-int.rs:12:8: 12:15 + nop; // scope 0 at $DIR/if-condition-int.rs:12:14: 12:15 -+ switchInt(move _3) -> [42_u32: bb1, otherwise: bb2]; // scope 0 at $DIR/if-condition-int.rs:12:5: 12:32 ++ switchInt(move _3) -> [42_u32: bb2, otherwise: bb1]; // scope 0 at $DIR/if-condition-int.rs:12:5: 12:32 } bb1: { + StorageDead(_3); // scope 0 at $DIR/if-condition-int.rs:12:5: 12:32 - _0 = const 0_u32; // scope 0 at $DIR/if-condition-int.rs:12:18: 12:19 + _0 = const 1_u32; // scope 0 at $DIR/if-condition-int.rs:12:29: 12:30 goto -> bb3; // scope 0 at $DIR/if-condition-int.rs:12:5: 12:32 } bb2: { + StorageDead(_3); // scope 0 at $DIR/if-condition-int.rs:12:5: 12:32 - _0 = const 1_u32; // scope 0 at $DIR/if-condition-int.rs:12:29: 12:30 + _0 = const 0_u32; // scope 0 at $DIR/if-condition-int.rs:12:18: 12:19 goto -> bb3; // scope 0 at $DIR/if-condition-int.rs:12:5: 12:32 } bb3: { - StorageDead(_2); // scope 0 at $DIR/if-condition-int.rs:12:31: 12:32 + StorageDead(_2); // scope 0 at $DIR/if-condition-int.rs:13:1: 13:2 return; // scope 0 at $DIR/if-condition-int.rs:13:2: 13:2 } } diff --git a/src/test/mir-opt/inline/inline_diverging.g.Inline.diff b/src/test/mir-opt/inline/inline_diverging.g.Inline.diff index a746baa63eb53..3dc33354a5a56 100644 --- a/src/test/mir-opt/inline/inline_diverging.g.Inline.diff +++ b/src/test/mir-opt/inline/inline_diverging.g.Inline.diff @@ -19,19 +19,10 @@ _3 = _1; // scope 0 at $DIR/inline-diverging.rs:13:8: 13:9 _2 = Gt(move _3, const 0_i32); // scope 0 at $DIR/inline-diverging.rs:13:8: 13:13 StorageDead(_3); // scope 0 at $DIR/inline-diverging.rs:13:12: 13:13 - switchInt(move _2) -> [false: bb2, otherwise: bb1]; // scope 0 at $DIR/inline-diverging.rs:13:5: 17:6 + switchInt(_2) -> [false: bb1, otherwise: bb2]; // scope 0 at $DIR/inline-diverging.rs:13:5: 17:6 } bb1: { - StorageLive(_4); // scope 0 at $DIR/inline-diverging.rs:14:9: 14:10 - _4 = _1; // scope 0 at $DIR/inline-diverging.rs:14:9: 14:10 - _0 = move _4 as u32 (Misc); // scope 0 at $DIR/inline-diverging.rs:14:9: 14:17 - StorageDead(_4); // scope 0 at $DIR/inline-diverging.rs:14:16: 14:17 - StorageDead(_2); // scope 0 at $DIR/inline-diverging.rs:17:5: 17:6 - return; // scope 0 at $DIR/inline-diverging.rs:18:2: 18:2 - } - - bb2: { StorageLive(_6); // scope 0 at $DIR/inline-diverging.rs:16:9: 16:16 - panic(); // scope 0 at $DIR/inline-diverging.rs:16:9: 16:16 + StorageLive(_7); // scope 0 at $DIR/inline-diverging.rs:16:9: 16:16 @@ -48,5 +39,14 @@ + // + span: $DIR/inline-diverging.rs:16:9: 16:16 + // + literal: Const { ty: &str, val: Value(Slice { data: Allocation { bytes: [101, 120, 112, 108, 105, 99, 105, 116, 32, 112, 97, 110, 105, 99], relocations: Relocations(SortedMap { data: [] }), init_mask: InitMask { blocks: [16383], len: Size { raw: 14 } }, size: Size { raw: 14 }, align: Align { pow2: 0 }, mutability: Not, extra: () }, start: 0, end: 14 }) } } + + bb2: { + StorageLive(_4); // scope 0 at $DIR/inline-diverging.rs:14:9: 14:10 + _4 = _1; // scope 0 at $DIR/inline-diverging.rs:14:9: 14:10 + _0 = move _4 as u32 (Misc); // scope 0 at $DIR/inline-diverging.rs:14:9: 14:17 + StorageDead(_4); // scope 0 at $DIR/inline-diverging.rs:14:16: 14:17 + StorageDead(_2); // scope 0 at $DIR/inline-diverging.rs:18:1: 18:2 + return; // scope 0 at $DIR/inline-diverging.rs:18:2: 18:2 + } } diff --git a/src/test/mir-opt/inline/inline_generator.main.Inline.diff b/src/test/mir-opt/inline/inline_generator.main.Inline.diff index 066ac8d82d36b..99497a6fc791c 100644 --- a/src/test/mir-opt/inline/inline_generator.main.Inline.diff +++ b/src/test/mir-opt/inline/inline_generator.main.Inline.diff @@ -90,16 +90,16 @@ + + bb3: { + _8 = move _7; // scope 6 at $DIR/inline-generator.rs:9:14: 9:46 -+ switchInt(move _8) -> [false: bb5, otherwise: bb4]; // scope 6 at $DIR/inline-generator.rs:9:14: 9:46 ++ switchInt(_8) -> [false: bb4, otherwise: bb5]; // scope 6 at $DIR/inline-generator.rs:9:14: 9:46 + } + + bb4: { -+ ((_1 as Yielded).0: i32) = const 7_i32; // scope 6 at $DIR/inline-generator.rs:9:14: 9:46 ++ ((_1 as Yielded).0: i32) = const 13_i32; // scope 6 at $DIR/inline-generator.rs:9:14: 9:46 + goto -> bb6; // scope 6 at $DIR/inline-generator.rs:9:14: 9:46 + } + + bb5: { -+ ((_1 as Yielded).0: i32) = const 13_i32; // scope 6 at $DIR/inline-generator.rs:9:14: 9:46 ++ ((_1 as Yielded).0: i32) = const 7_i32; // scope 6 at $DIR/inline-generator.rs:9:14: 9:46 + goto -> bb6; // scope 6 at $DIR/inline-generator.rs:9:14: 9:46 + } + diff --git a/src/test/mir-opt/inst_combine_deref.do_not_miscompile.InstCombine.diff b/src/test/mir-opt/inst_combine_deref.do_not_miscompile.InstCombine.diff index ee8fcdcde4095..a8b523d06dfc7 100644 --- a/src/test/mir-opt/inst_combine_deref.do_not_miscompile.InstCombine.diff +++ b/src/test/mir-opt/inst_combine_deref.do_not_miscompile.InstCombine.diff @@ -53,10 +53,22 @@ StorageDead(_10); // scope 4 at $DIR/inst_combine_deref.rs:60:20: 60:21 _8 = Not(move _9); // scope 4 at $DIR/inst_combine_deref.rs:60:5: 60:23 StorageDead(_9); // scope 4 at $DIR/inst_combine_deref.rs:60:22: 60:23 - switchInt(move _8) -> [false: bb2, otherwise: bb1]; // scope 4 at $DIR/inst_combine_deref.rs:60:5: 60:23 + switchInt(_8) -> [false: bb1, otherwise: bb2]; // scope 4 at $DIR/inst_combine_deref.rs:60:5: 60:23 } bb1: { + _7 = const (); // scope 4 at $DIR/inst_combine_deref.rs:60:23: 60:23 + StorageDead(_8); // scope 4 at $DIR/inst_combine_deref.rs:60:22: 60:23 + StorageDead(_7); // scope 4 at $DIR/inst_combine_deref.rs:60:22: 60:23 + _0 = const (); // scope 0 at $DIR/inst_combine_deref.rs:54:24: 61:2 + StorageDead(_4); // scope 3 at $DIR/inst_combine_deref.rs:61:1: 61:2 + StorageDead(_3); // scope 2 at $DIR/inst_combine_deref.rs:61:1: 61:2 + StorageDead(_2); // scope 1 at $DIR/inst_combine_deref.rs:61:1: 61:2 + StorageDead(_1); // scope 0 at $DIR/inst_combine_deref.rs:61:1: 61:2 + return; // scope 0 at $DIR/inst_combine_deref.rs:61:2: 61:2 + } + + bb2: { StorageLive(_11); // scope 4 at $DIR/inst_combine_deref.rs:60:5: 60:23 core::panicking::panic(const "assertion failed: *y == 99"); // scope 4 at $DIR/inst_combine_deref.rs:60:5: 60:23 // mir::Constant @@ -69,17 +81,5 @@ // + span: $DIR/inst_combine_deref.rs:1:1: 1:1 // + literal: Const { ty: &str, val: Value(Slice { data: Allocation { bytes: [97, 115, 115, 101, 114, 116, 105, 111, 110, 32, 102, 97, 105, 108, 101, 100, 58, 32, 42, 121, 32, 61, 61, 32, 57, 57], relocations: Relocations(SortedMap { data: [] }), init_mask: InitMask { blocks: [67108863], len: Size { raw: 26 } }, size: Size { raw: 26 }, align: Align { pow2: 0 }, mutability: Not, extra: () }, start: 0, end: 26 }) } } - - bb2: { - _7 = const (); // scope 4 at $DIR/inst_combine_deref.rs:60:23: 60:23 - StorageDead(_8); // scope 4 at $DIR/inst_combine_deref.rs:60:22: 60:23 - StorageDead(_7); // scope 4 at $DIR/inst_combine_deref.rs:60:22: 60:23 - _0 = const (); // scope 0 at $DIR/inst_combine_deref.rs:54:24: 61:2 - StorageDead(_4); // scope 3 at $DIR/inst_combine_deref.rs:61:1: 61:2 - StorageDead(_3); // scope 2 at $DIR/inst_combine_deref.rs:61:1: 61:2 - StorageDead(_2); // scope 1 at $DIR/inst_combine_deref.rs:61:1: 61:2 - StorageDead(_1); // scope 0 at $DIR/inst_combine_deref.rs:61:1: 61:2 - return; // scope 0 at $DIR/inst_combine_deref.rs:61:2: 61:2 - } } diff --git a/src/test/mir-opt/instrument_coverage.main.InstrumentCoverage.diff b/src/test/mir-opt/instrument_coverage.main.InstrumentCoverage.diff index 226db9558ef46..9bd8c9cf61331 100644 --- a/src/test/mir-opt/instrument_coverage.main.InstrumentCoverage.diff +++ b/src/test/mir-opt/instrument_coverage.main.InstrumentCoverage.diff @@ -9,37 +9,42 @@ bb0: { + Coverage::Counter(1) for /the/src/instrument_coverage.rs:10:1 - 12:17; // scope 0 at /the/src/instrument_coverage.rs:11:5: 15:6 - falseUnwind -> [real: bb1, cleanup: bb5]; // scope 0 at /the/src/instrument_coverage.rs:11:5: 15:6 + falseUnwind -> [real: bb1, cleanup: bb6]; // scope 0 at /the/src/instrument_coverage.rs:11:5: 15:6 } bb1: { StorageLive(_2); // scope 0 at /the/src/instrument_coverage.rs:12:12: 12:17 - _2 = bar() -> [return: bb2, unwind: bb5]; // scope 0 at /the/src/instrument_coverage.rs:12:12: 12:17 + _2 = bar() -> [return: bb2, unwind: bb6]; // scope 0 at /the/src/instrument_coverage.rs:12:12: 12:17 // mir::Constant // + span: /the/src/instrument_coverage.rs:12:12: 12:15 // + literal: Const { ty: fn() -> bool {bar}, val: Value(Scalar()) } } bb2: { - switchInt(move _2) -> [false: bb4, otherwise: bb3]; // scope 0 at /the/src/instrument_coverage.rs:12:9: 14:10 + FakeRead(ForMatchedPlace, _2); // scope 0 at /the/src/instrument_coverage.rs:12:12: 12:17 + switchInt(_2) -> [false: bb4, otherwise: bb3]; // scope 0 at /the/src/instrument_coverage.rs:12:9: 14:10 } bb3: { -+ Coverage::Expression(4294967294) = 2 + 0 for /the/src/instrument_coverage.rs:16:1 - 16:2; // scope 0 at /the/src/instrument_coverage.rs:16:2: 16:2 -+ Coverage::Counter(2) for /the/src/instrument_coverage.rs:13:13 - 13:18; // scope 0 at /the/src/instrument_coverage.rs:16:2: 16:2 - _0 = const (); // scope 0 at /the/src/instrument_coverage.rs:13:13: 13:18 - StorageDead(_2); // scope 0 at /the/src/instrument_coverage.rs:14:9: 14:10 - return; // scope 0 at /the/src/instrument_coverage.rs:16:2: 16:2 ++ Coverage::Expression(4294967294) = 2 + 0 for /the/src/instrument_coverage.rs:16:1 - 16:2; // scope 0 at /the/src/instrument_coverage.rs:12:9: 14:10 ++ Coverage::Counter(2) for /the/src/instrument_coverage.rs:13:13 - 13:18; // scope 0 at /the/src/instrument_coverage.rs:12:9: 14:10 + falseEdge -> [real: bb5, imaginary: bb4]; // scope 0 at /the/src/instrument_coverage.rs:12:9: 14:10 } bb4: { + Coverage::Expression(4294967295) = 1 - 2 for /the/src/instrument_coverage.rs:14:10 - 14:11; // scope 0 at /the/src/instrument_coverage.rs:11:5: 15:6 _1 = const (); // scope 0 at /the/src/instrument_coverage.rs:14:10: 14:10 - StorageDead(_2); // scope 0 at /the/src/instrument_coverage.rs:14:9: 14:10 + StorageDead(_2); // scope 0 at /the/src/instrument_coverage.rs:15:5: 15:6 goto -> bb0; // scope 0 at /the/src/instrument_coverage.rs:11:5: 15:6 } - bb5 (cleanup): { + bb5: { + _0 = const (); // scope 0 at /the/src/instrument_coverage.rs:13:13: 13:18 + StorageDead(_2); // scope 0 at /the/src/instrument_coverage.rs:15:5: 15:6 + return; // scope 0 at /the/src/instrument_coverage.rs:16:2: 16:2 + } + + bb6 (cleanup): { resume; // scope 0 at /the/src/instrument_coverage.rs:10:1: 16:2 } } diff --git a/src/test/mir-opt/issue_38669.main.SimplifyCfg-initial.after.mir b/src/test/mir-opt/issue_38669.main.SimplifyCfg-initial.after.mir index e9e5a101a64a5..30036e4034af6 100644 --- a/src/test/mir-opt/issue_38669.main.SimplifyCfg-initial.after.mir +++ b/src/test/mir-opt/issue_38669.main.SimplifyCfg-initial.after.mir @@ -19,22 +19,19 @@ fn main() -> () { } bb1: { - falseUnwind -> [real: bb2, cleanup: bb5]; // scope 1 at $DIR/issue-38669.rs:6:5: 11:6 + falseUnwind -> [real: bb2, cleanup: bb6]; // scope 1 at $DIR/issue-38669.rs:6:5: 11:6 } bb2: { StorageLive(_3); // scope 1 at $DIR/issue-38669.rs:7:9: 9:10 StorageLive(_4); // scope 1 at $DIR/issue-38669.rs:7:12: 7:24 _4 = _1; // scope 1 at $DIR/issue-38669.rs:7:12: 7:24 - switchInt(move _4) -> [false: bb4, otherwise: bb3]; // scope 1 at $DIR/issue-38669.rs:7:9: 9:10 + FakeRead(ForMatchedPlace, _4); // scope 1 at $DIR/issue-38669.rs:7:12: 7:24 + switchInt(_4) -> [false: bb4, otherwise: bb3]; // scope 1 at $DIR/issue-38669.rs:7:9: 9:10 } bb3: { - _0 = const (); // scope 1 at $DIR/issue-38669.rs:8:13: 8:18 - StorageDead(_4); // scope 1 at $DIR/issue-38669.rs:9:9: 9:10 - StorageDead(_3); // scope 1 at $DIR/issue-38669.rs:9:9: 9:10 - StorageDead(_1); // scope 0 at $DIR/issue-38669.rs:12:1: 12:2 - return; // scope 0 at $DIR/issue-38669.rs:12:2: 12:2 + falseEdge -> [real: bb5, imaginary: bb4]; // scope 1 at $DIR/issue-38669.rs:7:9: 9:10 } bb4: { @@ -46,7 +43,15 @@ fn main() -> () { goto -> bb1; // scope 1 at $DIR/issue-38669.rs:6:5: 11:6 } - bb5 (cleanup): { + bb5: { + _0 = const (); // scope 1 at $DIR/issue-38669.rs:8:13: 8:18 + StorageDead(_4); // scope 1 at $DIR/issue-38669.rs:9:9: 9:10 + StorageDead(_3); // scope 1 at $DIR/issue-38669.rs:9:9: 9:10 + StorageDead(_1); // scope 0 at $DIR/issue-38669.rs:12:1: 12:2 + return; // scope 0 at $DIR/issue-38669.rs:12:2: 12:2 + } + + bb6 (cleanup): { resume; // scope 0 at $DIR/issue-38669.rs:4:1: 12:2 } } diff --git a/src/test/mir-opt/issue_41888.main.ElaborateDrops.after.mir b/src/test/mir-opt/issue_41888.main.ElaborateDrops.after.mir index 4fc7f9daa22b9..5011c2adfa581 100644 --- a/src/test/mir-opt/issue_41888.main.ElaborateDrops.after.mir +++ b/src/test/mir-opt/issue_41888.main.ElaborateDrops.after.mir @@ -33,10 +33,15 @@ fn main() -> () { } bb1: { - switchInt(move _2) -> [false: bb3, otherwise: bb2]; // scope 1 at $DIR/issue-41888.rs:8:5: 14:6 + switchInt(_2) -> [false: bb2, otherwise: bb3]; // scope 1 at $DIR/issue-41888.rs:8:5: 14:6 } bb2: { + _0 = const (); // scope 1 at $DIR/issue-41888.rs:14:6: 14:6 + goto -> bb7; // scope 1 at $DIR/issue-41888.rs:8:5: 14:6 + } + + bb3: { StorageLive(_3); // scope 1 at $DIR/issue-41888.rs:9:13: 9:20 StorageLive(_4); // scope 1 at $DIR/issue-41888.rs:9:18: 9:19 _4 = K; // scope 1 at $DIR/issue-41888.rs:9:18: 9:19 @@ -45,11 +50,6 @@ fn main() -> () { goto -> bb12; // scope 1 at $DIR/issue-41888.rs:9:9: 9:10 } - bb3: { - _0 = const (); // scope 1 at $DIR/issue-41888.rs:14:6: 14:6 - goto -> bb7; // scope 1 at $DIR/issue-41888.rs:8:5: 14:6 - } - bb4: { StorageDead(_3); // scope 1 at $DIR/issue-41888.rs:9:19: 9:20 _5 = discriminant(_1); // scope 1 at $DIR/issue-41888.rs:10:16: 10:24 @@ -71,7 +71,6 @@ fn main() -> () { } bb7: { - StorageDead(_2); // scope 1 at $DIR/issue-41888.rs:14:5: 14:6 goto -> bb18; // scope 0 at $DIR/issue-41888.rs:15:1: 15:2 } @@ -80,6 +79,7 @@ fn main() -> () { _8 = const false; // scope 0 at $DIR/issue-41888.rs:15:1: 15:2 _9 = const false; // scope 0 at $DIR/issue-41888.rs:15:1: 15:2 StorageDead(_1); // scope 0 at $DIR/issue-41888.rs:15:1: 15:2 + StorageDead(_2); // scope 0 at $DIR/issue-41888.rs:15:1: 15:2 return; // scope 0 at $DIR/issue-41888.rs:15:2: 15:2 } diff --git a/src/test/mir-opt/issue_73223.main.PreCodegen.32bit.diff b/src/test/mir-opt/issue_73223.main.PreCodegen.32bit.diff index 435b2a1360a6b..4db83c5c683d2 100644 --- a/src/test/mir-opt/issue_73223.main.PreCodegen.32bit.diff +++ b/src/test/mir-opt/issue_73223.main.PreCodegen.32bit.diff @@ -99,10 +99,19 @@ StorageDead(_11); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL _9 = Not(move _10); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageDead(_10); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - switchInt(move _9) -> [false: bb2, otherwise: bb1]; // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + switchInt(_9) -> [false: bb1, otherwise: bb2]; // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL } bb1: { + StorageDead(_9); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + StorageDead(_8); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + StorageDead(_7); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + _0 = const (); // scope 0 at $DIR/issue-73223.rs:1:11: 9:2 + StorageDead(_1); // scope 0 at $DIR/issue-73223.rs:9:1: 9:2 + return; // scope 0 at $DIR/issue-73223.rs:9:2: 9:2 + } + + bb2: { _13 = const main::promoted[0]; // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL // ty::Const // + ty: &[&str; 3] @@ -134,15 +143,6 @@ // + literal: Const { ty: unsafe extern "rust-intrinsic" fn(for<'r, 's, 't0> fn(&'r &i32, &'s mut std::fmt::Formatter<'t0>) -> std::result::Result<(), std::fmt::Error>) -> for<'r, 's, 't0> fn(&'r core::fmt::Opaque, &'s mut std::fmt::Formatter<'t0>) -> std::result::Result<(), std::fmt::Error> {std::intrinsics::transmute:: fn(&'r &i32, &'s mut std::fmt::Formatter<'t0>) -> std::result::Result<(), std::fmt::Error>, for<'r, 's, 't0> fn(&'r core::fmt::Opaque, &'s mut std::fmt::Formatter<'t0>) -> std::result::Result<(), std::fmt::Error>>}, val: Value(Scalar()) } } - bb2: { - StorageDead(_9); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_8); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_7); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - _0 = const (); // scope 0 at $DIR/issue-73223.rs:1:11: 9:2 - StorageDead(_1); // scope 0 at $DIR/issue-73223.rs:9:1: 9:2 - return; // scope 0 at $DIR/issue-73223.rs:9:2: 9:2 - } - bb3: { (_20.0: &core::fmt::Opaque) = transmute::<&&i32, &core::fmt::Opaque>(move _24) -> bb4; // scope 7 at $SRC_DIR/core/src/macros/mod.rs:LL:COL // mir::Constant diff --git a/src/test/mir-opt/issue_73223.main.PreCodegen.64bit.diff b/src/test/mir-opt/issue_73223.main.PreCodegen.64bit.diff index 435b2a1360a6b..4db83c5c683d2 100644 --- a/src/test/mir-opt/issue_73223.main.PreCodegen.64bit.diff +++ b/src/test/mir-opt/issue_73223.main.PreCodegen.64bit.diff @@ -99,10 +99,19 @@ StorageDead(_11); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL _9 = Not(move _10); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageDead(_10); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - switchInt(move _9) -> [false: bb2, otherwise: bb1]; // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + switchInt(_9) -> [false: bb1, otherwise: bb2]; // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL } bb1: { + StorageDead(_9); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + StorageDead(_8); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + StorageDead(_7); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + _0 = const (); // scope 0 at $DIR/issue-73223.rs:1:11: 9:2 + StorageDead(_1); // scope 0 at $DIR/issue-73223.rs:9:1: 9:2 + return; // scope 0 at $DIR/issue-73223.rs:9:2: 9:2 + } + + bb2: { _13 = const main::promoted[0]; // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL // ty::Const // + ty: &[&str; 3] @@ -134,15 +143,6 @@ // + literal: Const { ty: unsafe extern "rust-intrinsic" fn(for<'r, 's, 't0> fn(&'r &i32, &'s mut std::fmt::Formatter<'t0>) -> std::result::Result<(), std::fmt::Error>) -> for<'r, 's, 't0> fn(&'r core::fmt::Opaque, &'s mut std::fmt::Formatter<'t0>) -> std::result::Result<(), std::fmt::Error> {std::intrinsics::transmute:: fn(&'r &i32, &'s mut std::fmt::Formatter<'t0>) -> std::result::Result<(), std::fmt::Error>, for<'r, 's, 't0> fn(&'r core::fmt::Opaque, &'s mut std::fmt::Formatter<'t0>) -> std::result::Result<(), std::fmt::Error>>}, val: Value(Scalar()) } } - bb2: { - StorageDead(_9); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_8); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_7); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - _0 = const (); // scope 0 at $DIR/issue-73223.rs:1:11: 9:2 - StorageDead(_1); // scope 0 at $DIR/issue-73223.rs:9:1: 9:2 - return; // scope 0 at $DIR/issue-73223.rs:9:2: 9:2 - } - bb3: { (_20.0: &core::fmt::Opaque) = transmute::<&&i32, &core::fmt::Opaque>(move _24) -> bb4; // scope 7 at $SRC_DIR/core/src/macros/mod.rs:LL:COL // mir::Constant diff --git a/src/test/mir-opt/issue_73223.main.SimplifyArmIdentity.32bit.diff b/src/test/mir-opt/issue_73223.main.SimplifyArmIdentity.32bit.diff index d87cb2af8baac..4e362f3556b20 100644 --- a/src/test/mir-opt/issue_73223.main.SimplifyArmIdentity.32bit.diff +++ b/src/test/mir-opt/issue_73223.main.SimplifyArmIdentity.32bit.diff @@ -151,10 +151,23 @@ StorageDead(_17); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL _15 = Not(move _16); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageDead(_16); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - switchInt(move _15) -> [false: bb4, otherwise: bb3]; // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + switchInt(_15) -> [false: bb3, otherwise: bb4]; // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL } bb3: { + _8 = const (); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + StorageDead(_15); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + StorageDead(_14); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + StorageDead(_13); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + StorageDead(_9); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + StorageDead(_8); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + _0 = const (); // scope 0 at $DIR/issue-73223.rs:1:11: 9:2 + StorageDead(_6); // scope 1 at $DIR/issue-73223.rs:9:1: 9:2 + StorageDead(_1); // scope 0 at $DIR/issue-73223.rs:9:1: 9:2 + return; // scope 0 at $DIR/issue-73223.rs:9:2: 9:2 + } + + bb4: { StorageLive(_19); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageLive(_20); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageLive(_21); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL @@ -209,19 +222,6 @@ // + literal: Const { ty: unsafe extern "rust-intrinsic" fn(for<'r, 's, 't0> fn(&'r &i32, &'s mut std::fmt::Formatter<'t0>) -> std::result::Result<(), std::fmt::Error>) -> for<'r, 's, 't0> fn(&'r core::fmt::Opaque, &'s mut std::fmt::Formatter<'t0>) -> std::result::Result<(), std::fmt::Error> {std::intrinsics::transmute:: fn(&'r &i32, &'s mut std::fmt::Formatter<'t0>) -> std::result::Result<(), std::fmt::Error>, for<'r, 's, 't0> fn(&'r core::fmt::Opaque, &'s mut std::fmt::Formatter<'t0>) -> std::result::Result<(), std::fmt::Error>>}, val: Value(Scalar()) } } - bb4: { - _8 = const (); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_15); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_14); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_13); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_9); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_8); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - _0 = const (); // scope 0 at $DIR/issue-73223.rs:1:11: 9:2 - StorageDead(_6); // scope 1 at $DIR/issue-73223.rs:9:1: 9:2 - StorageDead(_1); // scope 0 at $DIR/issue-73223.rs:9:1: 9:2 - return; // scope 0 at $DIR/issue-73223.rs:9:2: 9:2 - } - bb5: { StorageDead(_45); // scope 7 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageLive(_46); // scope 7 at $SRC_DIR/core/src/macros/mod.rs:LL:COL diff --git a/src/test/mir-opt/issue_73223.main.SimplifyArmIdentity.64bit.diff b/src/test/mir-opt/issue_73223.main.SimplifyArmIdentity.64bit.diff index d87cb2af8baac..4e362f3556b20 100644 --- a/src/test/mir-opt/issue_73223.main.SimplifyArmIdentity.64bit.diff +++ b/src/test/mir-opt/issue_73223.main.SimplifyArmIdentity.64bit.diff @@ -151,10 +151,23 @@ StorageDead(_17); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL _15 = Not(move _16); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageDead(_16); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - switchInt(move _15) -> [false: bb4, otherwise: bb3]; // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + switchInt(_15) -> [false: bb3, otherwise: bb4]; // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL } bb3: { + _8 = const (); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + StorageDead(_15); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + StorageDead(_14); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + StorageDead(_13); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + StorageDead(_9); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + StorageDead(_8); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL + _0 = const (); // scope 0 at $DIR/issue-73223.rs:1:11: 9:2 + StorageDead(_6); // scope 1 at $DIR/issue-73223.rs:9:1: 9:2 + StorageDead(_1); // scope 0 at $DIR/issue-73223.rs:9:1: 9:2 + return; // scope 0 at $DIR/issue-73223.rs:9:2: 9:2 + } + + bb4: { StorageLive(_19); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageLive(_20); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageLive(_21); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL @@ -209,19 +222,6 @@ // + literal: Const { ty: unsafe extern "rust-intrinsic" fn(for<'r, 's, 't0> fn(&'r &i32, &'s mut std::fmt::Formatter<'t0>) -> std::result::Result<(), std::fmt::Error>) -> for<'r, 's, 't0> fn(&'r core::fmt::Opaque, &'s mut std::fmt::Formatter<'t0>) -> std::result::Result<(), std::fmt::Error> {std::intrinsics::transmute:: fn(&'r &i32, &'s mut std::fmt::Formatter<'t0>) -> std::result::Result<(), std::fmt::Error>, for<'r, 's, 't0> fn(&'r core::fmt::Opaque, &'s mut std::fmt::Formatter<'t0>) -> std::result::Result<(), std::fmt::Error>>}, val: Value(Scalar()) } } - bb4: { - _8 = const (); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_15); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_14); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_13); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_9); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - StorageDead(_8); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL - _0 = const (); // scope 0 at $DIR/issue-73223.rs:1:11: 9:2 - StorageDead(_6); // scope 1 at $DIR/issue-73223.rs:9:1: 9:2 - StorageDead(_1); // scope 0 at $DIR/issue-73223.rs:9:1: 9:2 - return; // scope 0 at $DIR/issue-73223.rs:9:2: 9:2 - } - bb5: { StorageDead(_45); // scope 7 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageLive(_46); // scope 7 at $SRC_DIR/core/src/macros/mod.rs:LL:COL diff --git a/src/test/mir-opt/issues/issue-59352.rs b/src/test/mir-opt/issues/issue-59352.rs deleted file mode 100644 index 9e59337a01d5c..0000000000000 --- a/src/test/mir-opt/issues/issue-59352.rs +++ /dev/null @@ -1,19 +0,0 @@ -// This test is a mirror of codegen/issue-59352.rs. -// The LLVM inliner doesn't inline `char::method::is_digit()` and so it doesn't recognize this case -// as effectively `if x.is_some() { x.unwrap() } else { 0 }`. -// -// Currently, the MIR optimizer isn't capable of removing the unreachable panic in this test case. -// Once the optimizer can do that, this test case will need to be updated and codegen/issue-59352.rs -// removed. - -// EMIT_MIR issue_59352.num_to_digit.PreCodegen.after.mir -// compile-flags: -Z mir-opt-level=2 -Z span_free_formats - -pub fn num_to_digit(num: char) -> u32 { - // CHECK-NOT: panic - if num.is_digit(8) { num.to_digit(8).unwrap() } else { 0 } -} - -pub fn main() { - num_to_digit('2'); -} diff --git a/src/test/mir-opt/issues/issue_59352.num_to_digit.PreCodegen.after.mir b/src/test/mir-opt/issues/issue_59352.num_to_digit.PreCodegen.after.mir deleted file mode 100644 index 04a8c94e003c4..0000000000000 --- a/src/test/mir-opt/issues/issue_59352.num_to_digit.PreCodegen.after.mir +++ /dev/null @@ -1,102 +0,0 @@ -// MIR for `num_to_digit` after PreCodegen - -fn num_to_digit(_1: char) -> u32 { - debug num => _1; // in scope 0 at $DIR/issue-59352.rs:12:21: 12:24 - let mut _0: u32; // return place in scope 0 at $DIR/issue-59352.rs:12:35: 12:38 - let mut _2: bool; // in scope 0 at $DIR/issue-59352.rs:14:8: 14:23 - let mut _3: std::option::Option; // in scope 0 at $DIR/issue-59352.rs:14:26: 14:41 - let mut _4: char; // in scope 0 at $DIR/issue-59352.rs:14:26: 14:29 - let mut _5: u32; // in scope 0 at $DIR/issue-59352.rs:14:8: 14:23 - let mut _10: isize; // in scope 0 at $DIR/issue-59352.rs:14:8: 14:23 - scope 1 (inlined char::methods::::is_digit) { // at $DIR/issue-59352.rs:14:8: 14:23 - debug self => _8; // in scope 1 at $DIR/issue-59352.rs:14:8: 14:23 - debug radix => _5; // in scope 1 at $DIR/issue-59352.rs:14:8: 14:23 - let mut _6: &std::option::Option; // in scope 1 at $DIR/issue-59352.rs:14:8: 14:23 - let _7: std::option::Option; // in scope 1 at $DIR/issue-59352.rs:14:8: 14:23 - let mut _8: char; // in scope 1 at $DIR/issue-59352.rs:14:8: 14:23 - scope 2 (inlined Option::::is_some) { // at $DIR/issue-59352.rs:14:8: 14:23 - debug self => _6; // in scope 2 at $DIR/issue-59352.rs:14:8: 14:23 - } - } - scope 3 (inlined #[track_caller] Option::::unwrap) { // at $DIR/issue-59352.rs:14:26: 14:50 - debug self => _3; // in scope 3 at $DIR/issue-59352.rs:14:26: 14:50 - let mut _9: isize; // in scope 3 at $DIR/issue-59352.rs:14:26: 14:50 - scope 4 { - debug val => _0; // in scope 4 at $DIR/issue-59352.rs:14:26: 14:50 - } - } - - bb0: { - StorageLive(_2); // scope 0 at $DIR/issue-59352.rs:14:8: 14:23 - _8 = _1; // scope 0 at $DIR/issue-59352.rs:14:8: 14:11 - StorageLive(_5); // scope 0 at $DIR/issue-59352.rs:14:8: 14:23 - _5 = const 8_u32; // scope 0 at $DIR/issue-59352.rs:14:8: 14:23 - StorageLive(_6); // scope 1 at $DIR/issue-59352.rs:14:8: 14:23 - StorageLive(_7); // scope 1 at $DIR/issue-59352.rs:14:8: 14:23 - _7 = char::methods::::to_digit(move _8, const 8_u32) -> bb5; // scope 1 at $DIR/issue-59352.rs:14:8: 14:23 - // mir::Constant - // + span: $DIR/issue-59352.rs:14:8: 14:23 - // + literal: Const { ty: fn(char, u32) -> std::option::Option {std::char::methods::::to_digit}, val: Value(Scalar()) } - } - - bb1: { - StorageLive(_3); // scope 0 at $DIR/issue-59352.rs:14:26: 14:41 - StorageLive(_4); // scope 0 at $DIR/issue-59352.rs:14:26: 14:29 - _4 = _1; // scope 0 at $DIR/issue-59352.rs:14:26: 14:29 - _3 = char::methods::::to_digit(move _4, const 8_u32) -> bb3; // scope 0 at $DIR/issue-59352.rs:14:26: 14:41 - // mir::Constant - // + span: $DIR/issue-59352.rs:14:30: 14:38 - // + literal: Const { ty: fn(char, u32) -> std::option::Option {std::char::methods::::to_digit}, val: Value(Scalar()) } - } - - bb2: { - _0 = const 0_u32; // scope 0 at $DIR/issue-59352.rs:14:60: 14:61 - goto -> bb4; // scope 0 at $DIR/issue-59352.rs:14:5: 14:63 - } - - bb3: { - StorageDead(_4); // scope 0 at $DIR/issue-59352.rs:14:40: 14:41 - StorageLive(_9); // scope 0 at $DIR/issue-59352.rs:14:26: 14:50 - _9 = discriminant(_3); // scope 3 at $DIR/issue-59352.rs:14:26: 14:50 - switchInt(move _9) -> [0_isize: bb6, 1_isize: bb8, otherwise: bb7]; // scope 3 at $DIR/issue-59352.rs:14:26: 14:50 - } - - bb4: { - StorageDead(_2); // scope 0 at $DIR/issue-59352.rs:14:62: 14:63 - return; // scope 0 at $DIR/issue-59352.rs:15:2: 15:2 - } - - bb5: { - _6 = &_7; // scope 1 at $DIR/issue-59352.rs:14:8: 14:23 - _10 = discriminant((*_6)); // scope 2 at $DIR/issue-59352.rs:14:8: 14:23 - _2 = Eq(_10, const 1_isize); // scope 2 at $DIR/issue-59352.rs:14:8: 14:23 - StorageDead(_6); // scope 1 at $DIR/issue-59352.rs:14:8: 14:23 - StorageDead(_7); // scope 1 at $DIR/issue-59352.rs:14:8: 14:23 - StorageDead(_5); // scope 0 at $DIR/issue-59352.rs:14:8: 14:23 - switchInt(move _2) -> [false: bb2, otherwise: bb1]; // scope 0 at $DIR/issue-59352.rs:14:5: 14:63 - } - - bb6: { - core::panicking::panic(const "called `Option::unwrap()` on a `None` value"); // scope 3 at $DIR/issue-59352.rs:14:26: 14:50 - // mir::Constant - // + span: $DIR/issue-59352.rs:14:26: 14:50 - // + literal: Const { ty: fn(&'static str) -> ! {core::panicking::panic}, val: Value(Scalar()) } - // ty::Const - // + ty: &str - // + val: Value(Slice { data: Allocation { bytes: [99, 97, 108, 108, 101, 100, 32, 96, 79, 112, 116, 105, 111, 110, 58, 58, 117, 110, 119, 114, 97, 112, 40, 41, 96, 32, 111, 110, 32, 97, 32, 96, 78, 111, 110, 101, 96, 32, 118, 97, 108, 117, 101], relocations: Relocations(SortedMap { data: [] }), init_mask: InitMask { blocks: [8796093022207], len: Size { raw: 43 } }, size: Size { raw: 43 }, align: Align { pow2: 0 }, mutability: Not, extra: () }, start: 0, end: 43 }) - // mir::Constant - // + span: $DIR/issue-59352.rs:14:26: 14:50 - // + literal: Const { ty: &str, val: Value(Slice { data: Allocation { bytes: [99, 97, 108, 108, 101, 100, 32, 96, 79, 112, 116, 105, 111, 110, 58, 58, 117, 110, 119, 114, 97, 112, 40, 41, 96, 32, 111, 110, 32, 97, 32, 96, 78, 111, 110, 101, 96, 32, 118, 97, 108, 117, 101], relocations: Relocations(SortedMap { data: [] }), init_mask: InitMask { blocks: [8796093022207], len: Size { raw: 43 } }, size: Size { raw: 43 }, align: Align { pow2: 0 }, mutability: Not, extra: () }, start: 0, end: 43 }) } - } - - bb7: { - unreachable; // scope 3 at $DIR/issue-59352.rs:14:26: 14:50 - } - - bb8: { - _0 = move ((_3 as Some).0: u32); // scope 3 at $DIR/issue-59352.rs:14:26: 14:50 - StorageDead(_9); // scope 0 at $DIR/issue-59352.rs:14:26: 14:50 - StorageDead(_3); // scope 0 at $DIR/issue-59352.rs:14:49: 14:50 - goto -> bb4; // scope 0 at $DIR/issue-59352.rs:14:5: 14:63 - } -} diff --git a/src/test/mir-opt/loop_test.main.SimplifyCfg-promote-consts.after.mir b/src/test/mir-opt/loop_test.main.SimplifyCfg-promote-consts.after.mir index f109937dbf937..56df50c089318 100644 --- a/src/test/mir-opt/loop_test.main.SimplifyCfg-promote-consts.after.mir +++ b/src/test/mir-opt/loop_test.main.SimplifyCfg-promote-consts.after.mir @@ -16,14 +16,12 @@ fn main() -> () { StorageLive(_1); // scope 0 at $DIR/loop_test.rs:10:5: 12:6 StorageLive(_2); // scope 0 at $DIR/loop_test.rs:10:8: 10:12 _2 = const true; // scope 0 at $DIR/loop_test.rs:10:8: 10:12 - switchInt(move _2) -> [false: bb2, otherwise: bb1]; // scope 0 at $DIR/loop_test.rs:10:5: 12:6 + FakeRead(ForMatchedPlace, _2); // scope 0 at $DIR/loop_test.rs:10:8: 10:12 + switchInt(_2) -> [false: bb2, otherwise: bb1]; // scope 0 at $DIR/loop_test.rs:10:5: 12:6 } bb1: { - _0 = const (); // scope 0 at $DIR/loop_test.rs:11:9: 11:15 - StorageDead(_2); // scope 0 at $DIR/loop_test.rs:12:5: 12:6 - StorageDead(_1); // scope 0 at $DIR/loop_test.rs:12:5: 12:6 - return; // scope 0 at $DIR/loop_test.rs:17:2: 17:2 + falseEdge -> [real: bb3, imaginary: bb2]; // scope 0 at $DIR/loop_test.rs:10:5: 12:6 } bb2: { @@ -31,22 +29,29 @@ fn main() -> () { StorageDead(_2); // scope 0 at $DIR/loop_test.rs:12:5: 12:6 StorageDead(_1); // scope 0 at $DIR/loop_test.rs:12:5: 12:6 StorageLive(_4); // scope 0 at $DIR/loop_test.rs:13:5: 16:6 - goto -> bb3; // scope 0 at $DIR/loop_test.rs:13:5: 16:6 + goto -> bb4; // scope 0 at $DIR/loop_test.rs:13:5: 16:6 } bb3: { - falseUnwind -> [real: bb4, cleanup: bb5]; // scope 0 at $DIR/loop_test.rs:13:5: 16:6 + _0 = const (); // scope 0 at $DIR/loop_test.rs:11:9: 11:15 + StorageDead(_2); // scope 0 at $DIR/loop_test.rs:12:5: 12:6 + StorageDead(_1); // scope 0 at $DIR/loop_test.rs:12:5: 12:6 + return; // scope 0 at $DIR/loop_test.rs:17:2: 17:2 } bb4: { + falseUnwind -> [real: bb5, cleanup: bb6]; // scope 0 at $DIR/loop_test.rs:13:5: 16:6 + } + + bb5: { StorageLive(_6); // scope 0 at $DIR/loop_test.rs:14:13: 14:14 _6 = const 1_i32; // scope 0 at $DIR/loop_test.rs:14:17: 14:18 FakeRead(ForLet, _6); // scope 0 at $DIR/loop_test.rs:14:13: 14:14 StorageDead(_6); // scope 0 at $DIR/loop_test.rs:16:5: 16:6 - goto -> bb3; // scope 0 at $DIR/loop_test.rs:1:1: 1:1 + goto -> bb4; // scope 0 at $DIR/loop_test.rs:1:1: 1:1 } - bb5 (cleanup): { + bb6 (cleanup): { resume; // scope 0 at $DIR/loop_test.rs:6:1: 17:2 } } diff --git a/src/test/mir-opt/lower_intrinsics.f_u64.PreCodegen.before.mir b/src/test/mir-opt/lower_intrinsics.f_u64.PreCodegen.before.mir index 740a6e0edb0c4..654dd8275c9de 100644 --- a/src/test/mir-opt/lower_intrinsics.f_u64.PreCodegen.before.mir +++ b/src/test/mir-opt/lower_intrinsics.f_u64.PreCodegen.before.mir @@ -3,28 +3,24 @@ fn f_u64() -> () { let mut _0: (); // return place in scope 0 at $DIR/lower_intrinsics.rs:34:16: 34:16 scope 1 (inlined f_dispatch::) { // at $DIR/lower_intrinsics.rs:35:5: 35:21 - debug t => _1; // in scope 1 at $DIR/lower_intrinsics.rs:35:5: 35:21 - let mut _1: u64; // in scope 1 at $DIR/lower_intrinsics.rs:35:5: 35:21 - let _2: (); // in scope 1 at $DIR/lower_intrinsics.rs:35:5: 35:21 - let mut _3: u64; // in scope 1 at $DIR/lower_intrinsics.rs:35:5: 35:21 + debug t => _2; // in scope 1 at $DIR/lower_intrinsics.rs:35:5: 35:21 + let _1: (); // in scope 1 at $DIR/lower_intrinsics.rs:35:5: 35:21 + let mut _2: u64; // in scope 1 at $DIR/lower_intrinsics.rs:35:5: 35:21 scope 2 (inlined std::mem::size_of::) { // at $DIR/lower_intrinsics.rs:35:5: 35:21 } } bb0: { - _1 = const 0_u64; // scope 0 at $DIR/lower_intrinsics.rs:35:5: 35:21 - StorageLive(_2); // scope 1 at $DIR/lower_intrinsics.rs:35:5: 35:21 - StorageLive(_3); // scope 1 at $DIR/lower_intrinsics.rs:35:5: 35:21 - _3 = move _1; // scope 1 at $DIR/lower_intrinsics.rs:35:5: 35:21 - _2 = f_non_zst::(move _3) -> bb1; // scope 1 at $DIR/lower_intrinsics.rs:35:5: 35:21 + _2 = const 0_u64; // scope 0 at $DIR/lower_intrinsics.rs:35:5: 35:21 + StorageLive(_1); // scope 1 at $DIR/lower_intrinsics.rs:35:5: 35:21 + _1 = f_non_zst::(move _2) -> bb1; // scope 1 at $DIR/lower_intrinsics.rs:35:5: 35:21 // mir::Constant // + span: $DIR/lower_intrinsics.rs:35:5: 35:21 // + literal: Const { ty: fn(u64) {f_non_zst::}, val: Value(Scalar()) } } bb1: { - StorageDead(_3); // scope 1 at $DIR/lower_intrinsics.rs:35:5: 35:21 - StorageDead(_2); // scope 1 at $DIR/lower_intrinsics.rs:35:5: 35:21 + StorageDead(_1); // scope 1 at $DIR/lower_intrinsics.rs:35:5: 35:21 _0 = const (); // scope 0 at $DIR/lower_intrinsics.rs:34:16: 36:2 return; // scope 0 at $DIR/lower_intrinsics.rs:36:2: 36:2 } diff --git a/src/test/mir-opt/match_arm_scopes.complicated_match.SimplifyCfg-initial.after-ElaborateDrops.after.diff b/src/test/mir-opt/match_arm_scopes.complicated_match.SimplifyCfg-initial.after-ElaborateDrops.after.diff index 95beab2ec9af7..4e7cd77035eec 100644 --- a/src/test/mir-opt/match_arm_scopes.complicated_match.SimplifyCfg-initial.after-ElaborateDrops.after.diff +++ b/src/test/mir-opt/match_arm_scopes.complicated_match.SimplifyCfg-initial.after-ElaborateDrops.after.diff @@ -47,7 +47,7 @@ } bb3: { -- falseEdge -> [real: bb13, imaginary: bb5]; // scope 0 at $DIR/match-arm-scopes.rs:15:25: 15:38 +- falseEdge -> [real: bb14, imaginary: bb5]; // scope 0 at $DIR/match-arm-scopes.rs:15:25: 15:38 - } - - bb4: { @@ -55,7 +55,7 @@ - } - - bb5: { -- falseEdge -> [real: bb20, imaginary: bb6]; // scope 0 at $DIR/match-arm-scopes.rs:16:9: 16:21 +- falseEdge -> [real: bb22, imaginary: bb6]; // scope 0 at $DIR/match-arm-scopes.rs:16:9: 16:21 - } - - bb6: { @@ -63,14 +63,14 @@ _15 = (_2.1: bool); // scope 0 at $DIR/match-arm-scopes.rs:16:32: 16:33 StorageLive(_16); // scope 0 at $DIR/match-arm-scopes.rs:16:35: 16:36 _16 = move (_2.2: std::string::String); // scope 0 at $DIR/match-arm-scopes.rs:16:35: 16:36 -- goto -> bb19; // scope 0 at $DIR/match-arm-scopes.rs:14:5: 17:6 +- goto -> bb21; // scope 0 at $DIR/match-arm-scopes.rs:14:5: 17:6 + goto -> bb16; // scope 0 at $DIR/match-arm-scopes.rs:14:5: 17:6 } - bb7: { + bb4: { _0 = const 1_i32; // scope 1 at $DIR/match-arm-scopes.rs:15:77: 15:78 -- drop(_7) -> [return: bb18, unwind: bb25]; // scope 0 at $DIR/match-arm-scopes.rs:15:77: 15:78 +- drop(_7) -> [return: bb20, unwind: bb27]; // scope 0 at $DIR/match-arm-scopes.rs:15:77: 15:78 + drop(_7) -> [return: bb15, unwind: bb22]; // scope 0 at $DIR/match-arm-scopes.rs:15:77: 15:78 } @@ -85,28 +85,33 @@ StorageLive(_9); // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 StorageLive(_10); // scope 0 at $DIR/match-arm-scopes.rs:15:45: 15:49 _10 = _1; // scope 0 at $DIR/match-arm-scopes.rs:15:45: 15:49 -- switchInt(move _10) -> [false: bb10, otherwise: bb9]; // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 -+ switchInt(move _10) -> [false: bb7, otherwise: bb6]; // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 +- FakeRead(ForMatchedPlace, _10); // scope 0 at $DIR/match-arm-scopes.rs:15:45: 15:49 +- switchInt(_10) -> [false: bb10, otherwise: bb9]; // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 ++ switchInt(_10) -> [false: bb6, otherwise: bb7]; // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 } - bb9: { +- falseEdge -> [real: bb11, imaginary: bb10]; // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 +- } +- +- bb10: { + bb6: { - _0 = const 3_i32; // scope 0 at $DIR/match-arm-scopes.rs:15:59: 15:60 + _9 = (*_6); // scope 0 at $DIR/match-arm-scopes.rs:15:70: 15:71 StorageDead(_10); // scope 0 at $DIR/match-arm-scopes.rs:15:72: 15:73 - StorageDead(_9); // scope 0 at $DIR/match-arm-scopes.rs:15:77: 15:78 -- goto -> bb23; // scope 0 at $DIR/match-arm-scopes.rs:1:1: 1:1 -+ goto -> bb20; // scope 0 at $DIR/match-arm-scopes.rs:1:1: 1:1 +- switchInt(move _9) -> [false: bb13, otherwise: bb12]; // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 ++ switchInt(move _9) -> [false: bb9, otherwise: bb8]; // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 } -- bb10: { +- bb11: { + bb7: { - _9 = (*_6); // scope 0 at $DIR/match-arm-scopes.rs:15:70: 15:71 + _0 = const 3_i32; // scope 0 at $DIR/match-arm-scopes.rs:15:59: 15:60 StorageDead(_10); // scope 0 at $DIR/match-arm-scopes.rs:15:72: 15:73 -- switchInt(move _9) -> [false: bb12, otherwise: bb11]; // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 -+ switchInt(move _9) -> [false: bb9, otherwise: bb8]; // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 + StorageDead(_9); // scope 0 at $DIR/match-arm-scopes.rs:15:77: 15:78 +- goto -> bb25; // scope 0 at $DIR/match-arm-scopes.rs:1:1: 1:1 ++ goto -> bb20; // scope 0 at $DIR/match-arm-scopes.rs:1:1: 1:1 } -- bb11: { +- bb12: { + bb8: { StorageDead(_9); // scope 0 at $DIR/match-arm-scopes.rs:15:77: 15:78 - FakeRead(ForMatchGuard, _3); // scope 0 at $DIR/match-arm-scopes.rs:15:72: 15:73 @@ -121,7 +126,7 @@ + goto -> bb4; // scope 0 at $DIR/match-arm-scopes.rs:14:5: 17:6 } -- bb12: { +- bb13: { + bb9: { StorageDead(_9); // scope 0 at $DIR/match-arm-scopes.rs:15:77: 15:78 StorageDead(_8); // scope 0 at $DIR/match-arm-scopes.rs:15:77: 15:78 @@ -130,7 +135,7 @@ + goto -> bb1; // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 } -- bb13: { +- bb14: { + bb10: { StorageLive(_6); // scope 0 at $DIR/match-arm-scopes.rs:15:26: 15:27 _6 = &(_2.0: bool); // scope 0 at $DIR/match-arm-scopes.rs:15:26: 15:27 @@ -141,28 +146,33 @@ StorageLive(_12); // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 StorageLive(_13); // scope 0 at $DIR/match-arm-scopes.rs:15:45: 15:49 _13 = _1; // scope 0 at $DIR/match-arm-scopes.rs:15:45: 15:49 -- switchInt(move _13) -> [false: bb15, otherwise: bb14]; // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 -+ switchInt(move _13) -> [false: bb12, otherwise: bb11]; // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 +- FakeRead(ForMatchedPlace, _13); // scope 0 at $DIR/match-arm-scopes.rs:15:45: 15:49 +- switchInt(_13) -> [false: bb16, otherwise: bb15]; // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 ++ switchInt(_13) -> [false: bb11, otherwise: bb12]; // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 } -- bb14: { +- bb15: { +- falseEdge -> [real: bb17, imaginary: bb16]; // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 +- } +- +- bb16: { + bb11: { - _0 = const 3_i32; // scope 0 at $DIR/match-arm-scopes.rs:15:59: 15:60 + _12 = (*_6); // scope 0 at $DIR/match-arm-scopes.rs:15:70: 15:71 StorageDead(_13); // scope 0 at $DIR/match-arm-scopes.rs:15:72: 15:73 - StorageDead(_12); // scope 0 at $DIR/match-arm-scopes.rs:15:77: 15:78 -- goto -> bb23; // scope 0 at $DIR/match-arm-scopes.rs:1:1: 1:1 -+ goto -> bb20; // scope 0 at $DIR/match-arm-scopes.rs:1:1: 1:1 +- switchInt(move _12) -> [false: bb19, otherwise: bb18]; // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 ++ switchInt(move _12) -> [false: bb14, otherwise: bb13]; // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 } -- bb15: { +- bb17: { + bb12: { - _12 = (*_6); // scope 0 at $DIR/match-arm-scopes.rs:15:70: 15:71 + _0 = const 3_i32; // scope 0 at $DIR/match-arm-scopes.rs:15:59: 15:60 StorageDead(_13); // scope 0 at $DIR/match-arm-scopes.rs:15:72: 15:73 -- switchInt(move _12) -> [false: bb17, otherwise: bb16]; // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 -+ switchInt(move _12) -> [false: bb14, otherwise: bb13]; // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 + StorageDead(_12); // scope 0 at $DIR/match-arm-scopes.rs:15:77: 15:78 +- goto -> bb25; // scope 0 at $DIR/match-arm-scopes.rs:1:1: 1:1 ++ goto -> bb20; // scope 0 at $DIR/match-arm-scopes.rs:1:1: 1:1 } -- bb16: { +- bb18: { + bb13: { StorageDead(_12); // scope 0 at $DIR/match-arm-scopes.rs:15:77: 15:78 - FakeRead(ForMatchGuard, _3); // scope 0 at $DIR/match-arm-scopes.rs:15:72: 15:73 @@ -177,7 +187,7 @@ + goto -> bb4; // scope 0 at $DIR/match-arm-scopes.rs:14:5: 17:6 } -- bb17: { +- bb19: { + bb14: { StorageDead(_12); // scope 0 at $DIR/match-arm-scopes.rs:15:77: 15:78 StorageDead(_8); // scope 0 at $DIR/match-arm-scopes.rs:15:77: 15:78 @@ -186,67 +196,67 @@ + goto -> bb2; // scope 0 at $DIR/match-arm-scopes.rs:15:42: 15:73 } -- bb18: { +- bb20: { + bb15: { StorageDead(_7); // scope 0 at $DIR/match-arm-scopes.rs:15:77: 15:78 StorageDead(_5); // scope 0 at $DIR/match-arm-scopes.rs:15:77: 15:78 StorageDead(_8); // scope 0 at $DIR/match-arm-scopes.rs:15:77: 15:78 StorageDead(_6); // scope 0 at $DIR/match-arm-scopes.rs:15:77: 15:78 -- goto -> bb22; // scope 0 at $DIR/match-arm-scopes.rs:14:5: 17:6 +- goto -> bb24; // scope 0 at $DIR/match-arm-scopes.rs:14:5: 17:6 + goto -> bb19; // scope 0 at $DIR/match-arm-scopes.rs:14:5: 17:6 } -- bb19: { +- bb21: { + bb16: { _0 = const 2_i32; // scope 2 at $DIR/match-arm-scopes.rs:16:41: 16:42 -- drop(_16) -> [return: bb21, unwind: bb25]; // scope 0 at $DIR/match-arm-scopes.rs:16:41: 16:42 +- drop(_16) -> [return: bb23, unwind: bb27]; // scope 0 at $DIR/match-arm-scopes.rs:16:41: 16:42 + drop(_16) -> [return: bb18, unwind: bb22]; // scope 0 at $DIR/match-arm-scopes.rs:16:41: 16:42 } -- bb20: { +- bb22: { + bb17: { StorageLive(_15); // scope 0 at $DIR/match-arm-scopes.rs:16:16: 16:17 _15 = (_2.1: bool); // scope 0 at $DIR/match-arm-scopes.rs:16:16: 16:17 StorageLive(_16); // scope 0 at $DIR/match-arm-scopes.rs:16:19: 16:20 _16 = move (_2.2: std::string::String); // scope 0 at $DIR/match-arm-scopes.rs:16:19: 16:20 -- goto -> bb19; // scope 0 at $DIR/match-arm-scopes.rs:14:5: 17:6 +- goto -> bb21; // scope 0 at $DIR/match-arm-scopes.rs:14:5: 17:6 + goto -> bb16; // scope 0 at $DIR/match-arm-scopes.rs:14:5: 17:6 } -- bb21: { +- bb23: { + bb18: { StorageDead(_16); // scope 0 at $DIR/match-arm-scopes.rs:16:41: 16:42 StorageDead(_15); // scope 0 at $DIR/match-arm-scopes.rs:16:41: 16:42 -- goto -> bb22; // scope 0 at $DIR/match-arm-scopes.rs:14:5: 17:6 +- goto -> bb24; // scope 0 at $DIR/match-arm-scopes.rs:14:5: 17:6 + goto -> bb19; // scope 0 at $DIR/match-arm-scopes.rs:14:5: 17:6 } -- bb22: { -- drop(_2) -> [return: bb24, unwind: bb26]; // scope 0 at $DIR/match-arm-scopes.rs:18:1: 18:2 +- bb24: { +- drop(_2) -> [return: bb26, unwind: bb28]; // scope 0 at $DIR/match-arm-scopes.rs:18:1: 18:2 + bb19: { + goto -> bb26; // scope 0 at $DIR/match-arm-scopes.rs:18:1: 18:2 } -- bb23: { +- bb25: { + bb20: { StorageDead(_8); // scope 0 at $DIR/match-arm-scopes.rs:15:77: 15:78 StorageDead(_6); // scope 0 at $DIR/match-arm-scopes.rs:15:77: 15:78 -- drop(_2) -> [return: bb24, unwind: bb26]; // scope 0 at $DIR/match-arm-scopes.rs:18:1: 18:2 +- drop(_2) -> [return: bb26, unwind: bb28]; // scope 0 at $DIR/match-arm-scopes.rs:18:1: 18:2 + drop(_2) -> [return: bb21, unwind: bb23]; // scope 0 at $DIR/match-arm-scopes.rs:18:1: 18:2 } -- bb24: { +- bb26: { + bb21: { return; // scope 0 at $DIR/match-arm-scopes.rs:18:2: 18:2 } -- bb25 (cleanup): { -- drop(_2) -> bb26; // scope 0 at $DIR/match-arm-scopes.rs:18:1: 18:2 +- bb27 (cleanup): { +- drop(_2) -> bb28; // scope 0 at $DIR/match-arm-scopes.rs:18:1: 18:2 + bb22 (cleanup): { + goto -> bb27; // scope 0 at $DIR/match-arm-scopes.rs:18:1: 18:2 } -- bb26 (cleanup): { +- bb28 (cleanup): { + bb23 (cleanup): { resume; // scope 0 at $DIR/match-arm-scopes.rs:13:1: 18:2 + } diff --git a/src/test/mir-opt/matches_reduce_branches.foo.MatchBranchSimplification.32bit.diff b/src/test/mir-opt/matches_reduce_branches.foo.MatchBranchSimplification.32bit.diff index 20240348230f2..d0b1a96b9aef7 100644 --- a/src/test/mir-opt/matches_reduce_branches.foo.MatchBranchSimplification.32bit.diff +++ b/src/test/mir-opt/matches_reduce_branches.foo.MatchBranchSimplification.32bit.diff @@ -30,7 +30,7 @@ } bb3: { - switchInt(move _2) -> [false: bb4, otherwise: bb5]; // scope 0 at $DIR/matches_reduce_branches.rs:7:5: 9:6 + switchInt(_2) -> [false: bb4, otherwise: bb5]; // scope 0 at $DIR/matches_reduce_branches.rs:7:5: 9:6 } bb4: { @@ -39,7 +39,7 @@ } bb5: { - StorageDead(_2); // scope 0 at $DIR/matches_reduce_branches.rs:9:5: 9:6 + StorageDead(_2); // scope 0 at $DIR/matches_reduce_branches.rs:10:1: 10:2 return; // scope 0 at $DIR/matches_reduce_branches.rs:10:2: 10:2 } } diff --git a/src/test/mir-opt/matches_reduce_branches.foo.MatchBranchSimplification.64bit.diff b/src/test/mir-opt/matches_reduce_branches.foo.MatchBranchSimplification.64bit.diff index 20240348230f2..d0b1a96b9aef7 100644 --- a/src/test/mir-opt/matches_reduce_branches.foo.MatchBranchSimplification.64bit.diff +++ b/src/test/mir-opt/matches_reduce_branches.foo.MatchBranchSimplification.64bit.diff @@ -30,7 +30,7 @@ } bb3: { - switchInt(move _2) -> [false: bb4, otherwise: bb5]; // scope 0 at $DIR/matches_reduce_branches.rs:7:5: 9:6 + switchInt(_2) -> [false: bb4, otherwise: bb5]; // scope 0 at $DIR/matches_reduce_branches.rs:7:5: 9:6 } bb4: { @@ -39,7 +39,7 @@ } bb5: { - StorageDead(_2); // scope 0 at $DIR/matches_reduce_branches.rs:9:5: 9:6 + StorageDead(_2); // scope 0 at $DIR/matches_reduce_branches.rs:10:1: 10:2 return; // scope 0 at $DIR/matches_reduce_branches.rs:10:2: 10:2 } } diff --git a/src/test/mir-opt/matches_reduce_branches.match_nested_if.MatchBranchSimplification.32bit.diff b/src/test/mir-opt/matches_reduce_branches.match_nested_if.MatchBranchSimplification.32bit.diff index 1d895852354c9..1f46d3777bed8 100644 --- a/src/test/mir-opt/matches_reduce_branches.match_nested_if.MatchBranchSimplification.32bit.diff +++ b/src/test/mir-opt/matches_reduce_branches.match_nested_if.MatchBranchSimplification.32bit.diff @@ -25,9 +25,9 @@ StorageLive(_5); // scope 0 at $DIR/matches_reduce_branches.rs:40:21: 40:48 StorageLive(_6); // scope 0 at $DIR/matches_reduce_branches.rs:40:24: 40:28 _6 = const true; // scope 0 at $DIR/matches_reduce_branches.rs:40:24: 40:28 -- switchInt(move _6) -> [false: bb2, otherwise: bb1]; // scope 0 at $DIR/matches_reduce_branches.rs:40:21: 40:48 +- switchInt(_6) -> [false: bb2, otherwise: bb1]; // scope 0 at $DIR/matches_reduce_branches.rs:40:21: 40:48 + StorageLive(_7); // scope 0 at $DIR/matches_reduce_branches.rs:40:21: 40:48 -+ _7 = move _6; // scope 0 at $DIR/matches_reduce_branches.rs:40:21: 40:48 ++ _7 = _6; // scope 0 at $DIR/matches_reduce_branches.rs:40:21: 40:48 + _5 = Ne(_7, const false); // scope 0 at $DIR/matches_reduce_branches.rs:40:42: 40:47 + StorageDead(_7); // scope 0 at $DIR/matches_reduce_branches.rs:40:21: 40:48 + goto -> bb3; // scope 0 at $DIR/matches_reduce_branches.rs:40:21: 40:48 @@ -45,41 +45,41 @@ bb3: { StorageDead(_6); // scope 0 at $DIR/matches_reduce_branches.rs:40:47: 40:48 -- switchInt(move _5) -> [false: bb5, otherwise: bb4]; // scope 0 at $DIR/matches_reduce_branches.rs:40:18: 40:68 +- switchInt(_5) -> [false: bb4, otherwise: bb5]; // scope 0 at $DIR/matches_reduce_branches.rs:40:18: 40:68 + StorageLive(_8); // scope 0 at $DIR/matches_reduce_branches.rs:40:18: 40:68 -+ _8 = move _5; // scope 0 at $DIR/matches_reduce_branches.rs:40:18: 40:68 ++ _8 = _5; // scope 0 at $DIR/matches_reduce_branches.rs:40:18: 40:68 + _4 = Ne(_8, const false); // scope 0 at $DIR/matches_reduce_branches.rs:40:62: 40:67 + StorageDead(_8); // scope 0 at $DIR/matches_reduce_branches.rs:40:18: 40:68 + goto -> bb6; // scope 0 at $DIR/matches_reduce_branches.rs:40:18: 40:68 } bb4: { - _4 = const true; // scope 0 at $DIR/matches_reduce_branches.rs:40:50: 40:54 + _4 = const false; // scope 0 at $DIR/matches_reduce_branches.rs:40:62: 40:67 goto -> bb6; // scope 0 at $DIR/matches_reduce_branches.rs:40:18: 40:68 } bb5: { - _4 = const false; // scope 0 at $DIR/matches_reduce_branches.rs:40:62: 40:67 + _4 = const true; // scope 0 at $DIR/matches_reduce_branches.rs:40:50: 40:54 goto -> bb6; // scope 0 at $DIR/matches_reduce_branches.rs:40:18: 40:68 } bb6: { StorageDead(_5); // scope 0 at $DIR/matches_reduce_branches.rs:40:67: 40:68 -- switchInt(move _4) -> [false: bb8, otherwise: bb7]; // scope 0 at $DIR/matches_reduce_branches.rs:40:15: 40:88 +- switchInt(_4) -> [false: bb7, otherwise: bb8]; // scope 0 at $DIR/matches_reduce_branches.rs:40:15: 40:88 + StorageLive(_9); // scope 0 at $DIR/matches_reduce_branches.rs:40:15: 40:88 -+ _9 = move _4; // scope 0 at $DIR/matches_reduce_branches.rs:40:15: 40:88 ++ _9 = _4; // scope 0 at $DIR/matches_reduce_branches.rs:40:15: 40:88 + _3 = Ne(_9, const false); // scope 0 at $DIR/matches_reduce_branches.rs:40:82: 40:87 + StorageDead(_9); // scope 0 at $DIR/matches_reduce_branches.rs:40:15: 40:88 + goto -> bb9; // scope 0 at $DIR/matches_reduce_branches.rs:40:15: 40:88 } bb7: { - _3 = const true; // scope 0 at $DIR/matches_reduce_branches.rs:40:70: 40:74 + _3 = const false; // scope 0 at $DIR/matches_reduce_branches.rs:40:82: 40:87 goto -> bb9; // scope 0 at $DIR/matches_reduce_branches.rs:40:15: 40:88 } bb8: { - _3 = const false; // scope 0 at $DIR/matches_reduce_branches.rs:40:82: 40:87 + _3 = const true; // scope 0 at $DIR/matches_reduce_branches.rs:40:70: 40:74 goto -> bb9; // scope 0 at $DIR/matches_reduce_branches.rs:40:15: 40:88 } diff --git a/src/test/mir-opt/matches_reduce_branches.match_nested_if.MatchBranchSimplification.64bit.diff b/src/test/mir-opt/matches_reduce_branches.match_nested_if.MatchBranchSimplification.64bit.diff index 1d895852354c9..1f46d3777bed8 100644 --- a/src/test/mir-opt/matches_reduce_branches.match_nested_if.MatchBranchSimplification.64bit.diff +++ b/src/test/mir-opt/matches_reduce_branches.match_nested_if.MatchBranchSimplification.64bit.diff @@ -25,9 +25,9 @@ StorageLive(_5); // scope 0 at $DIR/matches_reduce_branches.rs:40:21: 40:48 StorageLive(_6); // scope 0 at $DIR/matches_reduce_branches.rs:40:24: 40:28 _6 = const true; // scope 0 at $DIR/matches_reduce_branches.rs:40:24: 40:28 -- switchInt(move _6) -> [false: bb2, otherwise: bb1]; // scope 0 at $DIR/matches_reduce_branches.rs:40:21: 40:48 +- switchInt(_6) -> [false: bb2, otherwise: bb1]; // scope 0 at $DIR/matches_reduce_branches.rs:40:21: 40:48 + StorageLive(_7); // scope 0 at $DIR/matches_reduce_branches.rs:40:21: 40:48 -+ _7 = move _6; // scope 0 at $DIR/matches_reduce_branches.rs:40:21: 40:48 ++ _7 = _6; // scope 0 at $DIR/matches_reduce_branches.rs:40:21: 40:48 + _5 = Ne(_7, const false); // scope 0 at $DIR/matches_reduce_branches.rs:40:42: 40:47 + StorageDead(_7); // scope 0 at $DIR/matches_reduce_branches.rs:40:21: 40:48 + goto -> bb3; // scope 0 at $DIR/matches_reduce_branches.rs:40:21: 40:48 @@ -45,41 +45,41 @@ bb3: { StorageDead(_6); // scope 0 at $DIR/matches_reduce_branches.rs:40:47: 40:48 -- switchInt(move _5) -> [false: bb5, otherwise: bb4]; // scope 0 at $DIR/matches_reduce_branches.rs:40:18: 40:68 +- switchInt(_5) -> [false: bb4, otherwise: bb5]; // scope 0 at $DIR/matches_reduce_branches.rs:40:18: 40:68 + StorageLive(_8); // scope 0 at $DIR/matches_reduce_branches.rs:40:18: 40:68 -+ _8 = move _5; // scope 0 at $DIR/matches_reduce_branches.rs:40:18: 40:68 ++ _8 = _5; // scope 0 at $DIR/matches_reduce_branches.rs:40:18: 40:68 + _4 = Ne(_8, const false); // scope 0 at $DIR/matches_reduce_branches.rs:40:62: 40:67 + StorageDead(_8); // scope 0 at $DIR/matches_reduce_branches.rs:40:18: 40:68 + goto -> bb6; // scope 0 at $DIR/matches_reduce_branches.rs:40:18: 40:68 } bb4: { - _4 = const true; // scope 0 at $DIR/matches_reduce_branches.rs:40:50: 40:54 + _4 = const false; // scope 0 at $DIR/matches_reduce_branches.rs:40:62: 40:67 goto -> bb6; // scope 0 at $DIR/matches_reduce_branches.rs:40:18: 40:68 } bb5: { - _4 = const false; // scope 0 at $DIR/matches_reduce_branches.rs:40:62: 40:67 + _4 = const true; // scope 0 at $DIR/matches_reduce_branches.rs:40:50: 40:54 goto -> bb6; // scope 0 at $DIR/matches_reduce_branches.rs:40:18: 40:68 } bb6: { StorageDead(_5); // scope 0 at $DIR/matches_reduce_branches.rs:40:67: 40:68 -- switchInt(move _4) -> [false: bb8, otherwise: bb7]; // scope 0 at $DIR/matches_reduce_branches.rs:40:15: 40:88 +- switchInt(_4) -> [false: bb7, otherwise: bb8]; // scope 0 at $DIR/matches_reduce_branches.rs:40:15: 40:88 + StorageLive(_9); // scope 0 at $DIR/matches_reduce_branches.rs:40:15: 40:88 -+ _9 = move _4; // scope 0 at $DIR/matches_reduce_branches.rs:40:15: 40:88 ++ _9 = _4; // scope 0 at $DIR/matches_reduce_branches.rs:40:15: 40:88 + _3 = Ne(_9, const false); // scope 0 at $DIR/matches_reduce_branches.rs:40:82: 40:87 + StorageDead(_9); // scope 0 at $DIR/matches_reduce_branches.rs:40:15: 40:88 + goto -> bb9; // scope 0 at $DIR/matches_reduce_branches.rs:40:15: 40:88 } bb7: { - _3 = const true; // scope 0 at $DIR/matches_reduce_branches.rs:40:70: 40:74 + _3 = const false; // scope 0 at $DIR/matches_reduce_branches.rs:40:82: 40:87 goto -> bb9; // scope 0 at $DIR/matches_reduce_branches.rs:40:15: 40:88 } bb8: { - _3 = const false; // scope 0 at $DIR/matches_reduce_branches.rs:40:82: 40:87 + _3 = const true; // scope 0 at $DIR/matches_reduce_branches.rs:40:70: 40:74 goto -> bb9; // scope 0 at $DIR/matches_reduce_branches.rs:40:15: 40:88 } diff --git a/src/test/mir-opt/multiple_return_terminators.test.MultipleReturnTerminators.diff b/src/test/mir-opt/multiple_return_terminators.test.MultipleReturnTerminators.diff index fb25cb90021f3..997c021d2ef21 100644 --- a/src/test/mir-opt/multiple_return_terminators.test.MultipleReturnTerminators.diff +++ b/src/test/mir-opt/multiple_return_terminators.test.MultipleReturnTerminators.diff @@ -9,21 +9,21 @@ bb0: { StorageLive(_2); // scope 0 at $DIR/multiple_return_terminators.rs:5:8: 5:9 _2 = _1; // scope 0 at $DIR/multiple_return_terminators.rs:5:8: 5:9 - switchInt(move _2) -> [false: bb2, otherwise: bb1]; // scope 0 at $DIR/multiple_return_terminators.rs:5:5: 9:6 + switchInt(_2) -> [false: bb1, otherwise: bb2]; // scope 0 at $DIR/multiple_return_terminators.rs:5:5: 9:6 } bb1: { - _0 = const (); // scope 0 at $DIR/multiple_return_terminators.rs:5:10: 7:6 + _0 = const (); // scope 0 at $DIR/multiple_return_terminators.rs:7:12: 9:6 goto -> bb3; // scope 0 at $DIR/multiple_return_terminators.rs:5:5: 9:6 } bb2: { - _0 = const (); // scope 0 at $DIR/multiple_return_terminators.rs:7:12: 9:6 + _0 = const (); // scope 0 at $DIR/multiple_return_terminators.rs:5:10: 7:6 goto -> bb3; // scope 0 at $DIR/multiple_return_terminators.rs:5:5: 9:6 } bb3: { - StorageDead(_2); // scope 0 at $DIR/multiple_return_terminators.rs:9:5: 9:6 + StorageDead(_2); // scope 0 at $DIR/multiple_return_terminators.rs:10:1: 10:2 return; // scope 0 at $DIR/multiple_return_terminators.rs:10:2: 10:2 } } diff --git a/src/test/mir-opt/nll/region_subtyping_basic.main.nll.0.32bit.mir b/src/test/mir-opt/nll/region_subtyping_basic.main.nll.0.32bit.mir index 8c939d5fc3da5..d8538a5461ed6 100644 --- a/src/test/mir-opt/nll/region_subtyping_basic.main.nll.0.32bit.mir +++ b/src/test/mir-opt/nll/region_subtyping_basic.main.nll.0.32bit.mir @@ -5,19 +5,19 @@ | '_#1r | Local | ['_#1r] | | Inferred Region Values -| '_#0r | U0 | {bb0[0..=8], bb1[0..=7], bb2[0..=3], bb3[0..=1], bb4[0..=3], bb5[0..=2], bb6[0..=5], bb7[0], '_#0r, '_#1r} -| '_#1r | U0 | {bb0[0..=8], bb1[0..=7], bb2[0..=3], bb3[0..=1], bb4[0..=3], bb5[0..=2], bb6[0..=5], bb7[0], '_#1r} +| '_#0r | U0 | {bb0[0..=8], bb1[0..=8], bb2[0], bb3[0..=1], bb4[0..=3], bb5[0..=3], bb6[0..=2], bb7[0..=5], bb8[0], '_#0r, '_#1r} +| '_#1r | U0 | {bb0[0..=8], bb1[0..=8], bb2[0], bb3[0..=1], bb4[0..=3], bb5[0..=3], bb6[0..=2], bb7[0..=5], bb8[0], '_#1r} | '_#2r | U0 | {} -| '_#3r | U0 | {bb1[0..=7], bb2[0..=2]} -| '_#4r | U0 | {bb1[1..=7], bb2[0..=2]} -| '_#5r | U0 | {bb1[4..=7], bb2[0..=2]} +| '_#3r | U0 | {bb1[0..=8], bb2[0], bb4[0..=2]} +| '_#4r | U0 | {bb1[1..=8], bb2[0], bb4[0..=2]} +| '_#5r | U0 | {bb1[4..=8], bb2[0], bb4[0..=2]} | | Inference Constraints -| '_#0r live at {bb0[0..=8], bb1[0..=7], bb2[0..=3], bb3[0..=1], bb4[0..=3], bb5[0..=2], bb6[0..=5], bb7[0]} -| '_#1r live at {bb0[0..=8], bb1[0..=7], bb2[0..=3], bb3[0..=1], bb4[0..=3], bb5[0..=2], bb6[0..=5], bb7[0]} +| '_#0r live at {bb0[0..=8], bb1[0..=8], bb2[0], bb3[0..=1], bb4[0..=3], bb5[0..=3], bb6[0..=2], bb7[0..=5], bb8[0]} +| '_#1r live at {bb0[0..=8], bb1[0..=8], bb2[0], bb3[0..=1], bb4[0..=3], bb5[0..=3], bb6[0..=2], bb7[0..=5], bb8[0]} | '_#3r live at {bb1[0]} | '_#4r live at {bb1[1..=3]} -| '_#5r live at {bb1[4..=7], bb2[0..=2]} +| '_#5r live at {bb1[4..=8], bb2[0], bb4[0..=2]} | '_#3r: '_#4r due to Assignment at Single(bb1[0]) | '_#4r: '_#5r due to Assignment at Single(bb1[3]) | @@ -52,7 +52,7 @@ fn main() -> () { _3 = const Const(Value(Scalar(0x00000000)): usize); // bb0[5]: scope 1 at $DIR/region-subtyping-basic.rs:18:16: 18:17 _4 = Len(_1); // bb0[6]: scope 1 at $DIR/region-subtyping-basic.rs:18:14: 18:18 _5 = Lt(_3, _4); // bb0[7]: scope 1 at $DIR/region-subtyping-basic.rs:18:14: 18:18 - assert(move _5, "index out of bounds: the length is {} but the index is {}", move _4, _3) -> [success: bb1, unwind: bb7]; // bb0[8]: scope 1 at $DIR/region-subtyping-basic.rs:18:14: 18:18 + assert(move _5, "index out of bounds: the length is {} but the index is {}", move _4, _3) -> [success: bb1, unwind: bb8]; // bb0[8]: scope 1 at $DIR/region-subtyping-basic.rs:18:14: 18:18 } bb1: { @@ -63,50 +63,55 @@ fn main() -> () { FakeRead(ForLet, _6); // bb1[4]: scope 2 at $DIR/region-subtyping-basic.rs:19:9: 19:10 StorageLive(_7); // bb1[5]: scope 3 at $DIR/region-subtyping-basic.rs:20:8: 20:12 _7 = const Const(Value(Scalar(0x01)): bool); // bb1[6]: scope 3 at $DIR/region-subtyping-basic.rs:20:8: 20:12 - switchInt(move _7) -> [Const(Value(Scalar(0x00)): bool): bb3, otherwise: bb2]; // bb1[7]: scope 3 at $DIR/region-subtyping-basic.rs:20:5: 24:6 + FakeRead(ForMatchedPlace, _7); // bb1[7]: scope 3 at $DIR/region-subtyping-basic.rs:20:8: 20:12 + switchInt(_7) -> [Const(Value(Scalar(0x00)): bool): bb3, otherwise: bb2]; // bb1[8]: scope 3 at $DIR/region-subtyping-basic.rs:20:5: 24:6 } bb2: { - StorageLive(_8); // bb2[0]: scope 3 at $DIR/region-subtyping-basic.rs:21:9: 21:18 - StorageLive(_9); // bb2[1]: scope 3 at $DIR/region-subtyping-basic.rs:21:15: 21:17 - _9 = (*_6); // bb2[2]: scope 3 at $DIR/region-subtyping-basic.rs:21:15: 21:17 - _8 = Const(Value(Scalar()): fn(usize) -> bool {use_x})(move _9) -> [return: bb4, unwind: bb7]; // bb2[3]: scope 3 at $DIR/region-subtyping-basic.rs:21:9: 21:18 - // mir::Constant - // + span: $DIR/region-subtyping-basic.rs:21:9: 21:14 - // + literal: Const { ty: fn(usize) -> bool {use_x}, val: Value(Scalar()) } + falseEdge -> [real: bb4, imaginary: bb3]; // bb2[0]: scope 3 at $DIR/region-subtyping-basic.rs:20:5: 24:6 } bb3: { StorageLive(_10); // bb3[0]: scope 3 at $DIR/region-subtyping-basic.rs:23:9: 23:18 - _10 = Const(Value(Scalar()): fn(usize) -> bool {use_x})(const Const(Value(Scalar(0x00000016)): usize)) -> [return: bb5, unwind: bb7]; // bb3[1]: scope 3 at $DIR/region-subtyping-basic.rs:23:9: 23:18 + _10 = Const(Value(Scalar()): fn(usize) -> bool {use_x})(const Const(Value(Scalar(0x00000016)): usize)) -> [return: bb6, unwind: bb8]; // bb3[1]: scope 3 at $DIR/region-subtyping-basic.rs:23:9: 23:18 // mir::Constant // + span: $DIR/region-subtyping-basic.rs:23:9: 23:14 // + literal: Const { ty: fn(usize) -> bool {use_x}, val: Value(Scalar()) } } bb4: { - StorageDead(_9); // bb4[0]: scope 3 at $DIR/region-subtyping-basic.rs:21:17: 21:18 - StorageDead(_8); // bb4[1]: scope 3 at $DIR/region-subtyping-basic.rs:21:18: 21:19 - _0 = const Const(Value(Scalar()): ()); // bb4[2]: scope 3 at $DIR/region-subtyping-basic.rs:20:13: 22:6 - goto -> bb6; // bb4[3]: scope 3 at $DIR/region-subtyping-basic.rs:20:5: 24:6 + StorageLive(_8); // bb4[0]: scope 3 at $DIR/region-subtyping-basic.rs:21:9: 21:18 + StorageLive(_9); // bb4[1]: scope 3 at $DIR/region-subtyping-basic.rs:21:15: 21:17 + _9 = (*_6); // bb4[2]: scope 3 at $DIR/region-subtyping-basic.rs:21:15: 21:17 + _8 = Const(Value(Scalar()): fn(usize) -> bool {use_x})(move _9) -> [return: bb5, unwind: bb8]; // bb4[3]: scope 3 at $DIR/region-subtyping-basic.rs:21:9: 21:18 + // mir::Constant + // + span: $DIR/region-subtyping-basic.rs:21:9: 21:14 + // + literal: Const { ty: fn(usize) -> bool {use_x}, val: Value(Scalar()) } } bb5: { - StorageDead(_10); // bb5[0]: scope 3 at $DIR/region-subtyping-basic.rs:23:18: 23:19 - _0 = const Const(Value(Scalar()): ()); // bb5[1]: scope 3 at $DIR/region-subtyping-basic.rs:22:12: 24:6 - goto -> bb6; // bb5[2]: scope 3 at $DIR/region-subtyping-basic.rs:20:5: 24:6 + StorageDead(_9); // bb5[0]: scope 3 at $DIR/region-subtyping-basic.rs:21:17: 21:18 + StorageDead(_8); // bb5[1]: scope 3 at $DIR/region-subtyping-basic.rs:21:18: 21:19 + _0 = const Const(Value(Scalar()): ()); // bb5[2]: scope 3 at $DIR/region-subtyping-basic.rs:20:13: 22:6 + goto -> bb7; // bb5[3]: scope 3 at $DIR/region-subtyping-basic.rs:20:5: 24:6 } bb6: { - StorageDead(_7); // bb6[0]: scope 3 at $DIR/region-subtyping-basic.rs:24:5: 24:6 - StorageDead(_6); // bb6[1]: scope 2 at $DIR/region-subtyping-basic.rs:25:1: 25:2 - StorageDead(_3); // bb6[2]: scope 1 at $DIR/region-subtyping-basic.rs:25:1: 25:2 - StorageDead(_2); // bb6[3]: scope 1 at $DIR/region-subtyping-basic.rs:25:1: 25:2 - StorageDead(_1); // bb6[4]: scope 0 at $DIR/region-subtyping-basic.rs:25:1: 25:2 - return; // bb6[5]: scope 0 at $DIR/region-subtyping-basic.rs:25:2: 25:2 + StorageDead(_10); // bb6[0]: scope 3 at $DIR/region-subtyping-basic.rs:23:18: 23:19 + _0 = const Const(Value(Scalar()): ()); // bb6[1]: scope 3 at $DIR/region-subtyping-basic.rs:22:12: 24:6 + goto -> bb7; // bb6[2]: scope 3 at $DIR/region-subtyping-basic.rs:20:5: 24:6 + } + + bb7: { + StorageDead(_6); // bb7[0]: scope 2 at $DIR/region-subtyping-basic.rs:25:1: 25:2 + StorageDead(_3); // bb7[1]: scope 1 at $DIR/region-subtyping-basic.rs:25:1: 25:2 + StorageDead(_2); // bb7[2]: scope 1 at $DIR/region-subtyping-basic.rs:25:1: 25:2 + StorageDead(_1); // bb7[3]: scope 0 at $DIR/region-subtyping-basic.rs:25:1: 25:2 + StorageDead(_7); // bb7[4]: scope 0 at $DIR/region-subtyping-basic.rs:25:1: 25:2 + return; // bb7[5]: scope 0 at $DIR/region-subtyping-basic.rs:25:2: 25:2 } - bb7 (cleanup): { - resume; // bb7[0]: scope 0 at $DIR/region-subtyping-basic.rs:16:1: 25:2 + bb8 (cleanup): { + resume; // bb8[0]: scope 0 at $DIR/region-subtyping-basic.rs:16:1: 25:2 } } diff --git a/src/test/mir-opt/nll/region_subtyping_basic.main.nll.0.64bit.mir b/src/test/mir-opt/nll/region_subtyping_basic.main.nll.0.64bit.mir index 00704baa6c19f..15aba40f169cd 100644 --- a/src/test/mir-opt/nll/region_subtyping_basic.main.nll.0.64bit.mir +++ b/src/test/mir-opt/nll/region_subtyping_basic.main.nll.0.64bit.mir @@ -5,19 +5,19 @@ | '_#1r | Local | ['_#1r] | | Inferred Region Values -| '_#0r | U0 | {bb0[0..=8], bb1[0..=7], bb2[0..=3], bb3[0..=1], bb4[0..=3], bb5[0..=2], bb6[0..=5], bb7[0], '_#0r, '_#1r} -| '_#1r | U0 | {bb0[0..=8], bb1[0..=7], bb2[0..=3], bb3[0..=1], bb4[0..=3], bb5[0..=2], bb6[0..=5], bb7[0], '_#1r} +| '_#0r | U0 | {bb0[0..=8], bb1[0..=8], bb2[0], bb3[0..=1], bb4[0..=3], bb5[0..=3], bb6[0..=2], bb7[0..=5], bb8[0], '_#0r, '_#1r} +| '_#1r | U0 | {bb0[0..=8], bb1[0..=8], bb2[0], bb3[0..=1], bb4[0..=3], bb5[0..=3], bb6[0..=2], bb7[0..=5], bb8[0], '_#1r} | '_#2r | U0 | {} -| '_#3r | U0 | {bb1[0..=7], bb2[0..=2]} -| '_#4r | U0 | {bb1[1..=7], bb2[0..=2]} -| '_#5r | U0 | {bb1[4..=7], bb2[0..=2]} +| '_#3r | U0 | {bb1[0..=8], bb2[0], bb4[0..=2]} +| '_#4r | U0 | {bb1[1..=8], bb2[0], bb4[0..=2]} +| '_#5r | U0 | {bb1[4..=8], bb2[0], bb4[0..=2]} | | Inference Constraints -| '_#0r live at {bb0[0..=8], bb1[0..=7], bb2[0..=3], bb3[0..=1], bb4[0..=3], bb5[0..=2], bb6[0..=5], bb7[0]} -| '_#1r live at {bb0[0..=8], bb1[0..=7], bb2[0..=3], bb3[0..=1], bb4[0..=3], bb5[0..=2], bb6[0..=5], bb7[0]} +| '_#0r live at {bb0[0..=8], bb1[0..=8], bb2[0], bb3[0..=1], bb4[0..=3], bb5[0..=3], bb6[0..=2], bb7[0..=5], bb8[0]} +| '_#1r live at {bb0[0..=8], bb1[0..=8], bb2[0], bb3[0..=1], bb4[0..=3], bb5[0..=3], bb6[0..=2], bb7[0..=5], bb8[0]} | '_#3r live at {bb1[0]} | '_#4r live at {bb1[1..=3]} -| '_#5r live at {bb1[4..=7], bb2[0..=2]} +| '_#5r live at {bb1[4..=8], bb2[0], bb4[0..=2]} | '_#3r: '_#4r due to Assignment at Single(bb1[0]) | '_#4r: '_#5r due to Assignment at Single(bb1[3]) | @@ -52,7 +52,7 @@ fn main() -> () { _3 = const Const(Value(Scalar(0x0000000000000000)): usize); // bb0[5]: scope 1 at $DIR/region-subtyping-basic.rs:18:16: 18:17 _4 = Len(_1); // bb0[6]: scope 1 at $DIR/region-subtyping-basic.rs:18:14: 18:18 _5 = Lt(_3, _4); // bb0[7]: scope 1 at $DIR/region-subtyping-basic.rs:18:14: 18:18 - assert(move _5, "index out of bounds: the length is {} but the index is {}", move _4, _3) -> [success: bb1, unwind: bb7]; // bb0[8]: scope 1 at $DIR/region-subtyping-basic.rs:18:14: 18:18 + assert(move _5, "index out of bounds: the length is {} but the index is {}", move _4, _3) -> [success: bb1, unwind: bb8]; // bb0[8]: scope 1 at $DIR/region-subtyping-basic.rs:18:14: 18:18 } bb1: { @@ -63,50 +63,55 @@ fn main() -> () { FakeRead(ForLet, _6); // bb1[4]: scope 2 at $DIR/region-subtyping-basic.rs:19:9: 19:10 StorageLive(_7); // bb1[5]: scope 3 at $DIR/region-subtyping-basic.rs:20:8: 20:12 _7 = const Const(Value(Scalar(0x01)): bool); // bb1[6]: scope 3 at $DIR/region-subtyping-basic.rs:20:8: 20:12 - switchInt(move _7) -> [Const(Value(Scalar(0x00)): bool): bb3, otherwise: bb2]; // bb1[7]: scope 3 at $DIR/region-subtyping-basic.rs:20:5: 24:6 + FakeRead(ForMatchedPlace, _7); // bb1[7]: scope 3 at $DIR/region-subtyping-basic.rs:20:8: 20:12 + switchInt(_7) -> [Const(Value(Scalar(0x00)): bool): bb3, otherwise: bb2]; // bb1[8]: scope 3 at $DIR/region-subtyping-basic.rs:20:5: 24:6 } bb2: { - StorageLive(_8); // bb2[0]: scope 3 at $DIR/region-subtyping-basic.rs:21:9: 21:18 - StorageLive(_9); // bb2[1]: scope 3 at $DIR/region-subtyping-basic.rs:21:15: 21:17 - _9 = (*_6); // bb2[2]: scope 3 at $DIR/region-subtyping-basic.rs:21:15: 21:17 - _8 = Const(Value(Scalar()): fn(usize) -> bool {use_x})(move _9) -> [return: bb4, unwind: bb7]; // bb2[3]: scope 3 at $DIR/region-subtyping-basic.rs:21:9: 21:18 - // mir::Constant - // + span: $DIR/region-subtyping-basic.rs:21:9: 21:14 - // + literal: Const { ty: fn(usize) -> bool {use_x}, val: Value(Scalar()) } + falseEdge -> [real: bb4, imaginary: bb3]; // bb2[0]: scope 3 at $DIR/region-subtyping-basic.rs:20:5: 24:6 } bb3: { StorageLive(_10); // bb3[0]: scope 3 at $DIR/region-subtyping-basic.rs:23:9: 23:18 - _10 = Const(Value(Scalar()): fn(usize) -> bool {use_x})(const Const(Value(Scalar(0x0000000000000016)): usize)) -> [return: bb5, unwind: bb7]; // bb3[1]: scope 3 at $DIR/region-subtyping-basic.rs:23:9: 23:18 + _10 = Const(Value(Scalar()): fn(usize) -> bool {use_x})(const Const(Value(Scalar(0x0000000000000016)): usize)) -> [return: bb6, unwind: bb8]; // bb3[1]: scope 3 at $DIR/region-subtyping-basic.rs:23:9: 23:18 // mir::Constant // + span: $DIR/region-subtyping-basic.rs:23:9: 23:14 // + literal: Const { ty: fn(usize) -> bool {use_x}, val: Value(Scalar()) } } bb4: { - StorageDead(_9); // bb4[0]: scope 3 at $DIR/region-subtyping-basic.rs:21:17: 21:18 - StorageDead(_8); // bb4[1]: scope 3 at $DIR/region-subtyping-basic.rs:21:18: 21:19 - _0 = const Const(Value(Scalar()): ()); // bb4[2]: scope 3 at $DIR/region-subtyping-basic.rs:20:13: 22:6 - goto -> bb6; // bb4[3]: scope 3 at $DIR/region-subtyping-basic.rs:20:5: 24:6 + StorageLive(_8); // bb4[0]: scope 3 at $DIR/region-subtyping-basic.rs:21:9: 21:18 + StorageLive(_9); // bb4[1]: scope 3 at $DIR/region-subtyping-basic.rs:21:15: 21:17 + _9 = (*_6); // bb4[2]: scope 3 at $DIR/region-subtyping-basic.rs:21:15: 21:17 + _8 = Const(Value(Scalar()): fn(usize) -> bool {use_x})(move _9) -> [return: bb5, unwind: bb8]; // bb4[3]: scope 3 at $DIR/region-subtyping-basic.rs:21:9: 21:18 + // mir::Constant + // + span: $DIR/region-subtyping-basic.rs:21:9: 21:14 + // + literal: Const { ty: fn(usize) -> bool {use_x}, val: Value(Scalar()) } } bb5: { - StorageDead(_10); // bb5[0]: scope 3 at $DIR/region-subtyping-basic.rs:23:18: 23:19 - _0 = const Const(Value(Scalar()): ()); // bb5[1]: scope 3 at $DIR/region-subtyping-basic.rs:22:12: 24:6 - goto -> bb6; // bb5[2]: scope 3 at $DIR/region-subtyping-basic.rs:20:5: 24:6 + StorageDead(_9); // bb5[0]: scope 3 at $DIR/region-subtyping-basic.rs:21:17: 21:18 + StorageDead(_8); // bb5[1]: scope 3 at $DIR/region-subtyping-basic.rs:21:18: 21:19 + _0 = const Const(Value(Scalar()): ()); // bb5[2]: scope 3 at $DIR/region-subtyping-basic.rs:20:13: 22:6 + goto -> bb7; // bb5[3]: scope 3 at $DIR/region-subtyping-basic.rs:20:5: 24:6 } bb6: { - StorageDead(_7); // bb6[0]: scope 3 at $DIR/region-subtyping-basic.rs:24:5: 24:6 - StorageDead(_6); // bb6[1]: scope 2 at $DIR/region-subtyping-basic.rs:25:1: 25:2 - StorageDead(_3); // bb6[2]: scope 1 at $DIR/region-subtyping-basic.rs:25:1: 25:2 - StorageDead(_2); // bb6[3]: scope 1 at $DIR/region-subtyping-basic.rs:25:1: 25:2 - StorageDead(_1); // bb6[4]: scope 0 at $DIR/region-subtyping-basic.rs:25:1: 25:2 - return; // bb6[5]: scope 0 at $DIR/region-subtyping-basic.rs:25:2: 25:2 + StorageDead(_10); // bb6[0]: scope 3 at $DIR/region-subtyping-basic.rs:23:18: 23:19 + _0 = const Const(Value(Scalar()): ()); // bb6[1]: scope 3 at $DIR/region-subtyping-basic.rs:22:12: 24:6 + goto -> bb7; // bb6[2]: scope 3 at $DIR/region-subtyping-basic.rs:20:5: 24:6 + } + + bb7: { + StorageDead(_6); // bb7[0]: scope 2 at $DIR/region-subtyping-basic.rs:25:1: 25:2 + StorageDead(_3); // bb7[1]: scope 1 at $DIR/region-subtyping-basic.rs:25:1: 25:2 + StorageDead(_2); // bb7[2]: scope 1 at $DIR/region-subtyping-basic.rs:25:1: 25:2 + StorageDead(_1); // bb7[3]: scope 0 at $DIR/region-subtyping-basic.rs:25:1: 25:2 + StorageDead(_7); // bb7[4]: scope 0 at $DIR/region-subtyping-basic.rs:25:1: 25:2 + return; // bb7[5]: scope 0 at $DIR/region-subtyping-basic.rs:25:2: 25:2 } - bb7 (cleanup): { - resume; // bb7[0]: scope 0 at $DIR/region-subtyping-basic.rs:16:1: 25:2 + bb8 (cleanup): { + resume; // bb8[0]: scope 0 at $DIR/region-subtyping-basic.rs:16:1: 25:2 } } diff --git a/src/test/mir-opt/simplify_cfg.main.SimplifyCfg-early-opt.diff b/src/test/mir-opt/simplify_cfg.main.SimplifyCfg-early-opt.diff index 52e705fdbeba8..5588877aec950 100644 --- a/src/test/mir-opt/simplify_cfg.main.SimplifyCfg-early-opt.diff +++ b/src/test/mir-opt/simplify_cfg.main.SimplifyCfg-early-opt.diff @@ -21,26 +21,31 @@ } - bb2: { -- switchInt(move _2) -> [false: bb4, otherwise: bb3]; // scope 0 at $DIR/simplify_cfg.rs:7:9: 9:10 +- nop; // scope 0 at $DIR/simplify_cfg.rs:7:12: 7:17 +- switchInt(_2) -> [false: bb4, otherwise: bb3]; // scope 0 at $DIR/simplify_cfg.rs:7:9: 9:10 + bb1: { -+ switchInt(move _2) -> [false: bb3, otherwise: bb2]; // scope 0 at $DIR/simplify_cfg.rs:7:9: 9:10 ++ switchInt(_2) -> [false: bb2, otherwise: bb3]; // scope 0 at $DIR/simplify_cfg.rs:7:9: 9:10 } - bb3: { +- goto -> bb5; // scope 0 at $DIR/simplify_cfg.rs:7:9: 9:10 +- } +- +- bb4: { + bb2: { - _0 = const (); // scope 0 at $DIR/simplify_cfg.rs:8:13: 8:18 - StorageDead(_2); // scope 0 at $DIR/simplify_cfg.rs:9:9: 9:10 - return; // scope 0 at $DIR/simplify_cfg.rs:11:2: 11:2 + _1 = const (); // scope 0 at $DIR/simplify_cfg.rs:9:10: 9:10 + StorageDead(_2); // scope 0 at $DIR/simplify_cfg.rs:10:5: 10:6 + goto -> bb0; // scope 0 at $DIR/simplify_cfg.rs:6:5: 10:6 } -- bb4: { +- bb5: { + bb3: { - _1 = const (); // scope 0 at $DIR/simplify_cfg.rs:9:10: 9:10 - StorageDead(_2); // scope 0 at $DIR/simplify_cfg.rs:9:9: 9:10 - goto -> bb0; // scope 0 at $DIR/simplify_cfg.rs:6:5: 10:6 + _0 = const (); // scope 0 at $DIR/simplify_cfg.rs:8:13: 8:18 + StorageDead(_2); // scope 0 at $DIR/simplify_cfg.rs:10:5: 10:6 + return; // scope 0 at $DIR/simplify_cfg.rs:11:2: 11:2 - } - -- bb5 (cleanup): { +- bb6 (cleanup): { - resume; // scope 0 at $DIR/simplify_cfg.rs:5:1: 11:2 } } diff --git a/src/test/mir-opt/simplify_cfg.main.SimplifyCfg-initial.diff b/src/test/mir-opt/simplify_cfg.main.SimplifyCfg-initial.diff index fef3ae2e461d8..e62935225d805 100644 --- a/src/test/mir-opt/simplify_cfg.main.SimplifyCfg-initial.diff +++ b/src/test/mir-opt/simplify_cfg.main.SimplifyCfg-initial.diff @@ -9,63 +9,69 @@ bb0: { - goto -> bb1; // scope 0 at $DIR/simplify_cfg.rs:6:5: 10:6 -+ falseUnwind -> [real: bb1, cleanup: bb5]; // scope 0 at $DIR/simplify_cfg.rs:6:5: 10:6 ++ falseUnwind -> [real: bb1, cleanup: bb6]; // scope 0 at $DIR/simplify_cfg.rs:6:5: 10:6 } bb1: { -- falseUnwind -> [real: bb2, cleanup: bb10]; // scope 0 at $DIR/simplify_cfg.rs:6:5: 10:6 +- falseUnwind -> [real: bb2, cleanup: bb11]; // scope 0 at $DIR/simplify_cfg.rs:6:5: 10:6 - } - - bb2: { StorageLive(_2); // scope 0 at $DIR/simplify_cfg.rs:7:12: 7:17 -- _2 = bar() -> [return: bb3, unwind: bb10]; // scope 0 at $DIR/simplify_cfg.rs:7:12: 7:17 -+ _2 = bar() -> [return: bb2, unwind: bb5]; // scope 0 at $DIR/simplify_cfg.rs:7:12: 7:17 +- _2 = bar() -> [return: bb3, unwind: bb11]; // scope 0 at $DIR/simplify_cfg.rs:7:12: 7:17 ++ _2 = bar() -> [return: bb2, unwind: bb6]; // scope 0 at $DIR/simplify_cfg.rs:7:12: 7:17 // mir::Constant // + span: $DIR/simplify_cfg.rs:7:12: 7:15 // + literal: Const { ty: fn() -> bool {bar}, val: Value(Scalar()) } } - bb3: { -- switchInt(move _2) -> [false: bb5, otherwise: bb4]; // scope 0 at $DIR/simplify_cfg.rs:7:9: 9:10 + bb2: { -+ switchInt(move _2) -> [false: bb4, otherwise: bb3]; // scope 0 at $DIR/simplify_cfg.rs:7:9: 9:10 + FakeRead(ForMatchedPlace, _2); // scope 0 at $DIR/simplify_cfg.rs:7:12: 7:17 +- switchInt(_2) -> [false: bb5, otherwise: bb4]; // scope 0 at $DIR/simplify_cfg.rs:7:9: 9:10 ++ switchInt(_2) -> [false: bb4, otherwise: bb3]; // scope 0 at $DIR/simplify_cfg.rs:7:9: 9:10 } - bb4: { +- falseEdge -> [real: bb6, imaginary: bb5]; // scope 0 at $DIR/simplify_cfg.rs:7:9: 9:10 + bb3: { - _0 = const (); // scope 0 at $DIR/simplify_cfg.rs:8:13: 8:18 -- goto -> bb9; // scope 0 at $DIR/simplify_cfg.rs:8:13: 8:18 -+ StorageDead(_2); // scope 0 at $DIR/simplify_cfg.rs:9:9: 9:10 -+ return; // scope 0 at $DIR/simplify_cfg.rs:11:2: 11:2 ++ falseEdge -> [real: bb5, imaginary: bb4]; // scope 0 at $DIR/simplify_cfg.rs:7:9: 9:10 } - bb5: { + bb4: { _1 = const (); // scope 0 at $DIR/simplify_cfg.rs:9:10: 9:10 -- goto -> bb8; // scope 0 at $DIR/simplify_cfg.rs:7:9: 9:10 -- } -- +- goto -> bb9; // scope 0 at $DIR/simplify_cfg.rs:7:9: 9:10 ++ StorageDead(_2); // scope 0 at $DIR/simplify_cfg.rs:10:5: 10:6 ++ goto -> bb0; // scope 0 at $DIR/simplify_cfg.rs:6:5: 10:6 + } + - bb6: { -- unreachable; // scope 0 at $DIR/simplify_cfg.rs:7:18: 9:10 ++ bb5: { + _0 = const (); // scope 0 at $DIR/simplify_cfg.rs:8:13: 8:18 +- goto -> bb10; // scope 0 at $DIR/simplify_cfg.rs:8:13: 8:18 - } - - bb7: { -- goto -> bb8; // scope 0 at $DIR/simplify_cfg.rs:7:9: 9:10 +- unreachable; // scope 0 at $DIR/simplify_cfg.rs:7:18: 9:10 - } - - bb8: { - StorageDead(_2); // scope 0 at $DIR/simplify_cfg.rs:9:9: 9:10 -- goto -> bb1; // scope 0 at $DIR/simplify_cfg.rs:6:5: 10:6 -+ goto -> bb0; // scope 0 at $DIR/simplify_cfg.rs:6:5: 10:6 - } - +- goto -> bb9; // scope 0 at $DIR/simplify_cfg.rs:7:9: 9:10 +- } +- - bb9: { -- StorageDead(_2); // scope 0 at $DIR/simplify_cfg.rs:9:9: 9:10 -- return; // scope 0 at $DIR/simplify_cfg.rs:11:2: 11:2 + StorageDead(_2); // scope 0 at $DIR/simplify_cfg.rs:10:5: 10:6 +- goto -> bb1; // scope 0 at $DIR/simplify_cfg.rs:6:5: 10:6 - } - -- bb10 (cleanup): { -+ bb5 (cleanup): { +- bb10: { +- StorageDead(_2); // scope 0 at $DIR/simplify_cfg.rs:10:5: 10:6 + return; // scope 0 at $DIR/simplify_cfg.rs:11:2: 11:2 + } + +- bb11 (cleanup): { ++ bb6 (cleanup): { resume; // scope 0 at $DIR/simplify_cfg.rs:5:1: 11:2 } } diff --git a/src/test/mir-opt/simplify_if.main.SimplifyBranches-after-const-prop.diff b/src/test/mir-opt/simplify_if.main.SimplifyBranches-after-const-prop.diff index 2cd57cb8474ec..bf3caf505eda1 100644 --- a/src/test/mir-opt/simplify_if.main.SimplifyBranches-after-const-prop.diff +++ b/src/test/mir-opt/simplify_if.main.SimplifyBranches-after-const-prop.diff @@ -9,11 +9,16 @@ bb0: { StorageLive(_1); // scope 0 at $DIR/simplify_if.rs:6:8: 6:13 _1 = const false; // scope 0 at $DIR/simplify_if.rs:6:8: 6:13 -- switchInt(const false) -> [false: bb2, otherwise: bb1]; // scope 0 at $DIR/simplify_if.rs:6:5: 8:6 -+ goto -> bb2; // scope 0 at $DIR/simplify_if.rs:6:5: 8:6 +- switchInt(const false) -> [false: bb1, otherwise: bb2]; // scope 0 at $DIR/simplify_if.rs:6:5: 8:6 ++ goto -> bb1; // scope 0 at $DIR/simplify_if.rs:6:5: 8:6 } bb1: { + _0 = const (); // scope 0 at $DIR/simplify_if.rs:8:6: 8:6 + goto -> bb4; // scope 0 at $DIR/simplify_if.rs:6:5: 8:6 + } + + bb2: { StorageLive(_2); // scope 0 at $DIR/simplify_if.rs:7:9: 7:15 _2 = noop() -> bb3; // scope 0 at $DIR/simplify_if.rs:7:9: 7:15 // mir::Constant @@ -21,11 +26,6 @@ // + literal: Const { ty: fn() {noop}, val: Value(Scalar()) } } - bb2: { - _0 = const (); // scope 0 at $DIR/simplify_if.rs:8:6: 8:6 - goto -> bb4; // scope 0 at $DIR/simplify_if.rs:6:5: 8:6 - } - bb3: { StorageDead(_2); // scope 0 at $DIR/simplify_if.rs:7:15: 7:16 _0 = const (); // scope 0 at $DIR/simplify_if.rs:6:14: 8:6 @@ -33,7 +33,7 @@ } bb4: { - StorageDead(_1); // scope 0 at $DIR/simplify_if.rs:8:5: 8:6 + StorageDead(_1); // scope 0 at $DIR/simplify_if.rs:9:1: 9:2 return; // scope 0 at $DIR/simplify_if.rs:9:2: 9:2 } } diff --git a/src/test/mir-opt/simplify_locals_fixedpoint.foo.SimplifyLocals.diff b/src/test/mir-opt/simplify_locals_fixedpoint.foo.SimplifyLocals.diff index 70725e5f14f7d..9f7507a5cadb2 100644 --- a/src/test/mir-opt/simplify_locals_fixedpoint.foo.SimplifyLocals.diff +++ b/src/test/mir-opt/simplify_locals_fixedpoint.foo.SimplifyLocals.diff @@ -47,21 +47,21 @@ _8 = _6; // scope 1 at $DIR/simplify-locals-fixedpoint.rs:5:12: 5:13 _7 = Gt(move _8, const 42_u8); // scope 1 at $DIR/simplify-locals-fixedpoint.rs:5:12: 5:20 StorageDead(_8); // scope 1 at $DIR/simplify-locals-fixedpoint.rs:5:19: 5:20 - switchInt(move _7) -> [false: bb5, otherwise: bb4]; // scope 1 at $DIR/simplify-locals-fixedpoint.rs:5:9: 7:10 + switchInt(_7) -> [false: bb4, otherwise: bb5]; // scope 1 at $DIR/simplify-locals-fixedpoint.rs:5:9: 7:10 } bb4: { - _0 = const (); // scope 1 at $DIR/simplify-locals-fixedpoint.rs:5:21: 7:10 + _0 = const (); // scope 1 at $DIR/simplify-locals-fixedpoint.rs:7:10: 7:10 goto -> bb6; // scope 1 at $DIR/simplify-locals-fixedpoint.rs:5:9: 7:10 } bb5: { - _0 = const (); // scope 1 at $DIR/simplify-locals-fixedpoint.rs:7:10: 7:10 + _0 = const (); // scope 1 at $DIR/simplify-locals-fixedpoint.rs:5:21: 7:10 goto -> bb6; // scope 1 at $DIR/simplify-locals-fixedpoint.rs:5:9: 7:10 } bb6: { - StorageDead(_7); // scope 1 at $DIR/simplify-locals-fixedpoint.rs:7:9: 7:10 + StorageDead(_7); // scope 1 at $DIR/simplify-locals-fixedpoint.rs:8:5: 8:6 StorageDead(_6); // scope 0 at $DIR/simplify-locals-fixedpoint.rs:8:5: 8:6 goto -> bb7; // scope 0 at $DIR/simplify-locals-fixedpoint.rs:4:5: 8:6 } diff --git a/src/test/mir-opt/unreachable.main.UnreachablePropagation.diff b/src/test/mir-opt/unreachable.main.UnreachablePropagation.diff index 23a3fbd5f4651..6f44de1e4a4f5 100644 --- a/src/test/mir-opt/unreachable.main.UnreachablePropagation.diff +++ b/src/test/mir-opt/unreachable.main.UnreachablePropagation.diff @@ -44,18 +44,18 @@ - StorageLive(_5); // scope 2 at $DIR/unreachable.rs:12:9: 16:10 - StorageLive(_6); // scope 2 at $DIR/unreachable.rs:12:12: 12:16 - _6 = const true; // scope 2 at $DIR/unreachable.rs:12:12: 12:16 -- switchInt(move _6) -> [false: bb5, otherwise: bb4]; // scope 2 at $DIR/unreachable.rs:12:9: 16:10 +- switchInt(_6) -> [false: bb4, otherwise: bb5]; // scope 2 at $DIR/unreachable.rs:12:9: 16:10 - } - - bb4: { -- _4 = const 21_i32; // scope 2 at $DIR/unreachable.rs:13:13: 13:20 -- _5 = const (); // scope 2 at $DIR/unreachable.rs:12:17: 14:10 +- _4 = const 42_i32; // scope 2 at $DIR/unreachable.rs:15:13: 15:20 +- _5 = const (); // scope 2 at $DIR/unreachable.rs:14:16: 16:10 - goto -> bb6; // scope 2 at $DIR/unreachable.rs:12:9: 16:10 - } - - bb5: { -- _4 = const 42_i32; // scope 2 at $DIR/unreachable.rs:15:13: 15:20 -- _5 = const (); // scope 2 at $DIR/unreachable.rs:14:16: 16:10 +- _4 = const 21_i32; // scope 2 at $DIR/unreachable.rs:13:13: 13:20 +- _5 = const (); // scope 2 at $DIR/unreachable.rs:12:17: 14:10 - goto -> bb6; // scope 2 at $DIR/unreachable.rs:12:9: 16:10 - } - diff --git a/src/test/mir-opt/unreachable_asm.main.UnreachablePropagation.diff b/src/test/mir-opt/unreachable_asm.main.UnreachablePropagation.diff index 3eda18317057b..9bca06a3e2b28 100644 --- a/src/test/mir-opt/unreachable_asm.main.UnreachablePropagation.diff +++ b/src/test/mir-opt/unreachable_asm.main.UnreachablePropagation.diff @@ -46,18 +46,18 @@ StorageLive(_5); // scope 2 at $DIR/unreachable_asm.rs:14:9: 18:10 StorageLive(_6); // scope 2 at $DIR/unreachable_asm.rs:14:12: 14:16 _6 = const true; // scope 2 at $DIR/unreachable_asm.rs:14:12: 14:16 - switchInt(move _6) -> [false: bb5, otherwise: bb4]; // scope 2 at $DIR/unreachable_asm.rs:14:9: 18:10 + switchInt(_6) -> [false: bb4, otherwise: bb5]; // scope 2 at $DIR/unreachable_asm.rs:14:9: 18:10 } bb4: { - _4 = const 21_i32; // scope 2 at $DIR/unreachable_asm.rs:15:13: 15:20 - _5 = const (); // scope 2 at $DIR/unreachable_asm.rs:14:17: 16:10 + _4 = const 42_i32; // scope 2 at $DIR/unreachable_asm.rs:17:13: 17:20 + _5 = const (); // scope 2 at $DIR/unreachable_asm.rs:16:16: 18:10 goto -> bb6; // scope 2 at $DIR/unreachable_asm.rs:14:9: 18:10 } bb5: { - _4 = const 42_i32; // scope 2 at $DIR/unreachable_asm.rs:17:13: 17:20 - _5 = const (); // scope 2 at $DIR/unreachable_asm.rs:16:16: 18:10 + _4 = const 21_i32; // scope 2 at $DIR/unreachable_asm.rs:15:13: 15:20 + _5 = const (); // scope 2 at $DIR/unreachable_asm.rs:14:17: 16:10 goto -> bb6; // scope 2 at $DIR/unreachable_asm.rs:14:9: 18:10 } diff --git a/src/test/mir-opt/unreachable_asm_2.main.UnreachablePropagation.diff b/src/test/mir-opt/unreachable_asm_2.main.UnreachablePropagation.diff index d0d52e869d624..cbc24eab0f568 100644 --- a/src/test/mir-opt/unreachable_asm_2.main.UnreachablePropagation.diff +++ b/src/test/mir-opt/unreachable_asm_2.main.UnreachablePropagation.diff @@ -49,21 +49,10 @@ StorageLive(_5); // scope 2 at $DIR/unreachable_asm_2.rs:14:9: 22:10 StorageLive(_6); // scope 2 at $DIR/unreachable_asm_2.rs:14:12: 14:16 _6 = const true; // scope 2 at $DIR/unreachable_asm_2.rs:14:12: 14:16 - switchInt(move _6) -> [false: bb5, otherwise: bb4]; // scope 2 at $DIR/unreachable_asm_2.rs:14:9: 22:10 + switchInt(_6) -> [false: bb4, otherwise: bb5]; // scope 2 at $DIR/unreachable_asm_2.rs:14:9: 22:10 } bb4: { - StorageLive(_7); // scope 2 at $DIR/unreachable_asm_2.rs:16:13: 16:41 - llvm_asm!(LlvmInlineAsmInner { asm: "NOP", asm_str_style: Cooked, outputs: [], inputs: [], clobbers: [], volatile: true, alignstack: false, dialect: Att } : [] : []); // scope 3 at $DIR/unreachable_asm_2.rs:16:22: 16:39 - _7 = const (); // scope 3 at $DIR/unreachable_asm_2.rs:16:13: 16:41 - StorageDead(_7); // scope 2 at $DIR/unreachable_asm_2.rs:16:40: 16:41 - _4 = const 21_i32; // scope 2 at $DIR/unreachable_asm_2.rs:17:13: 17:20 - _5 = const (); // scope 2 at $DIR/unreachable_asm_2.rs:14:17: 18:10 -- goto -> bb6; // scope 2 at $DIR/unreachable_asm_2.rs:14:9: 22:10 -+ unreachable; // scope 2 at $DIR/unreachable_asm_2.rs:14:9: 22:10 - } - - bb5: { StorageLive(_8); // scope 2 at $DIR/unreachable_asm_2.rs:20:13: 20:41 llvm_asm!(LlvmInlineAsmInner { asm: "NOP", asm_str_style: Cooked, outputs: [], inputs: [], clobbers: [], volatile: true, alignstack: false, dialect: Att } : [] : []); // scope 4 at $DIR/unreachable_asm_2.rs:20:22: 20:39 _8 = const (); // scope 4 at $DIR/unreachable_asm_2.rs:20:13: 20:41 @@ -71,6 +60,17 @@ _4 = const 42_i32; // scope 2 at $DIR/unreachable_asm_2.rs:21:13: 21:20 _5 = const (); // scope 2 at $DIR/unreachable_asm_2.rs:18:16: 22:10 - goto -> bb6; // scope 2 at $DIR/unreachable_asm_2.rs:14:9: 22:10 ++ unreachable; // scope 2 at $DIR/unreachable_asm_2.rs:14:9: 22:10 + } + + bb5: { + StorageLive(_7); // scope 2 at $DIR/unreachable_asm_2.rs:16:13: 16:41 + llvm_asm!(LlvmInlineAsmInner { asm: "NOP", asm_str_style: Cooked, outputs: [], inputs: [], clobbers: [], volatile: true, alignstack: false, dialect: Att } : [] : []); // scope 3 at $DIR/unreachable_asm_2.rs:16:22: 16:39 + _7 = const (); // scope 3 at $DIR/unreachable_asm_2.rs:16:13: 16:41 + StorageDead(_7); // scope 2 at $DIR/unreachable_asm_2.rs:16:40: 16:41 + _4 = const 21_i32; // scope 2 at $DIR/unreachable_asm_2.rs:17:13: 17:20 + _5 = const (); // scope 2 at $DIR/unreachable_asm_2.rs:14:17: 18:10 +- goto -> bb6; // scope 2 at $DIR/unreachable_asm_2.rs:14:9: 22:10 - } - - bb6: { diff --git a/src/test/mir-opt/unreachable_diverging.main.UnreachablePropagation.diff b/src/test/mir-opt/unreachable_diverging.main.UnreachablePropagation.diff index 2c0cc04085efa..fd8286f1c4f39 100644 --- a/src/test/mir-opt/unreachable_diverging.main.UnreachablePropagation.diff +++ b/src/test/mir-opt/unreachable_diverging.main.UnreachablePropagation.diff @@ -45,11 +45,16 @@ StorageLive(_5); // scope 2 at $DIR/unreachable_diverging.rs:15:9: 17:10 StorageLive(_6); // scope 2 at $DIR/unreachable_diverging.rs:15:12: 15:13 _6 = _1; // scope 2 at $DIR/unreachable_diverging.rs:15:12: 15:13 -- switchInt(move _6) -> [false: bb5, otherwise: bb4]; // scope 2 at $DIR/unreachable_diverging.rs:15:9: 17:10 +- switchInt(_6) -> [false: bb4, otherwise: bb5]; // scope 2 at $DIR/unreachable_diverging.rs:15:9: 17:10 + goto -> bb4; // scope 2 at $DIR/unreachable_diverging.rs:15:9: 17:10 } bb4: { +- _5 = const (); // scope 2 at $DIR/unreachable_diverging.rs:17:10: 17:10 +- goto -> bb6; // scope 2 at $DIR/unreachable_diverging.rs:15:9: 17:10 +- } +- +- bb5: { - _5 = loop_forever() -> bb6; // scope 2 at $DIR/unreachable_diverging.rs:16:13: 16:27 + _5 = loop_forever() -> bb5; // scope 2 at $DIR/unreachable_diverging.rs:16:13: 16:27 // mir::Constant @@ -57,12 +62,8 @@ // + literal: Const { ty: fn() {loop_forever}, val: Value(Scalar()) } } - bb5: { -- _5 = const (); // scope 2 at $DIR/unreachable_diverging.rs:17:10: 17:10 -- goto -> bb6; // scope 2 at $DIR/unreachable_diverging.rs:15:9: 17:10 -- } -- - bb6: { ++ bb5: { StorageDead(_6); // scope 2 at $DIR/unreachable_diverging.rs:17:9: 17:10 StorageDead(_5); // scope 2 at $DIR/unreachable_diverging.rs:17:9: 17:10 StorageLive(_7); // scope 2 at $DIR/unreachable_diverging.rs:18:9: 18:22 diff --git a/src/test/mir-opt/while_storage.while_loop.PreCodegen.after.mir b/src/test/mir-opt/while_storage.while_loop.PreCodegen.after.mir index 0c034891a80db..c27c68d870247 100644 --- a/src/test/mir-opt/while_storage.while_loop.PreCodegen.after.mir +++ b/src/test/mir-opt/while_storage.while_loop.PreCodegen.after.mir @@ -40,19 +40,19 @@ fn while_loop(_1: bool) -> () { bb4: { StorageDead(_5); // scope 0 at $DIR/while-storage.rs:11:22: 11:23 - switchInt(move _4) -> [false: bb6, otherwise: bb5]; // scope 0 at $DIR/while-storage.rs:11:9: 13:10 + switchInt(_4) -> [false: bb5, otherwise: bb6]; // scope 0 at $DIR/while-storage.rs:11:9: 13:10 } bb5: { - _0 = const (); // scope 0 at $DIR/while-storage.rs:12:13: 12:18 - StorageDead(_4); // scope 0 at $DIR/while-storage.rs:13:9: 13:10 - goto -> bb7; // scope 0 at $DIR/while-storage.rs:1:1: 1:1 + StorageDead(_4); // scope 0 at $DIR/while-storage.rs:14:5: 14:6 + StorageDead(_2); // scope 0 at $DIR/while-storage.rs:14:5: 14:6 + goto -> bb0; // scope 0 at $DIR/while-storage.rs:10:5: 14:6 } bb6: { - StorageDead(_4); // scope 0 at $DIR/while-storage.rs:13:9: 13:10 - StorageDead(_2); // scope 0 at $DIR/while-storage.rs:14:5: 14:6 - goto -> bb0; // scope 0 at $DIR/while-storage.rs:10:5: 14:6 + _0 = const (); // scope 0 at $DIR/while-storage.rs:12:13: 12:18 + StorageDead(_4); // scope 0 at $DIR/while-storage.rs:14:5: 14:6 + goto -> bb7; // scope 0 at $DIR/while-storage.rs:1:1: 1:1 } bb7: { diff --git a/src/test/pretty/expanded-and-path-remap-80832.pp b/src/test/pretty/expanded-and-path-remap-80832.pp deleted file mode 100644 index 6dbc19e9d9c6c..0000000000000 --- a/src/test/pretty/expanded-and-path-remap-80832.pp +++ /dev/null @@ -1,13 +0,0 @@ -#![feature(prelude_import)] -#![no_std] -#[prelude_import] -use ::std::prelude::v1::*; -#[macro_use] -extern crate std; -// Test for issue 80832 -// -// pretty-mode:expanded -// pp-exact:expanded-and-path-remap-80832.pp -// compile-flags: --remap-path-prefix {{src-base}}=the/src - -fn main() { } diff --git a/src/test/pretty/expanded-and-path-remap-80832.rs b/src/test/pretty/expanded-and-path-remap-80832.rs deleted file mode 100644 index f48441fbc5755..0000000000000 --- a/src/test/pretty/expanded-and-path-remap-80832.rs +++ /dev/null @@ -1,7 +0,0 @@ -// Test for issue 80832 -// -// pretty-mode:expanded -// pp-exact:expanded-and-path-remap-80832.pp -// compile-flags: --remap-path-prefix {{src-base}}=the/src - -fn main() {} diff --git a/src/test/run-make-fulldeps/archive-duplicate-names/foo.rs b/src/test/run-make-fulldeps/archive-duplicate-names/foo.rs index 0bf13c406ab53..5f5ed424ba980 100644 --- a/src/test/run-make-fulldeps/archive-duplicate-names/foo.rs +++ b/src/test/run-make-fulldeps/archive-duplicate-names/foo.rs @@ -1,7 +1,7 @@ #![crate_type = "rlib"] #[link(name = "foo", kind = "static")] -extern "C" { +extern { fn foo(); fn bar(); } diff --git a/src/test/run-make-fulldeps/c-dynamic-dylib/foo.rs b/src/test/run-make-fulldeps/c-dynamic-dylib/foo.rs index 9f7a9e2213c09..14f67017a3b8c 100644 --- a/src/test/run-make-fulldeps/c-dynamic-dylib/foo.rs +++ b/src/test/run-make-fulldeps/c-dynamic-dylib/foo.rs @@ -1,7 +1,7 @@ #![crate_type = "dylib"] #[link(name = "cfoo")] -extern "C" { +extern { fn foo(); } diff --git a/src/test/run-make-fulldeps/c-dynamic-rlib/foo.rs b/src/test/run-make-fulldeps/c-dynamic-rlib/foo.rs index 3dd376f1ff57b..9bf3689cd36d5 100644 --- a/src/test/run-make-fulldeps/c-dynamic-rlib/foo.rs +++ b/src/test/run-make-fulldeps/c-dynamic-rlib/foo.rs @@ -1,7 +1,7 @@ #![crate_type = "rlib"] #[link(name = "cfoo")] -extern "C" { +extern { fn foo(); } diff --git a/src/test/run-make-fulldeps/c-static-dylib/foo.rs b/src/test/run-make-fulldeps/c-static-dylib/foo.rs index 1e8af4d44040b..25e1ed2a9d328 100644 --- a/src/test/run-make-fulldeps/c-static-dylib/foo.rs +++ b/src/test/run-make-fulldeps/c-static-dylib/foo.rs @@ -1,7 +1,7 @@ #![crate_type = "dylib"] #[link(name = "cfoo", kind = "static")] -extern "C" { +extern { fn foo(); } diff --git a/src/test/run-make-fulldeps/c-static-rlib/foo.rs b/src/test/run-make-fulldeps/c-static-rlib/foo.rs index 9c6d2080ef4d3..d434ecfa8bb0b 100644 --- a/src/test/run-make-fulldeps/c-static-rlib/foo.rs +++ b/src/test/run-make-fulldeps/c-static-rlib/foo.rs @@ -1,7 +1,7 @@ #![crate_type = "rlib"] #[link(name = "cfoo", kind = "static")] -extern "C" { +extern { fn foo(); } diff --git a/src/test/run-make-fulldeps/cdylib-dylib-linkage/foo.rs b/src/test/run-make-fulldeps/cdylib-dylib-linkage/foo.rs index c4069495aaff1..c2cc3afcc1322 100644 --- a/src/test/run-make-fulldeps/cdylib-dylib-linkage/foo.rs +++ b/src/test/run-make-fulldeps/cdylib-dylib-linkage/foo.rs @@ -3,11 +3,11 @@ extern crate bar; #[no_mangle] -pub extern "C" fn foo() { +pub extern fn foo() { bar::bar(); } #[no_mangle] -pub extern "C" fn bar(a: u32, b: u32) -> u32 { +pub extern fn bar(a: u32, b: u32) -> u32 { a + b } diff --git a/src/test/run-make-fulldeps/cdylib-fewer-symbols/foo.rs b/src/test/run-make-fulldeps/cdylib-fewer-symbols/foo.rs index af37bc8e9534d..5a6f7c45bd284 100644 --- a/src/test/run-make-fulldeps/cdylib-fewer-symbols/foo.rs +++ b/src/test/run-make-fulldeps/cdylib-fewer-symbols/foo.rs @@ -1,6 +1,6 @@ #![crate_type = "cdylib"] #[no_mangle] -pub extern "C" fn foo() -> u32 { +pub extern fn foo() -> u32 { 3 } diff --git a/src/test/run-make-fulldeps/cdylib/foo.rs b/src/test/run-make-fulldeps/cdylib/foo.rs index c4069495aaff1..c2cc3afcc1322 100644 --- a/src/test/run-make-fulldeps/cdylib/foo.rs +++ b/src/test/run-make-fulldeps/cdylib/foo.rs @@ -3,11 +3,11 @@ extern crate bar; #[no_mangle] -pub extern "C" fn foo() { +pub extern fn foo() { bar::bar(); } #[no_mangle] -pub extern "C" fn bar(a: u32, b: u32) -> u32 { +pub extern fn bar(a: u32, b: u32) -> u32 { a + b } diff --git a/src/test/run-make-fulldeps/compiler-lookup-paths/d.rs b/src/test/run-make-fulldeps/compiler-lookup-paths/d.rs index 6cd9916b6f69d..ca2676cf67db2 100644 --- a/src/test/run-make-fulldeps/compiler-lookup-paths/d.rs +++ b/src/test/run-make-fulldeps/compiler-lookup-paths/d.rs @@ -1,4 +1,4 @@ #![crate_type = "rlib"] #[link(name = "native", kind = "static")] -extern "C" {} +extern {} diff --git a/src/test/run-make-fulldeps/compiler-rt-works-on-mingw/foo.rs b/src/test/run-make-fulldeps/compiler-rt-works-on-mingw/foo.rs index 7fdb815887118..7b5c740cb49b8 100644 --- a/src/test/run-make-fulldeps/compiler-rt-works-on-mingw/foo.rs +++ b/src/test/run-make-fulldeps/compiler-rt-works-on-mingw/foo.rs @@ -1,10 +1,6 @@ -extern "C" { - fn foo(); -} +extern { fn foo(); } pub fn main() { - unsafe { - foo(); - } + unsafe { foo(); } assert_eq!(7f32.powi(3), 343f32); } diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.abort/abort.main.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.abort/abort.main.-------.InstrumentCoverage.0.html index 176587af25be0..9834124694ec7 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.abort/abort.main.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.abort/abort.main.-------.InstrumentCoverage.0.html @@ -77,24 +77,27 @@ 16:11-16:24: @2[3]: _4 = Gt(move _5, const 0_i32) 16:11-16:24: @2[5]: FakeRead(ForMatchedPlace, _4)">@1,2⦊countdown > 0⦉@1,2 { if @3,5⦊countdown < 5⦉@3,5 @6,8⦊{ - might_abort(false); - }⦉@6,8@7⦊⦉@7 +17:12-17:25: @5[4]: _7 = Lt(move _8, const 5_i32) +17:12-17:25: @5[6]: FakeRead(ForMatchedPlace, _7)">@3,5⦊countdown < 5⦉@3,5 @6,8,9⦊{ + might_abort(false); + }⦉@6,8,9@7⦊⦉@7 // See discussion (below the `Notes` section) on coverage results for the closing brace. - if @9⦊countdown < 5⦉@9 @10,12⦊{ might_abort(false); }⦉@10,12@11⦊⦉@11 // Counts for different regions on one line. + if @10⦊countdown < 5⦉@10 @11,13,14⦊{ might_abort(false); }⦉@11,13,14@12⦊⦉@12 // Counts for different regions on one line. // For the following example, the closing brace is the last character on the line. // This shows the character after the closing brace is highlighted, even if that next // character is a newline. - if @13⦊countdown < 5⦉@13 @14,16⦊{ might_abort(false); }⦉@14,16@15⦊⦉@15 - @17,18⦊countdown -= 1⦉@17,18; + if @15⦊countdown < 5⦉@15 @16,18,19⦊{ might_abort(false); }⦉@16,18,19@17⦊⦉@17 + @20,21⦊countdown -= 1⦉@20,21; } @0⦊fn might_abort(should_abort: bool) ⦉@0{ - if @0⦊should_abort⦉@0 { - @1,3,4⦊println!("aborting..."); - panic!("panics and aborts");⦉@1,3,4 + if @0⦊should_abort⦉@0 { + @1,3,4,5⦊println!("aborting..."); + panic!("panics and aborts");⦉@1,3,4,5 } else @2,5,6⦊{ +10:9-10:33: @2.Call: _20 = Arguments::new_v1(move _21, move _25) -> [return: bb6, unwind: bb8] +10:9-10:33: @6.Call: _19 = _print(move _20) -> [return: bb7, unwind: bb8] +10:9-10:33: @7[5]: _18 = const () +9:12-11:6: @7[7]: _0 = const () +12:2-12:2: @7.Return: return">@2,6,7⦊{ println!("Don't Panic"); +10:9-10:33: @2.Call: _20 = Arguments::new_v1(move _21, move _25) -> [return: bb6, unwind: bb8] +10:9-10:33: @6.Call: _19 = _print(move _20) -> [return: bb7, unwind: bb8] +10:9-10:33: @7[5]: _18 = const () +9:12-11:6: @7[7]: _0 = const () +12:2-12:2: @7.Return: return"> println!("Don't Panic"); } +10:9-10:33: @2.Call: _20 = Arguments::new_v1(move _21, move _25) -> [return: bb6, unwind: bb8] +10:9-10:33: @6.Call: _19 = _print(move _20) -> [return: bb7, unwind: bb8] +10:9-10:33: @7[5]: _18 = const () +9:12-11:6: @7[7]: _0 = const () +12:2-12:2: @7.Return: return"> } }⦉@2,5,6
+10:9-10:33: @2.Call: _20 = Arguments::new_v1(move _21, move _25) -> [return: bb6, unwind: bb8] +10:9-10:33: @6.Call: _19 = _print(move _20) -> [return: bb7, unwind: bb8] +10:9-10:33: @7[5]: _18 = const () +9:12-11:6: @7[7]: _0 = const () +12:2-12:2: @7.Return: return">}⦉@2,6,7
diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.assert/assert.main.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.assert/assert.main.-------.InstrumentCoverage.0.html index 365e94cd31e50..f24de8e08432a 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.assert/assert.main.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.assert/assert.main.-------.InstrumentCoverage.0.html @@ -77,20 +77,22 @@ 11:11-11:24: @2[3]: _4 = Gt(move _5, const 0_i32) 11:11-11:24: @2[5]: FakeRead(ForMatchedPlace, _4)">@1,2⦊countdown > 0⦉@1,2
{
if @3,5⦊countdown == 1⦉@3,5 @6,8⦊{ - might_fail_assert(3); - }⦉@6,8 else if @7⦊countdown < 5⦉@7 @9,11⦊{ - might_fail_assert(2); - }⦉@9,11@10⦊⦉@10 - @13,14⦊countdown -= 1⦉@13,14; +12:12-12:26: @5[4]: _7 = Eq(move _8, const 1_i32) +12:12-12:26: @5[6]: FakeRead(ForMatchedPlace, _7)">@3,5⦊countdown == 1⦉@3,5
@6,8,9⦊{ + might_fail_assert(3); + }⦉@6,8,9 else if @7⦊countdown < 5⦉@7 @10,12,13⦊{ + might_fail_assert(2); + }⦉@10,12,13@11⦊⦉@11
+ @15,16⦊countdown -= 1⦉@15,16; } @0,1,2,3,4⦊println!("does 1 + 1 = {}?", one_plus_one);⦉@0,1,2,3,4 - assert_eq!(@0,1,2,3,4⦊1 + 1⦉@0,1,2,3,4, one_plus_one, @5,7,8,9,10,11⦊"the argument was wrong"⦉@5,7,8,9,10,11); + assert_eq!(@0,1,2,3,4⦊1 + 1⦉@0,1,2,3,4, one_plus_one, @5,7,8,9,10,11,12⦊"the argument was wrong"⦉@5,7,8,9,10,11,12); }@6⦊⦉@6 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.async/async.c-{closure#0}.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.async/async.c-{closure#0}.-------.InstrumentCoverage.0.html index 21bfce701fe6e..82a22ccb4e673 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.async/async.c-{closure#0}.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.async/async.c-{closure#0}.-------.InstrumentCoverage.0.html @@ -70,13 +70,15 @@
@0⦊{ +6:8-6:14: @0[6]: _4 = Eq(move _5, const 8_u8) +6:8-6:14: @0[8]: FakeRead(ForMatchedPlace, _4)">@0⦊{ if x == 8⦉@0 { - @1⦊1⦉@1 +6:8-6:14: @0[6]: _4 = Eq(move _5, const 8_u8) +6:8-6:14: @0[8]: FakeRead(ForMatchedPlace, _4)"> if x == 8⦉@0 { + @1,3⦊1⦉@1,3 } else { @2⦊0⦉@2 } -}@3⦊⦉@3
+}@4⦊⦉@4 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.async/async.j-c.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.async/async.j-c.-------.InstrumentCoverage.0.html index e6384b7598fc2..a8e2d7e2f396e 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.async/async.j-c.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.async/async.j-c.-------.InstrumentCoverage.0.html @@ -70,10 +70,12 @@
@0⦊fn c(x: u8) -> u8 { +52:12-52:18: @0[3]: _2 = Eq(move _3, const 8_u8) +52:12-52:18: @0[5]: FakeRead(ForMatchedPlace, _2)">@0⦊fn c(x: u8) -> u8 { if x == 8⦉@0 { - @1⦊1⦉@1 // This line appears covered, but the 1-character expression span covering the `1` +52:12-52:18: @0[3]: _2 = Eq(move _3, const 8_u8) +52:12-52:18: @0[5]: FakeRead(ForMatchedPlace, _2)"> if x == 8⦉@0 { + @1,3⦊1⦉@1,3 // This line appears covered, but the 1-character expression span covering the `1` // is not executed. (`llvm-cov show` displays a `^0` below the `1` ). This is because // `fn j()` executes the open brace for the funciton body, followed by the function's // first executable statement, `match x`. Inner function declarations are not @@ -85,6 +87,6 @@ } else { @2⦊0⦉@2 } - }@3⦊⦉@3
+ }@4⦊⦉@4 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#0}.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#0}.-------.InstrumentCoverage.0.html index b4b171dc955cb..523e839a918dd 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#0}.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#0}.-------.InstrumentCoverage.0.html @@ -72,25 +72,28 @@
|| @0⦊{ +36:12-36:20: @0[5]: _4 = (*((*_1).0: &bool)) +36:12-36:20: @0[6]: FakeRead(ForMatchedPlace, _4)">@0⦊{ let mut countdown = 0; +36:12-36:20: @0[5]: _4 = (*((*_1).0: &bool)) +36:12-36:20: @0[6]: FakeRead(ForMatchedPlace, _4)"> let mut countdown = 0; if is_false⦉@0 @1⦊{ - countdown = 10; - }⦉@1@2⦊⦉@2 - @3,4⦊"alt string 2".to_owned() - }⦉@3,4
+36:12-36:20: @0[5]: _4 = (*((*_1).0: &bool)) +36:12-36:20: @0[6]: FakeRead(ForMatchedPlace, _4)"> if is_false⦉@0
@1,3⦊{ + countdown = 10; + }⦉@1,3@2⦊⦉@2
+ @4,5⦊"alt string 2".to_owned() + }⦉@4,5 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#10}.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#10}.-------.InstrumentCoverage.0.html index c1edc3eb929b0..fdae1a012bc72 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#10}.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#10}.-------.InstrumentCoverage.0.html @@ -72,25 +72,28 @@
|| @0⦊{ +21:20-21:28: @0[5]: _4 = (*(_1.0: &bool)) +21:20-21:28: @0[6]: FakeRead(ForMatchedPlace, _4)">@0⦊{ let mut countdown = 0; +21:20-21:28: @0[5]: _4 = (*(_1.0: &bool)) +21:20-21:28: @0[6]: FakeRead(ForMatchedPlace, _4)"> let mut countdown = 0; if is_false⦉@0 @1⦊{ - countdown = 10; - }⦉@1@2⦊⦉@2 - @3,4⦊"alt string 1".to_owned() - }⦉@3,4
+21:20-21:28: @0[5]: _4 = (*(_1.0: &bool)) +21:20-21:28: @0[6]: FakeRead(ForMatchedPlace, _4)"> if is_false⦉@0
@1,3⦊{ + countdown = 10; + }⦉@1,3@2⦊⦉@2
+ @4,5⦊"alt string 1".to_owned() + }⦉@4,5 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#11}.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#11}.-------.InstrumentCoverage.0.html index 24c1cadacac4a..48f3944b8b762 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#11}.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#11}.-------.InstrumentCoverage.0.html @@ -72,25 +72,28 @@
|| @0⦊{ +63:20-63:28: @0[5]: _4 = (*(_1.0: &bool)) +63:20-63:28: @0[6]: FakeRead(ForMatchedPlace, _4)">@0⦊{ let mut countdown = 0; +63:20-63:28: @0[5]: _4 = (*(_1.0: &bool)) +63:20-63:28: @0[6]: FakeRead(ForMatchedPlace, _4)"> let mut countdown = 0; if is_false⦉@0 @1⦊{ - countdown = 10; - }⦉@1@2⦊⦉@2 - @3,4⦊"alt string 3".to_owned() - }⦉@3,4
+63:20-63:28: @0[5]: _4 = (*(_1.0: &bool)) +63:20-63:28: @0[6]: FakeRead(ForMatchedPlace, _4)"> if is_false⦉@0 @1,3⦊{ + countdown = 10; + }⦉@1,3@2⦊⦉@2 + @4,5⦊"alt string 3".to_owned() + }⦉@4,5 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#1}.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#1}.-------.InstrumentCoverage.0.html index 7a3921c5aec76..233ebf11b2cdc 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#1}.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#1}.-------.InstrumentCoverage.0.html @@ -72,25 +72,28 @@
|| @0⦊{ +78:12-78:20: @0[5]: _4 = (*((*_1).0: &bool)) +78:12-78:20: @0[6]: FakeRead(ForMatchedPlace, _4)">@0⦊{ let mut countdown = 0; +78:12-78:20: @0[5]: _4 = (*((*_1).0: &bool)) +78:12-78:20: @0[6]: FakeRead(ForMatchedPlace, _4)"> let mut countdown = 0; if is_false⦉@0 @1⦊{ - countdown = 10; - }⦉@1@2⦊⦉@2 - @3,4⦊"alt string 4".to_owned() - }⦉@3,4
+78:12-78:20: @0[5]: _4 = (*((*_1).0: &bool)) +78:12-78:20: @0[6]: FakeRead(ForMatchedPlace, _4)"> if is_false⦉@0 @1,3⦊{ + countdown = 10; + }⦉@1,3@2⦊⦉@2 + @4,5⦊"alt string 4".to_owned() + }⦉@4,5 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#2}.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#2}.-------.InstrumentCoverage.0.html index 06b817e4318e8..1cdca25cd6640 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#2}.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#2}.-------.InstrumentCoverage.0.html @@ -72,57 +72,60 @@
|val| @0⦊{ +100:12-100:20: @0[5]: _5 = (*((*_1).0: &bool)) +100:12-100:20: @0[6]: FakeRead(ForMatchedPlace, _5)">@0⦊{ let mut countdown = 0; +100:12-100:20: @0[5]: _5 = (*((*_1).0: &bool)) +100:12-100:20: @0[6]: FakeRead(ForMatchedPlace, _5)"> let mut countdown = 0; if is_false⦉@0 @1⦊{ - countdown = 10; - }⦉@1@2⦊⦉@2 - @3,4,5,6,7⦊format!("'{}'", val) - }⦉@3,4,5,6,7
+100:12-100:20: @0[5]: _5 = (*((*_1).0: &bool)) +100:12-100:20: @0[6]: FakeRead(ForMatchedPlace, _5)"> if is_false⦉@0 @1,3⦊{ + countdown = 10; + }⦉@1,3@2⦊⦉@2 + @4,5,6,7,8⦊format!("'{}'", val) + }⦉@4,5,6,7,8 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#3}.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#3}.-------.InstrumentCoverage.0.html index 0940775840093..032a6a7e435c1 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#3}.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.closure/closure.main-{closure#3}.-------.InstrumentCoverage.0.html @@ -72,20 +72,22 @@
| mut countdown | - @0⦊{ - if is_false⦉@0 @1⦊{ - countdown = 10; - }⦉@1@2⦊⦉@2 - @3,4⦊"closure should be unused".to_owned() - }⦉@3,4
+ @0⦊{ + if is_false⦉@0 @1,3⦊{ + countdown = 10; + }⦉@1,3@2⦊⦉@2 + @4,5⦊"closure should be unused".to_owned() + }⦉@4,5 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.conditions/conditions.main.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.conditions/conditions.main.-------.InstrumentCoverage.0.html index 184dba6abd17f..e16b366e2162e 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.conditions/conditions.main.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.conditions/conditions.main.-------.InstrumentCoverage.0.html @@ -72,236 +72,255 @@
@0⦊fn main() ⦉@0{ let @0⦊mut countdown = 0; +5:8-5:12: @0[5]: _3 = const true +5:8-5:12: @0[6]: FakeRead(ForMatchedPlace, _3)">@0⦊mut countdown = 0; if true⦉@0 @1⦊{ - countdown = 10; - }⦉@1@2⦊⦉@2 +5:8-5:12: @0[5]: _3 = const true +5:8-5:12: @0[6]: FakeRead(ForMatchedPlace, _3)"> if true⦉@0 @1,3⦊{ + countdown = 10; + }⦉@1,3@2⦊⦉@2 const B: u32 = 100; - let @21⦊x⦉@21 = if @3⦊countdown > 7⦉@3 { - @4,6⦊countdown -= 4; - B⦉@4,6 - } else if @5⦊countdown > 2⦉@5 { - if @7⦊countdown < 1⦉@7 || @15⦊countdown > 5⦉@15 || @11⦊countdown != 9⦉@11 @17⦊{ - countdown = 0; - }⦉@17@18⦊⦉@18 - @19,20⦊countdown -= 5; - countdown⦉@19,20 + let @25⦊x⦉@25 = if @4⦊countdown > 7⦉@4 { + @5,7,8⦊countdown -= 4; + B⦉@5,7,8 + } else if @6⦊countdown > 2⦉@6 { + if @9,11⦊countdown < 1⦉@9,11 || @18⦊countdown > 5⦉@18 || @14⦊countdown != 9⦉@14 @20,22⦊{ + countdown = 0; + }⦉@20,22@21⦊⦉@21 + @23,24⦊countdown -= 5; + countdown⦉@23,24 } else { - @8⦊return⦉@8; + @10⦊return⦉@10; }; - let @21⦊mut countdown = 0; - if true⦉@21 @22⦊{ - countdown = 10; - }⦉@22@23⦊⦉@23 + let @25⦊mut countdown = 0; + if true⦉@25 @26,28⦊{ + countdown = 10; + }⦉@26,28@27⦊⦉@27 - if @24⦊countdown > 7⦉@24 @25,27⦊{ - countdown -= 4; - }⦉@25,27 else if @26⦊countdown > 2⦉@26 { - if @28⦊countdown < 1⦉@28 || @36⦊countdown > 5⦉@36 || @32⦊countdown != 9⦉@32 @38⦊{ - countdown = 0; - }⦉@38@39⦊⦉@39 - @40,41⦊countdown -= 5⦉@40,41; + if @29⦊countdown > 7⦉@29 @30,32,33⦊{ + countdown -= 4; + }⦉@30,32,33 else if @31⦊countdown > 2⦉@31 { + if @34,36⦊countdown < 1⦉@34,36 || @43⦊countdown > 5⦉@43 || @39⦊countdown != 9⦉@39 @45,47⦊{ + countdown = 0; + }⦉@45,47@46⦊⦉@46 + @48,49⦊countdown -= 5⦉@48,49; } else { - @29⦊return⦉@29; + @35⦊return⦉@35; } - if @42⦊true⦉@42 { - let @43⦊mut countdown = 0; - if true⦉@43 @45⦊{ - countdown = 10; - }⦉@45@46⦊⦉@46 + if @50⦊true⦉@50 { + let @51,53⦊mut countdown = 0; + if true⦉@51,53 @54,56⦊{ + countdown = 10; + }⦉@54,56@55⦊⦉@55 - if @47⦊countdown > 7⦉@47 @48,50⦊{ - countdown -= 4; - }⦉@48,50 - else if @49⦊countdown > 2⦉@49 { - if @51⦊countdown < 1⦉@51 || @59⦊countdown > 5⦉@59 || @55⦊countdown != 9⦉@55 @61⦊{ - countdown = 0; - }⦉@61@62⦊⦉@62 - @63,64⦊countdown -= 5⦉@63,64; + if @57⦊countdown > 7⦉@57 @58,60,61⦊{ + countdown -= 4; + }⦉@58,60,61 + else if @59⦊countdown > 2⦉@59 { + if @62,64⦊countdown < 1⦉@62,64 || @71⦊countdown > 5⦉@71 || @67⦊countdown != 9⦉@67 @73,75⦊{ + countdown = 0; + }⦉@73,75@74⦊⦉@74 + @76,77⦊countdown -= 5⦉@76,77; } else { - @52⦊return⦉@52; + @63⦊return⦉@63; } - }@44⦊⦉@44 // Note: closing brace shows uncovered (vs. `0` for implicit else) because condition literal + }@52⦊⦉@52 // Note: closing brace shows uncovered (vs. `0` for implicit else) because condition literal // `true` was const-evaluated. The compiler knows the `if` block will be executed. - let @66⦊mut countdown = 0; - if true⦉@66 @67⦊{ - countdown = 1; - }⦉@67@68⦊⦉@68 + let @79⦊mut countdown = 0; + if true⦉@79 @80,82⦊{ + countdown = 1; + }⦉@80,82@81⦊⦉@81 - let @89⦊z⦉@89 = if @69⦊countdown > 7⦉@69 @70,72⦊{ - countdown -= 4; - }⦉@70,72 else if @71⦊countdown > 2⦉@71 { - if @73⦊countdown < 1⦉@73 || @81⦊countdown > 5⦉@81 || @77⦊countdown != 9⦉@77 @83⦊{ - countdown = 0; - }⦉@83@84⦊⦉@84 - @85,86⦊countdown -= 5⦉@85,86; + let @106⦊z⦉@106 = if @83⦊countdown > 7⦉@83 @84,86,87⦊{ + countdown -= 4; + }⦉@84,86,87 else if @85⦊countdown > 2⦉@85 { + if @88,90⦊countdown < 1⦉@88,90 || @97⦊countdown > 5⦉@97 || @93⦊countdown != 9⦉@93 @99,101⦊{ + countdown = 0; + }⦉@99,101@100⦊⦉@100 + @102,103⦊countdown -= 5⦉@102,103; } else { - let @74,87,88⦊should_be_reachable = countdown; - println!("reached"); - return⦉@74,87,88; + let @89,104,105⦊should_be_reachable = countdown; + println!("reached"); + return⦉@89,104,105; }; - let @107⦊w⦉@107 = if @89⦊countdown > 7⦉@89 @90,92⦊{ - countdown -= 4; - }⦉@90,92 else if @91⦊countdown > 2⦉@91 { - if @93⦊countdown < 1⦉@93 || @101⦊countdown > 5⦉@101 || @97⦊countdown != 9⦉@97 @103⦊{ - countdown = 0; - }⦉@103@104⦊⦉@104 - @105,106⦊countdown -= 5⦉@105,106; + let @127⦊w⦉@127 = if @106⦊countdown > 7⦉@106 @107,109,110⦊{ + countdown -= 4; + }⦉@107,109,110 else if @108⦊countdown > 2⦉@108 { + if @111,113⦊countdown < 1⦉@111,113 || @120⦊countdown > 5⦉@120 || @116⦊countdown != 9⦉@116 @122,124⦊{ + countdown = 0; + }⦉@122,124@123⦊⦉@123 + @125,126⦊countdown -= 5⦉@125,126; } else { - @94⦊return⦉@94; + @112⦊return⦉@112; }; -}@111⦊⦉@111
+}@131⦊⦉@131 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.dead_code/dead_code.main.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.dead_code/dead_code.main.-------.InstrumentCoverage.0.html index 421fe27825c3f..59d00600738f0 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.dead_code/dead_code.main.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.dead_code/dead_code.main.-------.InstrumentCoverage.0.html @@ -69,75 +69,83 @@ -
@0,1,2,3⦊fn main() { -@0,1,2,3⦊fn main() { + // Initialize test constants in a way that cannot be determined at compile time, to ensure - // Initialize test constants in a way that cannot be determined at compile time, to ensure + // rustc and LLVM cannot optimize out statements (or coverage counters) downstream from - // rustc and LLVM cannot optimize out statements (or coverage counters) downstream from + // dependent conditions. - // dependent conditions. + let is_true = std::env::args().len() == 1; - let is_true = std::env::args().len() == 1; + - + let mut countdown = 0; - let mut countdown = 0; + if is_true⦉@0,1,2,3 @4⦊{ - countdown = 10; - }⦉@4@5⦊⦉@5 -}@6⦊⦉@6
+34:8-34:15: @3[5]: _6 = _1 +34:8-34:15: @3[6]: FakeRead(ForMatchedPlace, _6)"> if is_true⦉@0,1,2,3 @4,6⦊{ + countdown = 10; + }⦉@4,6@5⦊⦉@5 +}@7⦊⦉@7 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.dead_code/dead_code.unused_fn.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.dead_code/dead_code.unused_fn.-------.InstrumentCoverage.0.html index ff3493c9f623b..1a535b937887b 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.dead_code/dead_code.unused_fn.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.dead_code/dead_code.unused_fn.-------.InstrumentCoverage.0.html @@ -69,75 +69,83 @@ -
@0,1,2,3⦊fn unused_fn() { -@0,1,2,3⦊fn unused_fn() { + // Initialize test constants in a way that cannot be determined at compile time, to ensure - // Initialize test constants in a way that cannot be determined at compile time, to ensure + // rustc and LLVM cannot optimize out statements (or coverage counters) downstream from - // rustc and LLVM cannot optimize out statements (or coverage counters) downstream from + // dependent conditions. - // dependent conditions. + let is_true = std::env::args().len() == 1; - let is_true = std::env::args().len() == 1; + - + let mut countdown = 0; - let mut countdown = 0; + if is_true⦉@0,1,2,3 @4⦊{ - countdown = 10; - }⦉@4@5⦊⦉@5 -}@6⦊⦉@6
+22:8-22:15: @3[5]: _6 = _1 +22:8-22:15: @3[6]: FakeRead(ForMatchedPlace, _6)"> if is_true⦉@0,1,2,3 @4,6⦊{ + countdown = 10; + }⦉@4,6@5⦊⦉@5 +}@7⦊⦉@7 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.dead_code/dead_code.unused_pub_fn_not_in_library.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.dead_code/dead_code.unused_pub_fn_not_in_library.-------.InstrumentCoverage.0.html index 829113e8a71d5..6eff51ad89c73 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.dead_code/dead_code.unused_pub_fn_not_in_library.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.dead_code/dead_code.unused_pub_fn_not_in_library.-------.InstrumentCoverage.0.html @@ -69,75 +69,83 @@ -
@0,1,2,3⦊pub fn unused_pub_fn_not_in_library() { -@0,1,2,3⦊pub fn unused_pub_fn_not_in_library() { + // Initialize test constants in a way that cannot be determined at compile time, to ensure - // Initialize test constants in a way that cannot be determined at compile time, to ensure + // rustc and LLVM cannot optimize out statements (or coverage counters) downstream from - // rustc and LLVM cannot optimize out statements (or coverage counters) downstream from + // dependent conditions. - // dependent conditions. + let is_true = std::env::args().len() == 1; - let is_true = std::env::args().len() == 1; + - + let mut countdown = 0; - let mut countdown = 0; + if is_true⦉@0,1,2,3 @4⦊{ - countdown = 10; - }⦉@4@5⦊⦉@5 -}@6⦊⦉@6
+10:8-10:15: @3[5]: _6 = _1 +10:8-10:15: @3[6]: FakeRead(ForMatchedPlace, _6)"> if is_true⦉@0,1,2,3 @4,6⦊{ + countdown = 10; + }⦉@4,6@5⦊⦉@5 +}@7⦊⦉@7 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.doctest/doctest.main.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.doctest/doctest.main.-------.InstrumentCoverage.0.html index 3566912628a9e..333476a2df573 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.doctest/doctest.main.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.doctest/doctest.main.-------.InstrumentCoverage.0.html @@ -70,57 +70,58 @@
@0⦊fn main() ⦉@0{ - if @0⦊true⦉@0 { - @4⦊@3,5,6,7⦊assert_eq!(1, 1);⦉@3,5,6,7⦉@4 + if @0⦊true⦉@0 { + @5⦊@4,6,7,8,9⦊assert_eq!(1, 1);⦉@4,6,7,8,9⦉@5 } else { - @9⦊@8,10,11,12⦊assert_eq!(1, 2);⦉@8,10,11,12⦉@9 + @11⦊@10,12,13,14,15⦊assert_eq!(1, 2);⦉@10,12,13,14,15⦉@11 } -}@13⦊⦉@13
+}@16⦊⦉@16 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.doctest_crate/doctest_crate.fn_run_in_doctests.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.doctest_crate/doctest_crate.fn_run_in_doctests.-------.InstrumentCoverage.0.html index 02c25cc904c4a..ae119d9ca9f2e 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.doctest_crate/doctest_crate.fn_run_in_doctests.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.doctest_crate/doctest_crate.fn_run_in_doctests.-------.InstrumentCoverage.0.html @@ -71,103 +71,103 @@
@0⦊pub fn fn_run_in_doctests(conditional: usize) ⦉@0{ match @0⦊conditional⦉@0 { - 1 => @7⦊@6,8,9,10⦊assert_eq!(1, 1)⦉@6,8,9,10⦉@7, // this is run, - 2 => @13⦊@12,14,15,16⦊assert_eq!(1, 1)⦉@12,14,15,16⦉@13, // this, - 3 => @19⦊@18,20,21,22⦊assert_eq!(1, 1)⦉@18,20,21,22⦉@19, // and this too - _ => @24⦊@23,25,26,27⦊assert_eq!(1, 2)⦉@23,25,26,27⦉@24, // however this is not + 1 => @7⦊@6,8,9,10,11⦊assert_eq!(1, 1)⦉@6,8,9,10,11⦉@7, // this is run, + 2 => @14⦊@13,15,16,17,18⦊assert_eq!(1, 1)⦉@13,15,16,17,18⦉@14, // this, + 3 => @21⦊@20,22,23,24,25⦊assert_eq!(1, 1)⦉@20,22,23,24,25⦉@21, // and this too + _ => @27⦊@26,28,29,30,31⦊assert_eq!(1, 2)⦉@26,28,29,30,31⦉@27, // however this is not } -}@28⦊⦉@28
+}@32⦊⦉@32 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.drop_trait/drop_trait.main.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.drop_trait/drop_trait.main.-------.InstrumentCoverage.0.html index 3b5d1e2cdac28..fa3c4b3c31257 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.drop_trait/drop_trait.main.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.drop_trait/drop_trait.main.-------.InstrumentCoverage.0.html @@ -73,80 +73,86 @@ 15:9-15:21: @0[2]: FakeRead(ForLet, _1) 17:16-17:42: @0[4]: _2 = Firework { strength: const 100_i32 } 17:9-17:13: @0[5]: FakeRead(ForLet, _2) -19:8-19:12: @0[8]: _4 = const true">@0⦊fn main() -> Result<(),u8> { +19:8-19:12: @0[8]: _4 = const true +19:8-19:12: @0[9]: FakeRead(ForMatchedPlace, _4)">@0⦊fn main() -> Result<(),u8> { let _firecracker = Firework { strength: 1 }; +19:8-19:12: @0[8]: _4 = const true +19:8-19:12: @0[9]: FakeRead(ForMatchedPlace, _4)"> let _firecracker = Firework { strength: 1 }; +19:8-19:12: @0[8]: _4 = const true +19:8-19:12: @0[9]: FakeRead(ForMatchedPlace, _4)"> let _tnt = Firework { strength: 100 }; +19:8-19:12: @0[8]: _4 = const true +19:8-19:12: @0[9]: FakeRead(ForMatchedPlace, _4)"> let _tnt = Firework { strength: 100 }; +19:8-19:12: @0[8]: _4 = const true +19:8-19:12: @0[9]: FakeRead(ForMatchedPlace, _4)"> if true⦉@0 { - @1,3,4,8,9⦊println!("Exiting with error..."); - return Err(1)⦉@1,3,4,8,9; +19:8-19:12: @0[8]: _4 = const true +19:8-19:12: @0[9]: FakeRead(ForMatchedPlace, _4)"> if true⦉@0 { + @1,3,4,5,9,10⦊println!("Exiting with error..."); + return Err(1)⦉@1,3,4,5,9,10; }@2,5,6,7⦊ +26:8-26:10: @6[2]: _19 = () +26:5-26:11: @6[3]: _0 = std::result::Result::<(), u8>::Ok(move _19)">@2,6,7,8⦊ +26:8-26:10: @6[2]: _19 = () +26:5-26:11: @6[3]: _0 = std::result::Result::<(), u8>::Ok(move _19)"> let _ = Firework { strength: 1000 }; +26:8-26:10: @6[2]: _19 = () +26:5-26:11: @6[3]: _0 = std::result::Result::<(), u8>::Ok(move _19)"> let _ = Firework { strength: 1000 }; +26:8-26:10: @6[2]: _19 = () +26:5-26:11: @6[3]: _0 = std::result::Result::<(), u8>::Ok(move _19)"> Ok(())⦉@2,5,6,7 -}@10⦊⦉@10 +26:8-26:10: @6[2]: _19 = () +26:5-26:11: @6[3]: _0 = std::result::Result::<(), u8>::Ok(move _19)"> Ok(())⦉@2,6,7,8 +}@11⦊⦉@11 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.generics/generics.main.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.generics/generics.main.-------.InstrumentCoverage.0.html index 0373b38e1b11f..52c5d4f47b1d3 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.generics/generics.main.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.generics/generics.main.-------.InstrumentCoverage.0.html @@ -72,166 +72,175 @@
@0,1,2,3⦊fn main() -> Result<(),u8> { +28:5-28:28: @2.Call: _7 = Firework::<f64>::set_strength(move _8, const 300.30000000000001f64) -> [return: bb3, unwind: bb15] +30:8-30:12: @3[4]: _10 = const true +30:8-30:12: @3[5]: FakeRead(ForMatchedPlace, _10)">@0,1,2,3⦊fn main() -> Result<(),u8> { let mut firecracker = Firework { strength: 1 }; +28:5-28:28: @2.Call: _7 = Firework::<f64>::set_strength(move _8, const 300.30000000000001f64) -> [return: bb3, unwind: bb15] +30:8-30:12: @3[4]: _10 = const true +30:8-30:12: @3[5]: FakeRead(ForMatchedPlace, _10)"> let mut firecracker = Firework { strength: 1 }; firecracker.set_strength(2); +28:5-28:28: @2.Call: _7 = Firework::<f64>::set_strength(move _8, const 300.30000000000001f64) -> [return: bb3, unwind: bb15] +30:8-30:12: @3[4]: _10 = const true +30:8-30:12: @3[5]: FakeRead(ForMatchedPlace, _10)"> firecracker.set_strength(2); +28:5-28:28: @2.Call: _7 = Firework::<f64>::set_strength(move _8, const 300.30000000000001f64) -> [return: bb3, unwind: bb15] +30:8-30:12: @3[4]: _10 = const true +30:8-30:12: @3[5]: FakeRead(ForMatchedPlace, _10)"> let mut tnt = Firework { strength: 100.1 }; +28:5-28:28: @2.Call: _7 = Firework::<f64>::set_strength(move _8, const 300.30000000000001f64) -> [return: bb3, unwind: bb15] +30:8-30:12: @3[4]: _10 = const true +30:8-30:12: @3[5]: FakeRead(ForMatchedPlace, _10)"> let mut tnt = Firework { strength: 100.1 }; tnt.set_strength(200.1); +28:5-28:28: @2.Call: _7 = Firework::<f64>::set_strength(move _8, const 300.30000000000001f64) -> [return: bb3, unwind: bb15] +30:8-30:12: @3[4]: _10 = const true +30:8-30:12: @3[5]: FakeRead(ForMatchedPlace, _10)"> tnt.set_strength(200.1); tnt.set_strength(300.3); +28:5-28:28: @2.Call: _7 = Firework::<f64>::set_strength(move _8, const 300.30000000000001f64) -> [return: bb3, unwind: bb15] +30:8-30:12: @3[4]: _10 = const true +30:8-30:12: @3[5]: FakeRead(ForMatchedPlace, _10)"> tnt.set_strength(300.3); +28:5-28:28: @2.Call: _7 = Firework::<f64>::set_strength(move _8, const 300.30000000000001f64) -> [return: bb3, unwind: bb15] +30:8-30:12: @3[4]: _10 = const true +30:8-30:12: @3[5]: FakeRead(ForMatchedPlace, _10)"> if true⦉@0,1,2,3 { - @4,6,7,11,12⦊println!("Exiting with error..."); - return Err(1)⦉@4,6,7,11,12; +28:5-28:28: @2.Call: _7 = Firework::<f64>::set_strength(move _8, const 300.30000000000001f64) -> [return: bb3, unwind: bb15] +30:8-30:12: @3[4]: _10 = const true +30:8-30:12: @3[5]: FakeRead(ForMatchedPlace, _10)"> if true⦉@0,1,2,3 { + @4,6,7,8,12,13⦊println!("Exiting with error..."); + return Err(1)⦉@4,6,7,8,12,13; }@5,8,9,10⦊ // The remaining lines below have no coverage because `if true` (with the constant literal +41:8-41:10: @9[2]: _25 = () +41:5-41:11: @9[3]: _0 = std::result::Result::<(), u8>::Ok(move _25)">@5,9,10,11⦊ // The remaining lines below have no coverage because `if true` (with the constant literal // `true`) is guaranteed to execute the `then` block, which is also guaranteed to `return`. +41:8-41:10: @9[2]: _25 = () +41:5-41:11: @9[3]: _0 = std::result::Result::<(), u8>::Ok(move _25)"> // `true`) is guaranteed to execute the `then` block, which is also guaranteed to `return`. // Thankfully, in the normal case, conditions are not guaranteed ahead of time, and as shown +41:8-41:10: @9[2]: _25 = () +41:5-41:11: @9[3]: _0 = std::result::Result::<(), u8>::Ok(move _25)"> // Thankfully, in the normal case, conditions are not guaranteed ahead of time, and as shown // in other tests, the lines below would have coverage (which would show they had `0` +41:8-41:10: @9[2]: _25 = () +41:5-41:11: @9[3]: _0 = std::result::Result::<(), u8>::Ok(move _25)"> // in other tests, the lines below would have coverage (which would show they had `0` // executions, assuming the condition still evaluated to `true`). +41:8-41:10: @9[2]: _25 = () +41:5-41:11: @9[3]: _0 = std::result::Result::<(), u8>::Ok(move _25)"> // executions, assuming the condition still evaluated to `true`). +41:8-41:10: @9[2]: _25 = () +41:5-41:11: @9[3]: _0 = std::result::Result::<(), u8>::Ok(move _25)"> let _ = Firework { strength: 1000 }; +41:8-41:10: @9[2]: _25 = () +41:5-41:11: @9[3]: _0 = std::result::Result::<(), u8>::Ok(move _25)"> let _ = Firework { strength: 1000 }; +41:8-41:10: @9[2]: _25 = () +41:5-41:11: @9[3]: _0 = std::result::Result::<(), u8>::Ok(move _25)"> Ok(())⦉@5,8,9,10 -}@13⦊⦉@13
+41:8-41:10: @9[2]: _25 = () +41:5-41:11: @9[3]: _0 = std::result::Result::<(), u8>::Ok(move _25)"> Ok(())⦉@5,9,10,11 +}@14⦊⦉@14 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.if/if.main.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.if/if.main.-------.InstrumentCoverage.0.html index dd9ba4a190cd8..8eb6c1dcb877a 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.if/if.main.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.if/if.main.-------.InstrumentCoverage.0.html @@ -69,170 +69,189 @@ -
@0,1,2,3⦊fn main() { -@0,1,2,3⦊fn main() { + // Initialize test constants in a way that cannot be determined at compile time, to ensure - // Initialize test constants in a way that cannot be determined at compile time, to ensure + // rustc and LLVM cannot optimize out statements (or coverage counters) downstream from - // rustc and LLVM cannot optimize out statements (or coverage counters) downstream from + // dependent conditions. - // dependent conditions. + let - let + is_true - is_true + = - = + std::env::args().len() - std::env::args().len() + == - == + 1 - 1 + ; - ; + let - let + mut - mut + countdown - countdown + = - = + 0 - 0 + ; - ; + if - if + is_true⦉@0,1,2,3 - @4⦊{ - countdown - = - 10 - ; - }⦉@4@5⦊⦉@5 -}@6⦊⦉@6
+21:9-21:16: @3[5]: _6 = _1 +21:9-21:16: @3[6]: FakeRead(ForMatchedPlace, _6)"> is_true⦉@0,1,2,3 + @4,6⦊{ + countdown + = + 10 + ; + }⦉@4,6@5⦊⦉@5 +}@7⦊⦉@7 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.if_else/if_else.main.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.if_else/if_else.main.-------.InstrumentCoverage.0.html index b642be382cbc4..5b2cce4f648fc 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.if_else/if_else.main.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.if_else/if_else.main.-------.InstrumentCoverage.0.html @@ -69,90 +69,99 @@ -
@0,1,2,3⦊fn main() { -@0,1,2,3⦊fn main() { + // Initialize test constants in a way that cannot be determined at compile time, to ensure - // Initialize test constants in a way that cannot be determined at compile time, to ensure + // rustc and LLVM cannot optimize out statements (or coverage counters) downstream from - // rustc and LLVM cannot optimize out statements (or coverage counters) downstream from + // dependent conditions. - // dependent conditions. + let is_true = std::env::args().len() == 1; - let is_true = std::env::args().len() == 1; + - + let mut countdown = 0; - let mut countdown = 0; + if - if + is_true⦉@0,1,2,3 - @4⦊{ - countdown - = - 10 - ; - }⦉@4 +11:9-11:16: @3[6]: _7 = _1 +11:9-11:16: @3[7]: FakeRead(ForMatchedPlace, _7)"> is_true⦉@0,1,2,3 + @4,6⦊{ + countdown + = + 10 + ; + }⦉@4,6 else // Note coverage region difference without semicolon { } if - @6⦊is_true⦉@6 - @7⦊{ - countdown - = - 10 - ; - }⦉@7 + @7⦊is_true⦉@7 + @8,10⦊{ + countdown + = + 10 + ; + }⦉@8,10 else - @8⦊{ - countdown - = - 100 - ; - }⦉@8 -}@9⦊⦉@9
+ @9⦊{ + countdown + = + 100 + ; + }⦉@9 +}@11⦊⦉@11 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.inner_items/inner_items.main.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.inner_items/inner_items.main.-------.InstrumentCoverage.0.html index d21710b7240d3..693b15f15b9ca 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.inner_items/inner_items.main.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.inner_items/inner_items.main.-------.InstrumentCoverage.0.html @@ -73,43 +73,47 @@ // Initialize test constants in a way that cannot be determined at compile time, to ensure // rustc and LLVM cannot optimize out statements (or coverage counters) downstream from // dependent conditions. - let let @0,1,2,3⦊is_true = std::env::args().len() == 1; -@0,1,2,3⦊is_true = std::env::args().len() == 1; + - + let mut countdown = 0; - let mut countdown = 0; + if is_true⦉@0,1,2,3 @4⦊{ - countdown = 10; - }⦉@4@5⦊⦉@5 +10:8-10:15: @3[6]: _7 = _1 +10:8-10:15: @3[7]: FakeRead(ForMatchedPlace, _7)"> if is_true⦉@0,1,2,3 @4,6⦊{ + countdown = 10; + }⦉@4,6@5⦊⦉@5 mod in_mod { const IN_MOD_CONST: u32 = 1000; @@ -145,45 +149,46 @@ type InType = String; - if @6⦊is_true⦉@6 @7,9⦊{ - in_func(countdown); - }⦉@7,9@8⦊⦉@8 + if @7⦊is_true⦉@7 @8,10,11⦊{ + in_func(countdown); + }⦉@8,10,11@9⦊⦉@9 - let @10,11⦊mut val = InStruct { - in_struct_field: 101, - }; - - val.default_trait_func(); -}⦉@10,11 + let @12,13⦊mut val = InStruct { + in_struct_field: 101, + }; + + val.default_trait_func(); +}⦉@12,13 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.lazy_boolean/lazy_boolean.main.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.lazy_boolean/lazy_boolean.main.-------.InstrumentCoverage.0.html index 0cfe2119fbc8a..f30f0ed9a8489 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.lazy_boolean/lazy_boolean.main.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.lazy_boolean/lazy_boolean.main.-------.InstrumentCoverage.0.html @@ -69,191 +69,204 @@ -
@0,1,2,3⦊fn main() { -@0,1,2,3⦊fn main() { + // Initialize test constants in a way that cannot be determined at compile time, to ensure - // Initialize test constants in a way that cannot be determined at compile time, to ensure + // rustc and LLVM cannot optimize out statements (or coverage counters) downstream from - // rustc and LLVM cannot optimize out statements (or coverage counters) downstream from + // dependent conditions. - // dependent conditions. + let is_true = std::env::args().len() == 1; - let is_true = std::env::args().len() == 1; + - + let (mut a, mut b, mut c) = (0, 0, 0); - let (mut a, mut b, mut c) = (0, 0, 0); + if is_true⦉@0,1,2,3 @4⦊{ - a = 1; - b = 10; - c = 100; - }⦉@4@5⦊⦉@5 +10:8-10:15: @3[12]: _10 = _1 +10:8-10:15: @3[13]: FakeRead(ForMatchedPlace, _10)"> if is_true⦉@0,1,2,3 @4,6⦊{ + a = 1; + b = 10; + c = 100; + }⦉@4,6@5⦊⦉@5 let - @10⦊somebool⦉@10 + @11⦊somebool⦉@11 = - @6⦊a < b⦉@6 + @7⦊a < b⦉@7 || - @9⦊b < c⦉@9 + @10⦊b < c⦉@10 ; let - @14⦊somebool⦉@14 + @15⦊somebool⦉@15 = - @10⦊b < a⦉@10 + @11⦊b < a⦉@11 || - @13⦊b < c⦉@13 + @14⦊b < c⦉@14 ; - let @18⦊somebool⦉@18 = @14⦊a < b⦉@14 && @17⦊b < c⦉@17; - let @22⦊somebool⦉@22 = @18⦊b < a⦉@18 && @21⦊b < c⦉@21; + let @19⦊somebool⦉@19 = @15⦊a < b⦉@15 && @18⦊b < c⦉@18; + let @23⦊somebool⦉@23 = @19⦊b < a⦉@19 && @22⦊b < c⦉@22; if - @22⦊! - is_true⦉@22 - @23⦊{ - a = 2 - ; - }⦉@23@24⦊⦉@24 + @23⦊! + is_true⦉@23 + @24,26⦊{ + a = 2 + ; + }⦉@24,26@25⦊⦉@25 if - @25⦊is_true⦉@25 - @26⦊{ - b = 30 - ; - }⦉@26 + @27⦊is_true⦉@27 + @28,30⦊{ + b = 30 + ; + }⦉@28,30 else - @27⦊{ - c = 400 - ; - }⦉@27 + @29⦊{ + c = 400 + ; + }⦉@29 - if @28⦊!is_true⦉@28 @29⦊{ - a = 2; - }⦉@29@30⦊⦉@30 + if @31⦊!is_true⦉@31 @32,34⦊{ + a = 2; + }⦉@32,34@33⦊⦉@33 - if @31⦊is_true⦉@31 @32⦊{ - b = 30; - }⦉@32 else @33⦊{ - c = 400; - }⦉@33 -}@34⦊⦉@34
+ if @35⦊is_true⦉@35 @36,38⦊{ + b = 30; + }⦉@36,38 else @37⦊{ + c = 400; + }⦉@37 +}@39⦊⦉@39 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.loops_branches/loops_branches.{impl#0}-fmt.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.loops_branches/loops_branches.{impl#0}-fmt.-------.InstrumentCoverage.0.html index b3f344f7fc0b8..312d2ee7e8f0e 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.loops_branches/loops_branches.{impl#0}-fmt.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.loops_branches/loops_branches.{impl#0}-fmt.-------.InstrumentCoverage.0.html @@ -69,32 +69,35 @@ -
@0⦊fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - if true⦉@0 { - if @1⦊false⦉@1 { - while @4,5⦊true⦉@4,5 @6,8⦊{ - }⦉@6,8 - }@3⦊⦉@3 - @9,10,11,12⦊write!(f, "error")⦉@9,10,11,12@14,16,17,18⦊?⦉@14,16,17,18; +
@0⦊fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + if true⦉@0 { + if @1,3⦊false⦉@1,3 { + while @6,7⦊true⦉@6,7 @8,10⦊{ + }⦉@8,10 + }@5⦊⦉@5 + @11,12,13,14⦊write!(f, "error")⦉@11,12,13,14@16,18,19,20⦊?⦉@16,18,19,20; } else @2⦊{ }⦉@2 - @19⦊Ok(())⦉@19 - }@20⦊⦉@20
+ @21⦊Ok(())⦉@21 + }@22⦊⦉@22
diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.match_or_pattern/match_or_pattern.main.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.match_or_pattern/match_or_pattern.main.-------.InstrumentCoverage.0.html index c7992614b5b6f..133a85c83945e 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.match_or_pattern/match_or_pattern.main.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.match_or_pattern/match_or_pattern.main.-------.InstrumentCoverage.0.html @@ -69,9 +69,9 @@ -
@0,1,2,3⦊fn main() { -@0,1,2,3⦊fn main() { + // Initialize test constants in a way that cannot be determined at compile time, to ensure - // Initialize test constants in a way that cannot be determined at compile time, to ensure + // rustc and LLVM cannot optimize out statements (or coverage counters) downstream from - // rustc and LLVM cannot optimize out statements (or coverage counters) downstream from + // dependent conditions. - // dependent conditions. + let is_true = std::env::args().len() == 1; - let is_true = std::env::args().len() == 1; + - + let mut a: u8 = 0; - let mut a: u8 = 0; + let mut b: u8 = 0; - let mut b: u8 = 0; + if is_true⦉@0,1,2,3 @4⦊{ - a = 2; - b = 0; - }⦉@4@5⦊⦉@5 - match @6⦊(a, b)⦉@6 { +11:8-11:15: @3[11]: _8 = _1 +11:8-11:15: @3[12]: FakeRead(ForMatchedPlace, _8)"> if is_true⦉@0,1,2,3 @4,6⦊{ + a = 2; + b = 0; + }⦉@4,6@5⦊⦉@5 + match @7⦊(a, b)⦉@7 { // Or patterns generate MIR `SwitchInt` with multiple targets to the same `BasicBlock`. // This test confirms a fix for Issue #79569. - (0 | 1, 2 | 3) => @9,10⦊{}⦉@9,10 - _ => @7⦊{}⦉@7 + (0 | 1, 2 | 3) => @10,11⦊{}⦉@10,11 + _ => @8⦊{}⦉@8 } - if @11⦊is_true⦉@11 @12⦊{ - a = 0; - b = 0; - }⦉@12@13⦊⦉@13 - match @14⦊(a, b)⦉@14 { - (0 | 1, 2 | 3) => @17,18⦊{}⦉@17,18 - _ => @15⦊{}⦉@15 + if @12⦊is_true⦉@12 @13,15⦊{ + a = 0; + b = 0; + }⦉@13,15@14⦊⦉@14 + match @16⦊(a, b)⦉@16 { + (0 | 1, 2 | 3) => @19,20⦊{}⦉@19,20 + _ => @17⦊{}⦉@17 } - if @19⦊is_true⦉@19 @20⦊{ - a = 2; - b = 2; - }⦉@20@21⦊⦉@21 - match @22⦊(a, b)⦉@22 { - (0 | 1, 2 | 3) => @25,26⦊{}⦉@25,26 - _ => @23⦊{}⦉@23 + if @21⦊is_true⦉@21 @22,24⦊{ + a = 2; + b = 2; + }⦉@22,24@23⦊⦉@23 + match @25⦊(a, b)⦉@25 { + (0 | 1, 2 | 3) => @28,29⦊{}⦉@28,29 + _ => @26⦊{}⦉@26 } - if @27⦊is_true⦉@27 @28⦊{ - a = 0; - b = 2; - }⦉@28@29⦊⦉@29 - match @30⦊(a, b)⦉@30 { - (0 | 1, 2 | 3) => @33,34⦊{}⦉@33,34 - _ => @31⦊{}⦉@31 + if @30⦊is_true⦉@30 @31,33⦊{ + a = 0; + b = 2; + }⦉@31,33@32⦊⦉@32 + match @34⦊(a, b)⦉@34 { + (0 | 1, 2 | 3) => @37,38⦊{}⦉@37,38 + _ => @35⦊{}⦉@35 } -}@35⦊⦉@35
+}@39⦊⦉@39 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.nested_loops/nested_loops.main.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.nested_loops/nested_loops.main.-------.InstrumentCoverage.0.html index 4dcf6c741dc73..cb60276aa1228 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.nested_loops/nested_loops.main.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.nested_loops/nested_loops.main.-------.InstrumentCoverage.0.html @@ -69,23 +69,23 @@ -
@0,1,2,3⦊fn main() { - let is_true = std::env::args().len() == 1; -@14,16⦊_⦉@14,16 in @10,11,12⦊0..50⦉@10,11,12 { if @14,16⦊a < 30⦉@14,16 { - @17⦊break⦉@17; +9:16-9:22: @16[16]: _26 = Lt(move _27, const 30_i32) +9:16-9:22: @16[18]: FakeRead(ForMatchedPlace, _26)">@14,16⦊a < 30⦉@14,16 { + @17,19⦊break⦉@17,19; }@18,19,20⦊ +12:13-12:19: @20[0]: _9 = move (_29.0: i32) +13:13-13:19: @20[1]: _30 = CheckedSub(_10, const 5_i32) +13:13-13:19: @21[0]: _10 = move (_30.0: i32) +14:16-14:17: @21[3]: _32 = _10 +14:16-14:22: @21[4]: _31 = Lt(move _32, const 90_i32) +14:16-14:22: @21[6]: FakeRead(ForMatchedPlace, _31)">@18,20,21⦊ a -= 5; +12:13-12:19: @20[0]: _9 = move (_29.0: i32) +13:13-13:19: @20[1]: _30 = CheckedSub(_10, const 5_i32) +13:13-13:19: @21[0]: _10 = move (_30.0: i32) +14:16-14:17: @21[3]: _32 = _10 +14:16-14:22: @21[4]: _31 = Lt(move _32, const 90_i32) +14:16-14:22: @21[6]: FakeRead(ForMatchedPlace, _31)"> a -= 5; b -= 5; +12:13-12:19: @20[0]: _9 = move (_29.0: i32) +13:13-13:19: @20[1]: _30 = CheckedSub(_10, const 5_i32) +13:13-13:19: @21[0]: _10 = move (_30.0: i32) +14:16-14:17: @21[3]: _32 = _10 +14:16-14:22: @21[4]: _31 = Lt(move _32, const 90_i32) +14:16-14:22: @21[6]: FakeRead(ForMatchedPlace, _31)"> b -= 5; if b < 90⦉@18,19,20 { - @21,23⦊a -= 10; - if is_true⦉@21,23 { - @24⦊break 'outer⦉@24; - } else @25,26⦊{ - a -= 2; - }⦉@25,26 - }@22⦊⦉@22 +12:13-12:19: @20[0]: _9 = move (_29.0: i32) +13:13-13:19: @20[1]: _30 = CheckedSub(_10, const 5_i32) +13:13-13:19: @21[0]: _10 = move (_30.0: i32) +14:16-14:17: @21[3]: _32 = _10 +14:16-14:22: @21[4]: _31 = Lt(move _32, const 90_i32) +14:16-14:22: @21[6]: FakeRead(ForMatchedPlace, _31)"> if b < 90⦉@18,20,21 { + @22,24,25⦊a -= 10; + if is_true⦉@22,24,25 { + @26,28⦊break 'outer⦉@26,28; + } else @27,29⦊{ + a -= 2; + }⦉@27,29 + }@23⦊⦉@23 } - @28,29⦊countdown -= 1⦉@28,29; + @31,32⦊countdown -= 1⦉@31,32; } -}@30⦊⦉@30
+}@33⦊⦉@33 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.overflow/overflow.main.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.overflow/overflow.main.-------.InstrumentCoverage.0.html index ca3515689d337..6739634f65b30 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.overflow/overflow.main.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.overflow/overflow.main.-------.InstrumentCoverage.0.html @@ -77,176 +77,178 @@ 17:11-17:24: @2[3]: _4 = Gt(move _5, const 0_i32) 17:11-17:24: @2[5]: FakeRead(ForMatchedPlace, _4)">@1,2⦊countdown > 0⦉@1,2 { if @3,5⦊countdown == 1⦉@3,5 @6,8,9,10,11⦊{ - let result = might_overflow(10); - println!("Result: {}", result); - }⦉@6,8,9,10,11 else if @7⦊countdown < 5⦉@7 @12,14,15,16,17⦊{ - let result = might_overflow(1); - println!("Result: {}", result); - }⦉@12,14,15,16,17@13⦊⦉@13 - @19,20⦊countdown -= 1⦉@19,20; +18:12-18:26: @5[4]: _7 = Eq(move _8, const 1_i32) +18:12-18:26: @5[6]: FakeRead(ForMatchedPlace, _7)">@3,5⦊countdown == 1⦉@3,5 @6,8,9,10,11,12⦊{ + let result = might_overflow(10); + println!("Result: {}", result); + }⦉@6,8,9,10,11,12 else if @7⦊countdown < 5⦉@7 @13,15,16,17,18,19⦊{ + let result = might_overflow(1); + println!("Result: {}", result); + }⦉@13,15,16,17,18,19@14⦊⦉@14 + @21,22⦊countdown -= 1⦉@21,22; } @0⦊fn might_overflow(to_add: u32) -> u32 { +5:8-5:18: @0[4]: _3 = Gt(move _4, const 5_u32) +5:8-5:18: @0[6]: FakeRead(ForMatchedPlace, _3)">@0⦊fn might_overflow(to_add: u32) -> u32 { if to_add > 5⦉@0 @1,3,4⦊{ - println!("this will probably overflow"); - }⦉@1,3,4@2⦊⦉@2 - let @5,6,7,8,9,10,11,12,13⦊add_to = u32::MAX - 5; - println!("does {} + {} overflow?", add_to, to_add); - let result = to_add + add_to; - println!("continuing after overflow check"); - result -}⦉@5,6,7,8,9,10,11,12,13 +5:8-5:18: @0[4]: _3 = Gt(move _4, const 5_u32) +5:8-5:18: @0[6]: FakeRead(ForMatchedPlace, _3)"> if to_add > 5⦉@0 @1,3,4,5⦊{ + println!("this will probably overflow"); + }⦉@1,3,4,5@2⦊⦉@2 + let @6,7,8,9,10,11,12,13,14⦊add_to = u32::MAX - 5; + println!("does {} + {} overflow?", add_to, to_add); + let result = to_add + add_to; + println!("continuing after overflow check"); + result +}⦉@6,7,8,9,10,11,12,13,14 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.panic_unwind/panic_unwind.main.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.panic_unwind/panic_unwind.main.-------.InstrumentCoverage.0.html index 5b097f118e3a8..bd6aac4103eb6 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.panic_unwind/panic_unwind.main.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.panic_unwind/panic_unwind.main.-------.InstrumentCoverage.0.html @@ -77,20 +77,22 @@ 15:11-15:24: @2[3]: _4 = Gt(move _5, const 0_i32) 15:11-15:24: @2[5]: FakeRead(ForMatchedPlace, _4)">@1,2⦊countdown > 0⦉@1,2 { if @3,5⦊countdown == 1⦉@3,5 @6,8⦊{ - might_panic(true); - }⦉@6,8 else if @7⦊countdown < 5⦉@7 @9,11⦊{ - might_panic(false); - }⦉@9,11@10⦊⦉@10 - @13,14⦊countdown -= 1⦉@13,14; +16:12-16:26: @5[4]: _7 = Eq(move _8, const 1_i32) +16:12-16:26: @5[6]: FakeRead(ForMatchedPlace, _7)">@3,5⦊countdown == 1⦉@3,5 @6,8,9⦊{ + might_panic(true); + }⦉@6,8,9 else if @7⦊countdown < 5⦉@7 @10,12,13⦊{ + might_panic(false); + }⦉@10,12,13@11⦊⦉@11 + @15,16⦊countdown -= 1⦉@15,16; } @0⦊fn might_panic(should_panic: bool) ⦉@0{ - if @0⦊should_panic⦉@0 { - @1,3,4⦊println!("panicking..."); - panic!("panics");⦉@1,3,4 + if @0⦊should_panic⦉@0 { + @1,3,4,5⦊println!("panicking..."); + panic!("panics");⦉@1,3,4,5 } else @2,5,6⦊{ +9:9-9:33: @2.Call: _20 = Arguments::new_v1(move _21, move _25) -> [return: bb6, unwind: bb8] +9:9-9:33: @6.Call: _19 = _print(move _20) -> [return: bb7, unwind: bb8] +9:9-9:33: @7[5]: _18 = const () +8:12-10:6: @7[7]: _0 = const () +11:2-11:2: @7.Return: return">@2,6,7⦊{ println!("Don't Panic"); +9:9-9:33: @2.Call: _20 = Arguments::new_v1(move _21, move _25) -> [return: bb6, unwind: bb8] +9:9-9:33: @6.Call: _19 = _print(move _20) -> [return: bb7, unwind: bb8] +9:9-9:33: @7[5]: _18 = const () +8:12-10:6: @7[7]: _0 = const () +11:2-11:2: @7.Return: return"> println!("Don't Panic"); } +9:9-9:33: @2.Call: _20 = Arguments::new_v1(move _21, move _25) -> [return: bb6, unwind: bb8] +9:9-9:33: @6.Call: _19 = _print(move _20) -> [return: bb7, unwind: bb8] +9:9-9:33: @7[5]: _18 = const () +8:12-10:6: @7[7]: _0 = const () +11:2-11:2: @7.Return: return"> } }⦉@2,5,6 +9:9-9:33: @2.Call: _20 = Arguments::new_v1(move _21, move _25) -> [return: bb6, unwind: bb8] +9:9-9:33: @6.Call: _19 = _print(move _20) -> [return: bb7, unwind: bb8] +9:9-9:33: @7[5]: _18 = const () +8:12-10:6: @7[7]: _0 = const () +11:2-11:2: @7.Return: return">}⦉@2,6,7 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.simple_loop/simple_loop.main.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.simple_loop/simple_loop.main.-------.InstrumentCoverage.0.html index f528b698d440f..1233dfb5bab1f 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.simple_loop/simple_loop.main.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.simple_loop/simple_loop.main.-------.InstrumentCoverage.0.html @@ -69,125 +69,138 @@ -
@0,1,2,3⦊fn main() { -@0,1,2,3⦊fn main() { + // Initialize test constants in a way that cannot be determined at compile time, to ensure - // Initialize test constants in a way that cannot be determined at compile time, to ensure + // rustc and LLVM cannot optimize out statements (or coverage counters) downstream from - // rustc and LLVM cannot optimize out statements (or coverage counters) downstream from + // dependent conditions. - // dependent conditions. + let is_true = std::env::args().len() == 1; - let is_true = std::env::args().len() == 1; + - + let mut countdown = 0; - let mut countdown = 0; + - + if - if + is_true⦉@0,1,2,3 - @4⦊{ - countdown - = - 10 - ; - }⦉@4@5⦊⦉@5 +12:9-12:16: @3[6]: _7 = _1 +12:9-12:16: @3[7]: FakeRead(ForMatchedPlace, _7)"> is_true⦉@0,1,2,3 + @4,6⦊{ + countdown + = + 10 + ; + }⦉@4,6@5⦊⦉@5 loop { if - @7,8⦊countdown - == - 0⦉@7,8 + @8,9⦊countdown + == + 0⦉@8,9 { - @9⦊break⦉@9 + @10,12⦊break⦉@10,12 ; - }@10,11⦊ - countdown - -= - 1⦉@10,11 + }@11,13⦊ + countdown + -= + 1⦉@11,13 ; } -}@9⦊⦉@9
+}@10,12⦊⦉@10,12 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.simple_match/simple_match.main.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.simple_match/simple_match.main.-------.InstrumentCoverage.0.html index 8e49e45b86e11..a8bae32490b0b 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.simple_match/simple_match.main.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.simple_match/simple_match.main.-------.InstrumentCoverage.0.html @@ -69,154 +69,162 @@ -
@0,1,2,3⦊fn main() { -@0,1,2,3⦊fn main() { + // Initialize test constants in a way that cannot be determined at compile time, to ensure - // Initialize test constants in a way that cannot be determined at compile time, to ensure + // rustc and LLVM cannot optimize out statements (or coverage counters) downstream from - // rustc and LLVM cannot optimize out statements (or coverage counters) downstream from + // dependent conditions. - // dependent conditions. + let is_true = std::env::args().len() == 1; - let is_true = std::env::args().len() == 1; + - + let mut countdown = 1; - let mut countdown = 1; + if is_true⦉@0,1,2,3 @4⦊{ - countdown = 0; - }⦉@4@5⦊⦉@5 +10:8-10:15: @3[6]: _7 = _1 +10:8-10:15: @3[7]: FakeRead(ForMatchedPlace, _7)"> if is_true⦉@0,1,2,3 @4,6⦊{ + countdown = 0; + }⦉@4,6@5⦊⦉@5 for - @12,14,16⦊_⦉@12,14,16 + @13,15,17⦊_⦉@13,15,17 in - @8,9,10⦊0..2⦉@8,9,10 + @9,10,11⦊0..2⦉@9,10,11 { let z ; match - @12,14,16⦊countdown⦉@12,14,16 + @13,15,17⦊countdown⦉@13,15,17 { - @17⦊x⦉@17 + @18⦊x⦉@18 if - @12,14,16⦊x - < - 1⦉@12,14,16 + @13,15,17⦊x + < + 1⦉@13,15,17 => - @17⦊{ - z = countdown - ; - let y = countdown - ; - countdown = 10 - ; - }⦉@17 + @18⦊{ + z = countdown + ; + let y = countdown + ; + countdown = 10 + ; + }⦉@18 _ => - @15⦊{}⦉@15 + @16⦊{}⦉@16 } } -}@11⦊⦉@11
+}@12⦊⦉@12 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.tight_inf_loop/tight_inf_loop.main.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.tight_inf_loop/tight_inf_loop.main.-------.InstrumentCoverage.0.html index 8cbd265c6a01c..d0ee798ca1978 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.tight_inf_loop/tight_inf_loop.main.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.tight_inf_loop/tight_inf_loop.main.-------.InstrumentCoverage.0.html @@ -69,10 +69,12 @@ -
@0⦊fn main() { - if false⦉@0 { - @3,4⦊loop {}⦉@3,4 +
@0⦊fn main() { + if false⦉@0 { + @4,5⦊loop {}⦉@4,5 }@2⦊ @0⦊fn call(return_error: bool) -> Result<(),()> { - if return_error⦉@0 { - @1⦊Err(())⦉@1 +
@0⦊fn call(return_error: bool) -> Result<(),()> { + if return_error⦉@0 { + @1,3⦊Err(())⦉@1,3 } else { @2⦊Ok(())⦉@2 } -}@3⦊⦉@3
+}@4⦊⦉@4
diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.try_error_result/try_error_result.main.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.try_error_result/try_error_result.main.-------.InstrumentCoverage.0.html index 41404759c3da7..3091eab3e7149 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.try_error_result/try_error_result.main.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.try_error_result/try_error_result.main.-------.InstrumentCoverage.0.html @@ -84,46 +84,51 @@ in @2,3,4⦊0..10⦉@2,3,4 { @6,8,9⦊countdown +25:13-25:26: @9[4]: _18 = Lt(move _19, const 5_i32) +25:13-25:26: @9[6]: FakeRead(ForMatchedPlace, _18)">@6,8,9⦊countdown -= 1 +25:13-25:26: @9[4]: _18 = Lt(move _19, const 5_i32) +25:13-25:26: @9[6]: FakeRead(ForMatchedPlace, _18)"> -= 1 ; +25:13-25:26: @9[4]: _18 = Lt(move _19, const 5_i32) +25:13-25:26: @9[6]: FakeRead(ForMatchedPlace, _18)"> ; if +25:13-25:26: @9[4]: _18 = Lt(move _19, const 5_i32) +25:13-25:26: @9[6]: FakeRead(ForMatchedPlace, _18)"> if countdown < 5⦉@6,8,9 +25:13-25:26: @9[4]: _18 = Lt(move _19, const 5_i32) +25:13-25:26: @9[6]: FakeRead(ForMatchedPlace, _18)"> countdown < 5⦉@6,8,9 { - @10,12,13⦊call(/*return_error=*/ true)⦉@10,12,13@15,17,18,19⦊?⦉@15,17,18,19; - @14,20,21⦊call(/*return_error=*/ false)⦉@14,20,21@23,25,26,27⦊?⦉@23,25,26,27; + @10,12,13,14⦊call(/*return_error=*/ true)⦉@10,12,13,14@16,18,19,20⦊?⦉@16,18,19,20; + @15,21,22⦊call(/*return_error=*/ false)⦉@15,21,22@24,26,27,28⦊?⦉@24,26,27,28; } else { - @11,28,29⦊call(/*return_error=*/ false)⦉@11,28,29@31,33,34,35⦊?⦉@31,33,34,35; + @11,29,30⦊call(/*return_error=*/ false)⦉@11,29,30@32,34,35,36⦊?⦉@32,34,35,36; } } @5⦊Ok(())⦉@5 -}@38⦊⦉@38
+}@39⦊⦉@39 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.used_crate/used_crate.unused_function.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.used_crate/used_crate.unused_function.-------.InstrumentCoverage.0.html index 4af7b17986622..47fe96eebd19f 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.used_crate/used_crate.unused_function.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.used_crate/used_crate.unused_function.-------.InstrumentCoverage.0.html @@ -69,47 +69,51 @@ -
@0,1,2,3⦊pub fn unused_function() { -@0,1,2,3⦊pub fn unused_function() { + let is_true = std::env::args().len() == 1; - let is_true = std::env::args().len() == 1; + let mut countdown = 2; - let mut countdown = 2; + if !is_true⦉@0,1,2,3 @4⦊{ - countdown = 20; - }⦉@4@5⦊⦉@5 -}@6⦊⦉@6
+40:8-40:16: @3[7]: _6 = Not(move _7) +40:8-40:16: @3[9]: FakeRead(ForMatchedPlace, _6)"> if !is_true⦉@0,1,2,3 @4,6⦊{ + countdown = 20; + }⦉@4,6@5⦊⦉@5 +}@7⦊⦉@7 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.used_crate/used_crate.unused_private_function.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.used_crate/used_crate.unused_private_function.-------.InstrumentCoverage.0.html index 6424e03fc7113..361c57930229a 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.used_crate/used_crate.unused_private_function.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.used_crate/used_crate.unused_private_function.-------.InstrumentCoverage.0.html @@ -69,47 +69,51 @@ -
@0,1,2,3⦊fn unused_private_function() { -@0,1,2,3⦊fn unused_private_function() { + let is_true = std::env::args().len() == 1; - let is_true = std::env::args().len() == 1; + let mut countdown = 2; - let mut countdown = 2; + if !is_true⦉@0,1,2,3 @4⦊{ - countdown = 20; - }⦉@4@5⦊⦉@5 -}@6⦊⦉@6
+48:8-48:16: @3[7]: _6 = Not(move _7) +48:8-48:16: @3[9]: FakeRead(ForMatchedPlace, _6)"> if !is_true⦉@0,1,2,3 @4,6⦊{ + countdown = 20; + }⦉@4,6@5⦊⦉@5 +}@7⦊⦉@7 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.used_crate/used_crate.used_function.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.used_crate/used_crate.used_function.-------.InstrumentCoverage.0.html index d35f191b64e85..2ffd9bfb82386 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.used_crate/used_crate.used_function.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.used_crate/used_crate.used_function.-------.InstrumentCoverage.0.html @@ -73,38 +73,41 @@ // Initialize test constants in a way that cannot be determined at compile time, to ensure // rustc and LLVM cannot optimize out statements (or coverage counters) downstream from // dependent conditions. - let let @0,1,2,3⦊is_true = std::env::args().len() == 1; -@0,1,2,3⦊is_true = std::env::args().len() == 1; + let mut countdown = 0; - let mut countdown = 0; + if is_true⦉@0,1,2,3 @4⦊{ - countdown = 10; - }⦉@4@5⦊⦉@5 - @6,7⦊use_this_lib_crate(); -}⦉@6,7 +11:8-11:15: @3[6]: _7 = _1 +11:8-11:15: @3[7]: FakeRead(ForMatchedPlace, _7)"> if is_true⦉@0,1,2,3 @4,6⦊{ + countdown = 10; + }⦉@4,6@5⦊⦉@5 + @7,8⦊use_this_lib_crate(); +}⦉@7,8 diff --git a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.while_early_ret/while_early_ret.main.-------.InstrumentCoverage.0.html b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.while_early_ret/while_early_ret.main.-------.InstrumentCoverage.0.html index fcb5418e1d0cf..4cab153e77f53 100644 --- a/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.while_early_ret/while_early_ret.main.-------.InstrumentCoverage.0.html +++ b/src/test/run-make-fulldeps/coverage-spanview/expected_mir_dump.while_early_ret/while_early_ret.main.-------.InstrumentCoverage.0.html @@ -86,45 +86,51 @@ { if @3,5⦊countdown +12:13-14:14: @5[4]: _7 = Lt(move _8, const 5_i32) +12:13-14:14: @5[6]: FakeRead(ForMatchedPlace, _7)">@3,5⦊countdown < +12:13-14:14: @5[4]: _7 = Lt(move _8, const 5_i32) +12:13-14:14: @5[6]: FakeRead(ForMatchedPlace, _7)"> < 5⦉@3,5 +12:13-14:14: @5[4]: _7 = Lt(move _8, const 5_i32) +12:13-14:14: @5[6]: FakeRead(ForMatchedPlace, _7)"> 5⦉@3,5 { return if - @6⦊countdown - > - 8⦉@6 + @6,8⦊countdown + > + 8⦉@6,8 { - @8⦊Ok(())⦉@8 + @9,11⦊Ok(())⦉@9,11 } else { - @9⦊Err(1)⦉@9 + @10⦊Err(1)⦉@10 } ; }@7,11⦊ +30:9-32:10: @12[0]: _1 = move (_13.0: i32)">@7,12⦊ countdown +30:9-32:10: @12[0]: _1 = move (_13.0: i32)"> countdown -= +30:9-32:10: @12[0]: _1 = move (_13.0: i32)"> -= 1⦉@7,11 +30:9-32:10: @12[0]: _1 = move (_13.0: i32)"> 1⦉@7,12 ; } @4⦊Ok(())⦉@4 -}@12⦊⦉@12 +}@14⦊⦉@14 diff --git a/src/test/run-make-fulldeps/cross-lang-lto-upstream-rlibs/staticlib.rs b/src/test/run-make-fulldeps/cross-lang-lto-upstream-rlibs/staticlib.rs index 34951dda3b6ec..b24522e7f0efa 100644 --- a/src/test/run-make-fulldeps/cross-lang-lto-upstream-rlibs/staticlib.rs +++ b/src/test/run-make-fulldeps/cross-lang-lto-upstream-rlibs/staticlib.rs @@ -3,6 +3,6 @@ extern crate upstream; #[no_mangle] -pub extern "C" fn bar() { +pub extern fn bar() { upstream::foo(); } diff --git a/src/test/run-make-fulldeps/extern-fn-generic/test.rs b/src/test/run-make-fulldeps/extern-fn-generic/test.rs index c9baa489881b1..0666bf4262de4 100644 --- a/src/test/run-make-fulldeps/extern-fn-generic/test.rs +++ b/src/test/run-make-fulldeps/extern-fn-generic/test.rs @@ -1,20 +1,22 @@ extern crate testcrate; -extern "C" fn bar(ts: testcrate::TestStruct) -> T { - ts.y -} +extern "C" fn bar(ts: testcrate::TestStruct) -> T { ts.y } #[link(name = "test", kind = "static")] -extern "C" { +extern { fn call(c: extern "C" fn(testcrate::TestStruct) -> i32) -> i32; } fn main() { // Let's test calling it cross crate - let back = unsafe { testcrate::call(testcrate::foo::) }; + let back = unsafe { + testcrate::call(testcrate::foo::) + }; assert_eq!(3, back); // And just within this crate - let back = unsafe { call(bar::) }; + let back = unsafe { + call(bar::) + }; assert_eq!(3, back); } diff --git a/src/test/run-make-fulldeps/extern-fn-generic/testcrate.rs b/src/test/run-make-fulldeps/extern-fn-generic/testcrate.rs index 39f76e59ca0c0..f0a721d35e29a 100644 --- a/src/test/run-make-fulldeps/extern-fn-generic/testcrate.rs +++ b/src/test/run-make-fulldeps/extern-fn-generic/testcrate.rs @@ -3,14 +3,12 @@ #[repr(C)] pub struct TestStruct { pub x: u8, - pub y: T, + pub y: T } -pub extern "C" fn foo(ts: TestStruct) -> T { - ts.y -} +pub extern "C" fn foo(ts: TestStruct) -> T { ts.y } #[link(name = "test", kind = "static")] -extern "C" { +extern { pub fn call(c: extern "C" fn(TestStruct) -> i32) -> i32; } diff --git a/src/test/run-make-fulldeps/extern-fn-mangle/test.rs b/src/test/run-make-fulldeps/extern-fn-mangle/test.rs index 40b08f1ed709e..b213534c95812 100644 --- a/src/test/run-make-fulldeps/extern-fn-mangle/test.rs +++ b/src/test/run-make-fulldeps/extern-fn-mangle/test.rs @@ -1,15 +1,11 @@ #[no_mangle] -pub extern "C" fn foo() -> i32 { - 3 -} +pub extern "C" fn foo() -> i32 { 3 } #[no_mangle] -pub extern "C" fn bar() -> i32 { - 5 -} +pub extern "C" fn bar() -> i32 { 5 } #[link(name = "test", kind = "static")] -extern "C" { +extern { fn add() -> i32; } diff --git a/src/test/run-make-fulldeps/extern-fn-struct-passing-abi/test.rs b/src/test/run-make-fulldeps/extern-fn-struct-passing-abi/test.rs index afe0f52ef0b28..615163d9ad25b 100644 --- a/src/test/run-make-fulldeps/extern-fn-struct-passing-abi/test.rs +++ b/src/test/run-make-fulldeps/extern-fn-struct-passing-abi/test.rs @@ -7,7 +7,7 @@ struct Rect { a: i32, b: i32, c: i32, - d: i32, + d: i32 } #[derive(Clone, Copy, Debug, PartialEq)] @@ -15,7 +15,7 @@ struct Rect { struct BiggerRect { s: Rect, a: i32, - b: i32, + b: i32 } #[derive(Clone, Copy, Debug, PartialEq)] @@ -23,7 +23,7 @@ struct BiggerRect { struct FloatRect { a: i32, b: i32, - c: f64, + c: f64 } #[derive(Clone, Copy, Debug, PartialEq)] @@ -33,14 +33,14 @@ struct Huge { b: i32, c: i32, d: i32, - e: i32, + e: i32 } #[derive(Clone, Copy, Debug, PartialEq)] #[repr(C)] struct FloatPoint { x: f64, - y: f64, + y: f64 } #[derive(Clone, Copy, Debug, PartialEq)] @@ -58,22 +58,13 @@ struct IntOdd { } #[link(name = "test", kind = "static")] -extern "C" { +extern { fn byval_rect(a: i32, b: i32, c: i32, d: i32, e: i32, s: Rect); fn byval_many_rect(a: i32, b: i32, c: i32, d: i32, e: i32, f: i32, s: Rect); - fn byval_rect_floats( - a: f32, - b: f32, - c: f64, - d: f32, - e: f32, - f: f32, - g: f64, - s: Rect, - t: FloatRect, - ); + fn byval_rect_floats(a: f32, b: f32, c: f64, d: f32, e: f32, + f: f32, g: f64, s: Rect, t: FloatRect); fn byval_rect_with_float(a: i32, b: i32, c: f32, d: i32, e: i32, f: i32, s: Rect); @@ -116,7 +107,12 @@ fn main() { byval_many_rect(1, 2, 3, 4, 5, 6, s); byval_rect_floats(1., 2., 3., 4., 5., 6., 7., s, u); byval_rect_with_float(1, 2, 3.0, 4, 5, 6, s); - byval_rect_with_many_huge(v, v, v, v, v, v, Rect { a: 123, b: 456, c: 789, d: 420 }); + byval_rect_with_many_huge(v, v, v, v, v, v, Rect { + a: 123, + b: 456, + c: 789, + d: 420 + }); split_rect(1, 2, s); split_rect_floats(1., 2., u); split_rect_with_floats(1, 2, 3.0, 4, 5.0, 6, s); diff --git a/src/test/run-make-fulldeps/extern-fn-with-extern-types/test.rs b/src/test/run-make-fulldeps/extern-fn-with-extern-types/test.rs index 90a6ebaf1aa6c..6c027cc8f57f1 100644 --- a/src/test/run-make-fulldeps/extern-fn-with-extern-types/test.rs +++ b/src/test/run-make-fulldeps/extern-fn-with-extern-types/test.rs @@ -1,7 +1,7 @@ #![feature(extern_types)] #[link(name = "ctest", kind = "static")] -extern "C" { +extern { type data; fn data_create(magic: u32) -> *mut data; diff --git a/src/test/run-make-fulldeps/extern-fn-with-packed-struct/test.rs b/src/test/run-make-fulldeps/extern-fn-with-packed-struct/test.rs index 2f261efb5105d..7d7658ceeb3bf 100644 --- a/src/test/run-make-fulldeps/extern-fn-with-packed-struct/test.rs +++ b/src/test/run-make-fulldeps/extern-fn-with-packed-struct/test.rs @@ -3,11 +3,11 @@ struct Foo { a: i8, b: i16, - c: i8, + c: i8 } #[link(name = "test", kind = "static")] -extern "C" { +extern { fn foo(f: Foo) -> Foo; } diff --git a/src/test/run-make-fulldeps/extern-fn-with-union/test.rs b/src/test/run-make-fulldeps/extern-fn-with-union/test.rs index 438fbddf31fb2..007dfdb5e1030 100644 --- a/src/test/run-make-fulldeps/extern-fn-with-union/test.rs +++ b/src/test/run-make-fulldeps/extern-fn-with-union/test.rs @@ -2,7 +2,7 @@ extern crate testcrate; use std::mem; -extern "C" { +extern { fn give_back(tu: testcrate::TestUnion) -> u64; } @@ -10,10 +10,14 @@ fn main() { let magic: u64 = 0xDEADBEEF; // Let's test calling it cross crate - let back = unsafe { testcrate::give_back(mem::transmute(magic)) }; + let back = unsafe { + testcrate::give_back(mem::transmute(magic)) + }; assert_eq!(magic, back); // And just within this crate - let back = unsafe { give_back(mem::transmute(magic)) }; + let back = unsafe { + give_back(mem::transmute(magic)) + }; assert_eq!(magic, back); } diff --git a/src/test/run-make-fulldeps/extern-fn-with-union/testcrate.rs b/src/test/run-make-fulldeps/extern-fn-with-union/testcrate.rs index 28d91ff37c360..b51526dfcee15 100644 --- a/src/test/run-make-fulldeps/extern-fn-with-union/testcrate.rs +++ b/src/test/run-make-fulldeps/extern-fn-with-union/testcrate.rs @@ -2,10 +2,10 @@ #[repr(C)] pub struct TestUnion { - _val: u64, + _val: u64 } #[link(name = "ctest", kind = "static")] -extern "C" { +extern { pub fn give_back(tu: TestUnion) -> u64; } diff --git a/src/test/run-make-fulldeps/glibc-staticlib-args/library.rs b/src/test/run-make-fulldeps/glibc-staticlib-args/library.rs index 5ab627a2ac1a2..991981dc09666 100644 --- a/src/test/run-make-fulldeps/glibc-staticlib-args/library.rs +++ b/src/test/run-make-fulldeps/glibc-staticlib-args/library.rs @@ -1,4 +1,4 @@ #[no_mangle] -pub extern "C" fn args_check() { +pub extern fn args_check() { assert_ne!(std::env::args_os().count(), 0); } diff --git a/src/test/run-make-fulldeps/inline-always-many-cgu/Makefile b/src/test/run-make-fulldeps/inline-always-many-cgu/Makefile index 0cab955f6442b..d12a23fbbf013 100644 --- a/src/test/run-make-fulldeps/inline-always-many-cgu/Makefile +++ b/src/test/run-make-fulldeps/inline-always-many-cgu/Makefile @@ -1,7 +1,12 @@ -include ../tools.mk all: - $(RUSTC) foo.rs --emit llvm-ir -C codegen-units=2 + $(RUSTC) foo.rs --emit llvm-ir -C codegen-units=2 -C opt-level=0 + if ![cat $(TMPDIR)/*.ll | $(CGREP) -e '\bcall\b']; then \ + echo "not found call instruction when one was expected"; \ + exit 1; \ + fi + $(RUSTC) foo.rs --emit llvm-ir -C codegen-units=2 -C opt-level=1 if cat $(TMPDIR)/*.ll | $(CGREP) -e '\bcall\b'; then \ echo "found call instruction when one wasn't expected"; \ exit 1; \ diff --git a/src/test/run-make-fulldeps/interdependent-c-libraries/bar.rs b/src/test/run-make-fulldeps/interdependent-c-libraries/bar.rs index 3c2c3f2181494..2794be53ce4dd 100644 --- a/src/test/run-make-fulldeps/interdependent-c-libraries/bar.rs +++ b/src/test/run-make-fulldeps/interdependent-c-libraries/bar.rs @@ -3,12 +3,10 @@ extern crate foo; #[link(name = "bar", kind = "static")] -extern "C" { +extern { fn bar(); } pub fn doit() { - unsafe { - bar(); - } + unsafe { bar(); } } diff --git a/src/test/run-make-fulldeps/interdependent-c-libraries/foo.rs b/src/test/run-make-fulldeps/interdependent-c-libraries/foo.rs index a69809726c693..891c47d61de97 100644 --- a/src/test/run-make-fulldeps/interdependent-c-libraries/foo.rs +++ b/src/test/run-make-fulldeps/interdependent-c-libraries/foo.rs @@ -1,12 +1,10 @@ #![crate_type = "rlib"] #[link(name = "foo", kind = "static")] -extern "C" { +extern { fn foo(); } pub fn doit() { - unsafe { - foo(); - } + unsafe { foo(); } } diff --git a/src/test/run-make-fulldeps/issue-14500/foo.rs b/src/test/run-make-fulldeps/issue-14500/foo.rs index 7c19c1f2c678a..feebef1a6d079 100644 --- a/src/test/run-make-fulldeps/issue-14500/foo.rs +++ b/src/test/run-make-fulldeps/issue-14500/foo.rs @@ -1,5 +1,5 @@ #[no_mangle] -pub extern "C" fn foo() {} +pub extern fn foo() {} #[no_mangle] pub static FOO_STATIC: u8 = 0; diff --git a/src/test/run-make-fulldeps/issue-15460/foo.rs b/src/test/run-make-fulldeps/issue-15460/foo.rs index b4eaa0b31c5be..9beafd9ff3532 100644 --- a/src/test/run-make-fulldeps/issue-15460/foo.rs +++ b/src/test/run-make-fulldeps/issue-15460/foo.rs @@ -1,6 +1,6 @@ #![crate_type = "dylib"] #[link(name = "foo", kind = "static")] -extern "C" { +extern { pub fn foo(); } diff --git a/src/test/run-make-fulldeps/issue-25581/test.rs b/src/test/run-make-fulldeps/issue-25581/test.rs index ba6749c972224..5dfa6bb7b69fc 100644 --- a/src/test/run-make-fulldeps/issue-25581/test.rs +++ b/src/test/run-make-fulldeps/issue-25581/test.rs @@ -1,11 +1,11 @@ #[link(name = "test", kind = "static")] -extern "C" { +extern { fn slice_len(s: &[u8]) -> usize; fn slice_elem(s: &[u8], idx: usize) -> u8; } fn main() { - let data = [1, 2, 3, 4, 5]; + let data = [1,2,3,4,5]; unsafe { assert_eq!(data.len(), slice_len(&data) as usize); diff --git a/src/test/run-make-fulldeps/issue-28595/a.rs b/src/test/run-make-fulldeps/issue-28595/a.rs index 07863cf64d6e9..448364151868c 100644 --- a/src/test/run-make-fulldeps/issue-28595/a.rs +++ b/src/test/run-make-fulldeps/issue-28595/a.rs @@ -1,6 +1,6 @@ #![crate_type = "rlib"] #[link(name = "a", kind = "static")] -extern "C" { +extern { pub fn a(); } diff --git a/src/test/run-make-fulldeps/issue-28595/b.rs b/src/test/run-make-fulldeps/issue-28595/b.rs index 1f389859fad73..24ab412284dd3 100644 --- a/src/test/run-make-fulldeps/issue-28595/b.rs +++ b/src/test/run-make-fulldeps/issue-28595/b.rs @@ -1,12 +1,11 @@ extern crate a; #[link(name = "b", kind = "static")] -extern "C" { +extern { pub fn b(); } + fn main() { - unsafe { - b(); - } + unsafe { b(); } } diff --git a/src/test/run-make-fulldeps/link-cfg/dep-with-staticlib.rs b/src/test/run-make-fulldeps/link-cfg/dep-with-staticlib.rs index 5ad66475d003f..55c96df7b5891 100644 --- a/src/test/run-make-fulldeps/link-cfg/dep-with-staticlib.rs +++ b/src/test/run-make-fulldeps/link-cfg/dep-with-staticlib.rs @@ -3,6 +3,6 @@ #[link(name = "return1", cfg(foo))] #[link(name = "return3", kind = "static", cfg(bar))] -extern "C" { +extern { pub fn my_function() -> i32; } diff --git a/src/test/run-make-fulldeps/link-cfg/dep.rs b/src/test/run-make-fulldeps/link-cfg/dep.rs index 40de77f05b3f6..149ae61bf88df 100644 --- a/src/test/run-make-fulldeps/link-cfg/dep.rs +++ b/src/test/run-make-fulldeps/link-cfg/dep.rs @@ -3,6 +3,6 @@ #[link(name = "return1", cfg(foo))] #[link(name = "return2", cfg(bar))] -extern "C" { +extern { pub fn my_function() -> i32; } diff --git a/src/test/run-make-fulldeps/link-cfg/no-deps.rs b/src/test/run-make-fulldeps/link-cfg/no-deps.rs index ba5a8711a2610..6dba7fe218e2b 100644 --- a/src/test/run-make-fulldeps/link-cfg/no-deps.rs +++ b/src/test/run-make-fulldeps/link-cfg/no-deps.rs @@ -2,7 +2,7 @@ #[link(name = "return1", cfg(foo))] #[link(name = "return2", cfg(bar))] -extern "C" { +extern { fn my_function() -> i32; } diff --git a/src/test/run-make-fulldeps/link-path-order/main.rs b/src/test/run-make-fulldeps/link-path-order/main.rs index 8024e343d19a7..10f12823bd3eb 100644 --- a/src/test/run-make-fulldeps/link-path-order/main.rs +++ b/src/test/run-make-fulldeps/link-path-order/main.rs @@ -2,13 +2,15 @@ extern crate libc; -#[link(name = "foo", kind = "static")] -extern "C" { +#[link(name="foo", kind = "static")] +extern { fn should_return_one() -> libc::c_int; } fn main() { - let result = unsafe { should_return_one() }; + let result = unsafe { + should_return_one() + }; if result != 1 { std::process::exit(255); diff --git a/src/test/run-make-fulldeps/linkage-attr-on-static/bar.rs b/src/test/run-make-fulldeps/linkage-attr-on-static/bar.rs index 68607cbb65721..b827532e8890d 100644 --- a/src/test/run-make-fulldeps/linkage-attr-on-static/bar.rs +++ b/src/test/run-make-fulldeps/linkage-attr-on-static/bar.rs @@ -5,7 +5,7 @@ static BAZ: i32 = 21; #[link(name = "foo", kind = "static")] -extern "C" { +extern { fn what() -> i32; } diff --git a/src/test/run-make-fulldeps/long-linker-command-lines/foo.rs b/src/test/run-make-fulldeps/long-linker-command-lines/foo.rs index db238c0cf1a92..f313798de215b 100644 --- a/src/test/run-make-fulldeps/long-linker-command-lines/foo.rs +++ b/src/test/run-make-fulldeps/long-linker-command-lines/foo.rs @@ -25,7 +25,7 @@ fn write_test_case(file: &Path, n: usize) -> HashSet { writeln!(f, "#[link(name = \"S{}{}S\")]", prefix, i).unwrap(); libs.insert(format!("{}{}", prefix, i)); } - writeln!(f, "extern \"C\" {{}}\nfn main() {{}}").unwrap(); + writeln!(f, "extern {{}}\nfn main() {{}}").unwrap(); f.into_inner().unwrap(); libs diff --git a/src/test/run-make-fulldeps/longjmp-across-rust/main.rs b/src/test/run-make-fulldeps/longjmp-across-rust/main.rs index cc1d5b126dd35..5b43c1cc3b70a 100644 --- a/src/test/run-make-fulldeps/longjmp-across-rust/main.rs +++ b/src/test/run-make-fulldeps/longjmp-across-rust/main.rs @@ -1,6 +1,6 @@ #[link(name = "foo", kind = "static")] -extern "C" { - fn test_start(f: extern "C" fn()); +extern { + fn test_start(f: extern fn()); fn test_end(); } @@ -13,10 +13,11 @@ fn main() { struct A; impl Drop for A { - fn drop(&mut self) {} + fn drop(&mut self) { + } } -extern "C" fn test_middle() { +extern fn test_middle() { let _a = A; foo(); } diff --git a/src/test/run-make-fulldeps/lto-no-link-whole-rlib/lib1.rs b/src/test/run-make-fulldeps/lto-no-link-whole-rlib/lib1.rs index f70bb338223e0..4b43b86600c52 100644 --- a/src/test/run-make-fulldeps/lto-no-link-whole-rlib/lib1.rs +++ b/src/test/run-make-fulldeps/lto-no-link-whole-rlib/lib1.rs @@ -1,7 +1,7 @@ #![crate_type = "rlib"] #[link(name = "foo", kind = "static")] -extern "C" { +extern { fn foo() -> i32; } diff --git a/src/test/run-make-fulldeps/lto-no-link-whole-rlib/lib2.rs b/src/test/run-make-fulldeps/lto-no-link-whole-rlib/lib2.rs index 2dec2a2718e83..c9e1baa434b12 100644 --- a/src/test/run-make-fulldeps/lto-no-link-whole-rlib/lib2.rs +++ b/src/test/run-make-fulldeps/lto-no-link-whole-rlib/lib2.rs @@ -3,7 +3,7 @@ extern crate lib1; #[link(name = "bar", kind = "static")] -extern "C" { +extern { fn foo() -> i32; } diff --git a/src/test/run-make-fulldeps/manual-link/foo.rs b/src/test/run-make-fulldeps/manual-link/foo.rs index c1f28236ffd2b..f5cd598abc6b0 100644 --- a/src/test/run-make-fulldeps/manual-link/foo.rs +++ b/src/test/run-make-fulldeps/manual-link/foo.rs @@ -1,11 +1,9 @@ #![crate_type = "rlib"] -extern "C" { +extern { fn bar(); } pub fn foo() { - unsafe { - bar(); - } + unsafe { bar(); } } diff --git a/src/test/run-make-fulldeps/no-duplicate-libs/main.rs b/src/test/run-make-fulldeps/no-duplicate-libs/main.rs index b25ef35ada68e..298018ca7183a 100644 --- a/src/test/run-make-fulldeps/no-duplicate-libs/main.rs +++ b/src/test/run-make-fulldeps/no-duplicate-libs/main.rs @@ -1,7 +1,7 @@ #[link(name = "foo")] // linker should drop this library, no symbols used #[link(name = "bar")] // symbol comes from this library #[link(name = "foo")] // now linker picks up `foo` b/c `bar` library needs it -extern "C" { +extern { fn bar(); } diff --git a/src/test/run-make-fulldeps/sanitizer-cdylib-link/library.rs b/src/test/run-make-fulldeps/sanitizer-cdylib-link/library.rs index f2a52cb5ca1c5..bf11553ea6b17 100644 --- a/src/test/run-make-fulldeps/sanitizer-cdylib-link/library.rs +++ b/src/test/run-make-fulldeps/sanitizer-cdylib-link/library.rs @@ -1,5 +1,5 @@ #[no_mangle] -pub extern "C" fn overflow() { +pub extern fn overflow() { let xs = [0, 1, 2, 3]; let _y = unsafe { *xs.as_ptr().offset(4) }; } diff --git a/src/test/run-make-fulldeps/sanitizer-cdylib-link/program.rs b/src/test/run-make-fulldeps/sanitizer-cdylib-link/program.rs index ef053aa2e7a3a..3bbbcd9c6f8e6 100644 --- a/src/test/run-make-fulldeps/sanitizer-cdylib-link/program.rs +++ b/src/test/run-make-fulldeps/sanitizer-cdylib-link/program.rs @@ -1,4 +1,4 @@ -extern "C" { +extern { fn overflow(); } diff --git a/src/test/run-make-fulldeps/sanitizer-dylib-link/library.rs b/src/test/run-make-fulldeps/sanitizer-dylib-link/library.rs index f2a52cb5ca1c5..bf11553ea6b17 100644 --- a/src/test/run-make-fulldeps/sanitizer-dylib-link/library.rs +++ b/src/test/run-make-fulldeps/sanitizer-dylib-link/library.rs @@ -1,5 +1,5 @@ #[no_mangle] -pub extern "C" fn overflow() { +pub extern fn overflow() { let xs = [0, 1, 2, 3]; let _y = unsafe { *xs.as_ptr().offset(4) }; } diff --git a/src/test/run-make-fulldeps/sanitizer-dylib-link/program.rs b/src/test/run-make-fulldeps/sanitizer-dylib-link/program.rs index ef053aa2e7a3a..3bbbcd9c6f8e6 100644 --- a/src/test/run-make-fulldeps/sanitizer-dylib-link/program.rs +++ b/src/test/run-make-fulldeps/sanitizer-dylib-link/program.rs @@ -1,4 +1,4 @@ -extern "C" { +extern { fn overflow(); } diff --git a/src/test/run-make-fulldeps/sanitizer-staticlib-link/library.rs b/src/test/run-make-fulldeps/sanitizer-staticlib-link/library.rs index f2a52cb5ca1c5..bf11553ea6b17 100644 --- a/src/test/run-make-fulldeps/sanitizer-staticlib-link/library.rs +++ b/src/test/run-make-fulldeps/sanitizer-staticlib-link/library.rs @@ -1,5 +1,5 @@ #[no_mangle] -pub extern "C" fn overflow() { +pub extern fn overflow() { let xs = [0, 1, 2, 3]; let _y = unsafe { *xs.as_ptr().offset(4) }; } diff --git a/src/test/run-make-fulldeps/sanitizer-staticlib-link/program.rs b/src/test/run-make-fulldeps/sanitizer-staticlib-link/program.rs index ec59bdb11c889..21e1ade2cd52c 100644 --- a/src/test/run-make-fulldeps/sanitizer-staticlib-link/program.rs +++ b/src/test/run-make-fulldeps/sanitizer-staticlib-link/program.rs @@ -1,5 +1,5 @@ #[link(name = "library")] -extern "C" { +extern { fn overflow(); } diff --git a/src/test/run-make-fulldeps/save-analysis-fail/foo.rs b/src/test/run-make-fulldeps/save-analysis-fail/foo.rs index 94879c2a6ed66..5d504ced65e33 100644 --- a/src/test/run-make-fulldeps/save-analysis-fail/foo.rs +++ b/src/test/run-make-fulldeps/save-analysis-fail/foo.rs @@ -1,4 +1,4 @@ -#![crate_name = "test"] +#![ crate_name = "test" ] #![feature(box_syntax)] #![feature(rustc_private)] @@ -9,10 +9,11 @@ extern crate krate2; extern crate krate2 as krate3; use rustc_graphviz::RenderOption; +use std::collections::{HashMap,HashSet}; use std::cell::RefCell; -use std::collections::{HashMap, HashSet}; use std::io::Write; + use sub::sub2 as msalias; use sub::sub2; use sub::sub2::nested_struct as sub_struct; @@ -29,7 +30,7 @@ static bob: Option = None; // buglink test - see issue #1337. fn test_alias(i: Option<::Item>) { - let s = sub_struct { field2: 45u32 }; + let s = sub_struct{ field2: 45u32, }; // import tests fn foo(x: &Write) {} @@ -79,7 +80,7 @@ mod sub { pub enum nested_enum { Nest2 = 2, - Nest3 = 3, + Nest3 = 3 } } } @@ -100,9 +101,7 @@ struct some_fields { type SF = some_fields; trait SuperTrait { - fn qux(&self) { - panic!(); - } + fn qux(&self) { panic!(); } } trait SomeTrait: SuperTrait { @@ -137,7 +136,8 @@ impl SomeTrait for some_fields { } } -impl SuperTrait for some_fields {} +impl SuperTrait for some_fields { +} impl SubTrait for some_fields {} @@ -150,14 +150,17 @@ impl some_fields { 42 } - fn align_to(&mut self) {} + fn align_to(&mut self) { + + } fn test(&mut self) { self.align_to::(); } } -impl SuperTrait for nofields {} +impl SuperTrait for nofields { +} impl SomeTrait for nofields { fn Method(&self, x: u32) -> u32 { self.Method(x); @@ -183,70 +186,59 @@ enum SomeEnum<'a> { Ints(isize, isize), Floats(f64, f64), Strings(&'a str, &'a str, &'a str), - MyTypes(MyType, MyType), + MyTypes(MyType, MyType) } #[derive(Copy, Clone)] enum SomeOtherEnum { SomeConst1, SomeConst2, - SomeConst3, + SomeConst3 } enum SomeStructEnum { - EnumStruct { a: isize, b: isize }, - EnumStruct2 { f1: MyType, f2: MyType }, - EnumStruct3 { f1: MyType, f2: MyType, f3: SomeEnum<'static> }, + EnumStruct{a:isize, b:isize}, + EnumStruct2{f1:MyType, f2:MyType}, + EnumStruct3{f1:MyType, f2:MyType, f3:SomeEnum<'static>} } fn matchSomeEnum(val: SomeEnum) { match val { - SomeEnum::Ints(int1, int2) => { - println(&(int1 + int2).to_string()); - } - SomeEnum::Floats(float1, float2) => { - println(&(float2 * float1).to_string()); - } - SomeEnum::Strings(.., s3) => { - println(s3); - } - SomeEnum::MyTypes(mt1, mt2) => { - println(&(mt1.field1 - mt2.field1).to_string()); - } + SomeEnum::Ints(int1, int2) => { println(&(int1+int2).to_string()); } + SomeEnum::Floats(float1, float2) => { println(&(float2*float1).to_string()); } + SomeEnum::Strings(.., s3) => { println(s3); } + SomeEnum::MyTypes(mt1, mt2) => { println(&(mt1.field1 - mt2.field1).to_string()); } } } fn matchSomeStructEnum(se: SomeStructEnum) { match se { - SomeStructEnum::EnumStruct { a: a, .. } => println(&a.to_string()), - SomeStructEnum::EnumStruct2 { f1: f1, f2: f_2 } => println(&f_2.field1.to_string()), - SomeStructEnum::EnumStruct3 { f1, .. } => println(&f1.field1.to_string()), + SomeStructEnum::EnumStruct{a:a, ..} => println(&a.to_string()), + SomeStructEnum::EnumStruct2{f1:f1, f2:f_2} => println(&f_2.field1.to_string()), + SomeStructEnum::EnumStruct3{f1, ..} => println(&f1.field1.to_string()), } } + fn matchSomeStructEnum2(se: SomeStructEnum) { use SomeStructEnum::*; match se { - EnumStruct { a: ref aaa, .. } => println(&aaa.to_string()), - EnumStruct2 { f1, f2: f2 } => println(&f1.field1.to_string()), - EnumStruct3 { f1, f3: SomeEnum::Ints(..), f2 } => println(&f1.field1.to_string()), - _ => {} + EnumStruct{a: ref aaa, ..} => println(&aaa.to_string()), + EnumStruct2{f1, f2: f2} => println(&f1.field1.to_string()), + EnumStruct3{f1, f3: SomeEnum::Ints(..), f2} => println(&f1.field1.to_string()), + _ => {}, } } fn matchSomeOtherEnum(val: SomeOtherEnum) { use SomeOtherEnum::{SomeConst2, SomeConst3}; match val { - SomeOtherEnum::SomeConst1 => { - println("I'm const1."); - } - SomeConst2 | SomeConst3 => { - println("I'm const2 or const3."); - } + SomeOtherEnum::SomeConst1 => { println("I'm const1."); } + SomeConst2 | SomeConst3 => { println("I'm const2 or const3."); } } } -fn hello((z, a): (u32, String), ex: X) { +fn hello((z, a) : (u32, String), ex: X) { SameDir2::hello(43); println(&yy.to_string()); @@ -261,8 +253,8 @@ fn hello((z, a): (u32, String), ex: X) { let x = 32.0f32; let _ = (x + ((x * x) + 1.0).sqrt()).ln(); - let s: Box = box some_fields { field1: 43 }; - let s2: Box = box some_fields { field1: 43 }; + let s: Box = box some_fields {field1: 43}; + let s2: Box = box some_fields {field1: 43}; let s3 = box nofields; s.Method(43); @@ -315,9 +307,8 @@ mod macro_use_test { } } -fn main() { - // foo - let s = box some_fields { field1: 43 }; +fn main() { // foo + let s = box some_fields {field1: 43}; hello((43, "a".to_string()), *s); sub::sub2::hello(); sub2::sub3::hello(); @@ -338,24 +329,26 @@ fn main() { let vs = variable_str!(32); let mut candidates: RefCell> = RefCell::new(HashMap::new()); - let _ = blah { used_link_args: RefCell::new([]) }; + let _ = blah { + used_link_args: RefCell::new([]), + }; let s1 = nofields; - let s2 = SF { field1: 55 }; - let s3: some_fields = some_fields { field1: 55 }; - let s4: msalias::nested_struct = sub::sub2::nested_struct { field2: 55 }; - let s4: msalias::nested_struct = sub2::nested_struct { field2: 55 }; + let s2 = SF { field1: 55}; + let s3: some_fields = some_fields{ field1: 55}; + let s4: msalias::nested_struct = sub::sub2::nested_struct{ field2: 55}; + let s4: msalias::nested_struct = sub2::nested_struct{ field2: 55}; println(&s2.field1.to_string()); - let s5: MyType = box some_fields { field1: 55 }; - let s = SameDir::SameStruct { name: "Bob".to_string() }; - let s = SubDir::SubStruct { name: "Bob".to_string() }; + let s5: MyType = box some_fields{ field1: 55}; + let s = SameDir::SameStruct{name: "Bob".to_string()}; + let s = SubDir::SubStruct{name:"Bob".to_string()}; let s6: SomeEnum = SomeEnum::MyTypes(box s2.clone(), s5); let s7: SomeEnum = SomeEnum::Strings("one", "two", "three"); matchSomeEnum(s6); matchSomeEnum(s7); let s8: SomeOtherEnum = SomeOtherEnum::SomeConst2; matchSomeOtherEnum(s8); - let s9: SomeStructEnum = - SomeStructEnum::EnumStruct2 { f1: box some_fields { field1: 10 }, f2: box s2 }; + let s9: SomeStructEnum = SomeStructEnum::EnumStruct2{ f1: box some_fields{ field1:10 }, + f2: box s2 }; matchSomeStructEnum(s9); for x in &vec![1, 2, 3] { @@ -416,7 +409,8 @@ impl<'a> Pattern<'a> for CharEqPattern { struct CharSearcher<'a>(>::Searcher); -pub trait Error {} +pub trait Error { +} impl Error + 'static { pub fn is(&self) -> bool { @@ -443,13 +437,13 @@ fn test_format_args() { print!("x is {}, y is {1}, name is {n}", x, y, n = name); } -extern "C" { +extern { static EXTERN_FOO: u8; fn extern_foo(a: u8, b: i32) -> String; } struct Rls699 { - f: u32, + f: u32, } fn new(f: u32) -> Rls699 { diff --git a/src/test/run-make-fulldeps/static-dylib-by-default/bar.rs b/src/test/run-make-fulldeps/static-dylib-by-default/bar.rs index 14421165e2da1..5381e7f24bc3a 100644 --- a/src/test/run-make-fulldeps/static-dylib-by-default/bar.rs +++ b/src/test/run-make-fulldeps/static-dylib-by-default/bar.rs @@ -3,6 +3,6 @@ extern crate foo; #[no_mangle] -pub extern "C" fn bar() { +pub extern fn bar() { foo::foo(); } diff --git a/src/test/run-make-fulldeps/static-nobundle/bbb.rs b/src/test/run-make-fulldeps/static-nobundle/bbb.rs index 69d1668d4f643..0e10fc3dd3a0c 100644 --- a/src/test/run-make-fulldeps/static-nobundle/bbb.rs +++ b/src/test/run-make-fulldeps/static-nobundle/bbb.rs @@ -2,7 +2,7 @@ #![feature(static_nobundle)] #[link(name = "aaa", kind = "static-nobundle")] -extern "C" { +extern { pub fn native_func(); } diff --git a/src/test/run-make-fulldeps/staticlib-blank-lib/foo.rs b/src/test/run-make-fulldeps/staticlib-blank-lib/foo.rs index bf48d069da956..48ba8b7f1b78d 100644 --- a/src/test/run-make-fulldeps/staticlib-blank-lib/foo.rs +++ b/src/test/run-make-fulldeps/staticlib-blank-lib/foo.rs @@ -1,6 +1,6 @@ #![crate_type = "staticlib"] #[link(name = "foo", kind = "static")] -extern "C" {} +extern {} fn main() {} diff --git a/src/test/run-make-fulldeps/std-core-cycle/foo.rs b/src/test/run-make-fulldeps/std-core-cycle/foo.rs index 6aa6e1ac3c505..3c80bc45a5b9c 100644 --- a/src/test/run-make-fulldeps/std-core-cycle/foo.rs +++ b/src/test/run-make-fulldeps/std-core-cycle/foo.rs @@ -6,6 +6,6 @@ extern crate bar; static A: bar::A = bar::A; #[no_mangle] -pub extern "C" fn a(a: u32, b: u32) -> u32 { +pub extern fn a(a: u32, b: u32) -> u32 { a / b } diff --git a/src/test/run-make-fulldeps/target-specs/foo.rs b/src/test/run-make-fulldeps/target-specs/foo.rs index 9ff33e24d04d7..ee443eb0aa32b 100644 --- a/src/test/run-make-fulldeps/target-specs/foo.rs +++ b/src/test/run-make-fulldeps/target-specs/foo.rs @@ -1,21 +1,19 @@ #![feature(lang_items, no_core, auto_traits)] #![no_core] -#[lang = "copy"] -trait Copy {} +#[lang="copy"] +trait Copy { } -#[lang = "sized"] -trait Sized {} +#[lang="sized"] +trait Sized { } #[lang = "freeze"] auto trait Freeze {} -#[lang = "start"] -fn start(_main: *const u8, _argc: isize, _argv: *const *const u8) -> isize { - 0 -} +#[lang="start"] +fn start(_main: *const u8, _argc: isize, _argv: *const *const u8) -> isize { 0 } -extern "C" { +extern { fn _foo() -> [u8; 16]; } diff --git a/src/test/run-make/issue-36710/foo.rs b/src/test/run-make/issue-36710/foo.rs index 845844f427bdf..061f07c324340 100644 --- a/src/test/run-make/issue-36710/foo.rs +++ b/src/test/run-make/issue-36710/foo.rs @@ -3,9 +3,7 @@ // For linking libstdc++ on MinGW #![cfg_attr(all(windows, target_env = "gnu"), feature(static_nobundle))] -extern "C" { - fn get() -> u32; -} +extern { fn get() -> u32; } fn main() { let i = unsafe { get() }; diff --git a/src/test/run-make/wasm-import-module/bar.rs b/src/test/run-make/wasm-import-module/bar.rs index 1b988c78321d9..206f7c63e036e 100644 --- a/src/test/run-make/wasm-import-module/bar.rs +++ b/src/test/run-make/wasm-import-module/bar.rs @@ -4,13 +4,13 @@ extern crate foo; #[link(wasm_import_module = "./me")] -extern "C" { +extern { #[link_name = "me_in_dep"] fn dep(); } #[no_mangle] -pub extern "C" fn foo() { +pub extern fn foo() { unsafe { foo::dep(); dep(); diff --git a/src/test/run-make/wasm-import-module/foo.rs b/src/test/run-make/wasm-import-module/foo.rs index bbeaf99bc778f..b9f87f18d0aa3 100644 --- a/src/test/run-make/wasm-import-module/foo.rs +++ b/src/test/run-make/wasm-import-module/foo.rs @@ -2,6 +2,6 @@ #![deny(warnings)] #[link(wasm_import_module = "./dep")] -extern "C" { +extern { pub fn dep(); } diff --git a/src/test/run-pass-valgrind/osx-frameworks.rs b/src/test/run-pass-valgrind/osx-frameworks.rs index 571621c1de776..ea1403645a515 100644 --- a/src/test/run-pass-valgrind/osx-frameworks.rs +++ b/src/test/run-pass-valgrind/osx-frameworks.rs @@ -6,15 +6,13 @@ extern crate libc; #[cfg(target_os = "macos")] #[link(name = "CoreFoundation", kind = "framework")] -extern "C" { +extern { fn CFRunLoopGetTypeID() -> libc::c_ulong; } #[cfg(target_os = "macos")] pub fn main() { - unsafe { - CFRunLoopGetTypeID(); - } + unsafe { CFRunLoopGetTypeID(); } } #[cfg(not(target_os = "macos"))] diff --git a/src/etc/check_missing_items.py b/src/test/rustdoc-json/check_missing_items.py similarity index 99% rename from src/etc/check_missing_items.py rename to src/test/rustdoc-json/check_missing_items.py index c7ca0134f9ce1..3a3bf7fa3ed58 100644 --- a/src/etc/check_missing_items.py +++ b/src/test/rustdoc-json/check_missing_items.py @@ -4,8 +4,6 @@ # `index` or `paths`. It DOES NOT check that the structure of the produced json is actually in # any way correct, for example an empty map would pass. -# FIXME: Better error output - import sys import json diff --git a/src/test/rustdoc-json/compare.py b/src/test/rustdoc-json/compare.py new file mode 100644 index 0000000000000..b0c5b16a19700 --- /dev/null +++ b/src/test/rustdoc-json/compare.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python + +# This script can check that an expected json blob is a subset of what actually gets produced. +# The comparison is independent of the value of IDs (which are unstable) and instead uses their +# relative ordering to check them against eachother by looking them up in their respective blob's +# `index` or `paths` mappings. To add a new test run `rustdoc --output-format json -o . yourtest.rs` +# and then create `yourtest.expected` by stripping unnecessary details from `yourtest.json`. If +# you're on windows, replace `\` with `/`. + +import copy +import sys +import json +import types + +# Used instead of the string ids when used as references. +# Not used as keys in `index` or `paths` +class ID(str): + pass + + +class SubsetException(Exception): + def __init__(self, msg, trace): + self.msg = msg + self.trace = msg + super().__init__("{}: {}".format(trace, msg)) + + +def check_subset(expected_main, actual_main, base_dir): + expected_index = expected_main["index"] + expected_paths = expected_main["paths"] + actual_index = actual_main["index"] + actual_paths = actual_main["paths"] + already_checked = set() + + def _check_subset(expected, actual, trace): + expected_type = type(expected) + actual_type = type(actual) + + if actual_type is str: + actual = normalize(actual).replace(base_dir, "$TEST_BASE_DIR") + + if expected_type is not actual_type: + raise SubsetException( + "expected type `{}`, got `{}`".format(expected_type, actual_type), trace + ) + + + if expected_type in (int, bool, str) and expected != actual: + raise SubsetException("expected `{}`, got: `{}`".format(expected, actual), trace) + if expected_type is dict: + for key in expected: + if key not in actual: + raise SubsetException( + "Key `{}` not found in output".format(key), trace + ) + new_trace = copy.deepcopy(trace) + new_trace.append(key) + _check_subset(expected[key], actual[key], new_trace) + elif expected_type is list: + expected_elements = len(expected) + actual_elements = len(actual) + if expected_elements != actual_elements: + raise SubsetException( + "Found {} items, expected {}".format( + expected_elements, actual_elements + ), + trace, + ) + for expected, actual in zip(expected, actual): + new_trace = copy.deepcopy(trace) + new_trace.append(expected) + _check_subset(expected, actual, new_trace) + elif expected_type is ID and expected not in already_checked: + already_checked.add(expected) + _check_subset( + expected_index.get(expected, {}), actual_index.get(actual, {}), trace + ) + _check_subset( + expected_paths.get(expected, {}), actual_paths.get(actual, {}), trace + ) + + _check_subset(expected_main["root"], actual_main["root"], []) + + +def rustdoc_object_hook(obj): + # No need to convert paths, index and external_crates keys to ids, since + # they are the target of resolution, and never a source itself. + if "id" in obj and obj["id"]: + obj["id"] = ID(obj["id"]) + if "root" in obj: + obj["root"] = ID(obj["root"]) + if "items" in obj: + obj["items"] = [ID(id) for id in obj["items"]] + if "variants" in obj: + obj["variants"] = [ID(id) for id in obj["variants"]] + if "fields" in obj: + obj["fields"] = [ID(id) for id in obj["fields"]] + if "impls" in obj: + obj["impls"] = [ID(id) for id in obj["impls"]] + if "implementors" in obj: + obj["implementors"] = [ID(id) for id in obj["implementors"]] + if "links" in obj: + obj["links"] = {s: ID(id) for s, id in obj["links"]} + if "variant_kind" in obj and obj["variant_kind"] == "struct": + obj["variant_inner"] = [ID(id) for id in obj["variant_inner"]] + return obj + + +def main(expected_fpath, actual_fpath, base_dir): + print( + "checking that {} is a logical subset of {}".format( + expected_fpath, actual_fpath + ) + ) + with open(expected_fpath) as expected_file: + expected_main = json.load(expected_file, object_hook=rustdoc_object_hook) + with open(actual_fpath) as actual_file: + actual_main = json.load(actual_file, object_hook=rustdoc_object_hook) + check_subset(expected_main, actual_main, base_dir) + print("all checks passed") + +def normalize(s): + return s.replace('\\', '/') + +if __name__ == "__main__": + if len(sys.argv) < 4: + print("Usage: `compare.py expected.json actual.json test-dir`") + else: + main(sys.argv[1], sys.argv[2], normalize(sys.argv[3])) diff --git a/src/test/rustdoc-json/nested.expected b/src/test/rustdoc-json/nested.expected new file mode 100644 index 0000000000000..65bb0c5fa0367 --- /dev/null +++ b/src/test/rustdoc-json/nested.expected @@ -0,0 +1,196 @@ +{ + "crate_version": null, + "external_crates": {}, + "format_version": 1, + "includes_private": false, + "index": { + "0:0": { + "attrs": [], + "crate_id": 0, + "deprecation": null, + "docs": "", + "id": "0:0", + "inner": { + "is_crate": true, + "items": [ + "0:3" + ] + }, + "kind": "module", + "links": {}, + "name": "nested", + "source": { + "begin": [ + 2, + 0 + ], + "end": [ + 7, + 1 + ], + "filename": "$TEST_BASE_DIR/nested.rs" + }, + "visibility": "public" + }, + "0:3": { + "attrs": [], + "crate_id": 0, + "deprecation": null, + "docs": "", + "id": "0:3", + "inner": { + "is_crate": false, + "items": [ + "0:7", + "0:4" + ] + }, + "kind": "module", + "links": {}, + "name": "l1", + "source": { + "begin": [ + 2, + 0 + ], + "end": [ + 7, + 1 + ], + "filename": "$TEST_BASE_DIR/nested.rs" + }, + "visibility": "public" + }, + "0:4": { + "attrs": [], + "crate_id": 0, + "deprecation": null, + "docs": "", + "id": "0:4", + "inner": { + "is_crate": false, + "items": [ + "0:5" + ] + }, + "kind": "module", + "links": {}, + "name": "l3", + "source": { + "begin": [ + 3, + 4 + ], + "end": [ + 5, + 5 + ], + "filename": "$TEST_BASE_DIR/nested.rs" + }, + "visibility": "public" + }, + "0:5": { + "attrs": [], + "crate_id": 0, + "deprecation": null, + "docs": "", + "id": "0:5", + "inner": { + "fields": [], + "fields_stripped": false, + "generics": { + "params": [], + "where_predicates": [] + }, + "impls": [ + "0:10", + "0:11", + "0:12", + "0:14", + "0:15" + ], + "struct_type": "unit" + }, + "kind": "struct", + "links": {}, + "name": "L4", + "source": { + "begin": [ + 4, + 8 + ], + "end": [ + 4, + 22 + ], + "filename": "$TEST_BASE_DIR/nested.rs" + }, + "visibility": "public" + }, + "0:7": { + "attrs": [], + "crate_id": 0, + "deprecation": null, + "docs": "", + "id": "0:7", + "inner": { + "glob": false, + "id": "0:5", + "name": "L4", + "span": "l3::L4" + }, + "kind": "import", + "links": {}, + "name": null, + "source": { + "begin": [ + 6, + 4 + ], + "end": [ + 6, + 19 + ], + "filename": "$TEST_BASE_DIR/nested.rs" + }, + "visibility": "public" + } + }, + "paths": { + "0:0": { + "crate_id": 0, + "kind": "module", + "path": [ + "nested" + ] + }, + "0:3": { + "crate_id": 0, + "kind": "module", + "path": [ + "nested", + "l1" + ] + }, + "0:4": { + "crate_id": 0, + "kind": "module", + "path": [ + "nested", + "l1", + "l3" + ] + }, + "0:5": { + "crate_id": 0, + "kind": "struct", + "path": [ + "nested", + "l1", + "l3", + "L4" + ] + } + }, + "root": "0:0" +} \ No newline at end of file diff --git a/src/test/rustdoc-json/nested.rs b/src/test/rustdoc-json/nested.rs index 7e705255d983d..e460b343d3730 100644 --- a/src/test/rustdoc-json/nested.rs +++ b/src/test/rustdoc-json/nested.rs @@ -1,24 +1,7 @@ // edition:2018 - -// @has nested.json "$.index[*][?(@.name=='nested')].kind" \"module\" -// @has - "$.index[*][?(@.name=='nested')].inner.is_crate" true -// @count - "$.index[*][?(@.name=='nested')].inner.items[*]" 1 - -// @has nested.json "$.index[*][?(@.name=='l1')].kind" \"module\" -// @has - "$.index[*][?(@.name=='l1')].inner.is_crate" false -// @count - "$.index[*][?(@.name=='l1')].inner.items[*]" 2 pub mod l1 { - - // @has nested.json "$.index[*][?(@.name=='l3')].kind" \"module\" - // @has - "$.index[*][?(@.name=='l3')].inner.is_crate" false - // @count - "$.index[*][?(@.name=='l3')].inner.items[*]" 1 pub mod l3 { - - // @has nested.json "$.index[*][?(@.name=='L4')].kind" \"struct\" - // @has - "$.index[*][?(@.name=='L4')].inner.struct_type" \"unit\" pub struct L4; } - // @has nested.json "$.index[*][?(@.inner.span=='l3::L4')].kind" \"import\" - // @has - "$.index[*][?(@.inner.span=='l3::L4')].inner.glob" false pub use l3::L4; } diff --git a/src/test/rustdoc-json/structs.expected b/src/test/rustdoc-json/structs.expected new file mode 100644 index 0000000000000..799829de3fd6c --- /dev/null +++ b/src/test/rustdoc-json/structs.expected @@ -0,0 +1,456 @@ +{ + "root": "0:0", + "version": null, + "includes_private": false, + "index": { + "0:9": { + "crate_id": 0, + "name": "Unit", + "source": { + "filename": "$TEST_BASE_DIR/structs.rs", + "begin": [ + 7, + 0 + ], + "end": [ + 7, + 16 + ] + }, + "visibility": "public", + "docs": "", + "links": {}, + "attrs": [], + "deprecation": null, + "kind": "struct", + "inner": { + "struct_type": "unit", + "generics": { + "params": [], + "where_predicates": [] + }, + "fields_stripped": false, + "fields": [] + } + }, + "0:8": { + "crate_id": 0, + "name": "1", + "source": { + "filename": "$TEST_BASE_DIR/structs.rs", + "begin": [ + 5, + 22 + ], + "end": [ + 5, + 28 + ] + }, + "visibility": "default", + "docs": "", + "links": {}, + "attrs": [], + "deprecation": null, + "kind": "struct_field", + "inner": { + "kind": "resolved_path", + "inner": { + "name": "String", + "id": "5:5035", + "args": { + "angle_bracketed": { + "args": [], + "bindings": [] + } + }, + "param_names": [] + } + } + }, + "0:18": { + "crate_id": 0, + "name": "stuff", + "source": { + "filename": "$TEST_BASE_DIR/structs.rs", + "begin": [ + 15, + 4 + ], + "end": [ + 15, + 17 + ] + }, + "visibility": "default", + "docs": "", + "links": {}, + "attrs": [], + "deprecation": null, + "kind": "struct_field", + "inner": { + "kind": "resolved_path", + "inner": { + "name": "Vec", + "id": "5:4322", + "args": { + "angle_bracketed": { + "args": [ + { + "type": { + "kind": "generic", + "inner": "T" + } + } + ], + "bindings": [] + } + }, + "param_names": [] + } + } + }, + "0:11": { + "crate_id": 0, + "name": "WithPrimitives", + "source": { + "filename": "$TEST_BASE_DIR/structs.rs", + "begin": [ + 9, + 0 + ], + "end": [ + 12, + 1 + ] + }, + "visibility": "public", + "docs": "", + "links": {}, + "attrs": [], + "deprecation": null, + "kind": "struct", + "inner": { + "struct_type": "plain", + "generics": { + "params": [ + { + "name": "'a", + "kind": "lifetime" + } + ], + "where_predicates": [] + }, + "fields_stripped": true + } + }, + "0:14": { + "crate_id": 0, + "name": "s", + "source": { + "filename": "$TEST_BASE_DIR/structs.rs", + "begin": [ + 11, + 4 + ], + "end": [ + 11, + 14 + ] + }, + "visibility": "default", + "docs": "", + "links": {}, + "attrs": [], + "deprecation": null, + "kind": "struct_field", + "inner": { + "kind": "borrowed_ref", + "inner": { + "lifetime": "'a", + "mutable": false, + "type": { + "kind": "primitive", + "inner": "str" + } + } + } + }, + "0:19": { + "crate_id": 0, + "name": "things", + "source": { + "filename": "$TEST_BASE_DIR/structs.rs", + "begin": [ + 16, + 4 + ], + "end": [ + 16, + 25 + ] + }, + "visibility": "default", + "docs": "", + "links": {}, + "attrs": [], + "deprecation": null, + "kind": "struct_field", + "inner": { + "kind": "resolved_path", + "inner": { + "name": "HashMap", + "id": "1:6600", + "args": { + "angle_bracketed": { + "args": [ + { + "type": { + "kind": "generic", + "inner": "U" + } + }, + { + "type": { + "kind": "generic", + "inner": "U" + } + } + ], + "bindings": [] + } + }, + "param_names": [] + } + } + }, + "0:15": { + "crate_id": 0, + "name": "WithGenerics", + "source": { + "filename": "$TEST_BASE_DIR/structs.rs", + "begin": [ + 14, + 0 + ], + "end": [ + 17, + 1 + ] + }, + "visibility": "public", + "docs": "", + "links": {}, + "attrs": [], + "deprecation": null, + "kind": "struct", + "inner": { + "struct_type": "plain", + "generics": { + "params": [ + { + "name": "T", + "kind": { + "type": { + "bounds": [], + "default": null + } + } + }, + { + "name": "U", + "kind": { + "type": { + "bounds": [], + "default": null + } + } + } + ], + "where_predicates": [] + }, + "fields_stripped": true + } + }, + "0:0": { + "crate_id": 0, + "name": "structs", + "source": { + "filename": "$TEST_BASE_DIR/structs.rs", + "begin": [ + 1, + 0 + ], + "end": [ + 17, + 1 + ] + }, + "visibility": "public", + "docs": "", + "links": {}, + "attrs": [], + "deprecation": null, + "kind": "module", + "inner": { + "is_crate": true, + "items": [ + "0:4", + "0:5", + "0:9", + "0:11", + "0:15" + ] + } + }, + "0:13": { + "crate_id": 0, + "name": "num", + "source": { + "filename": "$TEST_BASE_DIR/structs.rs", + "begin": [ + 10, + 4 + ], + "end": [ + 10, + 12 + ] + }, + "visibility": "default", + "docs": "", + "links": {}, + "attrs": [], + "deprecation": null, + "kind": "struct_field", + "inner": { + "kind": "primitive", + "inner": "u32" + } + }, + "0:5": { + "crate_id": 0, + "name": "Tuple", + "source": { + "filename": "$TEST_BASE_DIR/structs.rs", + "begin": [ + 5, + 0 + ], + "end": [ + 5, + 30 + ] + }, + "visibility": "public", + "docs": "", + "links": {}, + "attrs": [], + "deprecation": null, + "kind": "struct", + "inner": { + "struct_type": "tuple", + "generics": { + "params": [], + "where_predicates": [] + }, + "fields_stripped": true + } + }, + "0:4": { + "crate_id": 0, + "name": "PlainEmpty", + "source": { + "filename": "$TEST_BASE_DIR/structs.rs", + "begin": [ + 3, + 0 + ], + "end": [ + 3, + 24 + ] + }, + "visibility": "public", + "docs": "", + "links": {}, + "attrs": [], + "deprecation": null, + "kind": "struct", + "inner": { + "struct_type": "plain", + "generics": { + "params": [], + "where_predicates": [] + }, + "fields_stripped": false, + "fields": [] + } + }, + "0:7": { + "crate_id": 0, + "name": "0", + "source": { + "filename": "$TEST_BASE_DIR/structs.rs", + "begin": [ + 5, + 17 + ], + "end": [ + 5, + 20 + ] + }, + "visibility": "default", + "docs": "", + "links": {}, + "attrs": [], + "deprecation": null, + "kind": "struct_field", + "inner": { + "kind": "primitive", + "inner": "u32" + } + } + }, + "paths": { + "5:4322": { + "crate_id": 5, + "path": [ + "alloc", + "vec", + "Vec" + ], + "kind": "struct" + }, + "5:5035": { + "crate_id": 5, + "path": [ + "alloc", + "string", + "String" + ], + "kind": "struct" + }, + "1:6600": { + "crate_id": 1, + "path": [ + "std", + "collections", + "hash", + "map", + "HashMap" + ], + "kind": "struct" + } + }, + "external_crates": { + "1": { + "name": "std" + }, + "5": { + "name": "alloc" + } + }, + "format_version": 1 +} diff --git a/src/test/rustdoc-json/structs.rs b/src/test/rustdoc-json/structs.rs new file mode 100644 index 0000000000000..43fc4743503aa --- /dev/null +++ b/src/test/rustdoc-json/structs.rs @@ -0,0 +1,17 @@ +use std::collections::HashMap; + +pub struct PlainEmpty {} + +pub struct Tuple(u32, String); + +pub struct Unit; + +pub struct WithPrimitives<'a> { + num: u32, + s: &'a str, +} + +pub struct WithGenerics { + stuff: Vec, + things: HashMap, +} diff --git a/src/test/rustdoc-json/structs/plain_empty.rs b/src/test/rustdoc-json/structs/plain_empty.rs deleted file mode 100644 index a251caf4ba933..0000000000000 --- a/src/test/rustdoc-json/structs/plain_empty.rs +++ /dev/null @@ -1,6 +0,0 @@ -// @has plain_empty.json "$.index[*][?(@.name=='PlainEmpty')].visibility" \"public\" -// @has - "$.index[*][?(@.name=='PlainEmpty')].kind" \"struct\" -// @has - "$.index[*][?(@.name=='PlainEmpty')].inner.struct_type" \"plain\" -// @has - "$.index[*][?(@.name=='PlainEmpty')].inner.fields_stripped" false -// @has - "$.index[*][?(@.name=='PlainEmpty')].inner.fields" [] -pub struct PlainEmpty {} diff --git a/src/test/rustdoc-json/structs/tuple.rs b/src/test/rustdoc-json/structs/tuple.rs deleted file mode 100644 index 4e510b3982507..0000000000000 --- a/src/test/rustdoc-json/structs/tuple.rs +++ /dev/null @@ -1,5 +0,0 @@ -// @has tuple.json "$.index[*][?(@.name=='Tuple')].visibility" \"public\" -// @has - "$.index[*][?(@.name=='Tuple')].kind" \"struct\" -// @has - "$.index[*][?(@.name=='Tuple')].inner.struct_type" \"tuple\" -// @has - "$.index[*][?(@.name=='Tuple')].inner.fields_stripped" true -pub struct Tuple(u32, String); diff --git a/src/test/rustdoc-json/structs/unit.rs b/src/test/rustdoc-json/structs/unit.rs deleted file mode 100644 index 559d3068de6e4..0000000000000 --- a/src/test/rustdoc-json/structs/unit.rs +++ /dev/null @@ -1,5 +0,0 @@ -// @has unit.json "$.index[*][?(@.name=='Unit')].visibility" \"public\" -// @has - "$.index[*][?(@.name=='Unit')].kind" \"struct\" -// @has - "$.index[*][?(@.name=='Unit')].inner.struct_type" \"unit\" -// @has - "$.index[*][?(@.name=='Unit')].inner.fields" [] -pub struct Unit; diff --git a/src/test/rustdoc-json/structs/with_generics.rs b/src/test/rustdoc-json/structs/with_generics.rs deleted file mode 100644 index 65cfe7effa5f1..0000000000000 --- a/src/test/rustdoc-json/structs/with_generics.rs +++ /dev/null @@ -1,14 +0,0 @@ -use std::collections::HashMap; - -// @has with_generics.json "$.index[*][?(@.name=='WithGenerics')].visibility" \"public\" -// @has - "$.index[*][?(@.name=='WithGenerics')].kind" \"struct\" -// @has - "$.index[*][?(@.name=='WithGenerics')].inner.generics.params[0].name" \"T\" -// @has - "$.index[*][?(@.name=='WithGenerics')].inner.generics.params[0].kind.type" -// @has - "$.index[*][?(@.name=='WithGenerics')].inner.generics.params[1].name" \"U\" -// @has - "$.index[*][?(@.name=='WithGenerics')].inner.generics.params[1].kind.type" -// @has - "$.index[*][?(@.name=='WithGenerics')].inner.struct_type" \"plain\" -// @has - "$.index[*][?(@.name=='WithGenerics')].inner.fields_stripped" true -pub struct WithGenerics { - stuff: Vec, - things: HashMap, -} diff --git a/src/test/rustdoc-json/structs/with_primitives.rs b/src/test/rustdoc-json/structs/with_primitives.rs deleted file mode 100644 index ea98676863b5e..0000000000000 --- a/src/test/rustdoc-json/structs/with_primitives.rs +++ /dev/null @@ -1,10 +0,0 @@ -// @has with_primitives.json "$.index[*][?(@.name=='WithPrimitives')].visibility" \"public\" -// @has - "$.index[*][?(@.name=='WithPrimitives')].kind" \"struct\" -// @has - "$.index[*][?(@.name=='WithPrimitives')].inner.generics.params[0].name" \"\'a\" -// @has - "$.index[*][?(@.name=='WithPrimitives')].inner.generics.params[0].kind" \"lifetime\" -// @has - "$.index[*][?(@.name=='WithPrimitives')].inner.struct_type" \"plain\" -// @has - "$.index[*][?(@.name=='WithPrimitives')].inner.fields_stripped" true -pub struct WithPrimitives<'a> { - num: u32, - s: &'a str, -} diff --git a/src/test/rustdoc-ui/check-doc-alias-attr-location.rs b/src/test/rustdoc-ui/check-doc-alias-attr-location.rs index 6de1960e2e2b6..7de2caa189dc7 100644 --- a/src/test/rustdoc-ui/check-doc-alias-attr-location.rs +++ b/src/test/rustdoc-ui/check-doc-alias-attr-location.rs @@ -5,7 +5,7 @@ pub trait Foo { } #[doc(alias = "foo")] //~ ERROR -extern "C" {} +extern {} #[doc(alias = "bar")] //~ ERROR impl Bar { @@ -17,7 +17,5 @@ impl Bar { impl Foo for Bar { #[doc(alias = "assoc")] //~ ERROR type X = i32; - fn foo() -> Self::X { - 0 - } + fn foo() -> Self::X { 0 } } diff --git a/src/test/rustdoc-ui/coverage/basic.rs b/src/test/rustdoc-ui/coverage/basic.rs index 6c26b751c5e05..98507f99e8d4b 100644 --- a/src/test/rustdoc-ui/coverage/basic.rs +++ b/src/test/rustdoc-ui/coverage/basic.rs @@ -45,6 +45,6 @@ macro_rules! some_macro { () => {}; } -extern "C" { +extern { pub type ExternType; } diff --git a/src/test/rustdoc-ui/intra-doc/feature-gate-intra-doc-pointers.rs b/src/test/rustdoc-ui/intra-doc/feature-gate-intra-doc-pointers.rs deleted file mode 100644 index 3cfac942ca85e..0000000000000 --- a/src/test/rustdoc-ui/intra-doc/feature-gate-intra-doc-pointers.rs +++ /dev/null @@ -1,6 +0,0 @@ -//! [pointer::add] -//~^ ERROR: experimental -//! [pointer::wrapping_add] -//~^ ERROR: experimental -//! [pointer] // This is explicitly allowed -//! [reference] // This is explicitly allowed diff --git a/src/test/rustdoc-ui/intra-doc/feature-gate-intra-doc-pointers.stderr b/src/test/rustdoc-ui/intra-doc/feature-gate-intra-doc-pointers.stderr deleted file mode 100644 index 2c946ed48db17..0000000000000 --- a/src/test/rustdoc-ui/intra-doc/feature-gate-intra-doc-pointers.stderr +++ /dev/null @@ -1,23 +0,0 @@ -error[E0658]: linking to associated items of raw pointers is experimental - --> $DIR/feature-gate-intra-doc-pointers.rs:1:6 - | -LL | //! [pointer::add] - | ^^^^^^^^^^^^ - | - = note: see issue #80896 for more information - = help: add `#![feature(intra_doc_pointers)]` to the crate attributes to enable - = note: rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does - -error[E0658]: linking to associated items of raw pointers is experimental - --> $DIR/feature-gate-intra-doc-pointers.rs:3:6 - | -LL | //! [pointer::wrapping_add] - | ^^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #80896 for more information - = help: add `#![feature(intra_doc_pointers)]` to the crate attributes to enable - = note: rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does - -error: aborting due to 2 previous errors - -For more information about this error, try `rustc --explain E0658`. diff --git a/src/test/rustdoc-ui/intra-doc/non-path-primitives.rs b/src/test/rustdoc-ui/intra-doc/non-path-primitives.rs index 6785c4c43f541..114502b0ddf4e 100644 --- a/src/test/rustdoc-ui/intra-doc/non-path-primitives.rs +++ b/src/test/rustdoc-ui/intra-doc/non-path-primitives.rs @@ -1,5 +1,4 @@ #![deny(broken_intra_doc_links)] -#![feature(intra_doc_pointers)] // These are links that could reasonably expected to work, but don't. // `[]` isn't supported because it had too many false positives. diff --git a/src/test/rustdoc-ui/intra-doc/non-path-primitives.stderr b/src/test/rustdoc-ui/intra-doc/non-path-primitives.stderr index 174758504ae22..ea831e648f638 100644 --- a/src/test/rustdoc-ui/intra-doc/non-path-primitives.stderr +++ b/src/test/rustdoc-ui/intra-doc/non-path-primitives.stderr @@ -1,5 +1,5 @@ error: unresolved link to `T` - --> $DIR/non-path-primitives.rs:12:7 + --> $DIR/non-path-primitives.rs:11:7 | LL | //! [[T]::rotate_left] | ^ no item named `T` in scope @@ -12,7 +12,7 @@ LL | #![deny(broken_intra_doc_links)] = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]` error: unresolved link to `Z` - --> $DIR/non-path-primitives.rs:14:5 + --> $DIR/non-path-primitives.rs:13:5 | LL | //![Z]([T; N]::map) | ^ no item named `Z` in scope @@ -20,7 +20,7 @@ LL | //![Z]([T; N]::map) = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]` error: unresolved link to `Z` - --> $DIR/non-path-primitives.rs:17:6 + --> $DIR/non-path-primitives.rs:16:6 | LL | //! [Z][] | ^ no item named `Z` in scope @@ -28,7 +28,7 @@ LL | //! [Z][] = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]` error: unresolved link to `Z` - --> $DIR/non-path-primitives.rs:19:6 + --> $DIR/non-path-primitives.rs:18:6 | LL | //! [Z]: [T; N]::map | ^ no item named `Z` in scope @@ -36,31 +36,31 @@ LL | //! [Z]: [T; N]::map = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]` error: unresolved link to `unit::eq` - --> $DIR/non-path-primitives.rs:28:6 + --> $DIR/non-path-primitives.rs:27:6 | LL | //! [unit::eq] | ^^^^^^^^ the builtin type `unit` has no associated item named `eq` error: unresolved link to `tuple::eq` - --> $DIR/non-path-primitives.rs:29:6 + --> $DIR/non-path-primitives.rs:28:6 | LL | //! [tuple::eq] | ^^^^^^^^^ the builtin type `tuple` has no associated item named `eq` error: unresolved link to `fn::eq` - --> $DIR/non-path-primitives.rs:30:6 + --> $DIR/non-path-primitives.rs:29:6 | LL | //! [fn::eq] | ^^^^^^ the builtin type `fn` has no associated item named `eq` error: unresolved link to `never::eq` - --> $DIR/non-path-primitives.rs:31:6 + --> $DIR/non-path-primitives.rs:30:6 | LL | //! [never::eq] | ^^^^^^^^^ the builtin type `never` has no associated item named `eq` error: unresolved link to `reference::deref` - --> $DIR/non-path-primitives.rs:35:6 + --> $DIR/non-path-primitives.rs:34:6 | LL | //! [reference::deref] | ^^^^^^^^^^^^^^^^ the builtin type `reference` has no associated item named `deref` diff --git a/src/test/rustdoc-ui/issue-80992.rs b/src/test/rustdoc-ui/issue-80992.rs deleted file mode 100644 index 8983439bb64d3..0000000000000 --- a/src/test/rustdoc-ui/issue-80992.rs +++ /dev/null @@ -1,11 +0,0 @@ -// check-pass -// compile-flags:--test -// normalize-stdout-test: "src/test/rustdoc-ui" -> "$$DIR" -// normalize-stdout-test "finished in \d+\.\d+s" -> "finished in $$TIME" - -pub fn test() -> Result<(), ()> { - //! ```compile_fail - //! fn test() -> Result< {} - //! ``` - Ok(()) -} diff --git a/src/test/rustdoc-ui/issue-80992.stdout b/src/test/rustdoc-ui/issue-80992.stdout deleted file mode 100644 index 1dd19f468274c..0000000000000 --- a/src/test/rustdoc-ui/issue-80992.stdout +++ /dev/null @@ -1,6 +0,0 @@ - -running 1 test -test $DIR/issue-80992.rs - test (line 7) ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME - diff --git a/src/test/rustdoc/auxiliary/issue-34274.rs b/src/test/rustdoc/auxiliary/issue-34274.rs index c46660579a836..b0c3b4f562985 100644 --- a/src/test/rustdoc/auxiliary/issue-34274.rs +++ b/src/test/rustdoc/auxiliary/issue-34274.rs @@ -1,3 +1,3 @@ -extern "C" { +extern { pub fn extern_c_fn(); } diff --git a/src/test/rustdoc/foreigntype-reexport.rs b/src/test/rustdoc/foreigntype-reexport.rs index 1dec0ef3e0f71..616826ce7b4a8 100644 --- a/src/test/rustdoc/foreigntype-reexport.rs +++ b/src/test/rustdoc/foreigntype-reexport.rs @@ -1,7 +1,7 @@ #![feature(extern_types)] mod sub { - extern "C" { + extern { /// Another extern type. pub type C2; pub fn f2(); @@ -10,7 +10,7 @@ mod sub { } pub mod sub2 { - extern "C" { + extern { // @has foreigntype_reexport/sub2/foreigntype.C.html pub type C; // @has foreigntype_reexport/sub2/fn.f.html @@ -21,7 +21,7 @@ pub mod sub2 { } mod sub3 { - extern "C" { + extern { pub type C4; pub fn f4(); pub static K4: usize; @@ -35,7 +35,7 @@ mod sub3 { // @has foreigntype_reexport/index.html '//a[@class="foreigntype"]' 'C2' // @has foreigntype_reexport/index.html '//a[@class="fn"]' 'f2' // @has foreigntype_reexport/index.html '//a[@class="static"]' 'K2' -pub use self::sub::{f2, C2, K as K2}; +pub use self::sub::{C2, f2, K as K2}; // @has foreigntype_reexport/index.html '//a[@class="foreigntype"]' 'C' // @has foreigntype_reexport/index.html '//a[@class="fn"]' 'f' @@ -43,7 +43,7 @@ pub use self::sub::{f2, C2, K as K2}; // @has foreigntype_reexport/index.html '//code' 'pub use self::sub2::C as C3;' // @has foreigntype_reexport/index.html '//code' 'pub use self::sub2::f as f3;' // @has foreigntype_reexport/index.html '//code' 'pub use self::sub2::K3;' -pub use self::sub2::{f as f3, C as C3, K3}; +pub use self::sub2::{C as C3, f as f3, K3}; // @has foreigntype_reexport/foreigntype.C4.html // @has foreigntype_reexport/fn.f4.html diff --git a/src/test/rustdoc/foreigntype.rs b/src/test/rustdoc/foreigntype.rs index 891cdd5fed76c..bd8766c0cf13a 100644 --- a/src/test/rustdoc/foreigntype.rs +++ b/src/test/rustdoc/foreigntype.rs @@ -1,6 +1,6 @@ #![feature(extern_types)] -extern "C" { +extern { // @has foreigntype/foreigntype.ExtType.html pub type ExtType; } diff --git a/src/test/rustdoc/inline_local/glob-extern-no-defaults.rs b/src/test/rustdoc/inline_local/glob-extern-no-defaults.rs index 55c75dfe27b7e..276e4091c0273 100644 --- a/src/test/rustdoc/inline_local/glob-extern-no-defaults.rs +++ b/src/test/rustdoc/inline_local/glob-extern-no-defaults.rs @@ -3,7 +3,7 @@ #![crate_name = "foo"] mod mod1 { - extern "C" { + extern { pub fn public_fn(); fn private_fn(); } diff --git a/src/test/rustdoc/inline_local/glob-extern.rs b/src/test/rustdoc/inline_local/glob-extern.rs index 686e55de39264..a23ec3640eea7 100644 --- a/src/test/rustdoc/inline_local/glob-extern.rs +++ b/src/test/rustdoc/inline_local/glob-extern.rs @@ -1,7 +1,7 @@ #![crate_name = "foo"] mod mod1 { - extern "C" { + extern { pub fn public_fn(); fn private_fn(); } diff --git a/src/test/rustdoc/intra-doc/non-path-primitives.rs b/src/test/rustdoc/intra-doc/non-path-primitives.rs index 48c667ef2d18e..2c7e7b5c48c59 100644 --- a/src/test/rustdoc/intra-doc/non-path-primitives.rs +++ b/src/test/rustdoc/intra-doc/non-path-primitives.rs @@ -1,6 +1,5 @@ // ignore-tidy-linelength #![crate_name = "foo"] -#![feature(intra_doc_pointers)] #![deny(broken_intra_doc_links)] // @has foo/index.html '//a[@href="https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.rotate_left"]' 'slice::rotate_left' diff --git a/src/test/rustdoc/issue-22038.rs b/src/test/rustdoc/issue-22038.rs index ff5813dac8099..2db42b561f7f7 100644 --- a/src/test/rustdoc/issue-22038.rs +++ b/src/test/rustdoc/issue-22038.rs @@ -1,4 +1,4 @@ -extern "C" { +extern { // @has issue_22038/fn.foo1.html \ // '//*[@class="rust fn"]' 'pub unsafe extern "C" fn foo1()' pub fn foo1(); @@ -12,7 +12,7 @@ extern "system" { // @has issue_22038/fn.bar.html \ // '//*[@class="rust fn"]' 'pub extern "C" fn bar()' -pub extern "C" fn bar() {} +pub extern fn bar() {} // @has issue_22038/fn.baz.html \ // '//*[@class="rust fn"]' 'pub extern "system" fn baz()' diff --git a/src/test/rustdoc/issue-80233-normalize-auto-trait.rs b/src/test/rustdoc/issue-80233-normalize-auto-trait.rs deleted file mode 100644 index 585a0864bb25d..0000000000000 --- a/src/test/rustdoc/issue-80233-normalize-auto-trait.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Regression test for issue #80233 -// Tests that we don't ICE when processing auto traits - -#![crate_type = "lib"] -pub trait Trait1 {} - -pub trait Trait2 { - type Type2; -} - -pub trait Trait3 { - type Type3; -} - -impl Trait2 for Struct1 { - type Type2 = Struct1; -} - -impl Trait2 for Vec { - type Type2 = Vec; -} - -impl Trait3 for T { - type Type3 = Struct1; -} - -impl Trait3 for Vec { - type Type3 = Vec; -} - -pub struct Struct1 {} - -// @has issue_80233_normalize_auto_trait/struct.Question.html -// @has - '//code' 'impl Send for Question' -pub struct Question { - pub ins: < as Trait3>::Type3 as Trait2>::Type2, -} diff --git a/src/test/rustdoc/issue-80893.rs b/src/test/rustdoc/issue-80893.rs deleted file mode 100644 index 7c958a80be395..0000000000000 --- a/src/test/rustdoc/issue-80893.rs +++ /dev/null @@ -1,6 +0,0 @@ -// compile-flags: --test -Z unstable-options --test-builder true - -/// ```no_run -/// This tests that `--test-builder` is accepted as a flag by rustdoc. -/// ``` -pub struct Foo; diff --git a/src/test/rustdoc/sanitizer-option.rs b/src/test/rustdoc/sanitizer-option.rs index 1abba468febf5..a79b37ee08210 100644 --- a/src/test/rustdoc/sanitizer-option.rs +++ b/src/test/rustdoc/sanitizer-option.rs @@ -7,7 +7,7 @@ // correctly, then linking will fail. /// ``` -/// extern "C" { +/// extern { /// fn __sanitizer_print_stack_trace(); /// } /// diff --git a/src/test/rustdoc/titles.rs b/src/test/rustdoc/titles.rs index 2084e8517992a..3b4c42d865d06 100644 --- a/src/test/rustdoc/titles.rs +++ b/src/test/rustdoc/titles.rs @@ -7,7 +7,7 @@ pub mod foo_mod { pub struct __Thing {} } -extern "C" { +extern { // @matches 'foo/fn.foo_ffn.html' '//h1' 'Function foo::foo_ffn' pub fn foo_ffn(); } @@ -30,7 +30,7 @@ pub type FooType = FooStruct; // @matches 'foo/macro.foo_macro.html' '//h1' 'Macro foo::foo_macro' #[macro_export] macro_rules! foo_macro { - () => {}; + () => (); } // @matches 'foo/primitive.bool.html' '//h1' 'Primitive Type bool' @@ -40,7 +40,7 @@ mod bool {} // @matches 'foo/static.FOO_STATIC.html' '//h1' 'Static foo::FOO_STATIC' pub static FOO_STATIC: FooStruct = FooStruct; -extern "C" { +extern { // @matches 'foo/static.FOO_FSTATIC.html' '//h1' 'Static foo::FOO_FSTATIC' pub static FOO_FSTATIC: FooStruct; } diff --git a/src/test/ui-fulldeps/switch-stdout.rs b/src/test/ui-fulldeps/switch-stdout.rs index e9501a809308b..e105637c3da4f 100644 --- a/src/test/ui-fulldeps/switch-stdout.rs +++ b/src/test/ui-fulldeps/switch-stdout.rs @@ -9,7 +9,7 @@ use std::path::PathBuf; fn switch_stdout_to(file: File) { use std::os::unix::prelude::*; - extern "C" { + extern { fn dup2(old: i32, new: i32) -> i32; } @@ -29,7 +29,8 @@ fn switch_stdout_to(file: File) { const STD_OUTPUT_HANDLE: u32 = (-11i32) as u32; unsafe { - let rc = SetStdHandle(STD_OUTPUT_HANDLE, file.into_raw_handle() as *mut _); + let rc = SetStdHandle(STD_OUTPUT_HANDLE, + file.into_raw_handle() as *mut _); assert!(rc != 0); } } diff --git a/src/test/ui/abi/anon-extern-mod.rs b/src/test/ui/abi/anon-extern-mod.rs index 6c7d60d4cb0b4..37a67876c9170 100644 --- a/src/test/ui/abi/anon-extern-mod.rs +++ b/src/test/ui/abi/anon-extern-mod.rs @@ -7,7 +7,7 @@ extern crate libc; #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { fn rust_get_test_int() -> libc::intptr_t; } diff --git a/src/test/ui/abi/auxiliary/anon-extern-mod-cross-crate-1.rs b/src/test/ui/abi/auxiliary/anon-extern-mod-cross-crate-1.rs index 5cbf8093c5c3c..948b5e688ebcc 100644 --- a/src/test/ui/abi/auxiliary/anon-extern-mod-cross-crate-1.rs +++ b/src/test/ui/abi/auxiliary/anon-extern-mod-cross-crate-1.rs @@ -1,9 +1,9 @@ -#![crate_name = "anonexternmod"] +#![crate_name="anonexternmod"] #![feature(rustc_private)] extern crate libc; #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { pub fn rust_get_test_int() -> libc::intptr_t; } diff --git a/src/test/ui/abi/auxiliary/foreign_lib.rs b/src/test/ui/abi/auxiliary/foreign_lib.rs index 3c649b778bd1a..de6b0e2118a58 100644 --- a/src/test/ui/abi/auxiliary/foreign_lib.rs +++ b/src/test/ui/abi/auxiliary/foreign_lib.rs @@ -1,11 +1,12 @@ -#![crate_name = "foreign_lib"] +#![crate_name="foreign_lib"] + #![feature(rustc_private)] pub mod rustrt { extern crate libc; #[link(name = "rust_test_helpers", kind = "static")] - extern "C" { + extern { pub fn rust_get_test_int() -> libc::intptr_t; } } @@ -13,7 +14,7 @@ pub mod rustrt { pub mod rustrt2 { extern crate libc; - extern "C" { + extern { pub fn rust_get_test_int() -> libc::intptr_t; } } @@ -23,7 +24,7 @@ pub mod rustrt3 { // Ensures that we don't ICE or trigger LLVM asserts when // importing the same symbol under different types. // See https://github.com/rust-lang/rust/issues/32740. - extern "C" { + extern { pub fn rust_get_test_int() -> *const u8; } } diff --git a/src/test/ui/abi/c-stack-as-value.rs b/src/test/ui/abi/c-stack-as-value.rs index 5bece0ba2d15b..7595b76fb3fe7 100644 --- a/src/test/ui/abi/c-stack-as-value.rs +++ b/src/test/ui/abi/c-stack-as-value.rs @@ -8,7 +8,7 @@ mod rustrt { extern crate libc; #[link(name = "rust_test_helpers", kind = "static")] - extern "C" { + extern { pub fn rust_get_test_int() -> libc::intptr_t; } } diff --git a/src/test/ui/abi/cabi-int-widening.rs b/src/test/ui/abi/cabi-int-widening.rs index 1dbab275225cd..240eaebf3d685 100644 --- a/src/test/ui/abi/cabi-int-widening.rs +++ b/src/test/ui/abi/cabi-int-widening.rs @@ -2,7 +2,7 @@ // ignore-wasm32-bare no libc to test ffi with #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { fn rust_int8_to_int32(_: i8) -> i32; } diff --git a/src/test/ui/abi/consts/auxiliary/anon-extern-mod-cross-crate-1.rs b/src/test/ui/abi/consts/auxiliary/anon-extern-mod-cross-crate-1.rs index 5cbf8093c5c3c..948b5e688ebcc 100644 --- a/src/test/ui/abi/consts/auxiliary/anon-extern-mod-cross-crate-1.rs +++ b/src/test/ui/abi/consts/auxiliary/anon-extern-mod-cross-crate-1.rs @@ -1,9 +1,9 @@ -#![crate_name = "anonexternmod"] +#![crate_name="anonexternmod"] #![feature(rustc_private)] extern crate libc; #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { pub fn rust_get_test_int() -> libc::intptr_t; } diff --git a/src/test/ui/abi/cross-crate/auxiliary/anon-extern-mod-cross-crate-1.rs b/src/test/ui/abi/cross-crate/auxiliary/anon-extern-mod-cross-crate-1.rs index 5cbf8093c5c3c..948b5e688ebcc 100644 --- a/src/test/ui/abi/cross-crate/auxiliary/anon-extern-mod-cross-crate-1.rs +++ b/src/test/ui/abi/cross-crate/auxiliary/anon-extern-mod-cross-crate-1.rs @@ -1,9 +1,9 @@ -#![crate_name = "anonexternmod"] +#![crate_name="anonexternmod"] #![feature(rustc_private)] extern crate libc; #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { pub fn rust_get_test_int() -> libc::intptr_t; } diff --git a/src/test/ui/abi/extern/auxiliary/extern-crosscrate-source.rs b/src/test/ui/abi/extern/auxiliary/extern-crosscrate-source.rs index 9c61518b94142..d4568d38e25c9 100644 --- a/src/test/ui/abi/extern/auxiliary/extern-crosscrate-source.rs +++ b/src/test/ui/abi/extern/auxiliary/extern-crosscrate-source.rs @@ -1,4 +1,4 @@ -#![crate_name = "externcallback"] +#![crate_name="externcallback"] #![crate_type = "lib"] #![feature(rustc_private)] @@ -8,11 +8,10 @@ pub mod rustrt { extern crate libc; #[link(name = "rust_test_helpers", kind = "static")] - extern "C" { - pub fn rust_dbg_call( - cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, - data: libc::uintptr_t, - ) -> libc::uintptr_t; + extern { + pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, + data: libc::uintptr_t) + -> libc::uintptr_t; } } @@ -23,6 +22,10 @@ pub fn fact(n: libc::uintptr_t) -> libc::uintptr_t { } } -pub extern "C" fn cb(data: libc::uintptr_t) -> libc::uintptr_t { - if data == 1 { data } else { fact(data - 1) * data } +pub extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t { + if data == 1 { + data + } else { + fact(data - 1) * data + } } diff --git a/src/test/ui/abi/extern/extern-call-deep.rs b/src/test/ui/abi/extern/extern-call-deep.rs index db5f2ca652fa5..81f884dada9b8 100644 --- a/src/test/ui/abi/extern/extern-call-deep.rs +++ b/src/test/ui/abi/extern/extern-call-deep.rs @@ -10,16 +10,19 @@ mod rustrt { extern crate libc; #[link(name = "rust_test_helpers", kind = "static")] - extern "C" { - pub fn rust_dbg_call( - cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, - data: libc::uintptr_t, - ) -> libc::uintptr_t; + extern { + pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, + data: libc::uintptr_t) + -> libc::uintptr_t; } } -extern "C" fn cb(data: libc::uintptr_t) -> libc::uintptr_t { - if data == 1 { data } else { count(data - 1) + 1 } +extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t { + if data == 1 { + data + } else { + count(data - 1) + 1 + } } fn count(n: libc::uintptr_t) -> libc::uintptr_t { diff --git a/src/test/ui/abi/extern/extern-call-deep2.rs b/src/test/ui/abi/extern/extern-call-deep2.rs index 60e8db1592e94..b31489b1e10cc 100644 --- a/src/test/ui/abi/extern/extern-call-deep2.rs +++ b/src/test/ui/abi/extern/extern-call-deep2.rs @@ -1,6 +1,7 @@ // run-pass #![allow(unused_must_use)] // ignore-emscripten no threads support + #![feature(rustc_private)] extern crate libc; @@ -10,16 +11,19 @@ mod rustrt { extern crate libc; #[link(name = "rust_test_helpers", kind = "static")] - extern "C" { - pub fn rust_dbg_call( - cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, - data: libc::uintptr_t, - ) -> libc::uintptr_t; + extern { + pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, + data: libc::uintptr_t) + -> libc::uintptr_t; } } -extern "C" fn cb(data: libc::uintptr_t) -> libc::uintptr_t { - if data == 1 { data } else { count(data - 1) + 1 } +extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t { + if data == 1 { + data + } else { + count(data - 1) + 1 + } } fn count(n: libc::uintptr_t) -> libc::uintptr_t { @@ -32,10 +36,9 @@ fn count(n: libc::uintptr_t) -> libc::uintptr_t { pub fn main() { // Make sure we're on a thread with small Rust stacks (main currently // has a large stack) - thread::spawn(move || { + thread::spawn(move|| { let result = count(1000); println!("result = {}", result); assert_eq!(result, 1000); - }) - .join(); + }).join(); } diff --git a/src/test/ui/abi/extern/extern-call-direct.rs b/src/test/ui/abi/extern/extern-call-direct.rs index 19b901d49a428..7204176421565 100644 --- a/src/test/ui/abi/extern/extern-call-direct.rs +++ b/src/test/ui/abi/extern/extern-call-direct.rs @@ -2,7 +2,7 @@ // Test direct calls to extern fns. -extern "C" fn f(x: usize) -> usize { x * 2 } +extern fn f(x: usize) -> usize { x * 2 } pub fn main() { let x = f(22); diff --git a/src/test/ui/abi/extern/extern-call-indirect.rs b/src/test/ui/abi/extern/extern-call-indirect.rs index 886e8f6be1099..158b54e4b8cdd 100644 --- a/src/test/ui/abi/extern/extern-call-indirect.rs +++ b/src/test/ui/abi/extern/extern-call-indirect.rs @@ -9,16 +9,19 @@ mod rustrt { extern crate libc; #[link(name = "rust_test_helpers", kind = "static")] - extern "C" { - pub fn rust_dbg_call( - cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, - data: libc::uintptr_t, - ) -> libc::uintptr_t; + extern { + pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, + data: libc::uintptr_t) + -> libc::uintptr_t; } } -extern "C" fn cb(data: libc::uintptr_t) -> libc::uintptr_t { - if data == 1 { data } else { fact(data - 1) * data } +extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t { + if data == 1 { + data + } else { + fact(data - 1) * data + } } fn fact(n: libc::uintptr_t) -> libc::uintptr_t { diff --git a/src/test/ui/abi/extern/extern-call-scrub.rs b/src/test/ui/abi/extern/extern-call-scrub.rs index ff33cf31af85e..a7b1065c9e1f6 100644 --- a/src/test/ui/abi/extern/extern-call-scrub.rs +++ b/src/test/ui/abi/extern/extern-call-scrub.rs @@ -5,6 +5,7 @@ // directions // ignore-emscripten no threads support + #![feature(rustc_private)] extern crate libc; @@ -14,16 +15,19 @@ mod rustrt { extern crate libc; #[link(name = "rust_test_helpers", kind = "static")] - extern "C" { - pub fn rust_dbg_call( - cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, - data: libc::uintptr_t, - ) -> libc::uintptr_t; + extern { + pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, + data: libc::uintptr_t) + -> libc::uintptr_t; } } -extern "C" fn cb(data: libc::uintptr_t) -> libc::uintptr_t { - if data == 1 { data } else { count(data - 1) + count(data - 1) } +extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t { + if data == 1 { + data + } else { + count(data - 1) + count(data - 1) + } } fn count(n: libc::uintptr_t) -> libc::uintptr_t { @@ -36,10 +40,9 @@ fn count(n: libc::uintptr_t) -> libc::uintptr_t { pub fn main() { // Make sure we're on a thread with small Rust stacks (main currently // has a large stack) - thread::spawn(move || { + thread::spawn(move|| { let result = count(12); println!("result = {}", result); assert_eq!(result, 2048); - }) - .join(); + }).join(); } diff --git a/src/test/ui/abi/extern/extern-pass-TwoU16s.rs b/src/test/ui/abi/extern/extern-pass-TwoU16s.rs index cff25511cc95d..285bce2e19c31 100644 --- a/src/test/ui/abi/extern/extern-pass-TwoU16s.rs +++ b/src/test/ui/abi/extern/extern-pass-TwoU16s.rs @@ -8,18 +8,17 @@ #[derive(Copy, Clone, PartialEq, Debug)] pub struct TwoU16s { - one: u16, - two: u16, + one: u16, two: u16 } #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { pub fn rust_dbg_extern_identity_TwoU16s(v: TwoU16s) -> TwoU16s; } pub fn main() { unsafe { - let x = TwoU16s { one: 22, two: 23 }; + let x = TwoU16s {one: 22, two: 23}; let y = rust_dbg_extern_identity_TwoU16s(x); assert_eq!(x, y); } diff --git a/src/test/ui/abi/extern/extern-pass-TwoU32s.rs b/src/test/ui/abi/extern/extern-pass-TwoU32s.rs index 03a8ecf241da8..fb18aa8d22fda 100644 --- a/src/test/ui/abi/extern/extern-pass-TwoU32s.rs +++ b/src/test/ui/abi/extern/extern-pass-TwoU32s.rs @@ -8,18 +8,17 @@ #[derive(Copy, Clone, PartialEq, Debug)] pub struct TwoU32s { - one: u32, - two: u32, + one: u32, two: u32 } #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { pub fn rust_dbg_extern_identity_TwoU32s(v: TwoU32s) -> TwoU32s; } pub fn main() { unsafe { - let x = TwoU32s { one: 22, two: 23 }; + let x = TwoU32s {one: 22, two: 23}; let y = rust_dbg_extern_identity_TwoU32s(x); assert_eq!(x, y); } diff --git a/src/test/ui/abi/extern/extern-pass-TwoU64s.rs b/src/test/ui/abi/extern/extern-pass-TwoU64s.rs index 8bbc987c821b4..419648263aa9b 100644 --- a/src/test/ui/abi/extern/extern-pass-TwoU64s.rs +++ b/src/test/ui/abi/extern/extern-pass-TwoU64s.rs @@ -8,18 +8,17 @@ #[derive(Copy, Clone, PartialEq, Debug)] pub struct TwoU64s { - one: u64, - two: u64, + one: u64, two: u64 } #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { pub fn rust_dbg_extern_identity_TwoU64s(v: TwoU64s) -> TwoU64s; } pub fn main() { unsafe { - let x = TwoU64s { one: 22, two: 23 }; + let x = TwoU64s {one: 22, two: 23}; let y = rust_dbg_extern_identity_TwoU64s(x); assert_eq!(x, y); } diff --git a/src/test/ui/abi/extern/extern-pass-TwoU8s.rs b/src/test/ui/abi/extern/extern-pass-TwoU8s.rs index 55a53c250bf38..53a6a0f29f8a6 100644 --- a/src/test/ui/abi/extern/extern-pass-TwoU8s.rs +++ b/src/test/ui/abi/extern/extern-pass-TwoU8s.rs @@ -8,18 +8,17 @@ #[derive(Copy, Clone, PartialEq, Debug)] pub struct TwoU8s { - one: u8, - two: u8, + one: u8, two: u8 } #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { pub fn rust_dbg_extern_identity_TwoU8s(v: TwoU8s) -> TwoU8s; } pub fn main() { unsafe { - let x = TwoU8s { one: 22, two: 23 }; + let x = TwoU8s {one: 22, two: 23}; let y = rust_dbg_extern_identity_TwoU8s(x); assert_eq!(x, y); } diff --git a/src/test/ui/abi/extern/extern-pass-char.rs b/src/test/ui/abi/extern/extern-pass-char.rs index 2b10d26d1ddf2..22f841b45527e 100644 --- a/src/test/ui/abi/extern/extern-pass-char.rs +++ b/src/test/ui/abi/extern/extern-pass-char.rs @@ -3,8 +3,9 @@ // Test a function that takes/returns a u8. + #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { pub fn rust_dbg_extern_identity_u8(v: u8) -> u8; } diff --git a/src/test/ui/abi/extern/extern-pass-double.rs b/src/test/ui/abi/extern/extern-pass-double.rs index 0b556c99e8d0b..dbd0a2dfa4889 100644 --- a/src/test/ui/abi/extern/extern-pass-double.rs +++ b/src/test/ui/abi/extern/extern-pass-double.rs @@ -2,7 +2,7 @@ // ignore-wasm32-bare no libc for ffi testing #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { pub fn rust_dbg_extern_identity_double(v: f64) -> f64; } diff --git a/src/test/ui/abi/extern/extern-pass-empty.rs b/src/test/ui/abi/extern/extern-pass-empty.rs index ee974f6dbdeed..07099a2420483 100644 --- a/src/test/ui/abi/extern/extern-pass-empty.rs +++ b/src/test/ui/abi/extern/extern-pass-empty.rs @@ -27,7 +27,7 @@ struct ManyInts { struct Empty; #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { fn rust_dbg_extern_empty_struct(v1: ManyInts, e: Empty, v2: ManyInts); } @@ -39,7 +39,7 @@ pub fn main() { arg3: 4, arg4: 5, arg5: 6, - arg6: TwoU8s { one: 7, two: 8 }, + arg6: TwoU8s { one: 7, two: 8, } }; let y = ManyInts { arg1: 1, @@ -47,7 +47,7 @@ pub fn main() { arg3: 3, arg4: 4, arg5: 5, - arg6: TwoU8s { one: 6, two: 7 }, + arg6: TwoU8s { one: 6, two: 7, } }; let empty = Empty; rust_dbg_extern_empty_struct(x, empty, y); diff --git a/src/test/ui/abi/extern/extern-pass-u32.rs b/src/test/ui/abi/extern/extern-pass-u32.rs index c9b8d52cf5be9..f2efdb7d3664e 100644 --- a/src/test/ui/abi/extern/extern-pass-u32.rs +++ b/src/test/ui/abi/extern/extern-pass-u32.rs @@ -3,8 +3,9 @@ // Test a function that takes/returns a u32. + #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { pub fn rust_dbg_extern_identity_u32(v: u32) -> u32; } diff --git a/src/test/ui/abi/extern/extern-pass-u64.rs b/src/test/ui/abi/extern/extern-pass-u64.rs index 5103129abaa4d..975446d430c28 100644 --- a/src/test/ui/abi/extern/extern-pass-u64.rs +++ b/src/test/ui/abi/extern/extern-pass-u64.rs @@ -3,8 +3,9 @@ // Test a call to a function that takes/returns a u64. + #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { pub fn rust_dbg_extern_identity_u64(v: u64) -> u64; } diff --git a/src/test/ui/abi/extern/extern-return-TwoU16s.rs b/src/test/ui/abi/extern/extern-return-TwoU16s.rs index 2551c93a76541..dd884ee77fe77 100644 --- a/src/test/ui/abi/extern/extern-return-TwoU16s.rs +++ b/src/test/ui/abi/extern/extern-return-TwoU16s.rs @@ -4,12 +4,11 @@ // ignore-wasm32-bare no libc to test ffi with pub struct TwoU16s { - one: u16, - two: u16, + one: u16, two: u16 } #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { pub fn rust_dbg_extern_return_TwoU16s() -> TwoU16s; } diff --git a/src/test/ui/abi/extern/extern-return-TwoU32s.rs b/src/test/ui/abi/extern/extern-return-TwoU32s.rs index 70a42895d91df..d6aaf5c9eaf1b 100644 --- a/src/test/ui/abi/extern/extern-return-TwoU32s.rs +++ b/src/test/ui/abi/extern/extern-return-TwoU32s.rs @@ -4,12 +4,11 @@ // ignore-wasm32-bare no libc to test ffi with pub struct TwoU32s { - one: u32, - two: u32, + one: u32, two: u32 } #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { pub fn rust_dbg_extern_return_TwoU32s() -> TwoU32s; } diff --git a/src/test/ui/abi/extern/extern-return-TwoU64s.rs b/src/test/ui/abi/extern/extern-return-TwoU64s.rs index dd264fb9c196b..c5e4ebadc182a 100644 --- a/src/test/ui/abi/extern/extern-return-TwoU64s.rs +++ b/src/test/ui/abi/extern/extern-return-TwoU64s.rs @@ -4,12 +4,11 @@ // ignore-wasm32-bare no libc to test ffi with pub struct TwoU64s { - one: u64, - two: u64, + one: u64, two: u64 } #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { pub fn rust_dbg_extern_return_TwoU64s() -> TwoU64s; } diff --git a/src/test/ui/abi/extern/extern-return-TwoU8s.rs b/src/test/ui/abi/extern/extern-return-TwoU8s.rs index b60387aed99de..a7cd21b207359 100644 --- a/src/test/ui/abi/extern/extern-return-TwoU8s.rs +++ b/src/test/ui/abi/extern/extern-return-TwoU8s.rs @@ -4,12 +4,11 @@ // ignore-wasm32-bare no libc to test ffi with pub struct TwoU8s { - one: u8, - two: u8, + one: u8, two: u8 } #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { pub fn rust_dbg_extern_return_TwoU8s() -> TwoU8s; } diff --git a/src/test/ui/abi/foreign/auxiliary/foreign_lib.rs b/src/test/ui/abi/foreign/auxiliary/foreign_lib.rs index 3c649b778bd1a..de6b0e2118a58 100644 --- a/src/test/ui/abi/foreign/auxiliary/foreign_lib.rs +++ b/src/test/ui/abi/foreign/auxiliary/foreign_lib.rs @@ -1,11 +1,12 @@ -#![crate_name = "foreign_lib"] +#![crate_name="foreign_lib"] + #![feature(rustc_private)] pub mod rustrt { extern crate libc; #[link(name = "rust_test_helpers", kind = "static")] - extern "C" { + extern { pub fn rust_get_test_int() -> libc::intptr_t; } } @@ -13,7 +14,7 @@ pub mod rustrt { pub mod rustrt2 { extern crate libc; - extern "C" { + extern { pub fn rust_get_test_int() -> libc::intptr_t; } } @@ -23,7 +24,7 @@ pub mod rustrt3 { // Ensures that we don't ICE or trigger LLVM asserts when // importing the same symbol under different types. // See https://github.com/rust-lang/rust/issues/32740. - extern "C" { + extern { pub fn rust_get_test_int() -> *const u8; } } diff --git a/src/test/ui/abi/foreign/foreign-call-no-runtime.rs b/src/test/ui/abi/foreign/foreign-call-no-runtime.rs index d5b90a3592b3e..c6afa07ad0503 100644 --- a/src/test/ui/abi/foreign/foreign-call-no-runtime.rs +++ b/src/test/ui/abi/foreign/foreign-call-no-runtime.rs @@ -9,50 +9,45 @@ use std::mem; use std::thread; #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { - fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t), data: libc::uintptr_t) -> libc::uintptr_t; +extern { + fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t), + data: libc::uintptr_t) -> libc::uintptr_t; } pub fn main() { unsafe { - thread::spawn(move || { + thread::spawn(move|| { let i: isize = 100; rust_dbg_call(callback_isize, mem::transmute(&i)); - }) - .join() - .unwrap(); + }).join().unwrap(); - thread::spawn(move || { + thread::spawn(move|| { let i: i32 = 100; rust_dbg_call(callback_i32, mem::transmute(&i)); - }) - .join() - .unwrap(); + }).join().unwrap(); - thread::spawn(move || { + thread::spawn(move|| { let i: i64 = 100; rust_dbg_call(callback_i64, mem::transmute(&i)); - }) - .join() - .unwrap(); + }).join().unwrap(); } } -extern "C" fn callback_isize(data: libc::uintptr_t) { +extern fn callback_isize(data: libc::uintptr_t) { unsafe { let data: *const isize = mem::transmute(data); assert_eq!(*data, 100); } } -extern "C" fn callback_i64(data: libc::uintptr_t) { +extern fn callback_i64(data: libc::uintptr_t) { unsafe { let data: *const i64 = mem::transmute(data); assert_eq!(*data, 100); } } -extern "C" fn callback_i32(data: libc::uintptr_t) { +extern fn callback_i32(data: libc::uintptr_t) { unsafe { let data: *const i32 = mem::transmute(data); assert_eq!(*data, 100); diff --git a/src/test/ui/abi/foreign/foreign-fn-with-byval.rs b/src/test/ui/abi/foreign/foreign-fn-with-byval.rs index f366b6ee1bdd5..3a35599aa573f 100644 --- a/src/test/ui/abi/foreign/foreign-fn-with-byval.rs +++ b/src/test/ui/abi/foreign/foreign-fn-with-byval.rs @@ -11,15 +11,17 @@ pub struct S { } #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { pub fn get_x(x: S) -> u64; pub fn get_y(x: S) -> u64; pub fn get_z(x: S) -> u64; } #[inline(never)] -fn indirect_call(func: unsafe extern "C" fn(s: S) -> u64, s: S) -> u64 { - unsafe { func(s) } +fn indirect_call(func: unsafe extern fn(s: S) -> u64, s: S) -> u64 { + unsafe { + func(s) + } } fn main() { diff --git a/src/test/ui/abi/foreign/foreign-no-abi.rs b/src/test/ui/abi/foreign/foreign-no-abi.rs index 3f4f70c99e6a8..2f33fb4765690 100644 --- a/src/test/ui/abi/foreign/foreign-no-abi.rs +++ b/src/test/ui/abi/foreign/foreign-no-abi.rs @@ -10,7 +10,7 @@ mod rustrt { extern crate libc; #[link(name = "rust_test_helpers", kind = "static")] - extern "C" { + extern { pub fn rust_get_test_int() -> libc::intptr_t; } } diff --git a/src/test/ui/abi/issues/issue-62350-sysv-neg-reg-counts.rs b/src/test/ui/abi/issues/issue-62350-sysv-neg-reg-counts.rs index 29b2405189cc3..df819306e4aa2 100644 --- a/src/test/ui/abi/issues/issue-62350-sysv-neg-reg-counts.rs +++ b/src/test/ui/abi/issues/issue-62350-sysv-neg-reg-counts.rs @@ -5,18 +5,13 @@ // ignore-wasm32-bare no libc to test ffi with #[derive(Copy, Clone)] -pub struct QuadFloats { - a: f32, - b: f32, - c: f32, - d: f32, -} +pub struct QuadFloats { a: f32, b: f32, c: f32, d: f32 } mod rustrt { use super::QuadFloats; #[link(name = "rust_test_helpers", kind = "static")] - extern "C" { + extern { pub fn get_c_exhaust_sysv64_ints( _: *const (), _: *const (), @@ -33,7 +28,12 @@ mod rustrt { fn test() { unsafe { let null = std::ptr::null(); - let q = QuadFloats { a: 10.2, b: 20.3, c: 30.4, d: 40.5 }; + let q = QuadFloats { + a: 10.2, + b: 20.3, + c: 30.4, + d: 40.5 + }; assert_eq!( rustrt::get_c_exhaust_sysv64_ints(null, null, null, null, null, null, null, q), q.c, diff --git a/src/test/ui/abi/mir/mir_codegen_calls_variadic.rs b/src/test/ui/abi/mir/mir_codegen_calls_variadic.rs index b3392b9c60715..dc9fee03b776c 100644 --- a/src/test/ui/abi/mir/mir_codegen_calls_variadic.rs +++ b/src/test/ui/abi/mir/mir_codegen_calls_variadic.rs @@ -2,18 +2,21 @@ // ignore-wasm32-bare no libc to test ffi with #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { fn rust_interesting_average(_: i64, ...) -> f64; } fn test(a: i64, b: i64, c: i64, d: i64, e: i64, f: T, g: U) -> i64 { unsafe { - rust_interesting_average( - 6, a, a as f64, b, b as f64, c, c as f64, d, d as f64, e, e as f64, f, g, - ) as i64 + rust_interesting_average(6, a, a as f64, + b, b as f64, + c, c as f64, + d, d as f64, + e, e as f64, + f, g) as i64 } } -fn main() { +fn main(){ assert_eq!(test(10, 20, 30, 40, 50, 60_i64, 60.0_f64), 70); } diff --git a/src/test/ui/abi/segfault-no-out-of-stack.rs b/src/test/ui/abi/segfault-no-out-of-stack.rs index ad4faf95a0f95..0128e5e636d34 100644 --- a/src/test/ui/abi/segfault-no-out-of-stack.rs +++ b/src/test/ui/abi/segfault-no-out-of-stack.rs @@ -3,37 +3,39 @@ #![allow(unused_imports)] // ignore-emscripten can't run commands // ignore-sgx no processes + #![feature(rustc_private)] extern crate libc; -use std::env; use std::process::{Command, ExitStatus}; +use std::env; #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { fn rust_get_null_ptr() -> *mut ::libc::c_char; } #[cfg(unix)] -fn check_status(status: std::process::ExitStatus) { +fn check_status(status: std::process::ExitStatus) +{ use libc; use std::os::unix::process::ExitStatusExt; - assert!(status.signal() == Some(libc::SIGSEGV) || status.signal() == Some(libc::SIGBUS)); + assert!(status.signal() == Some(libc::SIGSEGV) + || status.signal() == Some(libc::SIGBUS)); } #[cfg(not(unix))] -fn check_status(status: std::process::ExitStatus) { +fn check_status(status: std::process::ExitStatus) +{ assert!(!status.success()); } fn main() { let args: Vec = env::args().collect(); if args.len() > 1 && args[1] == "segfault" { - unsafe { - *rust_get_null_ptr() = 1; - }; // trigger a segfault + unsafe { *rust_get_null_ptr() = 1; }; // trigger a segfault } else { let segfault = Command::new(&args[0]).arg("segfault").output().unwrap(); let stderr = String::from_utf8_lossy(&segfault.stderr); diff --git a/src/test/ui/abi/stack-probes.rs b/src/test/ui/abi/stack-probes.rs index e998dd0f83ebc..6c83e01d4cdb5 100644 --- a/src/test/ui/abi/stack-probes.rs +++ b/src/test/ui/abi/stack-probes.rs @@ -11,13 +11,13 @@ // ignore-emscripten no processes // ignore-sgx no processes -use std::env; use std::mem::MaybeUninit; use std::process::Command; use std::thread; +use std::env; #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { #[link_name = "rust_dbg_extern_identity_u64"] fn black_box(u: u64); } @@ -30,7 +30,7 @@ fn main() { "child-thread" => thread::spawn(|| recurse(&MaybeUninit::uninit())).join().unwrap(), _ => panic!(), } - return; + return } let me = env::current_exe().unwrap(); diff --git a/src/test/ui/abi/statics/static-mut-foreign.rs b/src/test/ui/abi/statics/static-mut-foreign.rs index ecd8ee94a01e3..5d6fa416b9895 100644 --- a/src/test/ui/abi/statics/static-mut-foreign.rs +++ b/src/test/ui/abi/statics/static-mut-foreign.rs @@ -10,7 +10,7 @@ extern crate libc; #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { static mut rust_dbg_static_mut: libc::c_int; pub fn rust_dbg_static_mut_check_four(); } diff --git a/src/test/ui/abi/struct-enums/struct-return.rs b/src/test/ui/abi/struct-enums/struct-return.rs index 1a7984ea5cd17..a3e70bbdb0809 100644 --- a/src/test/ui/abi/struct-enums/struct-return.rs +++ b/src/test/ui/abi/struct-enums/struct-return.rs @@ -4,42 +4,25 @@ #[repr(C)] #[derive(Copy, Clone)] -pub struct Quad { - a: u64, - b: u64, - c: u64, - d: u64, -} +pub struct Quad { a: u64, b: u64, c: u64, d: u64 } #[repr(C)] #[derive(Copy, Clone)] -pub struct Floats { - a: f64, - b: u8, - c: f64, -} +pub struct Floats { a: f64, b: u8, c: f64 } #[repr(C)] #[derive(Copy, Clone)] -pub struct CharCharDouble { - a: u8, - b: u8, - c: f64, -} +pub struct CharCharDouble { a: u8, b: u8, c: f64 } #[repr(C)] #[derive(Copy, Clone)] -pub struct CharCharFloat { - a: u8, - b: u8, - c: f32, -} +pub struct CharCharFloat { a: u8, b: u8, c: f32 } mod rustrt { - use super::{CharCharDouble, CharCharFloat, Floats, Quad}; + use super::{Floats, Quad, CharCharDouble, CharCharFloat}; #[link(name = "rust_test_helpers", kind = "static")] - extern "C" { + extern { pub fn rust_dbg_abi_1(q: Quad) -> Quad; pub fn rust_dbg_abi_2(f: Floats) -> Floats; pub fn rust_dbg_abi_3(a: CharCharDouble) -> CharCharDouble; @@ -49,12 +32,10 @@ mod rustrt { fn test1() { unsafe { - let q = Quad { - a: 0xaaaa_aaaa_aaaa_aaaa, - b: 0xbbbb_bbbb_bbbb_bbbb, - c: 0xcccc_cccc_cccc_cccc, - d: 0xdddd_dddd_dddd_dddd, - }; + let q = Quad { a: 0xaaaa_aaaa_aaaa_aaaa, + b: 0xbbbb_bbbb_bbbb_bbbb, + c: 0xcccc_cccc_cccc_cccc, + d: 0xdddd_dddd_dddd_dddd }; let qq = rustrt::rust_dbg_abi_1(q); println!("a: {:x}", qq.a as usize); println!("b: {:x}", qq.b as usize); @@ -70,7 +51,9 @@ fn test1() { #[cfg(target_pointer_width = "64")] fn test2() { unsafe { - let f = Floats { a: 1.234567890e-15_f64, b: 0b_1010_1010, c: 1.0987654321e-15_f64 }; + let f = Floats { a: 1.234567890e-15_f64, + b: 0b_1010_1010, + c: 1.0987654321e-15_f64 }; let ff = rustrt::rust_dbg_abi_2(f); println!("a: {}", ff.a as f64); println!("b: {}", ff.b as usize); @@ -82,12 +65,17 @@ fn test2() { } #[cfg(target_pointer_width = "32")] -fn test2() {} +fn test2() { +} #[cfg(target_pointer_width = "64")] fn test3() { unsafe { - let a = CharCharDouble { a: 1, b: 2, c: 3. }; + let a = CharCharDouble { + a: 1, + b: 2, + c: 3., + }; let b = rustrt::rust_dbg_abi_3(a); println!("a: {}", b.a); println!("b: {}", b.b); @@ -103,7 +91,11 @@ fn test3() {} fn test4() { unsafe { - let a = CharCharFloat { a: 1, b: 2, c: 3. }; + let a = CharCharFloat { + a: 1, + b: 2, + c: 3., + }; let b = rustrt::rust_dbg_abi_4(a); println!("a: {}", b.a); println!("b: {}", b.b); diff --git a/src/test/ui/abi/variadic-ffi.rs b/src/test/ui/abi/variadic-ffi.rs index a952ea0779329..3232a11d726e5 100644 --- a/src/test/ui/abi/variadic-ffi.rs +++ b/src/test/ui/abi/variadic-ffi.rs @@ -5,7 +5,7 @@ use std::ffi::VaList; #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { fn rust_interesting_average(_: u64, ...) -> f64; // FIXME: we need to disable this lint for `VaList`, @@ -61,7 +61,7 @@ pub fn main() { } // A function that takes a function pointer - unsafe fn call(fp: unsafe extern "C" fn(u64, ...) -> f64) { + unsafe fn call(fp: unsafe extern fn(u64, ...) -> f64) { let (x1, x2, x3, x4) = (10i64, 10.0f64, 20i64, 20.0f64); assert_eq!(fp(2, x1, x2, x3, x4) as i64, 30); } @@ -70,7 +70,7 @@ pub fn main() { call(rust_interesting_average); // Make a function pointer, pass indirectly - let x: unsafe extern "C" fn(u64, ...) -> f64 = rust_interesting_average; + let x: unsafe extern fn(u64, ...) -> f64 = rust_interesting_average; call(x); } diff --git a/src/test/ui/associated-item/associated-item-two-bounds.rs b/src/test/ui/associated-item/associated-item-two-bounds.rs deleted file mode 100644 index 25b0d5a56bfb3..0000000000000 --- a/src/test/ui/associated-item/associated-item-two-bounds.rs +++ /dev/null @@ -1,16 +0,0 @@ -// This test is a regression test for #34792 - -// check-pass - -pub struct A; -pub struct B; - -pub trait Foo { - type T: PartialEq
+ PartialEq; -} - -pub fn generic(t: F::T, a: A, b: B) -> bool { - t == a && t == b -} - -pub fn main() {} diff --git a/src/test/ui/associated-types/higher-ranked-projection.bad.stderr b/src/test/ui/associated-types/higher-ranked-projection.bad.stderr index e2847b6b72b86..811c9a8f5e12b 100644 --- a/src/test/ui/associated-types/higher-ranked-projection.bad.stderr +++ b/src/test/ui/associated-types/higher-ranked-projection.bad.stderr @@ -2,15 +2,10 @@ error[E0308]: mismatched types --> $DIR/higher-ranked-projection.rs:25:5 | LL | foo(()); - | ^^^ lifetime mismatch + | ^^^ one type is more general than the other | = note: expected type `&'a ()` found type `&()` -note: the lifetime requirement is introduced here - --> $DIR/higher-ranked-projection.rs:15:33 - | -LL | where for<'a> &'a T: Mirror - | ^^^^^^^ error: aborting due to previous error diff --git a/src/test/ui/async-await/issues/issue-65159.rs b/src/test/ui/async-await/issues/issue-65159.rs index ce3fa9180cb9e..4f160fccc0113 100644 --- a/src/test/ui/async-await/issues/issue-65159.rs +++ b/src/test/ui/async-await/issues/issue-65159.rs @@ -2,8 +2,7 @@ // // edition:2018 -async fn copy() -> Result<()> -//~^ ERROR this enum takes 2 type arguments but only 1 type argument was supplied +async fn copy() -> Result<()> //~ ERROR wrong number of type arguments { Ok(()) //~^ ERROR type annotations needed diff --git a/src/test/ui/async-await/issues/issue-65159.stderr b/src/test/ui/async-await/issues/issue-65159.stderr index bcb4c292e2626..04cfa5249982e 100644 --- a/src/test/ui/async-await/issues/issue-65159.stderr +++ b/src/test/ui/async-await/issues/issue-65159.stderr @@ -1,23 +1,11 @@ -error[E0107]: this enum takes 2 type arguments but only 1 type argument was supplied +error[E0107]: wrong number of type arguments: expected 2, found 1 --> $DIR/issue-65159.rs:5:20 | LL | async fn copy() -> Result<()> - | ^^^^^^ -- supplied 1 type argument - | | - | expected 2 type arguments - | -note: enum defined here, with 2 type parameters: `T`, `E` - --> $SRC_DIR/core/src/result.rs:LL:COL - | -LL | pub enum Result { - | ^^^^^^ - - -help: add missing type argument - | -LL | async fn copy() -> Result<(), E> - | ^^^ + | ^^^^^^^^^^ expected 2 type arguments error[E0282]: type annotations needed - --> $DIR/issue-65159.rs:8:5 + --> $DIR/issue-65159.rs:7:5 | LL | Ok(()) | ^^ cannot infer type for type parameter `E` declared on the enum `Result` diff --git a/src/test/ui/async-await/issues/issue-78938-async-block.rs b/src/test/ui/async-await/issues/issue-78938-async-block.rs deleted file mode 100644 index 36f7160198526..0000000000000 --- a/src/test/ui/async-await/issues/issue-78938-async-block.rs +++ /dev/null @@ -1,33 +0,0 @@ -// edition:2018 - -use std::{sync::Arc, future::Future, pin::Pin, task::{Context, Poll}}; - -async fn f() { - let room_ref = Arc::new(Vec::new()); - - let gameloop_handle = spawn(async { //~ ERROR E0373 - game_loop(Arc::clone(&room_ref)) - }); - gameloop_handle.await; -} - -fn game_loop(v: Arc>) {} - -fn spawn(future: F) -> JoinHandle -where - F: Future + Send + 'static, - F::Output: Send + 'static, -{ - loop {} -} - -struct JoinHandle; - -impl Future for JoinHandle { - type Output = (); - fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { - loop {} - } -} - -fn main() {} diff --git a/src/test/ui/async-await/issues/issue-78938-async-block.stderr b/src/test/ui/async-await/issues/issue-78938-async-block.stderr deleted file mode 100644 index 01ffc48d6542e..0000000000000 --- a/src/test/ui/async-await/issues/issue-78938-async-block.stderr +++ /dev/null @@ -1,21 +0,0 @@ -error[E0373]: async block may outlive the current function, but it borrows `room_ref`, which is owned by the current function - --> $DIR/issue-78938-async-block.rs:8:39 - | -LL | let gameloop_handle = spawn(async { - | _______________________________________^ -LL | | game_loop(Arc::clone(&room_ref)) - | | -------- `room_ref` is borrowed here -LL | | }); - | |_____^ may outlive borrowed value `room_ref` - | - = note: async blocks are not executed immediately and must either take a reference or ownership of outside variables they use -help: to force the async block to take ownership of `room_ref` (and any other referenced variables), use the `move` keyword - | -LL | let gameloop_handle = spawn(async move { -LL | game_loop(Arc::clone(&room_ref)) -LL | }); - | - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0373`. diff --git a/src/test/ui/async-await/unused-lifetime.rs b/src/test/ui/async-await/unused-lifetime.rs index 5bd6ae8d3a42d..1cf546bcb4266 100644 --- a/src/test/ui/async-await/unused-lifetime.rs +++ b/src/test/ui/async-await/unused-lifetime.rs @@ -1,47 +1,42 @@ -// Check "unused_lifetimes" lint on both async and sync functions - // edition:2018 -#![deny(unused_lifetimes)] - - -// Async part with unused lifetimes -// -// Even wrong cases don't cause errors because async functions are desugared with all lifetimes -// involved in the signature. So, we cannot predict what lifetimes are unused in async function. -async fn async_wrong_without_args<'a>() {} - -async fn async_wrong_1_lifetime<'a>(_: &i32) {} - -async fn async_wrong_2_lifetimes<'a, 'b>(_: &'a i32, _: &i32) {} - -async fn async_right_1_lifetime<'a>(_: &'a i32) {} - -async fn async_right_2_lifetimes<'a, 'b>(_: &'a i32, _: &'b i32) {} - -async fn async_right_trait_bound_lifetime<'a, I>(_: I) -where - I: Iterator -{} - - -// Sync part with unused lifetimes -// -// These functions are compiled as supposed -fn wrong_without_args<'a>() {} //~ ERROR lifetime parameter `'a` never used - -fn wrong_1_lifetime<'a>(_: &i32) {} //~ ERROR lifetime parameter `'a` never used - -fn wrong_2_lifetimes<'a, 'b>(_: &'a i32, _: &i32) {} //~ ERROR lifetime parameter `'b` never used - -fn right_1_lifetime<'a>(_: &'a i32) {} - -fn right_2_lifetimes<'a, 'b>(_: &'a i32, _: &'b i32) {} - -fn right_trait_bound_lifetime<'a, I>(_: I) -where - I: Iterator -{} +// Avoid spurious warnings of unused lifetime. The below async functions +// are desugered to have an unused lifetime +// but we don't want to warn about that as there's nothing they can do about it. +#![deny(unused_lifetimes)] +#![allow(dead_code)] + +pub async fn october(s: &str) { + println!("{}", s); +} + +pub async fn async_fn(&mut ref s: &mut[i32]) { + println!("{:?}", s); +} + +macro_rules! foo_macro { + () => { + pub async fn async_fn_in_macro(&mut ref _s: &mut[i32]) {} + }; +} + +foo_macro!(); + +pub async fn func_with_unused_lifetime<'a>(s: &'a str) { + //~^ ERROR lifetime parameter `'a` never used + println!("{}", s); +} + +pub async fn func_with_two_unused_lifetime<'a, 'b>(s: &'a str, t: &'b str) { + //~^ ERROR lifetime parameter `'a` never used + //~^^ ERROR lifetime parameter `'b` never used + println!("{}", s); +} + +pub async fn func_with_unused_lifetime_in_two_params<'c>(s: &'c str, t: &'c str) { + //~^ ERROR lifetime parameter `'c` never used + println!("{}", s); +} fn main() {} diff --git a/src/test/ui/async-await/unused-lifetime.stderr b/src/test/ui/async-await/unused-lifetime.stderr index 4e90f43fdd07b..2a7a12a364346 100644 --- a/src/test/ui/async-await/unused-lifetime.stderr +++ b/src/test/ui/async-await/unused-lifetime.stderr @@ -1,28 +1,32 @@ error: lifetime parameter `'a` never used - --> $DIR/unused-lifetime.rs:31:23 + --> $DIR/unused-lifetime.rs:26:40 | -LL | fn wrong_without_args<'a>() {} - | -^^- help: elide the unused lifetime +LL | pub async fn func_with_unused_lifetime<'a>(s: &'a str) { + | ^^ | note: the lint level is defined here - --> $DIR/unused-lifetime.rs:5:9 + --> $DIR/unused-lifetime.rs:7:9 | LL | #![deny(unused_lifetimes)] | ^^^^^^^^^^^^^^^^ error: lifetime parameter `'a` never used - --> $DIR/unused-lifetime.rs:33:21 + --> $DIR/unused-lifetime.rs:31:44 | -LL | fn wrong_1_lifetime<'a>(_: &i32) {} - | -^^- help: elide the unused lifetime +LL | pub async fn func_with_two_unused_lifetime<'a, 'b>(s: &'a str, t: &'b str) { + | ^^ error: lifetime parameter `'b` never used - --> $DIR/unused-lifetime.rs:35:26 + --> $DIR/unused-lifetime.rs:31:48 | -LL | fn wrong_2_lifetimes<'a, 'b>(_: &'a i32, _: &i32) {} - | --^^ - | | - | help: elide the unused lifetime +LL | pub async fn func_with_two_unused_lifetime<'a, 'b>(s: &'a str, t: &'b str) { + | ^^ -error: aborting due to 3 previous errors +error: lifetime parameter `'c` never used + --> $DIR/unused-lifetime.rs:37:54 + | +LL | pub async fn func_with_unused_lifetime_in_two_params<'c>(s: &'c str, t: &'c str) { + | ^^ + +error: aborting due to 4 previous errors diff --git a/src/test/ui/attributes/item-attributes.rs b/src/test/ui/attributes/item-attributes.rs index c6bf6c6560277..a3d5933965a41 100644 --- a/src/test/ui/attributes/item-attributes.rs +++ b/src/test/ui/attributes/item-attributes.rs @@ -5,6 +5,7 @@ // check-pass #![feature(rustc_attrs)] + #![rustc_dummy = "val"] #![rustc_dummy = "val"] #![rustc_dummy] @@ -20,14 +21,14 @@ mod test_single_attr_outer { pub static X: isize = 10; #[rustc_dummy = "val"] - pub fn f() {} + pub fn f() { } #[rustc_dummy = "val"] pub mod mod1 {} pub mod rustrt { #[rustc_dummy = "val"] - extern "C" {} + extern {} } } @@ -38,7 +39,7 @@ mod test_multi_attr_outer { #[rustc_dummy = "val"] #[rustc_dummy = "val"] - pub fn f() {} + pub fn f() { } #[rustc_dummy = "val"] #[rustc_dummy = "val"] @@ -47,14 +48,12 @@ mod test_multi_attr_outer { pub mod rustrt { #[rustc_dummy = "val"] #[rustc_dummy = "val"] - extern "C" {} + extern {} } #[rustc_dummy = "val"] #[rustc_dummy = "val"] - struct T { - x: isize, - } + struct T {x: isize} } mod test_stmt_single_attr_outer { @@ -63,36 +62,41 @@ mod test_stmt_single_attr_outer { static X: isize = 10; #[rustc_dummy = "val"] - fn f() {} + fn f() { } #[rustc_dummy = "val"] - mod mod1 {} + mod mod1 { + } mod rustrt { #[rustc_dummy = "val"] - extern "C" {} + extern { + } } } } mod test_stmt_multi_attr_outer { pub fn f() { + #[rustc_dummy = "val"] #[rustc_dummy = "val"] static X: isize = 10; #[rustc_dummy = "val"] #[rustc_dummy = "val"] - fn f() {} + fn f() { } #[rustc_dummy = "val"] #[rustc_dummy = "val"] - mod mod1 {} + mod mod1 { + } mod rustrt { #[rustc_dummy = "val"] #[rustc_dummy = "val"] - extern "C" {} + extern { + } } } } @@ -110,7 +114,7 @@ mod test_attr_inner_then_outer { #![rustc_dummy = "val"] // This is an attribute of fn f #[rustc_dummy = "val"] - fn f() {} + fn f() { } } } @@ -122,7 +126,7 @@ mod test_attr_inner_then_outer_multi { // This is an attribute of fn f #[rustc_dummy = "val"] #[rustc_dummy = "val"] - fn f() {} + fn f() { } } } @@ -130,7 +134,7 @@ mod test_distinguish_syntax_ext { pub fn f() { format!("test{}", "s"); #[rustc_dummy = "val"] - fn g() {} + fn g() { } } } @@ -139,12 +143,12 @@ mod test_other_forms { #[rustc_dummy(word)] #[rustc_dummy(attr(word))] #[rustc_dummy(key1 = "val", key2 = "val", attr)] - pub fn f() {} + pub fn f() { } } mod test_foreign_items { pub mod rustrt { - extern "C" { + extern { #![rustc_dummy] #[rustc_dummy] @@ -153,6 +157,7 @@ mod test_foreign_items { } } + // FIXME(#623): - these aren't supported yet /*mod test_literals { #![str = "s"] diff --git a/src/test/ui/attributes/obsolete-attr.rs b/src/test/ui/attributes/obsolete-attr.rs index 7019abcaffbae..42f90eda166b6 100644 --- a/src/test/ui/attributes/obsolete-attr.rs +++ b/src/test/ui/attributes/obsolete-attr.rs @@ -1,6 +1,6 @@ // Obsolete attributes fall back to unstable custom attributes. -#[ab_isize = "stdcall"] extern "C" {} +#[ab_isize="stdcall"] extern {} //~^ ERROR cannot find attribute `ab_isize` in this scope #[fixed_stack_segment] fn f() {} diff --git a/src/test/ui/attributes/obsolete-attr.stderr b/src/test/ui/attributes/obsolete-attr.stderr index 37c1cd0c94df2..2d7c257c6208c 100644 --- a/src/test/ui/attributes/obsolete-attr.stderr +++ b/src/test/ui/attributes/obsolete-attr.stderr @@ -7,7 +7,7 @@ LL | #[fixed_stack_segment] fn f() {} error: cannot find attribute `ab_isize` in this scope --> $DIR/obsolete-attr.rs:3:3 | -LL | #[ab_isize = "stdcall"] extern "C" {} +LL | #[ab_isize="stdcall"] extern {} | ^^^^^^^^ error: aborting due to 2 previous errors diff --git a/src/test/ui/auxiliary/extern-statics.rs b/src/test/ui/auxiliary/extern-statics.rs index c090bc79fce83..725fde518d81f 100644 --- a/src/test/ui/auxiliary/extern-statics.rs +++ b/src/test/ui/auxiliary/extern-statics.rs @@ -1,4 +1,4 @@ -extern "C" { +extern { pub static XA: u8; pub static mut XB: u8; } diff --git a/src/test/ui/auxiliary/link-cfg-works-transitive-dylib.rs b/src/test/ui/auxiliary/link-cfg-works-transitive-dylib.rs index 0d927117d81d3..fa4f33bcef669 100644 --- a/src/test/ui/auxiliary/link-cfg-works-transitive-dylib.rs +++ b/src/test/ui/auxiliary/link-cfg-works-transitive-dylib.rs @@ -1,4 +1,4 @@ #![feature(link_cfg)] #[link(name = "foo", cfg(foo))] -extern "C" {} +extern {} diff --git a/src/test/ui/auxiliary/link-cfg-works-transitive-rlib.rs b/src/test/ui/auxiliary/link-cfg-works-transitive-rlib.rs index 0a296f0b2ef4c..b365ed9173251 100644 --- a/src/test/ui/auxiliary/link-cfg-works-transitive-rlib.rs +++ b/src/test/ui/auxiliary/link-cfg-works-transitive-rlib.rs @@ -4,4 +4,4 @@ #![crate_type = "rlib"] #[link(name = "foo", cfg(foo))] -extern "C" {} +extern {} diff --git a/src/test/ui/auxiliary/lto-duplicate-symbols1.rs b/src/test/ui/auxiliary/lto-duplicate-symbols1.rs index ec6d056035784..9d510f2626f3a 100644 --- a/src/test/ui/auxiliary/lto-duplicate-symbols1.rs +++ b/src/test/ui/auxiliary/lto-duplicate-symbols1.rs @@ -3,4 +3,4 @@ #![crate_type = "rlib"] #[no_mangle] -pub extern "C" fn foo() {} +pub extern fn foo() {} diff --git a/src/test/ui/auxiliary/lto-duplicate-symbols2.rs b/src/test/ui/auxiliary/lto-duplicate-symbols2.rs index ec6d056035784..9d510f2626f3a 100644 --- a/src/test/ui/auxiliary/lto-duplicate-symbols2.rs +++ b/src/test/ui/auxiliary/lto-duplicate-symbols2.rs @@ -3,4 +3,4 @@ #![crate_type = "rlib"] #[no_mangle] -pub extern "C" fn foo() {} +pub extern fn foo() {} diff --git a/src/test/ui/bad/bad-extern-link-attrs.rs b/src/test/ui/bad/bad-extern-link-attrs.rs index 43fe8c11d7c48..f042832fba082 100644 --- a/src/test/ui/bad/bad-extern-link-attrs.rs +++ b/src/test/ui/bad/bad-extern-link-attrs.rs @@ -2,6 +2,6 @@ #[link(name = "")] //~ ERROR: with empty name #[link(name = "foo")] #[link(name = "foo", kind = "bar")] //~ ERROR: unknown kind -extern "C" {} +extern {} fn main() {} diff --git a/src/test/ui/bad/bad-mid-path-type-params.rs b/src/test/ui/bad/bad-mid-path-type-params.rs index c42ce602e9987..016b1d617e0f6 100644 --- a/src/test/ui/bad/bad-mid-path-type-params.rs +++ b/src/test/ui/bad/bad-mid-path-type-params.rs @@ -28,17 +28,16 @@ impl Trait for S2 { fn foo<'a>() { let _ = S::new::(1, 1.0); - //~^ ERROR this associated function takes 1 type argument but 2 type arguments were supplied + //~^ ERROR wrong number of type arguments let _ = S::<'a,isize>::new::(1, 1.0); - //~^ ERROR this struct takes 0 lifetime arguments but 1 lifetime argument was supplied + //~^ ERROR wrong number of lifetime arguments let _: S2 = Trait::new::(1, 1.0); - //~^ ERROR this associated function takes 1 type argument but 2 type arguments were supplied + //~^ ERROR wrong number of type arguments - let _: S2 = Trait::<'a,isize>::new::(1, 1.0); - //~^ ERROR this trait takes 0 lifetime arguments but 1 lifetime argument was supplied - //~| ERROR this associated function takes 1 type argument but 2 type arguments were supplied + let _: S2 = Trait::<'a,isize>::new::(1, 1.0); + //~^ ERROR wrong number of lifetime arguments } fn main() {} diff --git a/src/test/ui/bad/bad-mid-path-type-params.stderr b/src/test/ui/bad/bad-mid-path-type-params.stderr index dd96856e56324..ef53c9a38c7ca 100644 --- a/src/test/ui/bad/bad-mid-path-type-params.stderr +++ b/src/test/ui/bad/bad-mid-path-type-params.stderr @@ -1,73 +1,27 @@ -error[E0107]: this associated function takes 1 type argument but 2 type arguments were supplied - --> $DIR/bad-mid-path-type-params.rs:30:16 +error[E0107]: wrong number of type arguments: expected 1, found 2 + --> $DIR/bad-mid-path-type-params.rs:30:28 | LL | let _ = S::new::(1, 1.0); - | ^^^ ---- help: remove this type argument - | | - | expected 1 type argument - | -note: associated function defined here, with 1 type parameter: `U` - --> $DIR/bad-mid-path-type-params.rs:6:8 - | -LL | fn new(x: T, _: U) -> S { - | ^^^ - + | ^^^ unexpected type argument -error[E0107]: this struct takes 0 lifetime arguments but 1 lifetime argument was supplied - --> $DIR/bad-mid-path-type-params.rs:33:13 +error[E0107]: wrong number of lifetime arguments: expected 0, found 1 + --> $DIR/bad-mid-path-type-params.rs:33:17 | LL | let _ = S::<'a,isize>::new::(1, 1.0); - | ^ --- help: remove this lifetime argument - | | - | expected 0 lifetime arguments - | -note: struct defined here, with 0 lifetime parameters - --> $DIR/bad-mid-path-type-params.rs:1:8 - | -LL | struct S { - | ^ + | ^^ unexpected lifetime argument -error[E0107]: this associated function takes 1 type argument but 2 type arguments were supplied - --> $DIR/bad-mid-path-type-params.rs:36:24 +error[E0107]: wrong number of type arguments: expected 1, found 2 + --> $DIR/bad-mid-path-type-params.rs:36:36 | LL | let _: S2 = Trait::new::(1, 1.0); - | ^^^ ---- help: remove this type argument - | | - | expected 1 type argument - | -note: associated function defined here, with 1 type parameter: `U` - --> $DIR/bad-mid-path-type-params.rs:14:8 - | -LL | fn new(x: T, y: U) -> Self; - | ^^^ - + | ^^^ unexpected type argument -error[E0107]: this trait takes 0 lifetime arguments but 1 lifetime argument was supplied - --> $DIR/bad-mid-path-type-params.rs:39:17 - | -LL | let _: S2 = Trait::<'a,isize>::new::(1, 1.0); - | ^^^^^ --- help: remove this lifetime argument - | | - | expected 0 lifetime arguments - | -note: trait defined here, with 0 lifetime parameters - --> $DIR/bad-mid-path-type-params.rs:13:7 - | -LL | trait Trait { - | ^^^^^ - -error[E0107]: this associated function takes 1 type argument but 2 type arguments were supplied - --> $DIR/bad-mid-path-type-params.rs:39:36 - | -LL | let _: S2 = Trait::<'a,isize>::new::(1, 1.0); - | ^^^ ---- help: remove this type argument - | | - | expected 1 type argument - | -note: associated function defined here, with 1 type parameter: `U` - --> $DIR/bad-mid-path-type-params.rs:14:8 +error[E0107]: wrong number of lifetime arguments: expected 0, found 1 + --> $DIR/bad-mid-path-type-params.rs:39:25 | -LL | fn new(x: T, y: U) -> Self; - | ^^^ - +LL | let _: S2 = Trait::<'a,isize>::new::(1, 1.0); + | ^^ unexpected lifetime argument -error: aborting due to 5 previous errors +error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0107`. diff --git a/src/test/ui/borrowck/move-in-pattern-mut-in-loop.rs b/src/test/ui/borrowck/move-in-pattern-mut-in-loop.rs deleted file mode 100644 index 4b42f9d4cd580..0000000000000 --- a/src/test/ui/borrowck/move-in-pattern-mut-in-loop.rs +++ /dev/null @@ -1,10 +0,0 @@ -// Regression test for #80913. - -fn main() { - let mut x = 42_i32; - let mut opt = Some(&mut x); - for _ in 0..5 { - if let Some(mut _x) = opt {} - //~^ ERROR: use of moved value - } -} diff --git a/src/test/ui/borrowck/move-in-pattern-mut-in-loop.stderr b/src/test/ui/borrowck/move-in-pattern-mut-in-loop.stderr deleted file mode 100644 index 9373e4d95fccd..0000000000000 --- a/src/test/ui/borrowck/move-in-pattern-mut-in-loop.stderr +++ /dev/null @@ -1,15 +0,0 @@ -error[E0382]: use of moved value - --> $DIR/move-in-pattern-mut-in-loop.rs:7:21 - | -LL | if let Some(mut _x) = opt {} - | ^^^^^^ value moved here, in previous iteration of loop - | - = note: move occurs because value has type `&mut i32`, which does not implement the `Copy` trait -help: borrow this field in the pattern to avoid moving `opt.0` - | -LL | if let Some(ref mut _x) = opt {} - | ^^^ - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0382`. diff --git a/src/test/ui/c-stack-returning-int64.rs b/src/test/ui/c-stack-returning-int64.rs index fb3cb2083e4b9..388d280b831b4 100644 --- a/src/test/ui/c-stack-returning-int64.rs +++ b/src/test/ui/c-stack-returning-int64.rs @@ -11,7 +11,7 @@ use std::ffi::CString; mod mlibc { use libc::{c_char, c_long, c_longlong}; - extern "C" { + extern { pub fn atol(x: *const c_char) -> c_long; pub fn atoll(x: *const c_char) -> c_longlong; } @@ -29,8 +29,6 @@ fn atoll(s: String) -> i64 { pub fn main() { assert_eq!(atol("1024".to_string()) * 10, atol("10240".to_string())); - assert_eq!( - (atoll("11111111111111111".to_string()) * 10), - atoll("111111111111111110".to_string()) - ); + assert_eq!((atoll("11111111111111111".to_string()) * 10), + atoll("111111111111111110".to_string())); } diff --git a/src/test/ui/c-variadic/variadic-ffi-1.rs b/src/test/ui/c-variadic/variadic-ffi-1.rs index 2c02a0d3081e2..a7824d919674d 100644 --- a/src/test/ui/c-variadic/variadic-ffi-1.rs +++ b/src/test/ui/c-variadic/variadic-ffi-1.rs @@ -6,7 +6,7 @@ extern "stdcall" { fn printf(_: *const u8, ...); //~ ERROR: variadic function must have C or cdecl calling } -extern "C" { +extern { fn foo(f: isize, x: u8, ...); } @@ -14,7 +14,7 @@ extern "C" fn bar(f: isize, x: u8) {} fn main() { unsafe { - foo(); //~ ERROR this function takes at least 2 arguments but 0 arguments were supplied + foo(); //~ ERROR this function takes at least 2 arguments but 0 arguments were supplied foo(1); //~ ERROR this function takes at least 2 arguments but 1 argument was supplied let x: unsafe extern "C" fn(f: isize, x: u8) = foo; //~ ERROR mismatched types @@ -22,8 +22,8 @@ fn main() { foo(1, 2, 3f32); //~ ERROR can't pass foo(1, 2, true); //~ ERROR can't pass - foo(1, 2, 1i8); //~ ERROR can't pass - foo(1, 2, 1u8); //~ ERROR can't pass + foo(1, 2, 1i8); //~ ERROR can't pass + foo(1, 2, 1u8); //~ ERROR can't pass foo(1, 2, 1i16); //~ ERROR can't pass foo(1, 2, 1u16); //~ ERROR can't pass } diff --git a/src/test/ui/c-variadic/variadic-ffi-no-fixed-args.rs b/src/test/ui/c-variadic/variadic-ffi-no-fixed-args.rs index 588c15a182977..e3b642a9d418d 100644 --- a/src/test/ui/c-variadic/variadic-ffi-no-fixed-args.rs +++ b/src/test/ui/c-variadic/variadic-ffi-no-fixed-args.rs @@ -1,6 +1,6 @@ -extern "C" { +extern { fn foo(...); -//~^ ERROR C-variadic function must be declared with at least one named argument + //~^ ERROR C-variadic function must be declared with at least one named argument } fn main() {} diff --git a/src/test/ui/parser/can-begin-expr-check.rs b/src/test/ui/can-begin-expr-check.rs similarity index 100% rename from src/test/ui/parser/can-begin-expr-check.rs rename to src/test/ui/can-begin-expr-check.rs diff --git a/src/test/ui/parser/can-begin-expr-check.stderr b/src/test/ui/can-begin-expr-check.stderr similarity index 100% rename from src/test/ui/parser/can-begin-expr-check.stderr rename to src/test/ui/can-begin-expr-check.stderr diff --git a/src/test/ui/cfg/conditional-compile.rs b/src/test/ui/cfg/conditional-compile.rs index 69f4de43186d5..de5bd5f07dd57 100644 --- a/src/test/ui/cfg/conditional-compile.rs +++ b/src/test/ui/cfg/conditional-compile.rs @@ -16,13 +16,13 @@ static b: bool = true; mod rustrt { #[cfg(bogus)] - extern "C" { + extern { // This symbol doesn't exist and would be a link error if this // module was codegened pub fn bogus(); } - extern "C" {} + extern {} } #[cfg(bogus)] @@ -31,56 +31,52 @@ type t = isize; type t = bool; #[cfg(bogus)] -enum tg { - foo, -} +enum tg { foo, } -enum tg { - bar, -} +enum tg { bar, } #[cfg(bogus)] struct r { - i: isize, + i: isize, } #[cfg(bogus)] -fn r(i: isize) -> r { - r { i: i } +fn r(i:isize) -> r { + r { + i: i + } } struct r { - i: isize, + i: isize, } -fn r(i: isize) -> r { - r { i: i } +fn r(i:isize) -> r { + r { + i: i + } } #[cfg(bogus)] mod m { // This needs to parse but would fail in typeck. Since it's not in // the current config it should not be typechecked. - pub fn bogus() { - return 0; - } + pub fn bogus() { return 0; } } mod m { // Submodules have slightly different code paths than the top-level // module, so let's make sure this jazz works here as well #[cfg(bogus)] - pub fn f() {} + pub fn f() { } - pub fn f() {} + pub fn f() { } } // Since the bogus configuration isn't defined main will just be // parsed, but nothing further will be done with it #[cfg(bogus)] -pub fn main() { - panic!() -} +pub fn main() { panic!() } pub fn main() { // Exercise some of the configured items in ways that wouldn't be possible @@ -94,10 +90,8 @@ pub fn main() { fn test_in_fn_ctxt() { #[cfg(bogus)] - fn f() { - panic!() - } - fn f() {} + fn f() { panic!() } + fn f() { } f(); #[cfg(bogus)] @@ -108,7 +102,7 @@ fn test_in_fn_ctxt() { mod test_foreign_items { pub mod rustrt { - extern "C" { + extern { #[cfg(bogus)] pub fn write() -> String; pub fn write() -> String; @@ -123,19 +117,19 @@ mod test_use_statements { mod test_methods { struct Foo { - bar: usize, + bar: usize } impl Fooable for Foo { #[cfg(bogus)] - fn what(&self) {} + fn what(&self) { } - fn what(&self) {} + fn what(&self) { } #[cfg(bogus)] - fn the(&self) {} + fn the(&self) { } - fn the(&self) {} + fn the(&self) { } } trait Fooable { diff --git a/src/test/ui/check-doc-alias-attr-location.rs b/src/test/ui/check-doc-alias-attr-location.rs index 007d2ae6506d7..3a0436e468d11 100644 --- a/src/test/ui/check-doc-alias-attr-location.rs +++ b/src/test/ui/check-doc-alias-attr-location.rs @@ -7,7 +7,7 @@ pub trait Foo { } #[doc(alias = "foo")] //~ ERROR -extern "C" {} +extern {} #[doc(alias = "bar")] //~ ERROR impl Bar { @@ -19,7 +19,5 @@ impl Bar { impl Foo for Bar { #[doc(alias = "assoc")] //~ ERROR type X = i32; - fn foo() -> Self::X { - 0 - } + fn foo() -> Self::X { 0 } } diff --git a/src/test/ui/consts/check_const-feature-gated.rs b/src/test/ui/check_const-feature-gated.rs similarity index 100% rename from src/test/ui/consts/check_const-feature-gated.rs rename to src/test/ui/check_const-feature-gated.rs diff --git a/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-multi-variant-diagnostics.rs b/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-multi-variant-diagnostics.rs deleted file mode 100644 index 2916d8c794f22..0000000000000 --- a/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-multi-variant-diagnostics.rs +++ /dev/null @@ -1,31 +0,0 @@ -#![feature(capture_disjoint_fields)] -//~^ WARNING: the feature `capture_disjoint_fields` is incomplete -//~| `#[warn(incomplete_features)]` on by default -//~| see issue #53488 - -// Check that precise paths are being reported back in the error message. - - -enum MultiVariant { - Point(i32, i32), - Meta(i32) -} - -fn main() { - let mut point = MultiVariant::Point(10, -10,); - - let mut meta = MultiVariant::Meta(1); - - let c = || { - if let MultiVariant::Point(ref mut x, _) = point { - *x += 1; - } - - if let MultiVariant::Meta(ref mut v) = meta { - *v += 1; - } - }; - - let a = c; - let b = c; //~ ERROR use of moved value: `c` [E0382] -} diff --git a/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-multi-variant-diagnostics.stderr b/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-multi-variant-diagnostics.stderr deleted file mode 100644 index de0bfe3bd769f..0000000000000 --- a/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-multi-variant-diagnostics.stderr +++ /dev/null @@ -1,26 +0,0 @@ -warning: the feature `capture_disjoint_fields` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/closure-origin-multi-variant-diagnostics.rs:1:12 - | -LL | #![feature(capture_disjoint_fields)] - | ^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: `#[warn(incomplete_features)]` on by default - = note: see issue #53488 for more information - -error[E0382]: use of moved value: `c` - --> $DIR/closure-origin-multi-variant-diagnostics.rs:30:13 - | -LL | let a = c; - | - value moved here -LL | let b = c; - | ^ value used here after move - | -note: closure cannot be moved more than once as it is not `Copy` due to moving the variable `point.0` out of its environment - --> $DIR/closure-origin-multi-variant-diagnostics.rs:20:52 - | -LL | if let MultiVariant::Point(ref mut x, _) = point { - | ^^^^^ - -error: aborting due to previous error; 1 warning emitted - -For more information about this error, try `rustc --explain E0382`. diff --git a/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-single-variant-diagnostics.rs b/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-single-variant-diagnostics.rs deleted file mode 100644 index 8486f03f2eb8e..0000000000000 --- a/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-single-variant-diagnostics.rs +++ /dev/null @@ -1,26 +0,0 @@ -#![feature(capture_disjoint_fields)] -//~^ WARNING: the feature `capture_disjoint_fields` is incomplete -//~| `#[warn(incomplete_features)]` on by default -//~| see issue #53488 - -// Check that precise paths are being reported back in the error message. - -enum SingleVariant { - Point(i32, i32), -} - -fn main() { - let mut point = SingleVariant::Point(10, -10); - - let c = || { - // FIXME(project-rfc-2229#24): Change this to be a destructure pattern - // once this is fixed, to remove the warning. - if let SingleVariant::Point(ref mut x, _) = point { - //~^ WARNING: irrefutable if-let pattern - *x += 1; - } - }; - - let b = c; - let a = c; //~ ERROR use of moved value: `c` [E0382] -} diff --git a/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-single-variant-diagnostics.stderr b/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-single-variant-diagnostics.stderr deleted file mode 100644 index ad66f6d7ffcaa..0000000000000 --- a/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-single-variant-diagnostics.stderr +++ /dev/null @@ -1,37 +0,0 @@ -warning: the feature `capture_disjoint_fields` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/closure-origin-single-variant-diagnostics.rs:1:12 - | -LL | #![feature(capture_disjoint_fields)] - | ^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: `#[warn(incomplete_features)]` on by default - = note: see issue #53488 for more information - -warning: irrefutable if-let pattern - --> $DIR/closure-origin-single-variant-diagnostics.rs:18:9 - | -LL | / if let SingleVariant::Point(ref mut x, _) = point { -LL | | -LL | | *x += 1; -LL | | } - | |_________^ - | - = note: `#[warn(irrefutable_let_patterns)]` on by default - -error[E0382]: use of moved value: `c` - --> $DIR/closure-origin-single-variant-diagnostics.rs:25:13 - | -LL | let b = c; - | - value moved here -LL | let a = c; - | ^ value used here after move - | -note: closure cannot be moved more than once as it is not `Copy` due to moving the variable `point.0` out of its environment - --> $DIR/closure-origin-single-variant-diagnostics.rs:18:53 - | -LL | if let SingleVariant::Point(ref mut x, _) = point { - | ^^^^^ - -error: aborting due to previous error; 2 warnings emitted - -For more information about this error, try `rustc --explain E0382`. diff --git a/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-struct-diagnostics.rs b/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-struct-diagnostics.rs deleted file mode 100644 index 103890f1f3537..0000000000000 --- a/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-struct-diagnostics.rs +++ /dev/null @@ -1,25 +0,0 @@ -#![feature(capture_disjoint_fields)] -//~^ WARNING: the feature `capture_disjoint_fields` is incomplete -//~| `#[warn(incomplete_features)]` on by default -//~| see issue #53488 - -// Check that precise paths are being reported back in the error message. - -struct Y { - y: X -} - -struct X { - a: u32, - b: u32, -} - -fn main() { - let mut x = Y { y: X { a: 5, b: 0 } }; - let hello = || { - x.y.a += 1; - }; - - let b = hello; - let c = hello; //~ ERROR use of moved value: `hello` [E0382] -} diff --git a/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-struct-diagnostics.stderr b/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-struct-diagnostics.stderr deleted file mode 100644 index 474d77b7cd208..0000000000000 --- a/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-struct-diagnostics.stderr +++ /dev/null @@ -1,26 +0,0 @@ -warning: the feature `capture_disjoint_fields` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/closure-origin-struct-diagnostics.rs:1:12 - | -LL | #![feature(capture_disjoint_fields)] - | ^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: `#[warn(incomplete_features)]` on by default - = note: see issue #53488 for more information - -error[E0382]: use of moved value: `hello` - --> $DIR/closure-origin-struct-diagnostics.rs:24:13 - | -LL | let b = hello; - | ----- value moved here -LL | let c = hello; - | ^^^^^ value used here after move - | -note: closure cannot be moved more than once as it is not `Copy` due to moving the variable `x.y.a` out of its environment - --> $DIR/closure-origin-struct-diagnostics.rs:20:9 - | -LL | x.y.a += 1; - | ^^^^^ - -error: aborting due to previous error; 1 warning emitted - -For more information about this error, try `rustc --explain E0382`. diff --git a/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-tuple-diagnostics-1.rs b/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-tuple-diagnostics-1.rs deleted file mode 100644 index 6b078d2329c2f..0000000000000 --- a/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-tuple-diagnostics-1.rs +++ /dev/null @@ -1,16 +0,0 @@ -#![feature(capture_disjoint_fields)] -//~^ WARNING: the feature `capture_disjoint_fields` is incomplete -//~| `#[warn(incomplete_features)]` on by default -//~| see issue #53488 - -// Check that precise paths are being reported back in the error message. - -fn main() { - let mut x = (5, 0); - let hello = || { - x.0 += 1; - }; - - let b = hello; - let c = hello; //~ ERROR use of moved value: `hello` [E0382] -} diff --git a/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-tuple-diagnostics-1.stderr b/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-tuple-diagnostics-1.stderr deleted file mode 100644 index 716728e96ecbb..0000000000000 --- a/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-tuple-diagnostics-1.stderr +++ /dev/null @@ -1,26 +0,0 @@ -warning: the feature `capture_disjoint_fields` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/closure-origin-tuple-diagnostics-1.rs:1:12 - | -LL | #![feature(capture_disjoint_fields)] - | ^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: `#[warn(incomplete_features)]` on by default - = note: see issue #53488 for more information - -error[E0382]: use of moved value: `hello` - --> $DIR/closure-origin-tuple-diagnostics-1.rs:15:13 - | -LL | let b = hello; - | ----- value moved here -LL | let c = hello; - | ^^^^^ value used here after move - | -note: closure cannot be moved more than once as it is not `Copy` due to moving the variable `x.0` out of its environment - --> $DIR/closure-origin-tuple-diagnostics-1.rs:11:9 - | -LL | x.0 += 1; - | ^^^ - -error: aborting due to previous error; 1 warning emitted - -For more information about this error, try `rustc --explain E0382`. diff --git a/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-tuple-diagnostics.rs b/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-tuple-diagnostics.rs deleted file mode 100644 index 0638db607690f..0000000000000 --- a/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-tuple-diagnostics.rs +++ /dev/null @@ -1,15 +0,0 @@ -#![feature(capture_disjoint_fields)] -//~^ WARNING: the feature `capture_disjoint_fields` is incomplete -//~| `#[warn(incomplete_features)]` on by default -//~| see issue #53488 -struct S(String, String); - -fn expect_fn(_f: F) {} - -fn main() { - let s = S(format!("s"), format!("s")); - let c = || { //~ ERROR expected a closure that implements the `Fn` - let s = s.1; - }; - expect_fn(c); -} diff --git a/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-tuple-diagnostics.stderr b/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-tuple-diagnostics.stderr deleted file mode 100644 index 77eb2a94ffb4d..0000000000000 --- a/src/test/ui/closures/2229_closure_analysis/diagnostics/closure-origin-tuple-diagnostics.stderr +++ /dev/null @@ -1,23 +0,0 @@ -warning: the feature `capture_disjoint_fields` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/closure-origin-tuple-diagnostics.rs:1:12 - | -LL | #![feature(capture_disjoint_fields)] - | ^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: `#[warn(incomplete_features)]` on by default - = note: see issue #53488 for more information - -error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` - --> $DIR/closure-origin-tuple-diagnostics.rs:11:13 - | -LL | let c = || { - | ^^ this closure implements `FnOnce`, not `Fn` -LL | let s = s.1; - | --- closure is `FnOnce` because it moves the variable `s.1` out of its environment -LL | }; -LL | expect_fn(c); - | --------- the requirement to implement `Fn` derives from here - -error: aborting due to previous error; 1 warning emitted - -For more information about this error, try `rustc --explain E0525`. diff --git a/src/test/ui/closures/closure-no-fn-1.stderr b/src/test/ui/closures/closure-no-fn-1.stderr index 2b53802fea793..76136315a1b8b 100644 --- a/src/test/ui/closures/closure-no-fn-1.stderr +++ b/src/test/ui/closures/closure-no-fn-1.stderr @@ -8,11 +8,6 @@ LL | let foo: fn(u8) -> u8 = |v: u8| { a += v; a }; | = note: expected fn pointer `fn(u8) -> u8` found closure `[closure@$DIR/closure-no-fn-1.rs:6:29: 6:50]` -note: closures can only be coerced to `fn` types if they do not capture any variables - --> $DIR/closure-no-fn-1.rs:6:39 - | -LL | let foo: fn(u8) -> u8 = |v: u8| { a += v; a }; - | ^ `a` captured here error: aborting due to previous error diff --git a/src/test/ui/closures/closure-no-fn-2.stderr b/src/test/ui/closures/closure-no-fn-2.stderr index ed9f87a2c94a8..85cbdbe7c18e1 100644 --- a/src/test/ui/closures/closure-no-fn-2.stderr +++ b/src/test/ui/closures/closure-no-fn-2.stderr @@ -8,11 +8,6 @@ LL | let bar: fn() -> u8 = || { b }; | = note: expected fn pointer `fn() -> u8` found closure `[closure@$DIR/closure-no-fn-2.rs:6:27: 6:35]` -note: closures can only be coerced to `fn` types if they do not capture any variables - --> $DIR/closure-no-fn-2.rs:6:32 - | -LL | let bar: fn() -> u8 = || { b }; - | ^ `b` captured here error: aborting due to previous error diff --git a/src/test/ui/closures/closure-no-fn-4.rs b/src/test/ui/closures/closure-no-fn-4.rs deleted file mode 100644 index 275bff645dba6..0000000000000 --- a/src/test/ui/closures/closure-no-fn-4.rs +++ /dev/null @@ -1,8 +0,0 @@ -fn main() { - let b = 2; - let _: fn(usize) -> usize = match true { - true => |a| a + 1, - false => |a| a - b, - //~^ ERROR `match` arms have incompatible types - }; -} diff --git a/src/test/ui/closures/closure-no-fn-4.stderr b/src/test/ui/closures/closure-no-fn-4.stderr deleted file mode 100644 index 89798ec5dd34f..0000000000000 --- a/src/test/ui/closures/closure-no-fn-4.stderr +++ /dev/null @@ -1,24 +0,0 @@ -error[E0308]: `match` arms have incompatible types - --> $DIR/closure-no-fn-4.rs:5:18 - | -LL | let _: fn(usize) -> usize = match true { - | _________________________________- -LL | | true => |a| a + 1, - | | --------- this is found to be of type `fn(usize) -> usize` -LL | | false => |a| a - b, - | | ^^^^^^^^^ expected fn pointer, found closure -LL | | -LL | | }; - | |_____- `match` arms have incompatible types - | - = note: expected fn pointer `fn(usize) -> usize` - found closure `[closure@$DIR/closure-no-fn-4.rs:5:18: 5:27]` -note: closures can only be coerced to `fn` types if they do not capture any variables - --> $DIR/closure-no-fn-4.rs:5:26 - | -LL | false => |a| a - b, - | ^ `b` captured here - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0308`. diff --git a/src/test/ui/closures/closure-no-fn-5.rs b/src/test/ui/closures/closure-no-fn-5.rs deleted file mode 100644 index 43e3e977e34ab..0000000000000 --- a/src/test/ui/closures/closure-no-fn-5.rs +++ /dev/null @@ -1,12 +0,0 @@ -// When providing diagnostics about not being able to coerce a capturing-closure -// to fn type, we want to report only upto 4 captures. - -fn main() { - let a = 0u8; - let b = 0u8; - let c = 0u8; - let d = 0u8; - let e = 0u8; - let bar: fn() -> u8 = || { a; b; c; d; e }; - //~^ ERROR mismatched types -} diff --git a/src/test/ui/closures/closure-no-fn-5.stderr b/src/test/ui/closures/closure-no-fn-5.stderr deleted file mode 100644 index 1f373f10489e6..0000000000000 --- a/src/test/ui/closures/closure-no-fn-5.stderr +++ /dev/null @@ -1,23 +0,0 @@ -error[E0308]: mismatched types - --> $DIR/closure-no-fn-5.rs:10:27 - | -LL | let bar: fn() -> u8 = || { a; b; c; d; e }; - | ---------- ^^^^^^^^^^^^^^^^^^^^ expected fn pointer, found closure - | | - | expected due to this - | - = note: expected fn pointer `fn() -> u8` - found closure `[closure@$DIR/closure-no-fn-5.rs:10:27: 10:47]` -note: closures can only be coerced to `fn` types if they do not capture any variables - --> $DIR/closure-no-fn-5.rs:10:32 - | -LL | let bar: fn() -> u8 = || { a; b; c; d; e }; - | ^ ^ ^ ^ `d` captured here - | | | | - | | | `c` captured here - | | `b` captured here - | `a` captured here - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0308`. diff --git a/src/test/ui/closures/closure-reform-bad.stderr b/src/test/ui/closures/closure-reform-bad.stderr index 37813879ce752..77c8c7ab7948d 100644 --- a/src/test/ui/closures/closure-reform-bad.stderr +++ b/src/test/ui/closures/closure-reform-bad.stderr @@ -8,11 +8,6 @@ LL | call_bare(f) | = note: expected fn pointer `for<'r> fn(&'r str)` found closure `[closure@$DIR/closure-reform-bad.rs:10:13: 10:50]` -note: closures can only be coerced to `fn` types if they do not capture any variables - --> $DIR/closure-reform-bad.rs:10:43 - | -LL | let f = |s: &str| println!("{}{}", s, string); - | ^^^^^^ `string` captured here error: aborting due to previous error diff --git a/src/test/ui/closures/print/closure-print-verbose.stderr b/src/test/ui/closures/print/closure-print-verbose.stderr index d19b07acbf175..9e07137a24195 100644 --- a/src/test/ui/closures/print/closure-print-verbose.stderr +++ b/src/test/ui/closures/print/closure-print-verbose.stderr @@ -8,11 +8,6 @@ LL | let foo: fn(u8) -> u8 = |v: u8| { a += v; a }; | = note: expected fn pointer `fn(u8) -> u8` found closure `[main::{closure#0} closure_substs=(unavailable)]` -note: closures can only be coerced to `fn` types if they do not capture any variables - --> $DIR/closure-print-verbose.rs:10:39 - | -LL | let foo: fn(u8) -> u8 = |v: u8| { a += v; a }; - | ^ `a` captured here error: aborting due to previous error diff --git a/src/test/ui/command/command-current-dir.rs b/src/test/ui/command/command-current-dir.rs deleted file mode 100644 index 91d8e4f381a36..0000000000000 --- a/src/test/ui/command/command-current-dir.rs +++ /dev/null @@ -1,49 +0,0 @@ -// run-pass -// ignore-emscripten no processes -// ignore-sgx no processes - -use std::env; -use std::fs; -use std::path::Path; -use std::process::Command; - -fn main() { - // Checks the behavior of current_dir when used with a relative exe path. - let me = env::current_exe().unwrap(); - if matches!(env::args().skip(1).next().as_deref(), Some("current-dir")) { - let cwd = env::current_dir().unwrap(); - assert_eq!(cwd.file_name().unwrap(), "bar"); - std::process::exit(0); - } - let exe = me.file_name().unwrap(); - let cwd = me.parent().unwrap(); - eprintln!("cwd={:?}", cwd); - // Change directory to where the exectuable is located, since this test - // fundamentally needs to use relative paths. In some cases (like - // remote-test-server), the current_dir can be somewhere else, so make - // sure it is something we can use. We assume we can write to this - // directory. - env::set_current_dir(&cwd).unwrap(); - let foo = cwd.join("foo"); - let bar = cwd.join("bar"); - fs::create_dir_all(&foo).unwrap(); - fs::create_dir_all(&bar).unwrap(); - fs::copy(&me, foo.join(exe)).unwrap(); - - // Unfortunately this is inconsistent based on the platform, see - // https://github.com/rust-lang/rust/issues/37868. On Windows, - // it is relative *before* changing the directory, and on Unix - // it is *after* changing the directory. - let relative_exe = if cfg!(windows) { - Path::new("foo").join(exe) - } else { - Path::new("../foo").join(exe) - }; - - let status = Command::new(relative_exe) - .arg("current-dir") - .current_dir("bar") - .status() - .unwrap(); - assert!(status.success()); -} diff --git a/src/test/ui/const-generics/incorrect-number-of-const-args.full.stderr b/src/test/ui/const-generics/incorrect-number-of-const-args.full.stderr index dd7e63480eb20..9c8359b08a5c1 100644 --- a/src/test/ui/const-generics/incorrect-number-of-const-args.full.stderr +++ b/src/test/ui/const-generics/incorrect-number-of-const-args.full.stderr @@ -1,34 +1,14 @@ -error[E0107]: this function takes 2 const arguments but only 1 const argument was supplied +error[E0107]: wrong number of const arguments: expected 2, found 1 --> $DIR/incorrect-number-of-const-args.rs:11:5 | LL | foo::<0>(); - | ^^^ - supplied 1 const argument - | | - | expected 2 const arguments - | -note: function defined here, with 2 const parameters: `X`, `Y` - --> $DIR/incorrect-number-of-const-args.rs:6:4 - | -LL | fn foo() -> usize { - | ^^^ - - -help: add missing const argument - | -LL | foo::<0, Y>(); - | ^^^ + | ^^^^^^^^ expected 2 const arguments -error[E0107]: this function takes 2 const arguments but 3 const arguments were supplied - --> $DIR/incorrect-number-of-const-args.rs:14:5 +error[E0107]: wrong number of const arguments: expected 2, found 3 + --> $DIR/incorrect-number-of-const-args.rs:12:17 | LL | foo::<0, 0, 0>(); - | ^^^ --- help: remove this const argument - | | - | expected 2 const arguments - | -note: function defined here, with 2 const parameters: `X`, `Y` - --> $DIR/incorrect-number-of-const-args.rs:6:4 - | -LL | fn foo() -> usize { - | ^^^ - - + | ^ unexpected const argument error: aborting due to 2 previous errors diff --git a/src/test/ui/const-generics/incorrect-number-of-const-args.min.stderr b/src/test/ui/const-generics/incorrect-number-of-const-args.min.stderr index dd7e63480eb20..9c8359b08a5c1 100644 --- a/src/test/ui/const-generics/incorrect-number-of-const-args.min.stderr +++ b/src/test/ui/const-generics/incorrect-number-of-const-args.min.stderr @@ -1,34 +1,14 @@ -error[E0107]: this function takes 2 const arguments but only 1 const argument was supplied +error[E0107]: wrong number of const arguments: expected 2, found 1 --> $DIR/incorrect-number-of-const-args.rs:11:5 | LL | foo::<0>(); - | ^^^ - supplied 1 const argument - | | - | expected 2 const arguments - | -note: function defined here, with 2 const parameters: `X`, `Y` - --> $DIR/incorrect-number-of-const-args.rs:6:4 - | -LL | fn foo() -> usize { - | ^^^ - - -help: add missing const argument - | -LL | foo::<0, Y>(); - | ^^^ + | ^^^^^^^^ expected 2 const arguments -error[E0107]: this function takes 2 const arguments but 3 const arguments were supplied - --> $DIR/incorrect-number-of-const-args.rs:14:5 +error[E0107]: wrong number of const arguments: expected 2, found 3 + --> $DIR/incorrect-number-of-const-args.rs:12:17 | LL | foo::<0, 0, 0>(); - | ^^^ --- help: remove this const argument - | | - | expected 2 const arguments - | -note: function defined here, with 2 const parameters: `X`, `Y` - --> $DIR/incorrect-number-of-const-args.rs:6:4 - | -LL | fn foo() -> usize { - | ^^^ - - + | ^ unexpected const argument error: aborting due to 2 previous errors diff --git a/src/test/ui/const-generics/incorrect-number-of-const-args.rs b/src/test/ui/const-generics/incorrect-number-of-const-args.rs index 3114e716845bf..3c4290df0564f 100644 --- a/src/test/ui/const-generics/incorrect-number-of-const-args.rs +++ b/src/test/ui/const-generics/incorrect-number-of-const-args.rs @@ -8,9 +8,6 @@ fn foo() -> usize { } fn main() { - foo::<0>(); - //~^ ERROR this function takes 2 const arguments but only 1 const argument was supplied - - foo::<0, 0, 0>(); - //~^ ERROR this function takes 2 const arguments but 3 const arguments were supplied + foo::<0>(); //~ ERROR wrong number of const arguments: expected 2, found 1 + foo::<0, 0, 0>(); //~ ERROR wrong number of const arguments: expected 2, found 3 } diff --git a/src/test/ui/const-generics/invalid-const-arg-for-type-param.rs b/src/test/ui/const-generics/invalid-const-arg-for-type-param.rs index b67a1f153ffef..b069cd89680c1 100644 --- a/src/test/ui/const-generics/invalid-const-arg-for-type-param.rs +++ b/src/test/ui/const-generics/invalid-const-arg-for-type-param.rs @@ -3,12 +3,7 @@ use std::convert::TryInto; struct S; fn main() { - let _: u32 = 5i32.try_into::<32>().unwrap(); - //~^ ERROR this associated function takes 0 const arguments but 1 const argument was supplied - - S.f::<0>(); - //~^ ERROR no method named `f` - - S::<0>; - //~^ ERROR this struct takes 0 const arguments but 1 const argument was supplied + let _: u32 = 5i32.try_into::<32>().unwrap(); //~ ERROR wrong number of const arguments + S.f::<0>(); //~ ERROR no method named `f` + S::<0>; //~ ERROR wrong number of const arguments } diff --git a/src/test/ui/const-generics/invalid-const-arg-for-type-param.stderr b/src/test/ui/const-generics/invalid-const-arg-for-type-param.stderr index a75da91caa84f..19e7d2036bfc8 100644 --- a/src/test/ui/const-generics/invalid-const-arg-for-type-param.stderr +++ b/src/test/ui/const-generics/invalid-const-arg-for-type-param.stderr @@ -1,19 +1,11 @@ -error[E0107]: this associated function takes 0 const arguments but 1 const argument was supplied - --> $DIR/invalid-const-arg-for-type-param.rs:6:23 +error[E0107]: wrong number of const arguments: expected 0, found 1 + --> $DIR/invalid-const-arg-for-type-param.rs:6:34 | LL | let _: u32 = 5i32.try_into::<32>().unwrap(); - | ^^^^^^^^------ help: remove these generics - | | - | expected 0 const arguments - | -note: associated function defined here, with 0 const parameters - --> $SRC_DIR/core/src/convert/mod.rs:LL:COL - | -LL | fn try_into(self) -> Result; - | ^^^^^^^^ + | ^^ unexpected const argument error[E0599]: no method named `f` found for struct `S` in the current scope - --> $DIR/invalid-const-arg-for-type-param.rs:9:7 + --> $DIR/invalid-const-arg-for-type-param.rs:7:7 | LL | struct S; | --------- method `f` not found for this @@ -21,19 +13,11 @@ LL | struct S; LL | S.f::<0>(); | ^ method not found in `S` -error[E0107]: this struct takes 0 const arguments but 1 const argument was supplied - --> $DIR/invalid-const-arg-for-type-param.rs:12:5 +error[E0107]: wrong number of const arguments: expected 0, found 1 + --> $DIR/invalid-const-arg-for-type-param.rs:8:9 | LL | S::<0>; - | ^----- help: remove these generics - | | - | expected 0 const arguments - | -note: struct defined here, with 0 const parameters - --> $DIR/invalid-const-arg-for-type-param.rs:3:8 - | -LL | struct S; - | ^ + | ^ unexpected const argument error: aborting due to 3 previous errors diff --git a/src/test/ui/const-generics/invalid-constant-in-args.rs b/src/test/ui/const-generics/invalid-constant-in-args.rs index 7419d4a25ce12..0bd9cbf4f4708 100644 --- a/src/test/ui/const-generics/invalid-constant-in-args.rs +++ b/src/test/ui/const-generics/invalid-constant-in-args.rs @@ -2,5 +2,5 @@ use std::cell::Cell; fn main() { let _: Cell<&str, "a"> = Cell::new(""); - //~^ ERROR this struct takes 1 generic argument but 2 generic arguments were supplied + //~^ ERROR wrong number of generic arguments } diff --git a/src/test/ui/const-generics/invalid-constant-in-args.stderr b/src/test/ui/const-generics/invalid-constant-in-args.stderr index 57c1af36d61cc..9b8a5d1ae4f20 100644 --- a/src/test/ui/const-generics/invalid-constant-in-args.stderr +++ b/src/test/ui/const-generics/invalid-constant-in-args.stderr @@ -1,16 +1,8 @@ -error[E0107]: this struct takes 1 generic argument but 2 generic arguments were supplied - --> $DIR/invalid-constant-in-args.rs:4:12 +error[E0107]: wrong number of generic arguments: expected 1, found 2 + --> $DIR/invalid-constant-in-args.rs:4:23 | LL | let _: Cell<&str, "a"> = Cell::new(""); - | ^^^^ ----- help: remove this generic argument - | | - | expected 1 generic argument - | -note: struct defined here, with 1 generic parameter: `T` - --> $SRC_DIR/core/src/cell.rs:LL:COL - | -LL | pub struct Cell { - | ^^^^ - + | ^^^ unexpected const argument error: aborting due to previous error diff --git a/src/test/ui/const-generics/issues/issue-76595.rs b/src/test/ui/const-generics/issues/issue-76595.rs index d95d675ddad76..04c019015179e 100644 --- a/src/test/ui/const-generics/issues/issue-76595.rs +++ b/src/test/ui/const-generics/issues/issue-76595.rs @@ -13,5 +13,5 @@ fn test() where Bool<{core::mem::size_of::() > 4}>: True { fn main() { test::<2>(); - //~^ ERROR this function takes 2 generic arguments but only 1 generic argument was supplied + //~^ ERROR wrong number of generic arguments } diff --git a/src/test/ui/const-generics/issues/issue-76595.stderr b/src/test/ui/const-generics/issues/issue-76595.stderr index 9d95e5a014de4..1e37f9dcb1925 100644 --- a/src/test/ui/const-generics/issues/issue-76595.stderr +++ b/src/test/ui/const-generics/issues/issue-76595.stderr @@ -1,20 +1,8 @@ -error[E0107]: this function takes 2 generic arguments but only 1 generic argument was supplied +error[E0107]: wrong number of generic arguments: expected 2, found 1 --> $DIR/issue-76595.rs:15:5 | LL | test::<2>(); - | ^^^^ - supplied 1 generic argument - | | - | expected 2 generic arguments - | -note: function defined here, with 2 generic parameters: `T`, `P` - --> $DIR/issue-76595.rs:10:4 - | -LL | fn test() where Bool<{core::mem::size_of::() > 4}>: True { - | ^^^^ - - -help: add missing generic argument - | -LL | test::<2, P>(); - | ^^^ + | ^^^^^^^^^ expected 2 generic arguments error: aborting due to previous error diff --git a/src/test/ui/const-generics/late-bound-vars/in_closure.rs b/src/test/ui/const-generics/late-bound-vars/in_closure.rs deleted file mode 100644 index 0aaeaffb4cb9d..0000000000000 --- a/src/test/ui/const-generics/late-bound-vars/in_closure.rs +++ /dev/null @@ -1,18 +0,0 @@ -// run-pass -#![feature(const_generics)] -#![allow(incomplete_features)] - -const fn inner<'a>() -> usize where &'a (): Sized { - 3 -} - -fn test<'a>() { - let _ = || { - let _: [u8; inner::<'a>()]; - let _ = [0; inner::<'a>()]; - }; -} - -fn main() { - test(); -} diff --git a/src/test/ui/const-generics/late-bound-vars/simple.rs b/src/test/ui/const-generics/late-bound-vars/simple.rs deleted file mode 100644 index 2c411a3bdc5f3..0000000000000 --- a/src/test/ui/const-generics/late-bound-vars/simple.rs +++ /dev/null @@ -1,16 +0,0 @@ -// run-pass -#![feature(const_generics)] -#![allow(incomplete_features)] - -const fn inner<'a>() -> usize where &'a (): Sized { - 3 -} - -fn test<'a>() { - let _: [u8; inner::<'a>()]; - let _ = [0; inner::<'a>()]; -} - -fn main() { - test(); -} diff --git a/src/test/ui/consts/const-suggest-feature.rs b/src/test/ui/const-suggest-feature.rs similarity index 100% rename from src/test/ui/consts/const-suggest-feature.rs rename to src/test/ui/const-suggest-feature.rs diff --git a/src/test/ui/consts/const-suggest-feature.stderr b/src/test/ui/const-suggest-feature.stderr similarity index 100% rename from src/test/ui/consts/const-suggest-feature.stderr rename to src/test/ui/const-suggest-feature.stderr diff --git a/src/test/ui/constructor-lifetime-args.rs b/src/test/ui/constructor-lifetime-args.rs index d038269382be5..6af5f6d56e7f6 100644 --- a/src/test/ui/constructor-lifetime-args.rs +++ b/src/test/ui/constructor-lifetime-args.rs @@ -15,12 +15,12 @@ enum E<'a, 'b> { fn main() { S(&0, &0); // OK S::<'static>(&0, &0); - //~^ ERROR this struct takes 2 lifetime arguments but only 1 lifetime argument was supplied + //~^ ERROR wrong number of lifetime arguments: expected 2, found 1 S::<'static, 'static, 'static>(&0, &0); - //~^ ERROR this struct takes 2 lifetime arguments but 3 lifetime arguments were supplied + //~^ ERROR wrong number of lifetime arguments: expected 2, found 3 E::V(&0); // OK E::V::<'static>(&0); - //~^ ERROR this enum takes 2 lifetime arguments but only 1 lifetime argument was supplied + //~^ ERROR wrong number of lifetime arguments: expected 2, found 1 E::V::<'static, 'static, 'static>(&0); - //~^ ERROR this enum takes 2 lifetime arguments but 3 lifetime arguments were supplied + //~^ ERROR wrong number of lifetime arguments: expected 2, found 3 } diff --git a/src/test/ui/constructor-lifetime-args.stderr b/src/test/ui/constructor-lifetime-args.stderr index 378b07694e6fe..ec8ed9288cced 100644 --- a/src/test/ui/constructor-lifetime-args.stderr +++ b/src/test/ui/constructor-lifetime-args.stderr @@ -1,66 +1,26 @@ -error[E0107]: this struct takes 2 lifetime arguments but only 1 lifetime argument was supplied +error[E0107]: wrong number of lifetime arguments: expected 2, found 1 --> $DIR/constructor-lifetime-args.rs:17:5 | LL | S::<'static>(&0, &0); - | ^ ------- supplied 1 lifetime argument - | | - | expected 2 lifetime arguments - | -note: struct defined here, with 2 lifetime parameters: `'a`, `'b` - --> $DIR/constructor-lifetime-args.rs:9:8 - | -LL | struct S<'a, 'b>(&'a u8, &'b u8); - | ^ -- -- -help: add missing lifetime argument - | -LL | S::<'static, 'b>(&0, &0); - | ^^^^ + | ^^^^^^^^^^^^ expected 2 lifetime arguments -error[E0107]: this struct takes 2 lifetime arguments but 3 lifetime arguments were supplied - --> $DIR/constructor-lifetime-args.rs:19:5 +error[E0107]: wrong number of lifetime arguments: expected 2, found 3 + --> $DIR/constructor-lifetime-args.rs:19:27 | LL | S::<'static, 'static, 'static>(&0, &0); - | ^ --------- help: remove this lifetime argument - | | - | expected 2 lifetime arguments - | -note: struct defined here, with 2 lifetime parameters: `'a`, `'b` - --> $DIR/constructor-lifetime-args.rs:9:8 - | -LL | struct S<'a, 'b>(&'a u8, &'b u8); - | ^ -- -- + | ^^^^^^^ unexpected lifetime argument -error[E0107]: this enum takes 2 lifetime arguments but only 1 lifetime argument was supplied - --> $DIR/constructor-lifetime-args.rs:22:8 +error[E0107]: wrong number of lifetime arguments: expected 2, found 1 + --> $DIR/constructor-lifetime-args.rs:22:5 | LL | E::V::<'static>(&0); - | ^ ------- supplied 1 lifetime argument - | | - | expected 2 lifetime arguments - | -note: enum defined here, with 2 lifetime parameters: `'a`, `'b` - --> $DIR/constructor-lifetime-args.rs:10:6 - | -LL | enum E<'a, 'b> { - | ^ -- -- -help: add missing lifetime argument - | -LL | E::V::<'static, 'b>(&0); - | ^^^^ + | ^^^^^^^^^^^^^^^ expected 2 lifetime arguments -error[E0107]: this enum takes 2 lifetime arguments but 3 lifetime arguments were supplied - --> $DIR/constructor-lifetime-args.rs:24:8 +error[E0107]: wrong number of lifetime arguments: expected 2, found 3 + --> $DIR/constructor-lifetime-args.rs:24:30 | LL | E::V::<'static, 'static, 'static>(&0); - | ^ --------- help: remove this lifetime argument - | | - | expected 2 lifetime arguments - | -note: enum defined here, with 2 lifetime parameters: `'a`, `'b` - --> $DIR/constructor-lifetime-args.rs:10:6 - | -LL | enum E<'a, 'b> { - | ^ -- -- + | ^^^^^^^ unexpected lifetime argument error: aborting due to 4 previous errors diff --git a/src/test/ui/consts/auxiliary/cci_const.rs b/src/test/ui/consts/auxiliary/cci_const.rs index c83b3f4a5bbf0..af6a5ad8ed39d 100644 --- a/src/test/ui/consts/auxiliary/cci_const.rs +++ b/src/test/ui/consts/auxiliary/cci_const.rs @@ -1,4 +1,4 @@ -pub extern "C" fn bar() { +pub extern fn bar() { } pub const foopy: &'static str = "hi there"; diff --git a/src/test/ui/consts/auxiliary/issue-63226.rs b/src/test/ui/consts/auxiliary/issue-63226.rs index 2dc9539ba527b..39cc01a415e9a 100644 --- a/src/test/ui/consts/auxiliary/issue-63226.rs +++ b/src/test/ui/consts/auxiliary/issue-63226.rs @@ -1,5 +1,5 @@ pub struct VTable{ - state:extern "C" fn(), + state:extern fn(), } impl VTable{ @@ -11,4 +11,4 @@ impl VTable{ &VTable{state}; } -extern "C" fn state() {} +extern fn state() {} diff --git a/src/test/ui/consts/const-cast.rs b/src/test/ui/consts/const-cast.rs index abeb24121eb16..0d8609e334ac1 100644 --- a/src/test/ui/consts/const-cast.rs +++ b/src/test/ui/consts/const-cast.rs @@ -7,7 +7,7 @@ struct TestStruct { unsafe impl Sync for TestStruct {} -extern "C" fn foo() {} +extern fn foo() {} const x: extern "C" fn() = foo; static y: TestStruct = TestStruct { x: x as *const u8 }; diff --git a/src/test/ui/consts/const-eval/extern_fat_pointer.rs b/src/test/ui/consts/const-eval/extern_fat_pointer.rs index d91d07827dc05..f210d1a0a90c5 100644 --- a/src/test/ui/consts/const-eval/extern_fat_pointer.rs +++ b/src/test/ui/consts/const-eval/extern_fat_pointer.rs @@ -2,7 +2,7 @@ #![feature(extern_types)] -extern "C" { +extern { type Opaque; } diff --git a/src/test/ui/consts/const-eval/ub-wide-ptr.rs b/src/test/ui/consts/const-eval/ub-wide-ptr.rs index 2975118cdb7fb..bcd05b4cd7ec8 100644 --- a/src/test/ui/consts/const-eval/ub-wide-ptr.rs +++ b/src/test/ui/consts/const-eval/ub-wide-ptr.rs @@ -8,12 +8,6 @@ use std::mem; // normalize-stderr-test "alloc\d+" -> "allocN" // normalize-stderr-test "size \d+" -> "size N" -/// A newtype wrapper to prevent MIR generation from inserting reborrows that would affect the error -/// message. Use this whenever the message is "any use of this value will cause an error" instead of -/// "it is undefined behavior to use this value". -#[repr(transparent)] -struct W(T); - #[repr(C)] union MaybeUninit { uninit: (), @@ -101,22 +95,26 @@ const RAW_SLICE_LENGTH_UNINIT: *const [u8] = unsafe { // # trait object // bad trait object -const TRAIT_OBJ_SHORT_VTABLE_1: W<&dyn Trait> = unsafe { mem::transmute(W((&92u8, &3u8))) }; -//~^ ERROR it is undefined behavior to use this value +#[warn(const_err)] +const TRAIT_OBJ_SHORT_VTABLE_1: &dyn Trait = unsafe { mem::transmute((&92u8, &3u8)) }; +//~^ WARN any use of this value will cause an error [const_err] // bad trait object -const TRAIT_OBJ_SHORT_VTABLE_2: W<&dyn Trait> = unsafe { mem::transmute(W((&92u8, &3u64))) }; -//~^ ERROR it is undefined behavior to use this value +#[warn(const_err)] +const TRAIT_OBJ_SHORT_VTABLE_2: &dyn Trait = unsafe { mem::transmute((&92u8, &3u64)) }; +//~^ WARN any use of this value will cause an error [const_err] // bad trait object -const TRAIT_OBJ_INT_VTABLE: W<&dyn Trait> = unsafe { mem::transmute(W((&92u8, 4usize))) }; -//~^ ERROR it is undefined behavior to use this value +#[warn(const_err)] +const TRAIT_OBJ_INT_VTABLE: &dyn Trait = unsafe { mem::transmute((&92u8, 4usize)) }; +//~^ WARN any use of this value will cause an error [const_err] const TRAIT_OBJ_UNALIGNED_VTABLE: &dyn Trait = unsafe { mem::transmute((&92u8, &[0u8; 128])) }; //~^ ERROR it is undefined behavior to use this value const TRAIT_OBJ_BAD_DROP_FN_NULL: &dyn Trait = unsafe { mem::transmute((&92u8, &[0usize; 8])) }; //~^ ERROR it is undefined behavior to use this value const TRAIT_OBJ_BAD_DROP_FN_INT: &dyn Trait = unsafe { mem::transmute((&92u8, &[1usize; 8])) }; //~^ ERROR it is undefined behavior to use this value -const TRAIT_OBJ_BAD_DROP_FN_NOT_FN_PTR: W<&dyn Trait> = unsafe { mem::transmute(W((&92u8, &[&42u8; 8]))) }; -//~^ ERROR it is undefined behavior to use this value +#[warn(const_err)] +const TRAIT_OBJ_BAD_DROP_FN_NOT_FN_PTR: &dyn Trait = unsafe { mem::transmute((&92u8, &[&42u8; 8])) }; +//~^ WARN any use of this value will cause an error [const_err] // bad data *inside* the trait object const TRAIT_OBJ_CONTENT_INVALID: &dyn Trait = unsafe { mem::transmute::<_, &bool>(&3u8) }; diff --git a/src/test/ui/consts/const-eval/ub-wide-ptr.stderr b/src/test/ui/consts/const-eval/ub-wide-ptr.stderr index be9ec16a06fe3..ec5d465c88251 100644 --- a/src/test/ui/consts/const-eval/ub-wide-ptr.stderr +++ b/src/test/ui/consts/const-eval/ub-wide-ptr.stderr @@ -1,5 +1,5 @@ error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:37:1 + --> $DIR/ub-wide-ptr.rs:31:1 | LL | const STR_TOO_LONG: &str = unsafe { mem::transmute((&42u8, 999usize)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered a dangling reference (going beyond the bounds of its allocation) @@ -7,7 +7,7 @@ LL | const STR_TOO_LONG: &str = unsafe { mem::transmute((&42u8, 999usize)) }; = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:39:1 + --> $DIR/ub-wide-ptr.rs:33:1 | LL | const NESTED_STR_MUCH_TOO_LONG: (&str,) = (unsafe { mem::transmute((&42, usize::MAX)) },); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered invalid reference metadata: slice is bigger than largest supported object at .0 @@ -15,7 +15,7 @@ LL | const NESTED_STR_MUCH_TOO_LONG: (&str,) = (unsafe { mem::transmute((&42, us = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:42:1 + --> $DIR/ub-wide-ptr.rs:36:1 | LL | const STR_LENGTH_PTR: &str = unsafe { mem::transmute((&42u8, &3)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered non-integer slice length in wide pointer @@ -23,7 +23,7 @@ LL | const STR_LENGTH_PTR: &str = unsafe { mem::transmute((&42u8, &3)) }; = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:45:1 + --> $DIR/ub-wide-ptr.rs:39:1 | LL | const MY_STR_LENGTH_PTR: &MyStr = unsafe { mem::transmute((&42u8, &3)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered non-integer slice length in wide pointer @@ -31,7 +31,7 @@ LL | const MY_STR_LENGTH_PTR: &MyStr = unsafe { mem::transmute((&42u8, &3)) }; = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:47:1 + --> $DIR/ub-wide-ptr.rs:41:1 | LL | const MY_STR_MUCH_TOO_LONG: &MyStr = unsafe { mem::transmute((&42u8, usize::MAX)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered invalid reference metadata: slice is bigger than largest supported object @@ -39,7 +39,7 @@ LL | const MY_STR_MUCH_TOO_LONG: &MyStr = unsafe { mem::transmute((&42u8, usize: = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:51:1 + --> $DIR/ub-wide-ptr.rs:45:1 | LL | const STR_NO_INIT: &str = unsafe { mem::transmute::<&[_], _>(&[MaybeUninit:: { uninit: () }]) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered uninitialized data in `str` at . @@ -47,7 +47,7 @@ LL | const STR_NO_INIT: &str = unsafe { mem::transmute::<&[_], _>(&[MaybeUninit: = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:54:1 + --> $DIR/ub-wide-ptr.rs:48:1 | LL | const MYSTR_NO_INIT: &MyStr = unsafe { mem::transmute::<&[_], _>(&[MaybeUninit:: { uninit: () }]) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered uninitialized data in `str` at ..0 @@ -55,7 +55,7 @@ LL | const MYSTR_NO_INIT: &MyStr = unsafe { mem::transmute::<&[_], _>(&[MaybeUni = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:61:1 + --> $DIR/ub-wide-ptr.rs:55:1 | LL | / const SLICE_LENGTH_UNINIT: &[u8] = unsafe { LL | | @@ -67,7 +67,7 @@ LL | | }; = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:67:1 + --> $DIR/ub-wide-ptr.rs:61:1 | LL | const SLICE_TOO_LONG: &[u8] = unsafe { mem::transmute((&42u8, 999usize)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered a dangling reference (going beyond the bounds of its allocation) @@ -75,7 +75,7 @@ LL | const SLICE_TOO_LONG: &[u8] = unsafe { mem::transmute((&42u8, 999usize)) }; = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:70:1 + --> $DIR/ub-wide-ptr.rs:64:1 | LL | const SLICE_LENGTH_PTR: &[u8] = unsafe { mem::transmute((&42u8, &3)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered non-integer slice length in wide pointer @@ -83,7 +83,7 @@ LL | const SLICE_LENGTH_PTR: &[u8] = unsafe { mem::transmute((&42u8, &3)) }; = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:73:1 + --> $DIR/ub-wide-ptr.rs:67:1 | LL | const SLICE_TOO_LONG_BOX: Box<[u8]> = unsafe { mem::transmute((&42u8, 999usize)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered a dangling box (going beyond the bounds of its allocation) @@ -91,7 +91,7 @@ LL | const SLICE_TOO_LONG_BOX: Box<[u8]> = unsafe { mem::transmute((&42u8, 999us = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:76:1 + --> $DIR/ub-wide-ptr.rs:70:1 | LL | const SLICE_LENGTH_PTR_BOX: Box<[u8]> = unsafe { mem::transmute((&42u8, &3)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered non-integer slice length in wide pointer @@ -99,7 +99,7 @@ LL | const SLICE_LENGTH_PTR_BOX: Box<[u8]> = unsafe { mem::transmute((&42u8, &3) = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:80:1 + --> $DIR/ub-wide-ptr.rs:74:1 | LL | const SLICE_CONTENT_INVALID: &[bool] = &[unsafe { mem::transmute(3u8) }]; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 0x03 at .[0], but expected a boolean @@ -107,7 +107,7 @@ LL | const SLICE_CONTENT_INVALID: &[bool] = &[unsafe { mem::transmute(3u8) }]; = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:86:1 + --> $DIR/ub-wide-ptr.rs:80:1 | LL | const MYSLICE_PREFIX_BAD: &MySliceBool = &MySlice(unsafe { mem::transmute(3u8) }, [false]); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 0x03 at ..0, but expected a boolean @@ -115,7 +115,7 @@ LL | const MYSLICE_PREFIX_BAD: &MySliceBool = &MySlice(unsafe { mem::transmute(3 = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:89:1 + --> $DIR/ub-wide-ptr.rs:83:1 | LL | const MYSLICE_SUFFIX_BAD: &MySliceBool = &MySlice(true, [unsafe { mem::transmute(3u8) }]); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 0x03 at ..1[0], but expected a boolean @@ -123,7 +123,7 @@ LL | const MYSLICE_SUFFIX_BAD: &MySliceBool = &MySlice(true, [unsafe { mem::tran = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:96:1 + --> $DIR/ub-wide-ptr.rs:90:1 | LL | / const RAW_SLICE_LENGTH_UNINIT: *const [u8] = unsafe { LL | | @@ -134,32 +134,50 @@ LL | | }; | = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. -error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:104:1 +warning: any use of this value will cause an error + --> $DIR/ub-wide-ptr.rs:99:55 | -LL | const TRAIT_OBJ_SHORT_VTABLE_1: W<&dyn Trait> = unsafe { mem::transmute(W((&92u8, &3u8))) }; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered too small vtable at .0 +LL | const TRAIT_OBJ_SHORT_VTABLE_1: &dyn Trait = unsafe { mem::transmute((&92u8, &3u8)) }; + | ------------------------------------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^--- + | | + | memory access failed: pointer must be in-bounds at offset N, but is outside bounds of allocN which has size N | - = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. +note: the lint level is defined here + --> $DIR/ub-wide-ptr.rs:98:8 + | +LL | #[warn(const_err)] + | ^^^^^^^^^ -error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:107:1 +warning: any use of this value will cause an error + --> $DIR/ub-wide-ptr.rs:103:55 | -LL | const TRAIT_OBJ_SHORT_VTABLE_2: W<&dyn Trait> = unsafe { mem::transmute(W((&92u8, &3u64))) }; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered too small vtable at .0 +LL | const TRAIT_OBJ_SHORT_VTABLE_2: &dyn Trait = unsafe { mem::transmute((&92u8, &3u64)) }; + | ------------------------------------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^--- + | | + | memory access failed: pointer must be in-bounds at offset N, but is outside bounds of allocN which has size N | - = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. +note: the lint level is defined here + --> $DIR/ub-wide-ptr.rs:102:8 + | +LL | #[warn(const_err)] + | ^^^^^^^^^ -error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:110:1 +warning: any use of this value will cause an error + --> $DIR/ub-wide-ptr.rs:107:51 | -LL | const TRAIT_OBJ_INT_VTABLE: W<&dyn Trait> = unsafe { mem::transmute(W((&92u8, 4usize))) }; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered dangling vtable pointer in wide pointer at .0 +LL | const TRAIT_OBJ_INT_VTABLE: &dyn Trait = unsafe { mem::transmute((&92u8, 4usize)) }; + | --------------------------------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^--- + | | + | unable to turn bytes into a pointer | - = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. +note: the lint level is defined here + --> $DIR/ub-wide-ptr.rs:106:8 + | +LL | #[warn(const_err)] + | ^^^^^^^^^ error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:112:1 + --> $DIR/ub-wide-ptr.rs:109:1 | LL | const TRAIT_OBJ_UNALIGNED_VTABLE: &dyn Trait = unsafe { mem::transmute((&92u8, &[0u8; 128])) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered unaligned vtable pointer in wide pointer @@ -167,7 +185,7 @@ LL | const TRAIT_OBJ_UNALIGNED_VTABLE: &dyn Trait = unsafe { mem::transmute((&92 = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:114:1 + --> $DIR/ub-wide-ptr.rs:111:1 | LL | const TRAIT_OBJ_BAD_DROP_FN_NULL: &dyn Trait = unsafe { mem::transmute((&92u8, &[0usize; 8])) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered invalid drop function pointer in vtable (not pointing to a function) @@ -175,23 +193,29 @@ LL | const TRAIT_OBJ_BAD_DROP_FN_NULL: &dyn Trait = unsafe { mem::transmute((&92 = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:116:1 + --> $DIR/ub-wide-ptr.rs:113:1 | LL | const TRAIT_OBJ_BAD_DROP_FN_INT: &dyn Trait = unsafe { mem::transmute((&92u8, &[1usize; 8])) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered invalid drop function pointer in vtable (not pointing to a function) | = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. -error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:118:1 +warning: any use of this value will cause an error + --> $DIR/ub-wide-ptr.rs:116:63 | -LL | const TRAIT_OBJ_BAD_DROP_FN_NOT_FN_PTR: W<&dyn Trait> = unsafe { mem::transmute(W((&92u8, &[&42u8; 8]))) }; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered invalid drop function pointer in vtable (not pointing to a function) at .0 +LL | const TRAIT_OBJ_BAD_DROP_FN_NOT_FN_PTR: &dyn Trait = unsafe { mem::transmute((&92u8, &[&42u8; 8])) }; + | --------------------------------------------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^--- + | | + | "pointer-to-integer cast" needs an rfc before being allowed inside constants | - = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. +note: the lint level is defined here + --> $DIR/ub-wide-ptr.rs:115:8 + | +LL | #[warn(const_err)] + | ^^^^^^^^^ error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:122:1 + --> $DIR/ub-wide-ptr.rs:120:1 | LL | const TRAIT_OBJ_CONTENT_INVALID: &dyn Trait = unsafe { mem::transmute::<_, &bool>(&3u8) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 0x03 at .., but expected a boolean @@ -199,7 +223,7 @@ LL | const TRAIT_OBJ_CONTENT_INVALID: &dyn Trait = unsafe { mem::transmute::<_, = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:126:1 + --> $DIR/ub-wide-ptr.rs:124:1 | LL | const RAW_TRAIT_OBJ_VTABLE_NULL: *const dyn Trait = unsafe { mem::transmute((&92u8, 0usize)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered dangling vtable pointer in wide pointer @@ -207,7 +231,7 @@ LL | const RAW_TRAIT_OBJ_VTABLE_NULL: *const dyn Trait = unsafe { mem::transmute = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:128:1 + --> $DIR/ub-wide-ptr.rs:126:1 | LL | const RAW_TRAIT_OBJ_VTABLE_INVALID: *const dyn Trait = unsafe { mem::transmute((&92u8, &3u64)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered too small vtable @@ -215,17 +239,17 @@ LL | const RAW_TRAIT_OBJ_VTABLE_INVALID: *const dyn Trait = unsafe { mem::transm = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: could not evaluate static initializer - --> $DIR/ub-wide-ptr.rs:134:5 + --> $DIR/ub-wide-ptr.rs:132:5 | LL | mem::transmute::<_, &dyn Trait>((&92u8, 0usize)) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ inbounds test failed: 0x0 is not a valid pointer error[E0080]: could not evaluate static initializer - --> $DIR/ub-wide-ptr.rs:138:5 + --> $DIR/ub-wide-ptr.rs:136:5 | LL | mem::transmute::<_, &dyn Trait>((&92u8, &3u64)) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ memory access failed: pointer must be in-bounds at offset N, but is outside bounds of allocN which has size N -error: aborting due to 28 previous errors +error: aborting due to 24 previous errors; 4 warnings emitted For more information about this error, try `rustc --explain E0080`. diff --git a/src/test/ui/consts/const-extern-fn/const-extern-fn-call-extern-fn.rs b/src/test/ui/consts/const-extern-fn/const-extern-fn-call-extern-fn.rs index ee07dfae47c38..e18e0a83573ee 100644 --- a/src/test/ui/consts/const-extern-fn/const-extern-fn-call-extern-fn.rs +++ b/src/test/ui/consts/const-extern-fn/const-extern-fn-call-extern-fn.rs @@ -4,16 +4,16 @@ extern "C" { fn regular_in_block(); } -const extern "C" fn bar() { +const extern fn bar() { unsafe { regular_in_block(); //~^ ERROR: calls in constant functions } } -extern "C" fn regular() {} +extern fn regular() {} -const extern "C" fn foo() { +const extern fn foo() { unsafe { regular(); //~^ ERROR: calls in constant functions diff --git a/src/test/ui/consts/const-extern-fn/const-extern-fn-min-const-fn.rs b/src/test/ui/consts/const-extern-fn/const-extern-fn-min-const-fn.rs index 76380ebcb6599..645a957949c41 100644 --- a/src/test/ui/consts/const-extern-fn/const-extern-fn-min-const-fn.rs +++ b/src/test/ui/consts/const-extern-fn/const-extern-fn-min-const-fn.rs @@ -1,10 +1,10 @@ #![feature(const_extern_fn)] -const extern "C" fn unsize(x: &[u8; 3]) -> &[u8] { x } +const extern fn unsize(x: &[u8; 3]) -> &[u8] { x } const unsafe extern "C" fn closure() -> fn() { || {} } //~^ ERROR function pointer //~| ERROR function pointer cast -const unsafe extern "C" fn use_float() { 1.0 + 1.0; } +const unsafe extern fn use_float() { 1.0 + 1.0; } //~^ ERROR floating point arithmetic const extern "C" fn ptr_cast(val: *const u8) { val as usize; } //~^ ERROR casting pointers to integers diff --git a/src/test/ui/consts/const-extern-fn/const-extern-fn-min-const-fn.stderr b/src/test/ui/consts/const-extern-fn/const-extern-fn-min-const-fn.stderr index 80d234b0e881e..694e229080870 100644 --- a/src/test/ui/consts/const-extern-fn/const-extern-fn-min-const-fn.stderr +++ b/src/test/ui/consts/const-extern-fn/const-extern-fn-min-const-fn.stderr @@ -17,10 +17,10 @@ LL | const unsafe extern "C" fn closure() -> fn() { || {} } = help: add `#![feature(const_fn_fn_ptr_basics)]` to the crate attributes to enable error[E0658]: floating point arithmetic is not allowed in constant functions - --> $DIR/const-extern-fn-min-const-fn.rs:7:42 + --> $DIR/const-extern-fn-min-const-fn.rs:7:38 | -LL | const unsafe extern "C" fn use_float() { 1.0 + 1.0; } - | ^^^^^^^^^ +LL | const unsafe extern fn use_float() { 1.0 + 1.0; } + | ^^^^^^^^^ | = note: see issue #57241 for more information = help: add `#![feature(const_fn_floating_point_arithmetic)]` to the crate attributes to enable diff --git a/src/test/ui/consts/const-extern-fn/const-extern-fn-requires-unsafe.rs b/src/test/ui/consts/const-extern-fn/const-extern-fn-requires-unsafe.rs index 71e6c2cb85859..cab175bbfa818 100644 --- a/src/test/ui/consts/const-extern-fn/const-extern-fn-requires-unsafe.rs +++ b/src/test/ui/consts/const-extern-fn/const-extern-fn-requires-unsafe.rs @@ -1,6 +1,6 @@ #![feature(const_extern_fn)] -const unsafe extern "C" fn foo() -> usize { 5 } +const unsafe extern fn foo() -> usize { 5 } fn main() { let a: [u8; foo()]; diff --git a/src/test/ui/consts/const-extern-fn/const-extern-fn.rs b/src/test/ui/consts/const-extern-fn/const-extern-fn.rs index 2ce2eafd54507..1dc0f83cadf7d 100644 --- a/src/test/ui/consts/const-extern-fn/const-extern-fn.rs +++ b/src/test/ui/consts/const-extern-fn/const-extern-fn.rs @@ -1,7 +1,7 @@ // run-pass #![feature(const_extern_fn)] -const extern "C" fn foo1(val: u8) -> u8 { +const extern fn foo1(val: u8) -> u8 { val + 1 } @@ -9,7 +9,7 @@ const extern "C" fn foo2(val: u8) -> u8 { val + 1 } -const unsafe extern "C" fn bar1(val: bool) -> bool { +const unsafe extern fn bar1(val: bool) -> bool { !val } @@ -28,8 +28,8 @@ fn main() { assert!(bar1_res); assert_eq!(bar1_res, bar2_res); - let _foo1_cast: extern "C" fn(u8) -> u8 = foo1; - let _foo2_cast: extern "C" fn(u8) -> u8 = foo2; - let _bar1_cast: unsafe extern "C" fn(bool) -> bool = bar1; - let _bar2_cast: unsafe extern "C" fn(bool) -> bool = bar2; + let _foo1_cast: extern fn(u8) -> u8 = foo1; + let _foo2_cast: extern fn(u8) -> u8 = foo2; + let _bar1_cast: unsafe extern fn(bool) -> bool = bar1; + let _bar2_cast: unsafe extern fn(bool) -> bool = bar2; } diff --git a/src/test/ui/consts/const-extern-function.rs b/src/test/ui/consts/const-extern-function.rs index 01f487a7d7558..cfcf99b867a01 100644 --- a/src/test/ui/consts/const-extern-function.rs +++ b/src/test/ui/consts/const-extern-function.rs @@ -1,7 +1,7 @@ // run-pass #![allow(non_upper_case_globals)] -extern "C" fn foopy() {} +extern fn foopy() {} static f: extern "C" fn() = foopy; static s: S = S { f: foopy }; diff --git a/src/test/ui/consts/const-size_of_val-align_of_val-extern-type.rs b/src/test/ui/consts/const-size_of_val-align_of_val-extern-type.rs index 09c7d5580deca..96a8a8452edb0 100644 --- a/src/test/ui/consts/const-size_of_val-align_of_val-extern-type.rs +++ b/src/test/ui/consts/const-size_of_val-align_of_val-extern-type.rs @@ -2,9 +2,9 @@ #![feature(core_intrinsics)] #![feature(const_size_of_val, const_align_of_val)] -use std::intrinsics::{min_align_of_val, size_of_val}; +use std::intrinsics::{size_of_val, min_align_of_val}; -extern "C" { +extern { type Opaque; } diff --git a/src/test/ui/consts/intrinsic_without_const_stab.rs b/src/test/ui/consts/intrinsic_without_const_stab.rs deleted file mode 100644 index 810158a295792..0000000000000 --- a/src/test/ui/consts/intrinsic_without_const_stab.rs +++ /dev/null @@ -1,17 +0,0 @@ -#![feature(intrinsics, staged_api, const_intrinsic_copy)] -#![stable(feature = "core", since = "1.6.0")] - -#[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] -#[inline] -pub const unsafe fn copy(src: *const T, dst: *mut T, count: usize) { - // Const stability attributes are not inherited from parent items. - extern "rust-intrinsic" { - fn copy(src: *const T, dst: *mut T, count: usize); - } - - unsafe { copy(src, dst, count) } - //~^ ERROR calls in constant functions are limited to constant functions -} - -fn main() {} diff --git a/src/test/ui/consts/intrinsic_without_const_stab.stderr b/src/test/ui/consts/intrinsic_without_const_stab.stderr deleted file mode 100644 index 5a42823a6052a..0000000000000 --- a/src/test/ui/consts/intrinsic_without_const_stab.stderr +++ /dev/null @@ -1,9 +0,0 @@ -error[E0015]: calls in constant functions are limited to constant functions, tuple structs and tuple variants - --> $DIR/intrinsic_without_const_stab.rs:13:14 - | -LL | unsafe { copy(src, dst, count) } - | ^^^^^^^^^^^^^^^^^^^^^ - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0015`. diff --git a/src/test/ui/consts/intrinsic_without_const_stab_fail.rs b/src/test/ui/consts/intrinsic_without_const_stab_fail.rs deleted file mode 100644 index bf2c44169d48b..0000000000000 --- a/src/test/ui/consts/intrinsic_without_const_stab_fail.rs +++ /dev/null @@ -1,15 +0,0 @@ -#![feature(intrinsics, staged_api, const_intrinsic_copy)] -#![stable(feature = "core", since = "1.6.0")] - -extern "rust-intrinsic" { - fn copy(src: *const T, dst: *mut T, count: usize); -} - -#[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] -#[inline] -pub const unsafe fn stuff(src: *const T, dst: *mut T, count: usize) { - unsafe { copy(src, dst, count) } //~ ERROR calls in constant functions are limited -} - -fn main() {} diff --git a/src/test/ui/consts/intrinsic_without_const_stab_fail.stderr b/src/test/ui/consts/intrinsic_without_const_stab_fail.stderr deleted file mode 100644 index d4a2989e785e0..0000000000000 --- a/src/test/ui/consts/intrinsic_without_const_stab_fail.stderr +++ /dev/null @@ -1,9 +0,0 @@ -error[E0015]: calls in constant functions are limited to constant functions, tuple structs and tuple variants - --> $DIR/intrinsic_without_const_stab_fail.rs:12:14 - | -LL | unsafe { copy(src, dst, count) } - | ^^^^^^^^^^^^^^^^^^^^^ - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0015`. diff --git a/src/test/ui/cross-crate/auxiliary/cci_const.rs b/src/test/ui/cross-crate/auxiliary/cci_const.rs index c83b3f4a5bbf0..af6a5ad8ed39d 100644 --- a/src/test/ui/cross-crate/auxiliary/cci_const.rs +++ b/src/test/ui/cross-crate/auxiliary/cci_const.rs @@ -1,4 +1,4 @@ -pub extern "C" fn bar() { +pub extern fn bar() { } pub const foopy: &'static str = "hi there"; diff --git a/src/test/ui/destructuring-assignment/struct_destructure_fail.stderr b/src/test/ui/destructuring-assignment/struct_destructure_fail.stderr index c0955ef8b065a..81661a357e750 100644 --- a/src/test/ui/destructuring-assignment/struct_destructure_fail.stderr +++ b/src/test/ui/destructuring-assignment/struct_destructure_fail.stderr @@ -32,11 +32,11 @@ LL | Struct { a, _ } = Struct { a: 1, b: 2 }; | help: include the missing field in the pattern | -LL | Struct { a, b _ } = Struct { a: 1, b: 2 }; +LL | Struct { a, b, _ } = Struct { a: 1, b: 2 }; | ^^^ help: if you don't care about this missing field, you can explicitly ignore it | -LL | Struct { a, .. _ } = Struct { a: 1, b: 2 }; +LL | Struct { a, .., _ } = Struct { a: 1, b: 2 }; | ^^^^ error: aborting due to 5 previous errors diff --git a/src/test/ui/destructuring-assignment/tuple_struct_destructure_fail.stderr b/src/test/ui/destructuring-assignment/tuple_struct_destructure_fail.stderr index c270593cac741..0e7174e5b19d6 100644 --- a/src/test/ui/destructuring-assignment/tuple_struct_destructure_fail.stderr +++ b/src/test/ui/destructuring-assignment/tuple_struct_destructure_fail.stderr @@ -31,15 +31,6 @@ LL | struct TupleStruct(S, T); ... LL | TupleStruct(_) = TupleStruct(1, 2); | ^^^^^^^^^^^^^^ expected 2 fields, found 1 - | -help: use `_` to explicitly ignore each field - | -LL | TupleStruct(_, _) = TupleStruct(1, 2); - | ^^^ -help: use `..` to ignore all fields - | -LL | TupleStruct(..) = TupleStruct(1, 2); - | ^^ error[E0023]: this pattern has 3 fields, but the corresponding tuple variant has 2 fields --> $DIR/tuple_struct_destructure_fail.rs:34:5 @@ -58,15 +49,6 @@ LL | SingleVariant(S, T) ... LL | Enum::SingleVariant(_) = Enum::SingleVariant(1, 2); | ^^^^^^^^^^^^^^^^^^^^^^ expected 2 fields, found 1 - | -help: use `_` to explicitly ignore each field - | -LL | Enum::SingleVariant(_, _) = Enum::SingleVariant(1, 2); - | ^^^ -help: use `..` to ignore all fields - | -LL | Enum::SingleVariant(..) = Enum::SingleVariant(1, 2); - | ^^ error[E0070]: invalid left-hand side of assignment --> $DIR/tuple_struct_destructure_fail.rs:40:12 diff --git a/src/test/ui/duplicate/dupe-symbols-2.rs b/src/test/ui/duplicate/dupe-symbols-2.rs index e303a790bafca..d9edd77a19913 100644 --- a/src/test/ui/duplicate/dupe-symbols-2.rs +++ b/src/test/ui/duplicate/dupe-symbols-2.rs @@ -6,13 +6,13 @@ pub mod a { #[no_mangle] - pub extern "C" fn fail() { + pub extern fn fail() { } } pub mod b { #[no_mangle] - pub extern "C" fn fail() { + pub extern fn fail() { //~^ symbol `fail` is already defined } } diff --git a/src/test/ui/duplicate/dupe-symbols-2.stderr b/src/test/ui/duplicate/dupe-symbols-2.stderr index b132eae4b88d7..1b29edfb65598 100644 --- a/src/test/ui/duplicate/dupe-symbols-2.stderr +++ b/src/test/ui/duplicate/dupe-symbols-2.stderr @@ -1,8 +1,8 @@ error: symbol `fail` is already defined --> $DIR/dupe-symbols-2.rs:15:5 | -LL | pub extern "C" fn fail() { - | ^^^^^^^^^^^^^^^^^^^^^^^^ +LL | pub extern fn fail() { + | ^^^^^^^^^^^^^^^^^^^^ error: aborting due to previous error diff --git a/src/test/ui/emit-metadata-obj.rs b/src/test/ui/emit-metadata-obj.rs deleted file mode 100644 index 334c7cc5b8101..0000000000000 --- a/src/test/ui/emit-metadata-obj.rs +++ /dev/null @@ -1,7 +0,0 @@ -// compile-flags:--emit=metadata,obj -// build-pass - -// A test for the emission of metadata + obj and other metadata + non-link -// combinations. See issue #81117. - -fn main() {} diff --git a/src/test/ui/empty/empty-linkname.rs b/src/test/ui/empty/empty-linkname.rs index b64123389c2c1..79895ab583407 100644 --- a/src/test/ui/empty/empty-linkname.rs +++ b/src/test/ui/empty/empty-linkname.rs @@ -1,4 +1,5 @@ #[link(name = "")] //~ ERROR: given with empty name -extern "C" {} +extern { +} fn main() {} diff --git a/src/test/ui/threads-sendsync/eprint-on-tls-drop.rs b/src/test/ui/eprint-on-tls-drop.rs similarity index 100% rename from src/test/ui/threads-sendsync/eprint-on-tls-drop.rs rename to src/test/ui/eprint-on-tls-drop.rs diff --git a/src/test/ui/error-codes/E0023.stderr b/src/test/ui/error-codes/E0023.stderr index 832eba6972213..a3610099294da 100644 --- a/src/test/ui/error-codes/E0023.stderr +++ b/src/test/ui/error-codes/E0023.stderr @@ -6,11 +6,6 @@ LL | Apple(String, String), ... LL | Fruit::Apple(a) => {}, | ^^^^^^^^^^^^^^^ expected 2 fields, found 1 - | -help: use `_` to explicitly ignore each field - | -LL | Fruit::Apple(a, _) => {}, - | ^^^ error[E0023]: this pattern has 3 fields, but the corresponding tuple variant has 2 fields --> $DIR/E0023.rs:12:9 @@ -39,7 +34,7 @@ LL | Orange((String, String)), LL | Fruit::Orange(a, b) => {}, | ^^^^^^^^^^^^^^^^^^^ expected 1 field, found 2 | -help: missing parentheses +help: missing parenthesis | LL | Fruit::Orange((a, b)) => {}, | ^ ^ @@ -53,7 +48,7 @@ LL | Banana(()), LL | Fruit::Banana() => {}, | ^^^^^^^^^^^^^^^ expected 1 field, found 0 | -help: missing parentheses +help: missing parenthesis | LL | Fruit::Banana(()) => {}, | ^ ^ diff --git a/src/test/ui/error-codes/E0027.rs b/src/test/ui/error-codes/E0027.rs index e7eca1ce5af97..8d08e17893480 100644 --- a/src/test/ui/error-codes/E0027.rs +++ b/src/test/ui/error-codes/E0027.rs @@ -3,21 +3,12 @@ struct Dog { age: u32, } - fn main() { let d = Dog { name: "Rusty".to_string(), age: 8 }; match d { Dog { age: x } => {} //~ ERROR pattern does not mention field `name` } - match d { - // trailing comma - Dog { name: x, } => {} //~ ERROR pattern does not mention field `age` - } - match d { - // trailing comma with weird whitespace - Dog { name: x , } => {} //~ ERROR pattern does not mention field `age` - } match d { Dog {} => {} //~ ERROR pattern does not mention fields `name`, `age` } diff --git a/src/test/ui/error-codes/E0027.stderr b/src/test/ui/error-codes/E0027.stderr index 694bbc358fee2..cf0ff6311483c 100644 --- a/src/test/ui/error-codes/E0027.stderr +++ b/src/test/ui/error-codes/E0027.stderr @@ -1,5 +1,5 @@ error[E0027]: pattern does not mention field `name` - --> $DIR/E0027.rs:11:9 + --> $DIR/E0027.rs:10:9 | LL | Dog { age: x } => {} | ^^^^^^^^^^^^^^ missing field `name` @@ -13,38 +13,8 @@ help: if you don't care about this missing field, you can explicitly ignore it LL | Dog { age: x, .. } => {} | ^^^^ -error[E0027]: pattern does not mention field `age` - --> $DIR/E0027.rs:15:9 - | -LL | Dog { name: x, } => {} - | ^^^^^^^^^^^^^^^^ missing field `age` - | -help: include the missing field in the pattern - | -LL | Dog { name: x, age } => {} - | ^^^^^ -help: if you don't care about this missing field, you can explicitly ignore it - | -LL | Dog { name: x, .. } => {} - | ^^^^ - -error[E0027]: pattern does not mention field `age` - --> $DIR/E0027.rs:19:9 - | -LL | Dog { name: x , } => {} - | ^^^^^^^^^^^^^^^^^^ missing field `age` - | -help: include the missing field in the pattern - | -LL | Dog { name: x, age } => {} - | ^^^^^ -help: if you don't care about this missing field, you can explicitly ignore it - | -LL | Dog { name: x, .. } => {} - | ^^^^ - error[E0027]: pattern does not mention fields `name`, `age` - --> $DIR/E0027.rs:22:9 + --> $DIR/E0027.rs:13:9 | LL | Dog {} => {} | ^^^^^^ missing fields `name`, `age` @@ -58,6 +28,6 @@ help: if you don't care about these missing fields, you can explicitly ignore th LL | Dog { .. } => {} | ^^^^^^ -error: aborting due to 4 previous errors +error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0027`. diff --git a/src/test/ui/error-codes/E0040.fixed b/src/test/ui/error-codes/E0040.fixed deleted file mode 100644 index 139dc8f94964f..0000000000000 --- a/src/test/ui/error-codes/E0040.fixed +++ /dev/null @@ -1,18 +0,0 @@ -// run-rustfix -struct Foo { - x: i32, -} - -impl Drop for Foo { - fn drop(&mut self) { - println!("kaboom"); - } -} - -fn main() { - let mut x = Foo { x: -7 }; - x.x = 0; - println!("{}", x.x); - drop(x); - //~^ ERROR E0040 -} diff --git a/src/test/ui/error-codes/E0040.rs b/src/test/ui/error-codes/E0040.rs index 9ffc42d0c7804..113efae82c510 100644 --- a/src/test/ui/error-codes/E0040.rs +++ b/src/test/ui/error-codes/E0040.rs @@ -1,4 +1,3 @@ -// run-rustfix struct Foo { x: i32, } @@ -11,8 +10,6 @@ impl Drop for Foo { fn main() { let mut x = Foo { x: -7 }; - x.x = 0; - println!("{}", x.x); x.drop(); //~^ ERROR E0040 } diff --git a/src/test/ui/error-codes/E0040.stderr b/src/test/ui/error-codes/E0040.stderr index 9fcda1a9385d2..69cf28b29704f 100644 --- a/src/test/ui/error-codes/E0040.stderr +++ b/src/test/ui/error-codes/E0040.stderr @@ -1,11 +1,11 @@ error[E0040]: explicit use of destructor method - --> $DIR/E0040.rs:16:7 + --> $DIR/E0040.rs:13:7 | LL | x.drop(); - | --^^^^-- - | | | - | | explicit destructor calls not allowed - | help: consider using `drop` function: `drop(x)` + | ^^^^ + | | + | explicit destructor calls not allowed + | help: consider using `drop` function: `drop(x)` error: aborting due to previous error diff --git a/src/test/ui/error-codes/E0044.rs b/src/test/ui/error-codes/E0044.rs index d9cdaf83c698c..9eee9c31d3c38 100644 --- a/src/test/ui/error-codes/E0044.rs +++ b/src/test/ui/error-codes/E0044.rs @@ -1,8 +1,9 @@ -extern "C" { +extern { fn sqrt(f: T) -> T; -//~^ ERROR foreign items may not have type parameters [E0044] -//~| HELP replace the type parameters with concrete types -//~| NOTE can't have type parameters + //~^ ERROR foreign items may not have type parameters [E0044] + //~| HELP replace the type parameters with concrete types + //~| NOTE can't have type parameters } -fn main() {} +fn main() { +} diff --git a/src/test/ui/error-codes/E0107.rs b/src/test/ui/error-codes/E0107.rs index c3dde72599b71..35173dcce3012 100644 --- a/src/test/ui/error-codes/E0107.rs +++ b/src/test/ui/error-codes/E0107.rs @@ -9,16 +9,15 @@ enum Bar { struct Baz<'a, 'b, 'c> { buzz: Buzz<'a>, - //~^ ERROR this struct takes 2 lifetime arguments but only 1 lifetime argument was supplied - //~| HELP add missing lifetime argument - + //~^ ERROR E0107 + //~| expected 2 lifetime arguments bar: Bar<'a>, - //~^ ERROR this enum takes 0 lifetime arguments but 1 lifetime argument was supplied - //~| HELP remove these generics - + //~^ ERROR E0107 + //~| unexpected lifetime argument foo2: Foo<'a, 'b, 'c>, - //~^ ERROR this struct takes 1 lifetime argument but 3 lifetime arguments were supplied - //~| HELP remove these lifetime arguments + //~^ ERROR E0107 + //~| unexpected lifetime argument + //~| unexpected lifetime argument } fn main() {} diff --git a/src/test/ui/error-codes/E0107.stderr b/src/test/ui/error-codes/E0107.stderr index 30a2768d06058..486810ab113cc 100644 --- a/src/test/ui/error-codes/E0107.stderr +++ b/src/test/ui/error-codes/E0107.stderr @@ -1,48 +1,22 @@ -error[E0107]: this struct takes 2 lifetime arguments but only 1 lifetime argument was supplied +error[E0107]: wrong number of lifetime arguments: expected 2, found 1 --> $DIR/E0107.rs:11:11 | LL | buzz: Buzz<'a>, - | ^^^^ -- supplied 1 lifetime argument - | | - | expected 2 lifetime arguments - | -note: struct defined here, with 2 lifetime parameters: `'a`, `'b` - --> $DIR/E0107.rs:2:8 - | -LL | struct Buzz<'a, 'b>(&'a str, &'b str); - | ^^^^ -- -- -help: add missing lifetime argument - | -LL | buzz: Buzz<'a, 'b>, - | ^^^^ + | ^^^^^^^^ expected 2 lifetime arguments -error[E0107]: this enum takes 0 lifetime arguments but 1 lifetime argument was supplied - --> $DIR/E0107.rs:15:10 +error[E0107]: wrong number of lifetime arguments: expected 0, found 1 + --> $DIR/E0107.rs:14:14 | LL | bar: Bar<'a>, - | ^^^---- help: remove these generics - | | - | expected 0 lifetime arguments - | -note: enum defined here, with 0 lifetime parameters - --> $DIR/E0107.rs:4:6 - | -LL | enum Bar { - | ^^^ + | ^^ unexpected lifetime argument -error[E0107]: this struct takes 1 lifetime argument but 3 lifetime arguments were supplied - --> $DIR/E0107.rs:19:11 +error[E0107]: wrong number of lifetime arguments: expected 1, found 3 + --> $DIR/E0107.rs:17:19 | LL | foo2: Foo<'a, 'b, 'c>, - | ^^^ -------- help: remove these lifetime arguments - | | - | expected 1 lifetime argument - | -note: struct defined here, with 1 lifetime parameter: `'a` - --> $DIR/E0107.rs:1:8 - | -LL | struct Foo<'a>(&'a str); - | ^^^ -- + | ^^ ^^ unexpected lifetime argument + | | + | unexpected lifetime argument error: aborting due to 3 previous errors diff --git a/src/test/ui/error-codes/E0130.rs b/src/test/ui/error-codes/E0130.rs index d523507899fbc..1ac546b9dbe4d 100644 --- a/src/test/ui/error-codes/E0130.rs +++ b/src/test/ui/error-codes/E0130.rs @@ -1,6 +1,7 @@ -extern "C" { +extern { fn foo((a, b): (u32, u32)); -//~^ ERROR E0130 + //~^ ERROR E0130 } -fn main() {} +fn main() { +} diff --git a/src/test/ui/error-codes/E0283.rs b/src/test/ui/error-codes/E0283.rs index 4d7c2f2396d75..9bdcc9ac42a7a 100644 --- a/src/test/ui/error-codes/E0283.rs +++ b/src/test/ui/error-codes/E0283.rs @@ -8,18 +8,6 @@ impl Generator for Impl { fn create() -> u32 { 1 } } -impl Impl { - fn new() -> Self { - Impl{} - } -} - -impl Into for Impl { - fn into(self) -> u32 { 1 } -} - -fn foo(bar: u32) {} - struct AnotherImpl; impl Generator for AnotherImpl { @@ -29,9 +17,3 @@ impl Generator for AnotherImpl { fn main() { let cont: u32 = Generator::create(); //~ ERROR E0283 } - -fn buzz() { - let foo_impl = Impl::new(); - let bar = foo_impl.into() * 1u32; //~ ERROR E0283 - foo(bar); -} diff --git a/src/test/ui/error-codes/E0283.stderr b/src/test/ui/error-codes/E0283.stderr index 2f0dfb6dd8248..e95583c91a72f 100644 --- a/src/test/ui/error-codes/E0283.stderr +++ b/src/test/ui/error-codes/E0283.stderr @@ -1,5 +1,5 @@ error[E0283]: type annotations needed - --> $DIR/E0283.rs:30:21 + --> $DIR/E0283.rs:18:21 | LL | fn create() -> u32; | ------------------- required by `Generator::create` @@ -9,18 +9,6 @@ LL | let cont: u32 = Generator::create(); | = note: cannot satisfy `_: Generator` -error[E0283]: type annotations needed - --> $DIR/E0283.rs:35:24 - | -LL | let bar = foo_impl.into() * 1u32; - | ---------^^^^-- - | | | - | | cannot infer type for type parameter `T` declared on the trait `Into` - | this method call resolves to `T` - | help: use the fully qualified path for the potential candidate: `>::into(foo_impl)` - | - = note: cannot satisfy `Impl: Into<_>` - -error: aborting due to 2 previous errors +error: aborting due to previous error For more information about this error, try `rustc --explain E0283`. diff --git a/src/test/ui/error-codes/E0454.rs b/src/test/ui/error-codes/E0454.rs index ff5478382cc90..d62210c3f94a7 100644 --- a/src/test/ui/error-codes/E0454.rs +++ b/src/test/ui/error-codes/E0454.rs @@ -1,4 +1,4 @@ -#[link(name = "")] extern "C" {} +#[link(name = "")] extern {} //~^ ERROR E0454 fn main() { diff --git a/src/test/ui/error-codes/E0454.stderr b/src/test/ui/error-codes/E0454.stderr index 6b62bef112fe7..499162694e57d 100644 --- a/src/test/ui/error-codes/E0454.stderr +++ b/src/test/ui/error-codes/E0454.stderr @@ -1,7 +1,7 @@ error[E0454]: `#[link(name = "")]` given with empty name --> $DIR/E0454.rs:1:1 | -LL | #[link(name = "")] extern "C" {} +LL | #[link(name = "")] extern {} | ^^^^^^^^^^^^^^^^^^ empty name given error: aborting due to previous error diff --git a/src/test/ui/error-codes/E0458.rs b/src/test/ui/error-codes/E0458.rs index 35e7e84d4796d..3d2303587219c 100644 --- a/src/test/ui/error-codes/E0458.rs +++ b/src/test/ui/error-codes/E0458.rs @@ -1,5 +1,5 @@ -#[link(kind = "wonderful_unicorn")] extern "C" {} //~ ERROR E0458 - //~| ERROR E0459 +#[link(kind = "wonderful_unicorn")] extern {} //~ ERROR E0458 + //~| ERROR E0459 fn main() { } diff --git a/src/test/ui/error-codes/E0458.stderr b/src/test/ui/error-codes/E0458.stderr index 0f2fec029e78d..51f7764aaf283 100644 --- a/src/test/ui/error-codes/E0458.stderr +++ b/src/test/ui/error-codes/E0458.stderr @@ -1,7 +1,7 @@ error[E0458]: unknown kind: `wonderful_unicorn` --> $DIR/E0458.rs:1:8 | -LL | #[link(kind = "wonderful_unicorn")] extern "C" {} +LL | #[link(kind = "wonderful_unicorn")] extern {} | -------^^^^^^^^^^^^^^^^^^^^^^^^^^-- | | | unknown kind @@ -9,7 +9,7 @@ LL | #[link(kind = "wonderful_unicorn")] extern "C" {} error[E0459]: `#[link(...)]` specified without `name = "foo"` --> $DIR/E0458.rs:1:1 | -LL | #[link(kind = "wonderful_unicorn")] extern "C" {} +LL | #[link(kind = "wonderful_unicorn")] extern {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `name` argument error: aborting due to 2 previous errors diff --git a/src/test/ui/error-codes/E0459.rs b/src/test/ui/error-codes/E0459.rs index c56d8f0a8a848..80a2fd3515136 100644 --- a/src/test/ui/error-codes/E0459.rs +++ b/src/test/ui/error-codes/E0459.rs @@ -1,4 +1,4 @@ -#[link(kind = "dylib")] extern "C" {} //~ ERROR E0459 +#[link(kind = "dylib")] extern {} //~ ERROR E0459 fn main() { } diff --git a/src/test/ui/error-codes/E0459.stderr b/src/test/ui/error-codes/E0459.stderr index 4e0d51e87538a..c618fea9afc8a 100644 --- a/src/test/ui/error-codes/E0459.stderr +++ b/src/test/ui/error-codes/E0459.stderr @@ -1,7 +1,7 @@ error[E0459]: `#[link(...)]` specified without `name = "foo"` --> $DIR/E0459.rs:1:1 | -LL | #[link(kind = "dylib")] extern "C" {} +LL | #[link(kind = "dylib")] extern {} | ^^^^^^^^^^^^^^^^^^^^^^^ missing `name` argument error: aborting due to previous error diff --git a/src/test/ui/error-codes/E0617.rs b/src/test/ui/error-codes/E0617.rs index b71ba0ed88b9f..c832e09ac1118 100644 --- a/src/test/ui/error-codes/E0617.rs +++ b/src/test/ui/error-codes/E0617.rs @@ -1,4 +1,4 @@ -extern "C" { +extern { fn printf(c: *const i8, ...); } diff --git a/src/test/ui/explicit/explicit-call-to-dtor.fixed b/src/test/ui/explicit/explicit-call-to-dtor.fixed deleted file mode 100644 index 91a4ca608da4e..0000000000000 --- a/src/test/ui/explicit/explicit-call-to-dtor.fixed +++ /dev/null @@ -1,16 +0,0 @@ -// run-rustfix -struct Foo { - x: isize -} - -impl Drop for Foo { - fn drop(&mut self) { - println!("kaboom"); - } -} - -fn main() { - let x = Foo { x: 3 }; - println!("{}", x.x); - drop(x); //~ ERROR explicit use of destructor method -} diff --git a/src/test/ui/explicit/explicit-call-to-dtor.rs b/src/test/ui/explicit/explicit-call-to-dtor.rs index 0656871eb1b34..a6f9acc37a16d 100644 --- a/src/test/ui/explicit/explicit-call-to-dtor.rs +++ b/src/test/ui/explicit/explicit-call-to-dtor.rs @@ -1,4 +1,3 @@ -// run-rustfix struct Foo { x: isize } @@ -11,6 +10,5 @@ impl Drop for Foo { fn main() { let x = Foo { x: 3 }; - println!("{}", x.x); x.drop(); //~ ERROR explicit use of destructor method } diff --git a/src/test/ui/explicit/explicit-call-to-dtor.stderr b/src/test/ui/explicit/explicit-call-to-dtor.stderr index f3c9bf6cccdd3..5ebe4ee4b90f8 100644 --- a/src/test/ui/explicit/explicit-call-to-dtor.stderr +++ b/src/test/ui/explicit/explicit-call-to-dtor.stderr @@ -1,11 +1,11 @@ error[E0040]: explicit use of destructor method - --> $DIR/explicit-call-to-dtor.rs:15:7 + --> $DIR/explicit-call-to-dtor.rs:13:7 | LL | x.drop(); - | --^^^^-- - | | | - | | explicit destructor calls not allowed - | help: consider using `drop` function: `drop(x)` + | ^^^^ + | | + | explicit destructor calls not allowed + | help: consider using `drop` function: `drop(x)` error: aborting due to previous error diff --git a/src/test/ui/explicit/explicit-call-to-supertrait-dtor.fixed b/src/test/ui/explicit/explicit-call-to-supertrait-dtor.fixed deleted file mode 100644 index 47c4c9f67b692..0000000000000 --- a/src/test/ui/explicit/explicit-call-to-supertrait-dtor.fixed +++ /dev/null @@ -1,26 +0,0 @@ -// run-rustfix -struct Foo { - x: isize -} - -#[allow(drop_bounds)] -trait Bar: Drop { - fn blah(&self); -} - -impl Drop for Foo { - fn drop(&mut self) { - println!("kaboom"); - } -} - -impl Bar for Foo { - fn blah(&self) { - drop(self); //~ ERROR explicit use of destructor method - } -} - -fn main() { - let x = Foo { x: 3 }; - println!("{}", x.x); -} diff --git a/src/test/ui/explicit/explicit-call-to-supertrait-dtor.rs b/src/test/ui/explicit/explicit-call-to-supertrait-dtor.rs index c698de50c75b8..ff56b9a8ae424 100644 --- a/src/test/ui/explicit/explicit-call-to-supertrait-dtor.rs +++ b/src/test/ui/explicit/explicit-call-to-supertrait-dtor.rs @@ -1,10 +1,8 @@ -// run-rustfix struct Foo { x: isize } -#[allow(drop_bounds)] -trait Bar: Drop { +trait Bar : Drop { fn blah(&self); } @@ -22,5 +20,4 @@ impl Bar for Foo { fn main() { let x = Foo { x: 3 }; - println!("{}", x.x); } diff --git a/src/test/ui/explicit/explicit-call-to-supertrait-dtor.stderr b/src/test/ui/explicit/explicit-call-to-supertrait-dtor.stderr index 7f5106eb57e54..cd3fb3119a5cf 100644 --- a/src/test/ui/explicit/explicit-call-to-supertrait-dtor.stderr +++ b/src/test/ui/explicit/explicit-call-to-supertrait-dtor.stderr @@ -1,11 +1,11 @@ error[E0040]: explicit use of destructor method - --> $DIR/explicit-call-to-supertrait-dtor.rs:19:14 + --> $DIR/explicit-call-to-supertrait-dtor.rs:17:14 | LL | self.drop(); - | -----^^^^-- - | | | - | | explicit destructor calls not allowed - | help: consider using `drop` function: `drop(self)` + | ^^^^ + | | + | explicit destructor calls not allowed + | help: consider using `drop` function: `drop(self)` error: aborting due to previous error diff --git a/src/test/ui/lint/expr_attr_paren_order.rs b/src/test/ui/expr_attr_paren_order.rs similarity index 100% rename from src/test/ui/lint/expr_attr_paren_order.rs rename to src/test/ui/expr_attr_paren_order.rs diff --git a/src/test/ui/lint/expr_attr_paren_order.stderr b/src/test/ui/expr_attr_paren_order.stderr similarity index 100% rename from src/test/ui/lint/expr_attr_paren_order.stderr rename to src/test/ui/expr_attr_paren_order.stderr diff --git a/src/test/ui/extern/auxiliary/extern-take-value.rs b/src/test/ui/extern/auxiliary/extern-take-value.rs index 56256aa1927ee..869e794cc8a88 100644 --- a/src/test/ui/extern/auxiliary/extern-take-value.rs +++ b/src/test/ui/extern/auxiliary/extern-take-value.rs @@ -1,5 +1,5 @@ -pub extern "C" fn f() -> i32 { 1 } -pub extern "C" fn g() -> i32 { 2 } +pub extern fn f() -> i32 { 1 } +pub extern fn g() -> i32 { 2 } -pub fn get_f() -> extern "C" fn() -> i32 { f } -pub fn get_g() -> extern "C" fn() -> i32 { g } +pub fn get_f() -> extern fn() -> i32 { f } +pub fn get_g() -> extern fn() -> i32 { g } diff --git a/src/test/ui/extern/auxiliary/extern_calling_convention.rs b/src/test/ui/extern/auxiliary/extern_calling_convention.rs index e24cf9fdaa0c5..968b1a2551098 100644 --- a/src/test/ui/extern/auxiliary/extern_calling_convention.rs +++ b/src/test/ui/extern/auxiliary/extern_calling_convention.rs @@ -15,7 +15,7 @@ pub extern "win64" fn foo(a: isize, b: isize, c: isize, d: isize) { #[inline(never)] #[cfg(not(target_arch = "x86_64"))] -pub extern "C" fn foo(a: isize, b: isize, c: isize, d: isize) { +pub extern fn foo(a: isize, b: isize, c: isize, d: isize) { assert_eq!(a, 1); assert_eq!(b, 2); assert_eq!(c, 3); diff --git a/src/test/ui/extern/extern-1.rs b/src/test/ui/extern/extern-1.rs index 66e560501720c..eb9aabc87bc8b 100644 --- a/src/test/ui/extern/extern-1.rs +++ b/src/test/ui/extern/extern-1.rs @@ -2,7 +2,7 @@ #![allow(dead_code)] // pretty-expanded FIXME #23616 -extern "C" fn f() { +extern fn f() { } pub fn main() { diff --git a/src/test/ui/extern/extern-compare-with-return-type.rs b/src/test/ui/extern/extern-compare-with-return-type.rs index 1ddfc77a4c43a..6c9ed3760f6e4 100644 --- a/src/test/ui/extern/extern-compare-with-return-type.rs +++ b/src/test/ui/extern/extern-compare-with-return-type.rs @@ -2,24 +2,23 @@ // Tests that we can compare various kinds of extern fn signatures. #![allow(non_camel_case_types)] -// `dbg!()` differentiates these functions to ensure they won't be merged. -extern "C" fn voidret1() { dbg!() } -extern "C" fn voidret2() { dbg!() } +extern fn voidret1() {} +extern fn voidret2() {} -extern "C" fn uintret() -> usize { 22 } +extern fn uintret() -> usize { 22 } -extern "C" fn uintvoidret(_x: usize) {} +extern fn uintvoidret(_x: usize) {} -extern "C" fn uintuintuintuintret(x: usize, y: usize, z: usize) -> usize { x+y+z } -type uintuintuintuintret = extern "C" fn(usize,usize,usize) -> usize; +extern fn uintuintuintuintret(x: usize, y: usize, z: usize) -> usize { x+y+z } +type uintuintuintuintret = extern fn(usize,usize,usize) -> usize; pub fn main() { - assert!(voidret1 as extern "C" fn() == voidret1 as extern "C" fn()); - assert!(voidret1 as extern "C" fn() != voidret2 as extern "C" fn()); + assert!(voidret1 as extern fn() == voidret1 as extern fn()); + assert!(voidret1 as extern fn() != voidret2 as extern fn()); - assert!(uintret as extern "C" fn() -> usize == uintret as extern "C" fn() -> usize); + assert!(uintret as extern fn() -> usize == uintret as extern fn() -> usize); - assert!(uintvoidret as extern "C" fn(usize) == uintvoidret as extern "C" fn(usize)); + assert!(uintvoidret as extern fn(usize) == uintvoidret as extern fn(usize)); assert!(uintuintuintuintret as uintuintuintuintret == uintuintuintuintret as uintuintuintuintret); diff --git a/src/test/ui/extern/extern-main-fn.rs b/src/test/ui/extern/extern-main-fn.rs index bb1468a70fb1e..ddf2e136f03ce 100644 --- a/src/test/ui/extern/extern-main-fn.rs +++ b/src/test/ui/extern/extern-main-fn.rs @@ -1 +1 @@ -extern "C" fn main() {} //~ ERROR: `main` function has wrong type [E0580] +extern fn main() {} //~ ERROR: `main` function has wrong type [E0580] diff --git a/src/test/ui/extern/extern-main-fn.stderr b/src/test/ui/extern/extern-main-fn.stderr index 136c957538248..9c994985a3e0d 100644 --- a/src/test/ui/extern/extern-main-fn.stderr +++ b/src/test/ui/extern/extern-main-fn.stderr @@ -1,8 +1,8 @@ error[E0580]: `main` function has wrong type --> $DIR/extern-main-fn.rs:1:1 | -LL | extern "C" fn main() {} - | ^^^^^^^^^^^^^^^^^^^^ expected "Rust" fn, found "C" fn +LL | extern fn main() {} + | ^^^^^^^^^^^^^^^^ expected "Rust" fn, found "C" fn | = note: expected fn pointer `fn()` found fn pointer `extern "C" fn()` diff --git a/src/test/ui/extern/extern-methods.rs b/src/test/ui/extern/extern-methods.rs index 97559a6844219..3c3e229104e0e 100644 --- a/src/test/ui/extern/extern-methods.rs +++ b/src/test/ui/extern/extern-methods.rs @@ -5,7 +5,7 @@ trait A { extern "fastcall" fn test1(i: i32); - extern "C" fn test2(i: i32); + extern fn test2(i: i32); } struct S; @@ -19,7 +19,7 @@ impl A for S { extern "fastcall" fn test1(i: i32) { assert_eq!(i, 1); } - extern "C" fn test2(i: i32) { + extern fn test2(i: i32) { assert_eq!(i, 2); } } diff --git a/src/test/ui/extern/extern-pub.rs b/src/test/ui/extern/extern-pub.rs index 0b95045a03eb7..c97e04b0755ee 100644 --- a/src/test/ui/extern/extern-pub.rs +++ b/src/test/ui/extern/extern-pub.rs @@ -1,8 +1,9 @@ // run-pass // pretty-expanded FIXME #23616 -extern "C" { +extern { pub fn free(p: *const u8); } -pub fn main() {} +pub fn main() { +} diff --git a/src/test/ui/extern/extern-rust.rs b/src/test/ui/extern/extern-rust.rs index 7cea8be59215f..0cb190257be89 100644 --- a/src/test/ui/extern/extern-rust.rs +++ b/src/test/ui/extern/extern-rust.rs @@ -5,7 +5,7 @@ pub struct Foo(u32); // ICE trigger, bad handling of differing types between rust and external ABIs -pub extern "C" fn bar() -> Foo { +pub extern fn bar() -> Foo { Foo(0) } diff --git a/src/test/ui/extern/extern-types-distinct-types.rs b/src/test/ui/extern/extern-types-distinct-types.rs index 4da049b788212..000ba5432e492 100644 --- a/src/test/ui/extern/extern-types-distinct-types.rs +++ b/src/test/ui/extern/extern-types-distinct-types.rs @@ -1,6 +1,6 @@ #![feature(extern_types)] -extern "C" { +extern { type A; type B; } @@ -9,4 +9,4 @@ fn foo(r: &A) -> &B { r //~ ERROR mismatched types } -fn main() {} +fn main() { } diff --git a/src/test/ui/extern/extern-types-manual-sync-send.rs b/src/test/ui/extern/extern-types-manual-sync-send.rs index 87eb3f6224004..ec63e5d40b9af 100644 --- a/src/test/ui/extern/extern-types-manual-sync-send.rs +++ b/src/test/ui/extern/extern-types-manual-sync-send.rs @@ -3,15 +3,15 @@ #![feature(extern_types)] -extern "C" { +extern { type A; } -unsafe impl Sync for A {} -unsafe impl Send for A {} +unsafe impl Sync for A { } +unsafe impl Send for A { } -fn assert_sync() {} -fn assert_send() {} +fn assert_sync() { } +fn assert_send() { } fn main() { assert_sync::(); diff --git a/src/test/ui/extern/extern-types-not-sync-send.rs b/src/test/ui/extern/extern-types-not-sync-send.rs index ba82caced7a4e..3af8b9bf4aa92 100644 --- a/src/test/ui/extern/extern-types-not-sync-send.rs +++ b/src/test/ui/extern/extern-types-not-sync-send.rs @@ -2,12 +2,12 @@ #![feature(extern_types)] -extern "C" { +extern { type A; } -fn assert_sync() {} -fn assert_send() {} +fn assert_sync() { } +fn assert_send() { } fn main() { assert_sync::(); diff --git a/src/test/ui/extern/extern-types-not-sync-send.stderr b/src/test/ui/extern/extern-types-not-sync-send.stderr index 547116fbbabed..dc9810cfcf9b7 100644 --- a/src/test/ui/extern/extern-types-not-sync-send.stderr +++ b/src/test/ui/extern/extern-types-not-sync-send.stderr @@ -1,7 +1,7 @@ error[E0277]: `A` cannot be shared between threads safely --> $DIR/extern-types-not-sync-send.rs:13:19 | -LL | fn assert_sync() {} +LL | fn assert_sync() { } | ---- required by this bound in `assert_sync` ... LL | assert_sync::(); @@ -12,7 +12,7 @@ LL | assert_sync::(); error[E0277]: `A` cannot be sent between threads safely --> $DIR/extern-types-not-sync-send.rs:16:19 | -LL | fn assert_send() {} +LL | fn assert_send() { } | ---- required by this bound in `assert_send` ... LL | assert_send::(); diff --git a/src/test/ui/extern/extern-types-pointer-cast.rs b/src/test/ui/extern/extern-types-pointer-cast.rs index de6955bfaaa13..a4ebd3cf71e7a 100644 --- a/src/test/ui/extern/extern-types-pointer-cast.rs +++ b/src/test/ui/extern/extern-types-pointer-cast.rs @@ -2,9 +2,10 @@ #![allow(dead_code)] // Test that pointers to extern types can be cast from/to usize, // despite being !Sized. + #![feature(extern_types)] -extern "C" { +extern { type A; } diff --git a/src/test/ui/extern/extern-types-size_of_val.rs b/src/test/ui/extern/extern-types-size_of_val.rs index 3b02ea28eaa28..1c9656097585e 100644 --- a/src/test/ui/extern/extern-types-size_of_val.rs +++ b/src/test/ui/extern/extern-types-size_of_val.rs @@ -1,14 +1,16 @@ // run-pass #![feature(extern_types)] -use std::mem::{align_of_val, size_of_val}; +use std::mem::{size_of_val, align_of_val}; -extern "C" { +extern { type A; } fn main() { - let x: &A = unsafe { &*(1usize as *const A) }; + let x: &A = unsafe { + &*(1usize as *const A) + }; assert_eq!(size_of_val(x), 0); assert_eq!(align_of_val(x), 1); diff --git a/src/test/ui/extern/extern-types-thin-pointer.rs b/src/test/ui/extern/extern-types-thin-pointer.rs index b85fc4886abe0..83c35f7af78ea 100644 --- a/src/test/ui/extern/extern-types-thin-pointer.rs +++ b/src/test/ui/extern/extern-types-thin-pointer.rs @@ -2,11 +2,12 @@ #![allow(dead_code)] // Test that pointers and references to extern types are thin, ie they have the same size and // alignment as a pointer to (). + #![feature(extern_types)] use std::mem::{align_of, size_of}; -extern "C" { +extern { type A; } diff --git a/src/test/ui/extern/extern-types-trait-impl.rs b/src/test/ui/extern/extern-types-trait-impl.rs index 656101ed535b3..6cce6c723c5a2 100644 --- a/src/test/ui/extern/extern-types-trait-impl.rs +++ b/src/test/ui/extern/extern-types-trait-impl.rs @@ -1,21 +1,22 @@ // run-pass #![allow(dead_code)] // Test that traits can be implemented for extern types. + #![feature(extern_types)] -extern "C" { +extern { type A; } trait Foo { - fn foo(&self) {} + fn foo(&self) { } } impl Foo for A { - fn foo(&self) {} + fn foo(&self) { } } -fn assert_foo() {} +fn assert_foo() { } fn use_foo(x: &dyn Foo) { x.foo(); diff --git a/src/test/ui/extern/extern-types-unsized.rs b/src/test/ui/extern/extern-types-unsized.rs index 94a222a7e7e01..a296ae0739fe7 100644 --- a/src/test/ui/extern/extern-types-unsized.rs +++ b/src/test/ui/extern/extern-types-unsized.rs @@ -2,7 +2,7 @@ #![feature(extern_types)] -extern "C" { +extern { type A; } @@ -16,7 +16,7 @@ struct Bar { tail: T, } -fn assert_sized() {} +fn assert_sized() { } fn main() { assert_sized::(); diff --git a/src/test/ui/extern/extern-types-unsized.stderr b/src/test/ui/extern/extern-types-unsized.stderr index 278db45655720..fba919ceff97b 100644 --- a/src/test/ui/extern/extern-types-unsized.stderr +++ b/src/test/ui/extern/extern-types-unsized.stderr @@ -1,7 +1,7 @@ error[E0277]: the size for values of type `A` cannot be known at compilation time --> $DIR/extern-types-unsized.rs:22:20 | -LL | fn assert_sized() {} +LL | fn assert_sized() { } | - required by this bound in `assert_sized` ... LL | assert_sized::(); @@ -10,13 +10,13 @@ LL | assert_sized::(); = help: the trait `Sized` is not implemented for `A` help: consider relaxing the implicit `Sized` restriction | -LL | fn assert_sized() {} +LL | fn assert_sized() { } | ^^^^^^^^ error[E0277]: the size for values of type `A` cannot be known at compilation time --> $DIR/extern-types-unsized.rs:25:5 | -LL | fn assert_sized() {} +LL | fn assert_sized() { } | - required by this bound in `assert_sized` ... LL | assert_sized::(); @@ -26,13 +26,13 @@ LL | assert_sized::(); = note: required because it appears within the type `Foo` help: consider relaxing the implicit `Sized` restriction | -LL | fn assert_sized() {} +LL | fn assert_sized() { } | ^^^^^^^^ error[E0277]: the size for values of type `A` cannot be known at compilation time --> $DIR/extern-types-unsized.rs:28:5 | -LL | fn assert_sized() {} +LL | fn assert_sized() { } | - required by this bound in `assert_sized` ... LL | assert_sized::>(); @@ -42,13 +42,13 @@ LL | assert_sized::>(); = note: required because it appears within the type `Bar` help: consider relaxing the implicit `Sized` restriction | -LL | fn assert_sized() {} +LL | fn assert_sized() { } | ^^^^^^^^ error[E0277]: the size for values of type `A` cannot be known at compilation time --> $DIR/extern-types-unsized.rs:31:5 | -LL | fn assert_sized() {} +LL | fn assert_sized() { } | - required by this bound in `assert_sized` ... LL | assert_sized::>>(); @@ -59,7 +59,7 @@ LL | assert_sized::>>(); = note: required because it appears within the type `Bar>` help: consider relaxing the implicit `Sized` restriction | -LL | fn assert_sized() {} +LL | fn assert_sized() { } | ^^^^^^^^ error: aborting due to 4 previous errors diff --git a/src/test/ui/extern/extern-wrong-value-type.rs b/src/test/ui/extern/extern-wrong-value-type.rs index 337865ec18d51..a4d7b00b1c64e 100644 --- a/src/test/ui/extern/extern-wrong-value-type.rs +++ b/src/test/ui/extern/extern-wrong-value-type.rs @@ -1,4 +1,4 @@ -extern "C" fn f() { +extern fn f() { } fn is_fn(_: F) where F: Fn() {} diff --git a/src/test/ui/extern/issue-10025.rs b/src/test/ui/extern/issue-10025.rs index 4439b4685251f..193d7ee891f07 100644 --- a/src/test/ui/extern/issue-10025.rs +++ b/src/test/ui/extern/issue-10025.rs @@ -1,6 +1,6 @@ // run-pass -// pretty-expanded FIXME #23616 #![allow(dead_code)] +// pretty-expanded FIXME #23616 unsafe extern fn foo() {} unsafe extern "C" fn bar() {} diff --git a/src/test/ui/extern/issue-36122-accessing-externed-dst.rs b/src/test/ui/extern/issue-36122-accessing-externed-dst.rs index 5f886ff57379a..22229db8000a8 100644 --- a/src/test/ui/extern/issue-36122-accessing-externed-dst.rs +++ b/src/test/ui/extern/issue-36122-accessing-externed-dst.rs @@ -1,5 +1,5 @@ fn main() { - extern "C" { + extern { static symbol: [usize]; //~ ERROR: the size for values of type } println!("{}", symbol[0]); diff --git a/src/test/ui/feature-gates/feature-gate-edition_macro_pats.rs b/src/test/ui/feature-gate-edition_macro_pats.rs similarity index 100% rename from src/test/ui/feature-gates/feature-gate-edition_macro_pats.rs rename to src/test/ui/feature-gate-edition_macro_pats.rs diff --git a/src/test/ui/feature-gates/feature-gate-edition_macro_pats.stderr b/src/test/ui/feature-gate-edition_macro_pats.stderr similarity index 100% rename from src/test/ui/feature-gates/feature-gate-edition_macro_pats.stderr rename to src/test/ui/feature-gate-edition_macro_pats.stderr diff --git a/src/test/ui/feature-gates/feature-gate-const_refs_to_cell.rs b/src/test/ui/feature-gate/feature-gate-const_refs_to_cell.rs similarity index 100% rename from src/test/ui/feature-gates/feature-gate-const_refs_to_cell.rs rename to src/test/ui/feature-gate/feature-gate-const_refs_to_cell.rs diff --git a/src/test/ui/feature-gates/feature-gate-cfg-target-thread-local.rs b/src/test/ui/feature-gates/feature-gate-cfg-target-thread-local.rs index b600ad23eee64..d44f78d4fab27 100644 --- a/src/test/ui/feature-gates/feature-gate-cfg-target-thread-local.rs +++ b/src/test/ui/feature-gates/feature-gate-cfg-target-thread-local.rs @@ -5,9 +5,10 @@ extern crate cfg_target_thread_local; -extern "C" { +extern { #[cfg_attr(target_thread_local, thread_local)] //~^ `cfg(target_thread_local)` is experimental and subject to change + static FOO: u32; } diff --git a/src/test/ui/feature-gates/feature-gate-extern_types.rs b/src/test/ui/feature-gates/feature-gate-extern_types.rs index 103f8eed6f3c0..6bdc96f55d6a5 100644 --- a/src/test/ui/feature-gates/feature-gate-extern_types.rs +++ b/src/test/ui/feature-gates/feature-gate-extern_types.rs @@ -1,4 +1,4 @@ -extern "C" { +extern { type T; //~ ERROR extern types are experimental } diff --git a/src/test/ui/feature-gates/feature-gate-ffi_const.rs b/src/test/ui/feature-gates/feature-gate-ffi_const.rs index 9f3d783ccd69c..27323b1b60280 100644 --- a/src/test/ui/feature-gates/feature-gate-ffi_const.rs +++ b/src/test/ui/feature-gates/feature-gate-ffi_const.rs @@ -1,6 +1,6 @@ #![crate_type = "lib"] -extern "C" { +extern { #[ffi_const] //~ ERROR the `#[ffi_const]` attribute is an experimental feature pub fn foo(); } diff --git a/src/test/ui/feature-gates/feature-gate-ffi_pure.rs b/src/test/ui/feature-gates/feature-gate-ffi_pure.rs index b0dfa01ff4c20..e24a686853c88 100644 --- a/src/test/ui/feature-gates/feature-gate-ffi_pure.rs +++ b/src/test/ui/feature-gates/feature-gate-ffi_pure.rs @@ -1,6 +1,6 @@ #![crate_type = "lib"] -extern "C" { +extern { #[ffi_pure] //~ ERROR the `#[ffi_pure]` attribute is an experimental feature pub fn foo(); } diff --git a/src/test/ui/feature-gates/feature-gate-ffi_returns_twice.rs b/src/test/ui/feature-gates/feature-gate-ffi_returns_twice.rs index f354534356c21..d118b7f4ff2b2 100644 --- a/src/test/ui/feature-gates/feature-gate-ffi_returns_twice.rs +++ b/src/test/ui/feature-gates/feature-gate-ffi_returns_twice.rs @@ -1,6 +1,6 @@ #![crate_type = "lib"] -extern "C" { +extern { #[ffi_returns_twice] //~ ERROR the `#[ffi_returns_twice]` attribute is an experimental feature pub fn foo(); } diff --git a/src/test/ui/feature-gates/feature-gate-link_args.rs b/src/test/ui/feature-gates/feature-gate-link_args.rs index e1c651f46fb49..49948dab1ee55 100644 --- a/src/test/ui/feature-gates/feature-gate-link_args.rs +++ b/src/test/ui/feature-gates/feature-gate-link_args.rs @@ -5,12 +5,13 @@ // sidestep warning (which is correct, but misleading for // purposes of this test) #![allow(unused_attributes)] + #![link_args = "-l unexpected_use_as_inner_attr_on_mod"] //~^ ERROR the `link_args` attribute is experimental #[link_args = "-l expected_use_case"] //~^ ERROR the `link_args` attribute is experimental -extern "C" {} +extern {} #[link_args = "-l unexected_use_on_non_extern_item"] //~^ ERROR: the `link_args` attribute is experimental diff --git a/src/test/ui/feature-gates/feature-gate-link_args.stderr b/src/test/ui/feature-gates/feature-gate-link_args.stderr index ae4918f5c9f54..c75f762b908ff 100644 --- a/src/test/ui/feature-gates/feature-gate-link_args.stderr +++ b/src/test/ui/feature-gates/feature-gate-link_args.stderr @@ -1,5 +1,5 @@ error[E0658]: the `link_args` attribute is experimental and not portable across platforms, it is recommended to use `#[link(name = "foo")] instead - --> $DIR/feature-gate-link_args.rs:11:1 + --> $DIR/feature-gate-link_args.rs:12:1 | LL | #[link_args = "-l expected_use_case"] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -8,7 +8,7 @@ LL | #[link_args = "-l expected_use_case"] = help: add `#![feature(link_args)]` to the crate attributes to enable error[E0658]: the `link_args` attribute is experimental and not portable across platforms, it is recommended to use `#[link(name = "foo")] instead - --> $DIR/feature-gate-link_args.rs:15:1 + --> $DIR/feature-gate-link_args.rs:16:1 | LL | #[link_args = "-l unexected_use_on_non_extern_item"] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -17,7 +17,7 @@ LL | #[link_args = "-l unexected_use_on_non_extern_item"] = help: add `#![feature(link_args)]` to the crate attributes to enable error[E0658]: the `link_args` attribute is experimental and not portable across platforms, it is recommended to use `#[link(name = "foo")] instead - --> $DIR/feature-gate-link_args.rs:8:1 + --> $DIR/feature-gate-link_args.rs:9:1 | LL | #![link_args = "-l unexpected_use_as_inner_attr_on_mod"] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/test/ui/feature-gates/feature-gate-link_cfg.rs b/src/test/ui/feature-gates/feature-gate-link_cfg.rs index d30ee3bcfdb14..27ec2e98eb68b 100644 --- a/src/test/ui/feature-gates/feature-gate-link_cfg.rs +++ b/src/test/ui/feature-gates/feature-gate-link_cfg.rs @@ -1,5 +1,5 @@ #[link(name = "foo", cfg(foo))] //~^ ERROR: is unstable -extern "C" {} +extern {} fn main() {} diff --git a/src/test/ui/feature-gates/feature-gate-link_llvm_intrinsics.rs b/src/test/ui/feature-gates/feature-gate-link_llvm_intrinsics.rs index 7391ea94ebc04..1c7f33133280a 100644 --- a/src/test/ui/feature-gates/feature-gate-link_llvm_intrinsics.rs +++ b/src/test/ui/feature-gates/feature-gate-link_llvm_intrinsics.rs @@ -1,7 +1,8 @@ -extern "C" { +extern { #[link_name = "llvm.sqrt.f32"] fn sqrt(x: f32) -> f32; -//~^ ERROR linking to LLVM intrinsics is experimental + //~^ ERROR linking to LLVM intrinsics is experimental } -fn main() {} +fn main(){ +} diff --git a/src/test/ui/feature-gates/feature-gate-linkage.rs b/src/test/ui/feature-gates/feature-gate-linkage.rs index 15b8d442aeb9a..70f33cc0c6cc7 100644 --- a/src/test/ui/feature-gates/feature-gate-linkage.rs +++ b/src/test/ui/feature-gates/feature-gate-linkage.rs @@ -1,4 +1,4 @@ -extern "C" { +extern { #[linkage = "extern_weak"] static foo: isize; //~^ ERROR: the `linkage` attribute is experimental and not portable } diff --git a/src/test/ui/feature-gates/feature-gate-non_ascii_idents.rs b/src/test/ui/feature-gates/feature-gate-non_ascii_idents.rs index 5cc04ad5cdfdc..11ff54058488a 100644 --- a/src/test/ui/feature-gates/feature-gate-non_ascii_idents.rs +++ b/src/test/ui/feature-gates/feature-gate-non_ascii_idents.rs @@ -26,7 +26,7 @@ enum Bär { //~ ERROR non-ascii idents } } -extern "C" { +extern { fn qüx(); //~ ERROR non-ascii idents } diff --git a/src/test/ui/feature-gates/feature-gate-simd-ffi.rs b/src/test/ui/feature-gates/feature-gate-simd-ffi.rs index abffa4a10010d..0425e39e67745 100644 --- a/src/test/ui/feature-gates/feature-gate-simd-ffi.rs +++ b/src/test/ui/feature-gates/feature-gate-simd-ffi.rs @@ -5,7 +5,7 @@ #[derive(Copy, Clone)] struct LocalSimd(u8, u8); -extern "C" { +extern { fn baz() -> LocalSimd; //~ ERROR use of SIMD type fn qux(x: LocalSimd); //~ ERROR use of SIMD type } diff --git a/src/test/ui/feature-gates/feature-gate-static-nobundle.rs b/src/test/ui/feature-gates/feature-gate-static-nobundle.rs index 05c52f9dbead2..644b1f964a059 100644 --- a/src/test/ui/feature-gates/feature-gate-static-nobundle.rs +++ b/src/test/ui/feature-gates/feature-gate-static-nobundle.rs @@ -1,5 +1,5 @@ -#[link(name = "foo", kind = "static-nobundle")] +#[link(name="foo", kind="static-nobundle")] //~^ ERROR: kind="static-nobundle" is unstable -extern "C" {} +extern {} fn main() {} diff --git a/src/test/ui/feature-gates/feature-gate-static-nobundle.stderr b/src/test/ui/feature-gates/feature-gate-static-nobundle.stderr index 3a3c86c34295d..773ad8ff21760 100644 --- a/src/test/ui/feature-gates/feature-gate-static-nobundle.stderr +++ b/src/test/ui/feature-gates/feature-gate-static-nobundle.stderr @@ -1,8 +1,8 @@ error[E0658]: kind="static-nobundle" is unstable --> $DIR/feature-gate-static-nobundle.rs:1:1 | -LL | #[link(name = "foo", kind = "static-nobundle")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[link(name="foo", kind="static-nobundle")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: see issue #37403 for more information = help: add `#![feature(static_nobundle)]` to the crate attributes to enable diff --git a/src/test/ui/feature-gates/feature-gate-unwind-attributes.rs b/src/test/ui/feature-gates/feature-gate-unwind-attributes.rs index cd348ded4d7ce..20c443b63d175 100644 --- a/src/test/ui/feature-gates/feature-gate-unwind-attributes.rs +++ b/src/test/ui/feature-gates/feature-gate-unwind-attributes.rs @@ -3,12 +3,12 @@ #![crate_type = "lib"] -extern "C" { - // CHECK: Function Attrs: nounwind - // CHECK-NEXT: declare void @extern_fn +extern { +// CHECK: Function Attrs: nounwind +// CHECK-NEXT: declare void @extern_fn fn extern_fn(); - // CHECK-NOT: Function Attrs: nounwind - // CHECK: declare void @unwinding_extern_fn +// CHECK-NOT: Function Attrs: nounwind +// CHECK: declare void @unwinding_extern_fn #[unwind(allowed)] //~ ERROR the `#[unwind]` attribute is an experimental feature fn unwinding_extern_fn(); } diff --git a/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs b/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs index 21f40524f63df..aba6c08f41dae 100644 --- a/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs +++ b/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs @@ -536,7 +536,7 @@ mod link_name { //~^ WARN attribute should be applied to a foreign function or static [unused_attributes] //~| WARN this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! //~| HELP try `#[link(name = "1900")]` instead - extern "C" { } + extern { } //~^ NOTE not a foreign function or static mod inner { #![link_name="1900"] } diff --git a/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr b/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr index c908d2589cf49..128795f50f965 100644 --- a/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr +++ b/src/test/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr @@ -403,8 +403,8 @@ warning: attribute should be applied to a foreign function or static LL | #[link_name = "1900"] | ^^^^^^^^^^^^^^^^^^^^^ ... -LL | extern "C" { } - | -------------- not a foreign function or static +LL | extern { } + | ---------- not a foreign function or static | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! help: try `#[link(name = "1900")]` instead diff --git a/src/test/ui/ffi_const2.rs b/src/test/ui/ffi_const2.rs index 82fe8a9c91dd1..4bd9637f0832c 100644 --- a/src/test/ui/ffi_const2.rs +++ b/src/test/ui/ffi_const2.rs @@ -1,6 +1,6 @@ #![feature(ffi_const, ffi_pure)] -extern "C" { +extern { #[ffi_pure] //~ ERROR `#[ffi_const]` function cannot be `#[ffi_pure]` #[ffi_const] pub fn baz(); diff --git a/src/test/ui/foreign-unsafe-fn-called.rs b/src/test/ui/foreign-unsafe-fn-called.rs index abbe462021ed7..9352efaf2f000 100644 --- a/src/test/ui/foreign-unsafe-fn-called.rs +++ b/src/test/ui/foreign-unsafe-fn-called.rs @@ -1,5 +1,5 @@ mod test { - extern "C" { + extern { pub fn free(); } } diff --git a/src/test/ui/foreign/foreign-fn-linkname.rs b/src/test/ui/foreign/foreign-fn-linkname.rs index f6d820594f966..1f048159064b3 100644 --- a/src/test/ui/foreign/foreign-fn-linkname.rs +++ b/src/test/ui/foreign/foreign-fn-linkname.rs @@ -10,7 +10,7 @@ use std::ffi::CString; mod mlibc { use libc::{c_char, size_t}; - extern "C" { + extern { #[link_name = "strlen"] pub fn my_strlen(str: *const c_char) -> size_t; } @@ -19,7 +19,9 @@ mod mlibc { fn strlen(str: String) -> usize { // C string is terminated with a zero let s = CString::new(str).unwrap(); - unsafe { mlibc::my_strlen(s.as_ptr()) as usize } + unsafe { + mlibc::my_strlen(s.as_ptr()) as usize + } } pub fn main() { diff --git a/src/test/ui/foreign/foreign-int-types.rs b/src/test/ui/foreign/foreign-int-types.rs index 2d01d32042563..66296574d7def 100644 --- a/src/test/ui/foreign/foreign-int-types.rs +++ b/src/test/ui/foreign/foreign-int-types.rs @@ -3,10 +3,11 @@ #![allow(dead_code)] mod xx { - extern "C" { + extern { pub fn strlen(str: *const u8) -> usize; pub fn foo(x: isize, y: usize); } } -fn main() {} +fn main() { +} diff --git a/src/test/ui/foreign/foreign-mod-unused-const.rs b/src/test/ui/foreign/foreign-mod-unused-const.rs index 7d79c30f46906..d9efbe00e525d 100644 --- a/src/test/ui/foreign/foreign-mod-unused-const.rs +++ b/src/test/ui/foreign/foreign-mod-unused-const.rs @@ -3,9 +3,10 @@ // pretty-expanded FIXME #23616 mod foo { - extern "C" { + extern { pub static errno: u32; } } -pub fn main() {} +pub fn main() { +} diff --git a/src/test/ui/foreign/foreign2.rs b/src/test/ui/foreign/foreign2.rs index df431f2999c8e..c1ab57776f6dc 100644 --- a/src/test/ui/foreign/foreign2.rs +++ b/src/test/ui/foreign/foreign2.rs @@ -2,28 +2,29 @@ #![allow(dead_code)] // ignore-wasm32-bare no libc to test ffi with // pretty-expanded FIXME #23616 + #![feature(rustc_private)] extern crate libc; mod bar { - extern "C" {} + extern {} } mod zed { - extern "C" {} + extern {} } mod mlibc { use libc::{c_int, c_void, size_t, ssize_t}; - extern "C" { + extern { pub fn write(fd: c_int, buf: *const c_void, count: size_t) -> ssize_t; } } mod baz { - extern "C" {} + extern {} } -pub fn main() {} +pub fn main() { } diff --git a/src/test/ui/functions-closures/auxiliary/fn-abi.rs b/src/test/ui/functions-closures/auxiliary/fn-abi.rs index ace9fbdfd0c59..25c9e1b4ca332 100644 --- a/src/test/ui/functions-closures/auxiliary/fn-abi.rs +++ b/src/test/ui/functions-closures/auxiliary/fn-abi.rs @@ -1,2 +1,2 @@ #[no_mangle] -pub extern "C" fn foo() {} +pub extern fn foo() {} diff --git a/src/test/ui/functions-closures/fn-abi.rs b/src/test/ui/functions-closures/fn-abi.rs index ac3a4be3346e3..900af9c1f66b7 100644 --- a/src/test/ui/functions-closures/fn-abi.rs +++ b/src/test/ui/functions-closures/fn-abi.rs @@ -7,12 +7,12 @@ extern crate fn_abi; -extern "C" { +extern { fn foo(); } pub fn main() { // Will only type check if the type of _p and the decl of foo use the // same ABI - let _p: unsafe extern "C" fn() = foo; + let _p: unsafe extern fn() = foo; } diff --git a/src/test/ui/generator/auxiliary/metadata-sufficient-for-layout.rs b/src/test/ui/generator/auxiliary/metadata-sufficient-for-layout.rs deleted file mode 100644 index 207c2735f8886..0000000000000 --- a/src/test/ui/generator/auxiliary/metadata-sufficient-for-layout.rs +++ /dev/null @@ -1,11 +0,0 @@ -// compile-flags: --emit metadata -#![feature(generators, generator_trait)] - -use std::marker::Unpin; -use std::ops::Generator; - -pub fn g() -> impl Generator<(), Yield = (), Return = ()> { - || { - yield; - } -} diff --git a/src/test/ui/generator/layout-error.rs b/src/test/ui/generator/layout-error.rs deleted file mode 100644 index 059867277ad43..0000000000000 --- a/src/test/ui/generator/layout-error.rs +++ /dev/null @@ -1,28 +0,0 @@ -// Verifies that computing a layout of a generator tainted by type errors -// doesn't ICE. Regression test for #80998. -// -// edition:2018 - -#![feature(type_alias_impl_trait)] -use std::future::Future; - -pub struct Task(F); -impl Task { - fn new() -> Self { - todo!() - } - fn spawn(&self, _: impl FnOnce() -> F) { - todo!() - } -} - -fn main() { - async fn cb() { - let a = Foo; //~ ERROR cannot find value `Foo` in this scope - } - - type F = impl Future; - // Check that statics are inhabited computes they layout. - static POOL: Task = Task::new(); - Task::spawn(&POOL, || cb()); -} diff --git a/src/test/ui/generator/layout-error.stderr b/src/test/ui/generator/layout-error.stderr deleted file mode 100644 index b1a258f4f2ca7..0000000000000 --- a/src/test/ui/generator/layout-error.stderr +++ /dev/null @@ -1,9 +0,0 @@ -error[E0425]: cannot find value `Foo` in this scope - --> $DIR/layout-error.rs:21:17 - | -LL | let a = Foo; - | ^^^ not found in this scope - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0425`. diff --git a/src/test/ui/generator/metadata-sufficient-for-layout.rs b/src/test/ui/generator/metadata-sufficient-for-layout.rs deleted file mode 100644 index 9c82359a0be05..0000000000000 --- a/src/test/ui/generator/metadata-sufficient-for-layout.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Check that the layout of a generator is available when auxiliary crate -// is compiled with --emit metadata. -// -// Regression test for #80998. -// -// aux-build:metadata-sufficient-for-layout.rs -// check-pass - -#![feature(type_alias_impl_trait)] -#![feature(generator_trait)] - -extern crate metadata_sufficient_for_layout; - -use std::ops::Generator; - -type F = impl Generator<(), Yield = (), Return = ()>; - -// Static queries the layout of the generator. -static A: Option = None; - -fn f() -> F { metadata_sufficient_for_layout::g() } - -fn main() {} diff --git a/src/test/ui/generator/resume-arg-late-bound.stderr b/src/test/ui/generator/resume-arg-late-bound.stderr index 63411b59280bb..dc0864165abf4 100644 --- a/src/test/ui/generator/resume-arg-late-bound.stderr +++ b/src/test/ui/generator/resume-arg-late-bound.stderr @@ -2,47 +2,19 @@ error[E0308]: mismatched types --> $DIR/resume-arg-late-bound.rs:15:5 | LL | test(gen); - | ^^^^ lifetime mismatch + | ^^^^ one type is more general than the other | = note: expected type `for<'a> Generator<&'a mut bool>` found type `Generator<&mut bool>` -note: the required lifetime does not necessarily outlive the anonymous lifetime #1 defined on the body at 11:15 - --> $DIR/resume-arg-late-bound.rs:11:15 - | -LL | let gen = |arg: &mut bool| { - | _______________^ -LL | | yield (); -LL | | *arg = true; -LL | | }; - | |_____^ -note: the lifetime requirement is introduced here - --> $DIR/resume-arg-late-bound.rs:8:17 - | -LL | fn test(a: impl for<'a> Generator<&'a mut bool>) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0308]: mismatched types --> $DIR/resume-arg-late-bound.rs:15:5 | LL | test(gen); - | ^^^^ lifetime mismatch + | ^^^^ one type is more general than the other | = note: expected type `for<'a> Generator<&'a mut bool>` found type `Generator<&mut bool>` -note: the anonymous lifetime #1 defined on the body at 11:15 doesn't meet the lifetime requirements - --> $DIR/resume-arg-late-bound.rs:11:15 - | -LL | let gen = |arg: &mut bool| { - | _______________^ -LL | | yield (); -LL | | *arg = true; -LL | | }; - | |_____^ -note: the lifetime requirement is introduced here - --> $DIR/resume-arg-late-bound.rs:8:17 - | -LL | fn test(a: impl for<'a> Generator<&'a mut bool>) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 2 previous errors diff --git a/src/test/ui/generic-associated-types/parameter_number_and_kind.rs b/src/test/ui/generic-associated-types/parameter_number_and_kind.rs index 9d7ef88b7679d..f4d09fc1539da 100644 --- a/src/test/ui/generic-associated-types/parameter_number_and_kind.rs +++ b/src/test/ui/generic-associated-types/parameter_number_and_kind.rs @@ -11,10 +11,10 @@ trait Foo { // Test parameters in default values type FOk = Self::E<'static, T>; type FErr1 = Self::E<'static, 'static>; - //~^ ERROR this associated type takes 1 lifetime argument but 2 lifetime arguments were supplied - //~| ERROR this associated type takes 1 type argument but 0 type arguments were supplied + //~^ ERROR wrong number of lifetime arguments: expected 1, found 2 + //~| ERROR wrong number of type arguments: expected 1, found 0 type FErr2 = Self::E<'static, T, u32>; - //~^ ERROR this associated type takes 1 type argument but 2 type arguments were supplied + //~^ ERROR wrong number of type arguments: expected 1, found 2 } fn main() {} diff --git a/src/test/ui/generic-associated-types/parameter_number_and_kind.stderr b/src/test/ui/generic-associated-types/parameter_number_and_kind.stderr index d021889c08424..ed090e302cefa 100644 --- a/src/test/ui/generic-associated-types/parameter_number_and_kind.stderr +++ b/src/test/ui/generic-associated-types/parameter_number_and_kind.stderr @@ -1,46 +1,20 @@ -error[E0107]: this associated type takes 1 lifetime argument but 2 lifetime arguments were supplied - --> $DIR/parameter_number_and_kind.rs:13:24 +error[E0107]: wrong number of lifetime arguments: expected 1, found 2 + --> $DIR/parameter_number_and_kind.rs:13:35 | LL | type FErr1 = Self::E<'static, 'static>; - | ^ --------- help: remove this lifetime argument - | | - | expected 1 lifetime argument - | -note: associated type defined here, with 1 lifetime parameter: `'a` - --> $DIR/parameter_number_and_kind.rs:10:10 - | -LL | type E<'a, T>; - | ^ -- + | ^^^^^^^ unexpected lifetime argument -error[E0107]: this associated type takes 1 type argument but 0 type arguments were supplied - --> $DIR/parameter_number_and_kind.rs:13:24 +error[E0107]: wrong number of type arguments: expected 1, found 0 + --> $DIR/parameter_number_and_kind.rs:13:18 | LL | type FErr1 = Self::E<'static, 'static>; - | ^ expected 1 type argument - | -note: associated type defined here, with 1 type parameter: `T` - --> $DIR/parameter_number_and_kind.rs:10:10 - | -LL | type E<'a, T>; - | ^ - -help: add missing type argument - | -LL | type FErr1 = Self::E<'static, 'static, T>; - | ^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^ expected 1 type argument -error[E0107]: this associated type takes 1 type argument but 2 type arguments were supplied - --> $DIR/parameter_number_and_kind.rs:16:27 +error[E0107]: wrong number of type arguments: expected 1, found 2 + --> $DIR/parameter_number_and_kind.rs:16:41 | LL | type FErr2 = Self::E<'static, T, u32>; - | ^ ----- help: remove this type argument - | | - | expected 1 type argument - | -note: associated type defined here, with 1 type parameter: `T` - --> $DIR/parameter_number_and_kind.rs:10:10 - | -LL | type E<'a, T>; - | ^ - + | ^^^ unexpected type argument error: aborting due to 3 previous errors diff --git a/src/test/ui/generics/generic-arg-mismatch-recover.rs b/src/test/ui/generics/generic-arg-mismatch-recover.rs index 0e0d1daec5f31..3e5e2e601f5c4 100644 --- a/src/test/ui/generics/generic-arg-mismatch-recover.rs +++ b/src/test/ui/generics/generic-arg-mismatch-recover.rs @@ -3,10 +3,8 @@ struct Foo<'a, T: 'a>(&'a T); struct Bar<'a>(&'a ()); fn main() { - Foo::<'static, 'static, ()>(&0); - //~^ ERROR this struct takes 1 lifetime argument but 2 lifetime arguments were supplied + Foo::<'static, 'static, ()>(&0); //~ ERROR wrong number of lifetime arguments - Bar::<'static, 'static, ()>(&()); - //~^ ERROR this struct takes 1 lifetime argument but 2 lifetime arguments were supplied - //~| ERROR this struct takes 0 type arguments but 1 type argument was supplied + Bar::<'static, 'static, ()>(&()); //~ ERROR wrong number of lifetime arguments + //~^ ERROR wrong number of type arguments } diff --git a/src/test/ui/generics/generic-arg-mismatch-recover.stderr b/src/test/ui/generics/generic-arg-mismatch-recover.stderr index ca73b82737d64..99adb35268527 100644 --- a/src/test/ui/generics/generic-arg-mismatch-recover.stderr +++ b/src/test/ui/generics/generic-arg-mismatch-recover.stderr @@ -1,44 +1,20 @@ -error[E0107]: this struct takes 1 lifetime argument but 2 lifetime arguments were supplied - --> $DIR/generic-arg-mismatch-recover.rs:6:5 +error[E0107]: wrong number of lifetime arguments: expected 1, found 2 + --> $DIR/generic-arg-mismatch-recover.rs:6:20 | LL | Foo::<'static, 'static, ()>(&0); - | ^^^ --------- help: remove this lifetime argument - | | - | expected 1 lifetime argument - | -note: struct defined here, with 1 lifetime parameter: `'a` - --> $DIR/generic-arg-mismatch-recover.rs:1:8 - | -LL | struct Foo<'a, T: 'a>(&'a T); - | ^^^ -- + | ^^^^^^^ unexpected lifetime argument -error[E0107]: this struct takes 1 lifetime argument but 2 lifetime arguments were supplied - --> $DIR/generic-arg-mismatch-recover.rs:9:5 +error[E0107]: wrong number of lifetime arguments: expected 1, found 2 + --> $DIR/generic-arg-mismatch-recover.rs:8:20 | LL | Bar::<'static, 'static, ()>(&()); - | ^^^ --------- help: remove this lifetime argument - | | - | expected 1 lifetime argument - | -note: struct defined here, with 1 lifetime parameter: `'a` - --> $DIR/generic-arg-mismatch-recover.rs:3:8 - | -LL | struct Bar<'a>(&'a ()); - | ^^^ -- + | ^^^^^^^ unexpected lifetime argument -error[E0107]: this struct takes 0 type arguments but 1 type argument was supplied - --> $DIR/generic-arg-mismatch-recover.rs:9:5 +error[E0107]: wrong number of type arguments: expected 0, found 1 + --> $DIR/generic-arg-mismatch-recover.rs:8:29 | LL | Bar::<'static, 'static, ()>(&()); - | ^^^ ---- help: remove this type argument - | | - | expected 0 type arguments - | -note: struct defined here, with 0 type parameters - --> $DIR/generic-arg-mismatch-recover.rs:3:8 - | -LL | struct Bar<'a>(&'a ()); - | ^^^ + | ^^ unexpected type argument error: aborting due to 3 previous errors diff --git a/src/test/ui/generics/generic-extern-lifetime.rs b/src/test/ui/generics/generic-extern-lifetime.rs index c42744808c394..22bcd44a14d9b 100644 --- a/src/test/ui/generics/generic-extern-lifetime.rs +++ b/src/test/ui/generics/generic-extern-lifetime.rs @@ -1,15 +1,15 @@ // Test to make sure the names of the lifetimes are correctly resolved // in extern blocks. -extern "C" { - pub fn life<'a>(x: &'a i32); - pub fn life2<'b>(x: &'a i32, y: &'b i32); //~ ERROR use of undeclared lifetime name `'a` - pub fn life3<'a>(x: &'a i32, y: &i32) -> &'a i32; - pub fn life4<'b>(x: for<'c> fn(&'a i32)); //~ ERROR use of undeclared lifetime name `'a` - pub fn life5<'b>(x: for<'c> fn(&'b i32)); - pub fn life6<'b>(x: for<'c> fn(&'c i32)); - pub fn life7<'b>() -> for<'c> fn(&'a i32); //~ ERROR use of undeclared lifetime name `'a` - pub fn life8<'b>() -> for<'c> fn(&'b i32); - pub fn life9<'b>() -> for<'c> fn(&'c i32); +extern { + pub fn life<'a>(x:&'a i32); + pub fn life2<'b>(x:&'a i32, y:&'b i32); //~ ERROR use of undeclared lifetime name `'a` + pub fn life3<'a>(x:&'a i32, y:&i32) -> &'a i32; + pub fn life4<'b>(x: for<'c> fn(&'a i32)); //~ ERROR use of undeclared lifetime name `'a` + pub fn life5<'b>(x: for<'c> fn(&'b i32)); + pub fn life6<'b>(x: for<'c> fn(&'c i32)); + pub fn life7<'b>() -> for<'c> fn(&'a i32); //~ ERROR use of undeclared lifetime name `'a` + pub fn life8<'b>() -> for<'c> fn(&'b i32); + pub fn life9<'b>() -> for<'c> fn(&'c i32); } fn main() {} diff --git a/src/test/ui/generics/generic-extern-lifetime.stderr b/src/test/ui/generics/generic-extern-lifetime.stderr index 3c9ed7a9dec08..72951aea4aaf0 100644 --- a/src/test/ui/generics/generic-extern-lifetime.stderr +++ b/src/test/ui/generics/generic-extern-lifetime.stderr @@ -1,32 +1,32 @@ error[E0261]: use of undeclared lifetime name `'a` - --> $DIR/generic-extern-lifetime.rs:6:26 + --> $DIR/generic-extern-lifetime.rs:6:24 | -LL | pub fn life2<'b>(x: &'a i32, y: &'b i32); - | ^^ undeclared lifetime +LL | pub fn life2<'b>(x:&'a i32, y:&'b i32); + | ^^ undeclared lifetime error[E0261]: use of undeclared lifetime name `'a` - --> $DIR/generic-extern-lifetime.rs:8:37 + --> $DIR/generic-extern-lifetime.rs:8:36 | -LL | pub fn life4<'b>(x: for<'c> fn(&'a i32)); - | ^^ undeclared lifetime +LL | pub fn life4<'b>(x: for<'c> fn(&'a i32)); + | ^^ undeclared lifetime | = note: for more information on higher-ranked polymorphism, visit https://doc.rust-lang.org/nomicon/hrtb.html help: consider making the type lifetime-generic with a new `'a` lifetime | -LL | pub fn life4<'b>(x: for<'c, 'a> fn(&'a i32)); - | ^^^^ +LL | pub fn life4<'b>(x: for<'c, 'a> fn(&'a i32)); + | ^^^^ error[E0261]: use of undeclared lifetime name `'a` - --> $DIR/generic-extern-lifetime.rs:11:39 + --> $DIR/generic-extern-lifetime.rs:11:38 | -LL | pub fn life7<'b>() -> for<'c> fn(&'a i32); - | ^^ undeclared lifetime +LL | pub fn life7<'b>() -> for<'c> fn(&'a i32); + | ^^ undeclared lifetime | = note: for more information on higher-ranked polymorphism, visit https://doc.rust-lang.org/nomicon/hrtb.html help: consider making the type lifetime-generic with a new `'a` lifetime | -LL | pub fn life7<'b>() -> for<'c, 'a> fn(&'a i32); - | ^^^^ +LL | pub fn life7<'b>() -> for<'c, 'a> fn(&'a i32); + | ^^^^ error: aborting due to 3 previous errors diff --git a/src/test/ui/generics/generic-extern.rs b/src/test/ui/generics/generic-extern.rs index 3690d6fd07d29..e52a88592ff96 100644 --- a/src/test/ui/generics/generic-extern.rs +++ b/src/test/ui/generics/generic-extern.rs @@ -1,4 +1,4 @@ -extern "C" { +extern { fn foo(); //~ ERROR foreign items may not have type parameters } diff --git a/src/test/ui/generics/generic-impl-less-params-with-defaults.rs b/src/test/ui/generics/generic-impl-less-params-with-defaults.rs index 01964f652ee09..abbf64058204a 100644 --- a/src/test/ui/generics/generic-impl-less-params-with-defaults.rs +++ b/src/test/ui/generics/generic-impl-less-params-with-defaults.rs @@ -9,5 +9,5 @@ impl Foo { fn main() { Foo::::new(); - //~^ ERROR this struct takes at least 2 type arguments but only 1 type argument was supplied + //~^ ERROR wrong number of type arguments } diff --git a/src/test/ui/generics/generic-impl-less-params-with-defaults.stderr b/src/test/ui/generics/generic-impl-less-params-with-defaults.stderr index a8a17876ee0fd..22b00e1dea474 100644 --- a/src/test/ui/generics/generic-impl-less-params-with-defaults.stderr +++ b/src/test/ui/generics/generic-impl-less-params-with-defaults.stderr @@ -1,20 +1,8 @@ -error[E0107]: this struct takes at least 2 type arguments but only 1 type argument was supplied +error[E0107]: wrong number of type arguments: expected at least 2, found 1 --> $DIR/generic-impl-less-params-with-defaults.rs:11:5 | LL | Foo::::new(); - | ^^^ ----- supplied 1 type argument - | | - | expected at least 2 type arguments - | -note: struct defined here, with at least 2 type parameters: `A`, `B` - --> $DIR/generic-impl-less-params-with-defaults.rs:3:8 - | -LL | struct Foo( - | ^^^ - - -help: add missing type argument - | -LL | Foo::::new(); - | ^^^ + | ^^^^^^^^^^^^^^^^^ expected at least 2 type arguments error: aborting due to previous error diff --git a/src/test/ui/generics/generic-impl-more-params-with-defaults.rs b/src/test/ui/generics/generic-impl-more-params-with-defaults.rs index 24c41a9088b99..a14fb7064c995 100644 --- a/src/test/ui/generics/generic-impl-more-params-with-defaults.rs +++ b/src/test/ui/generics/generic-impl-more-params-with-defaults.rs @@ -11,5 +11,5 @@ impl Vec { fn main() { Vec::::new(); - //~^ ERROR this struct takes at most 2 type arguments but 3 type arguments were supplied + //~^ ERROR wrong number of type arguments } diff --git a/src/test/ui/generics/generic-impl-more-params-with-defaults.stderr b/src/test/ui/generics/generic-impl-more-params-with-defaults.stderr index 8ba86afe91ea0..380e9209e6c60 100644 --- a/src/test/ui/generics/generic-impl-more-params-with-defaults.stderr +++ b/src/test/ui/generics/generic-impl-more-params-with-defaults.stderr @@ -1,16 +1,8 @@ -error[E0107]: this struct takes at most 2 type arguments but 3 type arguments were supplied - --> $DIR/generic-impl-more-params-with-defaults.rs:13:5 +error[E0107]: wrong number of type arguments: expected at most 2, found 3 + --> $DIR/generic-impl-more-params-with-defaults.rs:13:24 | LL | Vec::::new(); - | ^^^ ------ help: remove this type argument - | | - | expected at most 2 type arguments - | -note: struct defined here, with at most 2 type parameters: `T`, `A` - --> $DIR/generic-impl-more-params-with-defaults.rs:5:8 - | -LL | struct Vec( - | ^^^ - - + | ^^^^ unexpected type argument error: aborting due to previous error diff --git a/src/test/ui/generics/generic-no-mangle.fixed b/src/test/ui/generics/generic-no-mangle.fixed index 207d8a91b0028..72f9af0124c16 100644 --- a/src/test/ui/generics/generic-no-mangle.fixed +++ b/src/test/ui/generics/generic-no-mangle.fixed @@ -6,7 +6,7 @@ pub fn foo() {} //~ ERROR functions generic over types or consts must be mangled -pub extern "C" fn bar() {} //~ ERROR functions generic over types or consts must be mangled +pub extern fn bar() {} //~ ERROR functions generic over types or consts must be mangled #[no_mangle] pub fn baz(x: &i32) -> &i32 { x } diff --git a/src/test/ui/generics/generic-no-mangle.rs b/src/test/ui/generics/generic-no-mangle.rs index 146896cdc3d02..08d631e6eee1e 100644 --- a/src/test/ui/generics/generic-no-mangle.rs +++ b/src/test/ui/generics/generic-no-mangle.rs @@ -6,7 +6,7 @@ pub fn foo() {} //~ ERROR functions generic over types or consts must be mangled #[no_mangle] -pub extern "C" fn bar() {} //~ ERROR functions generic over types or consts must be mangled +pub extern fn bar() {} //~ ERROR functions generic over types or consts must be mangled #[no_mangle] pub fn baz(x: &i32) -> &i32 { x } diff --git a/src/test/ui/generics/generic-no-mangle.stderr b/src/test/ui/generics/generic-no-mangle.stderr index b437417c0b180..e8e6d9d502d4b 100644 --- a/src/test/ui/generics/generic-no-mangle.stderr +++ b/src/test/ui/generics/generic-no-mangle.stderr @@ -17,8 +17,8 @@ error: functions generic over types or consts must be mangled | LL | #[no_mangle] | ------------ help: remove this attribute -LL | pub extern "C" fn bar() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | pub extern fn bar() {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 2 previous errors diff --git a/src/test/ui/generics/generic-type-less-params-with-defaults.rs b/src/test/ui/generics/generic-type-less-params-with-defaults.rs index 6b877ab8aee6a..3aa03392ff2d9 100644 --- a/src/test/ui/generics/generic-type-less-params-with-defaults.rs +++ b/src/test/ui/generics/generic-type-less-params-with-defaults.rs @@ -7,5 +7,5 @@ struct Vec( fn main() { let _: Vec; - //~^ ERROR missing generics for struct `Vec` + //~^ ERROR wrong number of type arguments: expected at least 1, found 0 [E0107] } diff --git a/src/test/ui/generics/generic-type-less-params-with-defaults.stderr b/src/test/ui/generics/generic-type-less-params-with-defaults.stderr index 93f7a24d87741..a4cc8325a04fc 100644 --- a/src/test/ui/generics/generic-type-less-params-with-defaults.stderr +++ b/src/test/ui/generics/generic-type-less-params-with-defaults.stderr @@ -1,18 +1,8 @@ -error[E0107]: missing generics for struct `Vec` +error[E0107]: wrong number of type arguments: expected at least 1, found 0 --> $DIR/generic-type-less-params-with-defaults.rs:9:12 | LL | let _: Vec; | ^^^ expected at least 1 type argument - | -note: struct defined here, with at least 1 type parameter: `T` - --> $DIR/generic-type-less-params-with-defaults.rs:5:8 - | -LL | struct Vec( - | ^^^ - -help: use angle brackets to add missing type argument - | -LL | let _: Vec; - | ^^^ error: aborting due to previous error diff --git a/src/test/ui/generics/generic-type-more-params-with-defaults.rs b/src/test/ui/generics/generic-type-more-params-with-defaults.rs index c421774ebbadd..2713f088dcb51 100644 --- a/src/test/ui/generics/generic-type-more-params-with-defaults.rs +++ b/src/test/ui/generics/generic-type-more-params-with-defaults.rs @@ -7,5 +7,5 @@ struct Vec( fn main() { let _: Vec; - //~^ ERROR this struct takes at most 2 type arguments but 3 type arguments were supplied + //~^ ERROR wrong number of type arguments: expected at most 2, found 3 [E0107] } diff --git a/src/test/ui/generics/generic-type-more-params-with-defaults.stderr b/src/test/ui/generics/generic-type-more-params-with-defaults.stderr index e331481390b66..cc296b5105a40 100644 --- a/src/test/ui/generics/generic-type-more-params-with-defaults.stderr +++ b/src/test/ui/generics/generic-type-more-params-with-defaults.stderr @@ -1,16 +1,8 @@ -error[E0107]: this struct takes at most 2 type arguments but 3 type arguments were supplied - --> $DIR/generic-type-more-params-with-defaults.rs:9:12 +error[E0107]: wrong number of type arguments: expected at most 2, found 3 + --> $DIR/generic-type-more-params-with-defaults.rs:9:29 | LL | let _: Vec; - | ^^^ ------ help: remove this type argument - | | - | expected at most 2 type arguments - | -note: struct defined here, with at most 2 type parameters: `T`, `A` - --> $DIR/generic-type-more-params-with-defaults.rs:5:8 - | -LL | struct Vec( - | ^^^ - - + | ^^^^ unexpected type argument error: aborting due to previous error diff --git a/src/test/ui/generics/wrong-number-of-args.rs b/src/test/ui/generics/wrong-number-of-args.rs deleted file mode 100644 index 6b99865202e54..0000000000000 --- a/src/test/ui/generics/wrong-number-of-args.rs +++ /dev/null @@ -1,161 +0,0 @@ -mod no_generics { - struct Ty; - - type A = Ty; - - type B = Ty<'static>; - //~^ ERROR this struct takes 0 lifetime arguments but 1 lifetime argument was supplied - //~| HELP remove these generics - - type C = Ty<'static, usize>; - //~^ ERROR this struct takes 0 lifetime arguments but 1 lifetime argument was supplied - //~| ERROR this struct takes 0 type arguments but 1 type argument was supplied - //~| HELP remove this lifetime argument - //~| HELP remove this type argument - - type D = Ty<'static, usize, { 0 }>; - //~^ ERROR this struct takes 0 lifetime arguments but 1 lifetime argument was supplied - //~| ERROR this struct takes 0 generic arguments but 2 generic arguments were supplied - //~| HELP remove this lifetime argument - //~| HELP remove these generic arguments -} - -mod type_and_type { - struct Ty; - - type A = Ty; - //~^ ERROR missing generics for struct `type_and_type::Ty` - //~| HELP use angle brackets - - type B = Ty; - //~^ ERROR this struct takes 2 type arguments but only 1 type argument was supplied - //~| HELP add missing type argument - - type C = Ty; - - type D = Ty; - //~^ ERROR this struct takes 2 type arguments but 3 type arguments were supplied - //~| HELP remove this type argument -} - -mod lifetime_and_type { - struct Ty<'a, T>; - - type A = Ty; - //~^ ERROR missing generics for struct `lifetime_and_type::Ty` - //~| ERROR missing lifetime specifier - //~| HELP consider introducing - //~| HELP use angle brackets - - type B = Ty<'static>; - //~^ ERROR this struct takes 1 type argument but 0 type arguments were supplied - //~| HELP add missing type argument - - type C = Ty; - //~^ ERROR missing lifetime specifier - //~| HELP consider introducing - - type D = Ty<'static, usize>; -} - -mod type_and_type_and_type { - struct Ty; - - type A = Ty; - //~^ ERROR missing generics for struct `type_and_type_and_type::Ty` - //~| HELP use angle brackets - - type B = Ty; - //~^ ERROR this struct takes at least 2 type arguments but only 1 type argument was supplied - //~| HELP add missing type argument - - type C = Ty; - - type D = Ty; - - type E = Ty; - //~^ ERROR this struct takes at most 3 type arguments but 4 type arguments were supplied - //~| HELP remove -} - -// Traits have an implicit `Self` type - these tests ensure we don't accidentally return it -// somewhere in the message -mod r#trait { - trait NonGeneric { - // - } - - trait GenericLifetime<'a> { - // - } - - trait GenericType { - // - } - - type A = Box>; - //~^ ERROR this trait takes 0 type arguments but 1 type argument was supplied - //~| HELP remove - - type B = Box; - //~^ ERROR missing lifetime specifier - //~| HELP consider introducing - - type C = Box>; - //~^ ERROR this trait takes 1 lifetime argument but 2 lifetime arguments were supplied - //~| HELP remove - - type D = Box; - //~^ ERROR missing generics for trait `GenericType` - //~| HELP use angle brackets - - type E = Box>; - //~^ ERROR this trait takes 1 type argument but 2 type arguments were supplied - //~| HELP remove -} - -mod stdlib { - mod hash_map { - use std::collections::HashMap; - - type A = HashMap; - //~^ ERROR missing generics for struct `HashMap` - //~| HELP use angle brackets - - type B = HashMap; - //~^ ERROR this struct takes at least 2 type arguments but only 1 type argument was supplied - //~| HELP add missing type argument - - type C = HashMap<'static>; - //~^ ERROR this struct takes 0 lifetime arguments but 1 lifetime argument was supplied - //~| HELP remove these generics - //~| ERROR this struct takes at least 2 type arguments but 0 type arguments were supplied - //~| HELP add missing type arguments - - type D = HashMap; - //~^ ERROR this struct takes at most 3 type arguments but 4 type arguments were supplied - //~| HELP remove this type argument - } - - mod result { - type A = Result; - //~^ ERROR missing generics for enum `std::result::Result` - //~| HELP use angle brackets - - type B = Result; - //~^ ERROR this enum takes 2 type arguments but only 1 type argument was supplied - //~| HELP add missing type argument - - type C = Result<'static>; - //~^ ERROR this enum takes 0 lifetime arguments but 1 lifetime argument was supplied - //~| HELP remove these generics - //~| ERROR this enum takes 2 type arguments but 0 type arguments were supplied - //~| HELP add missing type arguments - - type D = Result; - //~^ ERROR this enum takes 2 type arguments but 3 type arguments were supplied - //~| HELP remove - } -} - -fn main() { } diff --git a/src/test/ui/generics/wrong-number-of-args.stderr b/src/test/ui/generics/wrong-number-of-args.stderr deleted file mode 100644 index 2a34fba2c4875..0000000000000 --- a/src/test/ui/generics/wrong-number-of-args.stderr +++ /dev/null @@ -1,449 +0,0 @@ -error[E0106]: missing lifetime specifier - --> $DIR/wrong-number-of-args.rs:44:14 - | -LL | type A = Ty; - | ^^ expected named lifetime parameter - | -help: consider introducing a named lifetime parameter - | -LL | type A<'a> = Ty<'a>; - | ^^^^ ^^^^^^ - -error[E0106]: missing lifetime specifier - --> $DIR/wrong-number-of-args.rs:54:17 - | -LL | type C = Ty; - | ^ expected named lifetime parameter - | -help: consider introducing a named lifetime parameter - | -LL | type C<'a> = Ty<'a, usize>; - | ^^^^ ^^^ - -error[E0106]: missing lifetime specifier - --> $DIR/wrong-number-of-args.rs:100:22 - | -LL | type B = Box; - | ^^^^^^^^^^^^^^^ expected named lifetime parameter - | -help: consider introducing a named lifetime parameter - | -LL | type B<'a> = Box>; - | ^^^^ ^^^^^^^^^^^^^^^^^^^ - -error[E0107]: this struct takes 0 lifetime arguments but 1 lifetime argument was supplied - --> $DIR/wrong-number-of-args.rs:6:14 - | -LL | type B = Ty<'static>; - | ^^--------- help: remove these generics - | | - | expected 0 lifetime arguments - | -note: struct defined here, with 0 lifetime parameters - --> $DIR/wrong-number-of-args.rs:2:12 - | -LL | struct Ty; - | ^^ - -error[E0107]: this struct takes 0 lifetime arguments but 1 lifetime argument was supplied - --> $DIR/wrong-number-of-args.rs:10:14 - | -LL | type C = Ty<'static, usize>; - | ^^ --------- help: remove this lifetime argument - | | - | expected 0 lifetime arguments - | -note: struct defined here, with 0 lifetime parameters - --> $DIR/wrong-number-of-args.rs:2:12 - | -LL | struct Ty; - | ^^ - -error[E0107]: this struct takes 0 type arguments but 1 type argument was supplied - --> $DIR/wrong-number-of-args.rs:10:14 - | -LL | type C = Ty<'static, usize>; - | ^^ ------- help: remove this type argument - | | - | expected 0 type arguments - | -note: struct defined here, with 0 type parameters - --> $DIR/wrong-number-of-args.rs:2:12 - | -LL | struct Ty; - | ^^ - -error[E0107]: this struct takes 0 lifetime arguments but 1 lifetime argument was supplied - --> $DIR/wrong-number-of-args.rs:16:14 - | -LL | type D = Ty<'static, usize, { 0 }>; - | ^^ --------- help: remove this lifetime argument - | | - | expected 0 lifetime arguments - | -note: struct defined here, with 0 lifetime parameters - --> $DIR/wrong-number-of-args.rs:2:12 - | -LL | struct Ty; - | ^^ - -error[E0107]: this struct takes 0 generic arguments but 2 generic arguments were supplied - --> $DIR/wrong-number-of-args.rs:16:14 - | -LL | type D = Ty<'static, usize, { 0 }>; - | ^^ -------------- help: remove these generic arguments - | | - | expected 0 generic arguments - | -note: struct defined here, with 0 generic parameters - --> $DIR/wrong-number-of-args.rs:2:12 - | -LL | struct Ty; - | ^^ - -error[E0107]: missing generics for struct `type_and_type::Ty` - --> $DIR/wrong-number-of-args.rs:26:14 - | -LL | type A = Ty; - | ^^ expected 2 type arguments - | -note: struct defined here, with 2 type parameters: `A`, `B` - --> $DIR/wrong-number-of-args.rs:24:12 - | -LL | struct Ty; - | ^^ - - -help: use angle brackets to add missing type arguments - | -LL | type A = Ty; - | ^^^^^^ - -error[E0107]: this struct takes 2 type arguments but only 1 type argument was supplied - --> $DIR/wrong-number-of-args.rs:30:14 - | -LL | type B = Ty; - | ^^ ----- supplied 1 type argument - | | - | expected 2 type arguments - | -note: struct defined here, with 2 type parameters: `A`, `B` - --> $DIR/wrong-number-of-args.rs:24:12 - | -LL | struct Ty; - | ^^ - - -help: add missing type argument - | -LL | type B = Ty; - | ^^^ - -error[E0107]: this struct takes 2 type arguments but 3 type arguments were supplied - --> $DIR/wrong-number-of-args.rs:36:14 - | -LL | type D = Ty; - | ^^ ------ help: remove this type argument - | | - | expected 2 type arguments - | -note: struct defined here, with 2 type parameters: `A`, `B` - --> $DIR/wrong-number-of-args.rs:24:12 - | -LL | struct Ty; - | ^^ - - - -error[E0107]: missing generics for struct `lifetime_and_type::Ty` - --> $DIR/wrong-number-of-args.rs:44:14 - | -LL | type A = Ty; - | ^^ expected 1 type argument - | -note: struct defined here, with 1 type parameter: `T` - --> $DIR/wrong-number-of-args.rs:42:12 - | -LL | struct Ty<'a, T>; - | ^^ - -help: use angle brackets to add missing type argument - | -LL | type A = Ty; - | ^^^ - -error[E0107]: this struct takes 1 type argument but 0 type arguments were supplied - --> $DIR/wrong-number-of-args.rs:50:14 - | -LL | type B = Ty<'static>; - | ^^ expected 1 type argument - | -note: struct defined here, with 1 type parameter: `T` - --> $DIR/wrong-number-of-args.rs:42:12 - | -LL | struct Ty<'a, T>; - | ^^ - -help: add missing type argument - | -LL | type B = Ty<'static, T>; - | ^^^ - -error[E0107]: missing generics for struct `type_and_type_and_type::Ty` - --> $DIR/wrong-number-of-args.rs:64:14 - | -LL | type A = Ty; - | ^^ expected at least 2 type arguments - | -note: struct defined here, with at least 2 type parameters: `A`, `B` - --> $DIR/wrong-number-of-args.rs:62:12 - | -LL | struct Ty; - | ^^ - - -help: use angle brackets to add missing type arguments - | -LL | type A = Ty; - | ^^^^^^ - -error[E0107]: this struct takes at least 2 type arguments but only 1 type argument was supplied - --> $DIR/wrong-number-of-args.rs:68:14 - | -LL | type B = Ty; - | ^^ ----- supplied 1 type argument - | | - | expected at least 2 type arguments - | -note: struct defined here, with at least 2 type parameters: `A`, `B` - --> $DIR/wrong-number-of-args.rs:62:12 - | -LL | struct Ty; - | ^^ - - -help: add missing type argument - | -LL | type B = Ty; - | ^^^ - -error[E0107]: this struct takes at most 3 type arguments but 4 type arguments were supplied - --> $DIR/wrong-number-of-args.rs:76:14 - | -LL | type E = Ty; - | ^^ ----- help: remove this type argument - | | - | expected at most 3 type arguments - | -note: struct defined here, with at most 3 type parameters: `A`, `B`, `C` - --> $DIR/wrong-number-of-args.rs:62:12 - | -LL | struct Ty; - | ^^ - - - - -error[E0107]: this trait takes 0 type arguments but 1 type argument was supplied - --> $DIR/wrong-number-of-args.rs:96:22 - | -LL | type A = Box>; - | ^^^^^^^^^^------- help: remove these generics - | | - | expected 0 type arguments - | -note: trait defined here, with 0 type parameters - --> $DIR/wrong-number-of-args.rs:84:11 - | -LL | trait NonGeneric { - | ^^^^^^^^^^ - -error[E0107]: this trait takes 1 lifetime argument but 2 lifetime arguments were supplied - --> $DIR/wrong-number-of-args.rs:104:22 - | -LL | type C = Box>; - | ^^^^^^^^^^^^^^^ --------- help: remove this lifetime argument - | | - | expected 1 lifetime argument - | -note: trait defined here, with 1 lifetime parameter: `'a` - --> $DIR/wrong-number-of-args.rs:88:11 - | -LL | trait GenericLifetime<'a> { - | ^^^^^^^^^^^^^^^ -- - -error[E0107]: missing generics for trait `GenericType` - --> $DIR/wrong-number-of-args.rs:108:22 - | -LL | type D = Box; - | ^^^^^^^^^^^ expected 1 type argument - | -note: trait defined here, with 1 type parameter: `A` - --> $DIR/wrong-number-of-args.rs:92:11 - | -LL | trait GenericType { - | ^^^^^^^^^^^ - -help: use angle brackets to add missing type argument - | -LL | type D = Box>; - | ^^^ - -error[E0107]: this trait takes 1 type argument but 2 type arguments were supplied - --> $DIR/wrong-number-of-args.rs:112:22 - | -LL | type E = Box>; - | ^^^^^^^^^^^ ------- help: remove this type argument - | | - | expected 1 type argument - | -note: trait defined here, with 1 type parameter: `A` - --> $DIR/wrong-number-of-args.rs:92:11 - | -LL | trait GenericType { - | ^^^^^^^^^^^ - - -error[E0107]: missing generics for struct `HashMap` - --> $DIR/wrong-number-of-args.rs:121:18 - | -LL | type A = HashMap; - | ^^^^^^^ expected at least 2 type arguments - | -note: struct defined here, with at least 2 type parameters: `K`, `V` - --> $SRC_DIR/std/src/collections/hash/map.rs:LL:COL - | -LL | pub struct HashMap { - | ^^^^^^^ - - -help: use angle brackets to add missing type arguments - | -LL | type A = HashMap; - | ^^^^^^ - -error[E0107]: this struct takes at least 2 type arguments but only 1 type argument was supplied - --> $DIR/wrong-number-of-args.rs:125:18 - | -LL | type B = HashMap; - | ^^^^^^^ ------ supplied 1 type argument - | | - | expected at least 2 type arguments - | -note: struct defined here, with at least 2 type parameters: `K`, `V` - --> $SRC_DIR/std/src/collections/hash/map.rs:LL:COL - | -LL | pub struct HashMap { - | ^^^^^^^ - - -help: add missing type argument - | -LL | type B = HashMap; - | ^^^ - -error[E0107]: this struct takes 0 lifetime arguments but 1 lifetime argument was supplied - --> $DIR/wrong-number-of-args.rs:129:18 - | -LL | type C = HashMap<'static>; - | ^^^^^^^--------- help: remove these generics - | | - | expected 0 lifetime arguments - | -note: struct defined here, with 0 lifetime parameters - --> $SRC_DIR/std/src/collections/hash/map.rs:LL:COL - | -LL | pub struct HashMap { - | ^^^^^^^ - -error[E0107]: this struct takes at least 2 type arguments but 0 type arguments were supplied - --> $DIR/wrong-number-of-args.rs:129:18 - | -LL | type C = HashMap<'static>; - | ^^^^^^^ expected at least 2 type arguments - | -note: struct defined here, with at least 2 type parameters: `K`, `V` - --> $SRC_DIR/std/src/collections/hash/map.rs:LL:COL - | -LL | pub struct HashMap { - | ^^^^^^^ - - -help: add missing type arguments - | -LL | type C = HashMap<'static, K, V>; - | ^^^^^^ - -error[E0107]: this struct takes at most 3 type arguments but 4 type arguments were supplied - --> $DIR/wrong-number-of-args.rs:135:18 - | -LL | type D = HashMap; - | ^^^^^^^ ----- help: remove this type argument - | | - | expected at most 3 type arguments - | -note: struct defined here, with at most 3 type parameters: `K`, `V`, `S` - --> $SRC_DIR/std/src/collections/hash/map.rs:LL:COL - | -LL | pub struct HashMap { - | ^^^^^^^ - - - - -error[E0107]: missing generics for enum `std::result::Result` - --> $DIR/wrong-number-of-args.rs:141:18 - | -LL | type A = Result; - | ^^^^^^ expected 2 type arguments - | -note: enum defined here, with 2 type parameters: `T`, `E` - --> $SRC_DIR/core/src/result.rs:LL:COL - | -LL | pub enum Result { - | ^^^^^^ - - -help: use angle brackets to add missing type arguments - | -LL | type A = Result; - | ^^^^^^ - -error[E0107]: this enum takes 2 type arguments but only 1 type argument was supplied - --> $DIR/wrong-number-of-args.rs:145:18 - | -LL | type B = Result; - | ^^^^^^ ------ supplied 1 type argument - | | - | expected 2 type arguments - | -note: enum defined here, with 2 type parameters: `T`, `E` - --> $SRC_DIR/core/src/result.rs:LL:COL - | -LL | pub enum Result { - | ^^^^^^ - - -help: add missing type argument - | -LL | type B = Result; - | ^^^ - -error[E0107]: this enum takes 0 lifetime arguments but 1 lifetime argument was supplied - --> $DIR/wrong-number-of-args.rs:149:18 - | -LL | type C = Result<'static>; - | ^^^^^^--------- help: remove these generics - | | - | expected 0 lifetime arguments - | -note: enum defined here, with 0 lifetime parameters - --> $SRC_DIR/core/src/result.rs:LL:COL - | -LL | pub enum Result { - | ^^^^^^ - -error[E0107]: this enum takes 2 type arguments but 0 type arguments were supplied - --> $DIR/wrong-number-of-args.rs:149:18 - | -LL | type C = Result<'static>; - | ^^^^^^ expected 2 type arguments - | -note: enum defined here, with 2 type parameters: `T`, `E` - --> $SRC_DIR/core/src/result.rs:LL:COL - | -LL | pub enum Result { - | ^^^^^^ - - -help: add missing type arguments - | -LL | type C = Result<'static, T, E>; - | ^^^^^^ - -error[E0107]: this enum takes 2 type arguments but 3 type arguments were supplied - --> $DIR/wrong-number-of-args.rs:155:18 - | -LL | type D = Result; - | ^^^^^^ ------ help: remove this type argument - | | - | expected 2 type arguments - | -note: enum defined here, with 2 type parameters: `T`, `E` - --> $SRC_DIR/core/src/result.rs:LL:COL - | -LL | pub enum Result { - | ^^^^^^ - - - -error: aborting due to 30 previous errors - -Some errors have detailed explanations: E0106, E0107. -For more information about an error, try `rustc --explain E0106`. diff --git a/src/test/ui/hashmap/hashmap-memory.rs b/src/test/ui/hashmap/hashmap-memory.rs index 2031196ab215e..3129eb0da82f9 100644 --- a/src/test/ui/hashmap/hashmap-memory.rs +++ b/src/test/ui/hashmap/hashmap-memory.rs @@ -23,7 +23,7 @@ mod map_reduce { pub type putter<'a> = Box; - pub type mapper = extern "C" fn(String, putter); + pub type mapper = extern fn(String, putter); enum ctrl_proto { find_reducer(Vec, Sender), mapper_done, } diff --git a/src/test/ui/hrtb/hrtb-perfect-forwarding.stderr b/src/test/ui/hrtb/hrtb-perfect-forwarding.stderr index ed810d443bef7..1ceb0c99e90e9 100644 --- a/src/test/ui/hrtb/hrtb-perfect-forwarding.stderr +++ b/src/test/ui/hrtb/hrtb-perfect-forwarding.stderr @@ -2,39 +2,19 @@ error[E0308]: mismatched types --> $DIR/hrtb-perfect-forwarding.rs:46:5 | LL | foo_hrtb_bar_not(&mut t); - | ^^^^^^^^^^^^^^^^ lifetime mismatch + | ^^^^^^^^^^^^^^^^ one type is more general than the other | = note: expected type `Bar<&'a isize>` found type `Bar<&'b isize>` -note: the required lifetime does not necessarily outlive the lifetime `'b` as defined on the function body at 39:21 - --> $DIR/hrtb-perfect-forwarding.rs:39:21 - | -LL | fn foo_hrtb_bar_not<'b,T>(mut t: T) - | ^^ -note: the lifetime requirement is introduced here - --> $DIR/hrtb-perfect-forwarding.rs:40:15 - | -LL | where T : for<'a> Foo<&'a isize> + Bar<&'b isize> - | ^^^^^^^^^^^^^^^^^^^^^^ error[E0308]: mismatched types --> $DIR/hrtb-perfect-forwarding.rs:46:5 | LL | foo_hrtb_bar_not(&mut t); - | ^^^^^^^^^^^^^^^^ lifetime mismatch + | ^^^^^^^^^^^^^^^^ one type is more general than the other | = note: expected type `Bar<&'a isize>` found type `Bar<&'b isize>` -note: the lifetime `'b` as defined on the function body at 39:21 doesn't meet the lifetime requirements - --> $DIR/hrtb-perfect-forwarding.rs:39:21 - | -LL | fn foo_hrtb_bar_not<'b,T>(mut t: T) - | ^^ -note: the lifetime requirement is introduced here - --> $DIR/hrtb-perfect-forwarding.rs:40:15 - | -LL | where T : for<'a> Foo<&'a isize> + Bar<&'b isize> - | ^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 2 previous errors diff --git a/src/test/ui/hygiene/traits-in-scope.rs b/src/test/ui/hygiene/traits-in-scope.rs deleted file mode 100644 index 548bb226b713c..0000000000000 --- a/src/test/ui/hygiene/traits-in-scope.rs +++ /dev/null @@ -1,53 +0,0 @@ -// Macros with def-site hygiene still bring traits into scope. -// It is not clear whether this is desirable behavior or not. -// It is also not clear how to prevent it if it is not desirable. - -// check-pass - -#![feature(decl_macro)] -#![feature(trait_alias)] - -mod traits { - pub trait Trait1 { - fn simple_import(&self) {} - } - pub trait Trait2 { - fn renamed_import(&self) {} - } - pub trait Trait3 { - fn underscore_import(&self) {} - } - pub trait Trait4 { - fn trait_alias(&self) {} - } - - impl Trait1 for () {} - impl Trait2 for () {} - impl Trait3 for () {} - impl Trait4 for () {} -} - -macro m1() { - use traits::Trait1; -} -macro m2() { - use traits::Trait2 as Alias; -} -macro m3() { - use traits::Trait3 as _; -} -macro m4() { - trait Alias = traits::Trait4; -} - -fn main() { - m1!(); - m2!(); - m3!(); - m4!(); - - ().simple_import(); - ().renamed_import(); - ().underscore_import(); - ().trait_alias(); -} diff --git a/src/test/ui/illegal-ufcs-drop.fixed b/src/test/ui/illegal-ufcs-drop.fixed deleted file mode 100644 index d73b391be0621..0000000000000 --- a/src/test/ui/illegal-ufcs-drop.fixed +++ /dev/null @@ -1,10 +0,0 @@ -// run-rustfix -struct Foo; - -impl Drop for Foo { - fn drop(&mut self) {} -} - -fn main() { - drop(&mut Foo) //~ ERROR explicit use of destructor method -} diff --git a/src/test/ui/illegal-ufcs-drop.rs b/src/test/ui/illegal-ufcs-drop.rs index 11411f55494c5..5c072663eda45 100644 --- a/src/test/ui/illegal-ufcs-drop.rs +++ b/src/test/ui/illegal-ufcs-drop.rs @@ -1,4 +1,3 @@ -// run-rustfix struct Foo; impl Drop for Foo { diff --git a/src/test/ui/illegal-ufcs-drop.stderr b/src/test/ui/illegal-ufcs-drop.stderr index 91f47d5e456d3..57c99739afd24 100644 --- a/src/test/ui/illegal-ufcs-drop.stderr +++ b/src/test/ui/illegal-ufcs-drop.stderr @@ -1,5 +1,5 @@ error[E0040]: explicit use of destructor method - --> $DIR/illegal-ufcs-drop.rs:9:5 + --> $DIR/illegal-ufcs-drop.rs:8:5 | LL | Drop::drop(&mut Foo) | ^^^^^^^^^^ diff --git a/src/test/ui/imports/glob-resolve1.rs b/src/test/ui/imports/glob-resolve1.rs index 904b77117dafc..32660fdb41876 100644 --- a/src/test/ui/imports/glob-resolve1.rs +++ b/src/test/ui/imports/glob-resolve1.rs @@ -5,15 +5,11 @@ use bar::*; mod bar { use self::fpriv as import; fn fpriv() {} - extern "C" { + extern { fn epriv(); } - enum A { - A1, - } - pub enum B { - B1, - } + enum A { A1 } + pub enum B { B1 } struct C; diff --git a/src/test/ui/imports/glob-resolve1.stderr b/src/test/ui/imports/glob-resolve1.stderr index 7629cede7a45f..cd128c1ea0b48 100644 --- a/src/test/ui/imports/glob-resolve1.stderr +++ b/src/test/ui/imports/glob-resolve1.stderr @@ -1,5 +1,5 @@ error[E0425]: cannot find function `fpriv` in this scope - --> $DIR/glob-resolve1.rs:26:5 + --> $DIR/glob-resolve1.rs:22:5 | LL | fpriv(); | ^^^^^ not found in this scope @@ -10,7 +10,7 @@ LL | use bar::fpriv; | error[E0425]: cannot find function `epriv` in this scope - --> $DIR/glob-resolve1.rs:27:5 + --> $DIR/glob-resolve1.rs:23:5 | LL | epriv(); | ^^^^^ not found in this scope @@ -21,25 +21,23 @@ LL | use bar::epriv; | error[E0423]: expected value, found enum `B` - --> $DIR/glob-resolve1.rs:28:5 + --> $DIR/glob-resolve1.rs:24:5 | LL | B; | ^ | note: the enum is defined here - --> $DIR/glob-resolve1.rs:14:5 + --> $DIR/glob-resolve1.rs:12:5 | -LL | / pub enum B { -LL | | B1, -LL | | } - | |_____^ +LL | pub enum B { B1 } + | ^^^^^^^^^^^^^^^^^ help: you might have meant to use the following enum variant | LL | B::B1; | ^^^^^ error[E0425]: cannot find value `C` in this scope - --> $DIR/glob-resolve1.rs:29:5 + --> $DIR/glob-resolve1.rs:25:5 | LL | C; | ^ not found in this scope @@ -50,7 +48,7 @@ LL | use bar::C; | error[E0425]: cannot find function `import` in this scope - --> $DIR/glob-resolve1.rs:30:5 + --> $DIR/glob-resolve1.rs:26:5 | LL | import(); | ^^^^^^ not found in this scope @@ -61,9 +59,9 @@ LL | use other::import; | error[E0412]: cannot find type `A` in this scope - --> $DIR/glob-resolve1.rs:32:11 + --> $DIR/glob-resolve1.rs:28:11 | -LL | pub enum B { +LL | pub enum B { B1 } | ---------- similarly named enum `B` defined here ... LL | foo::(); @@ -79,9 +77,9 @@ LL | use bar::A; | error[E0412]: cannot find type `C` in this scope - --> $DIR/glob-resolve1.rs:33:11 + --> $DIR/glob-resolve1.rs:29:11 | -LL | pub enum B { +LL | pub enum B { B1 } | ---------- similarly named enum `B` defined here ... LL | foo::(); @@ -97,9 +95,9 @@ LL | use bar::C; | error[E0412]: cannot find type `D` in this scope - --> $DIR/glob-resolve1.rs:34:11 + --> $DIR/glob-resolve1.rs:30:11 | -LL | pub enum B { +LL | pub enum B { B1 } | ---------- similarly named enum `B` defined here ... LL | foo::(); diff --git a/src/test/ui/llvm-asm/inline-asm-bad-constraint.rs b/src/test/ui/inline-asm-bad-constraint.rs similarity index 100% rename from src/test/ui/llvm-asm/inline-asm-bad-constraint.rs rename to src/test/ui/inline-asm-bad-constraint.rs diff --git a/src/test/ui/llvm-asm/inline-asm-bad-constraint.stderr b/src/test/ui/inline-asm-bad-constraint.stderr similarity index 100% rename from src/test/ui/llvm-asm/inline-asm-bad-constraint.stderr rename to src/test/ui/inline-asm-bad-constraint.stderr diff --git a/src/test/ui/llvm-asm/inline-asm-bad-operand.rs b/src/test/ui/inline-asm-bad-operand.rs similarity index 100% rename from src/test/ui/llvm-asm/inline-asm-bad-operand.rs rename to src/test/ui/inline-asm-bad-operand.rs diff --git a/src/test/ui/llvm-asm/inline-asm-bad-operand.stderr b/src/test/ui/inline-asm-bad-operand.stderr similarity index 100% rename from src/test/ui/llvm-asm/inline-asm-bad-operand.stderr rename to src/test/ui/inline-asm-bad-operand.stderr diff --git a/src/test/ui/intrinsics/intrinsic-move-val-cleanups.rs b/src/test/ui/intrinsics/intrinsic-move-val-cleanups.rs new file mode 100644 index 0000000000000..9804c421db081 --- /dev/null +++ b/src/test/ui/intrinsics/intrinsic-move-val-cleanups.rs @@ -0,0 +1,191 @@ +// run-pass +#![allow(unused_braces)] +#![allow(unused_unsafe)] +#![allow(unreachable_code)] +// ignore-emscripten no threads support +#![allow(stable_features)] + +// This test is checking that the move_val_init intrinsic is +// respecting cleanups for both of its argument expressions. +// +// In other words, if either DEST or SOURCE in +// +// `intrinsics::move_val_init(DEST, SOURCE) +// +// introduce temporaries that require cleanup, and SOURCE panics, then +// make sure the cleanups still occur. + +#![feature(core_intrinsics, sync_poison)] + +use std::cell::RefCell; +use std::intrinsics; +use std::sync::{Arc, LockResult, Mutex, MutexGuard}; +use std::thread; + +type LogEntry = (&'static str, i32); +type Guarded = RefCell>; +#[derive(Clone)] +struct Log(Arc>); +struct Acquired<'a>(MutexGuard<'a, Guarded>); +type LogState = (MutexWas, &'static [LogEntry]); + +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +enum MutexWas { Poisoned, NotPoisoned } + +impl Log { + fn lock(&self) -> LockResult>>> { self.0.lock() } + fn acquire(&self) -> Acquired { Acquired(self.0.lock().unwrap()) } +} + +impl<'a> Acquired<'a> { + fn log(&self, s: &'static str, i: i32) { self.0.borrow_mut().push((s, i)); } +} + +const TEST1_EXPECT: LogState = (MutexWas::NotPoisoned, + &[("double-check non-poisoning path", 1) + ]); + +fn test1(log: Log) { + { + let acq = log.acquire(); + acq.log("double-check non-poisoning path", 1); + } + panic!("every test ends in a panic"); +} + +const TEST2_EXPECT: LogState = (MutexWas::Poisoned, + &[("double-check poisoning path", 1), + ("and multiple log entries", 2), + ]); +fn test2(log: Log) { + let acq = log.acquire(); + acq.log("double-check poisoning path", 1); + acq.log("and multiple log entries", 2); + panic!("every test ends in a panic"); +} + +struct LogOnDrop<'a>(&'a Acquired<'a>, &'static str, i32); +impl<'a> Drop for LogOnDrop<'a> { + fn drop(&mut self) { + self.0.log(self.1, self.2); + } +} + +const TEST3_EXPECT: LogState = (MutexWas::Poisoned, + &[("double-check destructors can log", 1), + ("drop d2", 2), + ("drop d1", 3), + ]); +fn test3(log: Log) { + let acq = log.acquire(); + acq.log("double-check destructors can log", 1); + let _d1 = LogOnDrop(&acq, "drop d1", 3); + let _d2 = LogOnDrop(&acq, "drop d2", 2); + panic!("every test ends in a panic"); +} + +// The *real* tests of panic-handling for move_val_init intrinsic +// start here. + +const TEST4_EXPECT: LogState = (MutexWas::Poisoned, + &[("neither arg panics", 1), + ("drop temp LOD", 2), + ("drop temp LOD", 3), + ("drop dest_b", 4), + ("drop dest_a", 5), + ]); +fn test4(log: Log) { + let acq = log.acquire(); + acq.log("neither arg panics", 1); + let mut dest_a = LogOnDrop(&acq, "a will be overwritten, not dropped", 0); + let mut dest_b = LogOnDrop(&acq, "b will be overwritten, not dropped", 0); + unsafe { + intrinsics::move_val_init({ LogOnDrop(&acq, "drop temp LOD", 2); &mut dest_a }, + LogOnDrop(&acq, "drop dest_a", 5)); + intrinsics::move_val_init(&mut dest_b, { LogOnDrop(&acq, "drop temp LOD", 3); + LogOnDrop(&acq, "drop dest_b", 4) }); + } + panic!("every test ends in a panic"); +} + + +// Check that move_val_init(PANIC, SOURCE_EXPR) never evaluates SOURCE_EXPR +const TEST5_EXPECT: LogState = (MutexWas::Poisoned, + &[("first arg panics", 1), + ("drop orig dest_a", 2), + ]); +fn test5(log: Log) { + let acq = log.acquire(); + acq.log("first arg panics", 1); + let mut _dest_a = LogOnDrop(&acq, "drop orig dest_a", 2); + unsafe { + intrinsics::move_val_init({ panic!("every test ends in a panic") }, + LogOnDrop(&acq, "we never get here", 0)); + } +} + +// Check that move_val_init(DEST_EXPR, PANIC) cleans up temps from DEST_EXPR. +const TEST6_EXPECT: LogState = (MutexWas::Poisoned, + &[("second arg panics", 1), + ("drop temp LOD", 2), + ("drop orig dest_a", 3), + ]); +fn test6(log: Log) { + let acq = log.acquire(); + acq.log("second arg panics", 1); + let mut dest_a = LogOnDrop(&acq, "drop orig dest_a", 3); + unsafe { + intrinsics::move_val_init({ LogOnDrop(&acq, "drop temp LOD", 2); &mut dest_a }, + { panic!("every test ends in a panic"); }); + } +} + +// Check that move_val_init(DEST_EXPR, COMPLEX_PANIC) cleans up temps from COMPLEX_PANIC. +const TEST7_EXPECT: LogState = (MutexWas::Poisoned, + &[("second arg panics", 1), + ("drop temp LOD", 2), + ("drop temp LOD", 3), + ("drop orig dest_a", 4), + ]); +fn test7(log: Log) { + let acq = log.acquire(); + acq.log("second arg panics", 1); + let mut dest_a = LogOnDrop(&acq, "drop orig dest_a", 4); + unsafe { + intrinsics::move_val_init({ LogOnDrop(&acq, "drop temp LOD", 2); &mut dest_a }, + { LogOnDrop(&acq, "drop temp LOD", 3); + panic!("every test ends in a panic"); }); + } +} + +const TEST_SUITE: &'static [(&'static str, fn (Log), LogState)] = + &[("test1", test1, TEST1_EXPECT), + ("test2", test2, TEST2_EXPECT), + ("test3", test3, TEST3_EXPECT), + ("test4", test4, TEST4_EXPECT), + ("test5", test5, TEST5_EXPECT), + ("test6", test6, TEST6_EXPECT), + ("test7", test7, TEST7_EXPECT), + ]; + +fn main() { + for &(name, test, expect) in TEST_SUITE { + let log = Log(Arc::new(Mutex::new(RefCell::new(Vec::new())))); + let ret = { let log = log.clone(); thread::spawn(move || test(log)).join() }; + assert!(ret.is_err(), "{} must end with panic", name); + { + let l = log.lock(); + match l { + Ok(acq) => { + assert_eq!((MutexWas::NotPoisoned, &acq.borrow()[..]), expect); + println!("{} (unpoisoned) log: {:?}", name, *acq); + } + Err(e) => { + let acq = e.into_inner(); + assert_eq!((MutexWas::Poisoned, &acq.borrow()[..]), expect); + println!("{} (poisoned) log: {:?}", name, *acq); + } + } + } + } +} diff --git a/src/test/ui/intrinsics/intrinsic-move-val.rs b/src/test/ui/intrinsics/intrinsic-move-val.rs new file mode 100644 index 0000000000000..b672f1ed26e8d --- /dev/null +++ b/src/test/ui/intrinsics/intrinsic-move-val.rs @@ -0,0 +1,81 @@ +// run-pass + +#![feature(box_syntax)] +#![feature(intrinsics)] + +mod rusti { + extern "rust-intrinsic" { + pub fn move_val_init(dst: *mut T, src: T); + } +} + +pub fn main() { + unsafe { + // sanity check + check_drops_state(0, None); + + let mut x: Option> = Some(box D(1)); + assert_eq!(x.as_ref().unwrap().0, 1); + + // A normal overwrite, to demonstrate `check_drops_state`. + x = Some(box D(2)); + + // At this point, one destructor has run, because the + // overwrite of `x` drops its initial value. + check_drops_state(1, Some(1)); + + let mut y: Option> = std::mem::zeroed(); + + // An initial binding does not overwrite anything. + check_drops_state(1, Some(1)); + + // Since `y` has been initialized via the `init` intrinsic, it + // would be unsound to directly overwrite its value via normal + // assignment. + // + // The code currently generated by the compiler is overly + // accepting, however, in that it will check if `y` is itself + // null and thus avoid the unsound action of attempting to + // free null. In other words, if we were to do a normal + // assignment like `y = box D(4);` here, it probably would not + // crash today. But the plan is that it may well crash in the + // future, (I believe). + + // `x` is moved here; the manner in which this is tracked by the + // compiler is hidden. + rusti::move_val_init(&mut y, x); + + // But what we *can* observe is how many times the destructor + // for `D` is invoked, and what the last value we saw was + // during such a destructor call. We do so after the end of + // this scope. + + assert_eq!(y.as_ref().unwrap().0, 2); + y.as_mut().unwrap().0 = 3; + assert_eq!(y.as_ref().unwrap().0, 3); + + check_drops_state(1, Some(1)); + } + + check_drops_state(2, Some(3)); +} + +static mut NUM_DROPS: i32 = 0; +static mut LAST_DROPPED: Option = None; + +fn check_drops_state(num_drops: i32, last_dropped: Option) { + unsafe { + assert_eq!(NUM_DROPS, num_drops); + assert_eq!(LAST_DROPPED, last_dropped); + } +} + +struct D(i32); +impl Drop for D { + fn drop(&mut self) { + unsafe { + NUM_DROPS += 1; + LAST_DROPPED = Some(self.0); + } + } +} diff --git a/src/test/ui/parser/issue-76597.fixed b/src/test/ui/issue-76597.fixed similarity index 100% rename from src/test/ui/parser/issue-76597.fixed rename to src/test/ui/issue-76597.fixed diff --git a/src/test/ui/parser/issue-76597.rs b/src/test/ui/issue-76597.rs similarity index 100% rename from src/test/ui/parser/issue-76597.rs rename to src/test/ui/issue-76597.rs diff --git a/src/test/ui/parser/issue-76597.stderr b/src/test/ui/issue-76597.stderr similarity index 100% rename from src/test/ui/parser/issue-76597.stderr rename to src/test/ui/issue-76597.stderr diff --git a/src/test/ui/issues/auxiliary/issue-13620-1.rs b/src/test/ui/issues/auxiliary/issue-13620-1.rs index a77aa5a71553a..1442c0cc7aab3 100644 --- a/src/test/ui/issues/auxiliary/issue-13620-1.rs +++ b/src/test/ui/issues/auxiliary/issue-13620-1.rs @@ -1,8 +1,8 @@ pub struct Foo { - pub foo: extern "C" fn() + pub foo: extern fn() } -extern "C" fn the_foo() {} +extern fn the_foo() {} pub const FOO: Foo = Foo { foo: the_foo diff --git a/src/test/ui/issues/auxiliary/issue-15562.rs b/src/test/ui/issues/auxiliary/issue-15562.rs index 6ff26b47ea64f..d5afaaa5622aa 100644 --- a/src/test/ui/issues/auxiliary/issue-15562.rs +++ b/src/test/ui/issues/auxiliary/issue-15562.rs @@ -1,5 +1,5 @@ #![crate_type = "lib"] -extern "C" { +extern { pub fn transmute(); } diff --git a/src/test/ui/issues/auxiliary/issue-16725.rs b/src/test/ui/issues/auxiliary/issue-16725.rs index 9f9abd575bbfc..b75b5e2d8d701 100644 --- a/src/test/ui/issues/auxiliary/issue-16725.rs +++ b/src/test/ui/issues/auxiliary/issue-16725.rs @@ -1,3 +1,3 @@ -extern "C" { +extern { fn bar(); } diff --git a/src/test/ui/parser/auxiliary/issue-21146-inc.rs b/src/test/ui/issues/auxiliary/issue-21146-inc.rs similarity index 100% rename from src/test/ui/parser/auxiliary/issue-21146-inc.rs rename to src/test/ui/issues/auxiliary/issue-21146-inc.rs diff --git a/src/test/ui/issues/auxiliary/issue-25185-1.rs b/src/test/ui/issues/auxiliary/issue-25185-1.rs index e957be9c1c1b6..77a4787ba943d 100644 --- a/src/test/ui/issues/auxiliary/issue-25185-1.rs +++ b/src/test/ui/issues/auxiliary/issue-25185-1.rs @@ -3,6 +3,6 @@ #![crate_type = "rlib"] #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { pub fn rust_dbg_extern_identity_u32(u: u32) -> u32; } diff --git a/src/test/ui/macros/auxiliary/issue-40469.rs b/src/test/ui/issues/auxiliary/issue-40469.rs similarity index 100% rename from src/test/ui/macros/auxiliary/issue-40469.rs rename to src/test/ui/issues/auxiliary/issue-40469.rs diff --git a/src/test/ui/issues/issue-10764.rs b/src/test/ui/issues/issue-10764.rs index bb915f58d9d25..8fa3607815ad5 100644 --- a/src/test/ui/issues/issue-10764.rs +++ b/src/test/ui/issues/issue-10764.rs @@ -1,5 +1,5 @@ fn f(_: extern "Rust" fn()) {} -extern "C" fn bar() {} +extern fn bar() {} fn main() { f(bar) } //~^ ERROR mismatched types diff --git a/src/test/ui/issues/issue-10877.rs b/src/test/ui/issues/issue-10877.rs index 15a383175b975..b57929be28403 100644 --- a/src/test/ui/issues/issue-10877.rs +++ b/src/test/ui/issues/issue-10877.rs @@ -1,14 +1,12 @@ -struct Foo { - x: isize, -} -extern "C" { +struct Foo { x: isize } +extern { fn foo(1: ()); //~^ ERROR: patterns aren't allowed in foreign function declarations fn bar((): isize); //~^ ERROR: patterns aren't allowed in foreign function declarations fn baz(Foo { x }: isize); //~^ ERROR: patterns aren't allowed in foreign function declarations - fn qux((x, y): ()); + fn qux((x,y): ()); //~^ ERROR: patterns aren't allowed in foreign function declarations fn this_is_actually_ok(a: usize); fn and_so_is_this(_: usize); diff --git a/src/test/ui/issues/issue-10877.stderr b/src/test/ui/issues/issue-10877.stderr index bd3797cba5585..0f9dc211ceacf 100644 --- a/src/test/ui/issues/issue-10877.stderr +++ b/src/test/ui/issues/issue-10877.stderr @@ -1,26 +1,26 @@ error[E0130]: patterns aren't allowed in foreign function declarations - --> $DIR/issue-10877.rs:5:12 + --> $DIR/issue-10877.rs:3:12 | LL | fn foo(1: ()); | ^ pattern not allowed in foreign function error[E0130]: patterns aren't allowed in foreign function declarations - --> $DIR/issue-10877.rs:7:12 + --> $DIR/issue-10877.rs:5:12 | LL | fn bar((): isize); | ^^ pattern not allowed in foreign function error[E0130]: patterns aren't allowed in foreign function declarations - --> $DIR/issue-10877.rs:9:12 + --> $DIR/issue-10877.rs:7:12 | LL | fn baz(Foo { x }: isize); | ^^^^^^^^^ pattern not allowed in foreign function error[E0130]: patterns aren't allowed in foreign function declarations - --> $DIR/issue-10877.rs:11:12 + --> $DIR/issue-10877.rs:9:12 | -LL | fn qux((x, y): ()); - | ^^^^^^ pattern not allowed in foreign function +LL | fn qux((x,y): ()); + | ^^^^^ pattern not allowed in foreign function error: aborting due to 4 previous errors diff --git a/src/test/ui/regions/issue-12470.rs b/src/test/ui/issues/issue-12470.rs similarity index 100% rename from src/test/ui/regions/issue-12470.rs rename to src/test/ui/issues/issue-12470.rs diff --git a/src/test/ui/regions/issue-12470.stderr b/src/test/ui/issues/issue-12470.stderr similarity index 100% rename from src/test/ui/regions/issue-12470.stderr rename to src/test/ui/issues/issue-12470.stderr diff --git a/src/test/ui/issues/issue-1251.rs b/src/test/ui/issues/issue-1251.rs index c2c047c79615e..7f25c9a787ed9 100644 --- a/src/test/ui/issues/issue-1251.rs +++ b/src/test/ui/issues/issue-1251.rs @@ -3,14 +3,15 @@ #![allow(dead_code)] // pretty-expanded FIXME #23616 // ignore-wasm32-bare no libc to test ffi with + #![feature(rustc_private)] mod rustrt { extern crate libc; - extern "C" { + extern { pub fn rust_get_test_int() -> libc::intptr_t; } } -pub fn main() {} +pub fn main() { } diff --git a/src/test/ui/pattern/issue-12582.rs b/src/test/ui/issues/issue-12582.rs similarity index 100% rename from src/test/ui/pattern/issue-12582.rs rename to src/test/ui/issues/issue-12582.rs diff --git a/src/test/ui/issues/issue-14091.stderr b/src/test/ui/issues/issue-14091.stderr index fc49cc6d68ea0..7db4734780817 100644 --- a/src/test/ui/issues/issue-14091.stderr +++ b/src/test/ui/issues/issue-14091.stderr @@ -3,8 +3,6 @@ error[E0308]: mismatched types | LL | assert!(1,1); | ^^^^^^^^^^^^^ expected `bool`, found integer - | - = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to previous error diff --git a/src/test/ui/issues/issue-14092.rs b/src/test/ui/issues/issue-14092.rs index 67c2a42eafb78..3cfaa20a8b5ab 100644 --- a/src/test/ui/issues/issue-14092.rs +++ b/src/test/ui/issues/issue-14092.rs @@ -1,4 +1,4 @@ fn fn1(0: Box) {} -//~^ ERROR missing generics for struct `Box` + //~^ ERROR wrong number of type arguments: expected at least 1, found 0 [E0107] fn main() {} diff --git a/src/test/ui/issues/issue-14092.stderr b/src/test/ui/issues/issue-14092.stderr index 5cacce751c925..b749c44780d96 100644 --- a/src/test/ui/issues/issue-14092.stderr +++ b/src/test/ui/issues/issue-14092.stderr @@ -1,20 +1,8 @@ -error[E0107]: missing generics for struct `Box` +error[E0107]: wrong number of type arguments: expected at least 1, found 0 --> $DIR/issue-14092.rs:1:11 | LL | fn fn1(0: Box) {} | ^^^ expected at least 1 type argument - | -note: struct defined here, with at least 1 type parameter: `T` - --> $SRC_DIR/alloc/src/boxed.rs:LL:COL - | -LL | pub struct Box< - | ^^^ -LL | T: ?Sized, - | - -help: use angle brackets to add missing type argument - | -LL | fn fn1(0: Box) {} - | ^^^ error: aborting due to previous error diff --git a/src/test/ui/pattern/issue-14221.rs b/src/test/ui/issues/issue-14221.rs similarity index 100% rename from src/test/ui/pattern/issue-14221.rs rename to src/test/ui/issues/issue-14221.rs diff --git a/src/test/ui/pattern/issue-14221.stderr b/src/test/ui/issues/issue-14221.stderr similarity index 100% rename from src/test/ui/pattern/issue-14221.stderr rename to src/test/ui/issues/issue-14221.stderr diff --git a/src/test/ui/issues/issue-14227.rs b/src/test/ui/issues/issue-14227.rs index a1fde14600a10..d80eefc41bf53 100644 --- a/src/test/ui/issues/issue-14227.rs +++ b/src/test/ui/issues/issue-14227.rs @@ -1,4 +1,4 @@ -extern "C" { +extern { pub static symbol: u32; } static CRASH: u32 = symbol; diff --git a/src/test/ui/llvm-asm/issue-14936.rs b/src/test/ui/issues/issue-14936.rs similarity index 100% rename from src/test/ui/llvm-asm/issue-14936.rs rename to src/test/ui/issues/issue-14936.rs diff --git a/src/test/ui/issues/issue-15487.rs b/src/test/ui/issues/issue-15487.rs index 34ac53be5becc..17b16a62a74e7 100644 --- a/src/test/ui/issues/issue-15487.rs +++ b/src/test/ui/issues/issue-15487.rs @@ -3,11 +3,12 @@ // ignore-windows // ignore-wasm32-bare no libs to link // ignore-sgx no libs to link + #![feature(link_args)] -#[link_args = "-lc -lm"] -#[link_args = " -lc"] -#[link_args = "-lc "] -extern "C" {} +#[link_args="-lc -lm"] +#[link_args=" -lc"] +#[link_args="-lc "] +extern {} fn main() {} diff --git a/src/test/ui/issues/issue-15562.rs b/src/test/ui/issues/issue-15562.rs index dc0ecd365226c..b37ba81e291e6 100644 --- a/src/test/ui/issues/issue-15562.rs +++ b/src/test/ui/issues/issue-15562.rs @@ -16,4 +16,4 @@ pub fn main() { // The above extern is NOT `extern "rust-intrinsic"` and thus // means it'll try to find a corresponding symbol to link to. #[no_mangle] -pub extern "C" fn transmute() {} +pub extern fn transmute() {} diff --git a/src/test/ui/array-slice-vec/issue-15730.rs b/src/test/ui/issues/issue-15730.rs similarity index 100% rename from src/test/ui/array-slice-vec/issue-15730.rs rename to src/test/ui/issues/issue-15730.rs diff --git a/src/test/ui/issues/issue-15881-model-lexer-dotdotdot.rs b/src/test/ui/issues/issue-15881-model-lexer-dotdotdot.rs new file mode 100644 index 0000000000000..dee7f25d7bb3a --- /dev/null +++ b/src/test/ui/issues/issue-15881-model-lexer-dotdotdot.rs @@ -0,0 +1,38 @@ +// run-pass +#![allow(illegal_floating_point_literal_pattern)] // FIXME #41620 +#![allow(ellipsis_inclusive_range_patterns)] + +// regression test for the model lexer handling the DOTDOTDOT syntax (#15877) + + +pub fn main() { + match 5_usize { + 1_usize...5_usize => {} + _ => panic!("should match range"), + } + match 5_usize { + 6_usize...7_usize => panic!("shouldn't match range"), + _ => {} + } + match 5_usize { + 1_usize => panic!("should match non-first range"), + 2_usize...6_usize => {} + _ => panic!("math is broken") + } + match 'c' { + 'a'...'z' => {} + _ => panic!("should support char ranges") + } + match -3_isize { + -7...5 => {} + _ => panic!("should match signed range") + } + match 3.0f64 { + 1.0...5.0 => {} + _ => panic!("should match float range") + } + match -1.5f64 { + -3.6...3.6 => {} + _ => panic!("should match negative float range") + } +} diff --git a/src/test/ui/issues/issue-16149.rs b/src/test/ui/issues/issue-16149.rs index 51b60725c5a0c..7f0cad96a58df 100644 --- a/src/test/ui/issues/issue-16149.rs +++ b/src/test/ui/issues/issue-16149.rs @@ -1,4 +1,4 @@ -extern "C" { +extern { static externalValue: isize; } @@ -6,6 +6,6 @@ fn main() { let boolValue = match 42 { externalValue => true, //~^ ERROR match bindings cannot shadow statics - _ => false, + _ => false }; } diff --git a/src/test/ui/issues/issue-16250.rs b/src/test/ui/issues/issue-16250.rs index 436e2a6cee355..a3c6751ad897c 100644 --- a/src/test/ui/issues/issue-16250.rs +++ b/src/test/ui/issues/issue-16250.rs @@ -2,8 +2,9 @@ pub struct Foo; -extern "C" { +extern { pub fn foo(x: (Foo)); //~ ERROR `extern` block uses type `Foo` } -fn main() {} +fn main() { +} diff --git a/src/test/ui/issues/issue-16538.rs b/src/test/ui/issues/issue-16538.rs index 7d6eefa5b1e80..54d9a732912c7 100644 --- a/src/test/ui/issues/issue-16538.rs +++ b/src/test/ui/issues/issue-16538.rs @@ -1,6 +1,6 @@ mod Y { pub type X = usize; - extern "C" { + extern { pub static x: *const usize; } pub fn foo(value: *const X) -> *const X { diff --git a/src/test/ui/issues/issue-16939.stderr b/src/test/ui/issues/issue-16939.stderr index 8e4237039fad7..103f56fa04dd3 100644 --- a/src/test/ui/issues/issue-16939.stderr +++ b/src/test/ui/issues/issue-16939.stderr @@ -5,12 +5,6 @@ LL | |t| f(t); | ^ - supplied 1 argument | | | expected 0 arguments - | -note: associated function defined here - --> $SRC_DIR/core/src/ops/function.rs:LL:COL - | -LL | extern "rust-call" fn call(&self, args: Args) -> Self::Output; - | ^^^^ error: aborting due to previous error diff --git a/src/test/ui/borrowck/issue-17263.rs b/src/test/ui/issues/issue-17263.rs similarity index 100% rename from src/test/ui/borrowck/issue-17263.rs rename to src/test/ui/issues/issue-17263.rs diff --git a/src/test/ui/borrowck/issue-17545.rs b/src/test/ui/issues/issue-17545.rs similarity index 100% rename from src/test/ui/borrowck/issue-17545.rs rename to src/test/ui/issues/issue-17545.rs diff --git a/src/test/ui/borrowck/issue-17545.stderr b/src/test/ui/issues/issue-17545.stderr similarity index 100% rename from src/test/ui/borrowck/issue-17545.stderr rename to src/test/ui/issues/issue-17545.stderr diff --git a/src/test/ui/consts/issue-17718-borrow-interior.rs b/src/test/ui/issues/issue-17718-borrow-interior.rs similarity index 100% rename from src/test/ui/consts/issue-17718-borrow-interior.rs rename to src/test/ui/issues/issue-17718-borrow-interior.rs diff --git a/src/test/ui/consts/issue-17718-const-bad-values.rs b/src/test/ui/issues/issue-17718-const-bad-values.rs similarity index 100% rename from src/test/ui/consts/issue-17718-const-bad-values.rs rename to src/test/ui/issues/issue-17718-const-bad-values.rs diff --git a/src/test/ui/consts/issue-17718-const-bad-values.stderr b/src/test/ui/issues/issue-17718-const-bad-values.stderr similarity index 100% rename from src/test/ui/consts/issue-17718-const-bad-values.stderr rename to src/test/ui/issues/issue-17718-const-bad-values.stderr diff --git a/src/test/ui/consts/issue-17718-const-borrow.rs b/src/test/ui/issues/issue-17718-const-borrow.rs similarity index 100% rename from src/test/ui/consts/issue-17718-const-borrow.rs rename to src/test/ui/issues/issue-17718-const-borrow.rs diff --git a/src/test/ui/consts/issue-17718-const-borrow.stderr b/src/test/ui/issues/issue-17718-const-borrow.stderr similarity index 100% rename from src/test/ui/consts/issue-17718-const-borrow.stderr rename to src/test/ui/issues/issue-17718-const-borrow.stderr diff --git a/src/test/ui/lint/issue-17718-const-naming.rs b/src/test/ui/issues/issue-17718-const-naming.rs similarity index 100% rename from src/test/ui/lint/issue-17718-const-naming.rs rename to src/test/ui/issues/issue-17718-const-naming.rs diff --git a/src/test/ui/lint/issue-17718-const-naming.stderr b/src/test/ui/issues/issue-17718-const-naming.stderr similarity index 100% rename from src/test/ui/lint/issue-17718-const-naming.stderr rename to src/test/ui/issues/issue-17718-const-naming.stderr diff --git a/src/test/ui/issues/issue-18423.rs b/src/test/ui/issues/issue-18423.rs index a81b32f050c38..c072e6b5d22b5 100644 --- a/src/test/ui/issues/issue-18423.rs +++ b/src/test/ui/issues/issue-18423.rs @@ -1,8 +1,8 @@ // Test that `Box` cannot be used with a lifetime argument. struct Foo<'a> { - x: Box<'a, isize> - //~^ ERROR this struct takes 0 lifetime arguments but 1 lifetime argument was supplied + x: Box<'a, isize> //~ ERROR wrong number of lifetime arguments } -fn main() { } +pub fn main() { +} diff --git a/src/test/ui/issues/issue-18423.stderr b/src/test/ui/issues/issue-18423.stderr index f9006235234b3..141fd27be3649 100644 --- a/src/test/ui/issues/issue-18423.stderr +++ b/src/test/ui/issues/issue-18423.stderr @@ -1,16 +1,8 @@ -error[E0107]: this struct takes 0 lifetime arguments but 1 lifetime argument was supplied - --> $DIR/issue-18423.rs:4:8 +error[E0107]: wrong number of lifetime arguments: expected 0, found 1 + --> $DIR/issue-18423.rs:4:12 | LL | x: Box<'a, isize> - | ^^^ ---- help: remove this lifetime argument - | | - | expected 0 lifetime arguments - | -note: struct defined here, with 0 lifetime parameters - --> $SRC_DIR/alloc/src/boxed.rs:LL:COL - | -LL | pub struct Box< - | ^^^ + | ^^ unexpected lifetime argument error: aborting due to previous error diff --git a/src/test/ui/issues/issue-1866.rs b/src/test/ui/issues/issue-1866.rs index caac0c504141e..9f8a3a8262444 100644 --- a/src/test/ui/issues/issue-1866.rs +++ b/src/test/ui/issues/issue-1866.rs @@ -9,7 +9,7 @@ mod a { pub type rust_task = usize; pub mod rustrt { use super::rust_task; - extern "C" { + extern { pub fn rust_task_is_unwinding(rt: *const rust_task) -> bool; } } @@ -19,11 +19,11 @@ mod b { pub type rust_task = bool; pub mod rustrt { use super::rust_task; - extern "C" { + extern { pub fn rust_task_is_unwinding(rt: *const rust_task) -> bool; - //~^ WARN `rust_task_is_unwinding` redeclared with a different signature + //~^ WARN `rust_task_is_unwinding` redeclared with a different signature } } } -pub fn main() {} +pub fn main() { } diff --git a/src/test/ui/issues/issue-18804/auxiliary/lib.rs b/src/test/ui/issues/issue-18804/auxiliary/lib.rs index e29d48285d829..ae27dd520e9f8 100644 --- a/src/test/ui/issues/issue-18804/auxiliary/lib.rs +++ b/src/test/ui/issues/issue-18804/auxiliary/lib.rs @@ -1,10 +1,10 @@ #![crate_type = "rlib"] #![feature(linkage)] -pub fn foo() -> *const () { - extern "C" { +pub fn foo() -> *const() { + extern { #[linkage = "extern_weak"] - static FOO: *const (); + static FOO: *const(); } unsafe { FOO } } diff --git a/src/test/ui/issues/issue-20313-rpass.rs b/src/test/ui/issues/issue-20313-rpass.rs index 591f3659e98f3..09352044b0161 100644 --- a/src/test/ui/issues/issue-20313-rpass.rs +++ b/src/test/ui/issues/issue-20313-rpass.rs @@ -1,11 +1,13 @@ // run-pass #![allow(dead_code)] // pretty-expanded FIXME #23616 + #![feature(link_llvm_intrinsics)] -extern "C" { +extern { #[link_name = "llvm.sqrt.f32"] fn sqrt(x: f32) -> f32; } -fn main() {} +fn main(){ +} diff --git a/src/test/ui/issues/issue-20313.rs b/src/test/ui/issues/issue-20313.rs index a72af650c7071..4149ab4a30275 100644 --- a/src/test/ui/issues/issue-20313.rs +++ b/src/test/ui/issues/issue-20313.rs @@ -1,6 +1,7 @@ -extern "C" { +extern { #[link_name = "llvm.sqrt.f32"] fn sqrt(x: f32) -> f32; //~ ERROR linking to LLVM intrinsics is experimental } -fn main() {} +fn main(){ +} diff --git a/src/test/ui/parser/issue-20616-1.rs b/src/test/ui/issues/issue-20616-1.rs similarity index 100% rename from src/test/ui/parser/issue-20616-1.rs rename to src/test/ui/issues/issue-20616-1.rs diff --git a/src/test/ui/parser/issue-20616-1.stderr b/src/test/ui/issues/issue-20616-1.stderr similarity index 100% rename from src/test/ui/parser/issue-20616-1.stderr rename to src/test/ui/issues/issue-20616-1.stderr diff --git a/src/test/ui/parser/issue-20616-2.rs b/src/test/ui/issues/issue-20616-2.rs similarity index 100% rename from src/test/ui/parser/issue-20616-2.rs rename to src/test/ui/issues/issue-20616-2.rs diff --git a/src/test/ui/parser/issue-20616-2.stderr b/src/test/ui/issues/issue-20616-2.stderr similarity index 100% rename from src/test/ui/parser/issue-20616-2.stderr rename to src/test/ui/issues/issue-20616-2.stderr diff --git a/src/test/ui/borrowck/issue-20801.rs b/src/test/ui/issues/issue-20801.rs similarity index 100% rename from src/test/ui/borrowck/issue-20801.rs rename to src/test/ui/issues/issue-20801.rs diff --git a/src/test/ui/borrowck/issue-20801.stderr b/src/test/ui/issues/issue-20801.stderr similarity index 100% rename from src/test/ui/borrowck/issue-20801.stderr rename to src/test/ui/issues/issue-20801.stderr diff --git a/src/test/ui/parser/issue-21146.rs b/src/test/ui/issues/issue-21146.rs similarity index 100% rename from src/test/ui/parser/issue-21146.rs rename to src/test/ui/issues/issue-21146.rs diff --git a/src/test/ui/parser/issue-21146.stderr b/src/test/ui/issues/issue-21146.stderr similarity index 100% rename from src/test/ui/parser/issue-21146.stderr rename to src/test/ui/issues/issue-21146.stderr diff --git a/src/test/ui/consts/issue-21562.rs b/src/test/ui/issues/issue-21562.rs similarity index 100% rename from src/test/ui/consts/issue-21562.rs rename to src/test/ui/issues/issue-21562.rs diff --git a/src/test/ui/consts/issue-21721.rs b/src/test/ui/issues/issue-21721.rs similarity index 100% rename from src/test/ui/consts/issue-21721.rs rename to src/test/ui/issues/issue-21721.rs diff --git a/src/test/ui/issues/issue-2214.rs b/src/test/ui/issues/issue-2214.rs index 1994c3515ab3b..52ab29f423533 100644 --- a/src/test/ui/issues/issue-2214.rs +++ b/src/test/ui/issues/issue-2214.rs @@ -5,11 +5,13 @@ extern crate libc; -use libc::{c_double, c_int}; use std::mem; +use libc::{c_double, c_int}; fn to_c_int(v: &mut isize) -> &mut c_int { - unsafe { mem::transmute_copy(&v) } + unsafe { + mem::transmute_copy(&v) + } } fn lgamma(n: c_double, value: &mut isize) -> c_double { @@ -21,21 +23,21 @@ fn lgamma(n: c_double, value: &mut isize) -> c_double { mod m { use libc::{c_double, c_int}; - extern "C" { + extern { #[cfg(all(unix, not(target_os = "vxworks")))] #[link_name="lgamma_r"] pub fn lgamma(n: c_double, sign: &mut c_int) -> c_double; #[cfg(windows)] - #[link_name = "lgamma"] + #[link_name="lgamma"] pub fn lgamma(n: c_double, sign: &mut c_int) -> c_double; #[cfg(target_os = "vxworks")] - #[link_name = "lgamma"] + #[link_name="lgamma"] pub fn lgamma(n: c_double, sign: &mut c_int) -> c_double; } } pub fn main() { - let mut y: isize = 5; - let x: &mut isize = &mut y; - assert_eq!(lgamma(1.0 as c_double, x), 0.0 as c_double); + let mut y: isize = 5; + let x: &mut isize = &mut y; + assert_eq!(lgamma(1.0 as c_double, x), 0.0 as c_double); } diff --git a/src/test/ui/pattern/issue-22546.rs b/src/test/ui/issues/issue-22546.rs similarity index 100% rename from src/test/ui/pattern/issue-22546.rs rename to src/test/ui/issues/issue-22546.rs diff --git a/src/test/ui/issues/issue-23024.rs b/src/test/ui/issues/issue-23024.rs index e92273bd40914..ddeb516a4b030 100644 --- a/src/test/ui/issues/issue-23024.rs +++ b/src/test/ui/issues/issue-23024.rs @@ -8,6 +8,6 @@ fn main() vfnfer.push(box h); println!("{:?}",(vfnfer[0] as dyn Fn)(3)); //~^ ERROR the precise format of `Fn`-family traits' - //~| ERROR missing generics for trait `Fn` + //~| ERROR wrong number of type arguments: expected 1, found 0 [E0107] //~| ERROR the value of the associated type `Output` (from trait `FnOnce`) } diff --git a/src/test/ui/issues/issue-23024.stderr b/src/test/ui/issues/issue-23024.stderr index 1b876090ad6f6..fdb68ff7126a0 100644 --- a/src/test/ui/issues/issue-23024.stderr +++ b/src/test/ui/issues/issue-23024.stderr @@ -7,21 +7,11 @@ LL | println!("{:?}",(vfnfer[0] as dyn Fn)(3)); = note: see issue #29625 for more information = help: add `#![feature(unboxed_closures)]` to the crate attributes to enable -error[E0107]: missing generics for trait `Fn` +error[E0107]: wrong number of type arguments: expected 1, found 0 --> $DIR/issue-23024.rs:9:39 | LL | println!("{:?}",(vfnfer[0] as dyn Fn)(3)); | ^^ expected 1 type argument - | -note: trait defined here, with 1 type parameter: `Args` - --> $SRC_DIR/core/src/ops/function.rs:LL:COL - | -LL | pub trait Fn: FnMut { - | ^^ ---- -help: use angle brackets to add missing type argument - | -LL | println!("{:?}",(vfnfer[0] as dyn Fn)(3)); - | ^^^^^^ error[E0191]: the value of the associated type `Output` (from trait `FnOnce`) must be specified --> $DIR/issue-23024.rs:9:39 diff --git a/src/test/ui/regions/issue-24085.rs b/src/test/ui/issues/issue-24085.rs similarity index 100% rename from src/test/ui/regions/issue-24085.rs rename to src/test/ui/issues/issue-24085.rs diff --git a/src/test/ui/borrowck/issue-24267-flow-exit.rs b/src/test/ui/issues/issue-24267-flow-exit.rs similarity index 100% rename from src/test/ui/borrowck/issue-24267-flow-exit.rs rename to src/test/ui/issues/issue-24267-flow-exit.rs diff --git a/src/test/ui/borrowck/issue-24267-flow-exit.stderr b/src/test/ui/issues/issue-24267-flow-exit.stderr similarity index 100% rename from src/test/ui/borrowck/issue-24267-flow-exit.stderr rename to src/test/ui/issues/issue-24267-flow-exit.stderr diff --git a/src/test/ui/associated-types/issue-24338.rs b/src/test/ui/issues/issue-24338.rs similarity index 100% rename from src/test/ui/associated-types/issue-24338.rs rename to src/test/ui/issues/issue-24338.rs diff --git a/src/test/ui/borrowck/issue-25793.rs b/src/test/ui/issues/issue-25793.rs similarity index 100% rename from src/test/ui/borrowck/issue-25793.rs rename to src/test/ui/issues/issue-25793.rs diff --git a/src/test/ui/borrowck/issue-25793.stderr b/src/test/ui/issues/issue-25793.stderr similarity index 100% rename from src/test/ui/borrowck/issue-25793.stderr rename to src/test/ui/issues/issue-25793.stderr diff --git a/src/test/ui/binop/issue-25916.rs b/src/test/ui/issues/issue-25916.rs similarity index 100% rename from src/test/ui/binop/issue-25916.rs rename to src/test/ui/issues/issue-25916.rs diff --git a/src/test/ui/issues/issue-26217.stderr b/src/test/ui/issues/issue-26217.stderr index f5c641be2d47c..b1625536d4202 100644 --- a/src/test/ui/issues/issue-26217.stderr +++ b/src/test/ui/issues/issue-26217.stderr @@ -3,6 +3,8 @@ error[E0477]: the type `&'a i32` does not fulfill the required lifetime | LL | foo::<&'a i32>(); | ^^^^^^^^^^^^^^ + | + = note: type must outlive any other region error: aborting due to previous error diff --git a/src/test/ui/macros/issue-26322.rs b/src/test/ui/issues/issue-26322.rs similarity index 100% rename from src/test/ui/macros/issue-26322.rs rename to src/test/ui/issues/issue-26322.rs diff --git a/src/test/ui/imports/issue-26873-onefile.rs b/src/test/ui/issues/issue-26873-onefile.rs similarity index 100% rename from src/test/ui/imports/issue-26873-onefile.rs rename to src/test/ui/issues/issue-26873-onefile.rs diff --git a/src/test/ui/issues/issue-26997.rs b/src/test/ui/issues/issue-26997.rs index 3653e62732d41..fcabd1d84557c 100644 --- a/src/test/ui/issues/issue-26997.rs +++ b/src/test/ui/issues/issue-26997.rs @@ -7,7 +7,7 @@ pub struct Foo { impl Foo { #[allow(improper_ctypes_definitions)] - pub extern "C" fn foo_new() -> Foo { + pub extern fn foo_new() -> Foo { Foo { x: 21, y: 33 } } } diff --git a/src/test/ui/regions/issue-2718.rs b/src/test/ui/issues/issue-2718.rs similarity index 100% rename from src/test/ui/regions/issue-2718.rs rename to src/test/ui/issues/issue-2718.rs diff --git a/src/test/ui/borrowck/issue-27282-move-match-input-into-guard.rs b/src/test/ui/issues/issue-27282-move-match-input-into-guard.rs similarity index 100% rename from src/test/ui/borrowck/issue-27282-move-match-input-into-guard.rs rename to src/test/ui/issues/issue-27282-move-match-input-into-guard.rs diff --git a/src/test/ui/borrowck/issue-27282-move-match-input-into-guard.stderr b/src/test/ui/issues/issue-27282-move-match-input-into-guard.stderr similarity index 100% rename from src/test/ui/borrowck/issue-27282-move-match-input-into-guard.stderr rename to src/test/ui/issues/issue-27282-move-match-input-into-guard.stderr diff --git a/src/test/ui/borrowck/issue-27282-mutate-before-diverging-arm-2.rs b/src/test/ui/issues/issue-27282-mutate-before-diverging-arm-2.rs similarity index 100% rename from src/test/ui/borrowck/issue-27282-mutate-before-diverging-arm-2.rs rename to src/test/ui/issues/issue-27282-mutate-before-diverging-arm-2.rs diff --git a/src/test/ui/borrowck/issue-27282-mutate-before-diverging-arm-2.stderr b/src/test/ui/issues/issue-27282-mutate-before-diverging-arm-2.stderr similarity index 100% rename from src/test/ui/borrowck/issue-27282-mutate-before-diverging-arm-2.stderr rename to src/test/ui/issues/issue-27282-mutate-before-diverging-arm-2.stderr diff --git a/src/test/ui/borrowck/issue-27282-reborrow-ref-mut-in-guard.rs b/src/test/ui/issues/issue-27282-reborrow-ref-mut-in-guard.rs similarity index 100% rename from src/test/ui/borrowck/issue-27282-reborrow-ref-mut-in-guard.rs rename to src/test/ui/issues/issue-27282-reborrow-ref-mut-in-guard.rs diff --git a/src/test/ui/borrowck/issue-27282-reborrow-ref-mut-in-guard.stderr b/src/test/ui/issues/issue-27282-reborrow-ref-mut-in-guard.stderr similarity index 100% rename from src/test/ui/borrowck/issue-27282-reborrow-ref-mut-in-guard.stderr rename to src/test/ui/issues/issue-27282-reborrow-ref-mut-in-guard.stderr diff --git a/src/test/ui/consts/issue-27890.rs b/src/test/ui/issues/issue-27890.rs similarity index 100% rename from src/test/ui/consts/issue-27890.rs rename to src/test/ui/issues/issue-27890.rs diff --git a/src/test/ui/consts/issue-28113.rs b/src/test/ui/issues/issue-28113.rs similarity index 100% rename from src/test/ui/consts/issue-28113.rs rename to src/test/ui/issues/issue-28113.rs diff --git a/src/test/ui/consts/issue-28113.stderr b/src/test/ui/issues/issue-28113.stderr similarity index 100% rename from src/test/ui/consts/issue-28113.stderr rename to src/test/ui/issues/issue-28113.stderr diff --git a/src/test/ui/issues/issue-28324.rs b/src/test/ui/issues/issue-28324.rs index f74726e8166dc..bb48508a4a438 100644 --- a/src/test/ui/issues/issue-28324.rs +++ b/src/test/ui/issues/issue-28324.rs @@ -1,4 +1,4 @@ -extern "C" { +extern { static error_message_count: u32; } diff --git a/src/test/ui/issues/issue-28472.rs b/src/test/ui/issues/issue-28472.rs index 6db1f9a5bddf9..17d74ea0cf41d 100644 --- a/src/test/ui/issues/issue-28472.rs +++ b/src/test/ui/issues/issue-28472.rs @@ -1,6 +1,6 @@ // Check that the visibility modifier is included in the span of foreign items. -extern "C" { +extern { fn foo(); pub //~ ERROR the name `foo` is defined multiple times diff --git a/src/test/ui/dropck/issue-28498-ugeh-with-lifetime-param.rs b/src/test/ui/issues/issue-28498-ugeh-with-lifetime-param.rs similarity index 100% rename from src/test/ui/dropck/issue-28498-ugeh-with-lifetime-param.rs rename to src/test/ui/issues/issue-28498-ugeh-with-lifetime-param.rs diff --git a/src/test/ui/dropck/issue-28498-ugeh-with-trait-bound.rs b/src/test/ui/issues/issue-28498-ugeh-with-trait-bound.rs similarity index 100% rename from src/test/ui/dropck/issue-28498-ugeh-with-trait-bound.rs rename to src/test/ui/issues/issue-28498-ugeh-with-trait-bound.rs diff --git a/src/test/ui/issues/issue-28600.rs b/src/test/ui/issues/issue-28600.rs index 52db0d5fd84a9..297519b9a79e2 100644 --- a/src/test/ui/issues/issue-28600.rs +++ b/src/test/ui/issues/issue-28600.rs @@ -7,7 +7,7 @@ impl Test { #[allow(dead_code)] #[allow(unused_variables)] #[allow(improper_ctypes_definitions)] - pub extern "C" fn test(val: &str) { + pub extern fn test(val: &str) { } } diff --git a/src/test/ui/abi/issue-28676.rs b/src/test/ui/issues/issue-28676.rs similarity index 57% rename from src/test/ui/abi/issue-28676.rs rename to src/test/ui/issues/issue-28676.rs index 347a840296ddd..2b83478ca6115 100644 --- a/src/test/ui/abi/issue-28676.rs +++ b/src/test/ui/issues/issue-28676.rs @@ -5,32 +5,27 @@ // ignore-wasm32-bare no libc to test ffi with #[derive(Copy, Clone)] -pub struct Quad { - a: u64, - b: u64, - c: u64, - d: u64, -} +pub struct Quad { a: u64, b: u64, c: u64, d: u64 } mod rustrt { use super::Quad; #[link(name = "rust_test_helpers", kind = "static")] - extern "C" { - pub fn get_c_many_params( - _: *const (), - _: *const (), - _: *const (), - _: *const (), - f: Quad, - ) -> u64; + extern { + pub fn get_c_many_params(_: *const (), _: *const (), + _: *const (), _: *const (), f: Quad) -> u64; } } fn test() { unsafe { let null = std::ptr::null(); - let q = Quad { a: 1, b: 2, c: 3, d: 4 }; + let q = Quad { + a: 1, + b: 2, + c: 3, + d: 4 + }; assert_eq!(rustrt::get_c_many_params(null, null, null, null, q), q.c); } } diff --git a/src/test/ui/binop/issue-28837.rs b/src/test/ui/issues/issue-28837.rs similarity index 100% rename from src/test/ui/binop/issue-28837.rs rename to src/test/ui/issues/issue-28837.rs diff --git a/src/test/ui/binop/issue-28837.stderr b/src/test/ui/issues/issue-28837.stderr similarity index 100% rename from src/test/ui/binop/issue-28837.stderr rename to src/test/ui/issues/issue-28837.stderr diff --git a/src/test/ui/regions/issue-28848.nll.stderr b/src/test/ui/issues/issue-28848.nll.stderr similarity index 100% rename from src/test/ui/regions/issue-28848.nll.stderr rename to src/test/ui/issues/issue-28848.nll.stderr diff --git a/src/test/ui/regions/issue-28848.rs b/src/test/ui/issues/issue-28848.rs similarity index 100% rename from src/test/ui/regions/issue-28848.rs rename to src/test/ui/issues/issue-28848.rs diff --git a/src/test/ui/regions/issue-28848.stderr b/src/test/ui/issues/issue-28848.stderr similarity index 100% rename from src/test/ui/regions/issue-28848.stderr rename to src/test/ui/issues/issue-28848.stderr diff --git a/src/test/ui/privacy/issue-29161.rs b/src/test/ui/issues/issue-29161.rs similarity index 100% rename from src/test/ui/privacy/issue-29161.rs rename to src/test/ui/issues/issue-29161.rs diff --git a/src/test/ui/privacy/issue-29161.stderr b/src/test/ui/issues/issue-29161.stderr similarity index 100% rename from src/test/ui/privacy/issue-29161.stderr rename to src/test/ui/issues/issue-29161.stderr diff --git a/src/test/ui/generics/issue-2936.rs b/src/test/ui/issues/issue-2936.rs similarity index 100% rename from src/test/ui/generics/issue-2936.rs rename to src/test/ui/issues/issue-2936.rs diff --git a/src/test/ui/dropck/issue-29844.rs b/src/test/ui/issues/issue-29844.rs similarity index 100% rename from src/test/ui/dropck/issue-29844.rs rename to src/test/ui/issues/issue-29844.rs diff --git a/src/test/ui/consts/issue-29914-2.rs b/src/test/ui/issues/issue-29914-2.rs similarity index 100% rename from src/test/ui/consts/issue-29914-2.rs rename to src/test/ui/issues/issue-29914-2.rs diff --git a/src/test/ui/consts/issue-29914-3.rs b/src/test/ui/issues/issue-29914-3.rs similarity index 100% rename from src/test/ui/consts/issue-29914-3.rs rename to src/test/ui/issues/issue-29914-3.rs diff --git a/src/test/ui/consts/issue-29914.rs b/src/test/ui/issues/issue-29914.rs similarity index 100% rename from src/test/ui/consts/issue-29914.rs rename to src/test/ui/issues/issue-29914.rs diff --git a/src/test/ui/consts/issue-29927-1.rs b/src/test/ui/issues/issue-29927-1.rs similarity index 100% rename from src/test/ui/consts/issue-29927-1.rs rename to src/test/ui/issues/issue-29927-1.rs diff --git a/src/test/ui/consts/issue-29927.rs b/src/test/ui/issues/issue-29927.rs similarity index 100% rename from src/test/ui/consts/issue-29927.rs rename to src/test/ui/issues/issue-29927.rs diff --git a/src/test/ui/drop/issue-30018-nopanic.rs b/src/test/ui/issues/issue-30018-nopanic.rs similarity index 100% rename from src/test/ui/drop/issue-30018-nopanic.rs rename to src/test/ui/issues/issue-30018-nopanic.rs diff --git a/src/test/ui/privacy/issue-30079.rs b/src/test/ui/issues/issue-30079.rs similarity index 100% rename from src/test/ui/privacy/issue-30079.rs rename to src/test/ui/issues/issue-30079.rs diff --git a/src/test/ui/privacy/issue-30079.stderr b/src/test/ui/issues/issue-30079.stderr similarity index 100% rename from src/test/ui/privacy/issue-30079.stderr rename to src/test/ui/issues/issue-30079.stderr diff --git a/src/test/ui/lint/issue-30302.rs b/src/test/ui/issues/issue-30302.rs similarity index 100% rename from src/test/ui/lint/issue-30302.rs rename to src/test/ui/issues/issue-30302.rs diff --git a/src/test/ui/lint/issue-30302.stderr b/src/test/ui/issues/issue-30302.stderr similarity index 100% rename from src/test/ui/lint/issue-30302.stderr rename to src/test/ui/issues/issue-30302.stderr diff --git a/src/test/ui/issues/issue-3044.stderr b/src/test/ui/issues/issue-3044.stderr index b93aeade95e42..d2c010659edd0 100644 --- a/src/test/ui/issues/issue-3044.stderr +++ b/src/test/ui/issues/issue-3044.stderr @@ -7,12 +7,6 @@ LL | needlesArr.iter().fold(|x, y| { | | expected 2 arguments LL | | }); | |_____- supplied 1 argument - | -note: associated function defined here - --> $SRC_DIR/core/src/iter/traits/iterator.rs:LL:COL - | -LL | fn fold(mut self, init: B, mut f: F) -> B - | ^^^^ error: aborting due to previous error diff --git a/src/test/ui/imports/issue-32119.rs b/src/test/ui/issues/issue-32119.rs similarity index 100% rename from src/test/ui/imports/issue-32119.rs rename to src/test/ui/issues/issue-32119.rs diff --git a/src/test/ui/issues/issue-3214.rs b/src/test/ui/issues/issue-3214.rs index 9bb164f1ddd2d..030677c879fb5 100644 --- a/src/test/ui/issues/issue-3214.rs +++ b/src/test/ui/issues/issue-3214.rs @@ -6,7 +6,7 @@ fn foo() { } impl Drop for Foo { - //~^ ERROR this struct takes 0 type arguments but 1 type argument was supplied + //~^ ERROR wrong number of type arguments //~| ERROR the type parameter `T` is not constrained by the impl trait, self type, or predicates fn drop(&mut self) {} } diff --git a/src/test/ui/issues/issue-3214.stderr b/src/test/ui/issues/issue-3214.stderr index c2268924bc4e9..30bc6cb115ffc 100644 --- a/src/test/ui/issues/issue-3214.stderr +++ b/src/test/ui/issues/issue-3214.stderr @@ -9,19 +9,11 @@ LL | struct Foo { LL | x: T, | ^ use of generic parameter from outer function -error[E0107]: this struct takes 0 type arguments but 1 type argument was supplied - --> $DIR/issue-3214.rs:8:22 +error[E0107]: wrong number of type arguments: expected 0, found 1 + --> $DIR/issue-3214.rs:8:26 | LL | impl Drop for Foo { - | ^^^--- help: remove these generics - | | - | expected 0 type arguments - | -note: struct defined here, with 0 type parameters - --> $DIR/issue-3214.rs:4:12 - | -LL | struct Foo { - | ^^^ + | ^ unexpected type argument error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates --> $DIR/issue-3214.rs:8:10 diff --git a/src/test/ui/issues/issue-32201.rs b/src/test/ui/issues/issue-32201.rs index f27bb1c2eb5b6..e22c160416517 100644 --- a/src/test/ui/issues/issue-32201.rs +++ b/src/test/ui/issues/issue-32201.rs @@ -1,4 +1,4 @@ -extern "C" { +extern { fn foo(a: i32, ...); } diff --git a/src/test/ui/imports/issue-32222.rs b/src/test/ui/issues/issue-32222.rs similarity index 100% rename from src/test/ui/imports/issue-32222.rs rename to src/test/ui/issues/issue-32222.rs diff --git a/src/test/ui/consts/issue-32829-2.rs b/src/test/ui/issues/issue-32829-2.rs similarity index 100% rename from src/test/ui/consts/issue-32829-2.rs rename to src/test/ui/issues/issue-32829-2.rs diff --git a/src/test/ui/consts/issue-32829-2.stderr b/src/test/ui/issues/issue-32829-2.stderr similarity index 100% rename from src/test/ui/consts/issue-32829-2.stderr rename to src/test/ui/issues/issue-32829-2.stderr diff --git a/src/test/ui/parser/issue-34222-1.rs b/src/test/ui/issues/issue-34222-1.rs similarity index 100% rename from src/test/ui/parser/issue-34222-1.rs rename to src/test/ui/issues/issue-34222-1.rs diff --git a/src/test/ui/parser/issue-34222-1.stderr b/src/test/ui/issues/issue-34222-1.stderr similarity index 100% rename from src/test/ui/parser/issue-34222-1.stderr rename to src/test/ui/issues/issue-34222-1.stderr diff --git a/src/test/ui/lint/issue-34798.rs b/src/test/ui/issues/issue-34798.rs similarity index 100% rename from src/test/ui/lint/issue-34798.rs rename to src/test/ui/issues/issue-34798.rs diff --git a/src/test/ui/consts/issue-36163.rs b/src/test/ui/issues/issue-36163.rs similarity index 100% rename from src/test/ui/consts/issue-36163.rs rename to src/test/ui/issues/issue-36163.rs diff --git a/src/test/ui/consts/issue-36163.stderr b/src/test/ui/issues/issue-36163.stderr similarity index 100% rename from src/test/ui/consts/issue-36163.stderr rename to src/test/ui/issues/issue-36163.stderr diff --git a/src/test/ui/issues/issue-3656.rs b/src/test/ui/issues/issue-3656.rs index 4a9f94306d5b8..17ff6b9f9f40c 100644 --- a/src/test/ui/issues/issue-3656.rs +++ b/src/test/ui/issues/issue-3656.rs @@ -1,12 +1,14 @@ // run-pass #![allow(dead_code)] #![allow(improper_ctypes)] + // Issue #3656 // Incorrect struct size computation in the FFI, because of not taking // the alignment of elements into account. // pretty-expanded FIXME #23616 // ignore-wasm32-bare no libc to test with + #![feature(rustc_private)] extern crate libc; @@ -19,9 +21,10 @@ pub struct KEYGEN { salt_size: u32, } -extern "C" { +extern { // Bogus signature, just need to test if it compiles. pub fn malloc(data: KEYGEN); } -pub fn main() {} +pub fn main() { +} diff --git a/src/test/ui/autoref-autoderef/issue-38940.rs b/src/test/ui/issues/issue-38940.rs similarity index 100% rename from src/test/ui/autoref-autoderef/issue-38940.rs rename to src/test/ui/issues/issue-38940.rs diff --git a/src/test/ui/autoref-autoderef/issue-38940.stderr b/src/test/ui/issues/issue-38940.stderr similarity index 100% rename from src/test/ui/autoref-autoderef/issue-38940.stderr rename to src/test/ui/issues/issue-38940.stderr diff --git a/src/test/ui/macros/issue-40469.rs b/src/test/ui/issues/issue-40469.rs similarity index 100% rename from src/test/ui/macros/issue-40469.rs rename to src/test/ui/issues/issue-40469.rs diff --git a/src/test/ui/macros/issue-41803.rs b/src/test/ui/issues/issue-41803.rs similarity index 100% rename from src/test/ui/macros/issue-41803.rs rename to src/test/ui/issues/issue-41803.rs diff --git a/src/test/ui/consts/issue-43105.rs b/src/test/ui/issues/issue-43105.rs similarity index 100% rename from src/test/ui/consts/issue-43105.rs rename to src/test/ui/issues/issue-43105.rs diff --git a/src/test/ui/consts/issue-43105.stderr b/src/test/ui/issues/issue-43105.stderr similarity index 100% rename from src/test/ui/consts/issue-43105.stderr rename to src/test/ui/issues/issue-43105.stderr diff --git a/src/test/ui/parser/issue-43196.rs b/src/test/ui/issues/issue-43196.rs similarity index 100% rename from src/test/ui/parser/issue-43196.rs rename to src/test/ui/issues/issue-43196.rs diff --git a/src/test/ui/parser/issue-43196.stderr b/src/test/ui/issues/issue-43196.stderr similarity index 100% rename from src/test/ui/parser/issue-43196.stderr rename to src/test/ui/issues/issue-43196.stderr diff --git a/src/test/ui/enum-discriminant/issue-43398.rs b/src/test/ui/issues/issue-43398.rs similarity index 100% rename from src/test/ui/enum-discriminant/issue-43398.rs rename to src/test/ui/issues/issue-43398.rs diff --git a/src/test/ui/enum-discriminant/issue-43398.stderr b/src/test/ui/issues/issue-43398.stderr similarity index 100% rename from src/test/ui/enum-discriminant/issue-43398.stderr rename to src/test/ui/issues/issue-43398.stderr diff --git a/src/test/ui/issues/issue-43925.rs b/src/test/ui/issues/issue-43925.rs index 73d1792825117..1f3bee38e8cbc 100644 --- a/src/test/ui/issues/issue-43925.rs +++ b/src/test/ui/issues/issue-43925.rs @@ -1,4 +1,4 @@ -#[link(name = "foo", cfg("rlib"))] //~ ERROR invalid argument for `cfg(..)` -extern "C" {} +#[link(name="foo", cfg("rlib"))] //~ ERROR invalid argument for `cfg(..)` +extern {} fn main() {} diff --git a/src/test/ui/issues/issue-43925.stderr b/src/test/ui/issues/issue-43925.stderr index 7bf64dc693c5e..739ace10aa6ab 100644 --- a/src/test/ui/issues/issue-43925.stderr +++ b/src/test/ui/issues/issue-43925.stderr @@ -1,8 +1,8 @@ error: invalid argument for `cfg(..)` - --> $DIR/issue-43925.rs:1:26 + --> $DIR/issue-43925.rs:1:24 | -LL | #[link(name = "foo", cfg("rlib"))] - | ^^^^^^ +LL | #[link(name="foo", cfg("rlib"))] + | ^^^^^^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-43926.rs b/src/test/ui/issues/issue-43926.rs index 0171c12b1cc4e..c56a796187a2a 100644 --- a/src/test/ui/issues/issue-43926.rs +++ b/src/test/ui/issues/issue-43926.rs @@ -1,4 +1,4 @@ -#[link(name = "foo", cfg())] //~ ERROR `cfg()` must have an argument -extern "C" {} +#[link(name="foo", cfg())] //~ ERROR `cfg()` must have an argument +extern {} fn main() {} diff --git a/src/test/ui/issues/issue-43926.stderr b/src/test/ui/issues/issue-43926.stderr index d83e9bd7ed464..d9d6b3a34fe2e 100644 --- a/src/test/ui/issues/issue-43926.stderr +++ b/src/test/ui/issues/issue-43926.stderr @@ -1,8 +1,8 @@ error: `cfg()` must have an argument - --> $DIR/issue-43926.rs:1:22 + --> $DIR/issue-43926.rs:1:20 | -LL | #[link(name = "foo", cfg())] - | ^^^^^ +LL | #[link(name="foo", cfg())] + | ^^^^^ error: aborting due to previous error diff --git a/src/test/ui/parser/issue-44021.rs b/src/test/ui/issues/issue-44021.rs similarity index 100% rename from src/test/ui/parser/issue-44021.rs rename to src/test/ui/issues/issue-44021.rs diff --git a/src/test/ui/parser/issue-44021.stderr b/src/test/ui/issues/issue-44021.stderr similarity index 100% rename from src/test/ui/parser/issue-44021.stderr rename to src/test/ui/issues/issue-44021.stderr diff --git a/src/test/ui/unsafe/issue-45087-unreachable-unsafe.rs b/src/test/ui/issues/issue-45087-unreachable-unsafe.rs similarity index 100% rename from src/test/ui/unsafe/issue-45087-unreachable-unsafe.rs rename to src/test/ui/issues/issue-45087-unreachable-unsafe.rs diff --git a/src/test/ui/unsafe/issue-45087-unreachable-unsafe.stderr b/src/test/ui/issues/issue-45087-unreachable-unsafe.stderr similarity index 100% rename from src/test/ui/unsafe/issue-45087-unreachable-unsafe.stderr rename to src/test/ui/issues/issue-45087-unreachable-unsafe.stderr diff --git a/src/test/ui/borrowck/issue-45199.rs b/src/test/ui/issues/issue-45199.rs similarity index 100% rename from src/test/ui/borrowck/issue-45199.rs rename to src/test/ui/issues/issue-45199.rs diff --git a/src/test/ui/borrowck/issue-45199.stderr b/src/test/ui/issues/issue-45199.stderr similarity index 100% rename from src/test/ui/borrowck/issue-45199.stderr rename to src/test/ui/issues/issue-45199.stderr diff --git a/src/test/ui/parser/issue-45296.rs b/src/test/ui/issues/issue-45296.rs similarity index 100% rename from src/test/ui/parser/issue-45296.rs rename to src/test/ui/issues/issue-45296.rs diff --git a/src/test/ui/parser/issue-45296.stderr b/src/test/ui/issues/issue-45296.stderr similarity index 100% rename from src/test/ui/parser/issue-45296.stderr rename to src/test/ui/issues/issue-45296.stderr diff --git a/src/test/ui/nll/issue-45696-long-live-borrows-in-boxes.rs b/src/test/ui/issues/issue-45696-long-live-borrows-in-boxes.rs similarity index 100% rename from src/test/ui/nll/issue-45696-long-live-borrows-in-boxes.rs rename to src/test/ui/issues/issue-45696-long-live-borrows-in-boxes.rs diff --git a/src/test/ui/parser/issue-46186.fixed b/src/test/ui/issues/issue-46186.fixed similarity index 100% rename from src/test/ui/parser/issue-46186.fixed rename to src/test/ui/issues/issue-46186.fixed diff --git a/src/test/ui/parser/issue-46186.rs b/src/test/ui/issues/issue-46186.rs similarity index 100% rename from src/test/ui/parser/issue-46186.rs rename to src/test/ui/issues/issue-46186.rs diff --git a/src/test/ui/parser/issue-46186.stderr b/src/test/ui/issues/issue-46186.stderr similarity index 100% rename from src/test/ui/parser/issue-46186.stderr rename to src/test/ui/issues/issue-46186.stderr diff --git a/src/test/ui/borrowck/issue-46471.rs b/src/test/ui/issues/issue-46471.rs similarity index 100% rename from src/test/ui/borrowck/issue-46471.rs rename to src/test/ui/issues/issue-46471.rs diff --git a/src/test/ui/borrowck/issue-46471.stderr b/src/test/ui/issues/issue-46471.stderr similarity index 100% rename from src/test/ui/borrowck/issue-46471.stderr rename to src/test/ui/issues/issue-46471.stderr diff --git a/src/test/ui/consts/issue-47789.rs b/src/test/ui/issues/issue-47789.rs similarity index 100% rename from src/test/ui/consts/issue-47789.rs rename to src/test/ui/issues/issue-47789.rs diff --git a/src/test/ui/associated-types/issue-48551.rs b/src/test/ui/issues/issue-48551.rs similarity index 100% rename from src/test/ui/associated-types/issue-48551.rs rename to src/test/ui/issues/issue-48551.rs diff --git a/src/test/ui/associated-types/issue-50301.rs b/src/test/ui/issues/issue-50301.rs similarity index 100% rename from src/test/ui/associated-types/issue-50301.rs rename to src/test/ui/issues/issue-50301.rs diff --git a/src/test/ui/macros/issue-5060.rs b/src/test/ui/issues/issue-5060.rs similarity index 100% rename from src/test/ui/macros/issue-5060.rs rename to src/test/ui/issues/issue-5060.rs diff --git a/src/test/ui/nll/issue-51345-2.rs b/src/test/ui/issues/issue-51345-2.rs similarity index 100% rename from src/test/ui/nll/issue-51345-2.rs rename to src/test/ui/issues/issue-51345-2.rs diff --git a/src/test/ui/parser/issue-51602.rs b/src/test/ui/issues/issue-51602.rs similarity index 100% rename from src/test/ui/parser/issue-51602.rs rename to src/test/ui/issues/issue-51602.rs diff --git a/src/test/ui/parser/issue-51602.stderr b/src/test/ui/issues/issue-51602.stderr similarity index 100% rename from src/test/ui/parser/issue-51602.stderr rename to src/test/ui/issues/issue-51602.stderr diff --git a/src/test/ui/nll/issue-51770.rs b/src/test/ui/issues/issue-51770.rs similarity index 100% rename from src/test/ui/nll/issue-51770.rs rename to src/test/ui/issues/issue-51770.rs diff --git a/src/test/ui/issues/issue-51907.rs b/src/test/ui/issues/issue-51907.rs index 9378f4357134b..52d26d0954af8 100644 --- a/src/test/ui/issues/issue-51907.rs +++ b/src/test/ui/issues/issue-51907.rs @@ -1,15 +1,15 @@ // run-pass trait Foo { - extern "C" fn borrow(&self); - extern "C" fn take(self: Box); + extern fn borrow(&self); + extern fn take(self: Box); } struct Bar; impl Foo for Bar { #[allow(improper_ctypes_definitions)] - extern "C" fn borrow(&self) {} + extern fn borrow(&self) {} #[allow(improper_ctypes_definitions)] - extern "C" fn take(self: Box) {} + extern fn take(self: Box) {} } fn main() { diff --git a/src/test/ui/consts/issue-52023-array-size-pointer-cast.rs b/src/test/ui/issues/issue-52023-array-size-pointer-cast.rs similarity index 100% rename from src/test/ui/consts/issue-52023-array-size-pointer-cast.rs rename to src/test/ui/issues/issue-52023-array-size-pointer-cast.rs diff --git a/src/test/ui/consts/issue-52023-array-size-pointer-cast.stderr b/src/test/ui/issues/issue-52023-array-size-pointer-cast.stderr similarity index 100% rename from src/test/ui/consts/issue-52023-array-size-pointer-cast.stderr rename to src/test/ui/issues/issue-52023-array-size-pointer-cast.stderr diff --git a/src/test/ui/regions/issue-5243.rs b/src/test/ui/issues/issue-5243.rs similarity index 100% rename from src/test/ui/regions/issue-5243.rs rename to src/test/ui/issues/issue-5243.rs diff --git a/src/test/ui/parser/issue-52496.rs b/src/test/ui/issues/issue-52496.rs similarity index 100% rename from src/test/ui/parser/issue-52496.rs rename to src/test/ui/issues/issue-52496.rs diff --git a/src/test/ui/parser/issue-52496.stderr b/src/test/ui/issues/issue-52496.stderr similarity index 100% rename from src/test/ui/parser/issue-52496.stderr rename to src/test/ui/issues/issue-52496.stderr diff --git a/src/test/ui/issues/issue-53251.rs b/src/test/ui/issues/issue-53251.rs index 309b9800b7d37..b5d55141b7509 100644 --- a/src/test/ui/issues/issue-53251.rs +++ b/src/test/ui/issues/issue-53251.rs @@ -1,5 +1,3 @@ -// ignore-tidy-linelength - struct S; impl S { @@ -11,8 +9,8 @@ macro_rules! impl_add { $( fn $n() { S::f::(); - //~^ ERROR this associated function takes 0 type arguments but 1 type argument was supplied - //~| ERROR this associated function takes 0 type arguments but 1 type argument was supplied + //~^ ERROR wrong number of type arguments + //~| ERROR wrong number of type arguments } )* } @@ -20,4 +18,4 @@ macro_rules! impl_add { impl_add!(a b); -fn main() { } +fn main() {} diff --git a/src/test/ui/issues/issue-53251.stderr b/src/test/ui/issues/issue-53251.stderr index 5d1a6d4a522f6..cd5030f761987 100644 --- a/src/test/ui/issues/issue-53251.stderr +++ b/src/test/ui/issues/issue-53251.stderr @@ -1,37 +1,23 @@ -error[E0107]: this associated function takes 0 type arguments but 1 type argument was supplied - --> $DIR/issue-53251.rs:13:20 +error[E0107]: wrong number of type arguments: expected 0, found 1 + --> $DIR/issue-53251.rs:11:24 | LL | S::f::(); - | ^------- help: remove these generics - | | - | expected 0 type arguments + | ^^^ unexpected type argument ... LL | impl_add!(a b); | --------------- in this macro invocation | -note: associated function defined here, with 0 type parameters - --> $DIR/issue-53251.rs:6:8 - | -LL | fn f() {} - | ^ = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0107]: this associated function takes 0 type arguments but 1 type argument was supplied - --> $DIR/issue-53251.rs:13:20 +error[E0107]: wrong number of type arguments: expected 0, found 1 + --> $DIR/issue-53251.rs:11:24 | LL | S::f::(); - | ^------- help: remove these generics - | | - | expected 0 type arguments + | ^^^ unexpected type argument ... LL | impl_add!(a b); | --------------- in this macro invocation | -note: associated function defined here, with 0 type parameters - --> $DIR/issue-53251.rs:6:8 - | -LL | fn f() {} - | ^ = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/src/test/ui/nll/issue-54943-3.rs b/src/test/ui/issues/issue-54943-3.rs similarity index 100% rename from src/test/ui/nll/issue-54943-3.rs rename to src/test/ui/issues/issue-54943-3.rs diff --git a/src/test/ui/nll/issue-55511.rs b/src/test/ui/issues/issue-55511.rs similarity index 100% rename from src/test/ui/nll/issue-55511.rs rename to src/test/ui/issues/issue-55511.rs diff --git a/src/test/ui/nll/issue-55511.stderr b/src/test/ui/issues/issue-55511.stderr similarity index 100% rename from src/test/ui/nll/issue-55511.stderr rename to src/test/ui/issues/issue-55511.stderr diff --git a/src/test/ui/issues/issue-57843.stderr b/src/test/ui/issues/issue-57843.stderr index 7699e97da99ad..01edb9507a3a7 100644 --- a/src/test/ui/issues/issue-57843.stderr +++ b/src/test/ui/issues/issue-57843.stderr @@ -6,11 +6,6 @@ LL | Foo(Box::new(|_| ())); | = note: expected type `FnOnce<(&'a bool,)>` found type `FnOnce<(&bool,)>` -note: this closure does not fulfill the lifetime requirements - --> $DIR/issue-57843.rs:23:18 - | -LL | Foo(Box::new(|_| ())); - | ^^^^^^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-5791.rs b/src/test/ui/issues/issue-5791.rs index 3544160f094e5..d9be27250cdea 100644 --- a/src/test/ui/issues/issue-5791.rs +++ b/src/test/ui/issues/issue-5791.rs @@ -3,7 +3,7 @@ #![warn(clashing_extern_declarations)] // pretty-expanded FIXME #23616 -extern "C" { +extern { #[link_name = "malloc"] fn malloc1(len: i32) -> *const u8; #[link_name = "malloc"] @@ -11,4 +11,4 @@ extern "C" { fn malloc2(len: i32, foo: i32) -> *const u8; } -pub fn main() {} +pub fn main () {} diff --git a/src/test/ui/consts/issue-58435-ice-with-assoc-const.rs b/src/test/ui/issues/issue-58435-ice-with-assoc-const.rs similarity index 100% rename from src/test/ui/consts/issue-58435-ice-with-assoc-const.rs rename to src/test/ui/issues/issue-58435-ice-with-assoc-const.rs diff --git a/src/test/ui/parser/issue-58856-2.rs b/src/test/ui/issues/issue-58856-2.rs similarity index 100% rename from src/test/ui/parser/issue-58856-2.rs rename to src/test/ui/issues/issue-58856-2.rs diff --git a/src/test/ui/parser/issue-58856-2.stderr b/src/test/ui/issues/issue-58856-2.stderr similarity index 100% rename from src/test/ui/parser/issue-58856-2.stderr rename to src/test/ui/issues/issue-58856-2.stderr diff --git a/src/test/ui/parser/issue-60075.rs b/src/test/ui/issues/issue-60075.rs similarity index 100% rename from src/test/ui/parser/issue-60075.rs rename to src/test/ui/issues/issue-60075.rs diff --git a/src/test/ui/parser/issue-60075.stderr b/src/test/ui/issues/issue-60075.stderr similarity index 100% rename from src/test/ui/parser/issue-60075.stderr rename to src/test/ui/issues/issue-60075.stderr diff --git a/src/test/ui/issues/issue-60622.rs b/src/test/ui/issues/issue-60622.rs index 1d9bd2dd2dc1c..d6a0189c3e042 100644 --- a/src/test/ui/issues/issue-60622.rs +++ b/src/test/ui/issues/issue-60622.rs @@ -11,8 +11,8 @@ impl Borked { fn run_wild(b: &Borked) { b.a::<'_, T>(); //~^ ERROR cannot specify lifetime arguments explicitly if late bound lifetime parameters are present - //~| ERROR this associated function takes 0 type arguments but 1 type argument was supplied - //~| WARN this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + //~^^ ERROR wrong number of type arguments: expected 0, found 1 + //~^^^ WARN this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! } fn main() {} diff --git a/src/test/ui/issues/issue-60622.stderr b/src/test/ui/issues/issue-60622.stderr index 47f2f181f2d7a..79cb6cfc35494 100644 --- a/src/test/ui/issues/issue-60622.stderr +++ b/src/test/ui/issues/issue-60622.stderr @@ -16,19 +16,11 @@ LL | #![deny(warnings)] = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #42868 -error[E0107]: this associated function takes 0 type arguments but 1 type argument was supplied - --> $DIR/issue-60622.rs:12:7 +error[E0107]: wrong number of type arguments: expected 0, found 1 + --> $DIR/issue-60622.rs:12:15 | LL | b.a::<'_, T>(); - | ^ --- help: remove this type argument - | | - | expected 0 type arguments - | -note: associated function defined here, with 0 type parameters - --> $DIR/issue-60622.rs:8:8 - | -LL | fn a(&self) {} - | ^ + | ^ unexpected type argument error: aborting due to 2 previous errors diff --git a/src/test/ui/parser/issue-62554.rs b/src/test/ui/issues/issue-62554.rs similarity index 100% rename from src/test/ui/parser/issue-62554.rs rename to src/test/ui/issues/issue-62554.rs diff --git a/src/test/ui/parser/issue-62554.stderr b/src/test/ui/issues/issue-62554.stderr similarity index 100% rename from src/test/ui/parser/issue-62554.stderr rename to src/test/ui/issues/issue-62554.stderr diff --git a/src/test/ui/traits/issue-6334.rs b/src/test/ui/issues/issue-6334.rs similarity index 100% rename from src/test/ui/traits/issue-6334.rs rename to src/test/ui/issues/issue-6334.rs diff --git a/src/test/ui/pattern/issue-6449.rs b/src/test/ui/issues/issue-6449.rs similarity index 100% rename from src/test/ui/pattern/issue-6449.rs rename to src/test/ui/issues/issue-6449.rs diff --git a/src/test/ui/issues/issue-6470.rs b/src/test/ui/issues/issue-6470.rs index 8c6192a59dba2..0c86a648828fa 100644 --- a/src/test/ui/issues/issue-6470.rs +++ b/src/test/ui/issues/issue-6470.rs @@ -1,6 +1,7 @@ // build-pass #![allow(dead_code)] #![allow(improper_ctypes)] + // pretty-expanded FIXME #23616 #![allow(non_snake_case)] @@ -9,9 +10,9 @@ pub mod Bar { v: isize, } - extern "C" { + extern { pub fn foo(v: *const Foo) -> Foo; } } -pub fn main() {} +pub fn main() { } diff --git a/src/test/ui/traits/issue-65673.rs b/src/test/ui/issues/issue-65673.rs similarity index 100% rename from src/test/ui/traits/issue-65673.rs rename to src/test/ui/issues/issue-65673.rs diff --git a/src/test/ui/traits/issue-65673.stderr b/src/test/ui/issues/issue-65673.stderr similarity index 100% rename from src/test/ui/traits/issue-65673.stderr rename to src/test/ui/issues/issue-65673.stderr diff --git a/src/test/ui/parser/issue-66473.rs b/src/test/ui/issues/issue-66473.rs similarity index 100% rename from src/test/ui/parser/issue-66473.rs rename to src/test/ui/issues/issue-66473.rs diff --git a/src/test/ui/parser/issue-66473.stderr b/src/test/ui/issues/issue-66473.stderr similarity index 100% rename from src/test/ui/parser/issue-66473.stderr rename to src/test/ui/issues/issue-66473.stderr diff --git a/src/test/ui/mir/issue-66851.rs b/src/test/ui/issues/issue-66851.rs similarity index 100% rename from src/test/ui/mir/issue-66851.rs rename to src/test/ui/issues/issue-66851.rs diff --git a/src/test/ui/pattern/issue-67037-pat-tup-scrut-ty-diff-less-fields.rs b/src/test/ui/issues/issue-67037-pat-tup-scrut-ty-diff-less-fields.rs similarity index 100% rename from src/test/ui/pattern/issue-67037-pat-tup-scrut-ty-diff-less-fields.rs rename to src/test/ui/issues/issue-67037-pat-tup-scrut-ty-diff-less-fields.rs diff --git a/src/test/ui/pattern/issue-67037-pat-tup-scrut-ty-diff-less-fields.stderr b/src/test/ui/issues/issue-67037-pat-tup-scrut-ty-diff-less-fields.stderr similarity index 81% rename from src/test/ui/pattern/issue-67037-pat-tup-scrut-ty-diff-less-fields.stderr rename to src/test/ui/issues/issue-67037-pat-tup-scrut-ty-diff-less-fields.stderr index 9bdbf0bf9f40d..6e8ea6bf618f2 100644 --- a/src/test/ui/pattern/issue-67037-pat-tup-scrut-ty-diff-less-fields.stderr +++ b/src/test/ui/issues/issue-67037-pat-tup-scrut-ty-diff-less-fields.stderr @@ -17,15 +17,6 @@ LL | struct P(T); // 1 type parameter wanted ... LL | let P() = U {}; | ^^^ expected 1 field, found 0 - | -help: use `_` to explicitly ignore each field - | -LL | let P(_) = U {}; - | ^ -help: use `..` to ignore all fields - | -LL | let P(..) = U {}; - | ^^ error: aborting due to 2 previous errors diff --git a/src/test/ui/consts/issue-6991.rs b/src/test/ui/issues/issue-6991.rs similarity index 100% rename from src/test/ui/consts/issue-6991.rs rename to src/test/ui/issues/issue-6991.rs diff --git a/src/test/ui/parser/issue-72253.rs b/src/test/ui/issues/issue-72253.rs similarity index 100% rename from src/test/ui/parser/issue-72253.rs rename to src/test/ui/issues/issue-72253.rs diff --git a/src/test/ui/parser/issue-72253.stderr b/src/test/ui/issues/issue-72253.stderr similarity index 100% rename from src/test/ui/parser/issue-72253.stderr rename to src/test/ui/issues/issue-72253.stderr diff --git a/src/test/ui/parser/issue-72373.rs b/src/test/ui/issues/issue-72373.rs similarity index 100% rename from src/test/ui/parser/issue-72373.rs rename to src/test/ui/issues/issue-72373.rs diff --git a/src/test/ui/parser/issue-72373.stderr b/src/test/ui/issues/issue-72373.stderr similarity index 100% rename from src/test/ui/parser/issue-72373.stderr rename to src/test/ui/issues/issue-72373.stderr diff --git a/src/test/ui/issues/issue-72574-2.stderr b/src/test/ui/issues/issue-72574-2.stderr index a1e8ec1677db5..0a9c868af7af8 100644 --- a/src/test/ui/issues/issue-72574-2.stderr +++ b/src/test/ui/issues/issue-72574-2.stderr @@ -26,11 +26,6 @@ LL | struct Binder(i32, i32, i32); ... LL | Binder(_a, _x @ ..) => {} | ^^^^^^^^^^^^^^^^^^^ expected 3 fields, found 2 - | -help: use `_` to explicitly ignore each field - | -LL | Binder(_a, _x @ .., _) => {} - | ^^^ error: aborting due to 3 previous errors diff --git a/src/test/ui/const-generics/issue-73899.rs b/src/test/ui/issues/issue-73899.rs similarity index 100% rename from src/test/ui/const-generics/issue-73899.rs rename to src/test/ui/issues/issue-73899.rs diff --git a/src/test/ui/parser/issue-75599.rs b/src/test/ui/issues/issue-75599.rs similarity index 100% rename from src/test/ui/parser/issue-75599.rs rename to src/test/ui/issues/issue-75599.rs diff --git a/src/test/ui/const-generics/issue-75763.rs b/src/test/ui/issues/issue-75763.rs similarity index 100% rename from src/test/ui/const-generics/issue-75763.rs rename to src/test/ui/issues/issue-75763.rs diff --git a/src/test/ui/async-await/issue-76547.nll.stderr b/src/test/ui/issues/issue-76547.nll.stderr similarity index 100% rename from src/test/ui/async-await/issue-76547.nll.stderr rename to src/test/ui/issues/issue-76547.nll.stderr diff --git a/src/test/ui/async-await/issue-76547.rs b/src/test/ui/issues/issue-76547.rs similarity index 100% rename from src/test/ui/async-await/issue-76547.rs rename to src/test/ui/issues/issue-76547.rs diff --git a/src/test/ui/async-await/issue-76547.stderr b/src/test/ui/issues/issue-76547.stderr similarity index 100% rename from src/test/ui/async-await/issue-76547.stderr rename to src/test/ui/issues/issue-76547.stderr diff --git a/src/test/ui/numbers-arithmetic/issue-8460-const.noopt.stderr b/src/test/ui/issues/issue-8460-const.noopt.stderr similarity index 100% rename from src/test/ui/numbers-arithmetic/issue-8460-const.noopt.stderr rename to src/test/ui/issues/issue-8460-const.noopt.stderr diff --git a/src/test/ui/numbers-arithmetic/issue-8460-const.opt.stderr b/src/test/ui/issues/issue-8460-const.opt.stderr similarity index 100% rename from src/test/ui/numbers-arithmetic/issue-8460-const.opt.stderr rename to src/test/ui/issues/issue-8460-const.opt.stderr diff --git a/src/test/ui/numbers-arithmetic/issue-8460-const.opt_with_overflow_checks.stderr b/src/test/ui/issues/issue-8460-const.opt_with_overflow_checks.stderr similarity index 100% rename from src/test/ui/numbers-arithmetic/issue-8460-const.opt_with_overflow_checks.stderr rename to src/test/ui/issues/issue-8460-const.opt_with_overflow_checks.stderr diff --git a/src/test/ui/numbers-arithmetic/issue-8460-const.rs b/src/test/ui/issues/issue-8460-const.rs similarity index 100% rename from src/test/ui/numbers-arithmetic/issue-8460-const.rs rename to src/test/ui/issues/issue-8460-const.rs diff --git a/src/test/ui/numbers-arithmetic/issue-8460.rs b/src/test/ui/issues/issue-8460.rs similarity index 100% rename from src/test/ui/numbers-arithmetic/issue-8460.rs rename to src/test/ui/issues/issue-8460.rs diff --git a/src/test/ui/traits/issue-9394-inherited-trait-calls.rs b/src/test/ui/issues/issue-9394-inherited-trait-calls.rs similarity index 100% rename from src/test/ui/traits/issue-9394-inherited-trait-calls.rs rename to src/test/ui/issues/issue-9394-inherited-trait-calls.rs diff --git a/src/test/ui/parser/lifetime_starts_expressions.rs b/src/test/ui/lifetime_starts_expressions.rs similarity index 100% rename from src/test/ui/parser/lifetime_starts_expressions.rs rename to src/test/ui/lifetime_starts_expressions.rs diff --git a/src/test/ui/parser/lifetime_starts_expressions.stderr b/src/test/ui/lifetime_starts_expressions.stderr similarity index 100% rename from src/test/ui/parser/lifetime_starts_expressions.stderr rename to src/test/ui/lifetime_starts_expressions.stderr diff --git a/src/test/ui/lifetimes/issue-79187-2.nll.stderr b/src/test/ui/lifetimes/issue-79187-2.nll.stderr deleted file mode 100644 index 4970c579e7b98..0000000000000 --- a/src/test/ui/lifetimes/issue-79187-2.nll.stderr +++ /dev/null @@ -1,44 +0,0 @@ -error: lifetime may not live long enough - --> $DIR/issue-79187-2.rs:9:24 - | -LL | take_foo(|a: &i32| a); - | - - ^ returning this value requires that `'1` must outlive `'2` - | | | - | | return type of closure is &'2 i32 - | let's call the lifetime of this reference `'1` - -error: lifetime may not live long enough - --> $DIR/issue-79187-2.rs:10:34 - | -LL | take_foo(|a: &i32| -> &i32 { a }); - | - - ^ returning this value requires that `'1` must outlive `'2` - | | | - | | let's call the lifetime of this reference `'2` - | let's call the lifetime of this reference `'1` - -error: higher-ranked subtype error - --> $DIR/issue-79187-2.rs:8:5 - | -LL | take_foo(|a| a); - | ^^^^^^^^^^^^^^^ - -error: higher-ranked subtype error - --> $DIR/issue-79187-2.rs:8:5 - | -LL | take_foo(|a| a); - | ^^^^^^^^^^^^^^^ - -error: higher-ranked subtype error - --> $DIR/issue-79187-2.rs:9:5 - | -LL | take_foo(|a: &i32| a); - | ^^^^^^^^^^^^^^^^^^^^^ - -error: higher-ranked subtype error - --> $DIR/issue-79187-2.rs:10:5 - | -LL | take_foo(|a: &i32| -> &i32 { a }); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -error: aborting due to 6 previous errors - diff --git a/src/test/ui/lifetimes/issue-79187-2.rs b/src/test/ui/lifetimes/issue-79187-2.rs deleted file mode 100644 index 29d108facab3f..0000000000000 --- a/src/test/ui/lifetimes/issue-79187-2.rs +++ /dev/null @@ -1,23 +0,0 @@ -trait Foo {} - -impl Foo for F where F: Fn(&i32) -> &i32 {} - -fn take_foo(_: impl Foo) {} - -fn main() { - take_foo(|a| a); //~ ERROR mismatched types - take_foo(|a: &i32| a); //~ ERROR mismatched types - take_foo(|a: &i32| -> &i32 { a }); //~ ERROR mismatched types - - // OK - take_foo(identity(|a| a)); - take_foo(identity(|a: &i32| a)); - take_foo(identity(|a: &i32| -> &i32 { a })); - - fn identity(t: F) -> F - where - F: Fn(&i32) -> &i32, - { - t - } -} diff --git a/src/test/ui/lifetimes/issue-79187-2.stderr b/src/test/ui/lifetimes/issue-79187-2.stderr deleted file mode 100644 index a156c74fb3304..0000000000000 --- a/src/test/ui/lifetimes/issue-79187-2.stderr +++ /dev/null @@ -1,60 +0,0 @@ -error[E0308]: mismatched types - --> $DIR/issue-79187-2.rs:8:5 - | -LL | take_foo(|a| a); - | ^^^^^^^^ lifetime mismatch - | - = note: expected type `for<'r> Fn<(&'r i32,)>` - found type `Fn<(&i32,)>` -note: this closure does not fulfill the lifetime requirements - --> $DIR/issue-79187-2.rs:8:14 - | -LL | take_foo(|a| a); - | ^^^^^ -note: the lifetime requirement is introduced here - --> $DIR/issue-79187-2.rs:5:21 - | -LL | fn take_foo(_: impl Foo) {} - | ^^^ - -error[E0308]: mismatched types - --> $DIR/issue-79187-2.rs:9:5 - | -LL | take_foo(|a: &i32| a); - | ^^^^^^^^ lifetime mismatch - | - = note: expected reference `&i32` - found reference `&i32` -note: the anonymous lifetime #1 defined on the body at 9:14 doesn't meet the lifetime requirements - --> $DIR/issue-79187-2.rs:9:14 - | -LL | take_foo(|a: &i32| a); - | ^^^^^^^^^^^ -note: the lifetime requirement is introduced here - --> $DIR/issue-79187-2.rs:5:21 - | -LL | fn take_foo(_: impl Foo) {} - | ^^^ - -error[E0308]: mismatched types - --> $DIR/issue-79187-2.rs:10:5 - | -LL | take_foo(|a: &i32| -> &i32 { a }); - | ^^^^^^^^ lifetime mismatch - | - = note: expected reference `&i32` - found reference `&i32` -note: the anonymous lifetime #1 defined on the body at 10:14 doesn't meet the lifetime requirements - --> $DIR/issue-79187-2.rs:10:14 - | -LL | take_foo(|a: &i32| -> &i32 { a }); - | ^^^^^^^^^^^^^^^^^^^^^^^ -note: the lifetime requirement is introduced here - --> $DIR/issue-79187-2.rs:5:21 - | -LL | fn take_foo(_: impl Foo) {} - | ^^^ - -error: aborting due to 3 previous errors - -For more information about this error, try `rustc --explain E0308`. diff --git a/src/test/ui/lifetimes/issue-79187.nll.stderr b/src/test/ui/lifetimes/issue-79187.nll.stderr deleted file mode 100644 index aa8809dbc95f7..0000000000000 --- a/src/test/ui/lifetimes/issue-79187.nll.stderr +++ /dev/null @@ -1,14 +0,0 @@ -error: higher-ranked subtype error - --> $DIR/issue-79187.rs:5:5 - | -LL | thing(f); - | ^^^^^^^^ - -error: higher-ranked subtype error - --> $DIR/issue-79187.rs:5:5 - | -LL | thing(f); - | ^^^^^^^^ - -error: aborting due to 2 previous errors - diff --git a/src/test/ui/lifetimes/issue-79187.rs b/src/test/ui/lifetimes/issue-79187.rs deleted file mode 100644 index bf331d8a6068e..0000000000000 --- a/src/test/ui/lifetimes/issue-79187.rs +++ /dev/null @@ -1,6 +0,0 @@ -fn thing(x: impl FnOnce(&u32)) {} - -fn main() { - let f = |_| (); - thing(f); //~ERROR mismatched types -} diff --git a/src/test/ui/lifetimes/issue-79187.stderr b/src/test/ui/lifetimes/issue-79187.stderr deleted file mode 100644 index 63f501e08fce4..0000000000000 --- a/src/test/ui/lifetimes/issue-79187.stderr +++ /dev/null @@ -1,22 +0,0 @@ -error[E0308]: mismatched types - --> $DIR/issue-79187.rs:5:5 - | -LL | thing(f); - | ^^^^^ lifetime mismatch - | - = note: expected type `FnOnce<(&u32,)>` - found type `FnOnce<(&u32,)>` -note: this closure does not fulfill the lifetime requirements - --> $DIR/issue-79187.rs:4:13 - | -LL | let f = |_| (); - | ^^^^^^ -note: the lifetime requirement is introduced here - --> $DIR/issue-79187.rs:1:18 - | -LL | fn thing(x: impl FnOnce(&u32)) {} - | ^^^^^^^^^^^^ - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0308`. diff --git a/src/test/ui/lifetimes/lifetime-errors/liveness-assign-imm-local-notes.stderr b/src/test/ui/lifetimes/lifetime-errors/liveness-assign-imm-local-notes.stderr index c646912d3b679..13b6a7bbef321 100644 --- a/src/test/ui/lifetimes/lifetime-errors/liveness-assign-imm-local-notes.stderr +++ b/src/test/ui/lifetimes/lifetime-errors/liveness-assign-imm-local-notes.stderr @@ -28,6 +28,9 @@ LL | let x; ... LL | x = 1; | ^^^^^ cannot assign twice to immutable variable +LL | } else { +LL | x = 2; + | ----- first assignment to `x` error[E0384]: cannot assign twice to immutable variable `x` --> $DIR/liveness-assign-imm-local-notes.rs:32:13 @@ -35,9 +38,6 @@ error[E0384]: cannot assign twice to immutable variable `x` LL | let x; | - help: make this binding mutable: `mut x` ... -LL | x = 1; - | ----- first assignment to `x` -LL | } else { LL | x = 2; | ^^^^^ cannot assign twice to immutable variable diff --git a/src/test/ui/link-cfg-works.rs b/src/test/ui/link-cfg-works.rs index 254091ff2508c..fe1b569dff61c 100644 --- a/src/test/ui/link-cfg-works.rs +++ b/src/test/ui/link-cfg-works.rs @@ -4,10 +4,10 @@ #![feature(link_cfg)] -extern crate link_cfg_works_transitive_dylib; extern crate link_cfg_works_transitive_rlib; +extern crate link_cfg_works_transitive_dylib; #[link(name = "foo", cfg(foo))] -extern "C" {} +extern {} fn main() {} diff --git a/src/test/ui/linkage-attr/auxiliary/def_colliding_external.rs b/src/test/ui/linkage-attr/auxiliary/def_colliding_external.rs index 60b55b3e27bc8..bbbfc4857918d 100644 --- a/src/test/ui/linkage-attr/auxiliary/def_colliding_external.rs +++ b/src/test/ui/linkage-attr/auxiliary/def_colliding_external.rs @@ -1,7 +1,7 @@ #![feature(linkage)] #![crate_type = "lib"] -extern "C" { - #[linkage = "external"] +extern { + #[linkage="external"] pub static collision: *const i32; } diff --git a/src/test/ui/linkage-attr/invalid-link-args.rs b/src/test/ui/linkage-attr/invalid-link-args.rs index 7418691d01409..5eb1c637f09e8 100644 --- a/src/test/ui/linkage-attr/invalid-link-args.rs +++ b/src/test/ui/linkage-attr/invalid-link-args.rs @@ -9,6 +9,6 @@ #![feature(link_args)] #[link_args = "aFdEfSeVEEE"] -extern "C" {} +extern {} -fn main() {} +fn main() { } diff --git a/src/test/ui/linkage-attr/linkage-detect-local-generated-name-collision.rs b/src/test/ui/linkage-attr/linkage-detect-local-generated-name-collision.rs index b712f3225ed16..1e5069612fb0d 100644 --- a/src/test/ui/linkage-attr/linkage-detect-local-generated-name-collision.rs +++ b/src/test/ui/linkage-attr/linkage-detect-local-generated-name-collision.rs @@ -3,8 +3,8 @@ #![feature(linkage)] mod dep1 { - extern "C" { - #[linkage = "external"] + extern { + #[linkage="external"] #[no_mangle] pub static collision: *const i32; //~ ERROR symbol `collision` is already defined } @@ -20,6 +20,6 @@ mod dep2 { fn main() { unsafe { - println!("{:p}", &dep1::collision); + println!("{:p}", &dep1::collision); } } diff --git a/src/test/ui/linkage-attr/linkage2.rs b/src/test/ui/linkage-attr/linkage2.rs index a7be1985286a1..41e7819e8cdf0 100644 --- a/src/test/ui/linkage-attr/linkage2.rs +++ b/src/test/ui/linkage-attr/linkage2.rs @@ -7,10 +7,9 @@ #![feature(linkage)] -extern "C" { - #[linkage = "extern_weak"] - static foo: i32; -//~^ ERROR: must have type `*const T` or `*mut T` due to `#[linkage]` attribute +extern { + #[linkage = "extern_weak"] static foo: i32; + //~^ ERROR: must have type `*const T` or `*mut T` due to `#[linkage]` attribute } fn main() { diff --git a/src/test/ui/linkage-attr/linkage2.stderr b/src/test/ui/linkage-attr/linkage2.stderr index 6ffe07170ede7..72ee3fb62ecb9 100644 --- a/src/test/ui/linkage-attr/linkage2.stderr +++ b/src/test/ui/linkage-attr/linkage2.stderr @@ -1,8 +1,8 @@ error: must have type `*const T` or `*mut T` due to `#[linkage]` attribute - --> $DIR/linkage2.rs:12:5 + --> $DIR/linkage2.rs:11:32 | -LL | static foo: i32; - | ^^^^^^^^^^^^^^^^ +LL | #[linkage = "extern_weak"] static foo: i32; + | ^^^^^^^^^^^^^^^^ error: aborting due to previous error diff --git a/src/test/ui/linkage-attr/linkage3.rs b/src/test/ui/linkage-attr/linkage3.rs index 112eb1d3bd9d2..e91dbf675d35f 100644 --- a/src/test/ui/linkage-attr/linkage3.rs +++ b/src/test/ui/linkage-attr/linkage3.rs @@ -6,10 +6,9 @@ #![feature(linkage)] -extern "C" { - #[linkage = "foo"] - static foo: *const i32; -//~^ ERROR: invalid linkage specified +extern { + #[linkage = "foo"] static foo: *const i32; + //~^ ERROR: invalid linkage specified } fn main() { diff --git a/src/test/ui/linkage-attr/linkage3.stderr b/src/test/ui/linkage-attr/linkage3.stderr index 0cbac28349d5a..5a0833f2f7434 100644 --- a/src/test/ui/linkage-attr/linkage3.stderr +++ b/src/test/ui/linkage-attr/linkage3.stderr @@ -1,8 +1,8 @@ error: invalid linkage specified - --> $DIR/linkage3.rs:11:5 + --> $DIR/linkage3.rs:10:24 | -LL | static foo: *const i32; - | ^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[linkage = "foo"] static foo: *const i32; + | ^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to previous error diff --git a/src/test/ui/linkage1.rs b/src/test/ui/linkage1.rs index deab7a251cbd4..bda4da53dbc2d 100644 --- a/src/test/ui/linkage1.rs +++ b/src/test/ui/linkage1.rs @@ -9,7 +9,7 @@ extern crate linkage1 as other; -extern "C" { +extern { #[linkage = "extern_weak"] static foo: *const isize; #[linkage = "extern_weak"] diff --git a/src/test/ui/lint/dead-code/leading-underscore.rs b/src/test/ui/lint/dead-code/leading-underscore.rs index d3582961b3e39..1b6e03ab8874d 100644 --- a/src/test/ui/lint/dead-code/leading-underscore.rs +++ b/src/test/ui/lint/dead-code/leading-underscore.rs @@ -8,7 +8,7 @@ static _X: usize = 0; fn _foo() {} struct _Y { - _z: usize, + _z: usize } enum _Z {} @@ -23,7 +23,7 @@ mod _bar { fn _qux() {} } -extern "C" { +extern { #[link_name = "abort"] fn _abort() -> !; } diff --git a/src/test/ui/lint/dead-code/lint-dead-code-3.rs b/src/test/ui/lint/dead-code/lint-dead-code-3.rs index 7f39f7965f286..fe3c392ccf100 100644 --- a/src/test/ui/lint/dead-code/lint-dead-code-3.rs +++ b/src/test/ui/lint/dead-code/lint-dead-code-3.rs @@ -7,7 +7,7 @@ pub use extern_foo as x; -extern "C" { +extern { pub fn extern_foo(); } @@ -47,7 +47,7 @@ mod blah { // `malloc` below, which are also used. enum c_void {} - extern "C" { + extern { fn free(p: *const c_void); fn malloc(size: usize) -> *const c_void; } @@ -58,7 +58,7 @@ mod blah { } enum c_void {} //~ ERROR: enum is never used -extern "C" { +extern { fn free(p: *const c_void); //~ ERROR: function is never used } diff --git a/src/test/ui/lint/inline-trait-and-foreign-items.rs b/src/test/ui/lint/inline-trait-and-foreign-items.rs index 6321b3c76e4d1..8bdefbb36ae5f 100644 --- a/src/test/ui/lint/inline-trait-and-foreign-items.rs +++ b/src/test/ui/lint/inline-trait-and-foreign-items.rs @@ -26,7 +26,7 @@ impl Trait for () { type U = impl Trait; //~ ERROR could not find defining uses } -extern "C" { +extern { #[inline] //~ ERROR attribute should be applied to function or closure static X: u32; diff --git a/src/test/ui/lint/lint-ctypes-enum.rs b/src/test/ui/lint/lint-ctypes-enum.rs index d7f947aa0f3bc..17cb705373109 100644 --- a/src/test/ui/lint/lint-ctypes-enum.rs +++ b/src/test/ui/lint/lint-ctypes-enum.rs @@ -5,57 +5,36 @@ use std::num; -enum Z {} -enum U { - A, -} -enum B { - C, - D, -} -enum T { - E, - F, - G, -} +enum Z { } +enum U { A } +enum B { C, D } +enum T { E, F, G } #[repr(C)] -enum ReprC { - A, - B, - C, -} +enum ReprC { A, B, C } #[repr(u8)] -enum U8 { - A, - B, - C, -} +enum U8 { A, B, C } #[repr(isize)] -enum Isize { - A, - B, - C, -} +enum Isize { A, B, C } #[repr(transparent)] struct TransparentStruct(T, std::marker::PhantomData); #[repr(transparent)] enum TransparentEnum { - Variant(T, std::marker::PhantomData), + Variant(T, std::marker::PhantomData), } #[repr(transparent)] union TransparentUnion { - field: T, + field: T, } struct Rust(T); -extern "C" { +extern { fn zf(x: Z); fn uf(x: U); //~ ERROR `extern` block uses type `U` fn bf(x: B); //~ ERROR `extern` block uses type `B` diff --git a/src/test/ui/lint/lint-ctypes-enum.stderr b/src/test/ui/lint/lint-ctypes-enum.stderr index 8917d309e6087..3d02cda7d3e5b 100644 --- a/src/test/ui/lint/lint-ctypes-enum.stderr +++ b/src/test/ui/lint/lint-ctypes-enum.stderr @@ -1,5 +1,5 @@ error: `extern` block uses type `U`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:60:13 + --> $DIR/lint-ctypes-enum.rs:39:13 | LL | fn uf(x: U); | ^ not FFI-safe @@ -14,13 +14,11 @@ LL | #![deny(improper_ctypes)] note: the type is defined here --> $DIR/lint-ctypes-enum.rs:9:1 | -LL | / enum U { -LL | | A, -LL | | } - | |_^ +LL | enum U { A } + | ^^^^^^^^^^^^ error: `extern` block uses type `B`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:61:13 + --> $DIR/lint-ctypes-enum.rs:40:13 | LL | fn bf(x: B); | ^ not FFI-safe @@ -28,16 +26,13 @@ LL | fn bf(x: B); = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum = note: enum has no representation hint note: the type is defined here - --> $DIR/lint-ctypes-enum.rs:12:1 + --> $DIR/lint-ctypes-enum.rs:10:1 | -LL | / enum B { -LL | | C, -LL | | D, -LL | | } - | |_^ +LL | enum B { C, D } + | ^^^^^^^^^^^^^^^ error: `extern` block uses type `T`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:62:13 + --> $DIR/lint-ctypes-enum.rs:41:13 | LL | fn tf(x: T); | ^ not FFI-safe @@ -45,17 +40,13 @@ LL | fn tf(x: T); = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum = note: enum has no representation hint note: the type is defined here - --> $DIR/lint-ctypes-enum.rs:16:1 - | -LL | / enum T { -LL | | E, -LL | | F, -LL | | G, -LL | | } - | |_^ + --> $DIR/lint-ctypes-enum.rs:11:1 + | +LL | enum T { E, F, G } + | ^^^^^^^^^^^^^^^^^^ error: `extern` block uses type `Option>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:69:17 + --> $DIR/lint-ctypes-enum.rs:48:17 | LL | fn unique(x: Option>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -64,7 +55,7 @@ LL | fn unique(x: Option>); = note: enum has no representation hint error: `extern` block uses type `u128`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:75:23 + --> $DIR/lint-ctypes-enum.rs:54:23 | LL | fn nonzero_u128(x: Option); | ^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -72,7 +63,7 @@ LL | fn nonzero_u128(x: Option); = note: 128-bit integers don't currently have a known stable ABI error: `extern` block uses type `i128`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:82:23 + --> $DIR/lint-ctypes-enum.rs:61:23 | LL | fn nonzero_i128(x: Option); | ^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -80,7 +71,7 @@ LL | fn nonzero_i128(x: Option); = note: 128-bit integers don't currently have a known stable ABI error: `extern` block uses type `Option>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:87:28 + --> $DIR/lint-ctypes-enum.rs:66:28 | LL | fn transparent_union(x: Option>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -89,7 +80,7 @@ LL | fn transparent_union(x: Option>); = note: enum has no representation hint error: `extern` block uses type `Option>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:89:20 + --> $DIR/lint-ctypes-enum.rs:68:20 | LL | fn repr_rust(x: Option>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -98,7 +89,7 @@ LL | fn repr_rust(x: Option>); = note: enum has no representation hint error: `extern` block uses type `std::result::Result<(), NonZeroI32>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:90:20 + --> $DIR/lint-ctypes-enum.rs:69:20 | LL | fn no_result(x: Result<(), num::NonZeroI32>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe diff --git a/src/test/ui/lint/lint-ctypes-fn.rs b/src/test/ui/lint/lint-ctypes-fn.rs index e69d0dab49642..170a04efb07c6 100644 --- a/src/test/ui/lint/lint-ctypes-fn.rs +++ b/src/test/ui/lint/lint-ctypes-fn.rs @@ -27,7 +27,7 @@ pub struct ZeroSize; pub type RustFn = fn(); -pub type RustBadRet = extern "C" fn() -> Box; +pub type RustBadRet = extern fn() -> Box; pub type CVoidRet = (); @@ -116,7 +116,7 @@ pub extern "C" fn transparent_str(p: TransparentStr) { } pub extern "C" fn transparent_fn(p: TransparentBadFn) { } -pub extern "C" fn good3(fptr: Option) { } +pub extern "C" fn good3(fptr: Option) { } pub extern "C" fn good4(aptr: &[u8; 4 as usize]) { } @@ -124,9 +124,9 @@ pub extern "C" fn good5(s: StructWithProjection) { } pub extern "C" fn good6(s: StructWithProjectionAndLifetime) { } -pub extern "C" fn good7(fptr: extern "C" fn() -> ()) { } +pub extern "C" fn good7(fptr: extern fn() -> ()) { } -pub extern "C" fn good8(fptr: extern "C" fn() -> !) { } +pub extern "C" fn good8(fptr: extern fn() -> !) { } pub extern "C" fn good9() -> () { } diff --git a/src/test/ui/lint/lint-ctypes.rs b/src/test/ui/lint/lint-ctypes.rs index fabbdcf689182..e8a90bca7d310 100644 --- a/src/test/ui/lint/lint-ctypes.rs +++ b/src/test/ui/lint/lint-ctypes.rs @@ -20,7 +20,7 @@ pub type I32Pair = (i32, i32); #[repr(C)] pub struct ZeroSize; pub type RustFn = fn(); -pub type RustBadRet = extern "C" fn() -> Box; +pub type RustBadRet = extern fn() -> Box; pub type CVoidRet = (); pub struct Foo; #[repr(transparent)] @@ -43,7 +43,7 @@ pub struct TransparentCustomZst(i32, ZeroSize); #[repr(C)] pub struct ZeroSizeWithPhantomData(::std::marker::PhantomData); -extern "C" { +extern { pub fn ptr_type1(size: *const Foo); //~ ERROR: uses type `Foo` pub fn ptr_type2(size: *const Foo); //~ ERROR: uses type `Foo` pub fn slice_type(p: &[u32]); //~ ERROR: uses type `[u32]` @@ -73,12 +73,12 @@ extern "C" { pub static static_u128_type: u128; //~ ERROR: uses type `u128` pub static static_u128_array_type: [u128; 16]; //~ ERROR: uses type `u128` - pub fn good3(fptr: Option); + pub fn good3(fptr: Option); pub fn good4(aptr: &[u8; 4 as usize]); pub fn good5(s: StructWithProjection); pub fn good6(s: StructWithProjectionAndLifetime); - pub fn good7(fptr: extern "C" fn() -> ()); - pub fn good8(fptr: extern "C" fn() -> !); + pub fn good7(fptr: extern fn() -> ()); + pub fn good8(fptr: extern fn() -> !); pub fn good9() -> (); pub fn good10() -> CVoidRet; pub fn good11(size: isize); @@ -96,12 +96,12 @@ extern "C" { } #[allow(improper_ctypes)] -extern "C" { +extern { pub fn good19(_: &String); } #[cfg(not(target_arch = "wasm32"))] -extern "C" { +extern { pub fn good1(size: *const libc::c_int); pub fn good2(size: *const libc::c_uint); } diff --git a/src/test/ui/lint/unreachable_pub-pub_crate.rs b/src/test/ui/lint/unreachable_pub-pub_crate.rs index 27c31c22311ab..94f79d69751f1 100644 --- a/src/test/ui/lint/unreachable_pub-pub_crate.rs +++ b/src/test/ui/lint/unreachable_pub-pub_crate.rs @@ -41,7 +41,7 @@ mod private_mod { } define_empty_struct_with_visibility!(pub, Fluorine); - extern "C" { + extern { pub fn catalyze() -> bool; //~ WARNING unreachable_pub } diff --git a/src/test/ui/lint/unreachable_pub.rs b/src/test/ui/lint/unreachable_pub.rs index 6bfec0ec5e8b0..a4c1497013964 100644 --- a/src/test/ui/lint/unreachable_pub.rs +++ b/src/test/ui/lint/unreachable_pub.rs @@ -37,7 +37,7 @@ mod private_mod { } define_empty_struct_with_visibility!(pub, Fluorine); - extern "C" { + extern { pub fn catalyze() -> bool; //~ WARNING unreachable_pub } diff --git a/src/test/ui/lint/warn-unused-inline-on-fn-prototypes.rs b/src/test/ui/lint/warn-unused-inline-on-fn-prototypes.rs index 4684fe145774d..21097197499dd 100644 --- a/src/test/ui/lint/warn-unused-inline-on-fn-prototypes.rs +++ b/src/test/ui/lint/warn-unused-inline-on-fn-prototypes.rs @@ -5,7 +5,7 @@ trait Trait { fn foo(); } -extern "C" { +extern { #[inline] //~ ERROR `#[inline]` is ignored on function prototypes fn foo(); } diff --git a/src/test/ui/macros/issue-81006.rs b/src/test/ui/macros/issue-81006.rs deleted file mode 100644 index 602eb59742879..0000000000000 --- a/src/test/ui/macros/issue-81006.rs +++ /dev/null @@ -1,10 +0,0 @@ -// check-fail - -// First format below would cause a panic, second would generate error with incorrect span - -fn main() { - let _ = format!("→{}→\n"); - //~^ ERROR 1 positional argument in format string, but no arguments were given - let _ = format!("→{} \n"); - //~^ ERROR 1 positional argument in format string, but no arguments were given -} diff --git a/src/test/ui/macros/issue-81006.stderr b/src/test/ui/macros/issue-81006.stderr deleted file mode 100644 index 14a8cbe0155f9..0000000000000 --- a/src/test/ui/macros/issue-81006.stderr +++ /dev/null @@ -1,14 +0,0 @@ -error: 1 positional argument in format string, but no arguments were given - --> $DIR/issue-81006.rs:6:23 - | -LL | let _ = format!("→{}→\n"); - | ^^ - -error: 1 positional argument in format string, but no arguments were given - --> $DIR/issue-81006.rs:8:23 - | -LL | let _ = format!("→{} \n"); - | ^^ - -error: aborting due to 2 previous errors - diff --git a/src/test/ui/macros/macros-in-extern.rs b/src/test/ui/macros/macros-in-extern.rs index 568ae3a8539a9..05002ed72c78d 100644 --- a/src/test/ui/macros/macros-in-extern.rs +++ b/src/test/ui/macros/macros-in-extern.rs @@ -10,7 +10,7 @@ macro_rules! returns_isize( ); macro takes_u32_returns_u32($ident:ident) { - fn $ident(arg: u32) -> u32; + fn $ident (arg: u32) -> u32; } macro_rules! emits_nothing( @@ -25,14 +25,8 @@ macro_rules! emits_multiple( ); mod defs { - #[no_mangle] - extern "C" fn f1() -> u32 { - 1 - } - #[no_mangle] - extern "C" fn f2() -> u32 { - 2 - } + #[no_mangle] extern fn f1() -> u32 { 1 } + #[no_mangle] extern fn f2() -> u32 { 2 } } fn main() { @@ -43,7 +37,7 @@ fn main() { } #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { returns_isize!(rust_get_test_int); takes_u32_returns_u32!(rust_dbg_extern_identity_u32); emits_nothing!(); diff --git a/src/test/ui/macros/vec-macro-in-pattern.rs b/src/test/ui/macros/vec-macro-in-pattern.rs deleted file mode 100644 index ce4298b8bb334..0000000000000 --- a/src/test/ui/macros/vec-macro-in-pattern.rs +++ /dev/null @@ -1,10 +0,0 @@ -// This is a regression test for #61933 -// Verify that the vec![] macro may not be used in patterns -// and that the resulting diagnostic is actually helpful. - -fn main() { - match Some(vec![42]) { - Some(vec![43]) => {} //~ ERROR arbitrary expressions aren't allowed in patterns - _ => {} - } -} diff --git a/src/test/ui/macros/vec-macro-in-pattern.stderr b/src/test/ui/macros/vec-macro-in-pattern.stderr deleted file mode 100644 index 3dabebfdaa253..0000000000000 --- a/src/test/ui/macros/vec-macro-in-pattern.stderr +++ /dev/null @@ -1,10 +0,0 @@ -error: arbitrary expressions aren't allowed in patterns - --> $DIR/vec-macro-in-pattern.rs:7:14 - | -LL | Some(vec![43]) => {} - | ^^^^^^^^ - | - = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) - -error: aborting due to previous error - diff --git a/src/test/ui/match/match-pattern-field-mismatch.stderr b/src/test/ui/match/match-pattern-field-mismatch.stderr index 37839482b31a2..c2298d6fbbf02 100644 --- a/src/test/ui/match/match-pattern-field-mismatch.stderr +++ b/src/test/ui/match/match-pattern-field-mismatch.stderr @@ -6,15 +6,6 @@ LL | Rgb(usize, usize, usize), ... LL | Color::Rgb(_, _) => { } | ^^^^^^^^^^^^^^^^ expected 3 fields, found 2 - | -help: use `_` to explicitly ignore each field - | -LL | Color::Rgb(_, _, _) => { } - | ^^^ -help: use `..` to ignore all fields - | -LL | Color::Rgb(..) => { } - | ^^ error: aborting due to previous error diff --git a/src/test/ui/methods/method-call-lifetime-args-fail.rs b/src/test/ui/methods/method-call-lifetime-args-fail.rs index 8a840ba62cc0d..938a7f5575e35 100644 --- a/src/test/ui/methods/method-call-lifetime-args-fail.rs +++ b/src/test/ui/methods/method-call-lifetime-args-fail.rs @@ -1,5 +1,3 @@ -// ignore-tidy-linelength - struct S; impl S { @@ -16,9 +14,9 @@ impl S { fn method_call() { S.early(); // OK S.early::<'static>(); - //~^ ERROR this associated function takes 2 lifetime arguments but only 1 lifetime argument was supplied + //~^ ERROR wrong number of lifetime arguments: expected 2, found 1 S.early::<'static, 'static, 'static>(); - //~^ ERROR this associated function takes 2 lifetime arguments but 3 lifetime arguments were supplied + //~^ ERROR wrong number of lifetime arguments: expected 2, found 3 let _: &u8 = S.life_and_type::<'static>(); S.life_and_type::(); S.life_and_type::<'static, u8>(); @@ -63,9 +61,9 @@ fn ufcs() { S::early(S); // OK S::early::<'static>(S); - //~^ ERROR this associated function takes 2 lifetime arguments but only 1 lifetime argument was supplied + //~^ ERROR wrong number of lifetime arguments: expected 2, found 1 S::early::<'static, 'static, 'static>(S); - //~^ ERROR this associated function takes 2 lifetime arguments but 3 lifetime arguments were supplied + //~^ ERROR wrong number of lifetime arguments: expected 2, found 3 let _: &u8 = S::life_and_type::<'static>(S); S::life_and_type::(S); S::life_and_type::<'static, u8>(S); diff --git a/src/test/ui/methods/method-call-lifetime-args-fail.stderr b/src/test/ui/methods/method-call-lifetime-args-fail.stderr index 34a2e3dec2ecf..74dab5f440064 100644 --- a/src/test/ui/methods/method-call-lifetime-args-fail.stderr +++ b/src/test/ui/methods/method-call-lifetime-args-fail.stderr @@ -1,234 +1,194 @@ -error[E0107]: this associated function takes 2 lifetime arguments but only 1 lifetime argument was supplied - --> $DIR/method-call-lifetime-args-fail.rs:18:7 +error[E0107]: wrong number of lifetime arguments: expected 2, found 1 + --> $DIR/method-call-lifetime-args-fail.rs:16:7 | LL | S.early::<'static>(); - | ^^^^^ ------- supplied 1 lifetime argument - | | - | expected 2 lifetime arguments - | -note: associated function defined here, with 2 lifetime parameters: `'a`, `'b` - --> $DIR/method-call-lifetime-args-fail.rs:8:8 - | -LL | fn early<'a, 'b>(self) -> (&'a u8, &'b u8) { loop {} } - | ^^^^^ -- -- -help: add missing lifetime argument - | -LL | S.early::<'static, 'b>(); - | ^^^^ + | ^^^^^ expected 2 lifetime arguments -error[E0107]: this associated function takes 2 lifetime arguments but 3 lifetime arguments were supplied - --> $DIR/method-call-lifetime-args-fail.rs:20:7 +error[E0107]: wrong number of lifetime arguments: expected 2, found 3 + --> $DIR/method-call-lifetime-args-fail.rs:18:33 | LL | S.early::<'static, 'static, 'static>(); - | ^^^^^ --------- help: remove this lifetime argument - | | - | expected 2 lifetime arguments - | -note: associated function defined here, with 2 lifetime parameters: `'a`, `'b` - --> $DIR/method-call-lifetime-args-fail.rs:8:8 - | -LL | fn early<'a, 'b>(self) -> (&'a u8, &'b u8) { loop {} } - | ^^^^^ -- -- + | ^^^^^^^ unexpected lifetime argument error: cannot specify lifetime arguments explicitly if late bound lifetime parameters are present - --> $DIR/method-call-lifetime-args-fail.rs:29:15 + --> $DIR/method-call-lifetime-args-fail.rs:27:15 | LL | S::late::<'static>(S, &0, &0); | ^^^^^^^ | note: the late bound lifetime parameter is introduced here - --> $DIR/method-call-lifetime-args-fail.rs:6:13 + --> $DIR/method-call-lifetime-args-fail.rs:4:13 | LL | fn late<'a, 'b>(self, _: &'a u8, _: &'b u8) {} | ^^ error: cannot specify lifetime arguments explicitly if late bound lifetime parameters are present - --> $DIR/method-call-lifetime-args-fail.rs:31:15 + --> $DIR/method-call-lifetime-args-fail.rs:29:15 | LL | S::late::<'static, 'static>(S, &0, &0); | ^^^^^^^ | note: the late bound lifetime parameter is introduced here - --> $DIR/method-call-lifetime-args-fail.rs:6:13 + --> $DIR/method-call-lifetime-args-fail.rs:4:13 | LL | fn late<'a, 'b>(self, _: &'a u8, _: &'b u8) {} | ^^ error: cannot specify lifetime arguments explicitly if late bound lifetime parameters are present - --> $DIR/method-call-lifetime-args-fail.rs:33:15 + --> $DIR/method-call-lifetime-args-fail.rs:31:15 | LL | S::late::<'static, 'static, 'static>(S, &0, &0); | ^^^^^^^ | note: the late bound lifetime parameter is introduced here - --> $DIR/method-call-lifetime-args-fail.rs:6:13 + --> $DIR/method-call-lifetime-args-fail.rs:4:13 | LL | fn late<'a, 'b>(self, _: &'a u8, _: &'b u8) {} | ^^ error: cannot specify lifetime arguments explicitly if late bound lifetime parameters are present - --> $DIR/method-call-lifetime-args-fail.rs:36:21 + --> $DIR/method-call-lifetime-args-fail.rs:34:21 | LL | S::late_early::<'static, 'static>(S, &0); | ^^^^^^^ | note: the late bound lifetime parameter is introduced here - --> $DIR/method-call-lifetime-args-fail.rs:9:19 + --> $DIR/method-call-lifetime-args-fail.rs:7:19 | LL | fn late_early<'a, 'b>(self, _: &'a u8) -> &'b u8 { loop {} } | ^^ error: cannot specify lifetime arguments explicitly if late bound lifetime parameters are present - --> $DIR/method-call-lifetime-args-fail.rs:38:21 + --> $DIR/method-call-lifetime-args-fail.rs:36:21 | LL | S::late_early::<'static, 'static, 'static>(S, &0); | ^^^^^^^ | note: the late bound lifetime parameter is introduced here - --> $DIR/method-call-lifetime-args-fail.rs:9:19 + --> $DIR/method-call-lifetime-args-fail.rs:7:19 | LL | fn late_early<'a, 'b>(self, _: &'a u8) -> &'b u8 { loop {} } | ^^ error: cannot specify lifetime arguments explicitly if late bound lifetime parameters are present - --> $DIR/method-call-lifetime-args-fail.rs:42:24 + --> $DIR/method-call-lifetime-args-fail.rs:40:24 | LL | S::late_implicit::<'static>(S, &0, &0); | ^^^^^^^ | note: the late bound lifetime parameter is introduced here - --> $DIR/method-call-lifetime-args-fail.rs:7:31 + --> $DIR/method-call-lifetime-args-fail.rs:5:31 | LL | fn late_implicit(self, _: &u8, _: &u8) {} | ^ error: cannot specify lifetime arguments explicitly if late bound lifetime parameters are present - --> $DIR/method-call-lifetime-args-fail.rs:44:24 + --> $DIR/method-call-lifetime-args-fail.rs:42:24 | LL | S::late_implicit::<'static, 'static>(S, &0, &0); | ^^^^^^^ | note: the late bound lifetime parameter is introduced here - --> $DIR/method-call-lifetime-args-fail.rs:7:31 + --> $DIR/method-call-lifetime-args-fail.rs:5:31 | LL | fn late_implicit(self, _: &u8, _: &u8) {} | ^ error: cannot specify lifetime arguments explicitly if late bound lifetime parameters are present - --> $DIR/method-call-lifetime-args-fail.rs:46:24 + --> $DIR/method-call-lifetime-args-fail.rs:44:24 | LL | S::late_implicit::<'static, 'static, 'static>(S, &0, &0); | ^^^^^^^ | note: the late bound lifetime parameter is introduced here - --> $DIR/method-call-lifetime-args-fail.rs:7:31 + --> $DIR/method-call-lifetime-args-fail.rs:5:31 | LL | fn late_implicit(self, _: &u8, _: &u8) {} | ^ error: cannot specify lifetime arguments explicitly if late bound lifetime parameters are present - --> $DIR/method-call-lifetime-args-fail.rs:49:30 + --> $DIR/method-call-lifetime-args-fail.rs:47:30 | LL | S::late_implicit_early::<'static, 'static>(S, &0); | ^^^^^^^ | note: the late bound lifetime parameter is introduced here - --> $DIR/method-call-lifetime-args-fail.rs:10:41 + --> $DIR/method-call-lifetime-args-fail.rs:8:41 | LL | fn late_implicit_early<'b>(self, _: &u8) -> &'b u8 { loop {} } | ^ error: cannot specify lifetime arguments explicitly if late bound lifetime parameters are present - --> $DIR/method-call-lifetime-args-fail.rs:51:30 + --> $DIR/method-call-lifetime-args-fail.rs:49:30 | LL | S::late_implicit_early::<'static, 'static, 'static>(S, &0); | ^^^^^^^ | note: the late bound lifetime parameter is introduced here - --> $DIR/method-call-lifetime-args-fail.rs:10:41 + --> $DIR/method-call-lifetime-args-fail.rs:8:41 | LL | fn late_implicit_early<'b>(self, _: &u8) -> &'b u8 { loop {} } | ^ error: cannot specify lifetime arguments explicitly if late bound lifetime parameters are present - --> $DIR/method-call-lifetime-args-fail.rs:54:35 + --> $DIR/method-call-lifetime-args-fail.rs:52:35 | LL | S::late_implicit_self_early::<'static, 'static>(&S); | ^^^^^^^ | note: the late bound lifetime parameter is introduced here - --> $DIR/method-call-lifetime-args-fail.rs:11:37 + --> $DIR/method-call-lifetime-args-fail.rs:9:37 | LL | fn late_implicit_self_early<'b>(&self) -> &'b u8 { loop {} } | ^ error: cannot specify lifetime arguments explicitly if late bound lifetime parameters are present - --> $DIR/method-call-lifetime-args-fail.rs:56:35 + --> $DIR/method-call-lifetime-args-fail.rs:54:35 | LL | S::late_implicit_self_early::<'static, 'static, 'static>(&S); | ^^^^^^^ | note: the late bound lifetime parameter is introduced here - --> $DIR/method-call-lifetime-args-fail.rs:11:37 + --> $DIR/method-call-lifetime-args-fail.rs:9:37 | LL | fn late_implicit_self_early<'b>(&self) -> &'b u8 { loop {} } | ^ error: cannot specify lifetime arguments explicitly if late bound lifetime parameters are present - --> $DIR/method-call-lifetime-args-fail.rs:59:28 + --> $DIR/method-call-lifetime-args-fail.rs:57:28 | LL | S::late_unused_early::<'static, 'static>(S); | ^^^^^^^ | note: the late bound lifetime parameter is introduced here - --> $DIR/method-call-lifetime-args-fail.rs:12:26 + --> $DIR/method-call-lifetime-args-fail.rs:10:26 | LL | fn late_unused_early<'a, 'b>(self) -> &'b u8 { loop {} } | ^^ error: cannot specify lifetime arguments explicitly if late bound lifetime parameters are present - --> $DIR/method-call-lifetime-args-fail.rs:61:28 + --> $DIR/method-call-lifetime-args-fail.rs:59:28 | LL | S::late_unused_early::<'static, 'static, 'static>(S); | ^^^^^^^ | note: the late bound lifetime parameter is introduced here - --> $DIR/method-call-lifetime-args-fail.rs:12:26 + --> $DIR/method-call-lifetime-args-fail.rs:10:26 | LL | fn late_unused_early<'a, 'b>(self) -> &'b u8 { loop {} } | ^^ -error[E0107]: this associated function takes 2 lifetime arguments but only 1 lifetime argument was supplied - --> $DIR/method-call-lifetime-args-fail.rs:65:8 +error[E0107]: wrong number of lifetime arguments: expected 2, found 1 + --> $DIR/method-call-lifetime-args-fail.rs:63:5 | LL | S::early::<'static>(S); - | ^^^^^ ------- supplied 1 lifetime argument - | | - | expected 2 lifetime arguments - | -note: associated function defined here, with 2 lifetime parameters: `'a`, `'b` - --> $DIR/method-call-lifetime-args-fail.rs:8:8 - | -LL | fn early<'a, 'b>(self) -> (&'a u8, &'b u8) { loop {} } - | ^^^^^ -- -- -help: add missing lifetime argument - | -LL | S::early::<'static, 'b>(S); - | ^^^^ + | ^^^^^^^^^^^^^^^^^^^ expected 2 lifetime arguments -error[E0107]: this associated function takes 2 lifetime arguments but 3 lifetime arguments were supplied - --> $DIR/method-call-lifetime-args-fail.rs:67:8 +error[E0107]: wrong number of lifetime arguments: expected 2, found 3 + --> $DIR/method-call-lifetime-args-fail.rs:65:34 | LL | S::early::<'static, 'static, 'static>(S); - | ^^^^^ --------- help: remove this lifetime argument - | | - | expected 2 lifetime arguments - | -note: associated function defined here, with 2 lifetime parameters: `'a`, `'b` - --> $DIR/method-call-lifetime-args-fail.rs:8:8 - | -LL | fn early<'a, 'b>(self) -> (&'a u8, &'b u8) { loop {} } - | ^^^^^ -- -- + | ^^^^^^^ unexpected lifetime argument error: aborting due to 18 previous errors diff --git a/src/test/ui/mir/mir_codegen_calls.rs b/src/test/ui/mir/mir_codegen_calls.rs index 6a5a4dace6492..d93a25c8ef4d3 100644 --- a/src/test/ui/mir/mir_codegen_calls.rs +++ b/src/test/ui/mir/mir_codegen_calls.rs @@ -75,7 +75,7 @@ fn test8() -> isize { } #[allow(improper_ctypes_definitions)] -extern "C" fn simple_extern(x: u32, y: (u32, u32)) -> u32 { +extern fn simple_extern(x: u32, y: (u32, u32)) -> u32 { x + y.0 * y.1 } diff --git a/src/test/ui/mir/ssa-analysis-regression-50041.rs b/src/test/ui/mir/ssa-analysis-regression-50041.rs deleted file mode 100644 index c818f2976e1cf..0000000000000 --- a/src/test/ui/mir/ssa-analysis-regression-50041.rs +++ /dev/null @@ -1,34 +0,0 @@ -// build-pass -// compile-flags: -Z mir-opt-level=3 - -#![crate_type="lib"] -#![feature(lang_items)] -#![no_std] - -#[lang = "owned_box"] -pub struct Box(*mut T); - -impl Drop for Box { - fn drop(&mut self) { - } -} - -#[lang = "box_free"] -#[inline(always)] -unsafe fn box_free(ptr: *mut T) { - dealloc(ptr) -} - -#[inline(never)] -fn dealloc(_: *mut T) { -} - -pub struct Foo(T); - -pub fn foo(a: Option>>) -> usize { - let f = match a { - None => Foo(0), - Some(vec) => *vec, - }; - f.0 -} diff --git a/src/test/ui/mismatched_types/closure-arg-type-mismatch.stderr b/src/test/ui/mismatched_types/closure-arg-type-mismatch.stderr index 02ba60f7f4b73..0af44d21196db 100644 --- a/src/test/ui/mismatched_types/closure-arg-type-mismatch.stderr +++ b/src/test/ui/mismatched_types/closure-arg-type-mismatch.stderr @@ -26,77 +26,37 @@ error[E0308]: mismatched types --> $DIR/closure-arg-type-mismatch.rs:10:5 | LL | baz(f); - | ^^^ lifetime mismatch + | ^^^ one type is more general than the other | = note: expected type `for<'r> Fn<(*mut &'r u32,)>` found type `Fn<(*mut &'a u32,)>` -note: the required lifetime does not necessarily outlive the lifetime `'a` as defined on the function body at 9:10 - --> $DIR/closure-arg-type-mismatch.rs:9:10 - | -LL | fn _test<'a>(f: fn(*mut &'a u32)) { - | ^^ -note: the lifetime requirement is introduced here - --> $DIR/closure-arg-type-mismatch.rs:8:11 - | -LL | fn baz(_: F) {} - | ^^^^^^^^^^^^^ error[E0308]: mismatched types --> $DIR/closure-arg-type-mismatch.rs:10:5 | LL | baz(f); - | ^^^ lifetime mismatch + | ^^^ one type is more general than the other | = note: expected type `FnOnce<(*mut &u32,)>` found type `FnOnce<(*mut &'a u32,)>` -note: the required lifetime does not necessarily outlive the lifetime `'a` as defined on the function body at 9:10 - --> $DIR/closure-arg-type-mismatch.rs:9:10 - | -LL | fn _test<'a>(f: fn(*mut &'a u32)) { - | ^^ -note: the lifetime requirement is introduced here - --> $DIR/closure-arg-type-mismatch.rs:8:11 - | -LL | fn baz(_: F) {} - | ^^^^^^^^^^^^^ error[E0308]: mismatched types --> $DIR/closure-arg-type-mismatch.rs:10:5 | LL | baz(f); - | ^^^ lifetime mismatch + | ^^^ one type is more general than the other | = note: expected type `for<'r> Fn<(*mut &'r u32,)>` found type `Fn<(*mut &'a u32,)>` -note: the lifetime `'a` as defined on the function body at 9:10 doesn't meet the lifetime requirements - --> $DIR/closure-arg-type-mismatch.rs:9:10 - | -LL | fn _test<'a>(f: fn(*mut &'a u32)) { - | ^^ -note: the lifetime requirement is introduced here - --> $DIR/closure-arg-type-mismatch.rs:8:11 - | -LL | fn baz(_: F) {} - | ^^^^^^^^^^^^^ error[E0308]: mismatched types --> $DIR/closure-arg-type-mismatch.rs:10:5 | LL | baz(f); - | ^^^ lifetime mismatch + | ^^^ one type is more general than the other | = note: expected type `FnOnce<(*mut &u32,)>` found type `FnOnce<(*mut &'a u32,)>` -note: the lifetime `'a` as defined on the function body at 9:10 doesn't meet the lifetime requirements - --> $DIR/closure-arg-type-mismatch.rs:9:10 - | -LL | fn _test<'a>(f: fn(*mut &'a u32)) { - | ^^ -note: the lifetime requirement is introduced here - --> $DIR/closure-arg-type-mismatch.rs:8:11 - | -LL | fn baz(_: F) {} - | ^^^^^^^^^^^^^ error: aborting due to 7 previous errors diff --git a/src/test/ui/mismatched_types/closure-mismatch.stderr b/src/test/ui/mismatched_types/closure-mismatch.stderr index c41bece3c196f..149f505dc6f57 100644 --- a/src/test/ui/mismatched_types/closure-mismatch.stderr +++ b/src/test/ui/mismatched_types/closure-mismatch.stderr @@ -2,20 +2,10 @@ error[E0308]: mismatched types --> $DIR/closure-mismatch.rs:8:5 | LL | baz(|_| ()); - | ^^^ lifetime mismatch + | ^^^ one type is more general than the other | = note: expected type `for<'r> Fn<(&'r (),)>` found type `Fn<(&(),)>` -note: this closure does not fulfill the lifetime requirements - --> $DIR/closure-mismatch.rs:8:9 - | -LL | baz(|_| ()); - | ^^^^^^ -note: the lifetime requirement is introduced here - --> $DIR/closure-mismatch.rs:5:11 - | -LL | fn baz(_: T) {} - | ^^^ error: aborting due to previous error diff --git a/src/test/ui/mismatched_types/issue-26480.rs b/src/test/ui/mismatched_types/issue-26480.rs index 8bd26cebc6934..d140e12b04d38 100644 --- a/src/test/ui/mismatched_types/issue-26480.rs +++ b/src/test/ui/mismatched_types/issue-26480.rs @@ -1,4 +1,4 @@ -extern "C" { +extern { fn write(fildes: i32, buf: *const i8, nbyte: u64) -> i64; } diff --git a/src/test/ui/mismatched_types/overloaded-calls-bad.stderr b/src/test/ui/mismatched_types/overloaded-calls-bad.stderr index 264d7cbb9b1cb..706e25529bfaf 100644 --- a/src/test/ui/mismatched_types/overloaded-calls-bad.stderr +++ b/src/test/ui/mismatched_types/overloaded-calls-bad.stderr @@ -11,12 +11,6 @@ LL | let ans = s(); | ^-- supplied 0 arguments | | | expected 1 argument - | -note: associated function defined here - --> $SRC_DIR/core/src/ops/function.rs:LL:COL - | -LL | extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output; - | ^^^^^^^^ error[E0057]: this function takes 1 argument but 2 arguments were supplied --> $DIR/overloaded-calls-bad.rs:31:15 @@ -25,12 +19,6 @@ LL | let ans = s("burma", "shave"); | ^ ------- ------- supplied 2 arguments | | | expected 1 argument - | -note: associated function defined here - --> $SRC_DIR/core/src/ops/function.rs:LL:COL - | -LL | extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output; - | ^^^^^^^^ error: aborting due to 3 previous errors diff --git a/src/test/ui/impl-trait/nested_impl_trait.rs b/src/test/ui/nested_impl_trait.rs similarity index 100% rename from src/test/ui/impl-trait/nested_impl_trait.rs rename to src/test/ui/nested_impl_trait.rs diff --git a/src/test/ui/impl-trait/nested_impl_trait.stderr b/src/test/ui/nested_impl_trait.stderr similarity index 100% rename from src/test/ui/impl-trait/nested_impl_trait.stderr rename to src/test/ui/nested_impl_trait.stderr diff --git a/src/test/ui/nil-decl-in-foreign.rs b/src/test/ui/nil-decl-in-foreign.rs index f3be948781be3..98422665b9c5b 100644 --- a/src/test/ui/nil-decl-in-foreign.rs +++ b/src/test/ui/nil-decl-in-foreign.rs @@ -6,9 +6,9 @@ // pretty-expanded FIXME #23616 mod libc { - extern "C" { + extern { pub fn printf(x: ()); } } -pub fn main() {} +pub fn main() { } diff --git a/src/test/ui/no-patterns-in-args.rs b/src/test/ui/no-patterns-in-args.rs index 54836b0a3f538..a774955c1e8a9 100644 --- a/src/test/ui/no-patterns-in-args.rs +++ b/src/test/ui/no-patterns-in-args.rs @@ -1,10 +1,10 @@ -extern "C" { +extern { fn f1(mut arg: u8); //~ ERROR patterns aren't allowed in foreign function declarations fn f2(&arg: u8); //~ ERROR patterns aren't allowed in foreign function declarations fn f3(arg @ _: u8); //~ ERROR patterns aren't allowed in foreign function declarations fn g1(arg: u8); // OK fn g2(_: u8); // OK -// fn g3(u8); // Not yet + // fn g3(u8); // Not yet } type A1 = fn(mut arg: u8); //~ ERROR patterns aren't allowed in function pointer types diff --git a/src/test/ui/no_owned_box_lang_item.rs b/src/test/ui/no_owned_box_lang_item.rs index c22b44ffca2a4..bef630d826c0f 100644 --- a/src/test/ui/no_owned_box_lang_item.rs +++ b/src/test/ui/no_owned_box_lang_item.rs @@ -11,6 +11,6 @@ fn main() { let x = box 1i32; } -#[lang = "eh_personality"] extern "C" fn eh_personality() {} +#[lang = "eh_personality"] extern fn eh_personality() {} #[lang = "eh_catch_typeinfo"] static EH_CATCH_TYPEINFO: u8 = 0; #[lang = "panic_impl"] fn panic_impl(panic: &PanicInfo) -> ! { loop {} } diff --git a/src/test/ui/non-built-in-quote.rs b/src/test/ui/non-built-in-quote.rs new file mode 100644 index 0000000000000..92efa99e3969d --- /dev/null +++ b/src/test/ui/non-built-in-quote.rs @@ -0,0 +1,8 @@ +// run-pass +// pretty-expanded FIXME #23616 + +macro_rules! quote_tokens { () => (()) } + +pub fn main() { + quote_tokens!(); +} diff --git a/src/test/ui/nullable-pointer-size.rs b/src/test/ui/nullable-pointer-size.rs index 0384553b6993f..63a106f129282 100644 --- a/src/test/ui/nullable-pointer-size.rs +++ b/src/test/ui/nullable-pointer-size.rs @@ -31,5 +31,5 @@ macro_rules! check_type { pub fn main() { check_type!(&'static isize); check_type!(Box); - check_type!(extern "C" fn()); + check_type!(extern fn()); } diff --git a/src/test/ui/associated-types/object-method-numbering.rs b/src/test/ui/object-method-numbering.rs similarity index 100% rename from src/test/ui/associated-types/object-method-numbering.rs rename to src/test/ui/object-method-numbering.rs diff --git a/src/test/ui/osx-frameworks.rs b/src/test/ui/osx-frameworks.rs index 31b853e24fe5b..227e07de9a81e 100644 --- a/src/test/ui/osx-frameworks.rs +++ b/src/test/ui/osx-frameworks.rs @@ -1,7 +1,8 @@ // ignore-macos this is supposed to succeed on osx #[link(name = "foo", kind = "framework")] -extern "C" {} +extern {} //~^^ ERROR: native frameworks are only available on macOS -fn main() {} +fn main() { +} diff --git a/src/test/ui/panic-runtime/auxiliary/panic-runtime-abort.rs b/src/test/ui/panic-runtime/auxiliary/panic-runtime-abort.rs index c92015eeebcc2..433301fb43441 100644 --- a/src/test/ui/panic-runtime/auxiliary/panic-runtime-abort.rs +++ b/src/test/ui/panic-runtime/auxiliary/panic-runtime-abort.rs @@ -8,10 +8,10 @@ #![panic_runtime] #[no_mangle] -pub extern "C" fn __rust_maybe_catch_panic() {} +pub extern fn __rust_maybe_catch_panic() {} #[no_mangle] -pub extern "C" fn __rust_start_panic() {} +pub extern fn __rust_start_panic() {} #[no_mangle] -pub extern "C" fn rust_eh_personality() {} +pub extern fn rust_eh_personality() {} diff --git a/src/test/ui/panic-runtime/auxiliary/panic-runtime-unwind.rs b/src/test/ui/panic-runtime/auxiliary/panic-runtime-unwind.rs index 2f7aed9248a06..97452a342ab4d 100644 --- a/src/test/ui/panic-runtime/auxiliary/panic-runtime-unwind.rs +++ b/src/test/ui/panic-runtime/auxiliary/panic-runtime-unwind.rs @@ -8,10 +8,10 @@ #![panic_runtime] #[no_mangle] -pub extern "C" fn __rust_maybe_catch_panic() {} +pub extern fn __rust_maybe_catch_panic() {} #[no_mangle] -pub extern "C" fn __rust_start_panic() {} +pub extern fn __rust_start_panic() {} #[no_mangle] -pub extern "C" fn rust_eh_personality() {} +pub extern fn rust_eh_personality() {} diff --git a/src/test/ui/panic-runtime/auxiliary/panic-runtime-unwind2.rs b/src/test/ui/panic-runtime/auxiliary/panic-runtime-unwind2.rs index 2f7aed9248a06..97452a342ab4d 100644 --- a/src/test/ui/panic-runtime/auxiliary/panic-runtime-unwind2.rs +++ b/src/test/ui/panic-runtime/auxiliary/panic-runtime-unwind2.rs @@ -8,10 +8,10 @@ #![panic_runtime] #[no_mangle] -pub extern "C" fn __rust_maybe_catch_panic() {} +pub extern fn __rust_maybe_catch_panic() {} #[no_mangle] -pub extern "C" fn __rust_start_panic() {} +pub extern fn __rust_start_panic() {} #[no_mangle] -pub extern "C" fn rust_eh_personality() {} +pub extern fn rust_eh_personality() {} diff --git a/src/test/ui/parser/attrs-after-extern-mod.rs b/src/test/ui/parser/attrs-after-extern-mod.rs index e3f0fa0fc46ac..ea899dca7b221 100644 --- a/src/test/ui/parser/attrs-after-extern-mod.rs +++ b/src/test/ui/parser/attrs-after-extern-mod.rs @@ -2,6 +2,6 @@ fn main() {} -extern "C" { +extern { #[cfg(stage37)] //~ ERROR expected item after attributes } diff --git a/src/test/ui/parser/attrs-after-extern-mod.stderr b/src/test/ui/parser/attrs-after-extern-mod.stderr index 135d98457e197..3862f5c379fc3 100644 --- a/src/test/ui/parser/attrs-after-extern-mod.stderr +++ b/src/test/ui/parser/attrs-after-extern-mod.stderr @@ -1,8 +1,8 @@ error: expected item after attributes --> $DIR/attrs-after-extern-mod.rs:6:5 | -LL | extern "C" { - | - while parsing this item list starting here +LL | extern { + | - while parsing this item list starting here LL | #[cfg(stage37)] | ^^^^^^^^^^^^^^^ LL | } diff --git a/src/test/ui/parser/doc-before-extern-rbrace.rs b/src/test/ui/parser/doc-before-extern-rbrace.rs index 515c90ed48c04..040206b80ffd0 100644 --- a/src/test/ui/parser/doc-before-extern-rbrace.rs +++ b/src/test/ui/parser/doc-before-extern-rbrace.rs @@ -1,6 +1,6 @@ fn main() {} -extern "C" { +extern { /// hi //~^ ERROR found a documentation comment that doesn't document anything } diff --git a/src/test/ui/parser/duplicate-visibility.rs b/src/test/ui/parser/duplicate-visibility.rs index 547329cfb1b84..31318ae3a096c 100644 --- a/src/test/ui/parser/duplicate-visibility.rs +++ b/src/test/ui/parser/duplicate-visibility.rs @@ -1,6 +1,6 @@ fn main() {} -extern "C" { +extern { pub pub fn foo(); //~^ ERROR visibility `pub` is not followed by an item //~| ERROR non-item in item list diff --git a/src/test/ui/parser/duplicate-visibility.stderr b/src/test/ui/parser/duplicate-visibility.stderr index 8d8122292ae9a..36b9efd9dca6e 100644 --- a/src/test/ui/parser/duplicate-visibility.stderr +++ b/src/test/ui/parser/duplicate-visibility.stderr @@ -9,8 +9,8 @@ LL | pub pub fn foo(); error: non-item in item list --> $DIR/duplicate-visibility.rs:4:9 | -LL | extern "C" { - | - item list starts here +LL | extern { + | - item list starts here LL | pub pub fn foo(); | ^^^ non-item starts here ... diff --git a/src/test/ui/parser/extern-no-fn.rs b/src/test/ui/parser/extern-no-fn.rs index 73568609cdfce..d9f35e0eb5cfc 100644 --- a/src/test/ui/parser/extern-no-fn.rs +++ b/src/test/ui/parser/extern-no-fn.rs @@ -1,4 +1,4 @@ -extern "C" { +extern { f(); //~ ERROR expected one of `!` or `::`, found `(` } diff --git a/src/test/ui/parser/extern-no-fn.stderr b/src/test/ui/parser/extern-no-fn.stderr index d9183d5646360..0151cb4235b0d 100644 --- a/src/test/ui/parser/extern-no-fn.stderr +++ b/src/test/ui/parser/extern-no-fn.stderr @@ -1,8 +1,8 @@ error: expected one of `!` or `::`, found `(` --> $DIR/extern-no-fn.rs:2:6 | -LL | extern "C" { - | - while parsing this item list starting here +LL | extern { + | - while parsing this item list starting here LL | f(); | ^ expected one of `!` or `::` LL | } diff --git a/src/test/ui/parser/fn-body-eq-expr-semi.rs b/src/test/ui/parser/fn-body-eq-expr-semi.rs index 7127ba8da6148..09444079365bf 100644 --- a/src/test/ui/parser/fn-body-eq-expr-semi.rs +++ b/src/test/ui/parser/fn-body-eq-expr-semi.rs @@ -5,7 +5,7 @@ fn syntax() { fn bar() -> u8 = 42; //~ ERROR function body cannot be `= expression;` } -extern "C" { +extern { fn foo() = 42; //~ ERROR function body cannot be `= expression;` //~^ ERROR incorrect function inside `extern` block fn bar() -> u8 = 42; //~ ERROR function body cannot be `= expression;` diff --git a/src/test/ui/parser/fn-body-eq-expr-semi.stderr b/src/test/ui/parser/fn-body-eq-expr-semi.stderr index fdc7a9409d733..739133e0b408b 100644 --- a/src/test/ui/parser/fn-body-eq-expr-semi.stderr +++ b/src/test/ui/parser/fn-body-eq-expr-semi.stderr @@ -89,8 +89,8 @@ LL | fn bar() -> u8 { 42 } error: incorrect function inside `extern` block --> $DIR/fn-body-eq-expr-semi.rs:9:8 | -LL | extern "C" { - | ---------- `extern` blocks define existing foreign functions and functions inside of them cannot have a body +LL | extern { + | ------ `extern` blocks define existing foreign functions and functions inside of them cannot have a body LL | fn foo() = 42; | ^^^ ----- help: remove the invalid body: `;` | | @@ -102,8 +102,8 @@ LL | fn foo() = 42; error: incorrect function inside `extern` block --> $DIR/fn-body-eq-expr-semi.rs:11:8 | -LL | extern "C" { - | ---------- `extern` blocks define existing foreign functions and functions inside of them cannot have a body +LL | extern { + | ------ `extern` blocks define existing foreign functions and functions inside of them cannot have a body ... LL | fn bar() -> u8 = 42; | ^^^ ----- help: remove the invalid body: `;` diff --git a/src/test/ui/parser/fn-body-optional-semantic-fail.rs b/src/test/ui/parser/fn-body-optional-semantic-fail.rs index 12df488802ecd..38def05e8f2b3 100644 --- a/src/test/ui/parser/fn-body-optional-semantic-fail.rs +++ b/src/test/ui/parser/fn-body-optional-semantic-fail.rs @@ -20,7 +20,7 @@ fn main() { fn f4() {} // OK. } - extern "C" { + extern { fn f5(); // OK. fn f6() {} //~ ERROR incorrect function inside `extern` block } diff --git a/src/test/ui/parser/fn-body-optional-semantic-fail.stderr b/src/test/ui/parser/fn-body-optional-semantic-fail.stderr index 14bcd7c16faa1..23ce98fb5d787 100644 --- a/src/test/ui/parser/fn-body-optional-semantic-fail.stderr +++ b/src/test/ui/parser/fn-body-optional-semantic-fail.stderr @@ -25,8 +25,8 @@ LL | fn f3(); error: incorrect function inside `extern` block --> $DIR/fn-body-optional-semantic-fail.rs:25:12 | -LL | extern "C" { - | ---------- `extern` blocks define existing foreign functions and functions inside of them cannot have a body +LL | extern { + | ------ `extern` blocks define existing foreign functions and functions inside of them cannot have a body LL | fn f5(); // OK. LL | fn f6() {} | ^^ -- help: remove the invalid body: `;` diff --git a/src/test/ui/parser/fn-body-optional-syntactic-pass.rs b/src/test/ui/parser/fn-body-optional-syntactic-pass.rs index f9dbebf0bea18..e7991c73b4b77 100644 --- a/src/test/ui/parser/fn-body-optional-syntactic-pass.rs +++ b/src/test/ui/parser/fn-body-optional-syntactic-pass.rs @@ -24,8 +24,8 @@ fn syntax() { fn f() {} } - extern "C" { - fn f(); + extern { fn f(); + fn f() {} } } diff --git a/src/test/ui/parser/fn-header-semantic-fail.rs b/src/test/ui/parser/fn-header-semantic-fail.rs index 0bbaeec0c7fec..c327667f4cdc7 100644 --- a/src/test/ui/parser/fn-header-semantic-fail.rs +++ b/src/test/ui/parser/fn-header-semantic-fail.rs @@ -47,7 +47,7 @@ fn main() { //~^ ERROR functions cannot be both `const` and `async` } - extern "C" { + extern { async fn fe1(); //~ ERROR functions in `extern` blocks cannot have qualifiers unsafe fn fe2(); //~ ERROR functions in `extern` blocks cannot have qualifiers const fn fe3(); //~ ERROR functions in `extern` blocks cannot have qualifiers diff --git a/src/test/ui/parser/fn-header-semantic-fail.stderr b/src/test/ui/parser/fn-header-semantic-fail.stderr index 4fde243b2f8ec..2f11f95bf4a7f 100644 --- a/src/test/ui/parser/fn-header-semantic-fail.stderr +++ b/src/test/ui/parser/fn-header-semantic-fail.stderr @@ -105,8 +105,8 @@ LL | const async unsafe extern "C" fn fi5() {} error: functions in `extern` blocks cannot have qualifiers --> $DIR/fn-header-semantic-fail.rs:51:18 | -LL | extern "C" { - | ---------- in this `extern` block +LL | extern { + | ------ in this `extern` block LL | async fn fe1(); | ^^^ | @@ -118,8 +118,8 @@ LL | fn fe1(); error: functions in `extern` blocks cannot have qualifiers --> $DIR/fn-header-semantic-fail.rs:52:19 | -LL | extern "C" { - | ---------- in this `extern` block +LL | extern { + | ------ in this `extern` block LL | async fn fe1(); LL | unsafe fn fe2(); | ^^^ @@ -132,8 +132,8 @@ LL | fn fe2(); error: functions in `extern` blocks cannot have qualifiers --> $DIR/fn-header-semantic-fail.rs:53:18 | -LL | extern "C" { - | ---------- in this `extern` block +LL | extern { + | ------ in this `extern` block ... LL | const fn fe3(); | ^^^ @@ -146,8 +146,8 @@ LL | fn fe3(); error: functions in `extern` blocks cannot have qualifiers --> $DIR/fn-header-semantic-fail.rs:54:23 | -LL | extern "C" { - | ---------- in this `extern` block +LL | extern { + | ------ in this `extern` block ... LL | extern "C" fn fe4(); | ^^^ @@ -160,8 +160,8 @@ LL | fn fe4(); error: functions in `extern` blocks cannot have qualifiers --> $DIR/fn-header-semantic-fail.rs:55:42 | -LL | extern "C" { - | ---------- in this `extern` block +LL | extern { + | ------ in this `extern` block ... LL | const async unsafe extern "C" fn fe5(); | ^^^ diff --git a/src/test/ui/parser/fn-header-syntactic-pass.rs b/src/test/ui/parser/fn-header-syntactic-pass.rs index 68f1f7901bb78..9e44541993d92 100644 --- a/src/test/ui/parser/fn-header-syntactic-pass.rs +++ b/src/test/ui/parser/fn-header-syntactic-pass.rs @@ -37,11 +37,11 @@ fn syntax() { const async unsafe extern "C" fn f(); } - extern "C" { - fn f(); - fn f(); - fn f(); - fn f(); - fn f(); + extern { + async fn f(); + unsafe fn f(); + const fn f(); + extern "C" fn f(); + const async unsafe extern "C" fn f(); } } diff --git a/src/test/ui/parser/foreign-const-semantic-fail.rs b/src/test/ui/parser/foreign-const-semantic-fail.rs index c9940b74aa2a0..82978e655ba38 100644 --- a/src/test/ui/parser/foreign-const-semantic-fail.rs +++ b/src/test/ui/parser/foreign-const-semantic-fail.rs @@ -1,6 +1,6 @@ fn main() {} -extern "C" { +extern { const A: isize; //~^ ERROR extern items cannot be `const` const B: isize = 42; diff --git a/src/test/ui/parser/foreign-const-semantic-fail.stderr b/src/test/ui/parser/foreign-const-semantic-fail.stderr index 8dc66c0d012ca..f529b3ad87b2f 100644 --- a/src/test/ui/parser/foreign-const-semantic-fail.stderr +++ b/src/test/ui/parser/foreign-const-semantic-fail.stderr @@ -21,8 +21,8 @@ LL | const B: isize = 42; error: incorrect `static` inside `extern` block --> $DIR/foreign-const-semantic-fail.rs:6:11 | -LL | extern "C" { - | ---------- `extern` blocks define existing foreign statics and statics inside of them cannot have a body +LL | extern { + | ------ `extern` blocks define existing foreign statics and statics inside of them cannot have a body ... LL | const B: isize = 42; | ^ -- the invalid body diff --git a/src/test/ui/parser/foreign-const-syntactic-fail.rs b/src/test/ui/parser/foreign-const-syntactic-fail.rs index a6e77f846638e..a78f8b1623a80 100644 --- a/src/test/ui/parser/foreign-const-syntactic-fail.rs +++ b/src/test/ui/parser/foreign-const-syntactic-fail.rs @@ -3,7 +3,7 @@ fn main() {} #[cfg(FALSE)] -extern "C" { +extern { const A: isize; //~ ERROR extern items cannot be `const` const B: isize = 42; //~ ERROR extern items cannot be `const` } diff --git a/src/test/ui/parser/foreign-static-semantic-fail.rs b/src/test/ui/parser/foreign-static-semantic-fail.rs index 3d427ed0efdfc..9abdf33df9c46 100644 --- a/src/test/ui/parser/foreign-static-semantic-fail.rs +++ b/src/test/ui/parser/foreign-static-semantic-fail.rs @@ -2,7 +2,7 @@ fn main() {} -extern "C" { +extern { static X: u8 = 0; //~ ERROR incorrect `static` inside `extern` block static mut Y: u8 = 0; //~ ERROR incorrect `static` inside `extern` block } diff --git a/src/test/ui/parser/foreign-static-semantic-fail.stderr b/src/test/ui/parser/foreign-static-semantic-fail.stderr index 105508cfefaaf..5942e3a94497b 100644 --- a/src/test/ui/parser/foreign-static-semantic-fail.stderr +++ b/src/test/ui/parser/foreign-static-semantic-fail.stderr @@ -1,8 +1,8 @@ error: incorrect `static` inside `extern` block --> $DIR/foreign-static-semantic-fail.rs:6:12 | -LL | extern "C" { - | ---------- `extern` blocks define existing foreign statics and statics inside of them cannot have a body +LL | extern { + | ------ `extern` blocks define existing foreign statics and statics inside of them cannot have a body LL | static X: u8 = 0; | ^ - the invalid body | | @@ -13,8 +13,8 @@ LL | static X: u8 = 0; error: incorrect `static` inside `extern` block --> $DIR/foreign-static-semantic-fail.rs:7:16 | -LL | extern "C" { - | ---------- `extern` blocks define existing foreign statics and statics inside of them cannot have a body +LL | extern { + | ------ `extern` blocks define existing foreign statics and statics inside of them cannot have a body LL | static X: u8 = 0; LL | static mut Y: u8 = 0; | ^ - the invalid body diff --git a/src/test/ui/parser/foreign-static-syntactic-pass.rs b/src/test/ui/parser/foreign-static-syntactic-pass.rs index 599496346173a..2c805e8a0b700 100644 --- a/src/test/ui/parser/foreign-static-syntactic-pass.rs +++ b/src/test/ui/parser/foreign-static-syntactic-pass.rs @@ -5,7 +5,7 @@ fn main() {} #[cfg(FALSE)] -extern "C" { - static X: u8; - static mut Y: u8; +extern { + static X: u8 = 0; + static mut Y: u8 = 0; } diff --git a/src/test/ui/parser/no-const-fn-in-extern-block.rs b/src/test/ui/parser/no-const-fn-in-extern-block.rs index 1993124edc394..4cae703a16395 100644 --- a/src/test/ui/parser/no-const-fn-in-extern-block.rs +++ b/src/test/ui/parser/no-const-fn-in-extern-block.rs @@ -1,4 +1,4 @@ -extern "C" { +extern { const fn foo(); //~^ ERROR functions in `extern` blocks cannot have qualifiers const unsafe fn bar(); diff --git a/src/test/ui/parser/no-const-fn-in-extern-block.stderr b/src/test/ui/parser/no-const-fn-in-extern-block.stderr index 04fc8c85e4f03..af92f2d94f2cc 100644 --- a/src/test/ui/parser/no-const-fn-in-extern-block.stderr +++ b/src/test/ui/parser/no-const-fn-in-extern-block.stderr @@ -1,8 +1,8 @@ error: functions in `extern` blocks cannot have qualifiers --> $DIR/no-const-fn-in-extern-block.rs:2:14 | -LL | extern "C" { - | ---------- in this `extern` block +LL | extern { + | ------ in this `extern` block LL | const fn foo(); | ^^^ | @@ -14,8 +14,8 @@ LL | fn foo(); error: functions in `extern` blocks cannot have qualifiers --> $DIR/no-const-fn-in-extern-block.rs:4:21 | -LL | extern "C" { - | ---------- in this `extern` block +LL | extern { + | ------ in this `extern` block ... LL | const unsafe fn bar(); | ^^^ diff --git a/src/test/ui/parser/self-param-semantic-fail.rs b/src/test/ui/parser/self-param-semantic-fail.rs index 621aab279aa4a..5676971b01ae4 100644 --- a/src/test/ui/parser/self-param-semantic-fail.rs +++ b/src/test/ui/parser/self-param-semantic-fail.rs @@ -23,7 +23,7 @@ fn free() { //~^ ERROR `self` parameter is only allowed in associated functions } -extern "C" { +extern { fn f1(self); //~^ ERROR `self` parameter is only allowed in associated functions fn f2(mut self); @@ -40,8 +40,8 @@ extern "C" { fn f7(self: u8); //~^ ERROR `self` parameter is only allowed in associated functions fn f8(mut self: u8); -//~^ ERROR `self` parameter is only allowed in associated functions -//~| ERROR patterns aren't allowed in + //~^ ERROR `self` parameter is only allowed in associated functions + //~| ERROR patterns aren't allowed in } type X1 = fn(self); diff --git a/src/test/ui/parser/self-param-syntactic-pass.rs b/src/test/ui/parser/self-param-syntactic-pass.rs index d7bb7863c07d6..9e215e6cdd4b7 100644 --- a/src/test/ui/parser/self-param-syntactic-pass.rs +++ b/src/test/ui/parser/self-param-syntactic-pass.rs @@ -18,7 +18,7 @@ fn free() { } #[cfg(FALSE)] -extern "C" { +extern { fn f(self); fn f(mut self); fn f(&self); diff --git a/src/test/ui/parser/unsafe-foreign-mod.rs b/src/test/ui/parser/unsafe-foreign-mod.rs index eab134a4a4de4..872af95bd225b 100644 --- a/src/test/ui/parser/unsafe-foreign-mod.rs +++ b/src/test/ui/parser/unsafe-foreign-mod.rs @@ -1,3 +1,7 @@ +unsafe extern { + //~^ ERROR extern block cannot be declared unsafe +} + unsafe extern "C" { //~^ ERROR extern block cannot be declared unsafe } diff --git a/src/test/ui/parser/unsafe-foreign-mod.stderr b/src/test/ui/parser/unsafe-foreign-mod.stderr index 4acf72c5dae89..5e10988051ea0 100644 --- a/src/test/ui/parser/unsafe-foreign-mod.stderr +++ b/src/test/ui/parser/unsafe-foreign-mod.stderr @@ -1,8 +1,14 @@ error: extern block cannot be declared unsafe --> $DIR/unsafe-foreign-mod.rs:1:1 | +LL | unsafe extern { + | ^^^^^^ + +error: extern block cannot be declared unsafe + --> $DIR/unsafe-foreign-mod.rs:5:1 + | LL | unsafe extern "C" { | ^^^^^^ -error: aborting due to previous error +error: aborting due to 2 previous errors diff --git a/src/test/ui/parser/variadic-ffi-semantic-restrictions.rs b/src/test/ui/parser/variadic-ffi-semantic-restrictions.rs index 404f409075519..aa85f6d6b522b 100644 --- a/src/test/ui/parser/variadic-ffi-semantic-restrictions.rs +++ b/src/test/ui/parser/variadic-ffi-semantic-restrictions.rs @@ -20,22 +20,22 @@ extern "C" fn f2_3(..., x: isize) {} //~^ ERROR only foreign or `unsafe extern "C" functions may be C-variadic //~| ERROR `...` must be the last argument of a C-variadic function -extern "C" fn f3_1(x: isize, ...) {} +extern fn f3_1(x: isize, ...) {} //~^ ERROR only foreign or `unsafe extern "C" functions may be C-variadic -extern "C" fn f3_2(...) {} +extern fn f3_2(...) {} //~^ ERROR only foreign or `unsafe extern "C" functions may be C-variadic //~| ERROR C-variadic function must be declared with at least one named argument -extern "C" fn f3_3(..., x: isize) {} +extern fn f3_3(..., x: isize) {} //~^ ERROR only foreign or `unsafe extern "C" functions may be C-variadic //~| ERROR `...` must be the last argument of a C-variadic function -extern "C" { +extern { fn e_f1(...); //~^ ERROR C-variadic function must be declared with at least one named argument fn e_f2(..., x: isize); -//~^ ERROR `...` must be the last argument of a C-variadic function + //~^ ERROR `...` must be the last argument of a C-variadic function } struct X; diff --git a/src/test/ui/parser/variadic-ffi-semantic-restrictions.stderr b/src/test/ui/parser/variadic-ffi-semantic-restrictions.stderr index ebfe4979fb6f2..3f3ddfed14a66 100644 --- a/src/test/ui/parser/variadic-ffi-semantic-restrictions.stderr +++ b/src/test/ui/parser/variadic-ffi-semantic-restrictions.stderr @@ -47,34 +47,34 @@ LL | extern "C" fn f2_3(..., x: isize) {} | ^^^ error: only foreign or `unsafe extern "C" functions may be C-variadic - --> $DIR/variadic-ffi-semantic-restrictions.rs:23:30 + --> $DIR/variadic-ffi-semantic-restrictions.rs:23:26 | -LL | extern "C" fn f3_1(x: isize, ...) {} - | ^^^ +LL | extern fn f3_1(x: isize, ...) {} + | ^^^ error: C-variadic function must be declared with at least one named argument - --> $DIR/variadic-ffi-semantic-restrictions.rs:26:20 + --> $DIR/variadic-ffi-semantic-restrictions.rs:26:16 | -LL | extern "C" fn f3_2(...) {} - | ^^^ +LL | extern fn f3_2(...) {} + | ^^^ error: only foreign or `unsafe extern "C" functions may be C-variadic - --> $DIR/variadic-ffi-semantic-restrictions.rs:26:20 + --> $DIR/variadic-ffi-semantic-restrictions.rs:26:16 | -LL | extern "C" fn f3_2(...) {} - | ^^^ +LL | extern fn f3_2(...) {} + | ^^^ error: `...` must be the last argument of a C-variadic function - --> $DIR/variadic-ffi-semantic-restrictions.rs:30:20 + --> $DIR/variadic-ffi-semantic-restrictions.rs:30:16 | -LL | extern "C" fn f3_3(..., x: isize) {} - | ^^^ +LL | extern fn f3_3(..., x: isize) {} + | ^^^ error: only foreign or `unsafe extern "C" functions may be C-variadic - --> $DIR/variadic-ffi-semantic-restrictions.rs:30:20 + --> $DIR/variadic-ffi-semantic-restrictions.rs:30:16 | -LL | extern "C" fn f3_3(..., x: isize) {} - | ^^^ +LL | extern fn f3_3(..., x: isize) {} + | ^^^ error: C-variadic function must be declared with at least one named argument --> $DIR/variadic-ffi-semantic-restrictions.rs:35:13 diff --git a/src/test/ui/pattern/issue-74539.stderr b/src/test/ui/pattern/issue-74539.stderr index f7644c19ea0d9..cbc90b5397d8b 100644 --- a/src/test/ui/pattern/issue-74539.stderr +++ b/src/test/ui/pattern/issue-74539.stderr @@ -26,11 +26,6 @@ LL | A(u8, u8), ... LL | E::A(x @ ..) => { | ^^^^^^^^^^^^ expected 2 fields, found 1 - | -help: use `_` to explicitly ignore each field - | -LL | E::A(x @ .., _) => { - | ^^^ error: aborting due to 3 previous errors diff --git a/src/test/ui/pattern/pat-tuple-underfield.rs b/src/test/ui/pattern/pat-tuple-underfield.rs deleted file mode 100644 index ed852a47bb4ee..0000000000000 --- a/src/test/ui/pattern/pat-tuple-underfield.rs +++ /dev/null @@ -1,55 +0,0 @@ -struct S(i32, f32); -enum E { - S(i32, f32), -} -struct Point4(i32, i32, i32, i32); - -fn main() { - match S(0, 1.0) { - S(x) => {} - //~^ ERROR this pattern has 1 field, but the corresponding tuple struct has 2 fields - //~| HELP use `_` to explicitly ignore each field - } - match S(0, 1.0) { - S(_) => {} - //~^ ERROR this pattern has 1 field, but the corresponding tuple struct has 2 fields - //~| HELP use `_` to explicitly ignore each field - //~| HELP use `..` to ignore all fields - } - match S(0, 1.0) { - S() => {} - //~^ ERROR this pattern has 0 fields, but the corresponding tuple struct has 2 fields - //~| HELP use `_` to explicitly ignore each field - //~| HELP use `..` to ignore all fields - } - - match E::S(0, 1.0) { - E::S(x) => {} - //~^ ERROR this pattern has 1 field, but the corresponding tuple variant has 2 fields - //~| HELP use `_` to explicitly ignore each field - } - match E::S(0, 1.0) { - E::S(_) => {} - //~^ ERROR this pattern has 1 field, but the corresponding tuple variant has 2 fields - //~| HELP use `_` to explicitly ignore each field - //~| HELP use `..` to ignore all fields - } - match E::S(0, 1.0) { - E::S() => {} - //~^ ERROR this pattern has 0 fields, but the corresponding tuple variant has 2 fields - //~| HELP use `_` to explicitly ignore each field - //~| HELP use `..` to ignore all fields - } - match E::S(0, 1.0) { - E::S => {} - //~^ ERROR expected unit struct, unit variant or constant, found tuple variant `E::S` - //~| HELP use the tuple variant pattern syntax instead - } - - match Point4(0, 1, 2, 3) { - Point4( a , _ ) => {} - //~^ ERROR this pattern has 2 fields, but the corresponding tuple struct has 4 fields - //~| HELP use `_` to explicitly ignore each field - //~| HELP use `..` to ignore the rest of the fields - } -} diff --git a/src/test/ui/pattern/pat-tuple-underfield.stderr b/src/test/ui/pattern/pat-tuple-underfield.stderr deleted file mode 100644 index 76323d9a7bf56..0000000000000 --- a/src/test/ui/pattern/pat-tuple-underfield.stderr +++ /dev/null @@ -1,131 +0,0 @@ -error[E0532]: expected unit struct, unit variant or constant, found tuple variant `E::S` - --> $DIR/pat-tuple-underfield.rs:44:9 - | -LL | S(i32, f32), - | ----------- `E::S` defined here -... -LL | E::S => {} - | ^^^^ help: use the tuple variant pattern syntax instead: `E::S(_, _)` - -error[E0023]: this pattern has 1 field, but the corresponding tuple struct has 2 fields - --> $DIR/pat-tuple-underfield.rs:9:9 - | -LL | struct S(i32, f32); - | ------------------- tuple struct defined here -... -LL | S(x) => {} - | ^^^^ expected 2 fields, found 1 - | -help: use `_` to explicitly ignore each field - | -LL | S(x, _) => {} - | ^^^ - -error[E0023]: this pattern has 1 field, but the corresponding tuple struct has 2 fields - --> $DIR/pat-tuple-underfield.rs:14:9 - | -LL | struct S(i32, f32); - | ------------------- tuple struct defined here -... -LL | S(_) => {} - | ^^^^ expected 2 fields, found 1 - | -help: use `_` to explicitly ignore each field - | -LL | S(_, _) => {} - | ^^^ -help: use `..` to ignore all fields - | -LL | S(..) => {} - | ^^ - -error[E0023]: this pattern has 0 fields, but the corresponding tuple struct has 2 fields - --> $DIR/pat-tuple-underfield.rs:20:9 - | -LL | struct S(i32, f32); - | ------------------- tuple struct defined here -... -LL | S() => {} - | ^^^ expected 2 fields, found 0 - | -help: use `_` to explicitly ignore each field - | -LL | S(_, _) => {} - | ^^^^ -help: use `..` to ignore all fields - | -LL | S(..) => {} - | ^^ - -error[E0023]: this pattern has 1 field, but the corresponding tuple variant has 2 fields - --> $DIR/pat-tuple-underfield.rs:27:9 - | -LL | S(i32, f32), - | ----------- tuple variant defined here -... -LL | E::S(x) => {} - | ^^^^^^^ expected 2 fields, found 1 - | -help: use `_` to explicitly ignore each field - | -LL | E::S(x, _) => {} - | ^^^ - -error[E0023]: this pattern has 1 field, but the corresponding tuple variant has 2 fields - --> $DIR/pat-tuple-underfield.rs:32:9 - | -LL | S(i32, f32), - | ----------- tuple variant defined here -... -LL | E::S(_) => {} - | ^^^^^^^ expected 2 fields, found 1 - | -help: use `_` to explicitly ignore each field - | -LL | E::S(_, _) => {} - | ^^^ -help: use `..` to ignore all fields - | -LL | E::S(..) => {} - | ^^ - -error[E0023]: this pattern has 0 fields, but the corresponding tuple variant has 2 fields - --> $DIR/pat-tuple-underfield.rs:38:9 - | -LL | S(i32, f32), - | ----------- tuple variant defined here -... -LL | E::S() => {} - | ^^^^^^ expected 2 fields, found 0 - | -help: use `_` to explicitly ignore each field - | -LL | E::S(_, _) => {} - | ^^^^ -help: use `..` to ignore all fields - | -LL | E::S(..) => {} - | ^^ - -error[E0023]: this pattern has 2 fields, but the corresponding tuple struct has 4 fields - --> $DIR/pat-tuple-underfield.rs:50:9 - | -LL | struct Point4(i32, i32, i32, i32); - | ---------------------------------- tuple struct defined here -... -LL | Point4( a , _ ) => {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ expected 4 fields, found 2 - | -help: use `_` to explicitly ignore each field - | -LL | Point4( a , _ , _, _) => {} - | ^^^^^^ -help: use `..` to ignore the rest of the fields - | -LL | Point4( a , _ , ..) => {} - | ^^^^ - -error: aborting due to 8 previous errors - -Some errors have detailed explanations: E0023, E0532. -For more information about an error, try `rustc --explain E0023`. diff --git a/src/test/ui/impl-trait/point-to-type-err-cause-on-impl-trait-return.rs b/src/test/ui/point-to-type-err-cause-on-impl-trait-return.rs similarity index 100% rename from src/test/ui/impl-trait/point-to-type-err-cause-on-impl-trait-return.rs rename to src/test/ui/point-to-type-err-cause-on-impl-trait-return.rs diff --git a/src/test/ui/impl-trait/point-to-type-err-cause-on-impl-trait-return.stderr b/src/test/ui/point-to-type-err-cause-on-impl-trait-return.stderr similarity index 100% rename from src/test/ui/impl-trait/point-to-type-err-cause-on-impl-trait-return.stderr rename to src/test/ui/point-to-type-err-cause-on-impl-trait-return.stderr diff --git a/src/test/ui/privacy/priv-in-bad-locations.rs b/src/test/ui/priv-in-bad-locations.rs similarity index 82% rename from src/test/ui/privacy/priv-in-bad-locations.rs rename to src/test/ui/priv-in-bad-locations.rs index 76af8c6cde801..b9f5d4c358657 100644 --- a/src/test/ui/privacy/priv-in-bad-locations.rs +++ b/src/test/ui/priv-in-bad-locations.rs @@ -1,4 +1,4 @@ -pub extern "C" { //~ ERROR unnecessary visibility qualifier +pub extern { //~ ERROR unnecessary visibility qualifier pub fn bar(); } diff --git a/src/test/ui/privacy/priv-in-bad-locations.stderr b/src/test/ui/priv-in-bad-locations.stderr similarity index 97% rename from src/test/ui/privacy/priv-in-bad-locations.stderr rename to src/test/ui/priv-in-bad-locations.stderr index 75bd2fe47b756..713568f879dad 100644 --- a/src/test/ui/privacy/priv-in-bad-locations.stderr +++ b/src/test/ui/priv-in-bad-locations.stderr @@ -1,7 +1,7 @@ error[E0449]: unnecessary visibility qualifier --> $DIR/priv-in-bad-locations.rs:1:1 | -LL | pub extern "C" { +LL | pub extern { | ^^^ `pub` not permitted here because it's implied | = note: place qualifiers on individual foreign items instead diff --git a/src/test/ui/privacy/privacy1.rs b/src/test/ui/privacy/privacy1.rs index 3c9fa983dfd1e..e28fd13b97f23 100644 --- a/src/test/ui/privacy/privacy1.rs +++ b/src/test/ui/privacy/privacy1.rs @@ -61,7 +61,7 @@ mod bar { pub fn bar() {} } - extern "C" { + extern { fn epriv(); pub fn epub(); } diff --git a/src/test/ui/privacy/private-in-public-warn.rs b/src/test/ui/privacy/private-in-public-warn.rs index 09afa04501ea0..1c8706d8ad2e1 100644 --- a/src/test/ui/privacy/private-in-public-warn.rs +++ b/src/test/ui/privacy/private-in-public-warn.rs @@ -29,7 +29,7 @@ mod types { fn f2() -> Priv { panic!() } //~ ERROR private type `types::Priv` in public interface //~^ WARNING hard error } - extern "C" { + extern { pub static ES: Priv; //~ ERROR private type `types::Priv` in public interface //~^ WARNING hard error pub fn ef1(arg: Priv); //~ ERROR private type `types::Priv` in public interface diff --git a/src/test/ui/privacy/pub-extern-privacy.rs b/src/test/ui/privacy/pub-extern-privacy.rs index dbbbe4e3b7d8f..832acfbadcbd4 100644 --- a/src/test/ui/privacy/pub-extern-privacy.rs +++ b/src/test/ui/privacy/pub-extern-privacy.rs @@ -6,7 +6,7 @@ use std::mem::transmute; mod a { - extern "C" { + extern { pub fn free(x: *const u8); } } diff --git a/src/test/ui/proc-macro/ambiguous-builtin-attrs.rs b/src/test/ui/proc-macro/ambiguous-builtin-attrs.rs index 5f45f6892d2e3..142efb3c6cdcf 100644 --- a/src/test/ui/proc-macro/ambiguous-builtin-attrs.rs +++ b/src/test/ui/proc-macro/ambiguous-builtin-attrs.rs @@ -1,5 +1,5 @@ -// edition:2018 // aux-build:builtin-attrs.rs + #![feature(decl_macro)] //~ ERROR `feature` is ambiguous extern crate builtin_attrs; @@ -31,7 +31,3 @@ fn main() { Bench; NonExistent; //~ ERROR cannot find value `NonExistent` in this scope } - -use deny as allow; -#[allow(unused)] //~ ERROR `allow` is ambiguous (built-in attribute vs any other name) -fn builtin_renamed() {} diff --git a/src/test/ui/proc-macro/ambiguous-builtin-attrs.stderr b/src/test/ui/proc-macro/ambiguous-builtin-attrs.stderr index dfd60dc92cc35..276ee1cfd3562 100644 --- a/src/test/ui/proc-macro/ambiguous-builtin-attrs.stderr +++ b/src/test/ui/proc-macro/ambiguous-builtin-attrs.stderr @@ -60,20 +60,6 @@ LL | use builtin_attrs::*; | ^^^^^^^^^^^^^^^^ = help: use `crate::repr` to refer to this attribute macro unambiguously -error[E0659]: `allow` is ambiguous (built-in attribute vs any other name) - --> $DIR/ambiguous-builtin-attrs.rs:36:3 - | -LL | #[allow(unused)] - | ^^^^^ ambiguous name - | - = note: `allow` could refer to a built-in attribute -note: `allow` could also refer to the built-in attribute imported here - --> $DIR/ambiguous-builtin-attrs.rs:35:5 - | -LL | use deny as allow; - | ^^^^^^^^^^^^^ - = help: use `crate::allow` to refer to this built-in attribute unambiguously - error[E0659]: `feature` is ambiguous (built-in attribute vs any other name) --> $DIR/ambiguous-builtin-attrs.rs:3:4 | @@ -94,7 +80,7 @@ error[E0517]: attribute should be applied to a struct, enum, or union LL | fn non_macro_expanded_location<#[repr(C)] T>() { | ^ - not a struct, enum, or union -error: aborting due to 8 previous errors +error: aborting due to 7 previous errors Some errors have detailed explanations: E0425, E0517, E0659. For more information about an error, try `rustc --explain E0425`. diff --git a/src/test/ui/proc-macro/macros-in-extern-derive.rs b/src/test/ui/proc-macro/macros-in-extern-derive.rs index e52bf435a1244..d2751a353bd93 100644 --- a/src/test/ui/proc-macro/macros-in-extern-derive.rs +++ b/src/test/ui/proc-macro/macros-in-extern-derive.rs @@ -1,4 +1,4 @@ -extern "C" { +extern { #[derive(Copy)] //~ ERROR `derive` may only be applied to structs, enums and unions fn f(); } diff --git a/src/test/ui/proc-macro/macros-in-extern.rs b/src/test/ui/proc-macro/macros-in-extern.rs index 57e2066d83c58..e2b1d55aedc28 100644 --- a/src/test/ui/proc-macro/macros-in-extern.rs +++ b/src/test/ui/proc-macro/macros-in-extern.rs @@ -11,14 +11,12 @@ fn main() { } #[link(name = "rust_test_helpers", kind = "static")] -extern "C" { +extern { #[empty_attr] fn some_definitely_unknown_symbol_which_should_be_removed(); #[identity_attr] fn rust_get_test_int() -> isize; - identity!( - fn rust_dbg_extern_identity_u32(arg: u32) -> u32; - ); + identity!(fn rust_dbg_extern_identity_u32(arg: u32) -> u32;); } diff --git a/src/test/ui/proc-macro/signature.rs b/src/test/ui/proc-macro/signature.rs index e08928716b05b..dbc1577172f03 100644 --- a/src/test/ui/proc-macro/signature.rs +++ b/src/test/ui/proc-macro/signature.rs @@ -7,7 +7,7 @@ extern crate proc_macro; #[proc_macro_derive(A)] -pub unsafe extern "C" fn foo(a: i32, b: u32) -> u32 { +pub unsafe extern fn foo(a: i32, b: u32) -> u32 { //~^ ERROR: mismatched types loop {} } diff --git a/src/test/ui/proc-macro/signature.stderr b/src/test/ui/proc-macro/signature.stderr index 80a459c41257f..6ebc99601c41f 100644 --- a/src/test/ui/proc-macro/signature.stderr +++ b/src/test/ui/proc-macro/signature.stderr @@ -1,7 +1,7 @@ error[E0308]: mismatched types --> $DIR/signature.rs:10:1 | -LL | / pub unsafe extern "C" fn foo(a: i32, b: u32) -> u32 { +LL | / pub unsafe extern fn foo(a: i32, b: u32) -> u32 { LL | | LL | | loop {} LL | | } diff --git a/src/test/ui/proc-macro/span-preservation.rs b/src/test/ui/proc-macro/span-preservation.rs index 0c73586555822..b22e50c4c1715 100644 --- a/src/test/ui/proc-macro/span-preservation.rs +++ b/src/test/ui/proc-macro/span-preservation.rs @@ -35,7 +35,7 @@ fn c() { } #[recollect_attr] -extern "C" fn bar() { +extern fn bar() { 0 //~ ERROR mismatched types } diff --git a/src/test/ui/proc-macro/span-preservation.stderr b/src/test/ui/proc-macro/span-preservation.stderr index 9e91ed4068b1f..4064c5b3819ec 100644 --- a/src/test/ui/proc-macro/span-preservation.stderr +++ b/src/test/ui/proc-macro/span-preservation.stderr @@ -37,8 +37,8 @@ LL | let y = Foo { a: 10, b: 10isize }; error[E0308]: mismatched types --> $DIR/span-preservation.rs:39:5 | -LL | extern "C" fn bar() { - | - possibly return type missing here? +LL | extern fn bar() { + | - possibly return type missing here? LL | 0 | ^ expected `()`, found integer diff --git a/src/test/ui/range/issue-54505-no-std.rs b/src/test/ui/range/issue-54505-no-std.rs index ab1a025b521a9..f5d5823e468b0 100644 --- a/src/test/ui/range/issue-54505-no-std.rs +++ b/src/test/ui/range/issue-54505-no-std.rs @@ -13,7 +13,7 @@ use core::ops::RangeBounds; #[cfg(any(not(target_arch = "wasm32"), target_os = "emscripten"))] #[lang = "eh_personality"] -extern "C" fn eh_personality() {} +extern fn eh_personality() {} #[cfg(target_os = "emscripten")] #[lang = "eh_catch_typeinfo"] static EH_CATCH_TYPEINFO: u8 = 0; diff --git a/src/test/ui/resolve/resolve-primitive-fallback.stderr b/src/test/ui/resolve/resolve-primitive-fallback.stderr index 5af0aefe22b8c..8611306e82d03 100644 --- a/src/test/ui/resolve/resolve-primitive-fallback.stderr +++ b/src/test/ui/resolve/resolve-primitive-fallback.stderr @@ -22,12 +22,6 @@ LL | std::mem::size_of(u16); | ^^^^^^^^^^^^^^^^^ --- supplied 1 argument | | | expected 0 arguments - | -note: function defined here - --> $SRC_DIR/core/src/mem/mod.rs:LL:COL - | -LL | pub const fn size_of() -> usize { - | ^^^^^^^ error: aborting due to 3 previous errors diff --git a/src/test/ui/rfc-2008-non-exhaustive/improper_ctypes/extern_crate_improper.rs b/src/test/ui/rfc-2008-non-exhaustive/improper_ctypes/extern_crate_improper.rs index 15c0c695fcabb..5feb9c98e964d 100644 --- a/src/test/ui/rfc-2008-non-exhaustive/improper_ctypes/extern_crate_improper.rs +++ b/src/test/ui/rfc-2008-non-exhaustive/improper_ctypes/extern_crate_improper.rs @@ -6,9 +6,9 @@ extern crate types; // This test checks that non-exhaustive types with `#[repr(C)]` from an extern crate are considered // improper. -use types::{NonExhaustiveEnum, NonExhaustiveVariants, NormalStruct, TupleStruct, UnitStruct}; +use types::{NonExhaustiveEnum, NormalStruct, UnitStruct, TupleStruct, NonExhaustiveVariants}; -extern "C" { +extern { pub fn non_exhaustive_enum(_: NonExhaustiveEnum); //~^ ERROR `extern` block uses type `NonExhaustiveEnum`, which is not FFI-safe pub fn non_exhaustive_normal_struct(_: NormalStruct); @@ -21,4 +21,4 @@ extern "C" { //~^ ERROR `extern` block uses type `NonExhaustiveVariants`, which is not FFI-safe } -fn main() {} +fn main() { } diff --git a/src/test/ui/rfc-2008-non-exhaustive/improper_ctypes/same_crate_proper.rs b/src/test/ui/rfc-2008-non-exhaustive/improper_ctypes/same_crate_proper.rs index fe4ae345d85f8..c09aa256e0e74 100644 --- a/src/test/ui/rfc-2008-non-exhaustive/improper_ctypes/same_crate_proper.rs +++ b/src/test/ui/rfc-2008-non-exhaustive/improper_ctypes/same_crate_proper.rs @@ -9,7 +9,7 @@ pub enum NonExhaustiveEnum { Unit, Tuple(u32), - Struct { field: u32 }, + Struct { field: u32 } } #[non_exhaustive] @@ -25,19 +25,16 @@ pub struct UnitStruct; #[non_exhaustive] #[repr(C)] -pub struct TupleStruct(pub u16, pub u16); +pub struct TupleStruct (pub u16, pub u16); #[repr(C)] pub enum NonExhaustiveVariants { - #[non_exhaustive] - Unit, - #[non_exhaustive] - Tuple(u32), - #[non_exhaustive] - Struct { field: u32 }, + #[non_exhaustive] Unit, + #[non_exhaustive] Tuple(u32), + #[non_exhaustive] Struct { field: u32 } } -extern "C" { +extern { // Unit structs aren't tested here because they will trigger `improper_ctypes` anyway. pub fn non_exhaustive_enum(_: NonExhaustiveEnum); pub fn non_exhaustive_normal_struct(_: NormalStruct); @@ -45,4 +42,4 @@ extern "C" { pub fn non_exhaustive_variant(_: NonExhaustiveVariants); } -fn main() {} +fn main() { } diff --git a/src/test/ui/rfc-2627-raw-dylib/feature-gate-raw-dylib-2.rs b/src/test/ui/rfc-2627-raw-dylib/feature-gate-raw-dylib-2.rs index 518aa20dd68ce..14345bad6e5b9 100644 --- a/src/test/ui/rfc-2627-raw-dylib/feature-gate-raw-dylib-2.rs +++ b/src/test/ui/rfc-2627-raw-dylib/feature-gate-raw-dylib-2.rs @@ -1,5 +1,5 @@ -#[link(name = "foo")] -extern "C" { +#[link(name="foo")] +extern { #[link_ordinal(42)] //~^ ERROR: the `#[link_ordinal]` attribute is an experimental feature fn foo(); diff --git a/src/test/ui/rfc-2627-raw-dylib/feature-gate-raw-dylib.rs b/src/test/ui/rfc-2627-raw-dylib/feature-gate-raw-dylib.rs index 29edd0f9ef90e..f0f83e0426dd6 100644 --- a/src/test/ui/rfc-2627-raw-dylib/feature-gate-raw-dylib.rs +++ b/src/test/ui/rfc-2627-raw-dylib/feature-gate-raw-dylib.rs @@ -1,5 +1,5 @@ -#[link(name = "foo", kind = "raw-dylib")] +#[link(name="foo", kind="raw-dylib")] //~^ ERROR: kind="raw-dylib" is unstable -extern "C" {} +extern {} fn main() {} diff --git a/src/test/ui/rfc-2627-raw-dylib/feature-gate-raw-dylib.stderr b/src/test/ui/rfc-2627-raw-dylib/feature-gate-raw-dylib.stderr index a670b6c6c2a0d..a69f67795418d 100644 --- a/src/test/ui/rfc-2627-raw-dylib/feature-gate-raw-dylib.stderr +++ b/src/test/ui/rfc-2627-raw-dylib/feature-gate-raw-dylib.stderr @@ -1,8 +1,8 @@ error[E0658]: kind="raw-dylib" is unstable --> $DIR/feature-gate-raw-dylib.rs:1:1 | -LL | #[link(name = "foo", kind = "raw-dylib")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[link(name="foo", kind="raw-dylib")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: see issue #58713 for more information = help: add `#![feature(raw_dylib)]` to the crate attributes to enable diff --git a/src/test/ui/rfc-2627-raw-dylib/link-ordinal-and-name.rs b/src/test/ui/rfc-2627-raw-dylib/link-ordinal-and-name.rs index 42685cad9482b..bf082932bd6ce 100644 --- a/src/test/ui/rfc-2627-raw-dylib/link-ordinal-and-name.rs +++ b/src/test/ui/rfc-2627-raw-dylib/link-ordinal-and-name.rs @@ -2,7 +2,7 @@ //~^ WARN the feature `raw_dylib` is incomplete #[link(name="foo")] -extern "C" { +extern { #[link_name="foo"] #[link_ordinal(42)] //~^ ERROR cannot use `#[link_name]` with `#[link_ordinal]` diff --git a/src/test/ui/rfc-2627-raw-dylib/link-ordinal-invalid-format.rs b/src/test/ui/rfc-2627-raw-dylib/link-ordinal-invalid-format.rs index 135f5909ea130..ea633c5bcce24 100644 --- a/src/test/ui/rfc-2627-raw-dylib/link-ordinal-invalid-format.rs +++ b/src/test/ui/rfc-2627-raw-dylib/link-ordinal-invalid-format.rs @@ -1,8 +1,8 @@ #![feature(raw_dylib)] //~^ WARN the feature `raw_dylib` is incomplete -#[link(name = "foo")] -extern "C" { +#[link(name="foo")] +extern { #[link_ordinal("JustMonika")] //~^ ERROR illegal ordinal format in `link_ordinal` fn foo(); diff --git a/src/test/ui/rfc-2627-raw-dylib/link-ordinal-too-large.rs b/src/test/ui/rfc-2627-raw-dylib/link-ordinal-too-large.rs index 10db497297027..55cc329dc594b 100644 --- a/src/test/ui/rfc-2627-raw-dylib/link-ordinal-too-large.rs +++ b/src/test/ui/rfc-2627-raw-dylib/link-ordinal-too-large.rs @@ -1,8 +1,8 @@ #![feature(raw_dylib)] //~^ WARN the feature `raw_dylib` is incomplete -#[link(name = "foo")] -extern "C" { +#[link(name="foo")] +extern { #[link_ordinal(18446744073709551616)] //~^ ERROR ordinal value in `link_ordinal` is too large: `18446744073709551616` fn foo(); diff --git a/src/test/ui/consts/rustc-args-required-const.rs b/src/test/ui/rustc-args-required-const.rs similarity index 100% rename from src/test/ui/consts/rustc-args-required-const.rs rename to src/test/ui/rustc-args-required-const.rs diff --git a/src/test/ui/consts/rustc-args-required-const.stderr b/src/test/ui/rustc-args-required-const.stderr similarity index 100% rename from src/test/ui/consts/rustc-args-required-const.stderr rename to src/test/ui/rustc-args-required-const.stderr diff --git a/src/test/ui/safe-extern-statics-mut.rs b/src/test/ui/safe-extern-statics-mut.rs index 324fa443aa50e..dbf0f523a9a86 100644 --- a/src/test/ui/safe-extern-statics-mut.rs +++ b/src/test/ui/safe-extern-statics-mut.rs @@ -3,7 +3,7 @@ extern crate extern_statics; use extern_statics::*; -extern "C" { +extern { static mut B: u8; } diff --git a/src/test/ui/safe-extern-statics.rs b/src/test/ui/safe-extern-statics.rs index 6fa4c4aaca578..0535a078d2c31 100644 --- a/src/test/ui/safe-extern-statics.rs +++ b/src/test/ui/safe-extern-statics.rs @@ -3,7 +3,7 @@ extern crate extern_statics; use extern_statics::*; -extern "C" { +extern { static A: u8; } diff --git a/src/test/ui/sepcomp/sepcomp-extern.rs b/src/test/ui/sepcomp/sepcomp-extern.rs index 6323bf664fc25..c4ccf23c47ab4 100644 --- a/src/test/ui/sepcomp/sepcomp-extern.rs +++ b/src/test/ui/sepcomp/sepcomp-extern.rs @@ -6,7 +6,7 @@ extern crate sepcomp_extern_lib; -extern "C" { +extern { fn foo() -> usize; } diff --git a/src/test/ui/seq-args.rs b/src/test/ui/seq-args.rs index 9a3c495602a69..9bb9f12f64c0a 100644 --- a/src/test/ui/seq-args.rs +++ b/src/test/ui/seq-args.rs @@ -1,13 +1,11 @@ fn main() { - trait Seq { } +trait Seq { } - impl Seq for Vec { - //~^ ERROR this trait takes 0 type arguments but 1 type argument was supplied - /* ... */ - } +impl Seq for Vec { //~ ERROR wrong number of type arguments + /* ... */ +} +impl Seq for u32 { //~ ERROR wrong number of type arguments + /* Treat the integer as a sequence of bits */ +} - impl Seq for u32 { - //~^ ERROR this trait takes 0 type arguments but 1 type argument was supplied - /* Treat the integer as a sequence of bits */ - } } diff --git a/src/test/ui/seq-args.stderr b/src/test/ui/seq-args.stderr index 0e89fefc69ddc..2e7d901640e84 100644 --- a/src/test/ui/seq-args.stderr +++ b/src/test/ui/seq-args.stderr @@ -1,30 +1,14 @@ -error[E0107]: this trait takes 0 type arguments but 1 type argument was supplied +error[E0107]: wrong number of type arguments: expected 0, found 1 --> $DIR/seq-args.rs:4:13 | -LL | impl Seq for Vec { - | ^^^--- help: remove these generics - | | - | expected 0 type arguments - | -note: trait defined here, with 0 type parameters - --> $DIR/seq-args.rs:2:11 - | -LL | trait Seq { } - | ^^^ +LL | impl Seq for Vec { + | ^ unexpected type argument -error[E0107]: this trait takes 0 type arguments but 1 type argument was supplied - --> $DIR/seq-args.rs:9:10 - | -LL | impl Seq for u32 { - | ^^^------ help: remove these generics - | | - | expected 0 type arguments - | -note: trait defined here, with 0 type parameters - --> $DIR/seq-args.rs:2:11 +error[E0107]: wrong number of type arguments: expected 0, found 1 + --> $DIR/seq-args.rs:7:10 | -LL | trait Seq { } - | ^^^ +LL | impl Seq for u32 { + | ^^^^ unexpected type argument error: aborting due to 2 previous errors diff --git a/src/test/ui/signal-alternate-stack-cleanup.rs b/src/test/ui/signal-alternate-stack-cleanup.rs index 8a6d738959e4c..15fcf78893ebb 100644 --- a/src/test/ui/signal-alternate-stack-cleanup.rs +++ b/src/test/ui/signal-alternate-stack-cleanup.rs @@ -13,11 +13,11 @@ extern crate libc; use libc::*; -unsafe extern "C" fn signal_handler(signum: c_int, _: *mut siginfo_t, _: *mut c_void) { +unsafe extern fn signal_handler(signum: c_int, _: *mut siginfo_t, _: *mut c_void) { assert_eq!(signum, SIGWINCH); } -extern "C" fn send_signal() { +extern fn send_signal() { unsafe { raise(SIGWINCH); } diff --git a/src/test/ui/simple_global_asm.rs b/src/test/ui/simple_global_asm.rs index 75b4788b56f7b..d95fefebc0f9e 100644 --- a/src/test/ui/simple_global_asm.rs +++ b/src/test/ui/simple_global_asm.rs @@ -5,26 +5,20 @@ #![allow(dead_code)] #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] -global_asm!( - r#" +global_asm!(r#" .global foo .global _foo foo: _foo: ret -"# -); +"#); -extern "C" { +extern { fn foo(); } #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] -fn main() { - unsafe { - foo(); - } -} +fn main() { unsafe { foo(); } } #[cfg(not(any(target_arch = "x86_64", target_arch = "x86")))] fn main() {} diff --git a/src/test/ui/pattern/size-and-align.rs b/src/test/ui/size-and-align.rs similarity index 100% rename from src/test/ui/pattern/size-and-align.rs rename to src/test/ui/size-and-align.rs diff --git a/src/test/ui/span/lint-unused-unsafe.rs b/src/test/ui/span/lint-unused-unsafe.rs index b6c4894d91807..338fbb994c5c5 100644 --- a/src/test/ui/span/lint-unused-unsafe.rs +++ b/src/test/ui/span/lint-unused-unsafe.rs @@ -5,7 +5,7 @@ mod foo { - extern "C" { + extern { pub fn bar(); } } diff --git a/src/test/ui/specialization/min_specialization/repeated_projection_type.stderr b/src/test/ui/specialization/min_specialization/repeated_projection_type.stderr index 92208231b1735..fee8b06e94c0b 100644 --- a/src/test/ui/specialization/min_specialization/repeated_projection_type.stderr +++ b/src/test/ui/specialization/min_specialization/repeated_projection_type.stderr @@ -1,4 +1,4 @@ -error: cannot specialize on `Binder(ProjectionPredicate(ProjectionTy { substs: [V], item_def_id: DefId(0:6 ~ repeated_projection_type[317d]::Id::This) }, (I,)))` +error: cannot specialize on `ProjectionPredicate(ProjectionTy { substs: [V], item_def_id: DefId(0:6 ~ repeated_projection_type[317d]::Id::This) }, (I,))` --> $DIR/repeated_projection_type.rs:19:1 | LL | / impl> X for V { diff --git a/src/test/ui/stability-attribute/stability-attribute-trait-impl.rs b/src/test/ui/stability-attribute/stability-attribute-trait-impl.rs index 656564fc9e3f8..cc57071b87cea 100644 --- a/src/test/ui/stability-attribute/stability-attribute-trait-impl.rs +++ b/src/test/ui/stability-attribute/stability-attribute-trait-impl.rs @@ -22,7 +22,7 @@ impl StableTrait for UnstableType {} impl UnstableTrait for StableType {} #[unstable(feature = "x", issue = "none")] -//~^ ERROR an `#[unstable]` annotation here has no effect [ineffective_unstable_trait_impl] +//~^ ERROR an `#[unstable]` annotation here has no effect [rustc::ineffective_unstable_trait_impl] impl StableTrait for StableType {} fn main() {} diff --git a/src/test/ui/stability-attribute/stability-attribute-trait-impl.stderr b/src/test/ui/stability-attribute/stability-attribute-trait-impl.stderr index a11479cc8f45c..1915d03fb0aaf 100644 --- a/src/test/ui/stability-attribute/stability-attribute-trait-impl.stderr +++ b/src/test/ui/stability-attribute/stability-attribute-trait-impl.stderr @@ -4,7 +4,7 @@ error: an `#[unstable]` annotation here has no effect LL | #[unstable(feature = "x", issue = "none")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: `#[deny(ineffective_unstable_trait_impl)]` on by default + = note: `#[deny(rustc::ineffective_unstable_trait_impl)]` on by default = note: see issue #55436 for more information error: aborting due to previous error diff --git a/src/test/ui/static/static-mut-foreign-requires-unsafe.rs b/src/test/ui/static/static-mut-foreign-requires-unsafe.rs index 90aa2537a82bb..535f6bc322653 100644 --- a/src/test/ui/static/static-mut-foreign-requires-unsafe.rs +++ b/src/test/ui/static/static-mut-foreign-requires-unsafe.rs @@ -1,9 +1,9 @@ -extern "C" { +extern { static mut a: i32; } fn main() { - a += 3; //~ ERROR: requires unsafe - a = 4; //~ ERROR: requires unsafe + a += 3; //~ ERROR: requires unsafe + a = 4; //~ ERROR: requires unsafe let _b = a; //~ ERROR: requires unsafe } diff --git a/src/test/ui/static_sized_requirement.rs b/src/test/ui/static_sized_requirement.rs index 3943b26085407..074280b7b6646 100644 --- a/src/test/ui/static_sized_requirement.rs +++ b/src/test/ui/static_sized_requirement.rs @@ -7,6 +7,6 @@ #[lang = "sized"] trait Sized {} -extern "C" { +extern { pub static A: u32; } diff --git a/src/test/ui/stmt_expr_attrs_no_feature.rs b/src/test/ui/stmt_expr_attrs_no_feature.rs index 627c97da008de..674a5ed18cee3 100644 --- a/src/test/ui/stmt_expr_attrs_no_feature.rs +++ b/src/test/ui/stmt_expr_attrs_no_feature.rs @@ -89,7 +89,7 @@ item_mac!(e); // check that the gate visitor works right: -extern "C" { +extern { #[cfg(unset)] fn x(a: [u8; #[rustc_dummy] 5]); fn y(a: [u8; #[rustc_dummy] 5]); //~ ERROR attributes on expressions are experimental diff --git a/src/test/ui/structs-enums/class-dtor.rs b/src/test/ui/structs-enums/class-dtor.rs index 583a5e2409859..ee1cac03c81e8 100644 --- a/src/test/ui/structs-enums/class-dtor.rs +++ b/src/test/ui/structs-enums/class-dtor.rs @@ -5,7 +5,7 @@ // pretty-expanded FIXME #23616 struct cat { - done : extern "C" fn(usize), + done : extern fn(usize), meows : usize, } @@ -15,7 +15,7 @@ impl Drop for cat { } } -fn cat(done: extern "C" fn(usize)) -> cat { +fn cat(done: extern fn(usize)) -> cat { cat { meows: 0, done: done diff --git a/src/test/ui/structs-enums/foreign-struct.rs b/src/test/ui/structs-enums/foreign-struct.rs index 00a23b354a97e..ce02c8fb5c3a5 100644 --- a/src/test/ui/structs-enums/foreign-struct.rs +++ b/src/test/ui/structs-enums/foreign-struct.rs @@ -6,14 +6,14 @@ // pretty-expanded FIXME #23616 -pub enum void {} +pub enum void { } mod bindgen { use super::void; - extern "C" { + extern { pub fn printf(v: void); } } -pub fn main() {} +pub fn main() { } diff --git a/src/test/ui/structs/structure-constructor-type-mismatch.rs b/src/test/ui/structs/structure-constructor-type-mismatch.rs index 56c8ffb3e65b7..01cc1764657e6 100644 --- a/src/test/ui/structs/structure-constructor-type-mismatch.rs +++ b/src/test/ui/structs/structure-constructor-type-mismatch.rs @@ -1,5 +1,3 @@ -// ignore-tidy-linelength - struct Point { x: T, y: T, @@ -47,13 +45,13 @@ fn main() { y: 8, }; - let pt3 = PointF:: { //~ ERROR this type alias takes 0 type arguments but 1 type argument was supplied + let pt3 = PointF:: { //~ ERROR wrong number of type arguments x: 9, //~ ERROR mismatched types y: 10, //~ ERROR mismatched types }; match (Point { x: 1, y: 2 }) { - PointF:: { .. } => {} //~ ERROR this type alias takes 0 type arguments but 1 type argument was supplied + PointF:: { .. } => {} //~ ERROR wrong number of type arguments //~^ ERROR mismatched types } diff --git a/src/test/ui/structs/structure-constructor-type-mismatch.stderr b/src/test/ui/structs/structure-constructor-type-mismatch.stderr index 4611414967290..8cfa118a2dac2 100644 --- a/src/test/ui/structs/structure-constructor-type-mismatch.stderr +++ b/src/test/ui/structs/structure-constructor-type-mismatch.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/structure-constructor-type-mismatch.rs:19:12 + --> $DIR/structure-constructor-type-mismatch.rs:17:12 | LL | x: 1, | ^ @@ -8,7 +8,7 @@ LL | x: 1, | help: use a float literal: `1.0` error[E0308]: mismatched types - --> $DIR/structure-constructor-type-mismatch.rs:22:12 + --> $DIR/structure-constructor-type-mismatch.rs:20:12 | LL | y: 2, | ^ @@ -17,7 +17,7 @@ LL | y: 2, | help: use a float literal: `2.0` error[E0308]: mismatched types - --> $DIR/structure-constructor-type-mismatch.rs:28:12 + --> $DIR/structure-constructor-type-mismatch.rs:26:12 | LL | x: 3, | ^ @@ -26,7 +26,7 @@ LL | x: 3, | help: use a float literal: `3.0` error[E0308]: mismatched types - --> $DIR/structure-constructor-type-mismatch.rs:31:12 + --> $DIR/structure-constructor-type-mismatch.rs:29:12 | LL | y: 4, | ^ @@ -35,7 +35,7 @@ LL | y: 4, | help: use a float literal: `4.0` error[E0308]: mismatched types - --> $DIR/structure-constructor-type-mismatch.rs:37:12 + --> $DIR/structure-constructor-type-mismatch.rs:35:12 | LL | x: 5, | ^ @@ -44,7 +44,7 @@ LL | x: 5, | help: use a float literal: `5.0` error[E0308]: mismatched types - --> $DIR/structure-constructor-type-mismatch.rs:44:12 + --> $DIR/structure-constructor-type-mismatch.rs:42:12 | LL | x: 7, | ^ @@ -52,22 +52,14 @@ LL | x: 7, | expected `f32`, found integer | help: use a float literal: `7.0` -error[E0107]: this type alias takes 0 type arguments but 1 type argument was supplied - --> $DIR/structure-constructor-type-mismatch.rs:50:15 +error[E0107]: wrong number of type arguments: expected 0, found 1 + --> $DIR/structure-constructor-type-mismatch.rs:48:24 | LL | let pt3 = PointF:: { - | ^^^^^^------- help: remove these generics - | | - | expected 0 type arguments - | -note: type alias defined here, with 0 type parameters - --> $DIR/structure-constructor-type-mismatch.rs:8:6 - | -LL | type PointF = Point; - | ^^^^^^ + | ^^^ unexpected type argument error[E0308]: mismatched types - --> $DIR/structure-constructor-type-mismatch.rs:51:12 + --> $DIR/structure-constructor-type-mismatch.rs:49:12 | LL | x: 9, | ^ @@ -76,7 +68,7 @@ LL | x: 9, | help: use a float literal: `9.0` error[E0308]: mismatched types - --> $DIR/structure-constructor-type-mismatch.rs:52:12 + --> $DIR/structure-constructor-type-mismatch.rs:50:12 | LL | y: 10, | ^^ @@ -84,22 +76,14 @@ LL | y: 10, | expected `f32`, found integer | help: use a float literal: `10.0` -error[E0107]: this type alias takes 0 type arguments but 1 type argument was supplied - --> $DIR/structure-constructor-type-mismatch.rs:56:9 +error[E0107]: wrong number of type arguments: expected 0, found 1 + --> $DIR/structure-constructor-type-mismatch.rs:54:18 | LL | PointF:: { .. } => {} - | ^^^^^^------- help: remove these generics - | | - | expected 0 type arguments - | -note: type alias defined here, with 0 type parameters - --> $DIR/structure-constructor-type-mismatch.rs:8:6 - | -LL | type PointF = Point; - | ^^^^^^ + | ^^^ unexpected type argument error[E0308]: mismatched types - --> $DIR/structure-constructor-type-mismatch.rs:56:9 + --> $DIR/structure-constructor-type-mismatch.rs:54:9 | LL | match (Point { x: 1, y: 2 }) { | ---------------------- this expression has type `Point<{integer}>` @@ -110,7 +94,7 @@ LL | PointF:: { .. } => {} found struct `Point` error[E0308]: mismatched types - --> $DIR/structure-constructor-type-mismatch.rs:61:9 + --> $DIR/structure-constructor-type-mismatch.rs:59:9 | LL | match (Point { x: 1, y: 2 }) { | ---------------------- this expression has type `Point<{integer}>` @@ -121,7 +105,7 @@ LL | PointF { .. } => {} found struct `Point` error[E0308]: mismatched types - --> $DIR/structure-constructor-type-mismatch.rs:69:9 + --> $DIR/structure-constructor-type-mismatch.rs:67:9 | LL | match (Pair { x: 1, y: 2 }) { | --------------------- this expression has type `Pair<{integer}, {integer}>` diff --git a/src/test/ui/suggestions/missing-lifetime-specifier.rs b/src/test/ui/suggestions/missing-lifetime-specifier.rs index 761922beb17d5..fe88d105c78bf 100644 --- a/src/test/ui/suggestions/missing-lifetime-specifier.rs +++ b/src/test/ui/suggestions/missing-lifetime-specifier.rs @@ -41,17 +41,17 @@ thread_local! { thread_local! { static e: RefCell>>>> = RefCell::new(HashMap::new()); - //~^ ERROR this union takes 2 lifetime arguments but only 1 lifetime argument was supplied - //~| ERROR this union takes 2 lifetime arguments but only 1 lifetime argument was supplied - //~| ERROR this union takes 2 lifetime arguments but only 1 lifetime argument was supplied - //~| ERROR this union takes 2 lifetime arguments but only 1 lifetime argument was supplied + //~^ ERROR wrong number of lifetime arguments: expected 2, found 1 + //~| ERROR wrong number of lifetime arguments: expected 2, found 1 + //~| ERROR wrong number of lifetime arguments: expected 2, found 1 + //~| ERROR wrong number of lifetime arguments: expected 2, found 1 } thread_local! { static f: RefCell>>>> = RefCell::new(HashMap::new()); - //~^ ERROR this trait takes 2 lifetime arguments but only 1 lifetime argument was supplied - //~| ERROR this trait takes 2 lifetime arguments but only 1 lifetime argument was supplied - //~| ERROR this trait takes 2 lifetime arguments but only 1 lifetime argument was supplied - //~| ERROR this trait takes 2 lifetime arguments but only 1 lifetime argument was supplied + //~^ ERROR wrong number of lifetime arguments: expected 2, found 1 + //~| ERROR wrong number of lifetime arguments: expected 2, found 1 + //~| ERROR wrong number of lifetime arguments: expected 2, found 1 + //~| ERROR wrong number of lifetime arguments: expected 2, found 1 //~| ERROR missing lifetime specifier //~| ERROR missing lifetime specifier } diff --git a/src/test/ui/suggestions/missing-lifetime-specifier.stderr b/src/test/ui/suggestions/missing-lifetime-specifier.stderr index e6cec5cbd45b9..9838ac72ad767 100644 --- a/src/test/ui/suggestions/missing-lifetime-specifier.stderr +++ b/src/test/ui/suggestions/missing-lifetime-specifier.stderr @@ -166,149 +166,53 @@ help: consider using the `'static` lifetime LL | static f: RefCell>>>> = RefCell::new(HashMap::new()); | ^^^^^^^^ -error[E0107]: this union takes 2 lifetime arguments but only 1 lifetime argument was supplied +error[E0107]: wrong number of lifetime arguments: expected 2, found 1 --> $DIR/missing-lifetime-specifier.rs:43:44 | LL | static e: RefCell>>>> = RefCell::new(HashMap::new()); - | ^^^ ------- supplied 1 lifetime argument - | | - | expected 2 lifetime arguments - | -note: union defined here, with 2 lifetime parameters: `'t`, `'k` - --> $DIR/missing-lifetime-specifier.rs:11:11 - | -LL | pub union Qux<'t, 'k, I> { - | ^^^ -- -- -help: add missing lifetime argument - | -LL | static e: RefCell>>>> = RefCell::new(HashMap::new()); - | ^^^^ + | ^^^^^^^^^^^^^^^^^ expected 2 lifetime arguments -error[E0107]: this union takes 2 lifetime arguments but only 1 lifetime argument was supplied +error[E0107]: wrong number of lifetime arguments: expected 2, found 1 --> $DIR/missing-lifetime-specifier.rs:43:44 | LL | static e: RefCell>>>> = RefCell::new(HashMap::new()); - | ^^^ ------- supplied 1 lifetime argument - | | - | expected 2 lifetime arguments - | -note: union defined here, with 2 lifetime parameters: `'t`, `'k` - --> $DIR/missing-lifetime-specifier.rs:11:11 - | -LL | pub union Qux<'t, 'k, I> { - | ^^^ -- -- -help: add missing lifetime argument - | -LL | static e: RefCell>>>> = RefCell::new(HashMap::new()); - | ^^^^ + | ^^^^^^^^^^^^^^^^^ expected 2 lifetime arguments -error[E0107]: this union takes 2 lifetime arguments but only 1 lifetime argument was supplied +error[E0107]: wrong number of lifetime arguments: expected 2, found 1 --> $DIR/missing-lifetime-specifier.rs:43:44 | LL | static e: RefCell>>>> = RefCell::new(HashMap::new()); - | ^^^ ------- supplied 1 lifetime argument - | | - | expected 2 lifetime arguments - | -note: union defined here, with 2 lifetime parameters: `'t`, `'k` - --> $DIR/missing-lifetime-specifier.rs:11:11 - | -LL | pub union Qux<'t, 'k, I> { - | ^^^ -- -- -help: add missing lifetime argument - | -LL | static e: RefCell>>>> = RefCell::new(HashMap::new()); - | ^^^^ + | ^^^^^^^^^^^^^^^^^ expected 2 lifetime arguments -error[E0107]: this union takes 2 lifetime arguments but only 1 lifetime argument was supplied +error[E0107]: wrong number of lifetime arguments: expected 2, found 1 --> $DIR/missing-lifetime-specifier.rs:43:44 | LL | static e: RefCell>>>> = RefCell::new(HashMap::new()); - | ^^^ ------- supplied 1 lifetime argument - | | - | expected 2 lifetime arguments - | -note: union defined here, with 2 lifetime parameters: `'t`, `'k` - --> $DIR/missing-lifetime-specifier.rs:11:11 - | -LL | pub union Qux<'t, 'k, I> { - | ^^^ -- -- -help: add missing lifetime argument - | -LL | static e: RefCell>>>> = RefCell::new(HashMap::new()); - | ^^^^ + | ^^^^^^^^^^^^^^^^^ expected 2 lifetime arguments -error[E0107]: this trait takes 2 lifetime arguments but only 1 lifetime argument was supplied +error[E0107]: wrong number of lifetime arguments: expected 2, found 1 --> $DIR/missing-lifetime-specifier.rs:50:45 | LL | static f: RefCell>>>> = RefCell::new(HashMap::new()); - | ^^^ ------- supplied 1 lifetime argument - | | - | expected 2 lifetime arguments - | -note: trait defined here, with 2 lifetime parameters: `'t`, `'k` - --> $DIR/missing-lifetime-specifier.rs:15:7 - | -LL | trait Tar<'t, 'k, I> {} - | ^^^ -- -- -help: add missing lifetime argument - | -LL | static f: RefCell>>>> = RefCell::new(HashMap::new()); - | ^^^^ + | ^^^^^^^^^^^^^^^^^ expected 2 lifetime arguments -error[E0107]: this trait takes 2 lifetime arguments but only 1 lifetime argument was supplied +error[E0107]: wrong number of lifetime arguments: expected 2, found 1 --> $DIR/missing-lifetime-specifier.rs:50:45 | LL | static f: RefCell>>>> = RefCell::new(HashMap::new()); - | ^^^ ------- supplied 1 lifetime argument - | | - | expected 2 lifetime arguments - | -note: trait defined here, with 2 lifetime parameters: `'t`, `'k` - --> $DIR/missing-lifetime-specifier.rs:15:7 - | -LL | trait Tar<'t, 'k, I> {} - | ^^^ -- -- -help: add missing lifetime argument - | -LL | static f: RefCell>>>> = RefCell::new(HashMap::new()); - | ^^^^ + | ^^^^^^^^^^^^^^^^^ expected 2 lifetime arguments -error[E0107]: this trait takes 2 lifetime arguments but only 1 lifetime argument was supplied +error[E0107]: wrong number of lifetime arguments: expected 2, found 1 --> $DIR/missing-lifetime-specifier.rs:50:45 | LL | static f: RefCell>>>> = RefCell::new(HashMap::new()); - | ^^^ ------- supplied 1 lifetime argument - | | - | expected 2 lifetime arguments - | -note: trait defined here, with 2 lifetime parameters: `'t`, `'k` - --> $DIR/missing-lifetime-specifier.rs:15:7 - | -LL | trait Tar<'t, 'k, I> {} - | ^^^ -- -- -help: add missing lifetime argument - | -LL | static f: RefCell>>>> = RefCell::new(HashMap::new()); - | ^^^^ + | ^^^^^^^^^^^^^^^^^ expected 2 lifetime arguments -error[E0107]: this trait takes 2 lifetime arguments but only 1 lifetime argument was supplied +error[E0107]: wrong number of lifetime arguments: expected 2, found 1 --> $DIR/missing-lifetime-specifier.rs:50:45 | LL | static f: RefCell>>>> = RefCell::new(HashMap::new()); - | ^^^ ------- supplied 1 lifetime argument - | | - | expected 2 lifetime arguments - | -note: trait defined here, with 2 lifetime parameters: `'t`, `'k` - --> $DIR/missing-lifetime-specifier.rs:15:7 - | -LL | trait Tar<'t, 'k, I> {} - | ^^^ -- -- -help: add missing lifetime argument - | -LL | static f: RefCell>>>> = RefCell::new(HashMap::new()); - | ^^^^ + | ^^^^^^^^^^^^^^^^^ expected 2 lifetime arguments error: aborting due to 22 previous errors diff --git a/src/test/ui/suggestions/use-type-argument-instead-of-assoc-type.rs b/src/test/ui/suggestions/use-type-argument-instead-of-assoc-type.rs index 05e2d38c43b53..78487bd7bb58c 100644 --- a/src/test/ui/suggestions/use-type-argument-instead-of-assoc-type.rs +++ b/src/test/ui/suggestions/use-type-argument-instead-of-assoc-type.rs @@ -6,7 +6,7 @@ pub trait T { pub struct Foo { i: Box>, //~^ ERROR must be specified - //~| ERROR this trait takes 2 type arguments but 4 type arguments were supplied + //~| ERROR wrong number of type arguments } diff --git a/src/test/ui/suggestions/use-type-argument-instead-of-assoc-type.stderr b/src/test/ui/suggestions/use-type-argument-instead-of-assoc-type.stderr index 2d06591f4c7bd..58a73187fb158 100644 --- a/src/test/ui/suggestions/use-type-argument-instead-of-assoc-type.stderr +++ b/src/test/ui/suggestions/use-type-argument-instead-of-assoc-type.stderr @@ -1,16 +1,10 @@ -error[E0107]: this trait takes 2 type arguments but 4 type arguments were supplied - --> $DIR/use-type-argument-instead-of-assoc-type.rs:7:16 +error[E0107]: wrong number of type arguments: expected 2, found 4 + --> $DIR/use-type-argument-instead-of-assoc-type.rs:7:32 | LL | i: Box>, - | ^ -------------- help: remove these type arguments - | | - | expected 2 type arguments - | -note: trait defined here, with 2 type parameters: `X`, `Y` - --> $DIR/use-type-argument-instead-of-assoc-type.rs:1:11 - | -LL | pub trait T { - | ^ - - + | ^^^^^ ^^^^^ unexpected type argument + | | + | unexpected type argument error[E0191]: the value of the associated types `A` (from trait `T`), `C` (from trait `T`) must be specified --> $DIR/use-type-argument-instead-of-assoc-type.rs:7:16 diff --git a/src/test/ui/suggestions/vec-macro-in-pattern.fixed b/src/test/ui/suggestions/vec-macro-in-pattern.fixed new file mode 100644 index 0000000000000..e1695d6820a81 --- /dev/null +++ b/src/test/ui/suggestions/vec-macro-in-pattern.fixed @@ -0,0 +1,8 @@ +// run-rustfix +fn main() { + // everything after `.as_ref` should be suggested + match Some(vec![3]).as_ref().map(|v| v.as_slice()) { + Some([_x]) => (), //~ ERROR unexpected `(` after qualified path + _ => (), + } +} diff --git a/src/test/ui/suggestions/vec-macro-in-pattern.rs b/src/test/ui/suggestions/vec-macro-in-pattern.rs new file mode 100644 index 0000000000000..4843629fbcf90 --- /dev/null +++ b/src/test/ui/suggestions/vec-macro-in-pattern.rs @@ -0,0 +1,8 @@ +// run-rustfix +fn main() { + // everything after `.as_ref` should be suggested + match Some(vec![3]).as_ref().map(|v| v.as_slice()) { + Some(vec![_x]) => (), //~ ERROR unexpected `(` after qualified path + _ => (), + } +} diff --git a/src/test/ui/suggestions/vec-macro-in-pattern.stderr b/src/test/ui/suggestions/vec-macro-in-pattern.stderr new file mode 100644 index 0000000000000..f9d0464ac88b1 --- /dev/null +++ b/src/test/ui/suggestions/vec-macro-in-pattern.stderr @@ -0,0 +1,16 @@ +error: unexpected `(` after qualified path + --> $DIR/vec-macro-in-pattern.rs:5:14 + | +LL | Some(vec![_x]) => (), + | ^^^^^^^^ + | | + | unexpected `(` after qualified path + | the qualified path + | in this macro invocation + | help: use a slice pattern here instead: `[_x]` + | + = help: for more information, see https://doc.rust-lang.org/edition-guide/rust-2018/slice-patterns.html + = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to previous error + diff --git a/src/test/ui/symbol-names/impl1.rs b/src/test/ui/symbol-names/impl1.rs index 24bdf6d669e88..05bd98df0064a 100644 --- a/src/test/ui/symbol-names/impl1.rs +++ b/src/test/ui/symbol-names/impl1.rs @@ -60,7 +60,7 @@ fn main() { } // Test type mangling, by putting them in an `impl` header. - impl Bar for [&'_ (dyn Foo + AutoTrait); 3] { + impl Bar for [&'_ (dyn Foo + AutoTrait); 3] { #[rustc_symbol_name] //[legacy]~^ ERROR symbol-name(_ZN209_$LT$$u5b$$RF$dyn$u20$impl1..Foo$u2b$Assoc$u20$$u3d$$u20$extern$u20$$u22$C$u22$$u20$fn$LP$$RF$u8$C$$u20$...$RP$$u2b$impl1..AutoTrait$u3b$$u20$3$u5d$$u20$as$u20$impl1..main..$u7b$$u7b$closure$u7d$$u7d$..Bar$GT$6method //[legacy]~| ERROR demangling(<[&dyn impl1::Foo+Assoc = extern "C" fn(&u8, ::.)+impl1::AutoTrait; 3] as impl1::main::{{closure}}::Bar>::method diff --git a/src/test/ui/tag-type-args.rs b/src/test/ui/tag-type-args.rs index 660d860ba7725..4f546fcc2adc2 100644 --- a/src/test/ui/tag-type-args.rs +++ b/src/test/ui/tag-type-args.rs @@ -1,5 +1,5 @@ enum Quux { Bar } -fn foo(c: Quux) { assert!((false)); } //~ ERROR missing generics for enum `Quux` +fn foo(c: Quux) { assert!((false)); } //~ ERROR wrong number of type arguments fn main() { panic!(); } diff --git a/src/test/ui/tag-type-args.stderr b/src/test/ui/tag-type-args.stderr index c9888dc54dc52..ac44dad4a888b 100644 --- a/src/test/ui/tag-type-args.stderr +++ b/src/test/ui/tag-type-args.stderr @@ -1,18 +1,8 @@ -error[E0107]: missing generics for enum `Quux` +error[E0107]: wrong number of type arguments: expected 1, found 0 --> $DIR/tag-type-args.rs:3:11 | LL | fn foo(c: Quux) { assert!((false)); } | ^^^^ expected 1 type argument - | -note: enum defined here, with 1 type parameter: `T` - --> $DIR/tag-type-args.rs:1:6 - | -LL | enum Quux { Bar } - | ^^^^ - -help: use angle brackets to add missing type argument - | -LL | fn foo(c: Quux) { assert!((false)); } - | ^^^ error: aborting due to previous error diff --git a/src/test/ui/threads-sendsync/thread-local-extern-static.rs b/src/test/ui/threads-sendsync/thread-local-extern-static.rs index a2dda31aa5539..e10f5174b120f 100644 --- a/src/test/ui/threads-sendsync/thread-local-extern-static.rs +++ b/src/test/ui/threads-sendsync/thread-local-extern-static.rs @@ -11,7 +11,7 @@ extern crate thread_local_extern_static; use std::cell::Cell; #[cfg(target_thread_local)] -extern "C" { +extern { #[thread_local] static FOO: Cell; } diff --git a/src/test/ui/feature-gates/trace_macros-gate.rs b/src/test/ui/trace_macros-gate.rs similarity index 100% rename from src/test/ui/feature-gates/trace_macros-gate.rs rename to src/test/ui/trace_macros-gate.rs diff --git a/src/test/ui/feature-gates/trace_macros-gate.stderr b/src/test/ui/trace_macros-gate.stderr similarity index 100% rename from src/test/ui/feature-gates/trace_macros-gate.stderr rename to src/test/ui/trace_macros-gate.stderr diff --git a/src/test/ui/traits/trait-object-vs-lifetime.rs b/src/test/ui/traits/trait-object-vs-lifetime.rs index e49d276a55a92..e885cd2f68ac5 100644 --- a/src/test/ui/traits/trait-object-vs-lifetime.rs +++ b/src/test/ui/traits/trait-object-vs-lifetime.rs @@ -9,8 +9,8 @@ fn main() { let _: S<'static, dyn 'static +>; //~^ at least one trait is required for an object type let _: S<'static, 'static>; - //~^ ERROR this struct takes 1 lifetime argument but 2 lifetime arguments were supplied - //~| ERROR this struct takes 1 type argument but 0 type arguments were supplied + //~^ ERROR wrong number of lifetime arguments: expected 1, found 2 + //~| ERROR wrong number of type arguments: expected 1, found 0 let _: S; //~^ ERROR type provided when a lifetime was expected //~| ERROR at least one trait is required for an object type diff --git a/src/test/ui/traits/trait-object-vs-lifetime.stderr b/src/test/ui/traits/trait-object-vs-lifetime.stderr index 620c816d6d984..8958547e82709 100644 --- a/src/test/ui/traits/trait-object-vs-lifetime.stderr +++ b/src/test/ui/traits/trait-object-vs-lifetime.stderr @@ -4,35 +4,17 @@ error[E0224]: at least one trait is required for an object type LL | let _: S<'static, dyn 'static +>; | ^^^^^^^^^^^^^ -error[E0107]: this struct takes 1 lifetime argument but 2 lifetime arguments were supplied - --> $DIR/trait-object-vs-lifetime.rs:11:12 +error[E0107]: wrong number of lifetime arguments: expected 1, found 2 + --> $DIR/trait-object-vs-lifetime.rs:11:23 | LL | let _: S<'static, 'static>; - | ^ --------- help: remove this lifetime argument - | | - | expected 1 lifetime argument - | -note: struct defined here, with 1 lifetime parameter: `'a` - --> $DIR/trait-object-vs-lifetime.rs:4:8 - | -LL | struct S<'a, T>(&'a u8, T); - | ^ -- + | ^^^^^^^ unexpected lifetime argument -error[E0107]: this struct takes 1 type argument but 0 type arguments were supplied +error[E0107]: wrong number of type arguments: expected 1, found 0 --> $DIR/trait-object-vs-lifetime.rs:11:12 | LL | let _: S<'static, 'static>; - | ^ expected 1 type argument - | -note: struct defined here, with 1 type parameter: `T` - --> $DIR/trait-object-vs-lifetime.rs:4:8 - | -LL | struct S<'a, T>(&'a u8, T); - | ^ - -help: add missing type argument - | -LL | let _: S<'static, 'static, T>; - | ^^^ + | ^^^^^^^^^^^^^^^^^^^ expected 1 type argument error[E0224]: at least one trait is required for an object type --> $DIR/trait-object-vs-lifetime.rs:14:14 diff --git a/src/test/ui/traits/trait-test-2.rs b/src/test/ui/traits/trait-test-2.rs index a33773144c21b..86570f1152e1e 100644 --- a/src/test/ui/traits/trait-test-2.rs +++ b/src/test/ui/traits/trait-test-2.rs @@ -6,10 +6,8 @@ impl bar for i32 { fn dup(&self) -> i32 { *self } fn blah(&self) {} } impl bar for u32 { fn dup(&self) -> u32 { *self } fn blah(&self) {} } fn main() { - 10.dup::(); - //~^ ERROR this associated function takes 0 type arguments but 1 type argument was supplied - 10.blah::(); - //~^ ERROR this associated function takes 1 type argument but 2 type arguments were supplied + 10.dup::(); //~ ERROR wrong number of type arguments: expected 0, found 1 + 10.blah::(); //~ ERROR wrong number of type arguments: expected 1, found 2 (box 10 as Box).dup(); //~^ ERROR E0038 //~| ERROR E0038 diff --git a/src/test/ui/traits/trait-test-2.stderr b/src/test/ui/traits/trait-test-2.stderr index a38d3387c8d7b..a06f6a49194ff 100644 --- a/src/test/ui/traits/trait-test-2.stderr +++ b/src/test/ui/traits/trait-test-2.stderr @@ -1,33 +1,17 @@ -error[E0107]: this associated function takes 0 type arguments but 1 type argument was supplied - --> $DIR/trait-test-2.rs:9:8 +error[E0107]: wrong number of type arguments: expected 0, found 1 + --> $DIR/trait-test-2.rs:9:14 | LL | 10.dup::(); - | ^^^------- help: remove these generics - | | - | expected 0 type arguments - | -note: associated function defined here, with 0 type parameters - --> $DIR/trait-test-2.rs:4:16 - | -LL | trait bar { fn dup(&self) -> Self; fn blah(&self); } - | ^^^ + | ^^^ unexpected type argument -error[E0107]: this associated function takes 1 type argument but 2 type arguments were supplied - --> $DIR/trait-test-2.rs:11:8 +error[E0107]: wrong number of type arguments: expected 1, found 2 + --> $DIR/trait-test-2.rs:10:20 | LL | 10.blah::(); - | ^^^^ ----- help: remove this type argument - | | - | expected 1 type argument - | -note: associated function defined here, with 1 type parameter: `X` - --> $DIR/trait-test-2.rs:4:39 - | -LL | trait bar { fn dup(&self) -> Self; fn blah(&self); } - | ^^^^ - + | ^^^ unexpected type argument error[E0038]: the trait `bar` cannot be made into an object - --> $DIR/trait-test-2.rs:13:16 + --> $DIR/trait-test-2.rs:11:16 | LL | (box 10 as Box).dup(); | ^^^^^^^^^^^^ `bar` cannot be made into an object @@ -44,7 +28,7 @@ LL | trait bar { fn dup(&self) -> Self; fn blah(&self); } | this trait cannot be made into an object... error[E0038]: the trait `bar` cannot be made into an object - --> $DIR/trait-test-2.rs:13:6 + --> $DIR/trait-test-2.rs:11:6 | LL | (box 10 as Box).dup(); | ^^^^^^ `bar` cannot be made into an object diff --git a/src/test/ui/lint/trivial_casts.rs b/src/test/ui/trivial_casts.rs similarity index 100% rename from src/test/ui/lint/trivial_casts.rs rename to src/test/ui/trivial_casts.rs diff --git a/src/test/ui/lint/trivial_casts.stderr b/src/test/ui/trivial_casts.stderr similarity index 100% rename from src/test/ui/lint/trivial_casts.stderr rename to src/test/ui/trivial_casts.stderr diff --git a/src/test/ui/type-alias-enum-variants/enum-variant-generic-args.rs b/src/test/ui/type-alias-enum-variants/enum-variant-generic-args.rs index f204035248a6f..f182c3ba8c798 100644 --- a/src/test/ui/type-alias-enum-variants/enum-variant-generic-args.rs +++ b/src/test/ui/type-alias-enum-variants/enum-variant-generic-args.rs @@ -16,10 +16,10 @@ impl Enum { //~^ ERROR type arguments are not allowed for this type [E0109] Self::<()>::TSVariant(()); //~^ ERROR type arguments are not allowed for this type [E0109] - //~| ERROR mismatched types [E0308] + //~^^ ERROR mismatched types [E0308] Self::<()>::TSVariant::<()>(()); //~^ ERROR type arguments are not allowed for this type [E0109] - //~| ERROR type arguments are not allowed for this type [E0109] + //~^^ ERROR type arguments are not allowed for this type [E0109] } fn s_variant() { @@ -27,14 +27,14 @@ impl Enum { //~^ ERROR mismatched types [E0308] Self::SVariant::<()> { v: () }; //~^ ERROR type arguments are not allowed for this type [E0109] - //~| ERROR mismatched types [E0308] + //~^^ ERROR mismatched types [E0308] Self::<()>::SVariant { v: () }; //~^ ERROR type arguments are not allowed for this type [E0109] - //~| ERROR mismatched types [E0308] + //~^^ ERROR mismatched types [E0308] Self::<()>::SVariant::<()> { v: () }; //~^ ERROR type arguments are not allowed for this type [E0109] - //~| ERROR type arguments are not allowed for this type [E0109] - //~| ERROR mismatched types [E0308] + //~^^ ERROR type arguments are not allowed for this type [E0109] + //~^^^ ERROR mismatched types [E0308] } fn u_variant() { @@ -44,7 +44,7 @@ impl Enum { //~^ ERROR type arguments are not allowed for this type [E0109] Self::<()>::UVariant::<()>; //~^ ERROR type arguments are not allowed for this type [E0109] - //~| ERROR type arguments are not allowed for this type [E0109] + //~^^ ERROR type arguments are not allowed for this type [E0109] } } @@ -62,10 +62,10 @@ fn main() { AliasFixed::TSVariant::<()>(()); //~^ ERROR type arguments are not allowed for this type [E0109] AliasFixed::<()>::TSVariant(()); - //~^ ERROR this type alias takes 0 type arguments but 1 type argument was supplied [E0107] + //~^ ERROR wrong number of type arguments: expected 0, found 1 [E0107] AliasFixed::<()>::TSVariant::<()>(()); //~^ ERROR type arguments are not allowed for this type [E0109] - //~| ERROR this type alias takes 0 type arguments but 1 type argument was supplied [E0107] + //~^^ ERROR wrong number of type arguments: expected 0, found 1 [E0107] // Struct variant @@ -80,10 +80,10 @@ fn main() { AliasFixed::SVariant::<()> { v: () }; //~^ ERROR type arguments are not allowed for this type [E0109] AliasFixed::<()>::SVariant { v: () }; - //~^ ERROR this type alias takes 0 type arguments but 1 type argument was supplied [E0107] + //~^ ERROR wrong number of type arguments: expected 0, found 1 [E0107] AliasFixed::<()>::SVariant::<()> { v: () }; //~^ ERROR type arguments are not allowed for this type [E0109] - //~| ERROR this type alias takes 0 type arguments but 1 type argument was supplied [E0107] + //~^^ ERROR wrong number of type arguments: expected 0, found 1 [E0107] // Unit variant @@ -98,8 +98,8 @@ fn main() { AliasFixed::UVariant::<()>; //~^ ERROR type arguments are not allowed for this type [E0109] AliasFixed::<()>::UVariant; - //~^ ERROR this type alias takes 0 type arguments but 1 type argument was supplied [E0107] + //~^ ERROR wrong number of type arguments: expected 0, found 1 [E0107] AliasFixed::<()>::UVariant::<()>; //~^ ERROR type arguments are not allowed for this type [E0109] - //~| ERROR this type alias takes 0 type arguments but 1 type argument was supplied [E0107] + //~^^ ERROR wrong number of type arguments: expected 0, found 1 [E0107] } diff --git a/src/test/ui/type-alias-enum-variants/enum-variant-generic-args.stderr b/src/test/ui/type-alias-enum-variants/enum-variant-generic-args.stderr index e83db3b0d512b..caea791e6536b 100644 --- a/src/test/ui/type-alias-enum-variants/enum-variant-generic-args.stderr +++ b/src/test/ui/type-alias-enum-variants/enum-variant-generic-args.stderr @@ -166,33 +166,17 @@ error[E0109]: type arguments are not allowed for this type LL | AliasFixed::TSVariant::<()>(()); | ^^ type argument not allowed -error[E0107]: this type alias takes 0 type arguments but 1 type argument was supplied - --> $DIR/enum-variant-generic-args.rs:64:5 +error[E0107]: wrong number of type arguments: expected 0, found 1 + --> $DIR/enum-variant-generic-args.rs:64:18 | LL | AliasFixed::<()>::TSVariant(()); - | ^^^^^^^^^^------ help: remove these generics - | | - | expected 0 type arguments - | -note: type alias defined here, with 0 type parameters - --> $DIR/enum-variant-generic-args.rs:9:6 - | -LL | type AliasFixed = Enum<()>; - | ^^^^^^^^^^ + | ^^ unexpected type argument -error[E0107]: this type alias takes 0 type arguments but 1 type argument was supplied - --> $DIR/enum-variant-generic-args.rs:66:5 +error[E0107]: wrong number of type arguments: expected 0, found 1 + --> $DIR/enum-variant-generic-args.rs:66:18 | LL | AliasFixed::<()>::TSVariant::<()>(()); - | ^^^^^^^^^^------ help: remove these generics - | | - | expected 0 type arguments - | -note: type alias defined here, with 0 type parameters - --> $DIR/enum-variant-generic-args.rs:9:6 - | -LL | type AliasFixed = Enum<()>; - | ^^^^^^^^^^ + | ^^ unexpected type argument error[E0109]: type arguments are not allowed for this type --> $DIR/enum-variant-generic-args.rs:66:35 @@ -224,33 +208,17 @@ error[E0109]: type arguments are not allowed for this type LL | AliasFixed::SVariant::<()> { v: () }; | ^^ type argument not allowed -error[E0107]: this type alias takes 0 type arguments but 1 type argument was supplied - --> $DIR/enum-variant-generic-args.rs:82:5 +error[E0107]: wrong number of type arguments: expected 0, found 1 + --> $DIR/enum-variant-generic-args.rs:82:18 | LL | AliasFixed::<()>::SVariant { v: () }; - | ^^^^^^^^^^------ help: remove these generics - | | - | expected 0 type arguments - | -note: type alias defined here, with 0 type parameters - --> $DIR/enum-variant-generic-args.rs:9:6 - | -LL | type AliasFixed = Enum<()>; - | ^^^^^^^^^^ + | ^^ unexpected type argument -error[E0107]: this type alias takes 0 type arguments but 1 type argument was supplied - --> $DIR/enum-variant-generic-args.rs:84:5 +error[E0107]: wrong number of type arguments: expected 0, found 1 + --> $DIR/enum-variant-generic-args.rs:84:18 | LL | AliasFixed::<()>::SVariant::<()> { v: () }; - | ^^^^^^^^^^------ help: remove these generics - | | - | expected 0 type arguments - | -note: type alias defined here, with 0 type parameters - --> $DIR/enum-variant-generic-args.rs:9:6 - | -LL | type AliasFixed = Enum<()>; - | ^^^^^^^^^^ + | ^^ unexpected type argument error[E0109]: type arguments are not allowed for this type --> $DIR/enum-variant-generic-args.rs:84:34 @@ -282,33 +250,17 @@ error[E0109]: type arguments are not allowed for this type LL | AliasFixed::UVariant::<()>; | ^^ type argument not allowed -error[E0107]: this type alias takes 0 type arguments but 1 type argument was supplied - --> $DIR/enum-variant-generic-args.rs:100:5 +error[E0107]: wrong number of type arguments: expected 0, found 1 + --> $DIR/enum-variant-generic-args.rs:100:18 | LL | AliasFixed::<()>::UVariant; - | ^^^^^^^^^^------ help: remove these generics - | | - | expected 0 type arguments - | -note: type alias defined here, with 0 type parameters - --> $DIR/enum-variant-generic-args.rs:9:6 - | -LL | type AliasFixed = Enum<()>; - | ^^^^^^^^^^ + | ^^ unexpected type argument -error[E0107]: this type alias takes 0 type arguments but 1 type argument was supplied - --> $DIR/enum-variant-generic-args.rs:102:5 +error[E0107]: wrong number of type arguments: expected 0, found 1 + --> $DIR/enum-variant-generic-args.rs:102:18 | LL | AliasFixed::<()>::UVariant::<()>; - | ^^^^^^^^^^------ help: remove these generics - | | - | expected 0 type arguments - | -note: type alias defined here, with 0 type parameters - --> $DIR/enum-variant-generic-args.rs:9:6 - | -LL | type AliasFixed = Enum<()>; - | ^^^^^^^^^^ + | ^^ unexpected type argument error[E0109]: type arguments are not allowed for this type --> $DIR/enum-variant-generic-args.rs:102:34 diff --git a/src/test/ui/type-alias-enum-variants/enum-variant-priority-higher-than-other-inherent.stderr b/src/test/ui/type-alias-enum-variants/enum-variant-priority-higher-than-other-inherent.stderr index 1d520613a288f..20e260584513a 100644 --- a/src/test/ui/type-alias-enum-variants/enum-variant-priority-higher-than-other-inherent.stderr +++ b/src/test/ui/type-alias-enum-variants/enum-variant-priority-higher-than-other-inherent.stderr @@ -5,6 +5,12 @@ LL | ::V(); | ^^^^^^-- supplied 0 arguments | | | expected 1 argument + | +note: tuple variant defined here + --> $DIR/enum-variant-priority-higher-than-other-inherent.rs:5:5 + | +LL | V(u8) + | ^^^^^ error[E0308]: mismatched types --> $DIR/enum-variant-priority-higher-than-other-inherent.rs:22:17 diff --git a/src/test/ui/type-alias-impl-trait/issue-57611-trait-alias.nll.stderr b/src/test/ui/type-alias-impl-trait/issue-57611-trait-alias.nll.stderr index be1dd1a8524c8..790aea87510e6 100644 --- a/src/test/ui/type-alias-impl-trait/issue-57611-trait-alias.nll.stderr +++ b/src/test/ui/type-alias-impl-trait/issue-57611-trait-alias.nll.stderr @@ -18,11 +18,6 @@ LL | type Bar = impl Baz; | = note: expected type `for<'r> Fn<(&'r X,)>` found type `Fn<(&'static X,)>` -note: this closure does not fulfill the lifetime requirements - --> $DIR/issue-57611-trait-alias.rs:25:9 - | -LL | |x| x - | ^^^^^ error[E0308]: mismatched types --> $DIR/issue-57611-trait-alias.rs:17:16 @@ -32,11 +27,6 @@ LL | type Bar = impl Baz; | = note: expected type `FnOnce<(&X,)>` found type `FnOnce<(&'static X,)>` -note: this closure does not fulfill the lifetime requirements - --> $DIR/issue-57611-trait-alias.rs:25:9 - | -LL | |x| x - | ^^^^^ error: aborting due to 4 previous errors diff --git a/src/test/ui/type-alias-impl-trait/issue-57611-trait-alias.stderr b/src/test/ui/type-alias-impl-trait/issue-57611-trait-alias.stderr index 9d9293e958eeb..5e2a8db02867f 100644 --- a/src/test/ui/type-alias-impl-trait/issue-57611-trait-alias.stderr +++ b/src/test/ui/type-alias-impl-trait/issue-57611-trait-alias.stderr @@ -6,11 +6,6 @@ LL | type Bar = impl Baz; | = note: expected type `FnOnce<(&X,)>` found type `FnOnce<(&X,)>` -note: this closure does not fulfill the lifetime requirements - --> $DIR/issue-57611-trait-alias.rs:25:9 - | -LL | |x| x - | ^^^^^ error[E0308]: mismatched types --> $DIR/issue-57611-trait-alias.rs:17:16 @@ -20,11 +15,6 @@ LL | type Bar = impl Baz; | = note: expected type `for<'r> Fn<(&'r X,)>` found type `Fn<(&' X,)>` -note: this closure does not fulfill the lifetime requirements - --> $DIR/issue-57611-trait-alias.rs:25:9 - | -LL | |x| x - | ^^^^^ error[E0308]: mismatched types --> $DIR/issue-57611-trait-alias.rs:17:16 @@ -34,11 +24,6 @@ LL | type Bar = impl Baz; | = note: expected type `FnOnce<(&X,)>` found type `FnOnce<(&' X,)>` -note: this closure does not fulfill the lifetime requirements - --> $DIR/issue-57611-trait-alias.rs:25:9 - | -LL | |x| x - | ^^^^^ error[E0308]: mismatched types --> $DIR/issue-57611-trait-alias.rs:17:16 @@ -48,11 +33,6 @@ LL | type Bar = impl Baz; | = note: expected type `for<'r> Fn<(&'r X,)>` found type `Fn<(&' X,)>` -note: this closure does not fulfill the lifetime requirements - --> $DIR/issue-57611-trait-alias.rs:25:9 - | -LL | |x| x - | ^^^^^ error[E0308]: mismatched types --> $DIR/issue-57611-trait-alias.rs:17:16 @@ -62,11 +42,6 @@ LL | type Bar = impl Baz; | = note: expected type `FnOnce<(&X,)>` found type `FnOnce<(&' X,)>` -note: this closure does not fulfill the lifetime requirements - --> $DIR/issue-57611-trait-alias.rs:25:9 - | -LL | |x| x - | ^^^^^ error: aborting due to 5 previous errors diff --git a/src/test/ui/type-param.rs b/src/test/ui/type-param.rs index ca2f24d379bc6..f5ac19cf73aa8 100644 --- a/src/test/ui/type-param.rs +++ b/src/test/ui/type-param.rs @@ -6,6 +6,6 @@ // pretty-expanded FIXME #23616 -type lteq = extern "C" fn(T) -> bool; +type lteq = extern fn(T) -> bool; pub fn main() { } diff --git a/src/test/ui/type-params-in-for-each.rs b/src/test/ui/type-params-in-for-each.rs index 53475d2804794..be4a0185edaf4 100644 --- a/src/test/ui/type-params-in-for-each.rs +++ b/src/test/ui/type-params-in-for-each.rs @@ -14,7 +14,7 @@ fn range_(lo: usize, hi: usize, mut it: F) where F: FnMut(usize) { while lo_ < hi { it(lo_); lo_ += 1; } } -fn create_index(_index: Vec> , _hash_fn: extern "C" fn(T) -> usize) { +fn create_index(_index: Vec> , _hash_fn: extern fn(T) -> usize) { range_(0, 256, |_i| { let _bucket: Vec = Vec::new(); }) diff --git a/src/test/ui/type/ascription/issue-34255-1.rs b/src/test/ui/type/ascription/issue-34255-1.rs index 44b47cc4eb2a2..3aad085f08972 100644 --- a/src/test/ui/type/ascription/issue-34255-1.rs +++ b/src/test/ui/type/ascription/issue-34255-1.rs @@ -7,7 +7,7 @@ impl Reactor { input_cells: Vec::new() //~^ ERROR cannot find value `input_cells` in this scope //~| ERROR parenthesized type parameters may only be used with a `Fn` trait - //~| ERROR missing generics for struct `Vec` + //~| ERROR wrong number of type arguments: expected at least 1, found 0 } } diff --git a/src/test/ui/type/ascription/issue-34255-1.stderr b/src/test/ui/type/ascription/issue-34255-1.stderr index fc474e1ec3b75..402e54d2a95dd 100644 --- a/src/test/ui/type/ascription/issue-34255-1.stderr +++ b/src/test/ui/type/ascription/issue-34255-1.stderr @@ -10,21 +10,11 @@ error[E0214]: parenthesized type parameters may only be used with a `Fn` trait LL | input_cells: Vec::new() | ^^^^^ only `Fn` traits may use parentheses -error[E0107]: missing generics for struct `Vec` +error[E0107]: wrong number of type arguments: expected at least 1, found 0 --> $DIR/issue-34255-1.rs:7:22 | LL | input_cells: Vec::new() - | ^^^ expected at least 1 type argument - | -note: struct defined here, with at least 1 type parameter: `T` - --> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL - | -LL | pub struct Vec { - | ^^^ - -help: use angle brackets to add missing type argument - | -LL | input_cells: Vec::new() - | ^^^ + | ^^^^^^^^^^ expected at least 1 type argument error: aborting due to 3 previous errors diff --git a/src/test/ui/type/ascription/issue-47666.stderr b/src/test/ui/type/ascription/issue-47666.stderr index 755eec23c2ee3..ba393ff1a208e 100644 --- a/src/test/ui/type/ascription/issue-47666.stderr +++ b/src/test/ui/type/ascription/issue-47666.stderr @@ -1,4 +1,4 @@ -error: expected type, found `<[_]>::into_vec(box [0, 1])` +error: expected type, found reserved keyword `box` --> $DIR/issue-47666.rs:3:25 | LL | let _ = Option:Some(vec![0, 1]); diff --git a/src/test/ui/type/type-ascription-instead-of-initializer.stderr b/src/test/ui/type/type-ascription-instead-of-initializer.stderr index e5666d4fe4f4b..530f77e5ae9b9 100644 --- a/src/test/ui/type/type-ascription-instead-of-initializer.stderr +++ b/src/test/ui/type/type-ascription-instead-of-initializer.stderr @@ -14,12 +14,6 @@ LL | let x: Vec::with_capacity(10, 20); | ^^^^^^^^^^^^^^^^^^ -- -- supplied 2 arguments | | | expected 1 argument - | -note: associated function defined here - --> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL - | -LL | pub fn with_capacity(capacity: usize) -> Self { - | ^^^^^^^^^^^^^ error: aborting due to 2 previous errors diff --git a/src/test/ui/typeck/typeck-builtin-bound-type-parameters.rs b/src/test/ui/typeck/typeck-builtin-bound-type-parameters.rs index f1659d086702e..f466c19e051ed 100644 --- a/src/test/ui/typeck/typeck-builtin-bound-type-parameters.rs +++ b/src/test/ui/typeck/typeck-builtin-bound-type-parameters.rs @@ -1,17 +1,19 @@ fn foo1, U>(x: T) {} -//~^ ERROR this trait takes 0 type arguments but 1 type argument was supplied +//~^ ERROR wrong number of type arguments: expected 0, found 1 [E0107] trait Trait: Copy {} -//~^ ERROR this trait takes 0 type arguments but 1 type argument was supplied +//~^ ERROR wrong number of type arguments: expected 0, found 1 [E0107] struct MyStruct1>; -//~^ ERROR this trait takes 0 type arguments but 1 type argument was supplied +//~^ ERROR wrong number of type arguments: expected 0, found 1 [E0107] struct MyStruct2<'a, T: Copy<'a>>; -//~^ ERROR this trait takes 0 lifetime arguments but 1 lifetime argument was supplied +//~^ ERROR: wrong number of lifetime arguments: expected 0, found 1 [E0107] + fn foo2<'a, T:Copy<'a, U>, U>(x: T) {} -//~^ ERROR this trait takes 0 lifetime arguments but 1 lifetime argument was supplied -//~| ERROR this trait takes 0 type arguments but 1 type argument was supplied +//~^ ERROR wrong number of type arguments: expected 0, found 1 [E0107] +//~| ERROR: wrong number of lifetime arguments: expected 0, found 1 -fn main() { } +fn main() { +} diff --git a/src/test/ui/typeck/typeck-builtin-bound-type-parameters.stderr b/src/test/ui/typeck/typeck-builtin-bound-type-parameters.stderr index 777bc1c95b0b3..0be1c8ef3bc16 100644 --- a/src/test/ui/typeck/typeck-builtin-bound-type-parameters.stderr +++ b/src/test/ui/typeck/typeck-builtin-bound-type-parameters.stderr @@ -1,86 +1,38 @@ -error[E0107]: this trait takes 0 type arguments but 1 type argument was supplied - --> $DIR/typeck-builtin-bound-type-parameters.rs:1:11 +error[E0107]: wrong number of type arguments: expected 0, found 1 + --> $DIR/typeck-builtin-bound-type-parameters.rs:1:16 | LL | fn foo1, U>(x: T) {} - | ^^^^--- help: remove these generics - | | - | expected 0 type arguments - | -note: trait defined here, with 0 type parameters - --> $SRC_DIR/core/src/marker.rs:LL:COL - | -LL | pub trait Copy: Clone { - | ^^^^ + | ^ unexpected type argument -error[E0107]: this trait takes 0 type arguments but 1 type argument was supplied - --> $DIR/typeck-builtin-bound-type-parameters.rs:4:14 +error[E0107]: wrong number of type arguments: expected 0, found 1 + --> $DIR/typeck-builtin-bound-type-parameters.rs:4:19 | LL | trait Trait: Copy {} - | ^^^^---------- help: remove these generics - | | - | expected 0 type arguments - | -note: trait defined here, with 0 type parameters - --> $SRC_DIR/core/src/marker.rs:LL:COL - | -LL | pub trait Copy: Clone { - | ^^^^ + | ^^^^^^^^ unexpected type argument -error[E0107]: this trait takes 0 type arguments but 1 type argument was supplied - --> $DIR/typeck-builtin-bound-type-parameters.rs:7:21 +error[E0107]: wrong number of type arguments: expected 0, found 1 + --> $DIR/typeck-builtin-bound-type-parameters.rs:7:26 | LL | struct MyStruct1>; - | ^^^^--- help: remove these generics - | | - | expected 0 type arguments - | -note: trait defined here, with 0 type parameters - --> $SRC_DIR/core/src/marker.rs:LL:COL - | -LL | pub trait Copy: Clone { - | ^^^^ + | ^ unexpected type argument -error[E0107]: this trait takes 0 lifetime arguments but 1 lifetime argument was supplied - --> $DIR/typeck-builtin-bound-type-parameters.rs:10:25 +error[E0107]: wrong number of lifetime arguments: expected 0, found 1 + --> $DIR/typeck-builtin-bound-type-parameters.rs:10:30 | LL | struct MyStruct2<'a, T: Copy<'a>>; - | ^^^^---- help: remove these generics - | | - | expected 0 lifetime arguments - | -note: trait defined here, with 0 lifetime parameters - --> $SRC_DIR/core/src/marker.rs:LL:COL - | -LL | pub trait Copy: Clone { - | ^^^^ + | ^^ unexpected lifetime argument -error[E0107]: this trait takes 0 lifetime arguments but 1 lifetime argument was supplied - --> $DIR/typeck-builtin-bound-type-parameters.rs:13:15 +error[E0107]: wrong number of lifetime arguments: expected 0, found 1 + --> $DIR/typeck-builtin-bound-type-parameters.rs:14:20 | LL | fn foo2<'a, T:Copy<'a, U>, U>(x: T) {} - | ^^^^ ---- help: remove this lifetime argument - | | - | expected 0 lifetime arguments - | -note: trait defined here, with 0 lifetime parameters - --> $SRC_DIR/core/src/marker.rs:LL:COL - | -LL | pub trait Copy: Clone { - | ^^^^ + | ^^ unexpected lifetime argument -error[E0107]: this trait takes 0 type arguments but 1 type argument was supplied - --> $DIR/typeck-builtin-bound-type-parameters.rs:13:15 +error[E0107]: wrong number of type arguments: expected 0, found 1 + --> $DIR/typeck-builtin-bound-type-parameters.rs:14:24 | LL | fn foo2<'a, T:Copy<'a, U>, U>(x: T) {} - | ^^^^ --- help: remove this type argument - | | - | expected 0 type arguments - | -note: trait defined here, with 0 type parameters - --> $SRC_DIR/core/src/marker.rs:LL:COL - | -LL | pub trait Copy: Clone { - | ^^^^ + | ^ unexpected type argument error: aborting due to 6 previous errors diff --git a/src/test/ui/typeck/typeck_type_placeholder_lifetime_1.rs b/src/test/ui/typeck/typeck_type_placeholder_lifetime_1.rs index 8f8917e16afda..57ab7dee0e893 100644 --- a/src/test/ui/typeck/typeck_type_placeholder_lifetime_1.rs +++ b/src/test/ui/typeck/typeck_type_placeholder_lifetime_1.rs @@ -7,5 +7,5 @@ struct Foo<'a, T:'a> { pub fn main() { let c: Foo<_, _> = Foo { r: &5 }; - //~^ ERROR this struct takes 1 type argument but 2 type arguments were supplied + //~^ ERROR wrong number of type arguments: expected 1, found 2 [E0107] } diff --git a/src/test/ui/typeck/typeck_type_placeholder_lifetime_1.stderr b/src/test/ui/typeck/typeck_type_placeholder_lifetime_1.stderr index 01ab8e78d7ca3..8186d75f92041 100644 --- a/src/test/ui/typeck/typeck_type_placeholder_lifetime_1.stderr +++ b/src/test/ui/typeck/typeck_type_placeholder_lifetime_1.stderr @@ -1,16 +1,8 @@ -error[E0107]: this struct takes 1 type argument but 2 type arguments were supplied - --> $DIR/typeck_type_placeholder_lifetime_1.rs:9:12 +error[E0107]: wrong number of type arguments: expected 1, found 2 + --> $DIR/typeck_type_placeholder_lifetime_1.rs:9:19 | LL | let c: Foo<_, _> = Foo { r: &5 }; - | ^^^ --- help: remove this type argument - | | - | expected 1 type argument - | -note: struct defined here, with 1 type parameter: `T` - --> $DIR/typeck_type_placeholder_lifetime_1.rs:4:8 - | -LL | struct Foo<'a, T:'a> { - | ^^^ - + | ^ unexpected type argument error: aborting due to previous error diff --git a/src/test/ui/typeck/typeck_type_placeholder_lifetime_2.rs b/src/test/ui/typeck/typeck_type_placeholder_lifetime_2.rs index b491a7e1a9caa..b68d2832b4ff7 100644 --- a/src/test/ui/typeck/typeck_type_placeholder_lifetime_2.rs +++ b/src/test/ui/typeck/typeck_type_placeholder_lifetime_2.rs @@ -7,5 +7,5 @@ struct Foo<'a, T:'a> { pub fn main() { let c: Foo<_, usize> = Foo { r: &5 }; - //~^ ERROR this struct takes 1 type argument but 2 type arguments were supplied + //~^ ERROR wrong number of type arguments: expected 1, found 2 [E0107] } diff --git a/src/test/ui/typeck/typeck_type_placeholder_lifetime_2.stderr b/src/test/ui/typeck/typeck_type_placeholder_lifetime_2.stderr index 6d03b833c0f15..9b0f9695ef723 100644 --- a/src/test/ui/typeck/typeck_type_placeholder_lifetime_2.stderr +++ b/src/test/ui/typeck/typeck_type_placeholder_lifetime_2.stderr @@ -1,16 +1,8 @@ -error[E0107]: this struct takes 1 type argument but 2 type arguments were supplied - --> $DIR/typeck_type_placeholder_lifetime_2.rs:9:12 +error[E0107]: wrong number of type arguments: expected 1, found 2 + --> $DIR/typeck_type_placeholder_lifetime_2.rs:9:19 | LL | let c: Foo<_, usize> = Foo { r: &5 }; - | ^^^ ------- help: remove this type argument - | | - | expected 1 type argument - | -note: struct defined here, with 1 type parameter: `T` - --> $DIR/typeck_type_placeholder_lifetime_2.rs:4:8 - | -LL | struct Foo<'a, T:'a> { - | ^^^ - + | ^^^^^ unexpected type argument error: aborting due to previous error diff --git a/src/test/ui/typestate-cfg-nesting.rs b/src/test/ui/typestate-cfg-nesting.rs new file mode 100644 index 0000000000000..5718e0efd1826 --- /dev/null +++ b/src/test/ui/typestate-cfg-nesting.rs @@ -0,0 +1,20 @@ +// run-pass + +#![allow(dead_code)] +#![allow(unused_assignments)] +#![allow(unknown_lints)] +// pretty-expanded FIXME #23616 + +#![allow(dead_assignment)] +#![allow(unused_variables)] + +fn f() { + let x = 10; let mut y = 11; + if true { match x { _ => { y = x; } } } else { } +} + +pub fn main() { + let x = 10; + let mut y = 11; + if true { while false { y = x; } } else { } +} diff --git a/src/test/ui/ufcs/ufcs-qpath-missing-params.rs b/src/test/ui/ufcs/ufcs-qpath-missing-params.rs index 7d2fbdae6a2b2..8b66a8fa90a06 100644 --- a/src/test/ui/ufcs/ufcs-qpath-missing-params.rs +++ b/src/test/ui/ufcs/ufcs-qpath-missing-params.rs @@ -12,9 +12,5 @@ impl<'a> IntoCow<'a, str> for String { fn main() { ::into_cow("foo".to_string()); - //~^ ERROR missing generics for trait `IntoCow` - - ::into_cow::("foo".to_string()); - //~^ ERROR missing generics for trait `IntoCow` - //~| ERROR this associated function takes 0 type arguments but 1 type argument was supplied + //~^ ERROR wrong number of type arguments: expected 1, found 0 } diff --git a/src/test/ui/ufcs/ufcs-qpath-missing-params.stderr b/src/test/ui/ufcs/ufcs-qpath-missing-params.stderr index e3fcef3dc1bb2..1145f1e6409b6 100644 --- a/src/test/ui/ufcs/ufcs-qpath-missing-params.stderr +++ b/src/test/ui/ufcs/ufcs-qpath-missing-params.stderr @@ -1,49 +1,9 @@ -error[E0107]: missing generics for trait `IntoCow` - --> $DIR/ufcs-qpath-missing-params.rs:14:16 +error[E0107]: wrong number of type arguments: expected 1, found 0 + --> $DIR/ufcs-qpath-missing-params.rs:14:5 | LL | ::into_cow("foo".to_string()); - | ^^^^^^^ expected 1 type argument - | -note: trait defined here, with 1 type parameter: `B` - --> $DIR/ufcs-qpath-missing-params.rs:3:11 - | -LL | pub trait IntoCow<'a, B: ?Sized> where B: ToOwned { - | ^^^^^^^ - -help: use angle brackets to add missing type argument - | -LL | >::into_cow("foo".to_string()); - | ^^^ - -error[E0107]: missing generics for trait `IntoCow` - --> $DIR/ufcs-qpath-missing-params.rs:17:16 - | -LL | ::into_cow::("foo".to_string()); - | ^^^^^^^ expected 1 type argument - | -note: trait defined here, with 1 type parameter: `B` - --> $DIR/ufcs-qpath-missing-params.rs:3:11 - | -LL | pub trait IntoCow<'a, B: ?Sized> where B: ToOwned { - | ^^^^^^^ - -help: use angle brackets to add missing type argument - | -LL | >::into_cow::("foo".to_string()); - | ^^^ - -error[E0107]: this associated function takes 0 type arguments but 1 type argument was supplied - --> $DIR/ufcs-qpath-missing-params.rs:17:26 - | -LL | ::into_cow::("foo".to_string()); - | ^^^^^^^^------- help: remove these generics - | | - | expected 0 type arguments - | -note: associated function defined here, with 0 type parameters - --> $DIR/ufcs-qpath-missing-params.rs:4:8 - | -LL | fn into_cow(self) -> Cow<'a, B>; - | ^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected 1 type argument -error: aborting due to 3 previous errors +error: aborting due to previous error For more information about this error, try `rustc --explain E0107`. diff --git a/src/test/ui/unboxed-closures/issue-30906.stderr b/src/test/ui/unboxed-closures/issue-30906.stderr index ecf3a96b5a8dc..5f343ff74a1c5 100644 --- a/src/test/ui/unboxed-closures/issue-30906.stderr +++ b/src/test/ui/unboxed-closures/issue-30906.stderr @@ -2,15 +2,10 @@ error[E0308]: mismatched types --> $DIR/issue-30906.rs:15:5 | LL | test(Compose(f, |_| {})); - | ^^^^ lifetime mismatch + | ^^^^ one type is more general than the other | = note: expected type `FnOnce<(&'x str,)>` found type `FnOnce<(&str,)>` -note: the lifetime requirement is introduced here - --> $DIR/issue-30906.rs:3:12 - | -LL | fn test FnOnce<(&'x str,)>>(_: F) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to previous error diff --git a/src/test/ui/unboxed-closures/unboxed-closure-sugar-region.rs b/src/test/ui/unboxed-closures/unboxed-closure-sugar-region.rs index 65f40075bd8eb..76c928d7b6ab5 100644 --- a/src/test/ui/unboxed-closures/unboxed-closure-sugar-region.rs +++ b/src/test/ui/unboxed-closures/unboxed-closure-sugar-region.rs @@ -28,7 +28,7 @@ fn test<'a,'b>() { } fn test2(x: &dyn Foo<(isize,),Output=()>, y: &dyn Foo(isize)) { - //~^ ERROR this trait takes 1 lifetime argument but 0 lifetime arguments were supplied +//~^ ERROR wrong number of lifetime arguments: expected 1, found 0 // Here, the omitted lifetimes are expanded to distinct things. same_type(x, y) } diff --git a/src/test/ui/unboxed-closures/unboxed-closure-sugar-region.stderr b/src/test/ui/unboxed-closures/unboxed-closure-sugar-region.stderr index 016fc4dfb2404..e9d51983a7a48 100644 --- a/src/test/ui/unboxed-closures/unboxed-closure-sugar-region.stderr +++ b/src/test/ui/unboxed-closures/unboxed-closure-sugar-region.stderr @@ -1,14 +1,8 @@ -error[E0107]: this trait takes 1 lifetime argument but 0 lifetime arguments were supplied +error[E0107]: wrong number of lifetime arguments: expected 1, found 0 --> $DIR/unboxed-closure-sugar-region.rs:30:51 | LL | fn test2(x: &dyn Foo<(isize,),Output=()>, y: &dyn Foo(isize)) { - | ^^^ expected 1 lifetime argument - | -note: trait defined here, with 1 lifetime parameter: `'a` - --> $DIR/unboxed-closure-sugar-region.rs:10:7 - | -LL | trait Foo<'a,T> { - | ^^^ -- + | ^^^^^^^^^^ expected 1 lifetime argument error: aborting due to previous error diff --git a/src/test/ui/unboxed-closures/unboxed-closure-sugar-used-on-struct-1.rs b/src/test/ui/unboxed-closures/unboxed-closure-sugar-used-on-struct-1.rs index a82856add5942..c96a6fa8b6c91 100644 --- a/src/test/ui/unboxed-closures/unboxed-closure-sugar-used-on-struct-1.rs +++ b/src/test/ui/unboxed-closures/unboxed-closure-sugar-used-on-struct-1.rs @@ -7,7 +7,7 @@ struct Bar { fn bar() { let x: Box = panic!(); //~^ ERROR parenthesized type parameters may only be used with a `Fn` trait - //~| ERROR missing generics for struct `Bar` + //~| ERROR wrong number of type arguments: expected 1, found 0 } fn main() { } diff --git a/src/test/ui/unboxed-closures/unboxed-closure-sugar-used-on-struct-1.stderr b/src/test/ui/unboxed-closures/unboxed-closure-sugar-used-on-struct-1.stderr index d81975abbe992..32619420f6d53 100644 --- a/src/test/ui/unboxed-closures/unboxed-closure-sugar-used-on-struct-1.stderr +++ b/src/test/ui/unboxed-closures/unboxed-closure-sugar-used-on-struct-1.stderr @@ -4,21 +4,11 @@ error[E0214]: parenthesized type parameters may only be used with a `Fn` trait LL | let x: Box = panic!(); | ^^^^^ only `Fn` traits may use parentheses -error[E0107]: missing generics for struct `Bar` +error[E0107]: wrong number of type arguments: expected 1, found 0 --> $DIR/unboxed-closure-sugar-used-on-struct-1.rs:8:16 | LL | let x: Box = panic!(); - | ^^^ expected 1 type argument - | -note: struct defined here, with 1 type parameter: `A` - --> $DIR/unboxed-closure-sugar-used-on-struct-1.rs:3:8 - | -LL | struct Bar { - | ^^^ - -help: use angle brackets to add missing type argument - | -LL | let x: Box()> = panic!(); - | ^^^ + | ^^^^^ expected 1 type argument error: aborting due to 2 previous errors diff --git a/src/test/ui/unboxed-closures/unboxed-closure-sugar-used-on-struct.rs b/src/test/ui/unboxed-closures/unboxed-closure-sugar-used-on-struct.rs index b44505f8a4133..1af7f55674c6a 100644 --- a/src/test/ui/unboxed-closures/unboxed-closure-sugar-used-on-struct.rs +++ b/src/test/ui/unboxed-closures/unboxed-closure-sugar-used-on-struct.rs @@ -6,7 +6,7 @@ struct Bar { fn foo(b: Box) { //~^ ERROR parenthesized type parameters may only be used with a `Fn` trait - //~| ERROR missing generics for struct `Bar` + //~| ERROR wrong number of type arguments: expected 1, found 0 } fn main() { } diff --git a/src/test/ui/unboxed-closures/unboxed-closure-sugar-used-on-struct.stderr b/src/test/ui/unboxed-closures/unboxed-closure-sugar-used-on-struct.stderr index 80d7c2402b6cf..ba93b60dad878 100644 --- a/src/test/ui/unboxed-closures/unboxed-closure-sugar-used-on-struct.stderr +++ b/src/test/ui/unboxed-closures/unboxed-closure-sugar-used-on-struct.stderr @@ -4,21 +4,11 @@ error[E0214]: parenthesized type parameters may only be used with a `Fn` trait LL | fn foo(b: Box) { | ^^^^^ only `Fn` traits may use parentheses -error[E0107]: missing generics for struct `Bar` +error[E0107]: wrong number of type arguments: expected 1, found 0 --> $DIR/unboxed-closure-sugar-used-on-struct.rs:7:15 | LL | fn foo(b: Box) { - | ^^^ expected 1 type argument - | -note: struct defined here, with 1 type parameter: `A` - --> $DIR/unboxed-closure-sugar-used-on-struct.rs:3:8 - | -LL | struct Bar { - | ^^^ - -help: use angle brackets to add missing type argument - | -LL | fn foo(b: Box()>) { - | ^^^ + | ^^^^^ expected 1 type argument error: aborting due to 2 previous errors diff --git a/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-number-number-type-parameters-3.rs b/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-number-number-type-parameters-3.rs index a496b7da2f10a..01c76d64c6ba0 100644 --- a/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-number-number-type-parameters-3.rs +++ b/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-number-number-type-parameters-3.rs @@ -3,7 +3,7 @@ trait Three { fn dummy(&self) -> (A,B,C); } fn foo(_: &dyn Three()) -//~^ ERROR this trait takes 3 type arguments but only 1 type argument was supplied +//~^ ERROR wrong number of type arguments //~| ERROR associated type `Output` not found {} diff --git a/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-number-number-type-parameters-3.stderr b/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-number-number-type-parameters-3.stderr index ef5e7d222b4b7..f42ac38d370d5 100644 --- a/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-number-number-type-parameters-3.stderr +++ b/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-number-number-type-parameters-3.stderr @@ -1,16 +1,8 @@ -error[E0107]: this trait takes 3 type arguments but only 1 type argument was supplied +error[E0107]: wrong number of type arguments: expected 3, found 1 --> $DIR/unboxed-closure-sugar-wrong-number-number-type-parameters-3.rs:5:16 | LL | fn foo(_: &dyn Three()) - | ^^^^^-- supplied 1 type argument - | | - | expected 3 type arguments - | -note: trait defined here, with 3 type parameters: `A`, `B`, `C` - --> $DIR/unboxed-closure-sugar-wrong-number-number-type-parameters-3.rs:3:7 - | -LL | trait Three { fn dummy(&self) -> (A,B,C); } - | ^^^^^ - - - + | ^^^^^^^ expected 3 type arguments error[E0220]: associated type `Output` not found for `Three<(), [type error], [type error]>` --> $DIR/unboxed-closure-sugar-wrong-number-number-type-parameters-3.rs:5:16 diff --git a/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-number-number-type-parameters.rs b/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-number-number-type-parameters.rs index d0c85150efe2b..bc9901c795b3a 100644 --- a/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-number-number-type-parameters.rs +++ b/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-number-number-type-parameters.rs @@ -2,27 +2,9 @@ trait Zero { fn dummy(&self); } -fn foo1(_: dyn Zero()) { - //~^ ERROR this trait takes 0 type arguments but 1 type argument was supplied +fn foo(_: dyn Zero()) + //~^ ERROR wrong number of type arguments //~| ERROR associated type `Output` not found for `Zero` -} - -fn foo2(_: dyn Zero) { - //~^ ERROR this trait takes 0 type arguments but 1 type argument was supplied -} - -fn foo3(_: dyn Zero < usize >) { - //~^ ERROR this trait takes 0 type arguments but 1 type argument was supplied -} - -fn foo4(_: dyn Zero(usize)) { - //~^ ERROR this trait takes 0 type arguments but 1 type argument was supplied - //~| ERROR associated type `Output` not found for `Zero` -} - -fn foo5(_: dyn Zero ( usize )) { - //~^ ERROR this trait takes 0 type arguments but 1 type argument was supplied - //~| ERROR associated type `Output` not found for `Zero` -} +{} fn main() { } diff --git a/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-number-number-type-parameters.stderr b/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-number-number-type-parameters.stderr index 2e620a5563f55..8185a798e7b65 100644 --- a/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-number-number-type-parameters.stderr +++ b/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-number-number-type-parameters.stderr @@ -1,92 +1,16 @@ -error[E0107]: this trait takes 0 type arguments but 1 type argument was supplied - --> $DIR/unboxed-closure-sugar-wrong-number-number-type-parameters.rs:5:16 +error[E0107]: wrong number of type arguments: expected 0, found 1 + --> $DIR/unboxed-closure-sugar-wrong-number-number-type-parameters.rs:5:15 | -LL | fn foo1(_: dyn Zero()) { - | ^^^^-- help: remove these parenthetical generics - | | - | expected 0 type arguments - | -note: trait defined here, with 0 type parameters - --> $DIR/unboxed-closure-sugar-wrong-number-number-type-parameters.rs:3:7 - | -LL | trait Zero { fn dummy(&self); } - | ^^^^ - -error[E0220]: associated type `Output` not found for `Zero` - --> $DIR/unboxed-closure-sugar-wrong-number-number-type-parameters.rs:5:16 - | -LL | fn foo1(_: dyn Zero()) { - | ^^^^^^ associated type `Output` not found - -error[E0107]: this trait takes 0 type arguments but 1 type argument was supplied - --> $DIR/unboxed-closure-sugar-wrong-number-number-type-parameters.rs:10:16 - | -LL | fn foo2(_: dyn Zero) { - | ^^^^------- help: remove these generics - | | - | expected 0 type arguments - | -note: trait defined here, with 0 type parameters - --> $DIR/unboxed-closure-sugar-wrong-number-number-type-parameters.rs:3:7 - | -LL | trait Zero { fn dummy(&self); } - | ^^^^ - -error[E0107]: this trait takes 0 type arguments but 1 type argument was supplied - --> $DIR/unboxed-closure-sugar-wrong-number-number-type-parameters.rs:14:16 - | -LL | fn foo3(_: dyn Zero < usize >) { - | ^^^^-------------- help: remove these generics - | | - | expected 0 type arguments - | -note: trait defined here, with 0 type parameters - --> $DIR/unboxed-closure-sugar-wrong-number-number-type-parameters.rs:3:7 - | -LL | trait Zero { fn dummy(&self); } - | ^^^^ - -error[E0107]: this trait takes 0 type arguments but 1 type argument was supplied - --> $DIR/unboxed-closure-sugar-wrong-number-number-type-parameters.rs:18:16 - | -LL | fn foo4(_: dyn Zero(usize)) { - | ^^^^------- help: remove these parenthetical generics - | | - | expected 0 type arguments - | -note: trait defined here, with 0 type parameters - --> $DIR/unboxed-closure-sugar-wrong-number-number-type-parameters.rs:3:7 - | -LL | trait Zero { fn dummy(&self); } - | ^^^^ - -error[E0220]: associated type `Output` not found for `Zero` - --> $DIR/unboxed-closure-sugar-wrong-number-number-type-parameters.rs:18:16 - | -LL | fn foo4(_: dyn Zero(usize)) { - | ^^^^^^^^^^^ associated type `Output` not found - -error[E0107]: this trait takes 0 type arguments but 1 type argument was supplied - --> $DIR/unboxed-closure-sugar-wrong-number-number-type-parameters.rs:23:16 - | -LL | fn foo5(_: dyn Zero ( usize )) { - | ^^^^-------------- help: remove these parenthetical generics - | | - | expected 0 type arguments - | -note: trait defined here, with 0 type parameters - --> $DIR/unboxed-closure-sugar-wrong-number-number-type-parameters.rs:3:7 - | -LL | trait Zero { fn dummy(&self); } - | ^^^^ +LL | fn foo(_: dyn Zero()) + | ^^^^^^ unexpected type argument error[E0220]: associated type `Output` not found for `Zero` - --> $DIR/unboxed-closure-sugar-wrong-number-number-type-parameters.rs:23:16 + --> $DIR/unboxed-closure-sugar-wrong-number-number-type-parameters.rs:5:15 | -LL | fn foo5(_: dyn Zero ( usize )) { - | ^^^^^^^^^^^^^^^^^^ associated type `Output` not found +LL | fn foo(_: dyn Zero()) + | ^^^^^^ associated type `Output` not found -error: aborting due to 8 previous errors +error: aborting due to 2 previous errors Some errors have detailed explanations: E0107, E0220. For more information about an error, try `rustc --explain E0107`. diff --git a/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-trait.rs b/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-trait.rs index 5a47942e5afc6..3e5342ca7df4a 100644 --- a/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-trait.rs +++ b/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-trait.rs @@ -3,7 +3,7 @@ trait Trait {} fn f isize>(x: F) {} -//~^ ERROR this trait takes 0 type arguments but 1 type argument was supplied -//~| ERROR associated type `Output` not found for `Trait` +//~^ ERROR wrong number of type arguments: expected 0, found 1 [E0107] +//~| ERROR E0220 fn main() {} diff --git a/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-trait.stderr b/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-trait.stderr index b88a316c0c9dc..c81402a3dcc00 100644 --- a/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-trait.stderr +++ b/src/test/ui/unboxed-closures/unboxed-closure-sugar-wrong-trait.stderr @@ -1,16 +1,8 @@ -error[E0107]: this trait takes 0 type arguments but 1 type argument was supplied +error[E0107]: wrong number of type arguments: expected 0, found 1 --> $DIR/unboxed-closure-sugar-wrong-trait.rs:5:8 | LL | fn f isize>(x: F) {} - | ^^^^^------- help: remove these parenthetical generics - | | - | expected 0 type arguments - | -note: trait defined here, with 0 type parameters - --> $DIR/unboxed-closure-sugar-wrong-trait.rs:3:7 - | -LL | trait Trait {} - | ^^^^^ + | ^^^^^^^^^^^^ unexpected type argument error[E0220]: associated type `Output` not found for `Trait` --> $DIR/unboxed-closure-sugar-wrong-trait.rs:5:24 diff --git a/src/test/ui/underscore-imports/hygiene.rs b/src/test/ui/underscore-imports/hygiene.rs index c4db65245386f..a254f6eaa5980 100644 --- a/src/test/ui/underscore-imports/hygiene.rs +++ b/src/test/ui/underscore-imports/hygiene.rs @@ -1,6 +1,5 @@ -// Make sure that underscore imports have the same hygiene considerations as other imports. - -// check-pass +// Make sure that underscore imports have the same hygiene considerations as +// other imports. #![feature(decl_macro)] @@ -8,6 +7,7 @@ mod x { pub use std::ops::Deref as _; } + macro glob_import() { pub use crate::x::*; } @@ -35,6 +35,6 @@ fn main() { use crate::z::*; glob_import!(); underscore_import!(); - (&()).deref(); - (&mut ()).deref_mut(); + (&()).deref(); //~ ERROR no method named `deref` + (&mut ()).deref_mut(); //~ ERROR no method named `deref_mut` } diff --git a/src/test/ui/underscore-imports/hygiene.stderr b/src/test/ui/underscore-imports/hygiene.stderr new file mode 100644 index 0000000000000..2983613786038 --- /dev/null +++ b/src/test/ui/underscore-imports/hygiene.stderr @@ -0,0 +1,27 @@ +error[E0599]: no method named `deref` found for reference `&()` in the current scope + --> $DIR/hygiene.rs:38:11 + | +LL | (&()).deref(); + | ^^^^^ method not found in `&()` + | + = help: items from traits can only be used if the trait is in scope +help: the following trait is implemented but not in scope; perhaps add a `use` for it: + | +LL | use std::ops::Deref; + | + +error[E0599]: no method named `deref_mut` found for mutable reference `&mut ()` in the current scope + --> $DIR/hygiene.rs:39:15 + | +LL | (&mut ()).deref_mut(); + | ^^^^^^^^^ method not found in `&mut ()` + | + = help: items from traits can only be used if the trait is in scope +help: the following trait is implemented but not in scope; perhaps add a `use` for it: + | +LL | use std::ops::DerefMut; + | + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0599`. diff --git a/src/test/ui/unique/unique-ffi-symbols.rs b/src/test/ui/unique/unique-ffi-symbols.rs index 77b5ead26337a..b0fe22bc33269 100644 --- a/src/test/ui/unique/unique-ffi-symbols.rs +++ b/src/test/ui/unique/unique-ffi-symbols.rs @@ -3,12 +3,12 @@ // whenever the item path wasn't enough to disambiguate between them. fn main() { let a = { - extern "C" fn good() -> i32 { return 0; } - good as extern "C" fn() -> i32 + extern fn good() -> i32 { return 0; } + good as extern fn() -> i32 }; let b = { - extern "C" fn good() -> i32 { return 5; } - good as extern "C" fn() -> i32 + extern fn good() -> i32 { return 5; } + good as extern fn() -> i32 }; assert!(a != b); diff --git a/src/test/ui/reachable/unreachable-code-ret.rs b/src/test/ui/unreachable-code-ret.rs similarity index 100% rename from src/test/ui/reachable/unreachable-code-ret.rs rename to src/test/ui/unreachable-code-ret.rs diff --git a/src/test/ui/reachable/unreachable-code-ret.stderr b/src/test/ui/unreachable-code-ret.stderr similarity index 100% rename from src/test/ui/reachable/unreachable-code-ret.stderr rename to src/test/ui/unreachable-code-ret.stderr diff --git a/src/test/ui/unsafe/rfc-2585-unsafe_op_in_unsafe_fn.rs b/src/test/ui/unsafe/rfc-2585-unsafe_op_in_unsafe_fn.rs index 9eec7e0e8fe62..1e57b03ced48b 100644 --- a/src/test/ui/unsafe/rfc-2585-unsafe_op_in_unsafe_fn.rs +++ b/src/test/ui/unsafe/rfc-2585-unsafe_op_in_unsafe_fn.rs @@ -13,9 +13,6 @@ unsafe fn deny_level() { //~^ ERROR dereference of raw pointer is unsafe and requires unsafe block VOID = (); //~^ ERROR use of mutable static is unsafe and requires unsafe block - - unsafe {} - //~^ ERROR unnecessary `unsafe` block } // Check that `unsafe_op_in_unsafe_fn` works starting from the `warn` level. @@ -28,8 +25,6 @@ unsafe fn warning_level() { //~^ ERROR dereference of raw pointer is unsafe and requires unsafe block VOID = (); //~^ ERROR use of mutable static is unsafe and requires unsafe block - unsafe {} - //~^ ERROR unnecessary `unsafe` block } unsafe fn explicit_block() { diff --git a/src/test/ui/unsafe/rfc-2585-unsafe_op_in_unsafe_fn.stderr b/src/test/ui/unsafe/rfc-2585-unsafe_op_in_unsafe_fn.stderr index 278a036c9f19f..cc595df12cc44 100644 --- a/src/test/ui/unsafe/rfc-2585-unsafe_op_in_unsafe_fn.stderr +++ b/src/test/ui/unsafe/rfc-2585-unsafe_op_in_unsafe_fn.stderr @@ -27,26 +27,14 @@ LL | VOID = (); | = note: mutable statics can be mutated by multiple threads: aliasing violations or data races will cause undefined behavior -error: unnecessary `unsafe` block - --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:17:5 - | -LL | unsafe {} - | ^^^^^^ unnecessary `unsafe` block - | -note: the lint level is defined here - --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:3:9 - | -LL | #![deny(unused_unsafe)] - | ^^^^^^^^^^^^^ - error: call to unsafe function is unsafe and requires unsafe block (error E0133) - --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:25:5 + --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:22:5 | LL | unsf(); | ^^^^^^ call to unsafe function | note: the lint level is defined here - --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:23:8 + --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:20:8 | LL | #[deny(warnings)] | ^^^^^^^^ @@ -54,7 +42,7 @@ LL | #[deny(warnings)] = note: consult the function's documentation for information on how to avoid undefined behavior error: dereference of raw pointer is unsafe and requires unsafe block (error E0133) - --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:27:5 + --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:24:5 | LL | *PTR; | ^^^^ dereference of raw pointer @@ -62,7 +50,7 @@ LL | *PTR; = note: raw pointers may be NULL, dangling or unaligned; they can violate aliasing rules and cause data races: all of these are undefined behavior error: use of mutable static is unsafe and requires unsafe block (error E0133) - --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:29:5 + --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:26:5 | LL | VOID = (); | ^^^^^^^^^ use of mutable static @@ -70,39 +58,33 @@ LL | VOID = (); = note: mutable statics can be mutated by multiple threads: aliasing violations or data races will cause undefined behavior error: unnecessary `unsafe` block - --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:31:5 - | -LL | unsafe {} - | ^^^^^^ unnecessary `unsafe` block - -error: unnecessary `unsafe` block - --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:45:14 + --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:40:14 | LL | unsafe { unsafe { unsf() } } | ------ ^^^^^^ unnecessary `unsafe` block | | | because it's nested under this `unsafe` block + | +note: the lint level is defined here + --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:3:9 + | +LL | #![deny(unused_unsafe)] + | ^^^^^^^^^^^^^ error: unnecessary `unsafe` block - --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:56:5 + --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:51:5 | -LL | unsafe fn allow_level() { - | ----------------------- because it's nested under this `unsafe` fn -... LL | unsafe { unsf() } | ^^^^^^ unnecessary `unsafe` block error: unnecessary `unsafe` block - --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:68:9 + --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:63:9 | -LL | unsafe fn nested_allow_level() { - | ------------------------------ because it's nested under this `unsafe` fn -... LL | unsafe { unsf() } | ^^^^^^ unnecessary `unsafe` block error[E0133]: call to unsafe function is unsafe and requires unsafe block - --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:74:5 + --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:69:5 | LL | unsf(); | ^^^^^^ call to unsafe function @@ -110,13 +92,13 @@ LL | unsf(); = note: consult the function's documentation for information on how to avoid undefined behavior error[E0133]: call to unsafe function is unsafe and requires unsafe function or block - --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:78:9 + --> $DIR/rfc-2585-unsafe_op_in_unsafe_fn.rs:73:9 | LL | unsf(); | ^^^^^^ call to unsafe function | = note: consult the function's documentation for information on how to avoid undefined behavior -error: aborting due to 13 previous errors +error: aborting due to 11 previous errors For more information about this error, try `rustc --explain E0133`. diff --git a/src/test/ui/unsafe/unsafe-move-val-init.rs b/src/test/ui/unsafe/unsafe-move-val-init.rs new file mode 100644 index 0000000000000..24249a7a813ec --- /dev/null +++ b/src/test/ui/unsafe/unsafe-move-val-init.rs @@ -0,0 +1,10 @@ +#![feature(core_intrinsics)] + +use std::intrinsics; + +// `move_val_init` has an odd desugaring, check that it is still treated +// as unsafe. +fn main() { + intrinsics::move_val_init(1 as *mut u32, 1); + //~^ ERROR dereference of raw pointer is unsafe +} diff --git a/src/test/ui/unsafe/unsafe-move-val-init.stderr b/src/test/ui/unsafe/unsafe-move-val-init.stderr new file mode 100644 index 0000000000000..44c2aae7cf4f4 --- /dev/null +++ b/src/test/ui/unsafe/unsafe-move-val-init.stderr @@ -0,0 +1,11 @@ +error[E0133]: dereference of raw pointer is unsafe and requires unsafe function or block + --> $DIR/unsafe-move-val-init.rs:8:5 + | +LL | intrinsics::move_val_init(1 as *mut u32, 1); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ dereference of raw pointer + | + = note: raw pointers may be NULL, dangling or unaligned; they can violate aliasing rules and cause data races: all of these are undefined behavior + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0133`. diff --git a/src/test/ui/warn-ctypes-inhibit.rs b/src/test/ui/warn-ctypes-inhibit.rs index 15d8b09d2ecfc..ab9634df65c8a 100644 --- a/src/test/ui/warn-ctypes-inhibit.rs +++ b/src/test/ui/warn-ctypes-inhibit.rs @@ -4,12 +4,14 @@ // compile-flags:-D improper-ctypes // pretty-expanded FIXME #23616 + #![allow(improper_ctypes)] mod libc { - extern "C" { + extern { pub fn malloc(size: isize) -> *const u8; } } -pub fn main() {} +pub fn main() { +} diff --git a/src/test/ui/wasm-import-module.rs b/src/test/ui/wasm-import-module.rs index 4152a1065ca14..16d628a618744 100644 --- a/src/test/ui/wasm-import-module.rs +++ b/src/test/ui/wasm-import-module.rs @@ -1,10 +1,10 @@ #[link(name = "...", wasm_import_module)] //~ ERROR: must be of the form -extern "C" {} +extern {} #[link(name = "...", wasm_import_module(x))] //~ ERROR: must be of the form -extern "C" {} +extern {} #[link(name = "...", wasm_import_module())] //~ ERROR: must be of the form -extern "C" {} +extern {} fn main() {} diff --git a/src/test/ui/wasm/wasm-hang-issue-76281.rs b/src/test/ui/wasm/wasm-hang-issue-76281.rs deleted file mode 100644 index a4adfa6d04461..0000000000000 --- a/src/test/ui/wasm/wasm-hang-issue-76281.rs +++ /dev/null @@ -1,12 +0,0 @@ -// only-wasm32 -// compile-flags: -C opt-level=2 -// build-pass - -// Regression test for #76281. -// This seems like an issue related to LLVM rather than -// libs-impl so place here. - -fn main() { - let mut v: Vec<&()> = Vec::new(); - v.sort_by_key(|&r| r as *const ()); -} diff --git a/src/tools/cargo b/src/tools/cargo index a73e5b7d567c3..329895f5b52a3 160000 --- a/src/tools/cargo +++ b/src/tools/cargo @@ -1 +1 @@ -Subproject commit a73e5b7d567c3036b296fc6b33ed52c5edcd882e +Subproject commit 329895f5b52a358e5d9ecb26215708b5cb31d906 diff --git a/src/tools/clippy/CHANGELOG.md b/src/tools/clippy/CHANGELOG.md index 64864c2e2780d..de8da99cdee12 100644 --- a/src/tools/clippy/CHANGELOG.md +++ b/src/tools/clippy/CHANGELOG.md @@ -6,138 +6,11 @@ document. ## Unreleased / In Rust Nightly -[4911ab1...master](https://github.com/rust-lang/rust-clippy/compare/4911ab1...master) - -## Rust 1.50 - -Current beta, release 2021-02-11 - -[b20d4c1...4911ab1](https://github.com/rust-lang/rust-clippy/compare/b20d4c1...4911ab1) - -### New Lints - -* [`suspicious_operation_groupings`] [#6086](https://github.com/rust-lang/rust-clippy/pull/6086) -* [`size_of_in_element_count`] [#6394](https://github.com/rust-lang/rust-clippy/pull/6394) -* [`unnecessary_wraps`] [#6070](https://github.com/rust-lang/rust-clippy/pull/6070) -* [`let_underscore_drop`] [#6305](https://github.com/rust-lang/rust-clippy/pull/6305) -* [`collapsible_match`] [#6402](https://github.com/rust-lang/rust-clippy/pull/6402) -* [`redundant_else`] [#6330](https://github.com/rust-lang/rust-clippy/pull/6330) -* [`zero_sized_map_values`] [#6218](https://github.com/rust-lang/rust-clippy/pull/6218) -* [`print_stderr`] [#6367](https://github.com/rust-lang/rust-clippy/pull/6367) -* [`string_from_utf8_as_bytes`] [#6134](https://github.com/rust-lang/rust-clippy/pull/6134) - -### Moves and Deprecations - -* Previously deprecated [`str_to_string`] and [`string_to_string`] have been un-deprecated - as `restriction` lints [#6333](https://github.com/rust-lang/rust-clippy/pull/6333) -* Deprecate [`panic_params`] lint. This is now available in rustc as `panic_fmt` - [#6351](https://github.com/rust-lang/rust-clippy/pull/6351) -* Move [`map_err_ignore`] to `restriction` - [#6416](https://github.com/rust-lang/rust-clippy/pull/6416) -* Move [`await_holding_refcell_ref`] to `pedantic` - [#6354](https://github.com/rust-lang/rust-clippy/pull/6354) -* Move [`await_holding_lock`] to `pedantic` - [#6354](https://github.com/rust-lang/rust-clippy/pull/6354) - -### Enhancements - -* Add the `unreadable-literal-lint-fractions` configuration to disable - the `unreadable_literal` lint for fractions - [#6421](https://github.com/rust-lang/rust-clippy/pull/6421) -* [`clone_on_copy`]: Now shows the type in the lint message - [#6443](https://github.com/rust-lang/rust-clippy/pull/6443) -* [`redundant_pattern_matching`]: Now also lints on `std::task::Poll` - [#6339](https://github.com/rust-lang/rust-clippy/pull/6339) -* [`redundant_pattern_matching`]: Additionally also lints on `std::net::IpAddr` - [#6377](https://github.com/rust-lang/rust-clippy/pull/6377) -* [`search_is_some`]: Now suggests `contains` instead of `find(foo).is_some()` - [#6119](https://github.com/rust-lang/rust-clippy/pull/6119) -* [`clone_double_ref`]: Now prints the reference type in the lint message - [#6442](https://github.com/rust-lang/rust-clippy/pull/6442) -* [`modulo_one`]: Now also lints on -1. - [#6360](https://github.com/rust-lang/rust-clippy/pull/6360) -* [`empty_loop`]: Now lints no_std crates, too - [#6205](https://github.com/rust-lang/rust-clippy/pull/6205) -* [`or_fun_call`]: Now also lints when indexing `HashMap` or `BTreeMap` - [#6267](https://github.com/rust-lang/rust-clippy/pull/6267) -* [`wrong_self_convention`]: Now also lints in trait definitions - [#6316](https://github.com/rust-lang/rust-clippy/pull/6316) -* [`needless_borrow`]: Print the type in the lint message - [#6449](https://github.com/rust-lang/rust-clippy/pull/6449) - -[msrv_readme]: https://github.com/rust-lang/rust-clippy#specifying-the-minimum-supported-rust-version - -### False Positive Fixes - -* [`manual_range_contains`]: No longer lints in `const fn` - [#6382](https://github.com/rust-lang/rust-clippy/pull/6382) -* [`unnecessary_lazy_evaluations`]: No longer lints if closure argument is used - [#6370](https://github.com/rust-lang/rust-clippy/pull/6370) -* [`match_single_binding`]: Now ignores cases with `#[cfg()]` macros - [#6435](https://github.com/rust-lang/rust-clippy/pull/6435) -* [`match_like_matches_macro`]: No longer lints on arms with attributes - [#6290](https://github.com/rust-lang/rust-clippy/pull/6290) -* [`map_clone`]: No longer lints with deref and clone - [#6269](https://github.com/rust-lang/rust-clippy/pull/6269) -* [`map_clone`]: No longer lints in the case of &mut - [#6301](https://github.com/rust-lang/rust-clippy/pull/6301) -* [`needless_update`]: Now ignores `non_exhaustive` structs - [#6464](https://github.com/rust-lang/rust-clippy/pull/6464) -* [`needless_collect`]: No longer lints when a collect is needed multiple times - [#6313](https://github.com/rust-lang/rust-clippy/pull/6313) -* [`unnecessary_cast`] No longer lints cfg-dependent types - [#6369](https://github.com/rust-lang/rust-clippy/pull/6369) -* [`declare_interior_mutable_const`] and [`borrow_interior_mutable_const`]: - Both now ignore enums with frozen variants - [#6110](https://github.com/rust-lang/rust-clippy/pull/6110) - - -### Suggestion Fixes/Improvements - -* [`vec_box`]: Provide correct type scope suggestion - [#6271](https://github.com/rust-lang/rust-clippy/pull/6271) -* [`manual_range_contains`]: Give correct suggestion when using floats - [#6320](https://github.com/rust-lang/rust-clippy/pull/6320) -* [`unnecessary_lazy_evaluations`]: Don't always mark suggestion as MachineApplicable - [#6272](https://github.com/rust-lang/rust-clippy/pull/6272) -* [`manual_async_fn`]: Improve suggestion formatting - [#6294](https://github.com/rust-lang/rust-clippy/pull/6294) -* [`unnecessary_cast`]: Fix incorrectly formatted float literal suggestion - [#6362](https://github.com/rust-lang/rust-clippy/pull/6362) - -### ICE Fixes - -* Fix a crash in [`from_iter_instead_of_collect`] - [#6304](https://github.com/rust-lang/rust-clippy/pull/6304) -* Fix a silent crash when parsing doc comments in [`needless_doctest_main`] - [#6458](https://github.com/rust-lang/rust-clippy/pull/6458) - -### Documentation Improvements - -* The lint website search has been improved ([#6477](https://github.com/rust-lang/rust-clippy/pull/6477)): - * Searching for lints with dashes and spaces is possible now. For example - `missing-errors-doc` and `missing errors doc` are now valid aliases for lint names - * Improved fuzzy search in lint descriptions -* Various README improvements - [#6287](https://github.com/rust-lang/rust-clippy/pull/6287) -* Add known problems to [`comparison_chain`] documentation - [#6390](https://github.com/rust-lang/rust-clippy/pull/6390) -* Fix example used in [`cargo_common_metadata`] - [#6293](https://github.com/rust-lang/rust-clippy/pull/6293) -* Improve [`map_clone`] documentation - [#6340](https://github.com/rust-lang/rust-clippy/pull/6340) - -### Others - -* You can now tell Clippy about the MSRV your project supports. Please refer to - the specific README section to learn more about MSRV support [here][msrv_readme] - [#6201](https://github.com/rust-lang/rust-clippy/pull/6201) -* Add `--no-deps` option to avoid running on path dependencies in workspaces - [#6188](https://github.com/rust-lang/rust-clippy/pull/6188) +[b20d4c1...master](https://github.com/rust-lang/rust-clippy/compare/b20d4c1...master) ## Rust 1.49 -Current stable, released 2020-12-31 +Current beta, release 2020-12-31 [e636b88...b20d4c1](https://github.com/rust-lang/rust-clippy/compare/e636b88...b20d4c1) @@ -243,7 +116,7 @@ Current stable, released 2020-12-31 ## Rust 1.48 -Released 2020-11-19 +Current stable, released 2020-11-19 [09bd400...e636b88](https://github.com/rust-lang/rust-clippy/compare/09bd400...e636b88) @@ -1896,7 +1769,6 @@ Released 2018-09-13 [`cmp_null`]: https://rust-lang.github.io/rust-clippy/master/index.html#cmp_null [`cmp_owned`]: https://rust-lang.github.io/rust-clippy/master/index.html#cmp_owned [`cognitive_complexity`]: https://rust-lang.github.io/rust-clippy/master/index.html#cognitive_complexity -[`collapsible_else_if`]: https://rust-lang.github.io/rust-clippy/master/index.html#collapsible_else_if [`collapsible_if`]: https://rust-lang.github.io/rust-clippy/master/index.html#collapsible_if [`collapsible_match`]: https://rust-lang.github.io/rust-clippy/master/index.html#collapsible_match [`comparison_chain`]: https://rust-lang.github.io/rust-clippy/master/index.html#comparison_chain @@ -2101,7 +1973,6 @@ Released 2018-09-13 [`needless_doctest_main`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_doctest_main [`needless_lifetimes`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_lifetimes [`needless_pass_by_value`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_value -[`needless_question_mark`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_question_mark [`needless_range_loop`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_range_loop [`needless_return`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_return [`needless_update`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_update @@ -2141,7 +2012,6 @@ Released 2018-09-13 [`print_with_newline`]: https://rust-lang.github.io/rust-clippy/master/index.html#print_with_newline [`println_empty_string`]: https://rust-lang.github.io/rust-clippy/master/index.html#println_empty_string [`ptr_arg`]: https://rust-lang.github.io/rust-clippy/master/index.html#ptr_arg -[`ptr_as_ptr`]: https://rust-lang.github.io/rust-clippy/master/index.html#ptr_as_ptr [`ptr_eq`]: https://rust-lang.github.io/rust-clippy/master/index.html#ptr_eq [`ptr_offset_with_cast`]: https://rust-lang.github.io/rust-clippy/master/index.html#ptr_offset_with_cast [`pub_enum_variant_names`]: https://rust-lang.github.io/rust-clippy/master/index.html#pub_enum_variant_names @@ -2282,7 +2152,6 @@ Released 2018-09-13 [`useless_transmute`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_transmute [`useless_vec`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_vec [`vec_box`]: https://rust-lang.github.io/rust-clippy/master/index.html#vec_box -[`vec_init_then_push`]: https://rust-lang.github.io/rust-clippy/master/index.html#vec_init_then_push [`vec_resize_to_zero`]: https://rust-lang.github.io/rust-clippy/master/index.html#vec_resize_to_zero [`verbose_bit_mask`]: https://rust-lang.github.io/rust-clippy/master/index.html#verbose_bit_mask [`verbose_file_reads`]: https://rust-lang.github.io/rust-clippy/master/index.html#verbose_file_reads diff --git a/src/tools/clippy/clippy_dev/src/bless.rs b/src/tools/clippy/clippy_dev/src/bless.rs index b877806946cfe..645098e4cfcd2 100644 --- a/src/tools/clippy/clippy_dev/src/bless.rs +++ b/src/tools/clippy/clippy_dev/src/bless.rs @@ -5,7 +5,7 @@ use std::env; use std::ffi::OsStr; use std::fs; use std::lazy::SyncLazy; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use walkdir::WalkDir; use crate::clippy_project_root; @@ -16,41 +16,27 @@ pub static CARGO_TARGET_DIR: SyncLazy = SyncLazy::new(|| match env::var None => env::current_dir().unwrap().join("target"), }); -static CLIPPY_BUILD_TIME: SyncLazy> = SyncLazy::new(|| { - let profile = env::var("PROFILE").unwrap_or_else(|_| "debug".to_string()); - let mut path = PathBuf::from(&**CARGO_TARGET_DIR); - path.push(profile); - path.push("cargo-clippy"); - fs::metadata(path).ok()?.modified().ok() -}); - -pub fn bless(ignore_timestamp: bool) { - let test_suite_dirs = [ +pub fn bless() { + let test_dirs = [ clippy_project_root().join("tests").join("ui"), - clippy_project_root().join("tests").join("ui-internal"), clippy_project_root().join("tests").join("ui-toml"), clippy_project_root().join("tests").join("ui-cargo"), ]; - for test_suite_dir in &test_suite_dirs { - WalkDir::new(test_suite_dir) + for test_dir in &test_dirs { + WalkDir::new(test_dir) .into_iter() .filter_map(Result::ok) .filter(|f| f.path().extension() == Some(OsStr::new("rs"))) .for_each(|f| { - let test_name = f.path().strip_prefix(test_suite_dir).unwrap(); - for &ext in &["stdout", "stderr", "fixed"] { - update_reference_file( - f.path().with_extension(ext), - test_name.with_extension(ext), - ignore_timestamp, - ); - } + update_reference_file(f.path().with_extension("stdout")); + update_reference_file(f.path().with_extension("stderr")); + update_reference_file(f.path().with_extension("fixed")); }); } } -fn update_reference_file(reference_file_path: PathBuf, test_name: PathBuf, ignore_timestamp: bool) { - let test_output_path = build_dir().join(test_name); +fn update_reference_file(reference_file_path: PathBuf) { + let test_output_path = build_dir().join(PathBuf::from(reference_file_path.file_name().unwrap())); let relative_reference_file_path = reference_file_path.strip_prefix(clippy_project_root()).unwrap(); // If compiletest did not write any changes during the test run, @@ -59,11 +45,6 @@ fn update_reference_file(reference_file_path: PathBuf, test_name: PathBuf, ignor return; } - // If the test output was not updated since the last clippy build, it may be outdated - if !ignore_timestamp && !updated_since_clippy_build(&test_output_path).unwrap_or(true) { - return; - } - let test_output_file = fs::read(&test_output_path).expect("Unable to read test output file"); let reference_file = fs::read(&reference_file_path).unwrap_or_default(); @@ -83,12 +64,6 @@ fn update_reference_file(reference_file_path: PathBuf, test_name: PathBuf, ignor } } -fn updated_since_clippy_build(path: &Path) -> Option { - let clippy_build_time = (*CLIPPY_BUILD_TIME)?; - let modified = fs::metadata(path).ok()?.modified().ok()?; - Some(modified >= clippy_build_time) -} - fn build_dir() -> PathBuf { let profile = env::var("PROFILE").unwrap_or_else(|_| "debug".to_string()); let mut path = PathBuf::new(); diff --git a/src/tools/clippy/clippy_dev/src/main.rs b/src/tools/clippy/clippy_dev/src/main.rs index 2ea56c42fafd6..4fdae38e3ab7a 100644 --- a/src/tools/clippy/clippy_dev/src/main.rs +++ b/src/tools/clippy/clippy_dev/src/main.rs @@ -7,8 +7,8 @@ fn main() { let matches = get_clap_config(); match matches.subcommand() { - ("bless", Some(matches)) => { - bless::bless(matches.is_present("ignore-timestamp")); + ("bless", Some(_)) => { + bless::bless(); }, ("fmt", Some(matches)) => { fmt::run(matches.is_present("check"), matches.is_present("verbose")); @@ -47,15 +47,7 @@ fn main() { fn get_clap_config<'a>() -> ArgMatches<'a> { App::new("Clippy developer tooling") - .subcommand( - SubCommand::with_name("bless") - .about("bless the test output changes") - .arg( - Arg::with_name("ignore-timestamp") - .long("ignore-timestamp") - .help("Include files updated before clippy was built"), - ), - ) + .subcommand(SubCommand::with_name("bless").about("bless the test output changes")) .subcommand( SubCommand::with_name("fmt") .about("Run rustfmt on all projects and tests") diff --git a/src/tools/clippy/clippy_lints/src/assertions_on_constants.rs b/src/tools/clippy/clippy_lints/src/assertions_on_constants.rs index aa431f0596cca..62c73dbac48b4 100644 --- a/src/tools/clippy/clippy_lints/src/assertions_on_constants.rs +++ b/src/tools/clippy/clippy_lints/src/assertions_on_constants.rs @@ -1,7 +1,8 @@ use crate::consts::{constant, Constant}; use crate::utils::{is_direct_expn_of, is_expn_of, match_panic_call, snippet_opt, span_lint_and_help}; use if_chain::if_chain; -use rustc_hir::{Expr, ExprKind, UnOp}; +use rustc_ast::ast::LitKind; +use rustc_hir::{Expr, ExprKind, PatKind, UnOp}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; @@ -101,22 +102,31 @@ enum AssertKind { /// Check if the expression matches /// /// ```rust,ignore -/// if !c { -/// { -/// ::std::rt::begin_panic(message, _) -/// } -/// } +/// match { let _t = !c; _t } { +/// true => { +/// { +/// ::std::rt::begin_panic(message, _) +/// } +/// } +/// _ => { } +/// }; /// ``` /// /// where `message` is any expression and `c` is a constant bool. fn match_assert_with_message<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option { if_chain! { - if let ExprKind::If(ref cond, ref then, _) = expr.kind; - if let ExprKind::Unary(UnOp::UnNot, ref expr) = cond.kind; + if let ExprKind::Match(ref expr, ref arms, _) = expr.kind; + // matches { let _t = expr; _t } + if let ExprKind::DropTemps(ref expr) = expr.kind; + if let ExprKind::Unary(UnOp::UnNot, ref expr) = expr.kind; // bind the first argument of the `assert!` macro if let Some((Constant::Bool(is_true), _)) = constant(cx, cx.typeck_results(), expr); - // block - if let ExprKind::Block(ref block, _) = then.kind; + // arm 1 pattern + if let PatKind::Lit(ref lit_expr) = arms[0].pat.kind; + if let ExprKind::Lit(ref lit) = lit_expr.kind; + if let LitKind::Bool(true) = lit.node; + // arm 1 block + if let ExprKind::Block(ref block, _) = arms[0].body.kind; if block.stmts.is_empty(); if let Some(block_expr) = &block.expr; // inner block is optional. unwrap it if it exists, or use the expression as is otherwise. diff --git a/src/tools/clippy/clippy_lints/src/attrs.rs b/src/tools/clippy/clippy_lints/src/attrs.rs index 652d1fa16b6de..3edbe723922f8 100644 --- a/src/tools/clippy/clippy_lints/src/attrs.rs +++ b/src/tools/clippy/clippy_lints/src/attrs.rs @@ -10,10 +10,11 @@ use rustc_errors::Applicability; use rustc_hir::{ Block, Expr, ExprKind, ImplItem, ImplItemKind, Item, ItemKind, StmtKind, TraitFn, TraitItem, TraitItemKind, }; -use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext}; +use rustc_lint::{CheckLintNameResult, EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext}; use rustc_middle::lint::in_external_macro; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; +use rustc_span::lev_distance::find_best_match_for_name; use rustc_span::source_map::Span; use rustc_span::sym; use rustc_span::symbol::{Symbol, SymbolStr}; @@ -155,6 +156,33 @@ declare_clippy_lint! { "empty line after outer attribute" } +declare_clippy_lint! { + /// **What it does:** Checks for `allow`/`warn`/`deny`/`forbid` attributes with scoped clippy + /// lints and if those lints exist in clippy. If there is an uppercase letter in the lint name + /// (not the tool name) and a lowercase version of this lint exists, it will suggest to lowercase + /// the lint name. + /// + /// **Why is this bad?** A lint attribute with a mistyped lint name won't have an effect. + /// + /// **Known problems:** None. + /// + /// **Example:** + /// Bad: + /// ```rust + /// #![warn(if_not_els)] + /// #![deny(clippy::All)] + /// ``` + /// + /// Good: + /// ```rust + /// #![warn(if_not_else)] + /// #![deny(clippy::all)] + /// ``` + pub UNKNOWN_CLIPPY_LINTS, + style, + "unknown_lints for scoped Clippy lints" +} + declare_clippy_lint! { /// **What it does:** Checks for `warn`/`deny`/`forbid` attributes targeting the whole clippy::restriction category. /// @@ -244,6 +272,7 @@ declare_lint_pass!(Attributes => [ INLINE_ALWAYS, DEPRECATED_SEMVER, USELESS_ATTRIBUTE, + UNKNOWN_CLIPPY_LINTS, BLANKET_CLIPPY_RESTRICTION_LINTS, ]); @@ -370,7 +399,7 @@ fn extract_clippy_lint(lint: &NestedMetaItem) -> Option { if let Some(meta_item) = lint.meta_item(); if meta_item.path.segments.len() > 1; if let tool_name = meta_item.path.segments[0].ident; - if tool_name.name == sym::clippy; + if tool_name.as_str() == "clippy"; let lint_name = meta_item.path.segments.last().unwrap().ident.name; then { return Some(lint_name.as_str()); @@ -380,9 +409,48 @@ fn extract_clippy_lint(lint: &NestedMetaItem) -> Option { } fn check_clippy_lint_names(cx: &LateContext<'_>, ident: &str, items: &[NestedMetaItem]) { + let lint_store = cx.lints(); for lint in items { if let Some(lint_name) = extract_clippy_lint(lint) { - if lint_name == "restriction" && ident != "allow" { + if let CheckLintNameResult::Tool(Err((None, _))) = lint_store.check_lint_name(&lint_name, Some(sym::clippy)) + { + span_lint_and_then( + cx, + UNKNOWN_CLIPPY_LINTS, + lint.span(), + &format!("unknown clippy lint: clippy::{}", lint_name), + |diag| { + let name_lower = lint_name.to_lowercase(); + let symbols = lint_store + .get_lints() + .iter() + .map(|l| Symbol::intern(&l.name_lower())) + .collect::>(); + let sugg = find_best_match_for_name( + &symbols, + Symbol::intern(&format!("clippy::{}", name_lower)), + None, + ); + if lint_name.chars().any(char::is_uppercase) + && lint_store.find_lints(&format!("clippy::{}", name_lower)).is_ok() + { + diag.span_suggestion( + lint.span(), + "lowercase the lint name", + format!("clippy::{}", name_lower), + Applicability::MachineApplicable, + ); + } else if let Some(sugg) = sugg { + diag.span_suggestion( + lint.span(), + "did you mean", + sugg.to_string(), + Applicability::MachineApplicable, + ); + } + }, + ); + } else if lint_name == "restriction" && ident != "allow" { span_lint_and_help( cx, BLANKET_CLIPPY_RESTRICTION_LINTS, diff --git a/src/tools/clippy/clippy_lints/src/blocks_in_if_conditions.rs b/src/tools/clippy/clippy_lints/src/blocks_in_if_conditions.rs index 4efca10bcdf13..736730d4084f4 100644 --- a/src/tools/clippy/clippy_lints/src/blocks_in_if_conditions.rs +++ b/src/tools/clippy/clippy_lints/src/blocks_in_if_conditions.rs @@ -1,4 +1,4 @@ -use crate::utils::{differing_macro_contexts, snippet_block_with_applicability, span_lint, span_lint_and_sugg}; +use crate::utils::{differing_macro_contexts, higher, snippet_block_with_applicability, span_lint, span_lint_and_sugg}; use rustc_errors::Applicability; use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor}; use rustc_hir::{BlockCheckMode, Expr, ExprKind}; @@ -75,7 +75,7 @@ impl<'tcx> LateLintPass<'tcx> for BlocksInIfConditions { if in_external_macro(cx.sess(), expr.span) { return; } - if let ExprKind::If(cond, _, _) = &expr.kind { + if let Some((cond, _, _)) = higher::if_block(&expr) { if let ExprKind::Block(block, _) = &cond.kind { if block.rules == BlockCheckMode::DefaultBlock { if block.stmts.is_empty() { diff --git a/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs b/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs index b3ebdf4ca30d8..b1bc2ec29e16e 100644 --- a/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs +++ b/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs @@ -147,9 +147,6 @@ impl<'tcx> Visitor<'tcx> for CCHelper { fn visit_expr(&mut self, e: &'tcx Expr<'_>) { walk_expr(self, e); match e.kind { - ExprKind::If(_, _, _) => { - self.cc += 1; - }, ExprKind::Match(_, ref arms, _) => { if arms.len() > 1 { self.cc += 1; diff --git a/src/tools/clippy/clippy_lints/src/collapsible_if.rs b/src/tools/clippy/clippy_lints/src/collapsible_if.rs index 93ccc76d0c9cd..42bff564de03d 100644 --- a/src/tools/clippy/clippy_lints/src/collapsible_if.rs +++ b/src/tools/clippy/clippy_lints/src/collapsible_if.rs @@ -23,7 +23,9 @@ use rustc_errors::Applicability; declare_clippy_lint! { /// **What it does:** Checks for nested `if` statements which can be collapsed - /// by `&&`-combining their conditions. + /// by `&&`-combining their conditions and for `else { if ... }` expressions + /// that + /// can be collapsed to `else if ...`. /// /// **Why is this bad?** Each `if`-statement adds one level of nesting, which /// makes code look more complex than it really is. @@ -38,31 +40,7 @@ declare_clippy_lint! { /// } /// } /// - /// ``` - /// - /// Should be written: - /// - /// ```rust.ignore - /// if x && y { - /// … - /// } - /// ``` - pub COLLAPSIBLE_IF, - style, - "nested `if`s that can be collapsed (e.g., `if x { if y { ... } }`" -} - -declare_clippy_lint! { - /// **What it does:** Checks for collapsible `else { if ... }` expressions - /// that can be collapsed to `else if ...`. - /// - /// **Why is this bad?** Each `if`-statement adds one level of nesting, which - /// makes code look more complex than it really is. - /// - /// **Known problems:** None. - /// - /// **Example:** - /// ```rust,ignore + /// // or /// /// if x { /// … @@ -76,18 +54,24 @@ declare_clippy_lint! { /// Should be written: /// /// ```rust.ignore + /// if x && y { + /// … + /// } + /// + /// // or + /// /// if x { /// … /// } else if y { /// … /// } /// ``` - pub COLLAPSIBLE_ELSE_IF, + pub COLLAPSIBLE_IF, style, - "nested `else`-`if` expressions that can be collapsed (e.g., `else { if x { ... } }`)" + "`if`s that can be collapsed (e.g., `if x { if y { ... } }` and `else { if x { ... } }`)" } -declare_lint_pass!(CollapsibleIf => [COLLAPSIBLE_IF, COLLAPSIBLE_ELSE_IF]); +declare_lint_pass!(CollapsibleIf => [COLLAPSIBLE_IF]); impl EarlyLintPass for CollapsibleIf { fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) { @@ -128,7 +112,7 @@ fn check_collapsible_maybe_if_let(cx: &EarlyContext<'_>, else_: &ast::Expr) { let mut applicability = Applicability::MachineApplicable; span_lint_and_sugg( cx, - COLLAPSIBLE_ELSE_IF, + COLLAPSIBLE_IF, block.span, "this `else { if .. }` block can be collapsed", "collapse nested if block", diff --git a/src/tools/clippy/clippy_lints/src/comparison_chain.rs b/src/tools/clippy/clippy_lints/src/comparison_chain.rs index 90d31dece1311..ae1143b2c50ce 100644 --- a/src/tools/clippy/clippy_lints/src/comparison_chain.rs +++ b/src/tools/clippy/clippy_lints/src/comparison_chain.rs @@ -13,7 +13,7 @@ declare_clippy_lint! { /// repetitive /// /// **Known problems:** The match statement may be slower due to the compiler - /// not inlining the call to cmp. See issue [#5354](https://github.com/rust-lang/rust-clippy/issues/5354) + /// not inlining the call to cmp. See issue #5354 /// /// **Example:** /// ```rust,ignore diff --git a/src/tools/clippy/clippy_lints/src/consts.rs b/src/tools/clippy/clippy_lints/src/consts.rs index 166eadf86c177..0035ded9356cf 100644 --- a/src/tools/clippy/clippy_lints/src/consts.rs +++ b/src/tools/clippy/clippy_lints/src/consts.rs @@ -1,6 +1,6 @@ #![allow(clippy::float_cmp)] -use crate::utils::{clip, sext, unsext}; +use crate::utils::{clip, higher, sext, unsext}; use if_chain::if_chain; use rustc_ast::ast::{FloatTy, LitFloatType, LitKind}; use rustc_data_structures::sync::Lrc; @@ -228,6 +228,9 @@ pub struct ConstEvalLateContext<'a, 'tcx> { impl<'a, 'tcx> ConstEvalLateContext<'a, 'tcx> { /// Simple constant folding: Insert an expression, get a constant or none. pub fn expr(&mut self, e: &Expr<'_>) -> Option { + if let Some((ref cond, ref then, otherwise)) = higher::if_block(&e) { + return self.ifthenelse(cond, then, otherwise); + } match e.kind { ExprKind::Path(ref qpath) => self.fetch_path(qpath, e.hir_id, self.typeck_results.expr_ty(e)), ExprKind::Block(ref block, _) => self.block(block), @@ -246,7 +249,6 @@ impl<'a, 'tcx> ConstEvalLateContext<'a, 'tcx> { UnOp::UnNeg => self.constant_negate(&o, self.typeck_results.expr_ty(e)), UnOp::UnDeref => Some(if let Constant::Ref(r) = o { *r } else { o }), }), - ExprKind::If(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, *otherwise), ExprKind::Binary(op, ref left, ref right) => self.binop(op, left, right), ExprKind::Call(ref callee, ref args) => { // We only handle a few const functions for now. diff --git a/src/tools/clippy/clippy_lints/src/copies.rs b/src/tools/clippy/clippy_lints/src/copies.rs index 944aaafb46de5..46ce92ea6d782 100644 --- a/src/tools/clippy/clippy_lints/src/copies.rs +++ b/src/tools/clippy/clippy_lints/src/copies.rs @@ -1,6 +1,6 @@ use crate::utils::{eq_expr_value, in_macro, search_same, SpanlessEq, SpanlessHash}; -use crate::utils::{get_parent_expr, if_sequence, span_lint_and_note}; -use rustc_hir::{Block, Expr, ExprKind}; +use crate::utils::{get_parent_expr, higher, if_sequence, span_lint_and_note}; +use rustc_hir::{Block, Expr}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; @@ -109,13 +109,11 @@ impl<'tcx> LateLintPass<'tcx> for CopyAndPaste { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if !expr.span.from_expansion() { // skip ifs directly in else, it will be checked in the parent if - if let Some(&Expr { - kind: ExprKind::If(_, _, Some(ref else_expr)), - .. - }) = get_parent_expr(cx, expr) - { - if else_expr.hir_id == expr.hir_id { - return; + if let Some(expr) = get_parent_expr(cx, expr) { + if let Some((_, _, Some(ref else_expr))) = higher::if_block(&expr) { + if else_expr.hir_id == expr.hir_id { + return; + } } } diff --git a/src/tools/clippy/clippy_lints/src/copy_iterator.rs b/src/tools/clippy/clippy_lints/src/copy_iterator.rs index 48899b3389937..349402453226a 100644 --- a/src/tools/clippy/clippy_lints/src/copy_iterator.rs +++ b/src/tools/clippy/clippy_lints/src/copy_iterator.rs @@ -1,5 +1,5 @@ use crate::utils::{is_copy, match_path, paths, span_lint_and_note}; -use rustc_hir::{Impl, Item, ItemKind}; +use rustc_hir::{Item, ItemKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; @@ -33,10 +33,10 @@ declare_lint_pass!(CopyIterator => [COPY_ITERATOR]); impl<'tcx> LateLintPass<'tcx> for CopyIterator { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { - if let ItemKind::Impl(Impl { + if let ItemKind::Impl { of_trait: Some(ref trait_ref), .. - }) = item.kind + } = item.kind { let ty = cx.tcx.type_of(cx.tcx.hir().local_def_id(item.hir_id)); diff --git a/src/tools/clippy/clippy_lints/src/default.rs b/src/tools/clippy/clippy_lints/src/default.rs index f7224811e6e79..b0d7c7b3baab1 100644 --- a/src/tools/clippy/clippy_lints/src/default.rs +++ b/src/tools/clippy/clippy_lints/src/default.rs @@ -1,6 +1,4 @@ -use crate::utils::{ - any_parent_is_automatically_derived, contains_name, match_def_path, paths, qpath_res, snippet_with_macro_callsite, -}; +use crate::utils::{any_parent_is_automatically_derived, contains_name, match_def_path, paths, qpath_res, snippet}; use crate::utils::{span_lint_and_note, span_lint_and_sugg}; use if_chain::if_chain; use rustc_data_structures::fx::FxHashSet; @@ -8,7 +6,6 @@ use rustc_errors::Applicability; use rustc_hir::def::Res; use rustc_hir::{Block, Expr, ExprKind, PatKind, QPath, Stmt, StmtKind}; use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::lint::in_external_macro; use rustc_middle::ty; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::symbol::{Ident, Symbol}; @@ -121,8 +118,6 @@ impl LateLintPass<'_> for Default { // only take `let ...` statements if let StmtKind::Local(local) = stmt.kind; if let Some(expr) = local.init; - if !any_parent_is_automatically_derived(cx.tcx, expr.hir_id); - if !in_external_macro(cx.tcx.sess, expr.span); // only take bindings to identifiers if let PatKind::Binding(_, binding_id, ident, _) = local.pat.kind; // only when assigning `... = Default::default()` @@ -192,7 +187,7 @@ impl LateLintPass<'_> for Default { .into_iter() .map(|(field, rhs)| { // extract and store the assigned value for help message - let value_snippet = snippet_with_macro_callsite(cx, rhs.span, ".."); + let value_snippet = snippet(cx, rhs.span, ".."); format!("{}: {}", field, value_snippet) }) .collect::>() diff --git a/src/tools/clippy/clippy_lints/src/deprecated_lints.rs b/src/tools/clippy/clippy_lints/src/deprecated_lints.rs index 47b3cc3ad3038..bec0c9f93a0d2 100644 --- a/src/tools/clippy/clippy_lints/src/deprecated_lints.rs +++ b/src/tools/clippy/clippy_lints/src/deprecated_lints.rs @@ -163,19 +163,6 @@ declare_deprecated_lint! { } declare_deprecated_lint! { - /// **What it does:** Nothing. This lint has been deprecated. - /// - /// **Deprecation reason:** This lint has been uplifted to rustc and is now called - /// `panic_fmt`. pub PANIC_PARAMS, "this lint has been uplifted to rustc and is now called `panic_fmt`" } - -declare_deprecated_lint! { - /// **What it does:** Nothing. This lint has been deprecated. - /// - /// **Deprecation reason:** This lint has been integrated into the `unknown_lints` - /// rustc lint. - pub UNKNOWN_CLIPPY_LINTS, - "this lint has been integrated into the `unknown_lints` rustc lint" -} diff --git a/src/tools/clippy/clippy_lints/src/derive.rs b/src/tools/clippy/clippy_lints/src/derive.rs index b1e363663bb27..c75efc6e99f89 100644 --- a/src/tools/clippy/clippy_lints/src/derive.rs +++ b/src/tools/clippy/clippy_lints/src/derive.rs @@ -7,7 +7,7 @@ use if_chain::if_chain; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::{walk_expr, walk_fn, walk_item, FnKind, NestedVisitorMap, Visitor}; use rustc_hir::{ - BlockCheckMode, BodyId, Expr, ExprKind, FnDecl, HirId, Impl, Item, ItemKind, TraitRef, UnsafeSource, Unsafety, + BlockCheckMode, BodyId, Expr, ExprKind, FnDecl, HirId, Item, ItemKind, TraitRef, UnsafeSource, Unsafety, }; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::map::Map; @@ -164,10 +164,10 @@ declare_lint_pass!(Derive => [ impl<'tcx> LateLintPass<'tcx> for Derive { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { - if let ItemKind::Impl(Impl { + if let ItemKind::Impl { of_trait: Some(ref trait_ref), .. - }) = item.kind + } = item.kind { let ty = cx.tcx.type_of(cx.tcx.hir().local_def_id(item.hir_id)); let is_automatically_derived = is_automatically_derived(&*item.attrs); diff --git a/src/tools/clippy/clippy_lints/src/doc.rs b/src/tools/clippy/clippy_lints/src/doc.rs index f518da55cd76f..aba6553279590 100644 --- a/src/tools/clippy/clippy_lints/src/doc.rs +++ b/src/tools/clippy/clippy_lints/src/doc.rs @@ -182,8 +182,11 @@ impl<'tcx> LateLintPass<'tcx> for DocMarkdown { lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, Some(body_id)); } }, - hir::ItemKind::Impl(ref impl_) => { - self.in_trait_impl = impl_.of_trait.is_some(); + hir::ItemKind::Impl { + of_trait: ref trait_ref, + .. + } => { + self.in_trait_impl = trait_ref.is_some(); }, _ => {}, } diff --git a/src/tools/clippy/clippy_lints/src/empty_enum.rs b/src/tools/clippy/clippy_lints/src/empty_enum.rs index 853b3afdc3ae2..a249117d182fa 100644 --- a/src/tools/clippy/clippy_lints/src/empty_enum.rs +++ b/src/tools/clippy/clippy_lints/src/empty_enum.rs @@ -8,12 +8,8 @@ use rustc_session::{declare_lint_pass, declare_tool_lint}; declare_clippy_lint! { /// **What it does:** Checks for `enum`s with no variants. /// - /// As of this writing, the `never_type` is still a - /// nightly-only experimental API. Therefore, this lint is only triggered - /// if the `never_type` is enabled. - /// /// **Why is this bad?** If you want to introduce a type which - /// can't be instantiated, you should use `!` (the primitive type "never"), + /// can't be instantiated, you should use `!` (the never type), /// or a wrapper around it, because `!` has more extensive /// compiler support (type inference, etc...) and wrappers /// around it are the conventional way to define an uninhabited type. @@ -44,11 +40,6 @@ declare_lint_pass!(EmptyEnum => [EMPTY_ENUM]); impl<'tcx> LateLintPass<'tcx> for EmptyEnum { fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) { - // Only suggest the `never_type` if the feature is enabled - if !cx.tcx.features().never_type { - return; - } - let did = cx.tcx.hir().local_def_id(item.hir_id); if let ItemKind::Enum(..) = item.kind { let ty = cx.tcx.type_of(did); diff --git a/src/tools/clippy/clippy_lints/src/entry.rs b/src/tools/clippy/clippy_lints/src/entry.rs index 37948e06869c3..35a5d00f4aa5a 100644 --- a/src/tools/clippy/clippy_lints/src/entry.rs +++ b/src/tools/clippy/clippy_lints/src/entry.rs @@ -1,5 +1,5 @@ use crate::utils::SpanlessEq; -use crate::utils::{get_item_name, is_type_diagnostic_item, match_type, paths, snippet, snippet_opt}; +use crate::utils::{get_item_name, higher, is_type_diagnostic_item, match_type, paths, snippet, snippet_opt}; use crate::utils::{snippet_with_applicability, span_lint_and_then}; use if_chain::if_chain; use rustc_errors::Applicability; @@ -54,7 +54,7 @@ declare_lint_pass!(HashMapPass => [MAP_ENTRY]); impl<'tcx> LateLintPass<'tcx> for HashMapPass { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - if let ExprKind::If(ref check, ref then_block, ref else_block) = expr.kind { + if let Some((ref check, ref then_block, ref else_block)) = higher::if_block(&expr) { if let ExprKind::Unary(UnOp::UnNot, ref check) = check.kind { if let Some((ty, map, key)) = check_cond(cx, check) { // in case of `if !m.contains_key(&k) { m.insert(k, v); }` diff --git a/src/tools/clippy/clippy_lints/src/escape.rs b/src/tools/clippy/clippy_lints/src/escape.rs index 40e93da8dffb4..d2dcb3e5c4644 100644 --- a/src/tools/clippy/clippy_lints/src/escape.rs +++ b/src/tools/clippy/clippy_lints/src/escape.rs @@ -1,16 +1,15 @@ use rustc_hir::intravisit; -use rustc_hir::{self, AssocItemKind, Body, FnDecl, HirId, HirIdSet, Impl, ItemKind, Node}; +use rustc_hir::{self, Body, FnDecl, HirId, HirIdSet, ItemKind, Node}; use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::ty::{self, TraitRef, Ty}; +use rustc_middle::ty::{self, Ty}; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::source_map::Span; -use rustc_span::symbol::kw; use rustc_target::abi::LayoutOf; use rustc_target::spec::abi::Abi; use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; -use crate::utils::{contains_ty, span_lint}; +use crate::utils::span_lint; #[derive(Copy, Clone)] pub struct BoxedLocal { @@ -52,7 +51,6 @@ fn is_non_trait_box(ty: Ty<'_>) -> bool { struct EscapeDelegate<'a, 'tcx> { cx: &'a LateContext<'tcx>, set: HirIdSet, - trait_self_ty: Option>, too_large_for_stack: u64, } @@ -74,34 +72,19 @@ impl<'tcx> LateLintPass<'tcx> for BoxedLocal { } } + // If the method is an impl for a trait, don't warn. let parent_id = cx.tcx.hir().get_parent_item(hir_id); let parent_node = cx.tcx.hir().find(parent_id); - let mut trait_self_ty = None; if let Some(Node::Item(item)) = parent_node { - // If the method is an impl for a trait, don't warn. - if let ItemKind::Impl(Impl { of_trait: Some(_), .. }) = item.kind { + if let ItemKind::Impl { of_trait: Some(_), .. } = item.kind { return; } - - // find `self` ty for this trait if relevant - if let ItemKind::Trait(_, _, _, _, items) = item.kind { - for trait_item in items { - if trait_item.id.hir_id == hir_id { - // be sure we have `self` parameter in this function - if let AssocItemKind::Fn { has_self: true } = trait_item.kind { - trait_self_ty = - Some(TraitRef::identity(cx.tcx, trait_item.id.hir_id.owner.to_def_id()).self_ty()); - } - } - } - } } let mut v = EscapeDelegate { cx, set: HirIdSet::default(), - trait_self_ty, too_large_for_stack: self.too_large_for_stack, }; @@ -170,17 +153,10 @@ impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> { return; } - // skip if there is a `self` parameter binding to a type - // that contains `Self` (i.e.: `self: Box`), see #4804 - if let Some(trait_self_ty) = self.trait_self_ty { - if map.name(cmt.hir_id) == kw::SelfLower && contains_ty(cmt.place.ty(), trait_self_ty) { - return; - } - } - if is_non_trait_box(cmt.place.ty()) && !self.is_large_box(cmt.place.ty()) { self.set.insert(cmt.hir_id); } + return; } } } diff --git a/src/tools/clippy/clippy_lints/src/eta_reduction.rs b/src/tools/clippy/clippy_lints/src/eta_reduction.rs index 1a722d39f730b..53df3abbf5437 100644 --- a/src/tools/clippy/clippy_lints/src/eta_reduction.rs +++ b/src/tools/clippy/clippy_lints/src/eta_reduction.rs @@ -22,7 +22,7 @@ declare_clippy_lint! { /// **Known problems:** If creating the closure inside the closure has a side- /// effect then moving the closure creation out will change when that side- /// effect runs. - /// See [#1439](https://github.com/rust-lang/rust-clippy/issues/1439) for more details. + /// See rust-lang/rust-clippy#1439 for more details. /// /// **Example:** /// ```rust,ignore @@ -45,9 +45,8 @@ declare_clippy_lint! { /// /// **Why is this bad?** It's unnecessary to create the closure. /// - /// **Known problems:** [#3071](https://github.com/rust-lang/rust-clippy/issues/3071), - /// [#3942](https://github.com/rust-lang/rust-clippy/issues/3942), - /// [#4002](https://github.com/rust-lang/rust-clippy/issues/4002) + /// **Known problems:** rust-lang/rust-clippy#3071, rust-lang/rust-clippy#4002, + /// rust-lang/rust-clippy#3942 /// /// /// **Example:** diff --git a/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs b/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs index 9f389c8d2f9e7..509a4a4e15f62 100644 --- a/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs +++ b/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs @@ -57,11 +57,11 @@ impl<'tcx> LateLintPass<'tcx> for FallibleImplFrom { // check for `impl From for ..` let impl_def_id = cx.tcx.hir().local_def_id(item.hir_id); if_chain! { - if let hir::ItemKind::Impl(impl_) = &item.kind; + if let hir::ItemKind::Impl{ items: impl_items, .. } = item.kind; if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(impl_def_id); if match_def_path(cx, impl_trait_ref.def_id, &FROM_TRAIT); then { - lint_impl_body(cx, item.span, impl_.items); + lint_impl_body(cx, item.span, impl_items); } } } diff --git a/src/tools/clippy/clippy_lints/src/floating_point_arithmetic.rs b/src/tools/clippy/clippy_lints/src/floating_point_arithmetic.rs index ffef78aac8067..18fea8b34bfd4 100644 --- a/src/tools/clippy/clippy_lints/src/floating_point_arithmetic.rs +++ b/src/tools/clippy/clippy_lints/src/floating_point_arithmetic.rs @@ -2,7 +2,7 @@ use crate::consts::{ constant, constant_simple, Constant, Constant::{Int, F32, F64}, }; -use crate::utils::{eq_expr_value, get_parent_expr, numeric_literal, span_lint_and_sugg, sugg}; +use crate::utils::{eq_expr_value, get_parent_expr, higher, numeric_literal, span_lint_and_sugg, sugg}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir::{BinOpKind, Expr, ExprKind, PathSegment, UnOp}; @@ -556,11 +556,11 @@ fn are_negated<'a>(cx: &LateContext<'_>, expr1: &'a Expr<'a>, expr2: &'a Expr<'a fn check_custom_abs(cx: &LateContext<'_>, expr: &Expr<'_>) { if_chain! { - if let ExprKind::If(cond, body, else_body) = expr.kind; + if let Some((cond, body, Some(else_body))) = higher::if_block(&expr); if let ExprKind::Block(block, _) = body.kind; if block.stmts.is_empty(); if let Some(if_body_expr) = block.expr; - if let Some(ExprKind::Block(else_block, _)) = else_body.map(|el| &el.kind); + if let ExprKind::Block(else_block, _) = else_body.kind; if else_block.stmts.is_empty(); if let Some(else_body_expr) = else_block.expr; if let Some((if_expr_positive, body)) = are_negated(cx, if_body_expr, else_body_expr); diff --git a/src/tools/clippy/clippy_lints/src/from_over_into.rs b/src/tools/clippy/clippy_lints/src/from_over_into.rs index b010abda24d10..1e7e5f53cc2a3 100644 --- a/src/tools/clippy/clippy_lints/src/from_over_into.rs +++ b/src/tools/clippy/clippy_lints/src/from_over_into.rs @@ -70,7 +70,7 @@ impl LateLintPass<'_> for FromOverInto { span_lint_and_help( cx, FROM_OVER_INTO, - cx.tcx.sess.source_map().guess_head_span(item.span), + item.span, "an implementation of `From` is preferred since it gives you `Into<_>` for free where the reverse isn't true", None, "consider to implement `From` instead", diff --git a/src/tools/clippy/clippy_lints/src/future_not_send.rs b/src/tools/clippy/clippy_lints/src/future_not_send.rs index a3a38fad9a377..f9697afe40525 100644 --- a/src/tools/clippy/clippy_lints/src/future_not_send.rs +++ b/src/tools/clippy/clippy_lints/src/future_not_send.rs @@ -4,7 +4,7 @@ use rustc_hir::{Body, FnDecl, HirId}; use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::subst::Subst; -use rustc_middle::ty::{Opaque, PredicateKind::Trait}; +use rustc_middle::ty::{Opaque, PredicateAtom::Trait}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::{sym, Span}; use rustc_trait_selection::traits::error_reporting::suggestions::InferCtxtExt; @@ -97,7 +97,7 @@ impl<'tcx> LateLintPass<'tcx> for FutureNotSend { &obligation, ); if let Trait(trait_pred, _) = - obligation.predicate.kind().skip_binder() + obligation.predicate.skip_binders() { db.note(&format!( "`{}` doesn't implement `{}`", diff --git a/src/tools/clippy/clippy_lints/src/if_let_mutex.rs b/src/tools/clippy/clippy_lints/src/if_let_mutex.rs index 58511c6d57c68..2e55094d90c6f 100644 --- a/src/tools/clippy/clippy_lints/src/if_let_mutex.rs +++ b/src/tools/clippy/clippy_lints/src/if_let_mutex.rs @@ -145,7 +145,7 @@ impl<'tcx, 'l> ArmVisitor<'tcx, 'l> { fn is_mutex_lock_call<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> { if_chain! { if let ExprKind::MethodCall(path, _span, args, _) = &expr.kind; - if path.ident.as_str() == "lock"; + if path.ident.to_string() == "lock"; let ty = cx.typeck_results().expr_ty(&args[0]); if is_type_diagnostic_item(cx, ty, sym!(mutex_type)); then { diff --git a/src/tools/clippy/clippy_lints/src/implicit_return.rs b/src/tools/clippy/clippy_lints/src/implicit_return.rs index 109d90ff772b5..03e95c9e27f6a 100644 --- a/src/tools/clippy/clippy_lints/src/implicit_return.rs +++ b/src/tools/clippy/clippy_lints/src/implicit_return.rs @@ -81,13 +81,6 @@ fn expr_match(cx: &LateContext<'_>, expr: &Expr<'_>) { lint(cx, expr.span, break_expr.span, LINT_BREAK); } }, - ExprKind::If(.., if_expr, else_expr) => { - expr_match(cx, if_expr); - - if let Some(else_expr) = else_expr { - expr_match(cx, else_expr); - } - }, ExprKind::Match(.., arms, source) => { let check_all_arms = match source { MatchSource::IfLetDesugar { diff --git a/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs b/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs index 16e162badb5ee..3a01acd8fdc97 100644 --- a/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs +++ b/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs @@ -1,4 +1,4 @@ -use crate::utils::{in_macro, match_qpath, span_lint_and_sugg, SpanlessEq}; +use crate::utils::{higher, in_macro, match_qpath, span_lint_and_sugg, SpanlessEq}; use if_chain::if_chain; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; @@ -42,7 +42,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitSaturatingSub { return; } if_chain! { - if let ExprKind::If(cond, then, None) = &expr.kind; + if let Some((ref cond, ref then, None)) = higher::if_block(&expr); // Check if the conditional expression is a binary operation if let ExprKind::Binary(ref cond_op, ref cond_left, ref cond_right) = cond.kind; diff --git a/src/tools/clippy/clippy_lints/src/inherent_impl.rs b/src/tools/clippy/clippy_lints/src/inherent_impl.rs index ea26c84cde16a..4e6bb60478541 100644 --- a/src/tools/clippy/clippy_lints/src/inherent_impl.rs +++ b/src/tools/clippy/clippy_lints/src/inherent_impl.rs @@ -2,7 +2,7 @@ use crate::utils::{in_macro, span_lint_and_then}; use rustc_data_structures::fx::FxHashMap; -use rustc_hir::{def_id, Crate, Impl, Item, ItemKind}; +use rustc_hir::{def_id, Crate, Item, ItemKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::Span; @@ -49,11 +49,11 @@ impl_lint_pass!(MultipleInherentImpl => [MULTIPLE_INHERENT_IMPL]); impl<'tcx> LateLintPass<'tcx> for MultipleInherentImpl { fn check_item(&mut self, _: &LateContext<'tcx>, item: &'tcx Item<'_>) { - if let ItemKind::Impl(Impl { + if let ItemKind::Impl { ref generics, of_trait: None, .. - }) = item.kind + } = item.kind { // Remember for each inherent implementation encountered its span and generics // but filter out implementations that have generic params (type or lifetime) diff --git a/src/tools/clippy/clippy_lints/src/len_zero.rs b/src/tools/clippy/clippy_lints/src/len_zero.rs index e95caf6a35f90..6fe5335109045 100644 --- a/src/tools/clippy/clippy_lints/src/len_zero.rs +++ b/src/tools/clippy/clippy_lints/src/len_zero.rs @@ -3,7 +3,7 @@ use rustc_ast::ast::LitKind; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir::def_id::DefId; -use rustc_hir::{AssocItemKind, BinOpKind, Expr, ExprKind, Impl, ImplItemRef, Item, ItemKind, TraitItemRef}; +use rustc_hir::{AssocItemKind, BinOpKind, Expr, ExprKind, ImplItemRef, Item, ItemKind, TraitItemRef}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; @@ -115,11 +115,11 @@ impl<'tcx> LateLintPass<'tcx> for LenZero { match item.kind { ItemKind::Trait(_, _, _, _, ref trait_items) => check_trait_items(cx, item, trait_items), - ItemKind::Impl(Impl { + ItemKind::Impl { of_trait: None, items: ref impl_items, .. - }) => check_impl_items(cx, item, impl_items), + } => check_impl_items(cx, item, impl_items), _ => (), } } diff --git a/src/tools/clippy/clippy_lints/src/let_if_seq.rs b/src/tools/clippy/clippy_lints/src/let_if_seq.rs index db717cd1240a4..0d2d95324c4f7 100644 --- a/src/tools/clippy/clippy_lints/src/let_if_seq.rs +++ b/src/tools/clippy/clippy_lints/src/let_if_seq.rs @@ -1,4 +1,5 @@ -use crate::utils::{qpath_res, snippet, span_lint_and_then, visitors::LocalUsedVisitor}; +use crate::utils::visitors::LocalUsedVisitor; +use crate::utils::{higher, qpath_res, snippet, span_lint_and_then}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; @@ -63,7 +64,7 @@ impl<'tcx> LateLintPass<'tcx> for LetIfSeq { if let hir::StmtKind::Local(ref local) = stmt.kind; if let hir::PatKind::Binding(mode, canonical_id, ident, None) = local.pat.kind; if let hir::StmtKind::Expr(ref if_) = expr.kind; - if let hir::ExprKind::If(ref cond, ref then, ref else_) = if_.kind; + if let Some((ref cond, ref then, ref else_)) = higher::if_block(&if_); if !LocalUsedVisitor::new(canonical_id).check_expr(cond); if let hir::ExprKind::Block(ref then, _) = then.kind; if let Some(value) = check_assign(cx, canonical_id, &*then); diff --git a/src/tools/clippy/clippy_lints/src/lib.rs b/src/tools/clippy/clippy_lints/src/lib.rs index 781282cdfbd03..35b057d7b6a41 100644 --- a/src/tools/clippy/clippy_lints/src/lib.rs +++ b/src/tools/clippy/clippy_lints/src/lib.rs @@ -271,7 +271,6 @@ mod needless_borrow; mod needless_borrowed_ref; mod needless_continue; mod needless_pass_by_value; -mod needless_question_mark; mod needless_update; mod neg_cmp_op_on_partial_ord; mod neg_multiply; @@ -342,7 +341,6 @@ mod unwrap_in_result; mod use_self; mod useless_conversion; mod vec; -mod vec_init_then_push; mod vec_resize_to_zero; mod verbose_file_reads; mod wildcard_dependencies; @@ -502,10 +500,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: "clippy::panic_params", "this lint has been uplifted to rustc and is now called `panic_fmt`", ); - store.register_removed( - "clippy::unknown_clippy_lints", - "this lint has been integrated into the `unknown_lints` rustc lint", - ); // end deprecated lints, do not remove this comment, it’s used in `update_lints` // begin register lints, do not remove this comment, it’s used in `update_lints` @@ -530,8 +524,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: &utils::internal_lints::OUTER_EXPN_EXPN_DATA, #[cfg(feature = "internal-lints")] &utils::internal_lints::PRODUCE_ICE, - #[cfg(feature = "internal-lints")] - &utils::internal_lints::UNNECESSARY_SYMBOL_STR, &approx_const::APPROX_CONSTANT, &arithmetic::FLOAT_ARITHMETIC, &arithmetic::INTEGER_ARITHMETIC, @@ -549,6 +541,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: &attrs::EMPTY_LINE_AFTER_OUTER_ATTR, &attrs::INLINE_ALWAYS, &attrs::MISMATCHED_TARGET_OS, + &attrs::UNKNOWN_CLIPPY_LINTS, &attrs::USELESS_ATTRIBUTE, &await_holding_invalid::AWAIT_HOLDING_LOCK, &await_holding_invalid::AWAIT_HOLDING_REFCELL_REF, @@ -563,7 +556,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: &cargo_common_metadata::CARGO_COMMON_METADATA, &checked_conversions::CHECKED_CONVERSIONS, &cognitive_complexity::COGNITIVE_COMPLEXITY, - &collapsible_if::COLLAPSIBLE_ELSE_IF, &collapsible_if::COLLAPSIBLE_IF, &collapsible_match::COLLAPSIBLE_MATCH, &comparison_chain::COMPARISON_CHAIN, @@ -807,7 +799,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: &needless_borrowed_ref::NEEDLESS_BORROWED_REFERENCE, &needless_continue::NEEDLESS_CONTINUE, &needless_pass_by_value::NEEDLESS_PASS_BY_VALUE, - &needless_question_mark::NEEDLESS_QUESTION_MARK, &needless_update::NEEDLESS_UPDATE, &neg_cmp_op_on_partial_ord::NEG_CMP_OP_ON_PARTIAL_ORD, &neg_multiply::NEG_MULTIPLY, @@ -917,7 +908,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: &types::LET_UNIT_VALUE, &types::LINKEDLIST, &types::OPTION_OPTION, - &types::PTR_AS_PTR, &types::RC_BUFFER, &types::REDUNDANT_ALLOCATION, &types::TYPE_COMPLEXITY, @@ -945,7 +935,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: &use_self::USE_SELF, &useless_conversion::USELESS_CONVERSION, &vec::USELESS_VEC, - &vec_init_then_push::VEC_INIT_THEN_PUSH, &vec_resize_to_zero::VEC_RESIZE_TO_ZERO, &verbose_file_reads::VERBOSE_FILE_READS, &wildcard_dependencies::WILDCARD_DEPENDENCIES, @@ -1030,7 +1019,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: store.register_late_pass(move || box from_over_into::FromOverInto::new(msrv)); store.register_late_pass(move || box use_self::UseSelf::new(msrv)); store.register_late_pass(move || box missing_const_for_fn::MissingConstForFn::new(msrv)); - store.register_late_pass(move || box needless_question_mark::NeedlessQuestionMark::new(msrv)); store.register_late_pass(|| box size_of_in_element_count::SizeOfInElementCount); store.register_late_pass(|| box map_clone::MapClone); @@ -1227,8 +1215,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: store.register_late_pass(|| box strings::StrToString); store.register_late_pass(|| box strings::StringToString); store.register_late_pass(|| box zero_sized_map_values::ZeroSizedMapValues); - store.register_late_pass(|| box vec_init_then_push::VecInitThenPush::default()); - store.register_late_pass(move || box types::PtrAsPtr::new(msrv)); store.register_group(true, "clippy::restriction", Some("clippy_restriction"), vec![ LintId::of(&arithmetic::FLOAT_ARITHMETIC), @@ -1355,7 +1341,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&types::LET_UNIT_VALUE), LintId::of(&types::LINKEDLIST), LintId::of(&types::OPTION_OPTION), - LintId::of(&types::PTR_AS_PTR), LintId::of(&unicode::NON_ASCII_LITERAL), LintId::of(&unicode::UNICODE_NOT_NFC), LintId::of(&unnested_or_patterns::UNNESTED_OR_PATTERNS), @@ -1377,7 +1362,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&utils::internal_lints::MATCH_TYPE_ON_DIAGNOSTIC_ITEM), LintId::of(&utils::internal_lints::OUTER_EXPN_EXPN_DATA), LintId::of(&utils::internal_lints::PRODUCE_ICE), - LintId::of(&utils::internal_lints::UNNECESSARY_SYMBOL_STR), ]); store.register_group(true, "clippy::all", Some("clippy"), vec![ @@ -1391,6 +1375,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&attrs::DEPRECATED_CFG_ATTR), LintId::of(&attrs::DEPRECATED_SEMVER), LintId::of(&attrs::MISMATCHED_TARGET_OS), + LintId::of(&attrs::UNKNOWN_CLIPPY_LINTS), LintId::of(&attrs::USELESS_ATTRIBUTE), LintId::of(&bit_mask::BAD_BIT_MASK), LintId::of(&bit_mask::INEFFECTIVE_BIT_MASK), @@ -1399,7 +1384,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&booleans::LOGIC_BUG), LintId::of(&booleans::NONMINIMAL_BOOL), LintId::of(&bytecount::NAIVE_BYTECOUNT), - LintId::of(&collapsible_if::COLLAPSIBLE_ELSE_IF), LintId::of(&collapsible_if::COLLAPSIBLE_IF), LintId::of(&collapsible_match::COLLAPSIBLE_MATCH), LintId::of(&comparison_chain::COMPARISON_CHAIN), @@ -1561,7 +1545,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&needless_bool::BOOL_COMPARISON), LintId::of(&needless_bool::NEEDLESS_BOOL), LintId::of(&needless_borrowed_ref::NEEDLESS_BORROWED_REFERENCE), - LintId::of(&needless_question_mark::NEEDLESS_QUESTION_MARK), LintId::of(&needless_update::NEEDLESS_UPDATE), LintId::of(&neg_cmp_op_on_partial_ord::NEG_CMP_OP_ON_PARTIAL_ORD), LintId::of(&neg_multiply::NEG_MULTIPLY), @@ -1653,7 +1636,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&unwrap::UNNECESSARY_UNWRAP), LintId::of(&useless_conversion::USELESS_CONVERSION), LintId::of(&vec::USELESS_VEC), - LintId::of(&vec_init_then_push::VEC_INIT_THEN_PUSH), LintId::of(&vec_resize_to_zero::VEC_RESIZE_TO_ZERO), LintId::of(&write::PRINTLN_EMPTY_STRING), LintId::of(&write::PRINT_LITERAL), @@ -1668,9 +1650,9 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&assertions_on_constants::ASSERTIONS_ON_CONSTANTS), LintId::of(&assign_ops::ASSIGN_OP_PATTERN), LintId::of(&attrs::BLANKET_CLIPPY_RESTRICTION_LINTS), + LintId::of(&attrs::UNKNOWN_CLIPPY_LINTS), LintId::of(&blacklisted_name::BLACKLISTED_NAME), LintId::of(&blocks_in_if_conditions::BLOCKS_IN_IF_CONDITIONS), - LintId::of(&collapsible_if::COLLAPSIBLE_ELSE_IF), LintId::of(&collapsible_if::COLLAPSIBLE_IF), LintId::of(&collapsible_match::COLLAPSIBLE_MATCH), LintId::of(&comparison_chain::COMPARISON_CHAIN), @@ -1821,7 +1803,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&needless_bool::BOOL_COMPARISON), LintId::of(&needless_bool::NEEDLESS_BOOL), LintId::of(&needless_borrowed_ref::NEEDLESS_BORROWED_REFERENCE), - LintId::of(&needless_question_mark::NEEDLESS_QUESTION_MARK), LintId::of(&needless_update::NEEDLESS_UPDATE), LintId::of(&neg_cmp_op_on_partial_ord::NEG_CMP_OP_ON_PARTIAL_ORD), LintId::of(&no_effect::NO_EFFECT), @@ -1954,7 +1935,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: LintId::of(&types::BOX_VEC), LintId::of(&types::REDUNDANT_ALLOCATION), LintId::of(&vec::USELESS_VEC), - LintId::of(&vec_init_then_push::VEC_INIT_THEN_PUSH), ]); store.register_group(true, "clippy::cargo", Some("clippy_cargo"), vec![ diff --git a/src/tools/clippy/clippy_lints/src/loops.rs b/src/tools/clippy/clippy_lints/src/loops.rs index 1c5ab2874b048..1bd96b2b4c89b 100644 --- a/src/tools/clippy/clippy_lints/src/loops.rs +++ b/src/tools/clippy/clippy_lints/src/loops.rs @@ -218,7 +218,7 @@ declare_clippy_lint! { /// **Why is this bad?** The `while let` loop is usually shorter and more /// readable. /// - /// **Known problems:** Sometimes the wrong binding is displayed ([#383](https://github.com/rust-lang/rust-clippy/issues/383)). + /// **Known problems:** Sometimes the wrong binding is displayed (#383). /// /// **Example:** /// ```rust,no_run @@ -742,14 +742,6 @@ fn never_loop_expr(expr: &Expr<'_>, main_loop_id: HirId) -> NeverLoopResult { // Break can come from the inner loop so remove them. absorb_break(&never_loop_block(b, main_loop_id)) }, - ExprKind::If(ref e, ref e2, ref e3) => { - let e1 = never_loop_expr(e, main_loop_id); - let e2 = never_loop_expr(e2, main_loop_id); - let e3 = e3 - .as_ref() - .map_or(NeverLoopResult::Otherwise, |e| never_loop_expr(e, main_loop_id)); - combine_seq(e1, combine_branches(e2, e3)) - }, ExprKind::Match(ref e, ref arms, _) => { let e = never_loop_expr(e, main_loop_id); if arms.is_empty() { @@ -2602,7 +2594,7 @@ fn is_loop(expr: &Expr<'_>) -> bool { } fn is_conditional(expr: &Expr<'_>) -> bool { - matches!(expr.kind, ExprKind::If(..) | ExprKind::Match(..)) + matches!(expr.kind, ExprKind::Match(..)) } fn is_nested(cx: &LateContext<'_>, match_expr: &Expr<'_>, iter_expr: &Expr<'_>) -> bool { diff --git a/src/tools/clippy/clippy_lints/src/manual_async_fn.rs b/src/tools/clippy/clippy_lints/src/manual_async_fn.rs index 89f5b2ff31137..29439e52c48e1 100644 --- a/src/tools/clippy/clippy_lints/src/manual_async_fn.rs +++ b/src/tools/clippy/clippy_lints/src/manual_async_fn.rs @@ -9,7 +9,7 @@ use rustc_hir::{ }; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; -use rustc_span::{sym, Span}; +use rustc_span::Span; declare_clippy_lint! { /// **What it does:** It checks for manual implementations of `async` functions. @@ -137,7 +137,7 @@ fn future_output_ty<'tcx>(trait_ref: &'tcx TraitRef<'tcx>) -> Option<&'tcx Ty<'t if let Some(args) = segment.args; if args.bindings.len() == 1; let binding = &args.bindings[0]; - if binding.ident.name == sym::Output; + if binding.ident.as_str() == "Output"; if let TypeBindingKind::Equality{ty: output} = binding.kind; then { return Some(output) diff --git a/src/tools/clippy/clippy_lints/src/manual_strip.rs b/src/tools/clippy/clippy_lints/src/manual_strip.rs index a0cfe145a301c..3c4368a3545a9 100644 --- a/src/tools/clippy/clippy_lints/src/manual_strip.rs +++ b/src/tools/clippy/clippy_lints/src/manual_strip.rs @@ -80,7 +80,7 @@ impl<'tcx> LateLintPass<'tcx> for ManualStrip { } if_chain! { - if let ExprKind::If(cond, then, _) = &expr.kind; + if let Some((cond, then, _)) = higher::if_block(&expr); if let ExprKind::MethodCall(_, _, [target_arg, pattern], _) = cond.kind; if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(cond.hir_id); if let ExprKind::Path(target_path) = &target_arg.kind; diff --git a/src/tools/clippy/clippy_lints/src/map_clone.rs b/src/tools/clippy/clippy_lints/src/map_clone.rs index 1818836d5d5e8..220240acb7aa9 100644 --- a/src/tools/clippy/clippy_lints/src/map_clone.rs +++ b/src/tools/clippy/clippy_lints/src/map_clone.rs @@ -53,7 +53,7 @@ impl<'tcx> LateLintPass<'tcx> for MapClone { if_chain! { if let hir::ExprKind::MethodCall(ref method, _, ref args, _) = e.kind; if args.len() == 2; - if method.ident.name == sym::map; + if method.ident.as_str() == "map"; let ty = cx.typeck_results().expr_ty(&args[0]); if is_type_diagnostic_item(cx, ty, sym::option_type) || match_trait_method(cx, e, &paths::ITERATOR); if let hir::ExprKind::Closure(_, _, body_id, _, _) = args[1].kind; diff --git a/src/tools/clippy/clippy_lints/src/map_identity.rs b/src/tools/clippy/clippy_lints/src/map_identity.rs index 9f9c108a85a05..6b782385a38d2 100644 --- a/src/tools/clippy/clippy_lints/src/map_identity.rs +++ b/src/tools/clippy/clippy_lints/src/map_identity.rs @@ -63,7 +63,7 @@ impl<'tcx> LateLintPass<'tcx> for MapIdentity { fn get_map_argument<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<&'a [Expr<'a>]> { if_chain! { if let ExprKind::MethodCall(ref method, _, ref args, _) = expr.kind; - if args.len() == 2 && method.ident.name == sym::map; + if args.len() == 2 && method.ident.as_str() == "map"; let caller_ty = cx.typeck_results().expr_ty(&args[0]); if match_trait_method(cx, expr, &paths::ITERATOR) || is_type_diagnostic_item(cx, caller_ty, sym::result_type) diff --git a/src/tools/clippy/clippy_lints/src/methods/mod.rs b/src/tools/clippy/clippy_lints/src/methods/mod.rs index 7adf6bdeac5a0..e99fe1b97ff64 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mod.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mod.rs @@ -1626,7 +1626,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods { let self_ty = cx.tcx.type_of(def_id); // if this impl block implements a trait, lint in trait definition instead - if let hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = item.kind { + if let hir::ItemKind::Impl { of_trait: Some(_), .. } = item.kind { return; } @@ -1697,7 +1697,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods { if let ty::Opaque(def_id, _) = *ret_ty.kind() { // one of the associated types must be Self for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) { - if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() { + if let ty::PredicateAtom::Projection(projection_predicate) = predicate.skip_binders() { // walk the associated type and check for Self if contains_ty(projection_predicate.ty, self_ty) { return; @@ -2048,7 +2048,6 @@ fn lint_expect_fun_call( hir::ExprKind::Call(..) | hir::ExprKind::MethodCall(..) // These variants are debatable or require further examination - | hir::ExprKind::If(..) | hir::ExprKind::Match(..) | hir::ExprKind::Block{ .. } => true, _ => false, @@ -3096,7 +3095,7 @@ fn lint_flat_map_identity<'tcx>( if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = body.value.kind; if path.segments.len() == 1; - if path.segments[0].ident.name == binding_ident.name; + if path.segments[0].ident.as_str() == binding_ident.as_str(); then { apply_lint("called `flat_map(|x| x)` on an `Iterator`"); diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_filter_map.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_filter_map.rs index d98e6160d3085..d082a88cd2db5 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_filter_map.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_filter_map.rs @@ -90,12 +90,6 @@ fn check_expression<'tcx>(cx: &LateContext<'tcx>, arg_id: hir::HirId, expr: &'tc } (found_mapping, found_filtering) }, - // There must be an else_arm or there will be a type error - hir::ExprKind::If(_, ref if_arm, Some(ref else_arm)) => { - let if_check = check_expression(cx, arg_id, if_arm); - let else_check = check_expression(cx, arg_id, else_arm); - (if_check.0 | else_check.0, if_check.1 | else_check.1) - }, hir::ExprKind::Path(path) if match_qpath(path, &paths::OPTION_NONE) => (false, true), _ => (true, true), } diff --git a/src/tools/clippy/clippy_lints/src/minmax.rs b/src/tools/clippy/clippy_lints/src/minmax.rs index 8d0c3b8e0fe89..004dd50a31be8 100644 --- a/src/tools/clippy/clippy_lints/src/minmax.rs +++ b/src/tools/clippy/clippy_lints/src/minmax.rs @@ -89,9 +89,9 @@ fn min_max<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<(MinMax, Cons if let [obj, _] = args; if cx.typeck_results().expr_ty(obj).is_floating_point() || match_trait_method(cx, expr, &paths::ORD); then { - if path.ident.name == sym!(max) { + if path.ident.as_str() == sym!(max).as_str() { fetch_const(cx, args, MinMax::Max) - } else if path.ident.name == sym!(min) { + } else if path.ident.as_str() == sym!(min).as_str() { fetch_const(cx, args, MinMax::Min) } else { None diff --git a/src/tools/clippy/clippy_lints/src/missing_doc.rs b/src/tools/clippy/clippy_lints/src/missing_doc.rs index 0e49eaab43685..27f1074a0dd8a 100644 --- a/src/tools/clippy/clippy_lints/src/missing_doc.rs +++ b/src/tools/clippy/clippy_lints/src/missing_doc.rs @@ -63,7 +63,7 @@ impl MissingDoc { if let Some(meta) = list.get(0); if let Some(name) = meta.ident(); then { - name.name == sym::include + name.as_str() == "include" } else { false } diff --git a/src/tools/clippy/clippy_lints/src/mutable_debug_assertion.rs b/src/tools/clippy/clippy_lints/src/mutable_debug_assertion.rs index 71f91eb4bfbe3..76417aa7ed09d 100644 --- a/src/tools/clippy/clippy_lints/src/mutable_debug_assertion.rs +++ b/src/tools/clippy/clippy_lints/src/mutable_debug_assertion.rs @@ -90,10 +90,6 @@ impl<'a, 'tcx> Visitor<'tcx> for MutArgVisitor<'a, 'tcx> { self.found = true; return; }, - ExprKind::If(..) => { - self.found = true; - return; - }, ExprKind::Path(_) => { if let Some(adj) = self.cx.typeck_results().adjustments().get(expr.hir_id) { if adj diff --git a/src/tools/clippy/clippy_lints/src/needless_bool.rs b/src/tools/clippy/clippy_lints/src/needless_bool.rs index d795f12645794..42f97b2ac497a 100644 --- a/src/tools/clippy/clippy_lints/src/needless_bool.rs +++ b/src/tools/clippy/clippy_lints/src/needless_bool.rs @@ -3,7 +3,9 @@ //! This lint is **warn** by default use crate::utils::sugg::Sugg; -use crate::utils::{is_expn_of, parent_node_is_if_expr, snippet_with_applicability, span_lint, span_lint_and_sugg}; +use crate::utils::{ + higher, is_expn_of, parent_node_is_if_expr, snippet_with_applicability, span_lint, span_lint_and_sugg, +}; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; use rustc_hir::{BinOpKind, Block, Expr, ExprKind, StmtKind, UnOp}; @@ -69,7 +71,7 @@ declare_lint_pass!(NeedlessBool => [NEEDLESS_BOOL]); impl<'tcx> LateLintPass<'tcx> for NeedlessBool { fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) { use self::Expression::{Bool, RetBool}; - if let ExprKind::If(ref pred, ref then_block, Some(ref else_expr)) = e.kind { + if let Some((ref pred, ref then_block, Some(ref else_expr))) = higher::if_block(&e) { let reduce = |ret, not| { let mut applicability = Applicability::MachineApplicable; let snip = Sugg::hir_with_applicability(cx, pred, "", &mut applicability); diff --git a/src/tools/clippy/clippy_lints/src/needless_borrow.rs b/src/tools/clippy/clippy_lints/src/needless_borrow.rs index f1c06692e30d9..bff53eb8ccada 100644 --- a/src/tools/clippy/clippy_lints/src/needless_borrow.rs +++ b/src/tools/clippy/clippy_lints/src/needless_borrow.rs @@ -2,7 +2,7 @@ //! //! This lint is **warn** by default -use crate::utils::{is_automatically_derived, snippet_opt, span_lint_and_then}; +use crate::utils::{snippet_opt, span_lint_and_then}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir::{BindingAnnotation, BorrowKind, Expr, ExprKind, HirId, Item, Mutability, Pat, PatKind}; @@ -10,6 +10,7 @@ use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; use rustc_middle::ty::adjustment::{Adjust, Adjustment}; use rustc_session::{declare_tool_lint, impl_lint_pass}; +use rustc_span::sym; declare_clippy_lint! { /// **What it does:** Checks for address of operations (`&`) that are going to @@ -115,7 +116,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessBorrow { } fn check_item(&mut self, _: &LateContext<'tcx>, item: &'tcx Item<'_>) { - if is_automatically_derived(item.attrs) { + if item.attrs.iter().any(|a| a.has_name(sym::automatically_derived)) { debug_assert!(self.derived_item.is_none()); self.derived_item = Some(item.hir_id); } diff --git a/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs b/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs index 89fe2c19a570d..5043b7b1fc3c1 100644 --- a/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs +++ b/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs @@ -8,12 +8,11 @@ use rustc_ast::ast::Attribute; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_errors::{Applicability, DiagnosticBuilder}; use rustc_hir::intravisit::FnKind; -use rustc_hir::{BindingAnnotation, Body, FnDecl, GenericArg, HirId, Impl, ItemKind, Node, PatKind, QPath, TyKind}; +use rustc_hir::{BindingAnnotation, Body, FnDecl, GenericArg, HirId, ItemKind, Node, PatKind, QPath, TyKind}; use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{self, TypeFoldable}; use rustc_session::{declare_lint_pass, declare_tool_lint}; -use rustc_span::symbol::kw; use rustc_span::{sym, Span}; use rustc_target::spec::abi::Abi; use rustc_trait_selection::traits; @@ -93,7 +92,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) { if matches!( item.kind, - ItemKind::Impl(Impl { of_trait: Some(_), .. }) | ItemKind::Trait(..) + ItemKind::Impl { of_trait: Some(_), .. } | ItemKind::Trait(..) ) { return; } @@ -116,11 +115,13 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { .filter(|p| !p.is_global()) .filter_map(|obligation| { // Note that we do not want to deal with qualified predicates here. - match obligation.predicate.kind().no_bound_vars() { - Some(ty::PredicateKind::Trait(pred, _)) if pred.def_id() != sized_trait => { - Some(pred) - }, - _ => None, + if let ty::PredicateKind::Atom(ty::PredicateAtom::Trait(pred, _)) = obligation.predicate.kind() { + if pred.def_id() == sized_trait { + return None; + } + Some(pred) + } else { + None } }) .collect::>(); @@ -152,7 +153,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { // Ignore `self`s. if idx == 0 { if let PatKind::Binding(.., ident, _) = arg.pat.kind { - if ident.name == kw::SelfLower { + if ident.as_str() == "self" { continue; } } diff --git a/src/tools/clippy/clippy_lints/src/needless_question_mark.rs b/src/tools/clippy/clippy_lints/src/needless_question_mark.rs deleted file mode 100644 index 9e9b79ee1cf08..0000000000000 --- a/src/tools/clippy/clippy_lints/src/needless_question_mark.rs +++ /dev/null @@ -1,232 +0,0 @@ -use rustc_errors::Applicability; -use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res}; -use rustc_hir::{Body, Expr, ExprKind, LangItem, MatchSource, QPath}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; -use rustc_middle::ty::DefIdTree; -use rustc_semver::RustcVersion; -use rustc_session::{declare_tool_lint, impl_lint_pass}; -use rustc_span::sym; - -use crate::utils; -use if_chain::if_chain; - -declare_clippy_lint! { - /// **What it does:** - /// Suggests alternatives for useless applications of `?` in terminating expressions - /// - /// **Why is this bad?** There's no reason to use `?` to short-circuit when execution of the body will end there anyway. - /// - /// **Known problems:** None. - /// - /// **Example:** - /// - /// ```rust - /// struct TO { - /// magic: Option, - /// } - /// - /// fn f(to: TO) -> Option { - /// Some(to.magic?) - /// } - /// - /// struct TR { - /// magic: Result, - /// } - /// - /// fn g(tr: Result) -> Result { - /// tr.and_then(|t| Ok(t.magic?)) - /// } - /// - /// ``` - /// Use instead: - /// ```rust - /// struct TO { - /// magic: Option, - /// } - /// - /// fn f(to: TO) -> Option { - /// to.magic - /// } - /// - /// struct TR { - /// magic: Result, - /// } - /// - /// fn g(tr: Result) -> Result { - /// tr.and_then(|t| t.magic) - /// } - /// ``` - pub NEEDLESS_QUESTION_MARK, - complexity, - "Suggest `value.inner_option` instead of `Some(value.inner_option?)`. The same goes for `Result`." -} - -const NEEDLESS_QUESTION_MARK_RESULT_MSRV: RustcVersion = RustcVersion::new(1, 13, 0); -const NEEDLESS_QUESTION_MARK_OPTION_MSRV: RustcVersion = RustcVersion::new(1, 22, 0); - -pub struct NeedlessQuestionMark { - msrv: Option, -} - -impl NeedlessQuestionMark { - #[must_use] - pub fn new(msrv: Option) -> Self { - Self { msrv } - } -} - -impl_lint_pass!(NeedlessQuestionMark => [NEEDLESS_QUESTION_MARK]); - -#[derive(Debug)] -enum SomeOkCall<'a> { - SomeCall(&'a Expr<'a>, &'a Expr<'a>), - OkCall(&'a Expr<'a>, &'a Expr<'a>), -} - -impl LateLintPass<'_> for NeedlessQuestionMark { - /* - * The question mark operator is compatible with both Result and Option, - * from Rust 1.13 and 1.22 respectively. - */ - - /* - * What do we match: - * Expressions that look like this: - * Some(option?), Ok(result?) - * - * Where do we match: - * Last expression of a body - * Return statement - * A body's value (single line closure) - * - * What do we not match: - * Implicit calls to `from(..)` on the error value - */ - - fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'_ Expr<'_>) { - let e = match &expr.kind { - ExprKind::Ret(Some(e)) => e, - _ => return, - }; - - if let Some(ok_some_call) = is_some_or_ok_call(self, cx, e) { - emit_lint(cx, &ok_some_call); - } - } - - fn check_body(&mut self, cx: &LateContext<'_>, body: &'_ Body<'_>) { - // Function / Closure block - let expr_opt = if let ExprKind::Block(block, _) = &body.value.kind { - block.expr - } else { - // Single line closure - Some(&body.value) - }; - - if_chain! { - if let Some(expr) = expr_opt; - if let Some(ok_some_call) = is_some_or_ok_call(self, cx, expr); - then { - emit_lint(cx, &ok_some_call); - } - }; - } - - extract_msrv_attr!(LateContext); -} - -fn emit_lint(cx: &LateContext<'_>, expr: &SomeOkCall<'_>) { - let (entire_expr, inner_expr) = match expr { - SomeOkCall::OkCall(outer, inner) | SomeOkCall::SomeCall(outer, inner) => (outer, inner), - }; - - utils::span_lint_and_sugg( - cx, - NEEDLESS_QUESTION_MARK, - entire_expr.span, - "Question mark operator is useless here", - "try", - format!("{}", utils::snippet(cx, inner_expr.span, r#""...""#)), - Applicability::MachineApplicable, - ); -} - -fn is_some_or_ok_call<'a>( - nqml: &NeedlessQuestionMark, - cx: &'a LateContext<'_>, - expr: &'a Expr<'_>, -) -> Option> { - if_chain! { - // Check outer expression matches CALL_IDENT(ARGUMENT) format - if let ExprKind::Call(path, args) = &expr.kind; - if let ExprKind::Path(QPath::Resolved(None, path)) = &path.kind; - if is_some_ctor(cx, path.res) || is_ok_ctor(cx, path.res); - - // Extract inner expression from ARGUMENT - if let ExprKind::Match(inner_expr_with_q, _, MatchSource::TryDesugar) = &args[0].kind; - if let ExprKind::Call(called, args) = &inner_expr_with_q.kind; - if args.len() == 1; - - if let ExprKind::Path(QPath::LangItem(LangItem::TryIntoResult, _)) = &called.kind; - then { - // Extract inner expr type from match argument generated by - // question mark operator - let inner_expr = &args[0]; - - let inner_ty = cx.typeck_results().expr_ty(inner_expr); - let outer_ty = cx.typeck_results().expr_ty(expr); - - // Check if outer and inner type are Option - let outer_is_some = utils::is_type_diagnostic_item(cx, outer_ty, sym::option_type); - let inner_is_some = utils::is_type_diagnostic_item(cx, inner_ty, sym::option_type); - - // Check for Option MSRV - let meets_option_msrv = utils::meets_msrv(nqml.msrv.as_ref(), &NEEDLESS_QUESTION_MARK_OPTION_MSRV); - if outer_is_some && inner_is_some && meets_option_msrv { - return Some(SomeOkCall::SomeCall(expr, inner_expr)); - } - - // Check if outer and inner type are Result - let outer_is_result = utils::is_type_diagnostic_item(cx, outer_ty, sym::result_type); - let inner_is_result = utils::is_type_diagnostic_item(cx, inner_ty, sym::result_type); - - // Additional check: if the error type of the Result can be converted - // via the From trait, then don't match - let does_not_call_from = !has_implicit_error_from(cx, expr, inner_expr); - - // Must meet Result MSRV - let meets_result_msrv = utils::meets_msrv(nqml.msrv.as_ref(), &NEEDLESS_QUESTION_MARK_RESULT_MSRV); - if outer_is_result && inner_is_result && does_not_call_from && meets_result_msrv { - return Some(SomeOkCall::OkCall(expr, inner_expr)); - } - } - } - - None -} - -fn has_implicit_error_from(cx: &LateContext<'_>, entire_expr: &Expr<'_>, inner_result_expr: &Expr<'_>) -> bool { - return cx.typeck_results().expr_ty(entire_expr) != cx.typeck_results().expr_ty(inner_result_expr); -} - -fn is_ok_ctor(cx: &LateContext<'_>, res: Res) -> bool { - if let Some(ok_id) = cx.tcx.lang_items().result_ok_variant() { - if let Res::Def(DefKind::Ctor(CtorOf::Variant, CtorKind::Fn), id) = res { - if let Some(variant_id) = cx.tcx.parent(id) { - return variant_id == ok_id; - } - } - } - false -} - -fn is_some_ctor(cx: &LateContext<'_>, res: Res) -> bool { - if let Some(some_id) = cx.tcx.lang_items().option_some_variant() { - if let Res::Def(DefKind::Ctor(CtorOf::Variant, CtorKind::Fn), id) = res { - if let Some(variant_id) = cx.tcx.parent(id) { - return variant_id == some_id; - } - } - } - false -} diff --git a/src/tools/clippy/clippy_lints/src/new_without_default.rs b/src/tools/clippy/clippy_lints/src/new_without_default.rs index bd3dac663fe27..68fdd0eb269ef 100644 --- a/src/tools/clippy/clippy_lints/src/new_without_default.rs +++ b/src/tools/clippy/clippy_lints/src/new_without_default.rs @@ -60,9 +60,9 @@ impl_lint_pass!(NewWithoutDefault => [NEW_WITHOUT_DEFAULT]); impl<'tcx> LateLintPass<'tcx> for NewWithoutDefault { #[allow(clippy::too_many_lines)] fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) { - if let hir::ItemKind::Impl(hir::Impl { + if let hir::ItemKind::Impl { of_trait: None, items, .. - }) = item.kind + } = item.kind { for assoc_item in items { if let hir::AssocItemKind::Fn { has_self: false } = assoc_item.kind { diff --git a/src/tools/clippy/clippy_lints/src/non_copy_const.rs b/src/tools/clippy/clippy_lints/src/non_copy_const.rs index 3a9aa6ced03ba..6b0d198edcffa 100644 --- a/src/tools/clippy/clippy_lints/src/non_copy_const.rs +++ b/src/tools/clippy/clippy_lints/src/non_copy_const.rs @@ -7,7 +7,7 @@ use std::ptr; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::{ - BodyId, Expr, ExprKind, HirId, Impl, ImplItem, ImplItemKind, Item, ItemKind, Node, TraitItem, TraitItemKind, UnOp, + BodyId, Expr, ExprKind, HirId, ImplItem, ImplItemKind, Item, ItemKind, Node, TraitItem, TraitItemKind, UnOp, }; use rustc_infer::traits::specialization_graph; use rustc_lint::{LateContext, LateLintPass, Lint}; @@ -275,10 +275,10 @@ impl<'tcx> LateLintPass<'tcx> for NonCopyConst { let item = cx.tcx.hir().expect_item(item_hir_id); match &item.kind { - ItemKind::Impl(Impl { + ItemKind::Impl { of_trait: Some(of_trait_ref), .. - }) => { + } => { if_chain! { // Lint a trait impl item only when the definition is a generic type, // assuming a assoc const is not meant to be a interior mutable type. @@ -317,7 +317,7 @@ impl<'tcx> LateLintPass<'tcx> for NonCopyConst { } } }, - ItemKind::Impl(Impl { of_trait: None, .. }) => { + ItemKind::Impl { of_trait: None, .. } => { let ty = hir_ty_to_ty(cx.tcx, hir_ty); // Normalize assoc types originated from generic params. let normalized = cx.tcx.normalize_erasing_regions(cx.param_env, ty); diff --git a/src/tools/clippy/clippy_lints/src/option_if_let_else.rs b/src/tools/clippy/clippy_lints/src/option_if_let_else.rs index 7bdf975ffd446..681dbce97697e 100644 --- a/src/tools/clippy/clippy_lints/src/option_if_let_else.rs +++ b/src/tools/clippy/clippy_lints/src/option_if_let_else.rs @@ -66,7 +66,7 @@ declare_lint_pass!(OptionIfLetElse => [OPTION_IF_LET_ELSE]); /// Returns true iff the given expression is the result of calling `Result::ok` fn is_result_ok(cx: &LateContext<'_>, expr: &'_ Expr<'_>) -> bool { if let ExprKind::MethodCall(ref path, _, &[ref receiver], _) = &expr.kind { - path.ident.name.as_str() == "ok" + path.ident.name.to_ident_string() == "ok" && is_type_diagnostic_item(cx, &cx.typeck_results().expr_ty(&receiver), sym::result_type) } else { false @@ -109,30 +109,25 @@ fn extract_body_from_arm<'a>(arm: &'a Arm<'a>) -> Option<&'a Expr<'a>> { /// it in curly braces. Otherwise, we don't. fn should_wrap_in_braces(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { utils::get_enclosing_block(cx, expr.hir_id).map_or(false, |parent| { - let mut should_wrap = false; - if let Some(Expr { kind: ExprKind::Match( _, arms, - MatchSource::IfLetDesugar { + MatchSource::IfDesugar { + contains_else_clause: true, + } + | MatchSource::IfLetDesugar { contains_else_clause: true, }, ), .. }) = parent.expr { - should_wrap = expr.hir_id == arms[1].body.hir_id; - } else if let Some(Expr { - kind: ExprKind::If(_, _, Some(else_clause)), - .. - }) = parent.expr - { - should_wrap = expr.hir_id == else_clause.hir_id; + expr.hir_id == arms[1].body.hir_id + } else { + false } - - should_wrap }) } diff --git a/src/tools/clippy/clippy_lints/src/partialeq_ne_impl.rs b/src/tools/clippy/clippy_lints/src/partialeq_ne_impl.rs index ed314937ce8be..ceecc8dbc06fc 100644 --- a/src/tools/clippy/clippy_lints/src/partialeq_ne_impl.rs +++ b/src/tools/clippy/clippy_lints/src/partialeq_ne_impl.rs @@ -1,6 +1,6 @@ use crate::utils::{is_automatically_derived, span_lint_hir}; use if_chain::if_chain; -use rustc_hir::{Impl, Item, ItemKind}; +use rustc_hir::{Item, ItemKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::sym; @@ -34,7 +34,7 @@ declare_lint_pass!(PartialEqNeImpl => [PARTIALEQ_NE_IMPL]); impl<'tcx> LateLintPass<'tcx> for PartialEqNeImpl { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { if_chain! { - if let ItemKind::Impl(Impl { of_trait: Some(ref trait_ref), items: impl_items, .. }) = item.kind; + if let ItemKind::Impl{ of_trait: Some(ref trait_ref), items: impl_items, .. } = item.kind; if !is_automatically_derived(&*item.attrs); if let Some(eq_trait) = cx.tcx.lang_items().eq_trait(); if trait_ref.path.res.def_id() == eq_trait; diff --git a/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs b/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs index d96a9b025f089..6a17d654ac943 100644 --- a/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs +++ b/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs @@ -6,7 +6,7 @@ use rustc_ast::attr; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_hir::intravisit::FnKind; -use rustc_hir::{BindingAnnotation, Body, FnDecl, HirId, Impl, ItemKind, MutTy, Mutability, Node, PatKind}; +use rustc_hir::{BindingAnnotation, Body, FnDecl, HirId, ItemKind, MutTy, Mutability, Node, PatKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; use rustc_session::{declare_tool_lint, impl_lint_pass}; @@ -63,7 +63,7 @@ declare_clippy_lint! { /// /// **Why is this bad?** Arguments passed by value might result in an unnecessary /// shallow copy, taking up more space in the stack and requiring a call to - /// `memcpy`, which can be expensive. + /// `memcpy`, which which can be expensive. /// /// **Example:** /// @@ -246,7 +246,7 @@ impl<'tcx> LateLintPass<'tcx> for PassByRefOrValue { if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) { if matches!( item.kind, - ItemKind::Impl(Impl { of_trait: Some(_), .. }) | ItemKind::Trait(..) + ItemKind::Impl { of_trait: Some(_), .. } | ItemKind::Trait(..) ) { return; } diff --git a/src/tools/clippy/clippy_lints/src/ptr.rs b/src/tools/clippy/clippy_lints/src/ptr.rs index c6329a1381c90..c494a71363131 100644 --- a/src/tools/clippy/clippy_lints/src/ptr.rs +++ b/src/tools/clippy/clippy_lints/src/ptr.rs @@ -8,8 +8,8 @@ use crate::utils::{ use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir::{ - BinOpKind, BodyId, Expr, ExprKind, FnDecl, FnRetTy, GenericArg, HirId, Impl, ImplItem, ImplItemKind, Item, - ItemKind, Lifetime, MutTy, Mutability, Node, PathSegment, QPath, TraitFn, TraitItem, TraitItemKind, Ty, TyKind, + BinOpKind, BodyId, Expr, ExprKind, FnDecl, FnRetTy, GenericArg, HirId, ImplItem, ImplItemKind, Item, ItemKind, + Lifetime, MutTy, Mutability, Node, PathSegment, QPath, TraitFn, TraitItem, TraitItemKind, Ty, TyKind, }; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; @@ -132,7 +132,7 @@ impl<'tcx> LateLintPass<'tcx> for Ptr { if let ImplItemKind::Fn(ref sig, body_id) = item.kind { let parent_item = cx.tcx.hir().get_parent_item(item.hir_id); if let Some(Node::Item(it)) = cx.tcx.hir().find(parent_item) { - if let ItemKind::Impl(Impl { of_trait: Some(_), .. }) = it.kind { + if let ItemKind::Impl { of_trait: Some(_), .. } = it.kind { return; // ignore trait impls } } diff --git a/src/tools/clippy/clippy_lints/src/question_mark.rs b/src/tools/clippy/clippy_lints/src/question_mark.rs index 6c480d48c7561..b91233ac58280 100644 --- a/src/tools/clippy/clippy_lints/src/question_mark.rs +++ b/src/tools/clippy/clippy_lints/src/question_mark.rs @@ -8,7 +8,7 @@ use rustc_span::sym; use crate::utils::sugg::Sugg; use crate::utils::{ - eq_expr_value, is_type_diagnostic_item, match_def_path, match_qpath, paths, snippet_with_applicability, + eq_expr_value, higher, is_type_diagnostic_item, match_def_path, match_qpath, paths, snippet_with_applicability, span_lint_and_sugg, }; @@ -50,7 +50,7 @@ impl QuestionMark { /// If it matches, it will suggest to use the question mark operator instead fn check_is_none_and_early_return_none(cx: &LateContext<'_>, expr: &Expr<'_>) { if_chain! { - if let ExprKind::If(if_expr, body, else_) = &expr.kind; + if let Some((if_expr, body, else_)) = higher::if_block(&expr); if let ExprKind::MethodCall(segment, _, args, _) = &if_expr.kind; if segment.ident.name == sym!(is_none); if Self::expression_returns_none(cx, body); diff --git a/src/tools/clippy/clippy_lints/src/ref_option_ref.rs b/src/tools/clippy/clippy_lints/src/ref_option_ref.rs index 8cd6692ce03a0..803ebada54b79 100644 --- a/src/tools/clippy/clippy_lints/src/ref_option_ref.rs +++ b/src/tools/clippy/clippy_lints/src/ref_option_ref.rs @@ -13,7 +13,7 @@ declare_clippy_lint! { /// **Why is this bad?** Since `&` is Copy, it's useless to have a /// reference on `Option<&T>`. /// - /// **Known problems:** It may be irrelevant to use this lint on + /// **Known problems:** It may be irrevelent to use this lint on /// public API code as it will make a breaking change to apply it. /// /// **Example:** diff --git a/src/tools/clippy/clippy_lints/src/returns.rs b/src/tools/clippy/clippy_lints/src/returns.rs index 63548d8fdb438..7f4913a02cbd3 100644 --- a/src/tools/clippy/clippy_lints/src/returns.rs +++ b/src/tools/clippy/clippy_lints/src/returns.rs @@ -184,14 +184,6 @@ fn check_final_expr<'tcx>( ExprKind::Block(ref block, _) => { check_block_return(cx, block); }, - ExprKind::If(_, then, else_clause_opt) => { - if let ExprKind::Block(ref ifblock, _) = then.kind { - check_block_return(cx, ifblock); - } - if let Some(else_clause) = else_clause_opt { - check_final_expr(cx, else_clause, None, RetReplacement::Empty); - } - }, // a match expr, check all arms // an if/if let expr, check both exprs // note, if without else is going to be a type checking error anyways @@ -202,7 +194,10 @@ fn check_final_expr<'tcx>( check_final_expr(cx, &arm.body, Some(arm.body.span), RetReplacement::Block); } }, - MatchSource::IfLetDesugar { + MatchSource::IfDesugar { + contains_else_clause: true, + } + | MatchSource::IfLetDesugar { contains_else_clause: true, } => { if let ExprKind::Block(ref ifblock, _) = arms[0].body.kind { @@ -217,9 +212,6 @@ fn check_final_expr<'tcx>( } fn emit_return_lint(cx: &LateContext<'_>, ret_span: Span, inner_span: Option, replacement: RetReplacement) { - if ret_span.from_expansion() { - return; - } match inner_span { Some(inner_span) => { if in_external_macro(cx.tcx.sess, inner_span) || inner_span.from_expansion() { diff --git a/src/tools/clippy/clippy_lints/src/serde_api.rs b/src/tools/clippy/clippy_lints/src/serde_api.rs index 44e739725c820..339a7cf3bf5d2 100644 --- a/src/tools/clippy/clippy_lints/src/serde_api.rs +++ b/src/tools/clippy/clippy_lints/src/serde_api.rs @@ -1,5 +1,5 @@ use crate::utils::{get_trait_def_id, paths, span_lint}; -use rustc_hir::{Impl, Item, ItemKind}; +use rustc_hir::{Item, ItemKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; @@ -22,11 +22,11 @@ declare_lint_pass!(SerdeAPI => [SERDE_API_MISUSE]); impl<'tcx> LateLintPass<'tcx> for SerdeAPI { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { - if let ItemKind::Impl(Impl { + if let ItemKind::Impl { of_trait: Some(ref trait_ref), items, .. - }) = item.kind + } = item.kind { let did = trait_ref.path.res.def_id(); if let Some(visit_did) = get_trait_def_id(cx, &paths::SERDE_DE_VISITOR) { diff --git a/src/tools/clippy/clippy_lints/src/shadow.rs b/src/tools/clippy/clippy_lints/src/shadow.rs index 24da056770c9d..f839659267825 100644 --- a/src/tools/clippy/clippy_lints/src/shadow.rs +++ b/src/tools/clippy/clippy_lints/src/shadow.rs @@ -333,13 +333,6 @@ fn check_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, bindings: &mut check_expr(cx, e, bindings) } }, - ExprKind::If(ref cond, ref then, ref otherwise) => { - check_expr(cx, cond, bindings); - check_expr(cx, &**then, bindings); - if let Some(ref o) = *otherwise { - check_expr(cx, o, bindings); - } - }, ExprKind::Match(ref init, arms, _) => { check_expr(cx, init, bindings); let len = bindings.len(); @@ -396,5 +389,5 @@ fn is_self_shadow(name: Symbol, expr: &Expr<'_>) -> bool { } fn path_eq_name(name: Symbol, path: &Path<'_>) -> bool { - !path.is_global() && path.segments.len() == 1 && path.segments[0].ident.name == name + !path.is_global() && path.segments.len() == 1 && path.segments[0].ident.as_str() == name.as_str() } diff --git a/src/tools/clippy/clippy_lints/src/swap.rs b/src/tools/clippy/clippy_lints/src/swap.rs index 699fd51ccc194..386987eb181ea 100644 --- a/src/tools/clippy/clippy_lints/src/swap.rs +++ b/src/tools/clippy/clippy_lints/src/swap.rs @@ -91,7 +91,7 @@ fn check_manual_swap(cx: &LateContext<'_>, block: &Block<'_>) { if let ExprKind::Path(QPath::Resolved(None, ref rhs2)) = rhs2.kind; if rhs2.segments.len() == 1; - if ident.name == rhs2.segments[0].ident.name; + if ident.as_str() == rhs2.segments[0].ident.as_str(); if eq_expr_value(cx, tmp_init, lhs1); if eq_expr_value(cx, rhs1, lhs2); then { diff --git a/src/tools/clippy/clippy_lints/src/to_string_in_display.rs b/src/tools/clippy/clippy_lints/src/to_string_in_display.rs index c53727ba16004..006d7a3a12d9a 100644 --- a/src/tools/clippy/clippy_lints/src/to_string_in_display.rs +++ b/src/tools/clippy/clippy_lints/src/to_string_in_display.rs @@ -1,7 +1,7 @@ use crate::utils::{match_def_path, match_trait_method, paths, qpath_res, span_lint}; use if_chain::if_chain; use rustc_hir::def::Res; -use rustc_hir::{Expr, ExprKind, HirId, Impl, ImplItem, ImplItemKind, Item, ItemKind}; +use rustc_hir::{Expr, ExprKind, HirId, ImplItem, ImplItemKind, Item, ItemKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_tool_lint, impl_lint_pass}; @@ -111,7 +111,7 @@ impl LateLintPass<'_> for ToStringInDisplay { fn is_display_impl(cx: &LateContext<'_>, item: &Item<'_>) -> bool { if_chain! { - if let ItemKind::Impl(Impl { of_trait: Some(trait_ref), .. }) = &item.kind; + if let ItemKind::Impl { of_trait: Some(trait_ref), .. } = &item.kind; if let Some(did) = trait_ref.trait_def_id(); then { match_def_path(cx, did, &paths::DISPLAY_TRAIT) diff --git a/src/tools/clippy/clippy_lints/src/types.rs b/src/tools/clippy/clippy_lints/src/types.rs index 3b5a83d2a0bec..fd74783335d57 100644 --- a/src/tools/clippy/clippy_lints/src/types.rs +++ b/src/tools/clippy/clippy_lints/src/types.rs @@ -8,6 +8,7 @@ use if_chain::if_chain; use rustc_ast::{FloatTy, IntTy, LitFloatType, LitIntType, LitKind, UintTy}; use rustc_errors::{Applicability, DiagnosticBuilder}; use rustc_hir as hir; +use rustc_hir::def::Res; use rustc_hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor}; use rustc_hir::{ BinOpKind, Block, Body, Expr, ExprKind, FnDecl, FnRetTy, FnSig, GenericArg, GenericBounds, GenericParamKind, HirId, @@ -18,8 +19,7 @@ use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_middle::hir::map::Map; use rustc_middle::lint::in_external_macro; use rustc_middle::ty::TypeFoldable; -use rustc_middle::ty::{self, InferTy, Ty, TyCtxt, TyS, TypeAndMut, TypeckResults}; -use rustc_semver::RustcVersion; +use rustc_middle::ty::{self, InferTy, Ty, TyCtxt, TyS, TypeckResults}; use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass}; use rustc_span::hygiene::{ExpnKind, MacroKind}; use rustc_span::source_map::Span; @@ -30,13 +30,11 @@ use rustc_typeck::hir_ty_to_ty; use crate::consts::{constant, Constant}; use crate::utils::paths; -use crate::utils::sugg::Sugg; use crate::utils::{ - clip, comparisons, differing_macro_contexts, higher, in_constant, indent_of, int_bits, is_hir_ty_cfg_dependant, - is_type_diagnostic_item, last_path_segment, match_def_path, match_path, meets_msrv, method_chain_args, - multispan_sugg, numeric_literal::NumericLiteral, qpath_res, reindent_multiline, sext, snippet, snippet_opt, - snippet_with_applicability, snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_sugg, - span_lint_and_then, unsext, + clip, comparisons, differing_macro_contexts, higher, in_constant, indent_of, int_bits, is_type_diagnostic_item, + last_path_segment, match_def_path, match_path, method_chain_args, multispan_sugg, numeric_literal::NumericLiteral, + qpath_res, reindent_multiline, sext, snippet, snippet_opt, snippet_with_applicability, snippet_with_macro_callsite, + span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, unsext, }; declare_clippy_lint! { @@ -75,7 +73,7 @@ declare_clippy_lint! { /// **Why is this bad?** `Vec` already keeps its contents in a separate area on /// the heap. So if you `Box` its contents, you just add another level of indirection. /// - /// **Known problems:** Vec> makes sense if T is a large type (see [#3530](https://github.com/rust-lang/rust-clippy/issues/3530), + /// **Known problems:** Vec> makes sense if T is a large type (see #3530, /// 1st comment). /// /// **Example:** @@ -260,7 +258,7 @@ impl<'tcx> LateLintPass<'tcx> for Types { fn check_fn(&mut self, cx: &LateContext<'_>, _: FnKind<'_>, decl: &FnDecl<'_>, _: &Body<'_>, _: Span, id: HirId) { // Skip trait implementations; see issue #605. if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_item(id)) { - if let ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = item.kind { + if let ItemKind::Impl { of_trait: Some(_), .. } = item.kind { return; } } @@ -1281,8 +1279,8 @@ declare_clippy_lint! { } declare_clippy_lint! { - /// **What it does:** Checks for casts, using `as` or `pointer::cast`, - /// from a less-strictly-aligned pointer to a more-strictly-aligned pointer + /// **What it does:** Checks for casts from a less-strictly-aligned pointer to a + /// more-strictly-aligned pointer /// /// **Why is this bad?** Dereferencing the resulting pointer may be undefined /// behavior. @@ -1295,9 +1293,6 @@ declare_clippy_lint! { /// ```rust /// let _ = (&1u8 as *const u8) as *const u16; /// let _ = (&mut 1u8 as *mut u8) as *mut u16; - /// - /// (&1u8 as *const u8).cast::(); - /// (&mut 1u8 as *mut u8).cast::(); /// ``` pub CAST_PTR_ALIGNMENT, pedantic, @@ -1639,8 +1634,12 @@ impl<'tcx> LateLintPass<'tcx> for Casts { return; } if let ExprKind::Cast(ref ex, cast_to) = expr.kind { - if is_hir_ty_cfg_dependant(cx, cast_to) { - return; + if let TyKind::Path(QPath::Resolved(_, path)) = cast_to.kind { + if let Res::Def(_, def_id) = path.res { + if cx.tcx.has_attr(def_id, sym::cfg) || cx.tcx.has_attr(def_id, sym::cfg_attr) { + return; + } + } } let (cast_from, cast_to) = (cx.typeck_results().expr_ty(ex), cx.typeck_results().expr_ty(expr)); lint_fn_to_numeric_cast(cx, expr, ex, cast_from, cast_to); @@ -1690,19 +1689,6 @@ impl<'tcx> LateLintPass<'tcx> for Casts { } lint_cast_ptr_alignment(cx, expr, cast_from, cast_to); - } else if let ExprKind::MethodCall(method_path, _, args, _) = expr.kind { - if_chain! { - if method_path.ident.name == sym!(cast); - if let Some(generic_args) = method_path.args; - if let [GenericArg::Type(cast_to)] = generic_args.args; - // There probably is no obvious reason to do this, just to be consistent with `as` cases. - if !is_hir_ty_cfg_dependant(cx, cast_to); - then { - let (cast_from, cast_to) = - (cx.typeck_results().expr_ty(&args[0]), cx.typeck_results().expr_ty(expr)); - lint_cast_ptr_alignment(cx, expr, cast_from, cast_to); - } - } } } } @@ -2572,16 +2558,21 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitHasher { } match item.kind { - ItemKind::Impl(ref impl_) => { + ItemKind::Impl { + ref generics, + self_ty: ref ty, + ref items, + .. + } => { let mut vis = ImplicitHasherTypeVisitor::new(cx); - vis.visit_ty(impl_.self_ty); + vis.visit_ty(ty); for target in &vis.found { if differing_macro_contexts(item.span, target.span()) { return; } - let generics_suggestion_span = impl_.generics.span.substitute_dummy({ + let generics_suggestion_span = generics.span.substitute_dummy({ let pos = snippet_opt(cx, item.span.until(target.span())) .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4))); if let Some(pos) = pos { @@ -2592,7 +2583,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitHasher { }); let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target); - for item in impl_.items.iter().map(|item| cx.tcx.hir().impl_item(item.id)) { + for item in items.iter().map(|item| cx.tcx.hir().impl_item(item.id)) { ctr_vis.visit_impl_item(item); } @@ -2605,7 +2596,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitHasher { target.type_name() ), move |diag| { - suggestion(cx, diag, impl_.generics.span, generics_suggestion_span, target, ctr_vis); + suggestion(cx, diag, generics.span, generics_suggestion_span, target, ctr_vis); }, ); } @@ -2887,93 +2878,3 @@ impl<'tcx> LateLintPass<'tcx> for RefToMut { } } } - -const PTR_AS_PTR_MSRV: RustcVersion = RustcVersion::new(1, 38, 0); - -declare_clippy_lint! { - /// **What it does:** - /// Checks for `as` casts between raw pointers without changing its mutability, - /// namely `*const T` to `*const U` and `*mut T` to `*mut U`. - /// - /// **Why is this bad?** - /// Though `as` casts between raw pointers is not terrible, `pointer::cast` is safer because - /// it cannot accidentally change the pointer's mutability nor cast the pointer to other types like `usize`. - /// - /// **Known problems:** None. - /// - /// **Example:** - /// - /// ```rust - /// let ptr: *const u32 = &42_u32; - /// let mut_ptr: *mut u32 = &mut 42_u32; - /// let _ = ptr as *const i32; - /// let _ = mut_ptr as *mut i32; - /// ``` - /// Use instead: - /// ```rust - /// let ptr: *const u32 = &42_u32; - /// let mut_ptr: *mut u32 = &mut 42_u32; - /// let _ = ptr.cast::(); - /// let _ = mut_ptr.cast::(); - /// ``` - pub PTR_AS_PTR, - pedantic, - "casting using `as` from and to raw pointers that doesn't change its mutability, where `pointer::cast` could take the place of `as`" -} - -pub struct PtrAsPtr { - msrv: Option, -} - -impl PtrAsPtr { - #[must_use] - pub fn new(msrv: Option) -> Self { - Self { msrv } - } -} - -impl_lint_pass!(PtrAsPtr => [PTR_AS_PTR]); - -impl<'tcx> LateLintPass<'tcx> for PtrAsPtr { - fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - if !meets_msrv(self.msrv.as_ref(), &PTR_AS_PTR_MSRV) { - return; - } - - if expr.span.from_expansion() { - return; - } - - if_chain! { - if let ExprKind::Cast(cast_expr, cast_to_hir_ty) = expr.kind; - let (cast_from, cast_to) = (cx.typeck_results().expr_ty(cast_expr), cx.typeck_results().expr_ty(expr)); - if let ty::RawPtr(TypeAndMut { mutbl: from_mutbl, .. }) = cast_from.kind(); - if let ty::RawPtr(TypeAndMut { ty: to_pointee_ty, mutbl: to_mutbl }) = cast_to.kind(); - if matches!((from_mutbl, to_mutbl), - (Mutability::Not, Mutability::Not) | (Mutability::Mut, Mutability::Mut)); - // The `U` in `pointer::cast` have to be `Sized` - // as explained here: https://github.com/rust-lang/rust/issues/60602. - if to_pointee_ty.is_sized(cx.tcx.at(expr.span), cx.param_env); - then { - let mut applicability = Applicability::MachineApplicable; - let cast_expr_sugg = Sugg::hir_with_applicability(cx, cast_expr, "_", &mut applicability); - let turbofish = match &cast_to_hir_ty.kind { - TyKind::Infer => Cow::Borrowed(""), - TyKind::Ptr(mut_ty) if matches!(mut_ty.ty.kind, TyKind::Infer) => Cow::Borrowed(""), - _ => Cow::Owned(format!("::<{}>", to_pointee_ty)), - }; - span_lint_and_sugg( - cx, - PTR_AS_PTR, - expr.span, - "`as` casting between raw pointers without changing its mutability", - "try `pointer::cast`, a safer alternative", - format!("{}.cast{}()", cast_expr_sugg.maybe_par(), turbofish), - applicability, - ); - } - } - } - - extract_msrv_attr!(LateContext); -} diff --git a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs index c6ae8b9b59837..2501635e7ef66 100644 --- a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs +++ b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs @@ -4,7 +4,7 @@ use rustc_hir::def_id::DefId; use rustc_hir::{Expr, ExprKind, StmtKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; -use rustc_middle::ty::{GenericPredicates, PredicateKind, ProjectionPredicate, TraitPredicate}; +use rustc_middle::ty::{GenericPredicates, PredicateAtom, ProjectionPredicate, TraitPredicate}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::{BytePos, Span}; @@ -42,7 +42,7 @@ fn get_trait_predicates_for_trait_id<'tcx>( let mut preds = Vec::new(); for (pred, _) in generics.predicates { if_chain! { - if let PredicateKind::Trait(poly_trait_pred, _) = pred.kind().skip_binder(); + if let PredicateAtom::Trait(poly_trait_pred, _) = pred.skip_binders(); let trait_pred = cx.tcx.erase_late_bound_regions(ty::Binder::bind(poly_trait_pred)); if let Some(trait_def_id) = trait_id; if trait_def_id == trait_pred.trait_ref.def_id; @@ -60,7 +60,7 @@ fn get_projection_pred<'tcx>( pred: TraitPredicate<'tcx>, ) -> Option> { generics.predicates.iter().find_map(|(proj_pred, _)| { - if let ty::PredicateKind::Projection(proj_pred) = proj_pred.kind().skip_binder() { + if let ty::PredicateAtom::Projection(proj_pred) = proj_pred.skip_binders() { let projection_pred = cx.tcx.erase_late_bound_regions(ty::Binder::bind(proj_pred)); if projection_pred.projection_ty.substs == pred.trait_ref.substs { return Some(projection_pred); diff --git a/src/tools/clippy/clippy_lints/src/unnecessary_sort_by.rs b/src/tools/clippy/clippy_lints/src/unnecessary_sort_by.rs index 9b45d38afd42f..0bccfc156788a 100644 --- a/src/tools/clippy/clippy_lints/src/unnecessary_sort_by.rs +++ b/src/tools/clippy/clippy_lints/src/unnecessary_sort_by.rs @@ -183,7 +183,7 @@ fn detect_lint(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option { Param { pat: Pat { kind: PatKind::Binding(_, _, right_ident, _), .. }, .. } ] = &closure_body.params; if let ExprKind::MethodCall(method_path, _, [ref left_expr, ref right_expr], _) = &closure_body.value.kind; - if method_path.ident.name == sym::cmp; + if method_path.ident.name.to_ident_string() == "cmp"; then { let (closure_body, closure_arg, reverse) = if mirrored_exprs( &cx, diff --git a/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs b/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs index 8ac5dd696b762..5b9a80f92db69 100644 --- a/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs +++ b/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs @@ -5,7 +5,7 @@ use crate::utils::{ use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir::intravisit::FnKind; -use rustc_hir::{Body, ExprKind, FnDecl, HirId, Impl, ItemKind, Node}; +use rustc_hir::{Body, ExprKind, FnDecl, HirId, ItemKind, Node}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::subst::GenericArgKind; use rustc_session::{declare_lint_pass, declare_tool_lint}; @@ -77,7 +77,7 @@ impl<'tcx> LateLintPass<'tcx> for UnnecessaryWraps { if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) { if matches!( item.kind, - ItemKind::Impl(Impl { of_trait: Some(_), .. }) | ItemKind::Trait(..) + ItemKind::Impl { of_trait: Some(_), .. } | ItemKind::Trait(..) ) { return; } diff --git a/src/tools/clippy/clippy_lints/src/unused_self.rs b/src/tools/clippy/clippy_lints/src/unused_self.rs index 5349c4f7eb8a7..da7517125c13b 100644 --- a/src/tools/clippy/clippy_lints/src/unused_self.rs +++ b/src/tools/clippy/clippy_lints/src/unused_self.rs @@ -1,7 +1,7 @@ use if_chain::if_chain; use rustc_hir::def::Res; use rustc_hir::intravisit::{walk_path, NestedVisitorMap, Visitor}; -use rustc_hir::{HirId, Impl, ImplItem, ImplItemKind, ItemKind, Path}; +use rustc_hir::{HirId, ImplItem, ImplItemKind, ItemKind, Path}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::map::Map; use rustc_session::{declare_lint_pass, declare_tool_lint}; @@ -49,7 +49,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedSelf { let def_id = cx.tcx.hir().local_def_id(impl_item.hir_id); let assoc_item = cx.tcx.associated_item(def_id); if_chain! { - if let ItemKind::Impl(Impl { of_trait: None, .. }) = parent_item.kind; + if let ItemKind::Impl { of_trait: None, .. } = parent_item.kind; if assoc_item.fn_has_self_parameter; if let ImplItemKind::Fn(.., body_id) = &impl_item.kind; let body = cx.tcx.hir().body(*body_id); diff --git a/src/tools/clippy/clippy_lints/src/unwrap.rs b/src/tools/clippy/clippy_lints/src/unwrap.rs index b82909eaea604..f4a77e54dd149 100644 --- a/src/tools/clippy/clippy_lints/src/unwrap.rs +++ b/src/tools/clippy/clippy_lints/src/unwrap.rs @@ -1,5 +1,6 @@ use crate::utils::{ - differing_macro_contexts, is_type_diagnostic_item, span_lint_and_then, usage::is_potentially_mutated, + differing_macro_contexts, higher::if_block, is_type_diagnostic_item, span_lint_and_then, + usage::is_potentially_mutated, }; use if_chain::if_chain; use rustc_hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor}; @@ -157,7 +158,7 @@ impl<'a, 'tcx> Visitor<'tcx> for UnwrappableVariablesVisitor<'a, 'tcx> { if in_external_macro(self.cx.tcx.sess, expr.span) { return; } - if let ExprKind::If(cond, then, els) = &expr.kind { + if let Some((cond, then, els)) = if_block(&expr) { walk_expr(self, cond); self.visit_branch(cond, then, false); if let Some(els) = els { diff --git a/src/tools/clippy/clippy_lints/src/use_self.rs b/src/tools/clippy/clippy_lints/src/use_self.rs index 72d1ca7392913..3b23f885e08d9 100644 --- a/src/tools/clippy/clippy_lints/src/use_self.rs +++ b/src/tools/clippy/clippy_lints/src/use_self.rs @@ -28,8 +28,8 @@ declare_clippy_lint! { /// feels inconsistent. /// /// **Known problems:** - /// - False positive when using associated types ([#2843](https://github.com/rust-lang/rust-clippy/issues/2843)) - /// - False positives in some situations when using generics ([#3410](https://github.com/rust-lang/rust-clippy/issues/3410)) + /// - False positive when using associated types (#2843) + /// - False positives in some situations when using generics (#3410) /// /// **Example:** /// ```rust @@ -181,8 +181,8 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { return; } if_chain! { - if let ItemKind::Impl(impl_) = &item.kind; - if let TyKind::Path(QPath::Resolved(_, ref item_path)) = impl_.self_ty.kind; + if let ItemKind::Impl{ self_ty: ref item_type, items: refs, .. } = item.kind; + if let TyKind::Path(QPath::Resolved(_, ref item_path)) = item_type.kind; then { let parameters = &item_path.segments.last().expect(SEGMENTS_MSG).args; let should_check = parameters.as_ref().map_or( @@ -200,7 +200,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { let impl_trait_ref = cx.tcx.impl_trait_ref(impl_def_id); if let Some(impl_trait_ref) = impl_trait_ref { - for impl_item_ref in impl_.items { + for impl_item_ref in refs { let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id); if let ImplItemKind::Fn(FnSig{ decl: impl_decl, .. }, impl_body_id) = &impl_item.kind { @@ -213,7 +213,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { } } } else { - for impl_item_ref in impl_.items { + for impl_item_ref in refs { let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id); visitor.visit_impl_item(impl_item); } diff --git a/src/tools/clippy/clippy_lints/src/useless_conversion.rs b/src/tools/clippy/clippy_lints/src/useless_conversion.rs index c533485398605..efa9c3fab4ab8 100644 --- a/src/tools/clippy/clippy_lints/src/useless_conversion.rs +++ b/src/tools/clippy/clippy_lints/src/useless_conversion.rs @@ -80,10 +80,10 @@ impl<'tcx> LateLintPass<'tcx> for UselessConversion { ); } } - if match_trait_method(cx, e, &paths::INTO_ITERATOR) && name.ident.name == sym::into_iter { + if match_trait_method(cx, e, &paths::INTO_ITERATOR) && &*name.ident.as_str() == "into_iter" { if let Some(parent_expr) = get_parent_expr(cx, e) { if let ExprKind::MethodCall(ref parent_name, ..) = parent_expr.kind { - if parent_name.ident.name != sym::into_iter { + if &*parent_name.ident.as_str() != "into_iter" { return; } } diff --git a/src/tools/clippy/clippy_lints/src/utils/attrs.rs b/src/tools/clippy/clippy_lints/src/utils/attrs.rs index 8d28421d70d70..24052a243af82 100644 --- a/src/tools/clippy/clippy_lints/src/utils/attrs.rs +++ b/src/tools/clippy/clippy_lints/src/utils/attrs.rs @@ -1,7 +1,6 @@ use rustc_ast::ast; use rustc_errors::Applicability; use rustc_session::Session; -use rustc_span::sym; use std::str::FromStr; /// Deprecation status of attributes known by Clippy. @@ -65,11 +64,11 @@ pub fn get_attr<'a>( return false; }; let attr_segments = &attr.path.segments; - if attr_segments.len() == 2 && attr_segments[0].ident.name == sym::clippy { + if attr_segments.len() == 2 && attr_segments[0].ident.to_string() == "clippy" { BUILTIN_ATTRIBUTES .iter() - .find_map(|&(builtin_name, ref deprecation_status)| { - if attr_segments[1].ident.name.as_str() == builtin_name { + .find_map(|(builtin_name, deprecation_status)| { + if *builtin_name == attr_segments[1].ident.to_string() { Some(deprecation_status) } else { None @@ -100,7 +99,7 @@ pub fn get_attr<'a>( }, DeprecationStatus::None => { diag.cancel(); - attr_segments[1].ident.name.as_str() == name + attr_segments[1].ident.to_string() == name }, } }, diff --git a/src/tools/clippy/clippy_lints/src/utils/author.rs b/src/tools/clippy/clippy_lints/src/utils/author.rs index 43afa65de3e55..4249dbb4e6519 100644 --- a/src/tools/clippy/clippy_lints/src/utils/author.rs +++ b/src/tools/clippy/clippy_lints/src/utils/author.rs @@ -1,7 +1,7 @@ //! A group of attributes that can be attached to Rust code in order //! to generate a clippy lint detecting said code automatically. -use crate::utils::get_attr; +use crate::utils::{get_attr, higher}; use rustc_ast::ast::{Attribute, LitFloatType, LitKind}; use rustc_ast::walk_list; use rustc_data_structures::fx::FxHashMap; @@ -201,6 +201,32 @@ impl<'tcx> Visitor<'tcx> for PrintVisitor { #[allow(clippy::too_many_lines)] fn visit_expr(&mut self, expr: &Expr<'_>) { + // handle if desugarings + // TODO add more desugarings here + if let Some((cond, then, opt_else)) = higher::if_block(&expr) { + let cond_pat = self.next("cond"); + let then_pat = self.next("then"); + if let Some(else_) = opt_else { + let else_pat = self.next("else_"); + println!( + " if let Some((ref {}, ref {}, Some({}))) = higher::if_block(&{});", + cond_pat, then_pat, else_pat, self.current + ); + self.current = else_pat; + self.visit_expr(else_); + } else { + println!( + " if let Some((ref {}, ref {}, None)) = higher::if_block(&{});", + cond_pat, then_pat, self.current + ); + } + self.current = cond_pat; + self.visit_expr(cond); + self.current = then_pat; + self.visit_expr(then); + return; + } + print!(" if let ExprKind::"); let current = format!("{}.kind", self.current); match expr.kind { @@ -325,25 +351,6 @@ impl<'tcx> Visitor<'tcx> for PrintVisitor { self.current = body_pat; self.visit_block(body); }, - ExprKind::If(ref cond, ref then, ref opt_else) => { - let cond_pat = self.next("cond"); - let then_pat = self.next("then"); - if let Some(ref else_) = *opt_else { - let else_pat = self.next("else_"); - println!( - "If(ref {}, ref {}, Some(ref {})) = {};", - cond_pat, then_pat, else_pat, current - ); - self.current = else_pat; - self.visit_expr(else_); - } else { - println!("If(ref {}, ref {}, None) = {};", cond_pat, then_pat, current); - } - self.current = cond_pat; - self.visit_expr(cond); - self.current = then_pat; - self.visit_expr(then); - }, ExprKind::Match(ref expr, ref arms, desugaring) => { let des = desugaring_name(desugaring); let expr_pat = self.next("expr"); @@ -736,6 +743,10 @@ fn desugaring_name(des: hir::MatchSource) -> String { contains_else_clause ), hir::MatchSource::IfLetGuardDesugar => "MatchSource::IfLetGuardDesugar".to_string(), + hir::MatchSource::IfDesugar { contains_else_clause } => format!( + "MatchSource::IfDesugar {{ contains_else_clause: {} }}", + contains_else_clause + ), hir::MatchSource::AwaitDesugar => "MatchSource::AwaitDesugar".to_string(), } } diff --git a/src/tools/clippy/clippy_lints/src/utils/eager_or_lazy.rs b/src/tools/clippy/clippy_lints/src/utils/eager_or_lazy.rs index 2f157c5030f44..8fe5ddee1ca8d 100644 --- a/src/tools/clippy/clippy_lints/src/utils/eager_or_lazy.rs +++ b/src/tools/clippy/clippy_lints/src/utils/eager_or_lazy.rs @@ -62,7 +62,6 @@ fn identify_some_pure_patterns(expr: &Expr<'_>) -> bool { | ExprKind::Type(..) | ExprKind::DropTemps(..) | ExprKind::Loop(..) - | ExprKind::If(..) | ExprKind::Match(..) | ExprKind::Closure(..) | ExprKind::Block(..) diff --git a/src/tools/clippy/clippy_lints/src/utils/higher.rs b/src/tools/clippy/clippy_lints/src/utils/higher.rs index 9b3585865da32..01ffac5b5599d 100644 --- a/src/tools/clippy/clippy_lints/src/utils/higher.rs +++ b/src/tools/clippy/clippy_lints/src/utils/higher.rs @@ -170,6 +170,33 @@ pub fn while_loop<'tcx>(expr: &'tcx hir::Expr<'tcx>) -> Option<(&'tcx hir::Expr< None } +/// Recover the essential nodes of a desugared if block +/// `if cond { then } else { els }` becomes `(cond, then, Some(els))` +pub fn if_block<'tcx>( + expr: &'tcx hir::Expr<'tcx>, +) -> Option<( + &'tcx hir::Expr<'tcx>, + &'tcx hir::Expr<'tcx>, + Option<&'tcx hir::Expr<'tcx>>, +)> { + if let hir::ExprKind::Match(ref cond, ref arms, hir::MatchSource::IfDesugar { contains_else_clause }) = expr.kind { + let cond = if let hir::ExprKind::DropTemps(ref cond) = cond.kind { + cond + } else { + panic!("If block desugar must contain DropTemps"); + }; + let then = &arms[0].body; + let els = if contains_else_clause { + Some(&*arms[1].body) + } else { + None + }; + Some((cond, then, els)) + } else { + None + } +} + /// Represent the pre-expansion arguments of a `vec!` invocation. pub enum VecArgs<'a> { /// `vec![elem; len]` @@ -240,11 +267,12 @@ pub fn extract_assert_macro_args<'tcx>(e: &'tcx Expr<'tcx>) -> Option SpanlessEq<'a, 'tcx> { lb == rb && l_mut == r_mut && self.eq_expr(le, re) }, (&ExprKind::Continue(li), &ExprKind::Continue(ri)) => { - both(&li.label, &ri.label, |l, r| l.ident.name == r.ident.name) + both(&li.label, &ri.label, |l, r| l.ident.as_str() == r.ident.as_str()) }, (&ExprKind::Assign(ref ll, ref lr, _), &ExprKind::Assign(ref rl, ref rr, _)) => { self.allow_side_effects && self.eq_expr(ll, rl) && self.eq_expr(lr, rr) @@ -102,7 +102,7 @@ impl<'a, 'tcx> SpanlessEq<'a, 'tcx> { }) }, (&ExprKind::Break(li, ref le), &ExprKind::Break(ri, ref re)) => { - both(&li.label, &ri.label, |l, r| l.ident.name == r.ident.name) + both(&li.label, &ri.label, |l, r| l.ident.as_str() == r.ident.as_str()) && both(le, re, |l, r| self.eq_expr(l, r)) }, (&ExprKind::Box(ref l), &ExprKind::Box(ref r)) => self.eq_expr(l, r), @@ -119,12 +119,9 @@ impl<'a, 'tcx> SpanlessEq<'a, 'tcx> { (&ExprKind::Index(ref la, ref li), &ExprKind::Index(ref ra, ref ri)) => { self.eq_expr(la, ra) && self.eq_expr(li, ri) }, - (&ExprKind::If(ref lc, ref lt, ref le), &ExprKind::If(ref rc, ref rt, ref re)) => { - self.eq_expr(lc, rc) && self.eq_expr(&**lt, &**rt) && both(le, re, |l, r| self.eq_expr(l, r)) - }, (&ExprKind::Lit(ref l), &ExprKind::Lit(ref r)) => l.node == r.node, (&ExprKind::Loop(ref lb, ref ll, ref lls), &ExprKind::Loop(ref rb, ref rl, ref rls)) => { - lls == rls && self.eq_block(lb, rb) && both(ll, rl, |l, r| l.ident.name == r.ident.name) + lls == rls && self.eq_block(lb, rb) && both(ll, rl, |l, r| l.ident.as_str() == r.ident.as_str()) }, (&ExprKind::Match(ref le, ref la, ref ls), &ExprKind::Match(ref re, ref ra, ref rs)) => { ls == rs @@ -191,7 +188,7 @@ impl<'a, 'tcx> SpanlessEq<'a, 'tcx> { pub fn eq_fieldpat(&mut self, left: &FieldPat<'_>, right: &FieldPat<'_>) -> bool { let (FieldPat { ident: li, pat: lp, .. }, FieldPat { ident: ri, pat: rp, .. }) = (&left, &right); - li.name == ri.name && self.eq_pat(lp, rp) + li.name.as_str() == ri.name.as_str() && self.eq_pat(lp, rp) } /// Checks whether two patterns are the same. @@ -205,7 +202,7 @@ impl<'a, 'tcx> SpanlessEq<'a, 'tcx> { self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat(l, r)) && ls == rs }, (&PatKind::Binding(ref lb, .., ref li, ref lp), &PatKind::Binding(ref rb, .., ref ri, ref rp)) => { - lb == rb && li.name == ri.name && both(lp, rp, |l, r| self.eq_pat(l, r)) + lb == rb && li.name.as_str() == ri.name.as_str() && both(lp, rp, |l, r| self.eq_pat(l, r)) }, (&PatKind::Path(ref l), &PatKind::Path(ref r)) => self.eq_qpath(l, r), (&PatKind::Lit(ref l), &PatKind::Lit(ref r)) => self.eq_expr(l, r), @@ -266,7 +263,8 @@ impl<'a, 'tcx> SpanlessEq<'a, 'tcx> { pub fn eq_path_segment(&mut self, left: &PathSegment<'_>, right: &PathSegment<'_>) -> bool { // The == of idents doesn't work with different contexts, // we have to be explicit about hygiene - left.ident.name == right.ident.name && both(&left.args, &right.args, |l, r| self.eq_path_parameters(l, r)) + left.ident.as_str() == right.ident.as_str() + && both(&left.args, &right.args, |l, r| self.eq_path_parameters(l, r)) } pub fn eq_ty(&mut self, left: &Ty<'_>, right: &Ty<'_>) -> bool { @@ -566,15 +564,6 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { self.hash_name(i.ident.name); } }, - ExprKind::If(ref cond, ref then, ref else_opt) => { - let c: fn(_, _, _) -> _ = ExprKind::If; - c.hash(&mut self.s); - self.hash_expr(cond); - self.hash_expr(&**then); - if let Some(ref e) = *else_opt { - self.hash_expr(e); - } - }, ExprKind::Match(ref e, arms, ref s) => { self.hash_expr(e); @@ -755,7 +744,7 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { } for segment in path.segments { segment.ident.name.hash(&mut self.s); - self.hash_generic_args(segment.args().args); + self.hash_generic_args(segment.generic_args().args); } }, QPath::TypeRelative(ref ty, ref segment) => { diff --git a/src/tools/clippy/clippy_lints/src/utils/inspector.rs b/src/tools/clippy/clippy_lints/src/utils/inspector.rs index 9bec24be9e4eb..5d946e4bd495d 100644 --- a/src/tools/clippy/clippy_lints/src/utils/inspector.rs +++ b/src/tools/clippy/clippy_lints/src/utils/inspector.rs @@ -213,15 +213,6 @@ fn print_expr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, indent: usize) { hir::ExprKind::Loop(..) => { println!("{}Loop", ind); }, - hir::ExprKind::If(ref cond, _, ref else_opt) => { - println!("{}If", ind); - println!("{}condition:", ind); - print_expr(cx, cond, indent + 1); - if let Some(ref els) = *else_opt { - println!("{}else:", ind); - print_expr(cx, els, indent + 1); - } - }, hir::ExprKind::Match(ref cond, _, ref source) => { println!("{}Match", ind); println!("{}condition:", ind); @@ -432,13 +423,13 @@ fn print_item(cx: &LateContext<'_>, item: &hir::Item<'_>) { hir::ItemKind::TraitAlias(..) => { println!("trait alias"); }, - hir::ItemKind::Impl(hir::Impl { + hir::ItemKind::Impl { of_trait: Some(ref _trait_ref), .. - }) => { + } => { println!("trait impl"); }, - hir::ItemKind::Impl(hir::Impl { of_trait: None, .. }) => { + hir::ItemKind::Impl { of_trait: None, .. } => { println!("impl"); }, } diff --git a/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs b/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs index 7aa17520ba79f..9ba39f73ee884 100644 --- a/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs +++ b/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs @@ -10,12 +10,9 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::def_id::DefId; use rustc_hir::hir_id::CRATE_HIR_ID; use rustc_hir::intravisit::{NestedVisitorMap, Visitor}; -use rustc_hir::{ - BinOpKind, Crate, Expr, ExprKind, HirId, Item, MutTy, Mutability, Node, Path, StmtKind, Ty, TyKind, UnOp, -}; +use rustc_hir::{Crate, Expr, ExprKind, HirId, Item, MutTy, Mutability, Node, Path, StmtKind, Ty, TyKind}; use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass}; use rustc_middle::hir::map::Map; use rustc_middle::mir::interpret::ConstValue; @@ -275,28 +272,6 @@ declare_clippy_lint! { "interning a symbol that is pre-interned and defined as a constant" } -declare_clippy_lint! { - /// **What it does:** Checks for unnecessary conversion from Symbol to a string. - /// - /// **Why is this bad?** It's faster use symbols directly intead of strings. - /// - /// **Known problems:** None. - /// - /// **Example:** - /// Bad: - /// ```rust,ignore - /// symbol.as_str() == "clippy"; - /// ``` - /// - /// Good: - /// ```rust,ignore - /// symbol == sym::clippy; - /// ``` - pub UNNECESSARY_SYMBOL_STR, - internal, - "unnecessary conversion between Symbol and string" -} - declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]); impl EarlyLintPass for ClippyLintsInternal { @@ -377,11 +352,11 @@ impl<'tcx> LateLintPass<'tcx> for LintWithoutLintPass { } else if is_expn_of(item.span, "impl_lint_pass").is_some() || is_expn_of(item.span, "declare_lint_pass").is_some() { - if let hir::ItemKind::Impl(hir::Impl { + if let hir::ItemKind::Impl { of_trait: None, items: ref impl_item_refs, .. - }) = item.kind + } = item.kind { let mut collector = LintCollector { output: &mut self.registered_lints, @@ -893,11 +868,11 @@ impl<'tcx> LateLintPass<'tcx> for InvalidPaths { #[derive(Default)] pub struct InterningDefinedSymbol { - // Maps the symbol value to the constant DefId. - symbol_map: FxHashMap, + // Maps the symbol value to the constant name. + symbol_map: FxHashMap, } -impl_lint_pass!(InterningDefinedSymbol => [INTERNING_DEFINED_SYMBOL, UNNECESSARY_SYMBOL_STR]); +impl_lint_pass!(InterningDefinedSymbol => [INTERNING_DEFINED_SYMBOL]); impl<'tcx> LateLintPass<'tcx> for InterningDefinedSymbol { fn check_crate(&mut self, cx: &LateContext<'_>, _: &Crate<'_>) { @@ -905,18 +880,16 @@ impl<'tcx> LateLintPass<'tcx> for InterningDefinedSymbol { return; } - for &module in &[&paths::KW_MODULE, &paths::SYM_MODULE] { - if let Some(Res::Def(_, def_id)) = path_to_res(cx, module) { - for item in cx.tcx.item_children(def_id).iter() { - if_chain! { - if let Res::Def(DefKind::Const, item_def_id) = item.res; - let ty = cx.tcx.type_of(item_def_id); - if match_type(cx, ty, &paths::SYMBOL); - if let Ok(ConstValue::Scalar(value)) = cx.tcx.const_eval_poly(item_def_id); - if let Ok(value) = value.to_u32(); - then { - self.symbol_map.insert(value, item_def_id); - } + if let Some(Res::Def(_, def_id)) = path_to_res(cx, &paths::SYM_MODULE) { + for item in cx.tcx.item_children(def_id).iter() { + if_chain! { + if let Res::Def(DefKind::Const, item_def_id) = item.res; + let ty = cx.tcx.type_of(item_def_id); + if match_type(cx, ty, &paths::SYMBOL); + if let Ok(ConstValue::Scalar(value)) = cx.tcx.const_eval_poly(item_def_id); + if let Ok(value) = value.to_u32(); + then { + self.symbol_map.insert(value, item.ident.to_string()); } } } @@ -930,7 +903,7 @@ impl<'tcx> LateLintPass<'tcx> for InterningDefinedSymbol { if match_def_path(cx, *def_id, &paths::SYMBOL_INTERN); if let Some(Constant::Str(arg)) = constant_simple(cx, cx.typeck_results(), arg); let value = Symbol::intern(&arg).as_u32(); - if let Some(&def_id) = self.symbol_map.get(&value); + if let Some(symbol_const) = self.symbol_map.get(&value); then { span_lint_and_sugg( cx, @@ -938,135 +911,10 @@ impl<'tcx> LateLintPass<'tcx> for InterningDefinedSymbol { is_expn_of(expr.span, "sym").unwrap_or(expr.span), "interning a defined symbol", "try", - cx.tcx.def_path_str(def_id), + format!("rustc_span::symbol::sym::{}", symbol_const), Applicability::MachineApplicable, ); } } - if let ExprKind::Binary(op, left, right) = expr.kind { - if matches!(op.node, BinOpKind::Eq | BinOpKind::Ne) { - let data = [ - (left, self.symbol_str_expr(left, cx)), - (right, self.symbol_str_expr(right, cx)), - ]; - match data { - // both operands are a symbol string - [(_, Some(left)), (_, Some(right))] => { - span_lint_and_sugg( - cx, - UNNECESSARY_SYMBOL_STR, - expr.span, - "unnecessary `Symbol` to string conversion", - "try", - format!( - "{} {} {}", - left.as_symbol_snippet(cx), - op.node.as_str(), - right.as_symbol_snippet(cx), - ), - Applicability::MachineApplicable, - ); - }, - // one of the operands is a symbol string - [(expr, Some(symbol)), _] | [_, (expr, Some(symbol))] => { - // creating an owned string for comparison - if matches!(symbol, SymbolStrExpr::Expr { is_to_owned: true, .. }) { - span_lint_and_sugg( - cx, - UNNECESSARY_SYMBOL_STR, - expr.span, - "unnecessary string allocation", - "try", - format!("{}.as_str()", symbol.as_symbol_snippet(cx)), - Applicability::MachineApplicable, - ); - } - }, - // nothing found - [(_, None), (_, None)] => {}, - } - } - } - } -} - -impl InterningDefinedSymbol { - fn symbol_str_expr<'tcx>(&self, expr: &'tcx Expr<'tcx>, cx: &LateContext<'tcx>) -> Option> { - static IDENT_STR_PATHS: &[&[&str]] = &[&paths::IDENT_AS_STR, &paths::TO_STRING_METHOD]; - static SYMBOL_STR_PATHS: &[&[&str]] = &[ - &paths::SYMBOL_AS_STR, - &paths::SYMBOL_TO_IDENT_STRING, - &paths::TO_STRING_METHOD, - ]; - // SymbolStr might be de-referenced: `&*symbol.as_str()` - let call = if_chain! { - if let ExprKind::AddrOf(_, _, e) = expr.kind; - if let ExprKind::Unary(UnOp::UnDeref, e) = e.kind; - then { e } else { expr } - }; - if_chain! { - // is a method call - if let ExprKind::MethodCall(_, _, [item], _) = call.kind; - if let Some(did) = cx.typeck_results().type_dependent_def_id(call.hir_id); - let ty = cx.typeck_results().expr_ty(item); - // ...on either an Ident or a Symbol - if let Some(is_ident) = if match_type(cx, ty, &paths::SYMBOL) { - Some(false) - } else if match_type(cx, ty, &paths::IDENT) { - Some(true) - } else { - None - }; - // ...which converts it to a string - let paths = if is_ident { IDENT_STR_PATHS } else { SYMBOL_STR_PATHS }; - if let Some(path) = paths.iter().find(|path| match_def_path(cx, did, path)); - then { - let is_to_owned = path.last().unwrap().ends_with("string"); - return Some(SymbolStrExpr::Expr { - item, - is_ident, - is_to_owned, - }); - } - } - // is a string constant - if let Some(Constant::Str(s)) = constant_simple(cx, cx.typeck_results(), expr) { - let value = Symbol::intern(&s).as_u32(); - // ...which matches a symbol constant - if let Some(&def_id) = self.symbol_map.get(&value) { - return Some(SymbolStrExpr::Const(def_id)); - } - } - None - } -} - -enum SymbolStrExpr<'tcx> { - /// a string constant with a corresponding symbol constant - Const(DefId), - /// a "symbol to string" expression like `symbol.as_str()` - Expr { - /// part that evaluates to `Symbol` or `Ident` - item: &'tcx Expr<'tcx>, - is_ident: bool, - /// whether an owned `String` is created like `to_ident_string()` - is_to_owned: bool, - }, -} - -impl<'tcx> SymbolStrExpr<'tcx> { - /// Returns a snippet that evaluates to a `Symbol` and is const if possible - fn as_symbol_snippet(&self, cx: &LateContext<'_>) -> Cow<'tcx, str> { - match *self { - Self::Const(def_id) => cx.tcx.def_path_str(def_id).into(), - Self::Expr { item, is_ident, .. } => { - let mut snip = snippet(cx, item.span.source_callsite(), ".."); - if is_ident { - // get `Ident.name` - snip.to_mut().push_str(".name"); - } - snip - }, - } } } diff --git a/src/tools/clippy/clippy_lints/src/utils/mod.rs b/src/tools/clippy/clippy_lints/src/utils/mod.rs index 9b262517a9834..1c68e837c4ab9 100644 --- a/src/tools/clippy/clippy_lints/src/utils/mod.rs +++ b/src/tools/clippy/clippy_lints/src/utils/mod.rs @@ -1,5 +1,5 @@ #[macro_use] -pub mod sym_helper; +pub mod sym; #[allow(clippy::module_name_repetitions)] pub mod ast_utils; @@ -56,8 +56,8 @@ use rustc_semver::RustcVersion; use rustc_session::Session; use rustc_span::hygiene::{ExpnKind, MacroKind}; use rustc_span::source_map::original_sp; -use rustc_span::sym; -use rustc_span::symbol::{kw, Symbol}; +use rustc_span::sym as rustc_sym; +use rustc_span::symbol::{self, kw, Symbol}; use rustc_span::{BytePos, Pos, Span, DUMMY_SP}; use rustc_target::abi::Integer; use rustc_trait_selection::traits::query::normalize::AtExt; @@ -439,8 +439,8 @@ pub fn trait_ref_of_method<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Optio if_chain! { if parent_impl != hir::CRATE_HIR_ID; if let hir::Node::Item(item) = cx.tcx.hir().get(parent_impl); - if let hir::ItemKind::Impl(impl_) = &item.kind; - then { return impl_.of_trait.as_ref(); } + if let hir::ItemKind::Impl{ of_trait: trait_ref, .. } = &item.kind; + then { return trait_ref.as_ref(); } } None } @@ -1121,7 +1121,7 @@ pub fn is_refutable(cx: &LateContext<'_>, pat: &Pat<'_>) -> bool { /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d /// implementations have. pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool { - attrs.iter().any(|attr| attr.has_name(sym::automatically_derived)) + attrs.iter().any(|attr| attr.has_name(rustc_sym::automatically_derived)) } /// Remove blocks around an expression. @@ -1405,7 +1405,7 @@ pub fn if_sequence<'tcx>( let mut conds = SmallVec::new(); let mut blocks: SmallVec<[&Block<'_>; 1]> = SmallVec::new(); - while let ExprKind::If(ref cond, ref then_expr, ref else_expr) = expr.kind { + while let Some((ref cond, ref then_expr, ref else_expr)) = higher::if_block(&expr) { conds.push(&**cond); if let ExprKind::Block(ref block, _) = then_expr.kind { blocks.push(block); @@ -1434,13 +1434,12 @@ pub fn parent_node_is_if_expr(expr: &Expr<'_>, cx: &LateContext<'_>) -> bool { let map = cx.tcx.hir(); let parent_id = map.get_parent_node(expr.hir_id); let parent_node = map.get(parent_id); - matches!( - parent_node, - Node::Expr(Expr { - kind: ExprKind::If(_, _, _), - .. - }) - ) + + match parent_node { + Node::Expr(e) => higher::if_block(&e).is_some(), + Node::Arm(e) => higher::if_block(&e.body).is_some(), + _ => false, + } } // Finds the attribute with the given name, if any @@ -1471,7 +1470,7 @@ pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { ty::Tuple(ref substs) => substs.types().any(|ty| is_must_use_ty(cx, ty)), ty::Opaque(ref def_id, _) => { for (predicate, _) in cx.tcx.explicit_item_bounds(*def_id) { - if let ty::PredicateKind::Trait(trait_predicate, _) = predicate.kind().skip_binder() { + if let ty::PredicateAtom::Trait(trait_predicate, _) = predicate.skip_binders() { if must_use_attr(&cx.tcx.get_attrs(trait_predicate.trait_ref.def_id)).is_some() { return true; } @@ -1515,7 +1514,7 @@ pub fn is_must_use_func_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { pub fn is_no_std_crate(krate: &Crate<'_>) -> bool { krate.item.attrs.iter().any(|attr| { if let ast::AttrKind::Normal(ref attr, _) = attr.kind { - attr.path == sym::no_std + attr.path == symbol::sym::no_std } else { false } @@ -1531,7 +1530,7 @@ pub fn is_no_std_crate(krate: &Crate<'_>) -> bool { /// ``` pub fn is_trait_impl_item(cx: &LateContext<'_>, hir_id: HirId) -> bool { if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) { - matches!(item.kind, ItemKind::Impl(hir::Impl { of_trait: Some(_), .. })) + matches!(item.kind, ItemKind::Impl { of_trait: Some(_), .. }) } else { false } @@ -1687,18 +1686,6 @@ macro_rules! unwrap_cargo_metadata { }}; } -pub fn is_hir_ty_cfg_dependant(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> bool { - if_chain! { - if let TyKind::Path(QPath::Resolved(_, path)) = ty.kind; - if let Res::Def(_, def_id) = path.res; - then { - cx.tcx.has_attr(def_id, sym::cfg) || cx.tcx.has_attr(def_id, sym::cfg_attr) - } else { - false - } - } -} - #[cfg(test)] mod test { use super::{reindent_multiline, without_block_comments}; diff --git a/src/tools/clippy/clippy_lints/src/utils/paths.rs b/src/tools/clippy/clippy_lints/src/utils/paths.rs index c0b203b5388dc..2080a49a11cd6 100644 --- a/src/tools/clippy/clippy_lints/src/utils/paths.rs +++ b/src/tools/clippy/clippy_lints/src/utils/paths.rs @@ -54,10 +54,6 @@ pub const HASH: [&str; 3] = ["core", "hash", "Hash"]; pub const HASHMAP: [&str; 5] = ["std", "collections", "hash", "map", "HashMap"]; pub const HASHMAP_ENTRY: [&str; 5] = ["std", "collections", "hash", "map", "Entry"]; pub const HASHSET: [&str; 5] = ["std", "collections", "hash", "set", "HashSet"]; -#[cfg(feature = "internal-lints")] -pub const IDENT: [&str; 3] = ["rustc_span", "symbol", "Ident"]; -#[cfg(feature = "internal-lints")] -pub const IDENT_AS_STR: [&str; 4] = ["rustc_span", "symbol", "Ident", "as_str"]; pub const INDEX: [&str; 3] = ["core", "ops", "Index"]; pub const INDEX_MUT: [&str; 3] = ["core", "ops", "IndexMut"]; pub const INSERT_STR: [&str; 4] = ["alloc", "string", "String", "insert_str"]; @@ -69,8 +65,6 @@ pub const IPADDR_V4: [&str; 4] = ["std", "net", "IpAddr", "V4"]; pub const IPADDR_V6: [&str; 4] = ["std", "net", "IpAddr", "V6"]; pub const ITERATOR: [&str; 5] = ["core", "iter", "traits", "iterator", "Iterator"]; #[cfg(feature = "internal-lints")] -pub const KW_MODULE: [&str; 3] = ["rustc_span", "symbol", "kw"]; -#[cfg(feature = "internal-lints")] pub const LATE_CONTEXT: [&str; 2] = ["rustc_lint", "LateContext"]; pub const LINKED_LIST: [&str; 4] = ["alloc", "collections", "linked_list", "LinkedList"]; #[cfg(feature = "internal-lints")] @@ -154,12 +148,8 @@ pub const STR_STARTS_WITH: [&str; 4] = ["core", "str", "", "starts_wit #[cfg(feature = "internal-lints")] pub const SYMBOL: [&str; 3] = ["rustc_span", "symbol", "Symbol"]; #[cfg(feature = "internal-lints")] -pub const SYMBOL_AS_STR: [&str; 4] = ["rustc_span", "symbol", "Symbol", "as_str"]; -#[cfg(feature = "internal-lints")] pub const SYMBOL_INTERN: [&str; 4] = ["rustc_span", "symbol", "Symbol", "intern"]; #[cfg(feature = "internal-lints")] -pub const SYMBOL_TO_IDENT_STRING: [&str; 4] = ["rustc_span", "symbol", "Symbol", "to_ident_string"]; -#[cfg(feature = "internal-lints")] pub const SYM_MODULE: [&str; 3] = ["rustc_span", "symbol", "sym"]; #[cfg(feature = "internal-lints")] pub const SYNTAX_CONTEXT: [&str; 3] = ["rustc_span", "hygiene", "SyntaxContext"]; diff --git a/src/tools/clippy/clippy_lints/src/utils/qualify_min_const_fn.rs b/src/tools/clippy/clippy_lints/src/utils/qualify_min_const_fn.rs index a482017afeb13..7cb7d0a26b65e 100644 --- a/src/tools/clippy/clippy_lints/src/utils/qualify_min_const_fn.rs +++ b/src/tools/clippy/clippy_lints/src/utils/qualify_min_const_fn.rs @@ -19,18 +19,18 @@ pub fn is_min_const_fn(tcx: TyCtxt<'tcx>, body: &'a Body<'tcx>) -> McfResult { loop { let predicates = tcx.predicates_of(current); for (predicate, _) in predicates.predicates { - match predicate.kind().skip_binder() { - ty::PredicateKind::RegionOutlives(_) - | ty::PredicateKind::TypeOutlives(_) - | ty::PredicateKind::WellFormed(_) - | ty::PredicateKind::Projection(_) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) - | ty::PredicateKind::TypeWellFormedFromEnv(..) => continue, - ty::PredicateKind::ObjectSafe(_) => panic!("object safe predicate on function: {:#?}", predicate), - ty::PredicateKind::ClosureKind(..) => panic!("closure kind predicate on function: {:#?}", predicate), - ty::PredicateKind::Subtype(_) => panic!("subtype predicate on function: {:#?}", predicate), - ty::PredicateKind::Trait(pred, _) => { + match predicate.skip_binders() { + ty::PredicateAtom::RegionOutlives(_) + | ty::PredicateAtom::TypeOutlives(_) + | ty::PredicateAtom::WellFormed(_) + | ty::PredicateAtom::Projection(_) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) + | ty::PredicateAtom::TypeWellFormedFromEnv(..) => continue, + ty::PredicateAtom::ObjectSafe(_) => panic!("object safe predicate on function: {:#?}", predicate), + ty::PredicateAtom::ClosureKind(..) => panic!("closure kind predicate on function: {:#?}", predicate), + ty::PredicateAtom::Subtype(_) => panic!("subtype predicate on function: {:#?}", predicate), + ty::PredicateAtom::Trait(pred, _) => { if Some(pred.def_id()) == tcx.lang_items().sized_trait() { continue; } diff --git a/src/tools/clippy/clippy_lints/src/utils/sugg.rs b/src/tools/clippy/clippy_lints/src/utils/sugg.rs index 03678db575f0d..1fcd41e4dbfed 100644 --- a/src/tools/clippy/clippy_lints/src/utils/sugg.rs +++ b/src/tools/clippy/clippy_lints/src/utils/sugg.rs @@ -103,7 +103,6 @@ impl<'a> Sugg<'a> { match expr.kind { hir::ExprKind::AddrOf(..) | hir::ExprKind::Box(..) - | hir::ExprKind::If(..) | hir::ExprKind::Closure(..) | hir::ExprKind::Unary(..) | hir::ExprKind::Match(..) => Sugg::MaybeParen(snippet), diff --git a/src/tools/clippy/clippy_lints/src/utils/sym_helper.rs b/src/tools/clippy/clippy_lints/src/utils/sym.rs similarity index 68% rename from src/tools/clippy/clippy_lints/src/utils/sym_helper.rs rename to src/tools/clippy/clippy_lints/src/utils/sym.rs index f47dc80ebade8..273288c3d52c5 100644 --- a/src/tools/clippy/clippy_lints/src/utils/sym_helper.rs +++ b/src/tools/clippy/clippy_lints/src/utils/sym.rs @@ -1,5 +1,4 @@ #[macro_export] -/// Convenience wrapper around rustc's `Symbol::intern` macro_rules! sym { ($tt:tt) => { rustc_span::symbol::Symbol::intern(stringify!($tt)) diff --git a/src/tools/clippy/clippy_lints/src/utils/visitors.rs b/src/tools/clippy/clippy_lints/src/utils/visitors.rs index ebf69df31ca41..28b3e79d7a6d6 100644 --- a/src/tools/clippy/clippy_lints/src/utils/visitors.rs +++ b/src/tools/clippy/clippy_lints/src/utils/visitors.rs @@ -101,13 +101,6 @@ where } } else { match expr.kind { - hir::ExprKind::If(cond, then, else_opt) => { - self.inside_stmt(true).visit_expr(cond); - self.visit_expr(then); - if let Some(el) = else_opt { - self.visit_expr(el); - } - }, hir::ExprKind::Match(cond, arms, _) => { self.inside_stmt(true).visit_expr(cond); for arm in arms { diff --git a/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs b/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs deleted file mode 100644 index e632a7e57ee87..0000000000000 --- a/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs +++ /dev/null @@ -1,187 +0,0 @@ -use crate::utils::{is_type_diagnostic_item, match_def_path, paths, snippet, span_lint_and_sugg}; -use if_chain::if_chain; -use rustc_ast::ast::LitKind; -use rustc_errors::Applicability; -use rustc_hir::{BindingAnnotation, Block, Expr, ExprKind, Local, PatKind, QPath, Stmt, StmtKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext}; -use rustc_middle::lint::in_external_macro; -use rustc_session::{declare_tool_lint, impl_lint_pass}; -use rustc_span::{symbol::sym, Span, Symbol}; -use std::convert::TryInto; - -declare_clippy_lint! { - /// **What it does:** Checks for calls to `push` immediately after creating a new `Vec`. - /// - /// **Why is this bad?** The `vec![]` macro is both more performant and easier to read than - /// multiple `push` calls. - /// - /// **Known problems:** None. - /// - /// **Example:** - /// - /// ```rust - /// let mut v = Vec::new(); - /// v.push(0); - /// ``` - /// Use instead: - /// ```rust - /// let v = vec![0]; - /// ``` - pub VEC_INIT_THEN_PUSH, - perf, - "`push` immediately after `Vec` creation" -} - -impl_lint_pass!(VecInitThenPush => [VEC_INIT_THEN_PUSH]); - -#[derive(Default)] -pub struct VecInitThenPush { - searcher: Option, -} - -#[derive(Clone, Copy)] -enum VecInitKind { - New, - WithCapacity(u64), -} -struct VecPushSearcher { - init: VecInitKind, - name: Symbol, - lhs_is_local: bool, - lhs_span: Span, - err_span: Span, - found: u64, -} -impl VecPushSearcher { - fn display_err(&self, cx: &LateContext<'_>) { - match self.init { - _ if self.found == 0 => return, - VecInitKind::WithCapacity(x) if x > self.found => return, - _ => (), - }; - - let mut s = if self.lhs_is_local { - String::from("let ") - } else { - String::new() - }; - s.push_str(&snippet(cx, self.lhs_span, "..")); - s.push_str(" = vec![..];"); - - span_lint_and_sugg( - cx, - VEC_INIT_THEN_PUSH, - self.err_span, - "calls to `push` immediately after creation", - "consider using the `vec![]` macro", - s, - Applicability::HasPlaceholders, - ); - } -} - -impl LateLintPass<'_> for VecInitThenPush { - fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'tcx>) { - self.searcher = None; - if_chain! { - if !in_external_macro(cx.sess(), local.span); - if let Some(init) = local.init; - if let PatKind::Binding(BindingAnnotation::Mutable, _, ident, None) = local.pat.kind; - if let Some(init_kind) = get_vec_init_kind(cx, init); - then { - self.searcher = Some(VecPushSearcher { - init: init_kind, - name: ident.name, - lhs_is_local: true, - lhs_span: local.ty.map_or(local.pat.span, |t| local.pat.span.to(t.span)), - err_span: local.span, - found: 0, - }); - } - } - } - - fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - if self.searcher.is_none() { - if_chain! { - if !in_external_macro(cx.sess(), expr.span); - if let ExprKind::Assign(left, right, _) = expr.kind; - if let ExprKind::Path(QPath::Resolved(_, path)) = left.kind; - if let Some(name) = path.segments.get(0); - if let Some(init_kind) = get_vec_init_kind(cx, right); - then { - self.searcher = Some(VecPushSearcher { - init: init_kind, - name: name.ident.name, - lhs_is_local: false, - lhs_span: left.span, - err_span: expr.span, - found: 0, - }); - } - } - } - } - - fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) { - if let Some(searcher) = self.searcher.take() { - if_chain! { - if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = stmt.kind; - if let ExprKind::MethodCall(path, _, [self_arg, _], _) = expr.kind; - if path.ident.name.as_str() == "push"; - if let ExprKind::Path(QPath::Resolved(_, self_path)) = self_arg.kind; - if let [self_name] = self_path.segments; - if self_name.ident.name == searcher.name; - then { - self.searcher = Some(VecPushSearcher { - found: searcher.found + 1, - err_span: searcher.err_span.to(stmt.span), - .. searcher - }); - } else { - searcher.display_err(cx); - } - } - } - } - - fn check_block_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Block<'tcx>) { - if let Some(searcher) = self.searcher.take() { - searcher.display_err(cx); - } - } -} - -fn get_vec_init_kind<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option { - if let ExprKind::Call(func, args) = expr.kind { - match func.kind { - ExprKind::Path(QPath::TypeRelative(ty, name)) - if is_type_diagnostic_item(cx, cx.typeck_results().node_type(ty.hir_id), sym::vec_type) => - { - if name.ident.name == sym::new { - return Some(VecInitKind::New); - } else if name.ident.name.as_str() == "with_capacity" { - return args.get(0).and_then(|arg| { - if_chain! { - if let ExprKind::Lit(lit) = &arg.kind; - if let LitKind::Int(num, _) = lit.node; - then { - Some(VecInitKind::WithCapacity(num.try_into().ok()?)) - } else { - None - } - } - }); - } - } - ExprKind::Path(QPath::Resolved(_, path)) - if match_def_path(cx, path.res.opt_def_id()?, &paths::DEFAULT_TRAIT_METHOD) - && is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::vec_type) => - { - return Some(VecInitKind::New); - } - _ => (), - } - } - None -} diff --git a/src/tools/clippy/clippy_lints/src/wildcard_imports.rs b/src/tools/clippy/clippy_lints/src/wildcard_imports.rs index 10005a7fc81ed..5683a71efea4e 100644 --- a/src/tools/clippy/clippy_lints/src/wildcard_imports.rs +++ b/src/tools/clippy/clippy_lints/src/wildcard_imports.rs @@ -7,8 +7,7 @@ use rustc_hir::{ }; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_tool_lint, impl_lint_pass}; -use rustc_span::symbol::kw; -use rustc_span::{sym, BytePos}; +use rustc_span::BytePos; declare_clippy_lint! { /// **What it does:** Checks for `use Enum::*`. @@ -199,12 +198,12 @@ impl WildcardImports { // Allow "...prelude::..::*" imports. // Many crates have a prelude, and it is imported as a glob by design. fn is_prelude_import(segments: &[PathSegment<'_>]) -> bool { - segments.iter().any(|ps| ps.ident.name == sym::prelude) + segments.iter().any(|ps| ps.ident.as_str() == "prelude") } // Allow "super::*" imports in tests. fn is_super_only_import(segments: &[PathSegment<'_>]) -> bool { - segments.len() == 1 && segments[0].ident.name == kw::Super + segments.len() == 1 && segments[0].ident.as_str() == "super" } fn is_test_module_or_function(item: &Item<'_>) -> bool { diff --git a/src/tools/clippy/clippy_lints/src/write.rs b/src/tools/clippy/clippy_lints/src/write.rs index af324f831dfa2..337f7a229b906 100644 --- a/src/tools/clippy/clippy_lints/src/write.rs +++ b/src/tools/clippy/clippy_lints/src/write.rs @@ -10,8 +10,7 @@ use rustc_lexer::unescape::{self, EscapeError}; use rustc_lint::{EarlyContext, EarlyLintPass}; use rustc_parse::parser; use rustc_session::{declare_tool_lint, impl_lint_pass}; -use rustc_span::symbol::kw; -use rustc_span::{sym, BytePos, Span}; +use rustc_span::{sym, BytePos, Span, Symbol}; declare_clippy_lint! { /// **What it does:** This lint warns when you use `println!("")` to @@ -302,7 +301,7 @@ impl EarlyLintPass for Write { } } else if mac.path == sym!(writeln) { if let (Some(fmt_str), expr) = self.check_tts(cx, mac.args.inner_tokens(), true) { - if fmt_str.symbol == kw::Empty { + if fmt_str.symbol == Symbol::intern("") { let mut applicability = Applicability::MachineApplicable; // FIXME: remove this `#[allow(...)]` once the issue #5822 gets fixed #[allow(clippy::option_if_let_else)] @@ -485,7 +484,7 @@ impl Write { fn lint_println_empty_string(&self, cx: &EarlyContext<'_>, mac: &MacCall) { if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) { - if fmt_str.symbol == kw::Empty { + if fmt_str.symbol == Symbol::intern("") { let name = mac.path.segments[0].ident.name; span_lint_and_sugg( cx, diff --git a/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs b/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs index 9761e822a7a00..1d5fa8d06a996 100644 --- a/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs +++ b/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs @@ -62,7 +62,7 @@ impl LateLintPass<'_> for ZeroSizedMapValues { fn in_trait_impl(cx: &LateContext<'_>, hir_id: HirId) -> bool { let parent_id = cx.tcx.hir().get_parent_item(hir_id); if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_item(parent_id)) { - if let ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = item.kind { + if let ItemKind::Impl { of_trait: Some(_), .. } = item.kind { return true; } } diff --git a/src/tools/clippy/doc/adding_lints.md b/src/tools/clippy/doc/adding_lints.md index 1a7a30c61be5b..60dfdb76650a1 100644 --- a/src/tools/clippy/doc/adding_lints.md +++ b/src/tools/clippy/doc/adding_lints.md @@ -147,14 +147,10 @@ add `// edition:2018` at the top of the test file (note that it's space-sensitiv Manually testing against an example file can be useful if you have added some `println!`s and the test suite output becomes unreadable. To try Clippy with -your local modifications, run +your local modifications, run `env CLIPPY_TESTS=true cargo run --bin +clippy-driver -- -L ./target/debug input.rs` from the working copy root. -``` -env __CLIPPY_INTERNAL_TESTS=true cargo run --bin clippy-driver -- -L ./target/debug input.rs -``` - -from the working copy root. With tests in place, let's have a look at -implementing our lint now. +With tests in place, let's have a look at implementing our lint now. ## Lint declaration diff --git a/src/tools/clippy/doc/roadmap-2021.md b/src/tools/clippy/doc/roadmap-2021.md deleted file mode 100644 index fe8b080f56f2b..0000000000000 --- a/src/tools/clippy/doc/roadmap-2021.md +++ /dev/null @@ -1,235 +0,0 @@ -# Roadmap 2021 - -# Summary - -This Roadmap lays out the plans for Clippy in 2021: - -- Improving usability and reliability -- Improving experience of contributors and maintainers -- Develop and specify processes - -Members of the Clippy team will be assigned tasks from one or more of these -topics. The team member is then responsible to complete the assigned tasks. This -can either be done by implementing them or by providing mentorship to interested -contributors. - -# Motivation - -With the ongoing growth of the Rust language and with that of the whole -ecosystem, also Clippy gets more and more users and contributors. This is good -for the project, but also brings challenges along. Some of these challenges are: - -- More issues about reliability or usability are popping up -- Traffic is hard to handle for a small team -- Bigger projects don't get completed due to the lack of processes and/or time - of the team members - -Additionally, according to the [Rust Roadmap 2021], clear processes should be -defined by every team and unified across teams. This Roadmap is the first step -towards this. - -[Rust Roadmap 2021]: https://github.com/rust-lang/rfcs/pull/3037 - -# Explanation - -This section will explain the things that should be done in 2021. It is -important to note, that this document focuses on the "What?", not the "How?". -The later will be addressed in follow-up tracking issue, with an assigned team -member. - -The following is split up in two major sections. The first section covers the -user facing plans, the second section the internal plans. - -## User Facing - -Clippy should be as pleasant to use and configure as possible. This section -covers plans that should be implemented to improve the situation of Clippy in -this regard. - -### Usability - -In the following, plans to improve the usability are covered. - -#### No Output After `cargo check` - -Currently when `cargo clippy` is run after `cargo check`, it does not produce -any output. This is especially problematic since `rust-analyzer` is on the rise -and it uses `cargo check` for checking code. A fix is already implemented, but -it still has to be pushed over the finish line. This also includes the -stabilization of the `cargo clippy --fix` command or the support of multi-span -suggestions in `rustfix`. - -- [#4612](https://github.com/rust-lang/rust-clippy/issues/4612) - -#### `lints.toml` Configuration - -This is something that comes up every now and then: a reusable configuration -file, where lint levels can be defined. Discussions about this often lead to -nothing specific or to "we need an RFC for this". And this is exactly what needs -to be done. Get together with the cargo team and write an RFC and implement such -a configuration file somehow and somewhere. - -- [#3164](https://github.com/rust-lang/rust-clippy/issues/3164) -- [cargo#5034](https://github.com/rust-lang/cargo/issues/5034) -- [IRLO](https://internals.rust-lang.org/t/proposal-cargo-lint-configuration/9135/8) - -#### Lint Groups - -There are more and more issues about managing lints in Clippy popping up. Lints -are hard to implement with a guarantee of no/few false positives (FPs). One way -to address this might be to introduce more lint groups to give users the ability -to better manage lints, or improve the process of classifying lints, so that -disabling lints due to FPs becomes rare. It is important to note, that Clippy -lints are less conservative than `rustc` lints, which won't change in the -future. - -- [#5537](https://github.com/rust-lang/rust-clippy/issues/5537) -- [#6366](https://github.com/rust-lang/rust-clippy/issues/6366) - -### Reliability - -In the following, plans to improve the reliability are covered. - -#### False Positive Rate - -In the worst case, new lints are only available in nightly for 2 weeks, before -hitting beta and ultimately stable. This and the fact that fewer people use -nightly Rust nowadays makes it more probable that a lint with many FPs hits -stable. This leads to annoyed users, that will disable these new lints in the -best case and to more annoyed users, that will stop using Clippy in the worst. -A process should be developed and implemented to prevent this from happening. - -- [#6429](https://github.com/rust-lang/rust-clippy/issues/6429) - -## Internal - -(The end of) 2020 has shown, that Clippy has to think about the available -resources, especially regarding management and maintenance of the project. This -section address issues affecting team members and contributors. - -### Management - -In 2020 Clippy achieved over 1000 open issues with regularly between 25-35 open -PRs. This is simultaneously a win and a loss. More issues and PRs means more -people are interested in Clippy and in contributing to it. On the other hand, it -means for team members more work and for contributors longer wait times for -reviews. The following will describe plans how to improve the situation for both -team members and contributors. - -#### Clear Expectations for Team Members - -According to the [Rust Roadmap 2021], a document specifying what it means to be -a member of the team should be produced. This should not put more pressure on -the team members, but rather help them and interested folks to know what the -expectations are. With this it should also be easier to recruit new team members -and may encourage people to get in touch, if they're interested to join. - -#### Scaling up the Team - -More people means less work for each individual. Together with the document -about expectations for team members, a document defining the process of how to -join the team should be produced. This can also increase the stability of the -team, in case of current members dropping out (temporarily). There can also be -different roles in the team, like people triaging vs. people reviewing. - -#### Regular Meetings - -Other teams have regular meetings. Clippy is big enough that it might be worth -to also do them. Especially if more people join the team, this can be important -for sync-ups. Besides the asynchronous communication, that works well for -working on separate lints, a meeting adds a synchronous alternative at a known -time. This is especially helpful if there are bigger things that need to be -discussed (like the projects in this roadmap). For starters bi-weekly meetings -before Rust syncs might make sense. - -#### Triaging - -To get a handle on the influx of open issues, a process for triaging issues and -PRs should be developed. Officially, Clippy follows the Rust triage process, but -currently no one enforces it. This can be improved by sharing triage teams -across projects or by implementing dashboards / tools which simplify triaging. - -### Development - -Improving the developer and contributor experience is something the Clippy team -works on regularly. Though, some things might need special attention and -planing. These topics are listed in the following. - -#### Process for New and Existing Lints - -As already mentioned above, classifying new lints gets quite hard, because the -probability of a buggy lint getting into stable is quite high. A process should -be implemented on how to classify lints. In addition, a test system should be -developed to find out which lints are currently problematic in real world code -to fix or disable them. - -- [#6429 (comment)](https://github.com/rust-lang/rust-clippy/issues/6429#issuecomment-741056379) -- [#6429 (comment)](https://github.com/rust-lang/rust-clippy/issues/6429#issuecomment-741153345) - -#### Processes - -Related to the point before, a process for suggesting and discussing major -changes should be implemented. It's also not clearly defined when a lint should -be enabled or disabled by default. This can also be improved by the test system -mentioned above. - -#### Dev-Tools - -There's already `cargo dev` which makes Clippy development easier and more -pleasant. This can still be expanded, so that it covers more areas of the -development process. - -- [#5394](https://github.com/rust-lang/rust-clippy/issues/5394) - -#### Contributor Guide - -Similar to a Clippy Book, which describes how to use Clippy, a book about how to -contribute to Clippy might be helpful for new and existing contributors. There's -already the `doc` directory in the Clippy repo, this can be turned into a -`mdbook`. - -#### `rustc` integration - -Recently Clippy was integrated with `git subtree` into the `rust-lang/rust` -repository. This made syncing between the two repositories easier. A -`#[non_exhaustive]` list of things that still can be improved is: - -1. Use the same `rustfmt` version and configuration as `rustc`. -2. Make `cargo dev` work in the Rust repo, just as it works in the Clippy repo. - E.g. `cargo dev bless` or `cargo dev update_lints`. And even add more things - to it that might be useful for the Rust repo, e.g. `cargo dev deprecate`. -3. Easier sync process. The `subtree` situation is not ideal. - -## Prioritization - -The most pressing issues for users of Clippy are of course the user facing -issues. So there should be a priority on those issues, but without losing track -of the internal issues listed in this document. - -Getting the FP rate of warn/deny-by-default lints under control should have the -highest priority. Other user facing issues should also get a high priority, but -shouldn't be in the way of addressing internal issues. - -To better manage the upcoming projects, the basic internal processes, like -meetings, tracking issues and documentation, should be established as soon as -possible. They might even be necessary to properly manage the projects, -regarding the user facing issues. - -# Prior Art - -## Rust Roadmap - -Rust's roadmap process was established by [RFC 1728] in 2016. Since then every -year a roadmap was published, that defined the bigger plans for the coming -years. This years roadmap can be found [here][Rust Roadmap 2021]. - -[RFC 1728]: https://rust-lang.github.io/rfcs/1728-north-star.html - -# Drawbacks - -## Big Roadmap - -This roadmap is pretty big and not all items listed in this document might be -addressed during 2021. Because this is the first roadmap for Clippy, having open -tasks at the end of 2021 is fine, but they should be revisited in the 2022 -roadmap. diff --git a/src/tools/clippy/rust-toolchain b/src/tools/clippy/rust-toolchain index 72935072f8cdd..c579beeae89be 100644 --- a/src/tools/clippy/rust-toolchain +++ b/src/tools/clippy/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2021-01-15" +channel = "nightly-2021-01-02" components = ["llvm-tools-preview", "rustc-dev", "rust-src", "rustfmt"] diff --git a/src/tools/clippy/src/driver.rs b/src/tools/clippy/src/driver.rs index f5f6c09ed8e94..e490ee54c0be0 100644 --- a/src/tools/clippy/src/driver.rs +++ b/src/tools/clippy/src/driver.rs @@ -298,7 +298,7 @@ pub fn main() { // - IF Clippy is run on the main crate, not on deps (`!cap_lints_allow`) THEN // - IF `--no-deps` is not set (`!no_deps`) OR // - IF `--no-deps` is set and Clippy is run on the specified primary package - let clippy_tests_set = env::var("__CLIPPY_INTERNAL_TESTS").map_or(false, |val| val == "true"); + let clippy_tests_set = env::var("CLIPPY_TESTS").map_or(false, |val| val == "true"); let cap_lints_allow = arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_some(); let in_primary_package = env::var("CARGO_PRIMARY_PACKAGE").is_ok(); diff --git a/src/tools/clippy/tests/compile-test.rs b/src/tools/clippy/tests/compile-test.rs index ea800336ef550..ec3af94b9ca91 100644 --- a/src/tools/clippy/tests/compile-test.rs +++ b/src/tools/clippy/tests/compile-test.rs @@ -254,7 +254,7 @@ fn run_ui_cargo(config: &mut compiletest::Config) { fn prepare_env() { set_var("CLIPPY_DISABLE_DOCS_LINKS", "true"); - set_var("__CLIPPY_INTERNAL_TESTS", "true"); + set_var("CLIPPY_TESTS", "true"); //set_var("RUST_BACKTRACE", "0"); } diff --git a/src/tools/clippy/tests/ui-internal/interning_defined_symbol.fixed b/src/tools/clippy/tests/ui-internal/interning_defined_symbol.fixed index 9ab845a573aca..c6b84d2ef650b 100644 --- a/src/tools/clippy/tests/ui-internal/interning_defined_symbol.fixed +++ b/src/tools/clippy/tests/ui-internal/interning_defined_symbol.fixed @@ -14,16 +14,13 @@ macro_rules! sym { fn main() { // Direct use of Symbol::intern - let _ = rustc_span::sym::f32; + let _ = rustc_span::symbol::sym::f32; // Using a sym macro - let _ = rustc_span::sym::f32; + let _ = rustc_span::symbol::sym::f32; // Correct suggestion when symbol isn't stringified constant name - let _ = rustc_span::sym::proc_dash_macro; - - // interning a keyword - let _ = rustc_span::symbol::kw::SelfLower; + let _ = rustc_span::symbol::sym::proc_dash_macro; // Interning a symbol that is not defined let _ = Symbol::intern("xyz123"); diff --git a/src/tools/clippy/tests/ui-internal/interning_defined_symbol.rs b/src/tools/clippy/tests/ui-internal/interning_defined_symbol.rs index a58e182971d73..9ec82d4ad0bae 100644 --- a/src/tools/clippy/tests/ui-internal/interning_defined_symbol.rs +++ b/src/tools/clippy/tests/ui-internal/interning_defined_symbol.rs @@ -22,9 +22,6 @@ fn main() { // Correct suggestion when symbol isn't stringified constant name let _ = Symbol::intern("proc-macro"); - // interning a keyword - let _ = Symbol::intern("self"); - // Interning a symbol that is not defined let _ = Symbol::intern("xyz123"); let _ = sym!(xyz123); diff --git a/src/tools/clippy/tests/ui-internal/interning_defined_symbol.stderr b/src/tools/clippy/tests/ui-internal/interning_defined_symbol.stderr index 50c1c268eb132..74b906c8a5797 100644 --- a/src/tools/clippy/tests/ui-internal/interning_defined_symbol.stderr +++ b/src/tools/clippy/tests/ui-internal/interning_defined_symbol.stderr @@ -2,7 +2,7 @@ error: interning a defined symbol --> $DIR/interning_defined_symbol.rs:17:13 | LL | let _ = Symbol::intern("f32"); - | ^^^^^^^^^^^^^^^^^^^^^ help: try: `rustc_span::sym::f32` + | ^^^^^^^^^^^^^^^^^^^^^ help: try: `rustc_span::symbol::sym::f32` | note: the lint level is defined here --> $DIR/interning_defined_symbol.rs:2:9 @@ -15,19 +15,13 @@ error: interning a defined symbol --> $DIR/interning_defined_symbol.rs:20:13 | LL | let _ = sym!(f32); - | ^^^^^^^^^ help: try: `rustc_span::sym::f32` + | ^^^^^^^^^ help: try: `rustc_span::symbol::sym::f32` error: interning a defined symbol --> $DIR/interning_defined_symbol.rs:23:13 | LL | let _ = Symbol::intern("proc-macro"); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `rustc_span::sym::proc_dash_macro` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `rustc_span::symbol::sym::proc_dash_macro` -error: interning a defined symbol - --> $DIR/interning_defined_symbol.rs:26:13 - | -LL | let _ = Symbol::intern("self"); - | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `rustc_span::symbol::kw::SelfLower` - -error: aborting due to 4 previous errors +error: aborting due to 3 previous errors diff --git a/src/tools/clippy/tests/ui-internal/unnecessary_symbol_str.fixed b/src/tools/clippy/tests/ui-internal/unnecessary_symbol_str.fixed deleted file mode 100644 index 2ec0efe4c10a5..0000000000000 --- a/src/tools/clippy/tests/ui-internal/unnecessary_symbol_str.fixed +++ /dev/null @@ -1,16 +0,0 @@ -// run-rustfix -#![feature(rustc_private)] -#![deny(clippy::internal)] -#![allow(clippy::unnecessary_operation, unused_must_use)] - -extern crate rustc_span; - -use rustc_span::symbol::{Ident, Symbol}; - -fn main() { - Symbol::intern("foo") == rustc_span::sym::clippy; - Symbol::intern("foo") == rustc_span::symbol::kw::SelfLower; - Symbol::intern("foo") != rustc_span::symbol::kw::SelfUpper; - Ident::invalid().name == rustc_span::sym::clippy; - rustc_span::sym::clippy == Ident::invalid().name; -} diff --git a/src/tools/clippy/tests/ui-internal/unnecessary_symbol_str.rs b/src/tools/clippy/tests/ui-internal/unnecessary_symbol_str.rs deleted file mode 100644 index 87e1b3a2ee76a..0000000000000 --- a/src/tools/clippy/tests/ui-internal/unnecessary_symbol_str.rs +++ /dev/null @@ -1,16 +0,0 @@ -// run-rustfix -#![feature(rustc_private)] -#![deny(clippy::internal)] -#![allow(clippy::unnecessary_operation, unused_must_use)] - -extern crate rustc_span; - -use rustc_span::symbol::{Ident, Symbol}; - -fn main() { - Symbol::intern("foo").as_str() == "clippy"; - Symbol::intern("foo").to_string() == "self"; - Symbol::intern("foo").to_ident_string() != "Self"; - &*Ident::invalid().as_str() == "clippy"; - "clippy" == Ident::invalid().to_string(); -} diff --git a/src/tools/clippy/tests/ui-internal/unnecessary_symbol_str.stderr b/src/tools/clippy/tests/ui-internal/unnecessary_symbol_str.stderr deleted file mode 100644 index b1284b7c8ffd0..0000000000000 --- a/src/tools/clippy/tests/ui-internal/unnecessary_symbol_str.stderr +++ /dev/null @@ -1,39 +0,0 @@ -error: unnecessary `Symbol` to string conversion - --> $DIR/unnecessary_symbol_str.rs:11:5 - | -LL | Symbol::intern("foo").as_str() == "clippy"; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Symbol::intern("foo") == rustc_span::sym::clippy` - | -note: the lint level is defined here - --> $DIR/unnecessary_symbol_str.rs:3:9 - | -LL | #![deny(clippy::internal)] - | ^^^^^^^^^^^^^^^^ - = note: `#[deny(clippy::unnecessary_symbol_str)]` implied by `#[deny(clippy::internal)]` - -error: unnecessary `Symbol` to string conversion - --> $DIR/unnecessary_symbol_str.rs:12:5 - | -LL | Symbol::intern("foo").to_string() == "self"; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Symbol::intern("foo") == rustc_span::symbol::kw::SelfLower` - -error: unnecessary `Symbol` to string conversion - --> $DIR/unnecessary_symbol_str.rs:13:5 - | -LL | Symbol::intern("foo").to_ident_string() != "Self"; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Symbol::intern("foo") != rustc_span::symbol::kw::SelfUpper` - -error: unnecessary `Symbol` to string conversion - --> $DIR/unnecessary_symbol_str.rs:14:5 - | -LL | &*Ident::invalid().as_str() == "clippy"; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Ident::invalid().name == rustc_span::sym::clippy` - -error: unnecessary `Symbol` to string conversion - --> $DIR/unnecessary_symbol_str.rs:15:5 - | -LL | "clippy" == Ident::invalid().to_string(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `rustc_span::sym::clippy == Ident::invalid().name` - -error: aborting due to 5 previous errors - diff --git a/src/tools/clippy/tests/ui/author/if.stdout b/src/tools/clippy/tests/ui/author/if.stdout index cac64a3f40b41..c18d035953e53 100644 --- a/src/tools/clippy/tests/ui/author/if.stdout +++ b/src/tools/clippy/tests/ui/author/if.stdout @@ -1,7 +1,7 @@ if_chain! { if let StmtKind::Local(ref local) = stmt.kind; if let Some(ref init) = local.init; - if let ExprKind::If(ref cond, ref then, Some(ref else_)) = init.kind; + if let Some((ref cond, ref then, Some(else_))) = higher::if_block(&init); if let ExprKind::Block(ref block) = else_.kind; if let Some(trailing_expr) = &block.expr; if block.stmts.len() == 1; diff --git a/src/tools/clippy/tests/ui/auxiliary/macro_rules.rs b/src/tools/clippy/tests/ui/auxiliary/macro_rules.rs index d6ecd8568ce78..1832482346820 100644 --- a/src/tools/clippy/tests/ui/auxiliary/macro_rules.rs +++ b/src/tools/clippy/tests/ui/auxiliary/macro_rules.rs @@ -94,19 +94,3 @@ macro_rules! large_enum_variant { } }; } - -#[macro_export] -macro_rules! field_reassign_with_default { - () => { - #[derive(Default)] - struct A { - pub i: i32, - pub j: i64, - } - fn lint() { - let mut a: A = Default::default(); - a.i = 42; - a; - } - }; -} diff --git a/src/tools/clippy/tests/ui/auxiliary/proc_macro_derive.rs b/src/tools/clippy/tests/ui/auxiliary/proc_macro_derive.rs index 24891682d368d..7c4e4a145512f 100644 --- a/src/tools/clippy/tests/ui/auxiliary/proc_macro_derive.rs +++ b/src/tools/clippy/tests/ui/auxiliary/proc_macro_derive.rs @@ -4,7 +4,6 @@ #![crate_type = "proc-macro"] #![feature(repr128, proc_macro_quote)] #![allow(incomplete_features)] -#![allow(clippy::field_reassign_with_default)] #![allow(clippy::eq_op)] extern crate proc_macro; @@ -24,20 +23,3 @@ pub fn derive(_: TokenStream) -> TokenStream { }; output } - -#[proc_macro_derive(FieldReassignWithDefault)] -pub fn derive_foo(_input: TokenStream) -> TokenStream { - quote! { - #[derive(Default)] - struct A { - pub i: i32, - pub j: i64, - } - #[automatically_derived] - fn lint() { - let mut a: A = Default::default(); - a.i = 42; - a; - } - } -} diff --git a/src/tools/clippy/tests/ui/cast_alignment.rs b/src/tools/clippy/tests/ui/cast_alignment.rs index d011e84b115a7..4c08935639f1f 100644 --- a/src/tools/clippy/tests/ui/cast_alignment.rs +++ b/src/tools/clippy/tests/ui/cast_alignment.rs @@ -12,10 +12,6 @@ fn main() { (&1u8 as *const u8) as *const u16; (&mut 1u8 as *mut u8) as *mut u16; - // cast to more-strictly-aligned type, but with the `pointer::cast` function. - (&1u8 as *const u8).cast::(); - (&mut 1u8 as *mut u8).cast::(); - /* These should be ok */ // not a pointer type diff --git a/src/tools/clippy/tests/ui/cast_alignment.stderr b/src/tools/clippy/tests/ui/cast_alignment.stderr index 7998b787b91fb..79219f86155a4 100644 --- a/src/tools/clippy/tests/ui/cast_alignment.stderr +++ b/src/tools/clippy/tests/ui/cast_alignment.stderr @@ -12,17 +12,5 @@ error: casting from `*mut u8` to a more-strictly-aligned pointer (`*mut u16`) (1 LL | (&mut 1u8 as *mut u8) as *mut u16; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: casting from `*const u8` to a more-strictly-aligned pointer (`*const u16`) (1 < 2 bytes) - --> $DIR/cast_alignment.rs:16:5 - | -LL | (&1u8 as *const u8).cast::(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -error: casting from `*mut u8` to a more-strictly-aligned pointer (`*mut u16`) (1 < 2 bytes) - --> $DIR/cast_alignment.rs:17:5 - | -LL | (&mut 1u8 as *mut u8).cast::(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -error: aborting due to 4 previous errors +error: aborting due to 2 previous errors diff --git a/src/tools/clippy/tests/ui/clone_on_copy.fixed b/src/tools/clippy/tests/ui/clone_on_copy.fixed index d924625132eb0..1f0ca101757ec 100644 --- a/src/tools/clippy/tests/ui/clone_on_copy.fixed +++ b/src/tools/clippy/tests/ui/clone_on_copy.fixed @@ -5,8 +5,7 @@ clippy::redundant_clone, clippy::deref_addrof, clippy::no_effect, - clippy::unnecessary_operation, - clippy::vec_init_then_push + clippy::unnecessary_operation )] use std::cell::RefCell; diff --git a/src/tools/clippy/tests/ui/clone_on_copy.rs b/src/tools/clippy/tests/ui/clone_on_copy.rs index 97f4946724458..ca39a654b4fce 100644 --- a/src/tools/clippy/tests/ui/clone_on_copy.rs +++ b/src/tools/clippy/tests/ui/clone_on_copy.rs @@ -5,8 +5,7 @@ clippy::redundant_clone, clippy::deref_addrof, clippy::no_effect, - clippy::unnecessary_operation, - clippy::vec_init_then_push + clippy::unnecessary_operation )] use std::cell::RefCell; diff --git a/src/tools/clippy/tests/ui/clone_on_copy.stderr b/src/tools/clippy/tests/ui/clone_on_copy.stderr index 7a706884fb0e7..14a700886a7bc 100644 --- a/src/tools/clippy/tests/ui/clone_on_copy.stderr +++ b/src/tools/clippy/tests/ui/clone_on_copy.stderr @@ -1,5 +1,5 @@ error: using `clone` on type `i32` which implements the `Copy` trait - --> $DIR/clone_on_copy.rs:23:5 + --> $DIR/clone_on_copy.rs:22:5 | LL | 42.clone(); | ^^^^^^^^^^ help: try removing the `clone` call: `42` @@ -7,25 +7,25 @@ LL | 42.clone(); = note: `-D clippy::clone-on-copy` implied by `-D warnings` error: using `clone` on type `i32` which implements the `Copy` trait - --> $DIR/clone_on_copy.rs:27:5 + --> $DIR/clone_on_copy.rs:26:5 | LL | (&42).clone(); | ^^^^^^^^^^^^^ help: try dereferencing it: `*(&42)` error: using `clone` on type `i32` which implements the `Copy` trait - --> $DIR/clone_on_copy.rs:30:5 + --> $DIR/clone_on_copy.rs:29:5 | LL | rc.borrow().clone(); | ^^^^^^^^^^^^^^^^^^^ help: try dereferencing it: `*rc.borrow()` error: using `clone` on type `char` which implements the `Copy` trait - --> $DIR/clone_on_copy.rs:36:14 + --> $DIR/clone_on_copy.rs:35:14 | LL | is_ascii('z'.clone()); | ^^^^^^^^^^^ help: try removing the `clone` call: `'z'` error: using `clone` on type `i32` which implements the `Copy` trait - --> $DIR/clone_on_copy.rs:40:14 + --> $DIR/clone_on_copy.rs:39:14 | LL | vec.push(42.clone()); | ^^^^^^^^^^ help: try removing the `clone` call: `42` diff --git a/src/tools/clippy/tests/ui/collapsible_else_if.fixed b/src/tools/clippy/tests/ui/collapsible_else_if.fixed index fa4bc30e933a2..ce2a1c28c8a80 100644 --- a/src/tools/clippy/tests/ui/collapsible_else_if.fixed +++ b/src/tools/clippy/tests/ui/collapsible_else_if.fixed @@ -3,8 +3,6 @@ #[rustfmt::skip] #[warn(clippy::collapsible_if)] -#[warn(clippy::collapsible_else_if)] - fn main() { let x = "hello"; let y = "world"; diff --git a/src/tools/clippy/tests/ui/collapsible_else_if.rs b/src/tools/clippy/tests/ui/collapsible_else_if.rs index bf6c1d1f894d7..99c40b8d38eb9 100644 --- a/src/tools/clippy/tests/ui/collapsible_else_if.rs +++ b/src/tools/clippy/tests/ui/collapsible_else_if.rs @@ -3,8 +3,6 @@ #[rustfmt::skip] #[warn(clippy::collapsible_if)] -#[warn(clippy::collapsible_else_if)] - fn main() { let x = "hello"; let y = "world"; diff --git a/src/tools/clippy/tests/ui/collapsible_else_if.stderr b/src/tools/clippy/tests/ui/collapsible_else_if.stderr index ee3e11ae565d4..3d1c458879e58 100644 --- a/src/tools/clippy/tests/ui/collapsible_else_if.stderr +++ b/src/tools/clippy/tests/ui/collapsible_else_if.stderr @@ -1,5 +1,5 @@ error: this `else { if .. }` block can be collapsed - --> $DIR/collapsible_else_if.rs:14:12 + --> $DIR/collapsible_else_if.rs:12:12 | LL | } else { | ____________^ @@ -9,7 +9,7 @@ LL | | } LL | | } | |_____^ | - = note: `-D clippy::collapsible-else-if` implied by `-D warnings` + = note: `-D clippy::collapsible-if` implied by `-D warnings` help: collapse nested if block | LL | } else if y == "world" { @@ -18,7 +18,7 @@ LL | } | error: this `else { if .. }` block can be collapsed - --> $DIR/collapsible_else_if.rs:22:12 + --> $DIR/collapsible_else_if.rs:20:12 | LL | } else { | ____________^ @@ -36,7 +36,7 @@ LL | } | error: this `else { if .. }` block can be collapsed - --> $DIR/collapsible_else_if.rs:30:12 + --> $DIR/collapsible_else_if.rs:28:12 | LL | } else { | ____________^ @@ -59,7 +59,7 @@ LL | } | error: this `else { if .. }` block can be collapsed - --> $DIR/collapsible_else_if.rs:41:12 + --> $DIR/collapsible_else_if.rs:39:12 | LL | } else { | ____________^ @@ -82,7 +82,7 @@ LL | } | error: this `else { if .. }` block can be collapsed - --> $DIR/collapsible_else_if.rs:52:12 + --> $DIR/collapsible_else_if.rs:50:12 | LL | } else { | ____________^ @@ -105,7 +105,7 @@ LL | } | error: this `else { if .. }` block can be collapsed - --> $DIR/collapsible_else_if.rs:63:12 + --> $DIR/collapsible_else_if.rs:61:12 | LL | } else { | ____________^ @@ -128,7 +128,7 @@ LL | } | error: this `else { if .. }` block can be collapsed - --> $DIR/collapsible_else_if.rs:74:12 + --> $DIR/collapsible_else_if.rs:72:12 | LL | } else { | ____________^ diff --git a/src/tools/clippy/tests/ui/deprecated.rs b/src/tools/clippy/tests/ui/deprecated.rs index 4a538021b98ea..e1ee8dbca2c04 100644 --- a/src/tools/clippy/tests/ui/deprecated.rs +++ b/src/tools/clippy/tests/ui/deprecated.rs @@ -9,6 +9,5 @@ #[warn(clippy::drop_bounds)] #[warn(clippy::temporary_cstring_as_ptr)] #[warn(clippy::panic_params)] -#[warn(clippy::unknown_clippy_lints)] fn main() {} diff --git a/src/tools/clippy/tests/ui/deprecated.stderr b/src/tools/clippy/tests/ui/deprecated.stderr index 3429317498ed6..edbb891afe07b 100644 --- a/src/tools/clippy/tests/ui/deprecated.stderr +++ b/src/tools/clippy/tests/ui/deprecated.stderr @@ -66,17 +66,11 @@ error: lint `clippy::panic_params` has been removed: `this lint has been uplifte LL | #[warn(clippy::panic_params)] | ^^^^^^^^^^^^^^^^^^^^ -error: lint `clippy::unknown_clippy_lints` has been removed: `this lint has been integrated into the `unknown_lints` rustc lint` - --> $DIR/deprecated.rs:12:8 - | -LL | #[warn(clippy::unknown_clippy_lints)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - error: lint `clippy::unstable_as_slice` has been removed: ``Vec::as_slice` has been stabilized in 1.7` --> $DIR/deprecated.rs:1:8 | LL | #[warn(clippy::unstable_as_slice)] | ^^^^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 13 previous errors +error: aborting due to 12 previous errors diff --git a/src/tools/clippy/tests/ui/empty_enum.rs b/src/tools/clippy/tests/ui/empty_enum.rs index a2e5c13c45282..12428f29625c0 100644 --- a/src/tools/clippy/tests/ui/empty_enum.rs +++ b/src/tools/clippy/tests/ui/empty_enum.rs @@ -1,7 +1,6 @@ #![allow(dead_code)] #![warn(clippy::empty_enum)] -// Enable never type to test empty enum lint -#![feature(never_type)] + enum Empty {} fn main() {} diff --git a/src/tools/clippy/tests/ui/empty_enum.stderr b/src/tools/clippy/tests/ui/empty_enum.stderr index 7125e5f602b75..466dfbe7cee7a 100644 --- a/src/tools/clippy/tests/ui/empty_enum.stderr +++ b/src/tools/clippy/tests/ui/empty_enum.stderr @@ -1,5 +1,5 @@ error: enum with no variants - --> $DIR/empty_enum.rs:5:1 + --> $DIR/empty_enum.rs:4:1 | LL | enum Empty {} | ^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/empty_enum_without_never_type.rs b/src/tools/clippy/tests/ui/empty_enum_without_never_type.rs deleted file mode 100644 index 386677352e29b..0000000000000 --- a/src/tools/clippy/tests/ui/empty_enum_without_never_type.rs +++ /dev/null @@ -1,7 +0,0 @@ -#![allow(dead_code)] -#![warn(clippy::empty_enum)] - -// `never_type` is not enabled; this test has no stderr file -enum Empty {} - -fn main() {} diff --git a/src/tools/clippy/tests/ui/escape_analysis.rs b/src/tools/clippy/tests/ui/escape_analysis.rs index d26f48fc68f85..07004489610d0 100644 --- a/src/tools/clippy/tests/ui/escape_analysis.rs +++ b/src/tools/clippy/tests/ui/escape_analysis.rs @@ -182,23 +182,3 @@ pub extern "C" fn do_not_warn_me(_c_pointer: Box) -> () {} #[rustfmt::skip] // Forces rustfmt to not add ABI pub extern fn do_not_warn_me_no_abi(_c_pointer: Box) -> () {} - -// Issue #4804 - default implementation in trait -mod issue4804 { - trait DefaultTraitImplTest { - // don't warn on `self` - fn default_impl(self: Box) -> u32 { - 5 - } - - // warn on `x: Box` - fn default_impl_x(self: Box, x: Box) -> u32 { - 4 - } - } - - trait WarnTrait { - // warn on `x: Box` - fn foo(x: Box) {} - } -} diff --git a/src/tools/clippy/tests/ui/escape_analysis.stderr b/src/tools/clippy/tests/ui/escape_analysis.stderr index 4a82b4419f997..c86a769a3da4b 100644 --- a/src/tools/clippy/tests/ui/escape_analysis.stderr +++ b/src/tools/clippy/tests/ui/escape_analysis.stderr @@ -12,17 +12,5 @@ error: local variable doesn't need to be boxed here LL | pub fn new(_needs_name: Box>) -> () {} | ^^^^^^^^^^^ -error: local variable doesn't need to be boxed here - --> $DIR/escape_analysis.rs:195:44 - | -LL | fn default_impl_x(self: Box, x: Box) -> u32 { - | ^ - -error: local variable doesn't need to be boxed here - --> $DIR/escape_analysis.rs:202:16 - | -LL | fn foo(x: Box) {} - | ^ - -error: aborting due to 4 previous errors +error: aborting due to 2 previous errors diff --git a/src/tools/clippy/tests/ui/field_reassign_with_default.rs b/src/tools/clippy/tests/ui/field_reassign_with_default.rs index 9fc208f5332a5..3e0921022b417 100644 --- a/src/tools/clippy/tests/ui/field_reassign_with_default.rs +++ b/src/tools/clippy/tests/ui/field_reassign_with_default.rs @@ -1,18 +1,5 @@ -// aux-build:proc_macro_derive.rs -// aux-build:macro_rules.rs - #![warn(clippy::field_reassign_with_default)] -#[macro_use] -extern crate proc_macro_derive; -#[macro_use] -extern crate macro_rules; - -// Don't lint on derives that derive `Default` -// See https://github.com/rust-lang/rust-clippy/issues/6545 -#[derive(FieldReassignWithDefault)] -struct DerivedStruct; - #[derive(Default)] struct A { i: i32, @@ -24,11 +11,6 @@ struct B { j: i64, } -#[derive(Default)] -struct C { - i: Vec, - j: i64, -} /// Implements .next() that returns a different number each time. struct SideEffect(i32); @@ -129,13 +111,6 @@ fn main() { // don't lint - some private fields let mut x = m::F::default(); x.a = 1; - - // don't expand macros in the suggestion (#6522) - let mut a: C = C::default(); - a.i = vec![1]; - - // Don't lint in external macros - field_reassign_with_default!(); } mod m { diff --git a/src/tools/clippy/tests/ui/field_reassign_with_default.stderr b/src/tools/clippy/tests/ui/field_reassign_with_default.stderr index 2f0f28f7bb724..9a2bc778c3ff7 100644 --- a/src/tools/clippy/tests/ui/field_reassign_with_default.stderr +++ b/src/tools/clippy/tests/ui/field_reassign_with_default.stderr @@ -1,87 +1,75 @@ error: field assignment outside of initializer for an instance created with Default::default() - --> $DIR/field_reassign_with_default.rs:48:5 + --> $DIR/field_reassign_with_default.rs:30:5 | LL | a.i = 42; | ^^^^^^^^^ | = note: `-D clippy::field-reassign-with-default` implied by `-D warnings` -note: consider initializing the variable with `main::A { i: 42, ..Default::default() }` and removing relevant reassignments - --> $DIR/field_reassign_with_default.rs:47:5 +note: consider initializing the variable with `A { i: 42, ..Default::default() }` and removing relevant reassignments + --> $DIR/field_reassign_with_default.rs:29:5 | LL | let mut a: A = Default::default(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: field assignment outside of initializer for an instance created with Default::default() - --> $DIR/field_reassign_with_default.rs:88:5 + --> $DIR/field_reassign_with_default.rs:70:5 | LL | a.j = 43; | ^^^^^^^^^ | -note: consider initializing the variable with `main::A { j: 43, i: 42 }` and removing relevant reassignments - --> $DIR/field_reassign_with_default.rs:87:5 +note: consider initializing the variable with `A { j: 43, i: 42 }` and removing relevant reassignments + --> $DIR/field_reassign_with_default.rs:69:5 | LL | let mut a: A = Default::default(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: field assignment outside of initializer for an instance created with Default::default() - --> $DIR/field_reassign_with_default.rs:93:5 + --> $DIR/field_reassign_with_default.rs:75:5 | LL | a.i = 42; | ^^^^^^^^^ | -note: consider initializing the variable with `main::A { i: 42, j: 44 }` and removing relevant reassignments - --> $DIR/field_reassign_with_default.rs:92:5 +note: consider initializing the variable with `A { i: 42, j: 44 }` and removing relevant reassignments + --> $DIR/field_reassign_with_default.rs:74:5 | LL | let mut a: A = Default::default(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: field assignment outside of initializer for an instance created with Default::default() - --> $DIR/field_reassign_with_default.rs:99:5 + --> $DIR/field_reassign_with_default.rs:81:5 | LL | a.i = 42; | ^^^^^^^^^ | -note: consider initializing the variable with `main::A { i: 42, ..Default::default() }` and removing relevant reassignments - --> $DIR/field_reassign_with_default.rs:98:5 +note: consider initializing the variable with `A { i: 42, ..Default::default() }` and removing relevant reassignments + --> $DIR/field_reassign_with_default.rs:80:5 | LL | let mut a = A::default(); | ^^^^^^^^^^^^^^^^^^^^^^^^^ error: field assignment outside of initializer for an instance created with Default::default() - --> $DIR/field_reassign_with_default.rs:109:5 + --> $DIR/field_reassign_with_default.rs:91:5 | LL | a.i = Default::default(); | ^^^^^^^^^^^^^^^^^^^^^^^^^ | -note: consider initializing the variable with `main::A { i: Default::default(), ..Default::default() }` and removing relevant reassignments - --> $DIR/field_reassign_with_default.rs:108:5 +note: consider initializing the variable with `A { i: Default::default(), ..Default::default() }` and removing relevant reassignments + --> $DIR/field_reassign_with_default.rs:90:5 | LL | let mut a: A = Default::default(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: field assignment outside of initializer for an instance created with Default::default() - --> $DIR/field_reassign_with_default.rs:113:5 + --> $DIR/field_reassign_with_default.rs:95:5 | LL | a.i = Default::default(); | ^^^^^^^^^^^^^^^^^^^^^^^^^ | -note: consider initializing the variable with `main::A { i: Default::default(), j: 45 }` and removing relevant reassignments - --> $DIR/field_reassign_with_default.rs:112:5 +note: consider initializing the variable with `A { i: Default::default(), j: 45 }` and removing relevant reassignments + --> $DIR/field_reassign_with_default.rs:94:5 | LL | let mut a: A = Default::default(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: field assignment outside of initializer for an instance created with Default::default() - --> $DIR/field_reassign_with_default.rs:135:5 - | -LL | a.i = vec![1]; - | ^^^^^^^^^^^^^^ - | -note: consider initializing the variable with `C { i: vec![1], ..Default::default() }` and removing relevant reassignments - --> $DIR/field_reassign_with_default.rs:134:5 - | -LL | let mut a: C = C::default(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -error: aborting due to 7 previous errors +error: aborting due to 6 previous errors diff --git a/src/tools/clippy/tests/ui/from_over_into.stderr b/src/tools/clippy/tests/ui/from_over_into.stderr index b101d2704fbda..18f56f854329e 100644 --- a/src/tools/clippy/tests/ui/from_over_into.stderr +++ b/src/tools/clippy/tests/ui/from_over_into.stderr @@ -1,8 +1,12 @@ error: an implementation of `From` is preferred since it gives you `Into<_>` for free where the reverse isn't true --> $DIR/from_over_into.rs:6:1 | -LL | impl Into for String { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | / impl Into for String { +LL | | fn into(self) -> StringWrapper { +LL | | StringWrapper(self) +LL | | } +LL | | } + | |_^ | = note: `-D clippy::from-over-into` implied by `-D warnings` = help: consider to implement `From` instead diff --git a/src/tools/clippy/tests/ui/if_same_then_else2.rs b/src/tools/clippy/tests/ui/if_same_then_else2.rs index e83ce47e56308..8d54f75b5d19f 100644 --- a/src/tools/clippy/tests/ui/if_same_then_else2.rs +++ b/src/tools/clippy/tests/ui/if_same_then_else2.rs @@ -1,7 +1,6 @@ #![warn(clippy::if_same_then_else)] #![allow( clippy::blacklisted_name, - clippy::collapsible_else_if, clippy::collapsible_if, clippy::ifs_same_cond, clippy::needless_return, diff --git a/src/tools/clippy/tests/ui/if_same_then_else2.stderr b/src/tools/clippy/tests/ui/if_same_then_else2.stderr index f98e30fa376fe..da2be6c8aa5ac 100644 --- a/src/tools/clippy/tests/ui/if_same_then_else2.stderr +++ b/src/tools/clippy/tests/ui/if_same_then_else2.stderr @@ -1,5 +1,5 @@ error: this `if` has identical blocks - --> $DIR/if_same_then_else2.rs:21:12 + --> $DIR/if_same_then_else2.rs:20:12 | LL | } else { | ____________^ @@ -13,7 +13,7 @@ LL | | } | = note: `-D clippy::if-same-then-else` implied by `-D warnings` note: same as this - --> $DIR/if_same_then_else2.rs:12:13 + --> $DIR/if_same_then_else2.rs:11:13 | LL | if true { | _____________^ @@ -26,7 +26,7 @@ LL | | } else { | |_____^ error: this `if` has identical blocks - --> $DIR/if_same_then_else2.rs:35:12 + --> $DIR/if_same_then_else2.rs:34:12 | LL | } else { | ____________^ @@ -36,7 +36,7 @@ LL | | } | |_____^ | note: same as this - --> $DIR/if_same_then_else2.rs:33:13 + --> $DIR/if_same_then_else2.rs:32:13 | LL | if true { | _____________^ @@ -45,7 +45,7 @@ LL | | } else { | |_____^ error: this `if` has identical blocks - --> $DIR/if_same_then_else2.rs:42:12 + --> $DIR/if_same_then_else2.rs:41:12 | LL | } else { | ____________^ @@ -55,7 +55,7 @@ LL | | } | |_____^ | note: same as this - --> $DIR/if_same_then_else2.rs:40:13 + --> $DIR/if_same_then_else2.rs:39:13 | LL | if true { | _____________^ @@ -64,7 +64,7 @@ LL | | } else { | |_____^ error: this `if` has identical blocks - --> $DIR/if_same_then_else2.rs:92:12 + --> $DIR/if_same_then_else2.rs:91:12 | LL | } else { | ____________^ @@ -74,7 +74,7 @@ LL | | }; | |_____^ | note: same as this - --> $DIR/if_same_then_else2.rs:90:21 + --> $DIR/if_same_then_else2.rs:89:21 | LL | let _ = if true { | _____________________^ @@ -83,7 +83,7 @@ LL | | } else { | |_____^ error: this `if` has identical blocks - --> $DIR/if_same_then_else2.rs:99:12 + --> $DIR/if_same_then_else2.rs:98:12 | LL | } else { | ____________^ @@ -93,7 +93,7 @@ LL | | } | |_____^ | note: same as this - --> $DIR/if_same_then_else2.rs:97:13 + --> $DIR/if_same_then_else2.rs:96:13 | LL | if true { | _____________^ @@ -102,7 +102,7 @@ LL | | } else { | |_____^ error: this `if` has identical blocks - --> $DIR/if_same_then_else2.rs:124:12 + --> $DIR/if_same_then_else2.rs:123:12 | LL | } else { | ____________^ @@ -112,7 +112,7 @@ LL | | } | |_____^ | note: same as this - --> $DIR/if_same_then_else2.rs:121:20 + --> $DIR/if_same_then_else2.rs:120:20 | LL | } else if true { | ____________________^ diff --git a/src/tools/clippy/tests/ui/needless_question_mark.fixed b/src/tools/clippy/tests/ui/needless_question_mark.fixed deleted file mode 100644 index 70218f3f041d8..0000000000000 --- a/src/tools/clippy/tests/ui/needless_question_mark.fixed +++ /dev/null @@ -1,163 +0,0 @@ -// run-rustfix - -#![warn(clippy::needless_question_mark)] -#![allow(clippy::needless_return, clippy::unnecessary_unwrap, dead_code, unused_must_use)] -#![feature(custom_inner_attributes)] - -struct TO { - magic: Option, -} - -struct TR { - magic: Result, -} - -fn simple_option_bad1(to: TO) -> Option { - // return as a statement - return to.magic; -} - -// formatting will add a semi-colon, which would make -// this identical to the test case above -#[rustfmt::skip] -fn simple_option_bad2(to: TO) -> Option { - // return as an expression - return to.magic -} - -fn simple_option_bad3(to: TO) -> Option { - // block value "return" - to.magic -} - -fn simple_option_bad4(to: Option) -> Option { - // single line closure - to.and_then(|t| t.magic) -} - -// formatting this will remove the block brackets, making -// this test identical to the one above -#[rustfmt::skip] -fn simple_option_bad5(to: Option) -> Option { - // closure with body - to.and_then(|t| { - t.magic - }) -} - -fn simple_result_bad1(tr: TR) -> Result { - return tr.magic; -} - -// formatting will add a semi-colon, which would make -// this identical to the test case above -#[rustfmt::skip] -fn simple_result_bad2(tr: TR) -> Result { - return tr.magic -} - -fn simple_result_bad3(tr: TR) -> Result { - tr.magic -} - -fn simple_result_bad4(tr: Result) -> Result { - tr.and_then(|t| t.magic) -} - -// formatting this will remove the block brackets, making -// this test identical to the one above -#[rustfmt::skip] -fn simple_result_bad5(tr: Result) -> Result { - tr.and_then(|t| { - t.magic - }) -} - -fn also_bad(tr: Result) -> Result { - if tr.is_ok() { - let t = tr.unwrap(); - return t.magic; - } - Err(false) -} - -fn false_positive_test(x: Result<(), U>) -> Result<(), T> -where - T: From, -{ - Ok(x?) -} - -fn main() {} - -mod question_mark_none { - #![clippy::msrv = "1.12.0"] - fn needless_question_mark_option() -> Option { - struct TO { - magic: Option, - } - let to = TO { magic: None }; - Some(to.magic?) // should not be triggered - } - - fn needless_question_mark_result() -> Result { - struct TO { - magic: Result, - } - let to = TO { magic: Ok(1_usize) }; - Ok(to.magic?) // should not be triggered - } - - fn main() { - needless_question_mark_option(); - needless_question_mark_result(); - } -} - -mod question_mark_result { - #![clippy::msrv = "1.21.0"] - fn needless_question_mark_option() -> Option { - struct TO { - magic: Option, - } - let to = TO { magic: None }; - Some(to.magic?) // should not be triggered - } - - fn needless_question_mark_result() -> Result { - struct TO { - magic: Result, - } - let to = TO { magic: Ok(1_usize) }; - to.magic // should be triggered - } - - fn main() { - needless_question_mark_option(); - needless_question_mark_result(); - } -} - -mod question_mark_both { - #![clippy::msrv = "1.22.0"] - fn needless_question_mark_option() -> Option { - struct TO { - magic: Option, - } - let to = TO { magic: None }; - to.magic // should be triggered - } - - fn needless_question_mark_result() -> Result { - struct TO { - magic: Result, - } - let to = TO { magic: Ok(1_usize) }; - to.magic // should be triggered - } - - fn main() { - needless_question_mark_option(); - needless_question_mark_result(); - } -} diff --git a/src/tools/clippy/tests/ui/needless_question_mark.rs b/src/tools/clippy/tests/ui/needless_question_mark.rs deleted file mode 100644 index 60ac2c8d72eac..0000000000000 --- a/src/tools/clippy/tests/ui/needless_question_mark.rs +++ /dev/null @@ -1,163 +0,0 @@ -// run-rustfix - -#![warn(clippy::needless_question_mark)] -#![allow(clippy::needless_return, clippy::unnecessary_unwrap, dead_code, unused_must_use)] -#![feature(custom_inner_attributes)] - -struct TO { - magic: Option, -} - -struct TR { - magic: Result, -} - -fn simple_option_bad1(to: TO) -> Option { - // return as a statement - return Some(to.magic?); -} - -// formatting will add a semi-colon, which would make -// this identical to the test case above -#[rustfmt::skip] -fn simple_option_bad2(to: TO) -> Option { - // return as an expression - return Some(to.magic?) -} - -fn simple_option_bad3(to: TO) -> Option { - // block value "return" - Some(to.magic?) -} - -fn simple_option_bad4(to: Option) -> Option { - // single line closure - to.and_then(|t| Some(t.magic?)) -} - -// formatting this will remove the block brackets, making -// this test identical to the one above -#[rustfmt::skip] -fn simple_option_bad5(to: Option) -> Option { - // closure with body - to.and_then(|t| { - Some(t.magic?) - }) -} - -fn simple_result_bad1(tr: TR) -> Result { - return Ok(tr.magic?); -} - -// formatting will add a semi-colon, which would make -// this identical to the test case above -#[rustfmt::skip] -fn simple_result_bad2(tr: TR) -> Result { - return Ok(tr.magic?) -} - -fn simple_result_bad3(tr: TR) -> Result { - Ok(tr.magic?) -} - -fn simple_result_bad4(tr: Result) -> Result { - tr.and_then(|t| Ok(t.magic?)) -} - -// formatting this will remove the block brackets, making -// this test identical to the one above -#[rustfmt::skip] -fn simple_result_bad5(tr: Result) -> Result { - tr.and_then(|t| { - Ok(t.magic?) - }) -} - -fn also_bad(tr: Result) -> Result { - if tr.is_ok() { - let t = tr.unwrap(); - return Ok(t.magic?); - } - Err(false) -} - -fn false_positive_test(x: Result<(), U>) -> Result<(), T> -where - T: From, -{ - Ok(x?) -} - -fn main() {} - -mod question_mark_none { - #![clippy::msrv = "1.12.0"] - fn needless_question_mark_option() -> Option { - struct TO { - magic: Option, - } - let to = TO { magic: None }; - Some(to.magic?) // should not be triggered - } - - fn needless_question_mark_result() -> Result { - struct TO { - magic: Result, - } - let to = TO { magic: Ok(1_usize) }; - Ok(to.magic?) // should not be triggered - } - - fn main() { - needless_question_mark_option(); - needless_question_mark_result(); - } -} - -mod question_mark_result { - #![clippy::msrv = "1.21.0"] - fn needless_question_mark_option() -> Option { - struct TO { - magic: Option, - } - let to = TO { magic: None }; - Some(to.magic?) // should not be triggered - } - - fn needless_question_mark_result() -> Result { - struct TO { - magic: Result, - } - let to = TO { magic: Ok(1_usize) }; - Ok(to.magic?) // should be triggered - } - - fn main() { - needless_question_mark_option(); - needless_question_mark_result(); - } -} - -mod question_mark_both { - #![clippy::msrv = "1.22.0"] - fn needless_question_mark_option() -> Option { - struct TO { - magic: Option, - } - let to = TO { magic: None }; - Some(to.magic?) // should be triggered - } - - fn needless_question_mark_result() -> Result { - struct TO { - magic: Result, - } - let to = TO { magic: Ok(1_usize) }; - Ok(to.magic?) // should be triggered - } - - fn main() { - needless_question_mark_option(); - needless_question_mark_result(); - } -} diff --git a/src/tools/clippy/tests/ui/needless_question_mark.stderr b/src/tools/clippy/tests/ui/needless_question_mark.stderr deleted file mode 100644 index b4eb21882ece9..0000000000000 --- a/src/tools/clippy/tests/ui/needless_question_mark.stderr +++ /dev/null @@ -1,88 +0,0 @@ -error: Question mark operator is useless here - --> $DIR/needless_question_mark.rs:17:12 - | -LL | return Some(to.magic?); - | ^^^^^^^^^^^^^^^ help: try: `to.magic` - | - = note: `-D clippy::needless-question-mark` implied by `-D warnings` - -error: Question mark operator is useless here - --> $DIR/needless_question_mark.rs:25:12 - | -LL | return Some(to.magic?) - | ^^^^^^^^^^^^^^^ help: try: `to.magic` - -error: Question mark operator is useless here - --> $DIR/needless_question_mark.rs:30:5 - | -LL | Some(to.magic?) - | ^^^^^^^^^^^^^^^ help: try: `to.magic` - -error: Question mark operator is useless here - --> $DIR/needless_question_mark.rs:35:21 - | -LL | to.and_then(|t| Some(t.magic?)) - | ^^^^^^^^^^^^^^ help: try: `t.magic` - -error: Question mark operator is useless here - --> $DIR/needless_question_mark.rs:44:9 - | -LL | Some(t.magic?) - | ^^^^^^^^^^^^^^ help: try: `t.magic` - -error: Question mark operator is useless here - --> $DIR/needless_question_mark.rs:49:12 - | -LL | return Ok(tr.magic?); - | ^^^^^^^^^^^^^ help: try: `tr.magic` - -error: Question mark operator is useless here - --> $DIR/needless_question_mark.rs:56:12 - | -LL | return Ok(tr.magic?) - | ^^^^^^^^^^^^^ help: try: `tr.magic` - -error: Question mark operator is useless here - --> $DIR/needless_question_mark.rs:60:5 - | -LL | Ok(tr.magic?) - | ^^^^^^^^^^^^^ help: try: `tr.magic` - -error: Question mark operator is useless here - --> $DIR/needless_question_mark.rs:64:21 - | -LL | tr.and_then(|t| Ok(t.magic?)) - | ^^^^^^^^^^^^ help: try: `t.magic` - -error: Question mark operator is useless here - --> $DIR/needless_question_mark.rs:72:9 - | -LL | Ok(t.magic?) - | ^^^^^^^^^^^^ help: try: `t.magic` - -error: Question mark operator is useless here - --> $DIR/needless_question_mark.rs:79:16 - | -LL | return Ok(t.magic?); - | ^^^^^^^^^^^^ help: try: `t.magic` - -error: Question mark operator is useless here - --> $DIR/needless_question_mark.rs:132:9 - | -LL | Ok(to.magic?) // should be triggered - | ^^^^^^^^^^^^^ help: try: `to.magic` - -error: Question mark operator is useless here - --> $DIR/needless_question_mark.rs:148:9 - | -LL | Some(to.magic?) // should be triggered - | ^^^^^^^^^^^^^^^ help: try: `to.magic` - -error: Question mark operator is useless here - --> $DIR/needless_question_mark.rs:156:9 - | -LL | Ok(to.magic?) // should be triggered - | ^^^^^^^^^^^^^ help: try: `to.magic` - -error: aborting due to 14 previous errors - diff --git a/src/tools/clippy/tests/ui/needless_return.fixed b/src/tools/clippy/tests/ui/needless_return.fixed index 86bfc5b4bb283..d849e093da7bb 100644 --- a/src/tools/clippy/tests/ui/needless_return.fixed +++ b/src/tools/clippy/tests/ui/needless_return.fixed @@ -86,21 +86,6 @@ fn borrows_but_not_last(value: bool) -> String { } } -macro_rules! needed_return { - ($e:expr) => { - if $e > 3 { - return; - } - }; -} - -fn test_return_in_macro() { - // This will return and the macro below won't be executed. Removing the `return` from the macro - // will change semantics. - needed_return!(10); - needed_return!(0); -} - fn main() { let _ = test_end_of_fn(); let _ = test_no_semicolon(); diff --git a/src/tools/clippy/tests/ui/needless_return.rs b/src/tools/clippy/tests/ui/needless_return.rs index 51061370dfe74..29f2bd1852af0 100644 --- a/src/tools/clippy/tests/ui/needless_return.rs +++ b/src/tools/clippy/tests/ui/needless_return.rs @@ -86,21 +86,6 @@ fn borrows_but_not_last(value: bool) -> String { } } -macro_rules! needed_return { - ($e:expr) => { - if $e > 3 { - return; - } - }; -} - -fn test_return_in_macro() { - // This will return and the macro below won't be executed. Removing the `return` from the macro - // will change semantics. - needed_return!(10); - needed_return!(0); -} - fn main() { let _ = test_end_of_fn(); let _ = test_no_semicolon(); diff --git a/src/tools/clippy/tests/ui/panic_in_result_fn_assertions.stderr b/src/tools/clippy/tests/ui/panic_in_result_fn_assertions.stderr index a17f043737d4e..86f61ad718a9c 100644 --- a/src/tools/clippy/tests/ui/panic_in_result_fn_assertions.stderr +++ b/src/tools/clippy/tests/ui/panic_in_result_fn_assertions.stderr @@ -14,7 +14,7 @@ note: return Err() instead of panicking --> $DIR/panic_in_result_fn_assertions.rs:9:9 | LL | assert!(x == 5, "wrong argument"); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) error: used `unimplemented!()`, `unreachable!()`, `todo!()`, `panic!()` or assertion in a function that returns `Result` diff --git a/src/tools/clippy/tests/ui/ptr_as_ptr.fixed b/src/tools/clippy/tests/ui/ptr_as_ptr.fixed deleted file mode 100644 index 8346a9454f4ee..0000000000000 --- a/src/tools/clippy/tests/ui/ptr_as_ptr.fixed +++ /dev/null @@ -1,50 +0,0 @@ -// run-rustfix - -#![warn(clippy::ptr_as_ptr)] -#![feature(custom_inner_attributes)] - -fn main() { - let ptr: *const u32 = &42_u32; - let mut_ptr: *mut u32 = &mut 42_u32; - - let _ = ptr.cast::(); - let _ = mut_ptr.cast::(); - - // Make sure the lint can handle the difference in their operator precedences. - unsafe { - let ptr_ptr: *const *const u32 = &ptr; - let _ = (*ptr_ptr).cast::(); - } - - // Changes in mutability. Do not lint this. - let _ = ptr as *mut i32; - let _ = mut_ptr as *const i32; - - // `pointer::cast` cannot perform unsized coercions unlike `as`. Do not lint this. - let ptr_of_array: *const [u32; 4] = &[1, 2, 3, 4]; - let _ = ptr_of_array as *const [u32]; - let _ = ptr_of_array as *const dyn std::fmt::Debug; - - // Ensure the lint doesn't produce unnecessary turbofish for inferred types. - let _: *const i32 = ptr.cast(); - let _: *mut i32 = mut_ptr.cast(); -} - -fn _msrv_1_37() { - #![clippy::msrv = "1.37"] - let ptr: *const u32 = &42_u32; - let mut_ptr: *mut u32 = &mut 42_u32; - - // `pointer::cast` was stabilized in 1.38. Do not lint this - let _ = ptr as *const i32; - let _ = mut_ptr as *mut i32; -} - -fn _msrv_1_38() { - #![clippy::msrv = "1.38"] - let ptr: *const u32 = &42_u32; - let mut_ptr: *mut u32 = &mut 42_u32; - - let _ = ptr.cast::(); - let _ = mut_ptr.cast::(); -} diff --git a/src/tools/clippy/tests/ui/ptr_as_ptr.rs b/src/tools/clippy/tests/ui/ptr_as_ptr.rs deleted file mode 100644 index b68d4bc0aaca1..0000000000000 --- a/src/tools/clippy/tests/ui/ptr_as_ptr.rs +++ /dev/null @@ -1,50 +0,0 @@ -// run-rustfix - -#![warn(clippy::ptr_as_ptr)] -#![feature(custom_inner_attributes)] - -fn main() { - let ptr: *const u32 = &42_u32; - let mut_ptr: *mut u32 = &mut 42_u32; - - let _ = ptr as *const i32; - let _ = mut_ptr as *mut i32; - - // Make sure the lint can handle the difference in their operator precedences. - unsafe { - let ptr_ptr: *const *const u32 = &ptr; - let _ = *ptr_ptr as *const i32; - } - - // Changes in mutability. Do not lint this. - let _ = ptr as *mut i32; - let _ = mut_ptr as *const i32; - - // `pointer::cast` cannot perform unsized coercions unlike `as`. Do not lint this. - let ptr_of_array: *const [u32; 4] = &[1, 2, 3, 4]; - let _ = ptr_of_array as *const [u32]; - let _ = ptr_of_array as *const dyn std::fmt::Debug; - - // Ensure the lint doesn't produce unnecessary turbofish for inferred types. - let _: *const i32 = ptr as *const _; - let _: *mut i32 = mut_ptr as _; -} - -fn _msrv_1_37() { - #![clippy::msrv = "1.37"] - let ptr: *const u32 = &42_u32; - let mut_ptr: *mut u32 = &mut 42_u32; - - // `pointer::cast` was stabilized in 1.38. Do not lint this - let _ = ptr as *const i32; - let _ = mut_ptr as *mut i32; -} - -fn _msrv_1_38() { - #![clippy::msrv = "1.38"] - let ptr: *const u32 = &42_u32; - let mut_ptr: *mut u32 = &mut 42_u32; - - let _ = ptr as *const i32; - let _ = mut_ptr as *mut i32; -} diff --git a/src/tools/clippy/tests/ui/ptr_as_ptr.stderr b/src/tools/clippy/tests/ui/ptr_as_ptr.stderr deleted file mode 100644 index 854906dc111df..0000000000000 --- a/src/tools/clippy/tests/ui/ptr_as_ptr.stderr +++ /dev/null @@ -1,46 +0,0 @@ -error: `as` casting between raw pointers without changing its mutability - --> $DIR/ptr_as_ptr.rs:10:13 - | -LL | let _ = ptr as *const i32; - | ^^^^^^^^^^^^^^^^^ help: try `pointer::cast`, a safer alternative: `ptr.cast::()` - | - = note: `-D clippy::ptr-as-ptr` implied by `-D warnings` - -error: `as` casting between raw pointers without changing its mutability - --> $DIR/ptr_as_ptr.rs:11:13 - | -LL | let _ = mut_ptr as *mut i32; - | ^^^^^^^^^^^^^^^^^^^ help: try `pointer::cast`, a safer alternative: `mut_ptr.cast::()` - -error: `as` casting between raw pointers without changing its mutability - --> $DIR/ptr_as_ptr.rs:16:17 - | -LL | let _ = *ptr_ptr as *const i32; - | ^^^^^^^^^^^^^^^^^^^^^^ help: try `pointer::cast`, a safer alternative: `(*ptr_ptr).cast::()` - -error: `as` casting between raw pointers without changing its mutability - --> $DIR/ptr_as_ptr.rs:29:25 - | -LL | let _: *const i32 = ptr as *const _; - | ^^^^^^^^^^^^^^^ help: try `pointer::cast`, a safer alternative: `ptr.cast()` - -error: `as` casting between raw pointers without changing its mutability - --> $DIR/ptr_as_ptr.rs:30:23 - | -LL | let _: *mut i32 = mut_ptr as _; - | ^^^^^^^^^^^^ help: try `pointer::cast`, a safer alternative: `mut_ptr.cast()` - -error: `as` casting between raw pointers without changing its mutability - --> $DIR/ptr_as_ptr.rs:48:13 - | -LL | let _ = ptr as *const i32; - | ^^^^^^^^^^^^^^^^^ help: try `pointer::cast`, a safer alternative: `ptr.cast::()` - -error: `as` casting between raw pointers without changing its mutability - --> $DIR/ptr_as_ptr.rs:49:13 - | -LL | let _ = mut_ptr as *mut i32; - | ^^^^^^^^^^^^^^^^^^^ help: try `pointer::cast`, a safer alternative: `mut_ptr.cast::()` - -error: aborting due to 7 previous errors - diff --git a/src/tools/clippy/tests/ui/try_err.fixed b/src/tools/clippy/tests/ui/try_err.fixed index 5b96bb59c5f18..652b611208b73 100644 --- a/src/tools/clippy/tests/ui/try_err.fixed +++ b/src/tools/clippy/tests/ui/try_err.fixed @@ -2,7 +2,7 @@ // aux-build:macro_rules.rs #![deny(clippy::try_err)] -#![allow(clippy::unnecessary_wraps, clippy::needless_question_mark)] +#![allow(clippy::unnecessary_wraps)] #[macro_use] extern crate macro_rules; diff --git a/src/tools/clippy/tests/ui/try_err.rs b/src/tools/clippy/tests/ui/try_err.rs index f220d697d2cd7..6bd479657b70b 100644 --- a/src/tools/clippy/tests/ui/try_err.rs +++ b/src/tools/clippy/tests/ui/try_err.rs @@ -2,7 +2,7 @@ // aux-build:macro_rules.rs #![deny(clippy::try_err)] -#![allow(clippy::unnecessary_wraps, clippy::needless_question_mark)] +#![allow(clippy::unnecessary_wraps)] #[macro_use] extern crate macro_rules; diff --git a/src/tools/clippy/tests/ui/unit_arg.rs b/src/tools/clippy/tests/ui/unit_arg.rs index b6a7bc5a1cc95..9ad16d365094e 100644 --- a/src/tools/clippy/tests/ui/unit_arg.rs +++ b/src/tools/clippy/tests/ui/unit_arg.rs @@ -5,8 +5,7 @@ unused_variables, clippy::unused_unit, clippy::unnecessary_wraps, - clippy::or_fun_call, - clippy::needless_question_mark + clippy::or_fun_call )] use std::fmt::Debug; diff --git a/src/tools/clippy/tests/ui/unit_arg.stderr b/src/tools/clippy/tests/ui/unit_arg.stderr index 094cff8c98591..c3a839a9bf812 100644 --- a/src/tools/clippy/tests/ui/unit_arg.stderr +++ b/src/tools/clippy/tests/ui/unit_arg.stderr @@ -1,5 +1,5 @@ error: passing a unit value to a function - --> $DIR/unit_arg.rs:31:5 + --> $DIR/unit_arg.rs:30:5 | LL | / foo({ LL | | 1; @@ -20,7 +20,7 @@ LL | foo(()); | error: passing a unit value to a function - --> $DIR/unit_arg.rs:34:5 + --> $DIR/unit_arg.rs:33:5 | LL | foo(foo(1)); | ^^^^^^^^^^^ @@ -32,7 +32,7 @@ LL | foo(()); | error: passing a unit value to a function - --> $DIR/unit_arg.rs:35:5 + --> $DIR/unit_arg.rs:34:5 | LL | / foo({ LL | | foo(1); @@ -54,7 +54,7 @@ LL | foo(()); | error: passing a unit value to a function - --> $DIR/unit_arg.rs:40:5 + --> $DIR/unit_arg.rs:39:5 | LL | / b.bar({ LL | | 1; @@ -74,7 +74,7 @@ LL | b.bar(()); | error: passing unit values to a function - --> $DIR/unit_arg.rs:43:5 + --> $DIR/unit_arg.rs:42:5 | LL | taking_multiple_units(foo(0), foo(1)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -87,7 +87,7 @@ LL | taking_multiple_units((), ()); | error: passing unit values to a function - --> $DIR/unit_arg.rs:44:5 + --> $DIR/unit_arg.rs:43:5 | LL | / taking_multiple_units(foo(0), { LL | | foo(1); @@ -110,7 +110,7 @@ LL | taking_multiple_units((), ()); | error: passing unit values to a function - --> $DIR/unit_arg.rs:48:5 + --> $DIR/unit_arg.rs:47:5 | LL | / taking_multiple_units( LL | | { @@ -140,7 +140,7 @@ LL | foo(2); ... error: passing a unit value to a function - --> $DIR/unit_arg.rs:59:13 + --> $DIR/unit_arg.rs:58:13 | LL | None.or(Some(foo(2))); | ^^^^^^^^^^^^ @@ -154,7 +154,7 @@ LL | }); | error: passing a unit value to a function - --> $DIR/unit_arg.rs:62:5 + --> $DIR/unit_arg.rs:61:5 | LL | foo(foo(())) | ^^^^^^^^^^^^ @@ -166,7 +166,7 @@ LL | foo(()) | error: passing a unit value to a function - --> $DIR/unit_arg.rs:95:5 + --> $DIR/unit_arg.rs:94:5 | LL | Some(foo(1)) | ^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/unknown_clippy_lints.stderr b/src/tools/clippy/tests/ui/unknown_clippy_lints.stderr index 94a667e589891..1b859043bb53b 100644 --- a/src/tools/clippy/tests/ui/unknown_clippy_lints.stderr +++ b/src/tools/clippy/tests/ui/unknown_clippy_lints.stderr @@ -1,58 +1,52 @@ -error: unknown lint: `clippy::All` - --> $DIR/unknown_clippy_lints.rs:5:10 - | -LL | #![allow(clippy::All)] - | ^^^^^^^^^^^ help: did you mean: `clippy::all` - | - = note: `-D unknown-lints` implied by `-D warnings` - -error: unknown lint: `clippy::CMP_NAN` - --> $DIR/unknown_clippy_lints.rs:6:9 - | -LL | #![warn(clippy::CMP_NAN)] - | ^^^^^^^^^^^^^^^ help: did you mean: `clippy::cmp_nan` - -error: unknown lint: `clippy::if_not_els` +error: unknown clippy lint: clippy::if_not_els --> $DIR/unknown_clippy_lints.rs:9:8 | LL | #[warn(clippy::if_not_els)] | ^^^^^^^^^^^^^^^^^^ help: did you mean: `clippy::if_not_else` + | + = note: `-D clippy::unknown-clippy-lints` implied by `-D warnings` -error: unknown lint: `clippy::UNNecsaRy_cAst` +error: unknown clippy lint: clippy::UNNecsaRy_cAst --> $DIR/unknown_clippy_lints.rs:10:8 | LL | #[warn(clippy::UNNecsaRy_cAst)] | ^^^^^^^^^^^^^^^^^^^^^^ help: did you mean: `clippy::unnecessary_cast` -error: unknown lint: `clippy::useles_transute` +error: unknown clippy lint: clippy::useles_transute --> $DIR/unknown_clippy_lints.rs:11:8 | LL | #[warn(clippy::useles_transute)] | ^^^^^^^^^^^^^^^^^^^^^^^ help: did you mean: `clippy::useless_transmute` -error: unknown lint: `clippy::dead_cod` +error: unknown clippy lint: clippy::dead_cod --> $DIR/unknown_clippy_lints.rs:13:8 | LL | #[warn(clippy::dead_cod)] | ^^^^^^^^^^^^^^^^ help: did you mean: `clippy::drop_copy` -error: unknown lint: `clippy::unused_colle` +error: unknown clippy lint: clippy::unused_colle --> $DIR/unknown_clippy_lints.rs:15:8 | LL | #[warn(clippy::unused_colle)] | ^^^^^^^^^^^^^^^^^^^^ help: did you mean: `clippy::unused_self` -error: unknown lint: `clippy::const_static_lifetim` +error: unknown clippy lint: clippy::const_static_lifetim --> $DIR/unknown_clippy_lints.rs:17:8 | LL | #[warn(clippy::const_static_lifetim)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: did you mean: `clippy::redundant_static_lifetimes` -error: unknown lint: `clippy::All` +error: unknown clippy lint: clippy::All --> $DIR/unknown_clippy_lints.rs:5:10 | LL | #![allow(clippy::All)] - | ^^^^^^^^^^^ help: did you mean: `clippy::all` + | ^^^^^^^^^^^ help: lowercase the lint name: `clippy::all` + +error: unknown clippy lint: clippy::CMP_NAN + --> $DIR/unknown_clippy_lints.rs:6:9 + | +LL | #![warn(clippy::CMP_NAN)] + | ^^^^^^^^^^^^^^^ help: lowercase the lint name: `clippy::cmp_nan` -error: aborting due to 9 previous errors +error: aborting due to 8 previous errors diff --git a/src/tools/clippy/tests/ui/vec_init_then_push.rs b/src/tools/clippy/tests/ui/vec_init_then_push.rs deleted file mode 100644 index 642ce5040096e..0000000000000 --- a/src/tools/clippy/tests/ui/vec_init_then_push.rs +++ /dev/null @@ -1,21 +0,0 @@ -#![allow(unused_variables)] -#![warn(clippy::vec_init_then_push)] - -fn main() { - let mut def_err: Vec = Default::default(); - def_err.push(0); - - let mut new_err = Vec::::new(); - new_err.push(1); - - let mut cap_err = Vec::with_capacity(2); - cap_err.push(0); - cap_err.push(1); - cap_err.push(2); - - let mut cap_ok = Vec::with_capacity(10); - cap_ok.push(0); - - new_err = Vec::new(); - new_err.push(0); -} diff --git a/src/tools/clippy/tests/ui/vec_init_then_push.stderr b/src/tools/clippy/tests/ui/vec_init_then_push.stderr deleted file mode 100644 index 819ed47d09919..0000000000000 --- a/src/tools/clippy/tests/ui/vec_init_then_push.stderr +++ /dev/null @@ -1,34 +0,0 @@ -error: calls to `push` immediately after creation - --> $DIR/vec_init_then_push.rs:5:5 - | -LL | / let mut def_err: Vec = Default::default(); -LL | | def_err.push(0); - | |____________________^ help: consider using the `vec![]` macro: `let mut def_err: Vec = vec![..];` - | - = note: `-D clippy::vec-init-then-push` implied by `-D warnings` - -error: calls to `push` immediately after creation - --> $DIR/vec_init_then_push.rs:8:5 - | -LL | / let mut new_err = Vec::::new(); -LL | | new_err.push(1); - | |____________________^ help: consider using the `vec![]` macro: `let mut new_err = vec![..];` - -error: calls to `push` immediately after creation - --> $DIR/vec_init_then_push.rs:11:5 - | -LL | / let mut cap_err = Vec::with_capacity(2); -LL | | cap_err.push(0); -LL | | cap_err.push(1); -LL | | cap_err.push(2); - | |____________________^ help: consider using the `vec![]` macro: `let mut cap_err = vec![..];` - -error: calls to `push` immediately after creation - --> $DIR/vec_init_then_push.rs:19:5 - | -LL | / new_err = Vec::new(); -LL | | new_err.push(0); - | |____________________^ help: consider using the `vec![]` macro: `new_err = vec![..];` - -error: aborting due to 4 previous errors - diff --git a/src/tools/clippy/tests/ui/wrong_self_convention.rs b/src/tools/clippy/tests/ui/wrong_self_convention.rs index 6cfc0fcb4cae4..5282eba74fd18 100644 --- a/src/tools/clippy/tests/ui/wrong_self_convention.rs +++ b/src/tools/clippy/tests/ui/wrong_self_convention.rs @@ -94,8 +94,7 @@ mod issue6307 { trait T: Sized { fn as_i32(self) {} fn as_u32(&self) {} - fn into_i32(self) {} - fn into_i32_ref(&self) {} + fn into_i32(&self) {} fn into_u32(self) {} fn is_i32(self) {} fn is_u32(&self) {} @@ -118,32 +117,7 @@ mod issue6307 { trait U { fn as_i32(self); fn as_u32(&self); - fn into_i32(self); - fn into_i32_ref(&self); - fn into_u32(self); - fn is_i32(self); - fn is_u32(&self); - fn to_i32(self); - fn to_u32(&self); - fn from_i32(self); - // check whether the lint can be allowed at the function level - #[allow(clippy::wrong_self_convention)] - fn from_cake(self); - - // test for false positives - fn as_(self); - fn into_(&self); - fn is_(self); - fn to_(self); - fn from_(self); - fn to_mut(&mut self); - } - - trait C: Copy { - fn as_i32(self); - fn as_u32(&self); - fn into_i32(self); - fn into_i32_ref(&self); + fn into_i32(&self); fn into_u32(self); fn is_i32(self); fn is_u32(&self); diff --git a/src/tools/clippy/tests/ui/wrong_self_convention.stderr b/src/tools/clippy/tests/ui/wrong_self_convention.stderr index 32bd9075bd5e1..86467eb0fc737 100644 --- a/src/tools/clippy/tests/ui/wrong_self_convention.stderr +++ b/src/tools/clippy/tests/ui/wrong_self_convention.stderr @@ -79,70 +79,58 @@ LL | fn as_i32(self) {} | ^^^^ error: methods called `into_*` usually take self by value; consider choosing a less ambiguous name - --> $DIR/wrong_self_convention.rs:98:25 + --> $DIR/wrong_self_convention.rs:97:21 | -LL | fn into_i32_ref(&self) {} - | ^^^^^ +LL | fn into_i32(&self) {} + | ^^^^^ error: methods called `is_*` usually take self by reference or no self; consider choosing a less ambiguous name - --> $DIR/wrong_self_convention.rs:100:19 + --> $DIR/wrong_self_convention.rs:99:19 | LL | fn is_i32(self) {} | ^^^^ error: methods called `to_*` usually take self by reference; consider choosing a less ambiguous name - --> $DIR/wrong_self_convention.rs:102:19 + --> $DIR/wrong_self_convention.rs:101:19 | LL | fn to_i32(self) {} | ^^^^ error: methods called `from_*` usually take no self; consider choosing a less ambiguous name - --> $DIR/wrong_self_convention.rs:104:21 + --> $DIR/wrong_self_convention.rs:103:21 | LL | fn from_i32(self) {} | ^^^^ error: methods called `as_*` usually take self by reference or self by mutable reference; consider choosing a less ambiguous name - --> $DIR/wrong_self_convention.rs:119:19 + --> $DIR/wrong_self_convention.rs:118:19 | LL | fn as_i32(self); | ^^^^ error: methods called `into_*` usually take self by value; consider choosing a less ambiguous name - --> $DIR/wrong_self_convention.rs:122:25 + --> $DIR/wrong_self_convention.rs:120:21 | -LL | fn into_i32_ref(&self); - | ^^^^^ +LL | fn into_i32(&self); + | ^^^^^ error: methods called `is_*` usually take self by reference or no self; consider choosing a less ambiguous name - --> $DIR/wrong_self_convention.rs:124:19 + --> $DIR/wrong_self_convention.rs:122:19 | LL | fn is_i32(self); | ^^^^ error: methods called `to_*` usually take self by reference; consider choosing a less ambiguous name - --> $DIR/wrong_self_convention.rs:126:19 + --> $DIR/wrong_self_convention.rs:124:19 | LL | fn to_i32(self); | ^^^^ error: methods called `from_*` usually take no self; consider choosing a less ambiguous name - --> $DIR/wrong_self_convention.rs:128:21 - | -LL | fn from_i32(self); - | ^^^^ - -error: methods called `into_*` usually take self by value; consider choosing a less ambiguous name - --> $DIR/wrong_self_convention.rs:146:25 - | -LL | fn into_i32_ref(&self); - | ^^^^^ - -error: methods called `from_*` usually take no self; consider choosing a less ambiguous name - --> $DIR/wrong_self_convention.rs:152:21 + --> $DIR/wrong_self_convention.rs:126:21 | LL | fn from_i32(self); | ^^^^ -error: aborting due to 24 previous errors +error: aborting due to 22 previous errors diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs index 5424889a8388b..43dbaeb46555c 100644 --- a/src/tools/compiletest/src/common.rs +++ b/src/tools/compiletest/src/common.rs @@ -198,9 +198,6 @@ pub struct Config { /// The Python executable to use for htmldocck. pub docck_python: String, - /// The jsondocck executable. - pub jsondocck_path: Option, - /// The LLVM `FileCheck` binary path. pub llvm_filecheck: Option, diff --git a/src/tools/compiletest/src/header/tests.rs b/src/tools/compiletest/src/header/tests.rs index ec99fde0df9c2..4bcbd89f09510 100644 --- a/src/tools/compiletest/src/header/tests.rs +++ b/src/tools/compiletest/src/header/tests.rs @@ -45,7 +45,6 @@ fn config() -> Config { "--rustc-path=", "--lldb-python=", "--docck-python=", - "--jsondocck-path=", "--src-base=", "--build-base=", "--stage-id=stage2", diff --git a/src/tools/compiletest/src/main.rs b/src/tools/compiletest/src/main.rs index 688cf930033ef..aefcfe222e509 100644 --- a/src/tools/compiletest/src/main.rs +++ b/src/tools/compiletest/src/main.rs @@ -60,7 +60,6 @@ pub fn parse_config(args: Vec) -> Config { .optopt("", "rust-demangler-path", "path to rust-demangler to use in tests", "PATH") .reqopt("", "lldb-python", "path to python to use for doc tests", "PATH") .reqopt("", "docck-python", "path to python to use for doc tests", "PATH") - .optopt("", "jsondocck-path", "path to jsondocck to use for doc tests", "PATH") .optopt("", "valgrind-path", "path to Valgrind executable for Valgrind tests", "PROGRAM") .optflag("", "force-valgrind", "fail if Valgrind tests cannot be run under Valgrind") .optopt("", "run-clang-based-tests-with", "path to Clang executable", "PATH") @@ -208,7 +207,6 @@ pub fn parse_config(args: Vec) -> Config { rust_demangler_path: matches.opt_str("rust-demangler-path").map(PathBuf::from), lldb_python: matches.opt_str("lldb-python").unwrap(), docck_python: matches.opt_str("docck-python").unwrap(), - jsondocck_path: matches.opt_str("jsondocck-path"), valgrind_path: matches.opt_str("valgrind-path"), force_valgrind: matches.opt_present("force-valgrind"), run_clang_based_tests_with: matches.opt_str("run-clang-based-tests-with"), diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 5608ff98417cd..9f31b3ae1b1a6 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -2490,27 +2490,27 @@ impl<'test> TestCx<'test> { let mut json_out = out_dir.join(self.testpaths.file.file_stem().unwrap()); json_out.set_extension("json"); let res = self.cmd2procres( - Command::new(self.config.jsondocck_path.as_ref().unwrap()) - .arg("--doc-dir") - .arg(root.join(&out_dir)) - .arg("--template") - .arg(&self.testpaths.file), + Command::new(&self.config.docck_python) + .arg(root.join("src/test/rustdoc-json/check_missing_items.py")) + .arg(&json_out), ); if !res.status.success() { - self.fatal_proc_rec("jsondocck failed!", &res) + self.fatal_proc_rec("check_missing_items failed!", &res); } - let mut json_out = out_dir.join(self.testpaths.file.file_stem().unwrap()); - json_out.set_extension("json"); + let mut expected = self.testpaths.file.clone(); + expected.set_extension("expected"); let res = self.cmd2procres( Command::new(&self.config.docck_python) - .arg(root.join("src/etc/check_missing_items.py")) - .arg(&json_out), + .arg(root.join("src/test/rustdoc-json/compare.py")) + .arg(&expected) + .arg(&json_out) + .arg(&expected.parent().unwrap()), ); if !res.status.success() { - self.fatal_proc_rec("check_missing_items failed!", &res); + self.fatal_proc_rec("compare failed!", &res); } } diff --git a/src/tools/jsondocck/Cargo.toml b/src/tools/jsondocck/Cargo.toml deleted file mode 100644 index 97052ef58d6f2..0000000000000 --- a/src/tools/jsondocck/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "jsondocck" -version = "0.1.0" -authors = ["Rune Tynan "] -edition = "2018" - -[dependencies] -jsonpath_lib = "0.2" -getopts = "0.2" -regex = "1.4" -lazy_static = "1.4" -shlex = "0.1" -serde = "1.0" -serde_json = "1.0" diff --git a/src/tools/jsondocck/src/cache.rs b/src/tools/jsondocck/src/cache.rs deleted file mode 100644 index b742f0eb3ee55..0000000000000 --- a/src/tools/jsondocck/src/cache.rs +++ /dev/null @@ -1,69 +0,0 @@ -use crate::error::CkError; -use serde_json::Value; -use std::collections::HashMap; -use std::path::{Path, PathBuf}; -use std::{fs, io}; - -#[derive(Debug)] -pub struct Cache { - root: PathBuf, - files: HashMap, - values: HashMap, - last_path: Option, -} - -impl Cache { - /// Create a new cache, used to read files only once and otherwise store their contents. - pub fn new(doc_dir: &str) -> Cache { - Cache { - root: Path::new(doc_dir).to_owned(), - files: HashMap::new(), - values: HashMap::new(), - last_path: None, - } - } - - fn resolve_path(&mut self, path: &String) -> PathBuf { - if path != "-" { - let resolve = self.root.join(path); - self.last_path = Some(resolve.clone()); - resolve - } else { - self.last_path.as_ref().unwrap().clone() - } - } - - fn read_file(&mut self, path: PathBuf) -> Result { - if let Some(f) = self.files.get(&path) { - return Ok(f.clone()); - } - - let file = fs::read_to_string(&path)?; - - self.files.insert(path, file.clone()); - - Ok(file) - } - - /// Get the text from a file. If called multiple times, the file will only be read once - pub fn get_file(&mut self, path: &String) -> Result { - let path = self.resolve_path(path); - self.read_file(path) - } - - /// Parse the JSON from a file. If called multiple times, the file will only be read once. - pub fn get_value(&mut self, path: &String) -> Result { - let path = self.resolve_path(path); - - if let Some(v) = self.values.get(&path) { - return Ok(v.clone()); - } - - let content = self.read_file(path.clone())?; - let val = serde_json::from_str::(&content)?; - - self.values.insert(path, val.clone()); - - Ok(val) - } -} diff --git a/src/tools/jsondocck/src/config.rs b/src/tools/jsondocck/src/config.rs deleted file mode 100644 index 9b3ba3f3fbe39..0000000000000 --- a/src/tools/jsondocck/src/config.rs +++ /dev/null @@ -1,37 +0,0 @@ -use getopts::Options; - -#[derive(Debug)] -pub struct Config { - /// The directory documentation output was generated in - pub doc_dir: String, - /// The file documentation was generated for, with docck commands to check - pub template: String, -} - -/// Create a Config from a vector of command-line arguments -pub fn parse_config(args: Vec) -> Config { - let mut opts = Options::new(); - opts.reqopt("", "doc-dir", "Path to the documentation directory", "PATH") - .reqopt("", "template", "Path to the template file", "PATH") - .optflag("h", "help", "show this message"); - - let (argv0, args_) = args.split_first().unwrap(); - if args.len() == 1 { - let message = format!("Usage: {}