diff --git a/RELEASES.md b/RELEASES.md index 427aa71b4b5dc..7e18f1befddec 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -1,3 +1,100 @@ +Version 1.42.0 (2020-03-12) +========================== + +Language +-------- +- [You can now use the slice pattern syntax with subslices.][67712] e.g. + ```rust + fn foo(words: &[&str]) { + match words { + ["Hello", "World", "!", ..] => println!("Hello World!"), + ["Foo", "Bar", ..] => println!("Baz"), + rest => println!("{:?}", rest), + } + } + ``` +- [You can now use `#[repr(transparent)]` on univariant `enum`s.][68122] Meaning + that you can create an enum that has the exact layout and ABI of the type + it contains. +- [There are some *syntax-only* changes:][67131] + - `default` is syntactically allowed before items in `trait` definitions. + - Items in `impl`s (i.e. `const`s, `type`s, and `fn`s) may syntactically + leave out their bodies in favor of `;`. + - Bounds on associated types in `impl`s are now syntactically allowed + (e.g. `type Foo: Ord;`). + - `...` (the C-variadic type) may occur syntactically directly as the type of + any function parameter. + + These are still rejected *semantically*, so you will likely receive an error + but these changes can be seen and parsed by procedural macros and + conditional compilation. + +Compiler +-------- +- [Added tier 2\* support for `armv7a-none-eabi`.][68253] +- [Added tier 2 support for `riscv64gc-unknown-linux-gnu`.][68339] +- [`Option::{expect,unwrap}` and + `Result::{expect, expect_err, unwrap, unwrap_err}` now produce panic messages + pointing to the location where they were called, rather than + `core`'s internals. ][67887] + +\* Refer to Rust's [platform support page][forge-platform-support] for more +information on Rust's tiered platform support. + +Libraries +--------- +- [`iter::Empty` now implements `Send` and `Sync` for any `T`.][68348] +- [`Pin::{map_unchecked, map_unchecked_mut}` no longer require the return type + to implement `Sized`.][67935] +- [`io::Cursor` now derives `PartialEq` and `Eq`.][67233] +- [`Layout::new` is now `const`.][66254] +- [Added Standard Library support for `riscv64gc-unknown-linux-gnu`.][66899] + + +Stabilized APIs +--------------- +- [`CondVar::wait_while`] +- [`CondVar::wait_timeout_while`] +- [`DebugMap::key`] +- [`DebugMap::value`] +- [`ManuallyDrop::take`] +- [`matches!`] +- [`ptr::slice_from_raw_parts_mut`] +- [`ptr::slice_from_raw_parts`] + +Cargo +----- +- [You no longer need to include `extern crate proc_macro;` to be able to + `use proc_macro;` in the `2018` edition.][cargo/7700] + +Compatibility Notes +------------------- +- [`Error::description` has been deprecated, and its use will now produce a + warning.][66919] It's recommended to use `Display`/`to_string` instead. + +[68253]: https://github.com/rust-lang/rust/pull/68253/ +[68348]: https://github.com/rust-lang/rust/pull/68348/ +[67935]: https://github.com/rust-lang/rust/pull/67935/ +[68339]: https://github.com/rust-lang/rust/pull/68339/ +[68122]: https://github.com/rust-lang/rust/pull/68122/ +[67712]: https://github.com/rust-lang/rust/pull/67712/ +[67887]: https://github.com/rust-lang/rust/pull/67887/ +[67131]: https://github.com/rust-lang/rust/pull/67131/ +[67233]: https://github.com/rust-lang/rust/pull/67233/ +[66899]: https://github.com/rust-lang/rust/pull/66899/ +[66919]: https://github.com/rust-lang/rust/pull/66919/ +[66254]: https://github.com/rust-lang/rust/pull/66254/ +[cargo/7700]: https://github.com/rust-lang/cargo/pull/7700 +[`DebugMap::key`]: https://doc.rust-lang.org/stable/std/fmt/struct.DebugMap.html#method.key +[`DebugMap::value`]: https://doc.rust-lang.org/stable/std/fmt/struct.DebugMap.html#method.value +[`ManuallyDrop::take`]: https://doc.rust-lang.org/stable/std/mem/struct.ManuallyDrop.html#method.take +[`matches!`]: https://doc.rust-lang.org/stable/std/macro.matches.html +[`ptr::slice_from_raw_parts_mut`]: https://doc.rust-lang.org/stable/std/ptr/fn.slice_from_raw_parts_mut.html +[`ptr::slice_from_raw_parts`]: https://doc.rust-lang.org/stable/std/ptr/fn.slice_from_raw_parts.html +[`CondVar::wait_while`]: https://doc.rust-lang.org/stable/std/sync/struct.Condvar.html#method.wait_while +[`CondVar::wait_timeout_while`]: https://doc.rust-lang.org/stable/std/sync/struct.Condvar.html#method.wait_timeout_while + + Version 1.41.1 (2020-02-27) =========================== @@ -8,6 +105,7 @@ Version 1.41.1 (2020-02-27) [69225]: https://github.com/rust-lang/rust/issues/69225 [69145]: https://github.com/rust-lang/rust/pull/69145 + Version 1.41.0 (2020-01-30) =========================== diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index 3ac4bd82a3a10..81b0e9817d261 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -825,7 +825,7 @@ impl From> for Box<[u8]> { } } -#[unstable(feature = "boxed_slice_try_from", issue = "none")] +#[stable(feature = "boxed_slice_try_from", since = "1.43.0")] impl TryFrom> for Box<[T; N]> where [T; N]: LengthAtMost32, diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 9dc5447397f09..6ee128f4fa1d2 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -1453,7 +1453,7 @@ impl From> for Rc<[T]> { } } -#[unstable(feature = "boxed_slice_try_from", issue = "none")] +#[stable(feature = "boxed_slice_try_from", since = "1.43.0")] impl TryFrom> for Rc<[T; N]> where [T; N]: LengthAtMost32, diff --git a/src/liballoc/sync.rs b/src/liballoc/sync.rs index fd285242d5be4..9bd708c0f595c 100644 --- a/src/liballoc/sync.rs +++ b/src/liballoc/sync.rs @@ -2002,7 +2002,7 @@ impl From> for Arc<[T]> { } } -#[unstable(feature = "boxed_slice_try_from", issue = "none")] +#[stable(feature = "boxed_slice_try_from", since = "1.43.0")] impl TryFrom> for Arc<[T; N]> where [T; N]: LengthAtMost32, diff --git a/src/librustc/hir/map/mod.rs b/src/librustc/hir/map/mod.rs index adda0cde24fc0..f7301280acd69 100644 --- a/src/librustc/hir/map/mod.rs +++ b/src/librustc/hir/map/mod.rs @@ -153,17 +153,13 @@ pub struct Map<'hir> { hir_to_node_id: FxHashMap, } -struct ParentHirIterator<'map, 'hir> { +/// An iterator that walks up the ancestor tree of a given `HirId`. +/// Constructed using `tcx.hir().parent_iter(hir_id)`. +pub struct ParentHirIterator<'map, 'hir> { current_id: HirId, map: &'map Map<'hir>, } -impl<'map, 'hir> ParentHirIterator<'map, 'hir> { - fn new(current_id: HirId, map: &'map Map<'hir>) -> Self { - Self { current_id, map } - } -} - impl<'hir> Iterator for ParentHirIterator<'_, 'hir> { type Item = (HirId, Node<'hir>); @@ -618,6 +614,12 @@ impl<'hir> Map<'hir> { self.find_entry(hir_id).and_then(|x| x.parent_node()).unwrap_or(hir_id) } + /// Returns an iterator for the nodes in the ancestor tree of the `current_id` + /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`. + pub fn parent_iter(&self, current_id: HirId) -> ParentHirIterator<'_, 'hir> { + ParentHirIterator { current_id, map: self } + } + /// Checks if the node is an argument. An argument is a local variable whose /// immediate parent is an item or a closure. pub fn is_argument(&self, id: HirId) -> bool { @@ -684,7 +686,7 @@ impl<'hir> Map<'hir> { /// } /// ``` pub fn get_return_block(&self, id: HirId) -> Option { - let mut iter = ParentHirIterator::new(id, &self).peekable(); + let mut iter = self.parent_iter(id).peekable(); let mut ignore_tail = false; if let Some(entry) = self.find_entry(id) { if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = entry.node { @@ -731,7 +733,7 @@ impl<'hir> Map<'hir> { /// in the HIR which is recorded by the map and is an item, either an item /// in a module, trait, or impl. pub fn get_parent_item(&self, hir_id: HirId) -> HirId { - for (hir_id, node) in ParentHirIterator::new(hir_id, &self) { + for (hir_id, node) in self.parent_iter(hir_id) { match node { Node::Crate | Node::Item(_) @@ -753,7 +755,7 @@ impl<'hir> Map<'hir> { /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no /// module parent is in this map. pub fn get_module_parent_node(&self, hir_id: HirId) -> HirId { - for (hir_id, node) in ParentHirIterator::new(hir_id, &self) { + for (hir_id, node) in self.parent_iter(hir_id) { if let Node::Item(&Item { kind: ItemKind::Mod(_), .. }) = node { return hir_id; } @@ -767,7 +769,7 @@ impl<'hir> Map<'hir> { /// 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_match_if_cause(&self, hir_id: HirId) -> Option<&'hir Expr<'hir>> { - for (_, node) in ParentHirIterator::new(hir_id, &self) { + for (_, node) in self.parent_iter(hir_id) { match node { Node::Item(_) | Node::ForeignItem(_) | Node::TraitItem(_) | Node::ImplItem(_) => { break; @@ -788,7 +790,7 @@ impl<'hir> Map<'hir> { /// Returns the nearest enclosing scope. A scope is roughly an item or block. pub fn get_enclosing_scope(&self, hir_id: HirId) -> Option { - for (hir_id, node) in ParentHirIterator::new(hir_id, &self) { + for (hir_id, node) in self.parent_iter(hir_id) { if match node { Node::Item(i) => match i.kind { ItemKind::Fn(..) diff --git a/src/librustc_builtin_macros/asm.rs b/src/librustc_builtin_macros/asm.rs index 4723544316faf..9f98cf253c977 100644 --- a/src/librustc_builtin_macros/asm.rs +++ b/src/librustc_builtin_macros/asm.rs @@ -182,7 +182,7 @@ fn parse_inline_asm<'a>( }; let is_rw = output.is_some(); - let is_indirect = constraint_str.contains("*"); + let is_indirect = constraint_str.contains('*'); outputs.push(ast::InlineAsmOutput { constraint: output.unwrap_or(constraint), expr, @@ -199,7 +199,7 @@ fn parse_inline_asm<'a>( let constraint = parse_asm_str(&mut p)?; - if constraint.as_str().starts_with("=") { + if constraint.as_str().starts_with('=') { struct_span_err!( cx.parse_sess.span_diagnostic, p.prev_span, @@ -207,7 +207,7 @@ fn parse_inline_asm<'a>( "input operand constraint contains '='" ) .emit(); - } else if constraint.as_str().starts_with("+") { + } else if constraint.as_str().starts_with('+') { struct_span_err!( cx.parse_sess.span_diagnostic, p.prev_span, @@ -234,7 +234,7 @@ fn parse_inline_asm<'a>( if OPTIONS.iter().any(|&opt| s == opt) { cx.span_warn(p.prev_span, "expected a clobber, found an option"); - } else if s.as_str().starts_with("{") || s.as_str().ends_with("}") { + } else if s.as_str().starts_with('{') || s.as_str().ends_with('}') { struct_span_err!( cx.parse_sess.span_diagnostic, p.prev_span, diff --git a/src/librustc_builtin_macros/format.rs b/src/librustc_builtin_macros/format.rs index a9298abe2d759..ad47e09aa671a 100644 --- a/src/librustc_builtin_macros/format.rs +++ b/src/librustc_builtin_macros/format.rs @@ -158,7 +158,7 @@ fn parse_args<'a>( } // accept trailing commas if p.token.is_ident() && p.look_ahead(1, |t| *t == token::Eq) { named = true; - let name = if let token::Ident(name, _) = p.token.kind { + let name = if let token::Ident(name, _) = p.normalized_token.kind { p.bump(); name } else { @@ -894,7 +894,7 @@ pub fn expand_preparsed_format_args( }; let (is_literal, fmt_snippet) = match ecx.source_map().span_to_snippet(fmt_sp) { - Ok(s) => (s.starts_with("\"") || s.starts_with("r#"), Some(s)), + Ok(s) => (s.starts_with('"') || s.starts_with("r#"), Some(s)), _ => (false, None), }; diff --git a/src/librustc_codegen_llvm/back/lto.rs b/src/librustc_codegen_llvm/back/lto.rs index d7297ed41769c..6b136aeb8d9fb 100644 --- a/src/librustc_codegen_llvm/back/lto.rs +++ b/src/librustc_codegen_llvm/back/lto.rs @@ -917,7 +917,7 @@ impl ThinLTOImports { if line.is_empty() { let importing_module = current_module.take().expect("Importing module not set"); imports.insert(importing_module, mem::replace(&mut current_imports, vec![])); - } else if line.starts_with(" ") { + } else if line.starts_with(' ') { // Space marks an imported module assert_ne!(current_module, None); current_imports.push(line.trim().to_string()); diff --git a/src/librustc_codegen_utils/link.rs b/src/librustc_codegen_utils/link.rs index 4dab4545b422f..92cbc42388d61 100644 --- a/src/librustc_codegen_utils/link.rs +++ b/src/librustc_codegen_utils/link.rs @@ -78,7 +78,7 @@ pub fn find_crate_name(sess: Option<&Session>, attrs: &[ast::Attribute], input: } if let Input::File(ref path) = *input { if let Some(s) = path.file_stem().and_then(|s| s.to_str()) { - if s.starts_with("-") { + if s.starts_with('-') { let msg = format!( "crate names cannot start with a `-`, but \ `{}` has a leading hyphen", diff --git a/src/librustc_driver/args.rs b/src/librustc_driver/args.rs index 5e2c43596dbeb..5686819c61b40 100644 --- a/src/librustc_driver/args.rs +++ b/src/librustc_driver/args.rs @@ -4,7 +4,7 @@ use std::fs; use std::io; pub fn arg_expand(arg: String) -> Result, Error> { - if arg.starts_with("@") { + if arg.starts_with('@') { let path = &arg[1..]; let file = match fs::read_to_string(path) { Ok(file) => file, diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index f68ea7e077032..b00b1656bf750 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -521,7 +521,7 @@ fn stdout_isatty() -> bool { fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) { let normalised = - if code.starts_with("E") { code.to_string() } else { format!("E{0:0>4}", code) }; + if code.starts_with('E') { code.to_string() } else { format!("E{0:0>4}", code) }; match registry.find_description(&normalised) { Some(ref description) => { let mut is_in_code_block = false; @@ -601,7 +601,7 @@ impl RustcDefaultCalls { }); compiler.codegen_backend().link(&sess, Box::new(codegen_results), &outputs) } else { - sess.fatal(&format!("rlink must be a file")) + sess.fatal("rlink must be a file") } } diff --git a/src/librustc_expand/expand.rs b/src/librustc_expand/expand.rs index 8ed7bbf6e1276..dff243a51b39f 100644 --- a/src/librustc_expand/expand.rs +++ b/src/librustc_expand/expand.rs @@ -503,13 +503,12 @@ impl<'a, 'b> MacroExpander<'a, 'b> { } fn error_derive_forbidden_on_non_adt(&self, derives: &[Path], item: &Annotatable) { - let attr = - attr::find_by_name(item.attrs(), sym::derive).expect("`derive` attribute should exist"); - let span = attr.span; + let attr = attr::find_by_name(item.attrs(), sym::derive); + let span = attr.map_or(item.span(), |attr| attr.span); let mut err = self .cx .struct_span_err(span, "`derive` may only be applied to structs, enums and unions"); - if let ast::AttrStyle::Inner = attr.style { + if let Some(ast::Attribute { style: ast::AttrStyle::Inner, .. }) = attr { let trait_list = derives.iter().map(|t| pprust::path_to_string(t)).collect::>(); let suggestion = format!("#[derive({})]", trait_list.join(", ")); err.span_suggestion( @@ -1669,10 +1668,9 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { } } } else { - let mut err = self.cx.struct_span_err( - it.span(), - &format!("expected path to external documentation"), - ); + let mut err = self + .cx + .struct_span_err(it.span(), "expected path to external documentation"); // Check if the user erroneously used `doc(include(...))` syntax. let literal = it.meta_item_list().and_then(|list| { diff --git a/src/librustc_expand/mbe/macro_parser.rs b/src/librustc_expand/mbe/macro_parser.rs index 6599e92222c75..2a53d600c5bcf 100644 --- a/src/librustc_expand/mbe/macro_parser.rs +++ b/src/librustc_expand/mbe/macro_parser.rs @@ -753,6 +753,12 @@ pub(super) fn parse_tt(parser: &mut Cow<'_, Parser<'_>>, ms: &[TokenTree]) -> Na fn get_macro_name(token: &Token) -> Option<(Name, bool)> { match token.kind { token::Ident(name, is_raw) if name != kw::Underscore => Some((name, is_raw)), + token::Interpolated(ref nt) => match **nt { + token::NtIdent(ident, is_raw) if ident.name != kw::Underscore => { + Some((ident.name, is_raw)) + } + _ => None, + }, _ => None, } } @@ -883,9 +889,8 @@ fn parse_nt_inner<'a>(p: &mut Parser<'a>, sp: Span, name: Symbol) -> PResult<'a, // this could be handled like a token, since it is one sym::ident => { if let Some((name, is_raw)) = get_macro_name(&p.token) { - let span = p.token.span; p.bump(); - token::NtIdent(Ident::new(name, span), is_raw) + token::NtIdent(Ident::new(name, p.normalized_prev_token.span), is_raw) } else { let token_str = pprust::token_to_string(&p.token); let msg = &format!("expected ident, found {}", &token_str); diff --git a/src/librustc_expand/proc_macro_server.rs b/src/librustc_expand/proc_macro_server.rs index afaba6bf315ed..ce4e262068c56 100644 --- a/src/librustc_expand/proc_macro_server.rs +++ b/src/librustc_expand/proc_macro_server.rs @@ -205,7 +205,7 @@ impl ToInternal for TokenTree { TokenTree::Literal(self::Literal { lit: token::Lit { kind: token::Integer, symbol, suffix }, span, - }) if symbol.as_str().starts_with("-") => { + }) if symbol.as_str().starts_with('-') => { let minus = BinOp(BinOpToken::Minus); let symbol = Symbol::intern(&symbol.as_str()[1..]); let integer = TokenKind::lit(token::Integer, symbol, suffix); @@ -216,7 +216,7 @@ impl ToInternal for TokenTree { TokenTree::Literal(self::Literal { lit: token::Lit { kind: token::Float, symbol, suffix }, span, - }) if symbol.as_str().starts_with("-") => { + }) if symbol.as_str().starts_with('-') => { let minus = BinOp(BinOpToken::Minus); let symbol = Symbol::intern(&symbol.as_str()[1..]); let float = TokenKind::lit(token::Float, symbol, suffix); diff --git a/src/librustc_hir/hir.rs b/src/librustc_hir/hir.rs index 2e99998c627bf..6cbd8400783b4 100644 --- a/src/librustc_hir/hir.rs +++ b/src/librustc_hir/hir.rs @@ -1504,7 +1504,7 @@ pub fn is_range_literal(sm: &SourceMap, expr: &Expr<'_>) -> bool { let end_point = sm.end_point(*span); if let Ok(end_string) = sm.span_to_snippet(end_point) { - !(end_string.ends_with("}") || end_string.ends_with(")")) + !(end_string.ends_with('}') || end_string.ends_with(')')) } else { false } diff --git a/src/librustc_incremental/assert_module_sources.rs b/src/librustc_incremental/assert_module_sources.rs index 70abb38278add..4dd08b517e1f2 100644 --- a/src/librustc_incremental/assert_module_sources.rs +++ b/src/librustc_incremental/assert_module_sources.rs @@ -81,10 +81,7 @@ impl AssertModuleSource<'tcx> { if !self.tcx.sess.opts.debugging_opts.query_dep_graph { self.tcx.sess.span_fatal( attr.span, - &format!( - "found CGU-reuse attribute but `-Zquery-dep-graph` \ - was not specified" - ), + "found CGU-reuse attribute but `-Zquery-dep-graph` was not specified", ); } @@ -107,7 +104,7 @@ impl AssertModuleSource<'tcx> { } // Split of the "special suffix" if there is one. - let (user_path, cgu_special_suffix) = if let Some(index) = user_path.rfind(".") { + let (user_path, cgu_special_suffix) = if let Some(index) = user_path.rfind('.') { (&user_path[..index], Some(&user_path[index + 1..])) } else { (&user_path[..], None) diff --git a/src/librustc_incremental/persist/dirty_clean.rs b/src/librustc_incremental/persist/dirty_clean.rs index 1fa57f1ecf26d..f6e2956e5b2fc 100644 --- a/src/librustc_incremental/persist/dirty_clean.rs +++ b/src/librustc_incremental/persist/dirty_clean.rs @@ -537,10 +537,7 @@ impl FindAllAttrs<'tcx> { if !checked_attrs.contains(&attr.id) { self.tcx.sess.span_err( attr.span, - &format!( - "found unchecked \ - `#[rustc_dirty]` / `#[rustc_clean]` attribute" - ), + "found unchecked `#[rustc_dirty]` / `#[rustc_clean]` attribute", ); } } diff --git a/src/librustc_incremental/persist/fs.rs b/src/librustc_incremental/persist/fs.rs index ba20006d73ccc..8548ad392d2dd 100644 --- a/src/librustc_incremental/persist/fs.rs +++ b/src/librustc_incremental/persist/fs.rs @@ -152,7 +152,7 @@ pub fn lock_file_path(session_dir: &Path) -> PathBuf { let directory_name = session_dir.file_name().unwrap().to_string_lossy(); assert_no_characters_lost(&directory_name); - let dash_indices: Vec<_> = directory_name.match_indices("-").map(|(idx, _)| idx).collect(); + let dash_indices: Vec<_> = directory_name.match_indices('-').map(|(idx, _)| idx).collect(); if dash_indices.len() != 3 { bug!( "Encountered incremental compilation session directory with \ @@ -342,7 +342,7 @@ pub fn finalize_session_directory(sess: &Session, svh: Svh) { // Keep the 's-{timestamp}-{random-number}' prefix, but replace the // '-working' part with the SVH of the crate - let dash_indices: Vec<_> = old_sub_dir_name.match_indices("-").map(|(idx, _)| idx).collect(); + let dash_indices: Vec<_> = old_sub_dir_name.match_indices('-').map(|(idx, _)| idx).collect(); if dash_indices.len() != 3 { bug!( "Encountered incremental compilation session directory with \ @@ -594,7 +594,7 @@ fn extract_timestamp_from_session_dir(directory_name: &str) -> Result = directory_name.match_indices("-").map(|(idx, _)| idx).collect(); + let dash_indices: Vec<_> = directory_name.match_indices('-').map(|(idx, _)| idx).collect(); if dash_indices.len() != 3 { return Err(()); } diff --git a/src/librustc_infer/traits/coherence.rs b/src/librustc_infer/traits/coherence.rs index d94231653abd4..0dec5ae6da57a 100644 --- a/src/librustc_infer/traits/coherence.rs +++ b/src/librustc_infer/traits/coherence.rs @@ -39,10 +39,10 @@ pub struct OverlapResult<'tcx> { } pub fn add_placeholder_note(err: &mut rustc_errors::DiagnosticBuilder<'_>) { - err.note(&format!( + err.note( "this behavior recently changed as a result of a bug fix; \ - see rust-lang/rust#56105 for details" - )); + see rust-lang/rust#56105 for details", + ); } /// If there are types that satisfy both impls, invokes `on_overlap` diff --git a/src/librustc_infer/traits/error_reporting/mod.rs b/src/librustc_infer/traits/error_reporting/mod.rs index 9bfa219695096..ca5f6b8b7b208 100644 --- a/src/librustc_infer/traits/error_reporting/mod.rs +++ b/src/librustc_infer/traits/error_reporting/mod.rs @@ -935,9 +935,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { // Already reported in the query. ConstEvalFailure(ErrorHandled::Reported) => { - self.tcx - .sess - .delay_span_bug(span, &format!("constant in type had an ignored error")); + self.tcx.sess.delay_span_bug(span, "constant in type had an ignored error"); return; } diff --git a/src/librustc_infer/traits/wf.rs b/src/librustc_infer/traits/wf.rs index 993eb41b9b1a7..980a3f0478134 100644 --- a/src/librustc_infer/traits/wf.rs +++ b/src/librustc_infer/traits/wf.rs @@ -232,10 +232,8 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { // found type `()` if let Some(hir::ItemKind::Impl { items, .. }) = item.map(|i| &i.kind) { let trait_assoc_item = tcx.associated_item(proj.projection_def_id()); - if let Some(impl_item) = items - .iter() - .filter(|item| item.ident == trait_assoc_item.ident) - .next() + if let Some(impl_item) = + items.iter().find(|item| item.ident == trait_assoc_item.ident) { cause.span = impl_item.span; cause.code = traits::AssocTypeBound(Box::new(AssocTypeBoundData { @@ -285,13 +283,11 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { { if let Some((impl_item, trait_assoc_item)) = trait_assoc_items .iter() - .filter(|i| i.def_id == *item_def_id) - .next() + .find(|i| i.def_id == *item_def_id) .and_then(|trait_assoc_item| { items .iter() - .filter(|i| i.ident == trait_assoc_item.ident) - .next() + .find(|i| i.ident == trait_assoc_item.ident) .map(|impl_item| (impl_item, trait_assoc_item)) }) { diff --git a/src/librustc_interface/util.rs b/src/librustc_interface/util.rs index 781b33bd94ce0..b816673a5674e 100644 --- a/src/librustc_interface/util.rs +++ b/src/librustc_interface/util.rs @@ -244,7 +244,7 @@ pub fn get_codegen_backend(sess: &Session) -> Box { .as_ref() .unwrap_or(&sess.target.target.options.codegen_backend); let backend = match &codegen_name[..] { - filename if filename.contains(".") => load_backend_from_dylib(filename.as_ref()), + filename if filename.contains('.') => load_backend_from_dylib(filename.as_ref()), codegen_name => get_builtin_codegen_backend(codegen_name), }; diff --git a/src/librustc_llvm/build.rs b/src/librustc_llvm/build.rs index 405ce0307cd82..9b4f03b3fb64b 100644 --- a/src/librustc_llvm/build.rs +++ b/src/librustc_llvm/build.rs @@ -178,7 +178,7 @@ fn main() { for lib in output(&mut cmd).split_whitespace() { let name = if lib.starts_with("-l") { &lib[2..] - } else if lib.starts_with("-") { + } else if lib.starts_with('-') { &lib[1..] } else if Path::new(lib).exists() { // On MSVC llvm-config will print the full name to libraries, but diff --git a/src/librustc_metadata/creader.rs b/src/librustc_metadata/creader.rs index 4c4383aa603cb..647224bc8d6b7 100644 --- a/src/librustc_metadata/creader.rs +++ b/src/librustc_metadata/creader.rs @@ -680,10 +680,7 @@ impl<'a> CrateLoader<'a> { // Sanity check the loaded crate to ensure it is indeed a profiler runtime if !data.is_profiler_runtime() { - self.sess.err(&format!( - "the crate `profiler_builtins` is not \ - a profiler runtime" - )); + self.sess.err("the crate `profiler_builtins` is not a profiler runtime"); } } } diff --git a/src/librustc_mir/borrow_check/diagnostics/region_errors.rs b/src/librustc_mir/borrow_check/diagnostics/region_errors.rs index 8d991927d5437..8cd75d4a2fd27 100644 --- a/src/librustc_mir/borrow_check/diagnostics/region_errors.rs +++ b/src/librustc_mir/borrow_check/diagnostics/region_errors.rs @@ -612,7 +612,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { } else { "'_".to_string() }; - let suggestion = if snippet.ends_with(";") { + let suggestion = if snippet.ends_with(';') { // `type X = impl Trait;` format!("{} + {};", &snippet[..snippet.len() - 1], suggestable_fr_name) } else { diff --git a/src/librustc_mir/borrow_check/mod.rs b/src/librustc_mir/borrow_check/mod.rs index c4d6023e06b3b..aa49ab1b722d1 100644 --- a/src/librustc_mir/borrow_check/mod.rs +++ b/src/librustc_mir/borrow_check/mod.rs @@ -365,7 +365,7 @@ fn do_mir_borrowck<'a, 'tcx>( // Skip over locals that begin with an underscore or have no name match mbcx.local_names[local] { Some(name) => { - if name.as_str().starts_with("_") { + if name.as_str().starts_with('_') { continue; } } diff --git a/src/librustc_mir/dataflow/mod.rs b/src/librustc_mir/dataflow/mod.rs index eccdac2fb9987..a0d93d6d19ab8 100644 --- a/src/librustc_mir/dataflow/mod.rs +++ b/src/librustc_mir/dataflow/mod.rs @@ -689,11 +689,7 @@ pub trait BottomValue { /// 3. Override `join` to do the opposite from what it's doing now. #[inline] fn join(&self, inout_set: &mut BitSet, in_set: &BitSet) -> bool { - if Self::BOTTOM_VALUE == false { - inout_set.union(in_set) - } else { - inout_set.intersect(in_set) - } + if !Self::BOTTOM_VALUE { inout_set.union(in_set) } else { inout_set.intersect(in_set) } } } diff --git a/src/librustc_mir/transform/check_consts/ops.rs b/src/librustc_mir/transform/check_consts/ops.rs index 3263905eadb81..9ba44a4d18e58 100644 --- a/src/librustc_mir/transform/check_consts/ops.rs +++ b/src/librustc_mir/transform/check_consts/ops.rs @@ -65,10 +65,8 @@ impl NonConstOp for Downcast { pub struct FnCallIndirect; impl NonConstOp for FnCallIndirect { fn emit_error(&self, item: &Item<'_, '_>, span: Span) { - let mut err = item - .tcx - .sess - .struct_span_err(span, &format!("function pointers are not allowed in const fn")); + let mut err = + item.tcx.sess.struct_span_err(span, "function pointers are not allowed in const fn"); err.emit(); } } diff --git a/src/librustc_mir/transform/mod.rs b/src/librustc_mir/transform/mod.rs index c9038ccf37b9e..c534c2f3bb84c 100644 --- a/src/librustc_mir/transform/mod.rs +++ b/src/librustc_mir/transform/mod.rs @@ -122,7 +122,7 @@ impl<'tcx> MirSource<'tcx> { /// type `T`. pub fn default_name() -> Cow<'static, str> { let name = ::std::any::type_name::(); - if let Some(tail) = name.rfind(":") { Cow::from(&name[tail + 1..]) } else { Cow::from(name) } + if let Some(tail) = name.rfind(':') { Cow::from(&name[tail + 1..]) } else { Cow::from(name) } } /// A streamlined trait that you can implement to create a pass; the diff --git a/src/librustc_parse/parser/diagnostics.rs b/src/librustc_parse/parser/diagnostics.rs index 018aef3c13cee..00f5fb9705286 100644 --- a/src/librustc_parse/parser/diagnostics.rs +++ b/src/librustc_parse/parser/diagnostics.rs @@ -13,7 +13,7 @@ use syntax::ast::{ }; use syntax::ast::{AttrVec, ItemKind, Mutability, Pat, PatKind, PathSegment, QSelf, Ty, TyKind}; use syntax::ptr::P; -use syntax::token::{self, token_can_begin_expr, TokenKind}; +use syntax::token::{self, TokenKind}; use syntax::util::parser::AssocOp; use log::{debug, trace}; @@ -192,12 +192,12 @@ impl<'a> Parser<'a> { TokenKind::CloseDelim(token::DelimToken::Brace), TokenKind::CloseDelim(token::DelimToken::Paren), ]; - if let token::Ident(name, false) = self.token.kind { - if Ident::new(name, self.token.span).is_raw_guess() + if let token::Ident(name, false) = self.normalized_token.kind { + if Ident::new(name, self.normalized_token.span).is_raw_guess() && self.look_ahead(1, |t| valid_follow.contains(&t.kind)) { err.span_suggestion( - self.token.span, + self.normalized_token.span, "you can escape reserved keywords to use them as identifiers", format!("r#{}", name), Applicability::MaybeIncorrect, @@ -900,8 +900,7 @@ impl<'a> Parser<'a> { } else if !sm.is_multiline(self.prev_span.until(self.token.span)) { // The current token is in the same line as the prior token, not recoverable. } else if self.look_ahead(1, |t| { - t == &token::CloseDelim(token::Brace) - || token_can_begin_expr(t) && t.kind != token::Colon + t == &token::CloseDelim(token::Brace) || t.can_begin_expr() && t.kind != token::Colon }) && [token::Comma, token::Colon].contains(&self.token.kind) { // Likely typo: `,` → `;` or `:` → `;`. This is triggered if the current token is @@ -919,7 +918,7 @@ impl<'a> Parser<'a> { } else if self.look_ahead(0, |t| { t == &token::CloseDelim(token::Brace) || ( - token_can_begin_expr(t) && t != &token::Semi && t != &token::Pound + t.can_begin_expr() && t != &token::Semi && t != &token::Pound // Avoid triggering with too many trailing `#` in raw string. ) }) { diff --git a/src/librustc_parse/parser/expr.rs b/src/librustc_parse/parser/expr.rs index b8f67e73bc3f7..71ca8fba0b479 100644 --- a/src/librustc_parse/parser/expr.rs +++ b/src/librustc_parse/parser/expr.rs @@ -97,15 +97,14 @@ impl<'a> Parser<'a> { fn parse_expr_catch_underscore(&mut self) -> PResult<'a, P> { match self.parse_expr() { Ok(expr) => Ok(expr), - Err(mut err) => match self.token.kind { + Err(mut err) => match self.normalized_token.kind { token::Ident(name, false) if name == kw::Underscore && self.look_ahead(1, |t| t == &token::Comma) => { // Special-case handling of `foo(_, _, _)` err.emit(); - let sp = self.token.span; self.bump(); - Ok(self.mk_expr(sp, ExprKind::Err, AttrVec::new())) + Ok(self.mk_expr(self.prev_token.span, ExprKind::Err, AttrVec::new())) } _ => Err(err), }, @@ -166,7 +165,7 @@ impl<'a> Parser<'a> { while let Some(op) = self.check_assoc_op() { // Adjust the span for interpolated LHS to point to the `$lhs` token // and not to what it refers to. - let lhs_span = match self.unnormalized_prev_token.kind { + let lhs_span = match self.prev_token.kind { TokenKind::Interpolated(..) => self.prev_span, _ => lhs.span, }; @@ -333,7 +332,7 @@ impl<'a> Parser<'a> { /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively. fn check_assoc_op(&self) -> Option> { Some(Spanned { - node: match (AssocOp::from_token(&self.token), &self.token.kind) { + node: match (AssocOp::from_token(&self.token), &self.normalized_token.kind) { (Some(op), _) => op, (None, token::Ident(sym::and, false)) => { self.error_bad_logical_op("and", "&&", "conjunction"); @@ -345,7 +344,7 @@ impl<'a> Parser<'a> { } _ => return None, }, - span: self.token.span, + span: self.normalized_token.span, }) } @@ -437,7 +436,7 @@ impl<'a> Parser<'a> { let attrs = self.parse_or_use_outer_attributes(attrs)?; let lo = self.token.span; // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr() - let (hi, ex) = match self.token.kind { + let (hi, ex) = match self.normalized_token.kind { token::Not => self.parse_unary_expr(lo, UnOp::Not), // `!expr` token::Tilde => self.recover_tilde_expr(lo), // `~expr` token::BinOp(token::Minus) => self.parse_unary_expr(lo, UnOp::Neg), // `-expr` @@ -523,7 +522,7 @@ impl<'a> Parser<'a> { ) -> PResult<'a, (Span, P)> { expr.map(|e| { ( - match self.unnormalized_prev_token.kind { + match self.prev_token.kind { TokenKind::Interpolated(..) => self.prev_span, _ => e.span, }, @@ -704,7 +703,7 @@ impl<'a> Parser<'a> { } fn parse_dot_suffix_expr(&mut self, lo: Span, base: P) -> PResult<'a, P> { - match self.token.kind { + match self.normalized_token.kind { token::Ident(..) => self.parse_dot_suffix(base, lo), token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => { Ok(self.parse_tuple_field_access_expr(lo, base, symbol, suffix)) @@ -754,7 +753,7 @@ impl<'a> Parser<'a> { s.print_usize(float.trunc() as usize); s.pclose(); s.s.word("."); - s.s.word(fstr.splitn(2, ".").last().unwrap().to_string()) + s.s.word(fstr.splitn(2, '.').last().unwrap().to_string()) }); err.span_suggestion( lo.to(self.prev_span), @@ -773,8 +772,8 @@ impl<'a> Parser<'a> { field: Symbol, suffix: Option, ) -> P { - let span = self.token.span; self.bump(); + let span = self.prev_token.span; let field = ExprKind::Field(base, Ident::new(field, span)); self.expect_no_suffix(span, "a tuple index", suffix); self.mk_expr(lo.to(span), field, AttrVec::new()) @@ -798,7 +797,7 @@ impl<'a> Parser<'a> { /// Assuming we have just parsed `.`, continue parsing into an expression. fn parse_dot_suffix(&mut self, self_arg: P, lo: Span) -> PResult<'a, P> { - if self.token.span.rust_2018() && self.eat_keyword(kw::Await) { + if self.normalized_token.span.rust_2018() && self.eat_keyword(kw::Await) { return self.mk_await_expr(self_arg, lo); } @@ -912,7 +911,7 @@ impl<'a> Parser<'a> { // | ^ expected expression self.bump(); Ok(self.mk_expr_err(self.token.span)) - } else if self.token.span.rust_2018() { + } else if self.normalized_token.span.rust_2018() { // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly. if self.check_keyword(kw::Async) { if self.is_async_block() { @@ -1342,7 +1341,7 @@ impl<'a> Parser<'a> { if self.eat_keyword(kw::Static) { Movability::Static } else { Movability::Movable }; let asyncness = - if self.token.span.rust_2018() { self.parse_asyncness() } else { Async::No }; + if self.normalized_token.span.rust_2018() { self.parse_asyncness() } else { Async::No }; if asyncness.is_async() { // Feature-gate `async ||` closures. self.sess.gated_spans.gate(sym::async_closure, self.prev_span); @@ -1556,9 +1555,8 @@ impl<'a> Parser<'a> { fn eat_label(&mut self) -> Option